|
6 | 6 |
|
7 | 7 | import pytest |
8 | 8 | import uvicorn |
| 9 | +from fastapi.testclient import TestClient |
| 10 | +from httpx import Response |
9 | 11 | from typer.testing import CliRunner |
| 12 | +from uvicorn.importer import import_from_string |
10 | 13 |
|
11 | 14 | from fastapi_cli.cli import app |
12 | 15 | from fastapi_cli.utils.cli import get_uvicorn_log_config |
|
18 | 21 |
|
19 | 22 |
|
20 | 23 | @pytest.fixture(autouse=True) |
21 | | -def force_rich_logs(monkeypatch: pytest.MonkeyPatch) -> None: |
| 24 | +def isolate_cli_environment(monkeypatch: pytest.MonkeyPatch) -> None: |
| 25 | + monkeypatch.delenv("FASTAPI_ENV", raising=False) |
22 | 26 | monkeypatch.setattr("fastapi_cli.cli.should_use_rich_logs", lambda: True) |
23 | 27 |
|
24 | 28 |
|
@@ -53,6 +57,49 @@ def test_dev() -> None: |
53 | 57 | assert "Configuration sources:" not in result.output |
54 | 58 |
|
55 | 59 |
|
| 60 | +def _get_fastapi_env_response(*, command: str, fastapi_env: str | None) -> Response: |
| 61 | + module_name = "environment_app" |
| 62 | + sys.modules.pop(module_name, None) |
| 63 | + |
| 64 | + try: |
| 65 | + with changing_dir(assets_path): |
| 66 | + with patch.object(uvicorn, "run") as mock_run: |
| 67 | + result = runner.invoke( |
| 68 | + app, |
| 69 | + [command, f"{module_name}.py"], |
| 70 | + env={"FASTAPI_ENV": fastapi_env}, |
| 71 | + ) |
| 72 | + |
| 73 | + assert result.exit_code == 0, result.output |
| 74 | + assert mock_run.call_args |
| 75 | + imported_app = import_from_string(mock_run.call_args.kwargs["app"]) |
| 76 | + with TestClient(imported_app) as test_client: |
| 77 | + return test_client.get("/fastapi-env") |
| 78 | + finally: |
| 79 | + sys.modules.pop(module_name, None) |
| 80 | + |
| 81 | + |
| 82 | +@pytest.mark.parametrize( |
| 83 | + ("command", "existing_fastapi_env", "expected_fastapi_env"), |
| 84 | + [ |
| 85 | + pytest.param("dev", None, "development", id="dev-sets-development"), |
| 86 | + pytest.param("dev", "staging", "staging", id="dev-preserves-existing-value"), |
| 87 | + pytest.param("run", None, None, id="run-leaves-value-unset"), |
| 88 | + ], |
| 89 | +) |
| 90 | +def test_fastapi_env_available_to_app( |
| 91 | + command: str, |
| 92 | + existing_fastapi_env: str | None, |
| 93 | + expected_fastapi_env: str | None, |
| 94 | +) -> None: |
| 95 | + response = _get_fastapi_env_response( |
| 96 | + command=command, fastapi_env=existing_fastapi_env |
| 97 | + ) |
| 98 | + |
| 99 | + assert response.status_code == 200 |
| 100 | + assert response.json() == {"fastapi_env": expected_fastapi_env} |
| 101 | + |
| 102 | + |
56 | 103 | def test_run_uses_uvicorn_default_log_config_without_rich_logs( |
57 | 104 | monkeypatch: pytest.MonkeyPatch, |
58 | 105 | ) -> None: |
|
0 commit comments