dotb_ai-platform/tests/test_dev_commands.py
hungtran24 d5e096b952 chore: simplify dev port lookup and isolate settings tests
Resolve the shared backend port once for make dev and reuse it in the child make. Keep pure configuration tests independent of local credentials and URLs without altering integration database settings.
2026-10-02 11:58:19 +07:00

69 lines
2.4 KiB
Python

import os
import shlex
import shutil
import subprocess
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
@pytest.mark.parametrize(
("configured_port", "environment_port", "argument_port", "expected_port"),
[
(None, None, None, "8000"),
("8002", None, None, "8002"),
("8123", None, None, "8123"),
("8002", "8124", None, "8124"),
("8002", "8124", "8125", "8125"),
],
)
def test_dev_uses_the_same_backend_port_for_both_servers(
tmp_path: Path,
configured_port: str | None,
environment_port: str | None,
argument_port: str | None,
expected_port: str,
):
shutil.copyfile(ROOT / "Makefile", tmp_path / "Makefile")
secret = "fixture-secret-must-not-be-exported-or-printed"
config = f"AI_PLATFORM_OPENAI_API_KEY={secret}\n"
if configured_port is not None:
config += f'BACKEND_PORT="{configured_port}"\n'
(tmp_path / ".env").write_text(config)
# Only the port lookup executes during dry-run; bypass uv project discovery in this fixture.
uv = tmp_path / "uv"
uv.write_text(
f'#!/bin/sh\necho port-lookup >&2\nshift 3\nexec {shlex.quote(sys.executable)} "$@"\n'
)
uv.chmod(0o700)
environment = os.environ.copy()
for name in ("BACKEND_PORT", "MAKEFLAGS", "MFLAGS", "MAKEOVERRIDES"):
environment.pop(name, None)
environment["PATH"] = f"{tmp_path}{os.pathsep}{environment['PATH']}"
if environment_port is not None:
environment["BACKEND_PORT"] = environment_port
command = ["make", "--dry-run", "dev"]
if argument_port is not None:
command.append(f"BACKEND_PORT={argument_port}")
result = subprocess.run(
command,
cwd=tmp_path,
env=environment,
text=True,
capture_output=True,
check=False,
timeout=30,
)
assert result.returncode == 0, result.stderr
assert f"--port {expected_port}" in result.stdout
assert f"BACKEND_INTERNAL_URL=http://127.0.0.1:{expected_port} bun" in result.stdout
assert "docker compose up -d --wait postgres" in result.stdout
assert "alembic" not in result.stdout
assert secret not in result.stdout + result.stderr
assert "AI_PLATFORM_OPENAI_API_KEY" not in result.stdout + result.stderr
expected_lookups = 0 if environment_port is not None or argument_port is not None else 1
assert result.stderr.count("port-lookup") == expected_lookups