Debian Codegraph @

tests/test_tutorial/test_settings/test_app01.py

raw
1 import importlib
2 import sys
3
4 import pytest
5 from dirty_equals import IsAnyStr
6 from fastapi.testclient import TestClient
7 from inline_snapshot import snapshot
8 from pydantic import ValidationError
9 from pytest import MonkeyPatch
10
11
12 @pytest.fixture(
13 name="mod_name",
14 params=[
15 pytest.param("app01_py310"),
16 ],
17 )
18 def get_mod_name(request: pytest.FixtureRequest):
19 return f"docs_src.settings.{request.param}.main"
20
21
22 @pytest.fixture(name="client")
23 def get_test_client(mod_name: str, monkeypatch: MonkeyPatch) -> TestClient:
24 if mod_name in sys.modules:
25 del sys.modules[mod_name] # pragma: no cover
26 monkeypatch.setenv("ADMIN_EMAIL", "[email protected]")
27 main_mod = importlib.import_module(mod_name)
28 return TestClient(main_mod.app)
29
30
31 def test_settings_validation_error(mod_name: str, monkeypatch: MonkeyPatch):
32 monkeypatch.delenv("ADMIN_EMAIL", raising=False)
33 if mod_name in sys.modules:
34 del sys.modules[mod_name] # pragma: no cover
35
36 with pytest.raises(ValidationError) as exc_info:
37 importlib.import_module(mod_name)
38 assert exc_info.value.errors() == [
39 {
40 "loc": ("admin_email",),
41 "msg": "Field required",
42 "type": "missing",
43 "input": {},
44 "url": IsAnyStr,
45 }
46 ]
47
48
49 def test_app(client: TestClient):
50 response = client.get("/info")
51 data = response.json()
52 assert data == {
53 "app_name": "Awesome API",
54 "admin_email": "[email protected]",
55 "items_per_user": 50,
56 }
57
58
59 def test_openapi_schema(client: TestClient):
60 response = client.get("/openapi.json")
61 assert response.status_code == 200, response.text
62 assert response.json() == snapshot(
63 {
64 "openapi": "3.1.0",
65 "info": {"title": "FastAPI", "version": "0.1.0"},
66 "paths": {
67 "/info": {
68 "get": {
69 "operationId": "info_info_get",
70 "responses": {
71 "200": {
72 "description": "Successful Response",
73 "content": {"application/json": {"schema": {}}},
74 }
75 },
76 "summary": "Info",
77 }
78 }
79 },
80 }
81 )