]> git.ipfire.org Git - thirdparty/fastapi/sqlmodel.git/blob
a1364091627145a65b86212909d16ecd1d632005
[thirdparty/fastapi/sqlmodel.git] /
1 import importlib
2 import sys
3 import types
4 from typing import Any
5 from unittest.mock import patch
6
7 import pytest
8 from sqlmodel import create_engine, SQLModel
9
10 from ....conftest import get_testing_print_function, needs_py39, needs_py310, PrintMock
11
12
13 expected_calls_tutorial005 = [
14 [
15 "Created hero:",
16 {
17 "name": "Deadpond",
18 "secret_name": "Dive Wilson",
19 "team_id": 1,
20 "id": 1,
21 "age": None,
22 },
23 ],
24 [
25 "Created hero:",
26 {
27 "name": "Rusty-Man",
28 "secret_name": "Tommy Sharp",
29 "team_id": 2,
30 "id": 2,
31 "age": 48,
32 },
33 ],
34 [
35 "Created hero:",
36 {
37 "name": "Spider-Boy",
38 "secret_name": "Pedro Parqueador",
39 "team_id": None,
40 "id": 3,
41 "age": None,
42 },
43 ],
44 [
45 "Updated hero:",
46 {
47 "name": "Spider-Boy",
48 "secret_name": "Pedro Parqueador",
49 "team_id": 2,
50 "id": 3,
51 "age": None,
52 },
53 ],
54 [
55 "Team Wakaland:",
56 {"id": 3, "headquarters": "Wakaland Capital City", "name": "Wakaland"},
57 ],
58 [
59 "Team with removed heroes:", # This print is specific to tutorial005.py's main()
60 {"id": 3, "headquarters": "Wakaland Capital City", "name": "Wakaland"},
61 ],
62 [
63 "Deleted team:",
64 {"id": 3, "headquarters": "Wakaland Capital City", "name": "Wakaland"},
65 ],
66 [
67 "Black Lion has no team:",
68 {
69 "name": "Black Lion",
70 "secret_name": "Trevor Challa",
71 "team_id": None,
72 "id": 4,
73 "age": 35,
74 },
75 ],
76 [
77 "Princess Sure-E has no team:",
78 {
79 "name": "Princess Sure-E",
80 "secret_name": "Sure-E",
81 "team_id": None,
82 "id": 5,
83 "age": None,
84 },
85 ],
86 ]
87
88
89 @pytest.fixture(
90 name="module",
91 params=[
92 "tutorial005",
93 pytest.param("tutorial005_py39", marks=needs_py39),
94 pytest.param("tutorial005_py310", marks=needs_py310),
95 ],
96 )
97 def module_fixture(request: pytest.FixtureRequest, clear_sqlmodel: Any):
98 module_name = request.param
99 full_module_name = f"docs_src.tutorial.relationship_attributes.cascade_delete_relationships.{module_name}"
100
101 if full_module_name in sys.modules:
102 mod = importlib.reload(sys.modules[full_module_name])
103 else:
104 mod = importlib.import_module(full_module_name)
105
106 mod.sqlite_url = "sqlite://"
107 mod.engine = create_engine(mod.sqlite_url)
108
109 if hasattr(mod, "create_db_and_tables") and callable(mod.create_db_and_tables):
110 pass
111 elif hasattr(mod, "SQLModel") and hasattr(mod.SQLModel, "metadata"):
112 mod.SQLModel.metadata.create_all(mod.engine)
113
114 return mod
115
116
117 def test_tutorial(module: types.ModuleType, print_mock: PrintMock, clear_sqlmodel: Any):
118 with patch("builtins.print", new=get_testing_print_function(print_mock.calls)):
119 module.main()
120
121 assert print_mock.calls == expected_calls_tutorial005