216 lines
9.0 KiB
Python
216 lines
9.0 KiB
Python
"""Guards of the isolated demo targets and the boundary of the demo overlay.
|
|
|
|
The script tests run demo.sh against a recording stub of the docker CLI, so
|
|
they prove which Docker commands a refusal never reaches. The render tests
|
|
need the docker CLI and are skipped without it.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import shutil
|
|
import stat
|
|
import subprocess
|
|
import tempfile
|
|
import textwrap
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
DEPLOY = ROOT / "deploy"
|
|
SCRIPT = DEPLOY / "scripts" / "demo.sh"
|
|
DOCKER = os.environ.get("DOCKER", "docker")
|
|
|
|
# The stub answers like a running demo stand: volumes exist with the label
|
|
# given in STUB_LABEL, the backend is ready, and check-reset exits with
|
|
# STUB_CHECK_RESET. Every call is appended to STUB_LOG.
|
|
STUB = textwrap.dedent(
|
|
"""\
|
|
#!/usr/bin/env bash
|
|
printf '%s\\n' "$*" >> "$STUB_LOG"
|
|
args=" $* "
|
|
if [[ "$args" == *" volume inspect --format "* ]]; then
|
|
printf '%s\\n' "${STUB_LABEL:-}"
|
|
exit 0
|
|
fi
|
|
if [[ "$args" == *" volume inspect "* ]]; then
|
|
exit "${STUB_VOLUME_STATUS:-0}"
|
|
fi
|
|
if [[ "$args" == *" wget "* ]]; then
|
|
printf '%s' '{"status":"ready"}'
|
|
exit 0
|
|
fi
|
|
if [[ "$args" == *" check-reset "* ]]; then
|
|
exit "${STUB_CHECK_RESET:-0}"
|
|
fi
|
|
exit 0
|
|
"""
|
|
)
|
|
|
|
|
|
class DemoScriptGuardTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.directory = tempfile.TemporaryDirectory()
|
|
self.addCleanup(self.directory.cleanup)
|
|
base = Path(self.directory.name)
|
|
self.stub = base / "docker"
|
|
self.stub.write_text(STUB)
|
|
self.stub.chmod(self.stub.stat().st_mode | stat.S_IXUSR)
|
|
self.log = base / "calls.log"
|
|
self.log.write_text("")
|
|
self.env_file = base / "root.env"
|
|
self.env_file.write_text("POSTGRES_USER=demo\n")
|
|
self.demo_env = base / "demo.env"
|
|
self.demo_env.write_text("DEMO_ACCOUNT_PASSWORD=synthetic demo stand only 2026\n")
|
|
|
|
def run_script(self, action, **overrides):
|
|
environment = {
|
|
"PATH": os.environ.get("PATH", ""),
|
|
"HOME": os.environ.get("HOME", ""),
|
|
"DOCKER": str(self.stub),
|
|
"STUB_LOG": str(self.log),
|
|
"DEMO_MODE": "isolated",
|
|
"DEMO_PROJECT": "lincodex-demo-test",
|
|
"APP_PROJECT": "app",
|
|
"ENV_FILE": str(self.env_file),
|
|
"DEMO_ENV_FILE": str(self.demo_env),
|
|
"STUB_LABEL": "isolated",
|
|
}
|
|
for key, value in overrides.items():
|
|
if value is None:
|
|
environment.pop(key, None)
|
|
else:
|
|
environment[key] = value
|
|
return subprocess.run(
|
|
["bash", str(SCRIPT), action], capture_output=True, text=True, env=environment, check=False
|
|
)
|
|
|
|
def calls(self):
|
|
return [line for line in self.log.read_text().splitlines() if line]
|
|
|
|
def test_every_action_refuses_without_the_isolated_mode_before_docker(self):
|
|
for action in ("seed", "reset", "down"):
|
|
for mode in (None, "", "production", "ISOLATED"):
|
|
with self.subTest(action=action, mode=mode):
|
|
result = self.run_script(action, DEMO_MODE=mode)
|
|
self.assertEqual(result.returncode, 2, result.stderr)
|
|
self.assertIn("DEMO_MODE=isolated", result.stderr)
|
|
self.assertEqual(self.calls(), [])
|
|
|
|
def test_the_project_must_be_a_separate_demo_project(self):
|
|
cases = (
|
|
{"DEMO_PROJECT": "app"},
|
|
{"DEMO_PROJECT": "lincodex-demo-test", "APP_PROJECT": "lincodex-demo-test"},
|
|
{"DEMO_PROJECT": "lincodex"},
|
|
{"DEMO_PROJECT": "Demo Stand"},
|
|
{"DEMO_ACTOR": "alice"},
|
|
{"ENV_FILE": str(Path(self.directory.name) / "missing.env")},
|
|
)
|
|
for overrides in cases:
|
|
with self.subTest(overrides=overrides):
|
|
result = self.run_script("reset", **overrides)
|
|
self.assertEqual(result.returncode, 2, result.stderr)
|
|
self.assertEqual(self.calls(), [])
|
|
|
|
def test_a_volume_without_the_demo_label_is_never_used(self):
|
|
for action in ("seed", "reset"):
|
|
with self.subTest(action=action):
|
|
result = self.run_script(action, STUB_LABEL="")
|
|
self.assertEqual(result.returncode, 2, result.stderr)
|
|
self.assertIn("was not created by the demo overlay", result.stderr)
|
|
self.assertFalse([call for call in self.calls() if call.startswith("compose")])
|
|
|
|
def test_reset_stops_before_down_when_the_check_refuses(self):
|
|
result = self.run_script("reset", STUB_CHECK_RESET="2")
|
|
self.assertEqual(result.returncode, 2, result.stderr)
|
|
self.assertIn("nothing was deleted", result.stderr)
|
|
calls = self.calls()
|
|
self.assertTrue(any(" check-reset" in call for call in calls))
|
|
self.assertFalse([call for call in calls if " down" in call])
|
|
|
|
def test_reset_discards_only_the_demo_project_and_seeds_again(self):
|
|
result = self.run_script("reset")
|
|
self.assertEqual(result.returncode, 0, result.stderr)
|
|
compose_calls = [call for call in self.calls() if call.startswith("compose")]
|
|
down = [call for call in compose_calls if " down --volumes" in call]
|
|
self.assertEqual(len(down), 1)
|
|
for call in compose_calls:
|
|
self.assertIn("-p lincodex-demo-test ", call)
|
|
self.assertIn("docker-compose.demo.yml", call)
|
|
self.assertLess(compose_calls.index(next(call for call in compose_calls if " check-reset" in call)), compose_calls.index(down[0]))
|
|
self.assertIn(" seed --actor operator:demo-seed", compose_calls[-2])
|
|
self.assertTrue(compose_calls[-1].endswith(" inventory"))
|
|
|
|
def test_down_keeps_the_volumes(self):
|
|
result = self.run_script("down")
|
|
self.assertEqual(result.returncode, 0, result.stderr)
|
|
compose_calls = [call for call in self.calls() if call.startswith("compose")]
|
|
self.assertEqual(len(compose_calls), 1)
|
|
self.assertTrue(compose_calls[0].endswith(" down"))
|
|
|
|
|
|
def render_demo(project="lincodex-demo-render"):
|
|
environment = dict(
|
|
os.environ,
|
|
APP_PROJECT=project,
|
|
APP_NETWORK=f"{project}_default",
|
|
APP_STORAGE_NETWORK=f"{project}_storage",
|
|
APP_HTTP_PORT="8090",
|
|
APP_SUBNET="172.29.84.0/24",
|
|
APP_FRONTEND_IP="172.29.84.10",
|
|
IDENTITY_KEY_SECRET="render-only-identity-key-secret",
|
|
DEMO_ACCOUNT_PASSWORD="render-only-demo-account-password",
|
|
DEMO_MODE="isolated",
|
|
)
|
|
environment.pop("APP_HTTP_BIND", None)
|
|
command = [
|
|
DOCKER, "compose", "--env-file", str(ROOT / ".env.example"), "-p", project,
|
|
"-f", str(DEPLOY / "docker" / "docker-compose.yml"), "-f", str(DEPLOY / "docker" / "docker-compose.demo.yml"),
|
|
"--profile", "demo-seed", "config", "--format", "json",
|
|
]
|
|
result = subprocess.run(command, capture_output=True, text=True, env=environment, check=False)
|
|
if result.returncode != 0:
|
|
raise AssertionError(f"docker compose config failed: {result.stderr}")
|
|
return json.loads(result.stdout)
|
|
|
|
|
|
class DemoOverlayTest(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
if shutil.which(DOCKER) is None:
|
|
raise unittest.SkipTest("docker CLI is not available")
|
|
cls.rendered = render_demo()
|
|
|
|
def test_only_the_frontend_is_published_on_loopback(self):
|
|
published = {name: service["ports"] for name, service in self.rendered["services"].items() if service.get("ports")}
|
|
self.assertEqual(list(published), ["frontend"])
|
|
for port in published["frontend"]:
|
|
self.assertEqual(port["host_ip"], "127.0.0.1")
|
|
self.assertEqual(port["published"], "8090")
|
|
|
|
def test_the_seed_reaches_only_the_default_network(self):
|
|
seed = self.rendered["services"]["demo-seed"]
|
|
self.assertEqual(seed["profiles"], ["demo-seed"])
|
|
self.assertEqual(list(seed["networks"]), ["default"])
|
|
self.assertEqual(seed["build"]["dockerfile"], "Dockerfile.demo-seed")
|
|
self.assertTrue(seed["read_only"])
|
|
self.assertEqual(seed["environment"]["DEMO_MODE"], "isolated")
|
|
|
|
def test_volumes_carry_the_demo_label_and_the_project_name(self):
|
|
for name, volume in self.rendered["volumes"].items():
|
|
with self.subTest(volume=name):
|
|
self.assertEqual(volume["labels"]["org.lincodex.demo-mode"], "isolated")
|
|
self.assertTrue(volume["name"].startswith("lincodex-demo-render_"))
|
|
|
|
def test_the_demo_backend_assigns_synthetic_categories(self):
|
|
backend = self.rendered["services"]["backend"]
|
|
self.assertEqual(backend["environment"]["ASSESSMENT_DEMO_CATEGORIES_ENABLED"], "true")
|
|
self.assertEqual(backend["labels"]["org.lincodex.demo-mode"], "isolated")
|
|
|
|
def test_release_and_ordinary_images_never_contain_the_seed(self):
|
|
for dockerfile in ("Dockerfile", "Dockerfile.e2e"):
|
|
self.assertNotIn("demo-seed", (ROOT / "backend" / dockerfile).read_text())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|