Debian Codegraph @

tests/test_tutorial/test_dependencies/test_tutorial008.py

raw
1 import importlib
2 import sys
3 from types import ModuleType
4 from typing import Annotated, Any
5 from unittest.mock import Mock, patch
6
7 import pytest
8 from fastapi import Depends, FastAPI
9 from fastapi.testclient import TestClient
10
11
12 @pytest.fixture(
13 name="module",
14 params=[
15 "tutorial008_py310",
16 pytest.param(
17 "tutorial008_an_py310",
18 marks=pytest.mark.xfail(
19 sys.version_info < (3, 14),
20 reason="Fails with `NameError: name 'DepA' is not defined`",
21 ),
22 ),
23 ],
24 )
25 def get_module(request: pytest.FixtureRequest):
26 mod_name = f"docs_src.dependencies.{request.param}"
27 mod = importlib.import_module(mod_name)
28 return mod
29
30
31 def test_get_db(module: ModuleType):
32 app = FastAPI()
33
34 @app.get("/")
35 def read_root(c: Annotated[Any, Depends(module.dependency_c)]):
36 return {"c": str(c)}
37
38 client = TestClient(app)
39
40 a_mock = Mock()
41 b_mock = Mock()
42 c_mock = Mock()
43
44 with (
45 patch(
46 f"{module.__name__}.generate_dep_a",
47 return_value=a_mock,
48 create=True,
49 ),
50 patch(
51 f"{module.__name__}.generate_dep_b",
52 return_value=b_mock,
53 create=True,
54 ),
55 patch(
56 f"{module.__name__}.generate_dep_c",
57 return_value=c_mock,
58 create=True,
59 ),
60 ):
61 response = client.get("/")
62
63 assert response.status_code == 200
64 assert response.json() == {"c": str(c_mock)}