]> git.ipfire.org Git - thirdparty/fastapi/sqlmodel.git/blob
e48aca5e33f03146a4bdc41b92ce6d344b7f20fb
[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 # Assuming conftest.py is at tests/conftest.py, the path should be ....conftest
11 from ....conftest import get_testing_print_function, needs_py39, needs_py310, PrintMock
12
13
14 expected_calls_tutorial001 = [
15 [
16 "Created hero:",
17 {
18 "age": None,
19 "id": 1,
20 "secret_name": "Dive Wilson",
21 "team_id": 1,
22 "name": "Deadpond",
23 },
24 ],
25 [
26 "Created hero:",
27 {
28 "age": 48,
29 "id": 2,
30 "secret_name": "Tommy Sharp",
31 "team_id": 2,
32 "name": "Rusty-Man",
33 },
34 ],
35 [
36 "Created hero:",
37 {
38 "age": None,
39 "id": 3,
40 "secret_name": "Pedro Parqueador",
41 "team_id": None,
42 "name": "Spider-Boy",
43 },
44 ],
45 [
46 "Updated hero:",
47 {
48 "age": None,
49 "id": 3,
50 "secret_name": "Pedro Parqueador",
51 "team_id": 2,
52 "name": "Spider-Boy",
53 },
54 ],
55 [
56 "Team Wakaland:",
57 {"id": 3, "headquarters": "Wakaland Capital City", "name": "Wakaland"},
58 ],
59 [
60 "Preventers new hero:",
61 {
62 "age": 32,
63 "id": 6,
64 "secret_name": "Natalia Roman-on",
65 "team_id": 2,
66 "name": "Tarantula",
67 },
68 ],
69 [
70 "Preventers new hero:",
71 {
72 "age": 36,
73 "id": 7,
74 "secret_name": "Steve Weird",
75 "team_id": 2,
76 "name": "Dr. Weird",
77 },
78 ],
79 [
80 "Preventers new hero:",
81 {
82 "age": 93,
83 "id": 8,
84 "secret_name": "Esteban Rogelios",
85 "team_id": 2,
86 "name": "Captain North America",
87 },
88 ],
89 ]
90
91
92 @pytest.fixture(
93 name="module",
94 params=[
95 "tutorial001",
96 pytest.param("tutorial001_py39", marks=needs_py39),
97 pytest.param("tutorial001_py310", marks=needs_py310),
98 ],
99 )
100 def module_fixture(request: pytest.FixtureRequest, clear_sqlmodel: Any):
101 module_name = request.param
102 full_module_name = f"docs_src.tutorial.relationship_attributes.create_and_update_relationships.{module_name}"
103
104 if full_module_name in sys.modules:
105 mod = importlib.reload(sys.modules[full_module_name])
106 else:
107 mod = importlib.import_module(full_module_name)
108
109 mod.sqlite_url = "sqlite://"
110 mod.engine = create_engine(mod.sqlite_url)
111
112 if hasattr(mod, "create_db_and_tables") and callable(mod.create_db_and_tables):
113 # Assuming main() or create_db_and_tables() handles table creation
114 pass
115 elif hasattr(mod, "SQLModel") and hasattr(mod.SQLModel, "metadata"):
116 mod.SQLModel.metadata.create_all(mod.engine)
117
118 return mod
119
120
121 def test_tutorial(module: types.ModuleType, print_mock: PrintMock, clear_sqlmodel: Any):
122 with patch("builtins.print", new=get_testing_print_function(print_mock.calls)):
123 module.main()
124
125 assert print_mock.calls == expected_calls_tutorial001