Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/fastapi_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,10 @@ def _run(

try:
config = FastAPIConfig.resolve(entrypoint=entrypoint)
except FastAPICLIException as e:
toolkit.print_line()
toolkit.print(f"[error]{e}")
raise typer.Exit(code=1) from None
except ValidationError as e:
toolkit.print_line()
toolkit.print("[error]Invalid configuration in pyproject.toml:")
Expand Down
7 changes: 6 additions & 1 deletion src/fastapi_cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

from pydantic import BaseModel, StrictStr

from fastapi_cli.exceptions import FastAPICLIException

logger = logging.getLogger(__name__)


Expand All @@ -29,7 +31,10 @@ def _read_pyproject_toml(cls) -> dict[str, Any]:
return {}

with open(pyproject_path, "rb") as f:
data = tomllib.load(f)
try:
data = tomllib.load(f)
except tomllib.TOMLDecodeError as e:
raise FastAPICLIException(f"Invalid TOML in pyproject.toml: {e}") from e

return data.get("tool", {}).get("fastapi", {}) # type: ignore[no-any-return]

Expand Down
21 changes: 21 additions & 0 deletions tests/test_cli_pyproject.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from pathlib import Path
from unittest.mock import patch

import pytest
import uvicorn
from typer.testing import CliRunner

Expand All @@ -12,6 +13,26 @@
assets_path = Path(__file__).parent / "assets"


@pytest.mark.parametrize("command", ["dev", "run"])
@pytest.mark.parametrize(
"content",
[
"[tool.fastapi\n",
'[tool.fastapi]\nentrypoint = "main:app"\nentrypoint = "other:app"\n',
],
)
def test_pyproject_toml_syntax_error(
command: str, content: str, tmp_path: Path
) -> None:
(tmp_path / "pyproject.toml").write_text(content)
with changing_dir(tmp_path), patch.object(uvicorn, "run") as mock_run:
result = runner.invoke(app, [command])

assert result.exit_code == 1
assert "Invalid TOML in pyproject.toml:" in result.output
mock_run.assert_not_called()


def test_dev_with_pyproject_app_config_uses() -> None:
with (
changing_dir(assets_path / "pyproject_config"),
Expand Down
Loading