]> git.ipfire.org Git - thirdparty/fastapi/sqlmodel.git/blob
3ce37700cf38102eae8ba31a6ef7f4b6dc2c228c
[thirdparty/fastapi/sqlmodel.git] /
1 from unittest.mock import patch
2
3 import pytest
4 from sqlalchemy.exc import IntegrityError
5 from sqlmodel import Session, create_engine, select
6
7 from tests.conftest import get_testing_print_function, needs_py310
8
9
10 @needs_py310
11 def test_tutorial(clear_sqlmodel):
12 from docs_src.tutorial.relationship_attributes.cascade_delete_relationships import (
13 tutorial004_py310 as mod,
14 )
15
16 mod.sqlite_url = "sqlite://"
17 mod.engine = create_engine(mod.sqlite_url)
18 calls = []
19
20 new_print = get_testing_print_function(calls)
21
22 with patch("builtins.print", new=new_print):
23 mod.create_db_and_tables()
24 mod.create_heroes()
25 mod.select_deleted_heroes()
26 with Session(mod.engine) as session:
27 team = session.exec(
28 select(mod.Team).where(mod.Team.name == "Wakaland")
29 ).one()
30 team.heroes.clear()
31 session.add(team)
32 session.commit()
33 mod.delete_team()
34 assert calls == [
35 [
36 "Created hero:",
37 {
38 "age": None,
39 "id": 1,
40 "name": "Deadpond",
41 "secret_name": "Dive Wilson",
42 "team_id": 1,
43 },
44 ],
45 [
46 "Created hero:",
47 {
48 "age": 48,
49 "id": 2,
50 "name": "Rusty-Man",
51 "secret_name": "Tommy Sharp",
52 "team_id": 2,
53 },
54 ],
55 [
56 "Created hero:",
57 {
58 "age": None,
59 "id": 3,
60 "name": "Spider-Boy",
61 "secret_name": "Pedro Parqueador",
62 "team_id": None,
63 },
64 ],
65 [
66 "Updated hero:",
67 {
68 "age": None,
69 "id": 3,
70 "name": "Spider-Boy",
71 "secret_name": "Pedro Parqueador",
72 "team_id": 2,
73 },
74 ],
75 [
76 "Team Wakaland:",
77 {"headquarters": "Wakaland Capital City", "id": 3, "name": "Wakaland"},
78 ],
79 [
80 "Black Lion has no team:",
81 {
82 "age": 35,
83 "id": 4,
84 "name": "Black Lion",
85 "secret_name": "Trevor Challa",
86 "team_id": 3,
87 },
88 ],
89 [
90 "Princess Sure-E has no team:",
91 {
92 "age": None,
93 "id": 5,
94 "name": "Princess Sure-E",
95 "secret_name": "Sure-E",
96 "team_id": 3,
97 },
98 ],
99 [
100 "Deleted team:",
101 {"headquarters": "Wakaland Capital City", "id": 3, "name": "Wakaland"},
102 ],
103 ]
104
105 with pytest.raises(IntegrityError) as exc:
106 mod.main()
107 assert "FOREIGN KEY constraint failed" in str(exc.value)