Debian Codegraph @

tests/test_tutorial/test_debugging/test_tutorial001.py

raw
1 import importlib
2 import runpy
3 import sys
4 from unittest import mock
5
6 import pytest
7 from fastapi.testclient import TestClient
8 from inline_snapshot import snapshot
9
10 MOD_NAME = "docs_src.debugging.tutorial001_py310"
11
12
13 @pytest.fixture(name="client")
14 def get_client():
15 mod = importlib.import_module(MOD_NAME)
16 client = TestClient(mod.app)
17 return client
18
19
20 def test_uvicorn_run_is_not_called_on_import():
21 if sys.modules.get(MOD_NAME):
22 del sys.modules[MOD_NAME] # pragma: no cover
23 with mock.patch("uvicorn.run") as uvicorn_run_mock:
24 importlib.import_module(MOD_NAME)
25 uvicorn_run_mock.assert_not_called()
26
27
28 def test_get_root(client: TestClient):
29 response = client.get("/")
30 assert response.status_code == 200
31 assert response.json() == {"hello world": "ba"}
32
33
34 def test_uvicorn_run_called_when_run_as_main(): # Just for coverage
35 if sys.modules.get(MOD_NAME):
36 del sys.modules[MOD_NAME]
37 with mock.patch("uvicorn.run") as uvicorn_run_mock:
38 runpy.run_module(MOD_NAME, run_name="__main__")
39
40 uvicorn_run_mock.assert_called_once_with(mock.ANY, host="0.0.0.0", port=8000)
41
42
43 def test_openapi_schema(client: TestClient):
44 response = client.get("/openapi.json")
45 assert response.status_code == 200
46 assert response.json() == snapshot(
47 {
48 "openapi": "3.1.0",
49 "info": {"title": "FastAPI", "version": "0.1.0"},
50 "paths": {
51 "/": {
52 "get": {
53 "summary": "Root",
54 "operationId": "root__get",
55 "responses": {
56 "200": {
57 "description": "Successful Response",
58 "content": {"application/json": {"schema": {}}},
59 },
60 },
61 }
62 }
63 },
64 }
65 )