49 lines
1.9 KiB
Python
49 lines
1.9 KiB
Python
import sys
|
|
from pathlib import Path
|
|
|
|
# Add api directory to path
|
|
api_dir = Path(__file__).parent.parent / 'api'
|
|
sys.path.insert(0, str(api_dir))
|
|
import unittest
|
|
from unittest.mock import patch, MagicMock
|
|
from container_manager import ContainerManager
|
|
|
|
class TestContainerManager(unittest.TestCase):
|
|
@patch('docker.from_env')
|
|
def test_list_containers(self, mock_from_env):
|
|
mock_client = MagicMock()
|
|
mock_container = MagicMock()
|
|
mock_container.id = 'abc'
|
|
mock_container.name = 'test'
|
|
mock_container.status = 'running'
|
|
mock_container.image.tags = ['img']
|
|
mock_container.labels = {}
|
|
mock_client.containers.list.return_value = [mock_container]
|
|
mock_from_env.return_value = mock_client
|
|
mgr = ContainerManager()
|
|
result = mgr.list_containers()
|
|
self.assertEqual(result[0]['name'], 'test')
|
|
@patch('docker.from_env')
|
|
def test_start_stop_restart_container(self, mock_from_env):
|
|
mock_client = MagicMock()
|
|
mock_container = MagicMock()
|
|
mock_client.containers.get.return_value = mock_container
|
|
mock_from_env.return_value = mock_client
|
|
mgr = ContainerManager()
|
|
# Start
|
|
self.assertTrue(mgr.start_container('test'))
|
|
mock_container.start.assert_called_once()
|
|
# Stop
|
|
self.assertTrue(mgr.stop_container('test'))
|
|
mock_container.stop.assert_called_once()
|
|
# Restart
|
|
self.assertTrue(mgr.restart_container('test'))
|
|
mock_container.restart.assert_called_once()
|
|
# Exception cases
|
|
mock_client.containers.get.side_effect = Exception('fail')
|
|
self.assertFalse(mgr.start_container('bad'))
|
|
self.assertFalse(mgr.stop_container('bad'))
|
|
self.assertFalse(mgr.restart_container('bad'))
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main() |