59 lines
2.0 KiB
Python
59 lines
2.0 KiB
Python
import importlib.util
|
|
import os
|
|
import pathlib
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
|
|
os.environ.setdefault("CONTROLLER_TOKEN", "x" * 48)
|
|
PATH = pathlib.Path(__file__).parents[1] / "platform/docker/profile-controller/profile_controller.py"
|
|
SPEC = importlib.util.spec_from_file_location("profile_controller", PATH)
|
|
controller = importlib.util.module_from_spec(SPEC)
|
|
assert SPEC and SPEC.loader
|
|
SPEC.loader.exec_module(controller)
|
|
|
|
|
|
def item(profile, state="exited"):
|
|
return {
|
|
"Id": f"id-{profile}",
|
|
"State": state,
|
|
"Labels": {controller.LABEL_KEY: profile},
|
|
}
|
|
|
|
|
|
class ProfileControllerTests(unittest.TestCase):
|
|
def test_rejects_unknown_profile_before_docker_call(self):
|
|
with patch.object(controller, "docker_request") as request:
|
|
with self.assertRaises(ValueError):
|
|
controller.activate("shell")
|
|
request.assert_not_called()
|
|
|
|
def test_switch_stops_running_profile_then_starts_target(self):
|
|
profiles = {name: item(name) for name in controller.ALLOWED}
|
|
profiles["fast"] = item("fast", "running")
|
|
calls = []
|
|
|
|
def request(method, path):
|
|
calls.append((method, path))
|
|
return 204, b""
|
|
|
|
with patch.object(controller, "containers", return_value=profiles), \
|
|
patch.object(controller, "docker_request", side_effect=request):
|
|
result = controller.activate("medium")
|
|
|
|
self.assertEqual(result, {"active_profile": "medium", "changed": True})
|
|
self.assertEqual(calls, [
|
|
("POST", "/containers/id-fast/stop?t=120"),
|
|
("POST", "/containers/id-medium/start"),
|
|
])
|
|
|
|
def test_fails_if_profile_container_is_missing(self):
|
|
profiles = {name: item(name) for name in controller.ALLOWED[:-1]}
|
|
with patch.object(controller, "containers", return_value=profiles):
|
|
with self.assertRaisesRegex(RuntimeError, "missing"):
|
|
controller.activate("fast")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|