Coverage for tests/test_new.py: 100%
148 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-12-05 11:35 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-12-05 11:35 +0000
1import shutil 1abcdefghijkl
2import subprocess 1abcdefghijkl
3import sys 1abcdefghijkl
4import sysconfig 1abcdefghijkl
5import tomllib 1abcdefghijkl
6from pathlib import Path 1abcdefghijkl
7from typing import Any 1abcdefghijkl
9import pytest 1abcdefghijkl
10from typer.testing import CliRunner 1abcdefghijkl
12from fastapi_new.cli import app 1abcdefghijkl
14runner = CliRunner() 1abcdefghijkl
17@pytest.fixture 1abcdefghijkl
18def temp_project_dir(tmp_path: Path, monkeypatch: Any) -> Path: 1abcdefghijkl
19 """Create a temporary directory and cd into it."""
20 monkeypatch.chdir(tmp_path) 1abcdefghijkl
21 # Use normal dependency installation for generated projects.
22 monkeypatch.delenv("UV_NO_SYNC", raising=False) 1abcdefghijkl
23 monkeypatch.delenv("UV_RESOLUTION", raising=False) 1abcdefghijkl
24 return tmp_path 1abcdefghijkl
27def _assert_project_created(project_path: Path) -> None: 1abcdefghijkl
28 assert (project_path / "main.py").exists() 2W m K ` X { y Y n L | Z } z 0 o M ~ 1 abA 2 p N bb3 cbB 4 q O db5 ebC 6 r P fb7 gbD 8 s Q hb9 ibE ! t R jb# kbF $ u S lb% mbG ' v T nb( obH ) w U pb* qbI + x V rb, sbJ
29 assert (project_path / "README.md").exists() 2W m K ` X { y Y n L | Z } z 0 o M ~ 1 abA 2 p N bb3 cbB 4 q O db5 ebC 6 r P fb7 gbD 8 s Q hb9 ibE ! t R jb# kbF $ u S lb% mbG ' v T nb( obH ) w U pb* qbI + x V rb, sbJ
30 pyproject = tomllib.loads((project_path / "pyproject.toml").read_text()) 2W m K ` X { y Y n L | Z } z 0 o M ~ 1 abA 2 p N bb3 cbB 4 q O db5 ebC 6 r P fb7 gbD 8 s Q hb9 ibE ! t R jb# kbF $ u S lb% mbG ' v T nb( obH ) w U pb* qbI + x V rb, sbJ
31 requires_python = pyproject["project"]["requires-python"] 2W m K ` X { y Y n L | Z } z 0 o M ~ 1 abA 2 p N bb3 cbB 4 q O db5 ebC 6 r P fb7 gbD 8 s Q hb9 ibE ! t R jb# kbF $ u S lb% mbG ' v T nb( obH ) w U pb* qbI + x V rb, sbJ
32 assert requires_python.startswith(">=") 2W m K ` X { y Y n L | Z } z 0 o M ~ 1 abA 2 p N bb3 cbB 4 q O db5 ebC 6 r P fb7 gbD 8 s Q hb9 ibE ! t R jb# kbF $ u S lb% mbG ' v T nb( obH ) w U pb* qbI + x V rb, sbJ
33 assert tuple(map(int, requires_python.removeprefix(">=").split(".")[:2])) >= (3, 11) 2W m K ` X { y Y n L | Z } z 0 o M ~ 1 abA 2 p N bb3 cbB 4 q O db5 ebC 6 r P fb7 gbD 8 s Q hb9 ibE ! t R jb# kbF $ u S lb% mbG ' v T nb( obH ) w U pb* qbI + x V rb, sbJ
36def _assert_project_runs(project_path: Path, python: str) -> None: 1abcdefghijkl
37 fixture = Path(__file__).parent / "fixtures" / "check_generated_project.py" 1mynzoApBqCrDsEtFuGvHwIxJ
38 script = project_path / fixture.name 1mynzoApBqCrDsEtFuGvHwIxJ
39 shutil.copyfile(fixture, script) 1mynzoApBqCrDsEtFuGvHwIxJ
40 result = subprocess.run( 1mynzoApBqCrDsEtFuGvHwIxJ
41 ["uv", "run", "--no-sync", "python", str(script), python],
42 cwd=project_path,
43 capture_output=True,
44 text=True,
45 )
46 assert result.returncode == 0, result.stderr 1mynzoApBqCrDsEtFuGvHwIxJ
49def test_creates_project_successfully(temp_project_dir: Path) -> None: 1abcdefghijkl
50 result = runner.invoke(app, ["my_fastapi_project"]) 1WY02468!$')+
52 assert result.exit_code == 0 1WY02468!$')+
53 project_path = temp_project_dir / "my_fastapi_project" 1WY02468!$')+
54 _assert_project_created(project_path) 1WY02468!$')+
55 assert "Success!" in result.output 1WY02468!$')+
56 assert "my_fastapi_project" in result.output 1WY02468!$')+
59def test_creates_project_with_python_version(temp_project_dir: Path) -> None: 1abcdefghijkl
60 # Test long form
61 result = runner.invoke(app, ["project_long", "--python", "3.12"]) 1mnopqrstuvwx
62 assert result.exit_code == 0 1mnopqrstuvwx
63 project_path = temp_project_dir / "project_long" 1mnopqrstuvwx
64 _assert_project_created(project_path) 1mnopqrstuvwx
65 assert "3.12" in (project_path / "pyproject.toml").read_text() 1mnopqrstuvwx
66 _assert_project_runs(project_path, "3.12") 1mnopqrstuvwx
68 # Test short form
69 result = runner.invoke(app, ["project_short", "-p", "3.11"]) 1mnopqrstuvwx
70 assert result.exit_code == 0 1mnopqrstuvwx
71 project_path = temp_project_dir / "project_short" 1mnopqrstuvwx
72 assert "3.11" in (project_path / "pyproject.toml").read_text() 1mnopqrstuvwx
73 _assert_project_runs(project_path, "3.11") 1mnopqrstuvwx
76def test_runs_project_with_current_python(temp_project_dir: Path) -> None: 1abcdefghijkl
77 version = sys.version_info[:2] 1yzABCDEFGHIJ
78 free_threaded = bool(sysconfig.get_config_var("Py_GIL_DISABLED")) 1yzABCDEFGHIJ
79 python = f"{version[0]}.{version[1]}" + ("t" if free_threaded else "") 1yzABCDEFGHIJ
80 result = runner.invoke(app, ["current_python", "--python", python]) 1yzABCDEFGHIJ
81 assert result.exit_code == 0, result.output 1yzABCDEFGHIJ
82 project_path = temp_project_dir / "current_python" 1yzABCDEFGHIJ
83 _assert_project_created(project_path) 1yzABCDEFGHIJ
84 _assert_project_runs(project_path, python) 1yzABCDEFGHIJ
87def test_validates_template_file_contents(temp_project_dir: Path) -> None: 1abcdefghijkl
88 result = runner.invoke(app, ["sample_project"]) 1-./:;=?@[]^_
89 assert result.exit_code == 0 1-./:;=?@[]^_
91 project_path = temp_project_dir / "sample_project" 1-./:;=?@[]^_
93 main_py_content = (project_path / "main.py").read_text() 1-./:;=?@[]^_
94 assert "from fastapi import FastAPI" in main_py_content 1-./:;=?@[]^_
95 assert "app = FastAPI()" in main_py_content 1-./:;=?@[]^_
97 # Check README.md
98 readme_content = (project_path / "README.md").read_text() 1-./:;=?@[]^_
99 assert "# sample_project" in readme_content 1-./:;=?@[]^_
100 assert "A project created with FastAPI" in readme_content 1-./:;=?@[]^_
102 # Check pyproject.toml
103 pyproject_content = (project_path / "pyproject.toml").read_text() 1-./:;=?@[]^_
104 assert 'name = "sample-project"' in pyproject_content 1-./:;=?@[]^_
105 assert "fastapi[standard]" in pyproject_content 1-./:;=?@[]^_
108def test_initializes_in_current_directory(temp_project_dir: Path) -> None: 1abcdefghijkl
109 result = runner.invoke(app, []) 2` | ~ bbdbfbhbjblbnbpbrb
111 assert result.exit_code == 0 2` | ~ bbdbfbhbjblbnbpbrb
112 assert "Initializing in current directory" in result.output 2` | ~ bbdbfbhbjblbnbpbrb
113 _assert_project_created(temp_project_dir) 2` | ~ bbdbfbhbjblbnbpbrb
116def test_initializes_in_current_directory_with_dot(temp_project_dir: Path) -> None: 1abcdefghijkl
117 result = runner.invoke(app, ["."]) 1XZ13579#%(*,
119 assert result.exit_code == 0 1XZ13579#%(*,
120 assert "Initializing in current directory" in result.output 1XZ13579#%(*,
121 _assert_project_created(temp_project_dir) 1XZ13579#%(*,
123 readme_content = (temp_project_dir / "README.md").read_text() 1XZ13579#%(*,
124 assert f"# {temp_project_dir.name}" in readme_content 1XZ13579#%(*,
127def test_rejects_existing_directory(temp_project_dir: Path) -> None: 1abcdefghijkl
128 existing_dir = temp_project_dir / "existing_project" 23b4b5b6b7b8b9b!b#b$b%b'b
129 existing_dir.mkdir() 23b4b5b6b7b8b9b!b#b$b%b'b
131 result = runner.invoke(app, ["existing_project"]) 23b4b5b6b7b8b9b!b#b$b%b'b
132 assert result.exit_code == 1 23b4b5b6b7b8b9b!b#b$b%b'b
133 assert "Directory 'existing_project' already exists." in result.output 23b4b5b6b7b8b9b!b#b$b%b'b
136@pytest.mark.parametrize("python", ["2.7", "3.9", "3.10", "3.10.15"]) 1abcdefghijkl
137def test_rejects_python_below_3_11(temp_project_dir: Path, python: str) -> None: 1abcdefghijkl
138 result = runner.invoke(app, ["test_project", "--python", python]) 2(b)b*b+b,b-b.b/b:b;b=b?b
139 assert result.exit_code == 1 2(b)b*b+b,b-b.b/b:b;b=b?b
140 assert f"Python {python} is not supported" in result.output 2(b)b*b+b,b-b.b/b:b;b=b?b
141 assert "FastAPI requires Python 3.11" in " ".join(result.output.split()) 2(b)b*b+b,b-b.b/b:b;b=b?b
142 assert not (temp_project_dir / "test_project").exists() 2(b)b*b+b,b-b.b/b:b;b=b?b
145def test_passes_single_digit_python_version_to_uv(temp_project_dir: Path) -> None: 1abcdefghijkl
146 result = runner.invoke(app, ["test_project", "--python", "3"]) 2{ } abcbebgbibkbmbobqbsb
147 assert result.exit_code == 0 2{ } abcbebgbibkbmbobqbsb
148 project_path = temp_project_dir / "test_project" 2{ } abcbebgbibkbmbobqbsb
149 _assert_project_created(project_path) 2{ } abcbebgbibkbmbobqbsb
152def test_passes_malformed_python_version_to_uv(temp_project_dir: Path) -> None: 1abcdefghijkl
153 result = runner.invoke(app, ["test_project", "--python", "abc.def"]) 2ocpcqcrcsctcucvcwcxcyczc
154 # uv will reject this, we just verify we don't crash during validation
155 assert result.exit_code == 1 2ocpcqcrcsctcucvcwcxcyczc
158def test_creates_project_without_python_flag( 1abcdefghijkl
159 temp_project_dir: Path, monkeypatch: pytest.MonkeyPatch
160) -> None:
161 monkeypatch.setenv("UV_PYTHON", "3.10") 1KLMNOPQRSTUV
162 result = runner.invoke(app, ["test_project"]) 1KLMNOPQRSTUV
163 assert result.exit_code == 0 1KLMNOPQRSTUV
164 project_path = temp_project_dir / "test_project" 1KLMNOPQRSTUV
165 _assert_project_created(project_path) 1KLMNOPQRSTUV
166 pyproject = tomllib.loads((project_path / "pyproject.toml").read_text()) 1KLMNOPQRSTUV
167 assert pyproject["project"]["requires-python"] == ">=3.11" 1KLMNOPQRSTUV
170def test_help_shows_minimum_python_version() -> None: 1abcdefghijkl
171 result = runner.invoke(app, ["--help"], env={"COLUMNS": "160"}) 2ccdcecfcgchcicjckclcmcnc
172 assert result.exit_code == 0 2ccdcecfcgchcicjckclcmcnc
173 assert "Must be 3.11 or higher." in result.output 2ccdcecfcgchcicjckclcmcnc
176def test_failed_to_initialize_with_uv(monkeypatch: Any) -> None: 1abcdefghijkl
177 def mock_run(*args: Any, **kwargs: Any) -> None: 2FbGbHbIbJbKbLbMbNbObPbQb
178 # Let the first check for 'uv' succeed, but fail on 'uv init'
179 if args[0][0] == "uv" and args[0][1] == "init": 2FbGbHbIbJbKbLbMbNbObPbQb
180 raise subprocess.CalledProcessError( 2FbGbHbIbJbKbLbMbNbObPbQb
181 1, args[0], stderr=b"uv init failed for some reason"
182 )
184 monkeypatch.setattr(subprocess, "run", mock_run) 2FbGbHbIbJbKbLbMbNbObPbQb
186 result = runner.invoke(app, ["failing_project"]) 2FbGbHbIbJbKbLbMbNbObPbQb
187 assert result.exit_code == 1 2FbGbHbIbJbKbLbMbNbObPbQb
188 assert "Failed to initialize project with uv" in result.output 2FbGbHbIbJbKbLbMbNbObPbQb
191def test_failed_to_add_dependencies(temp_project_dir: Path, monkeypatch: Any) -> None: 1abcdefghijkl
192 def mock_run(*args: Any, **kwargs: Any) -> None: 2RbSbTbUbVbWbXbYbZb0b1b2b
193 # Let 'uv init' succeed, but fail on 'uv add'
194 if args[0][0] == "uv" and args[0][1] == "add": 2RbSbTbUbVbWbXbYbZb0b1b2b
195 raise subprocess.CalledProcessError( 2RbSbTbUbVbWbXbYbZb0b1b2b
196 1, args[0], stderr=b"Failed to resolve dependencies"
197 )
199 monkeypatch.setattr(subprocess, "run", mock_run) 2RbSbTbUbVbWbXbYbZb0b1b2b
201 result = runner.invoke(app, ["failing_deps"]) 2RbSbTbUbVbWbXbYbZb0b1b2b
202 assert result.exit_code == 1 2RbSbTbUbVbWbXbYbZb0b1b2b
203 assert "Failed to install dependencies" in result.output 2RbSbTbUbVbWbXbYbZb0b1b2b
206def test_file_write_failure(temp_project_dir: Path, monkeypatch: Any) -> None: 1abcdefghijkl
207 original_write_text = Path.write_text 2tbubvbwbxbybzbAbBbCbDbEb
209 def mock_write_text(self: Path, *args: Any, **kwargs: Any) -> None: 2tbubvbwbxbybzbAbBbCbDbEb
210 # Fail when trying to write README.md (let main.py succeed first)
211 if self.name == "README.md": 2tbubvbwbxbybzbAbBbCbDbEb
212 raise PermissionError("Permission denied") 2tbubvbwbxbybzbAbBbCbDbEb
213 original_write_text(self, *args, **kwargs) 2tbubvbwbxbybzbAbBbCbDbEb
215 monkeypatch.setattr(Path, "write_text", mock_write_text) 2tbubvbwbxbybzbAbBbCbDbEb
217 result = runner.invoke(app, ["test_write_fail"]) 2tbubvbwbxbybzbAbBbCbDbEb
218 assert result.exit_code == 1 2tbubvbwbxbybzbAbBbCbDbEb
219 assert "Failed to write template files" in result.output 2tbubvbwbxbybzbAbBbCbDbEb
222def test_uv_not_installed(temp_project_dir: Path, monkeypatch: Any) -> None: 1abcdefghijkl
223 monkeypatch.setattr(shutil, "which", lambda _: None) 2@b[b]b^b_b`b{b|b}b~bacbc
225 result = runner.invoke(app, ["test_uv_missing_project"]) 2@b[b]b^b_b`b{b|b}b~bacbc
226 assert result.exit_code == 1 2@b[b]b^b_b`b{b|b}b~bacbc
227 assert "uv is required to create new projects" in result.output 2@b[b]b^b_b`b{b|b}b~bacbc
228 assert "https://docs.astral.sh/uv/" in result.output 2@b[b]b^b_b`b{b|b}b~bacbc