Skip to content

Commit d74d27b

Browse files
committed
✅ Add test for stringified / future annotations with Annotated
1 parent e820d24 commit d74d27b

1 file changed

Lines changed: 63 additions & 0 deletions

File tree

tests/test_future_annotations.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
from __future__ import annotations
2+
3+
from typing import Annotated, Optional
4+
5+
from sqlmodel import Field, Session, SQLModel, create_engine, select
6+
7+
8+
def test_model_with_future_annotations(clear_sqlmodel):
9+
class Hero(SQLModel, table=True):
10+
id: Annotated[Optional[int], Field(primary_key=True)] = None
11+
name: str
12+
secret_name: str
13+
age: Optional[int] = None
14+
15+
hero = Hero(name="Deadpond", secret_name="Dive Wilson", age=25)
16+
17+
engine = create_engine("sqlite://")
18+
SQLModel.metadata.create_all(engine)
19+
20+
with Session(engine) as session:
21+
session.add(hero)
22+
session.commit()
23+
session.refresh(hero)
24+
25+
assert hero.id is not None
26+
assert hero.name == "Deadpond"
27+
assert hero.secret_name == "Dive Wilson"
28+
assert hero.age == 25
29+
30+
with Session(engine) as session:
31+
heroes = session.exec(select(Hero)).all()
32+
assert len(heroes) == 1
33+
assert heroes[0].name == "Deadpond"
34+
35+
36+
def test_model_with_string_annotations(clear_sqlmodel):
37+
class Team(SQLModel, table=True):
38+
id: Annotated[Optional[int], Field(primary_key=True)] = None
39+
name: str
40+
41+
class Player(SQLModel, table=True):
42+
id: Annotated[Optional[int], Field(primary_key=True)] = None
43+
name: str
44+
team_id: Annotated[Optional[int], Field(foreign_key="team.id")] = None
45+
46+
engine = create_engine("sqlite://")
47+
SQLModel.metadata.create_all(engine)
48+
49+
team = Team(name="Champions")
50+
player = Player(name="Alice", team_id=None)
51+
52+
with Session(engine) as session:
53+
session.add(team)
54+
session.commit()
55+
session.refresh(team)
56+
57+
player.team_id = team.id
58+
session.add(player)
59+
session.commit()
60+
session.refresh(player)
61+
62+
assert team.id is not None
63+
assert player.team_id == team.id

0 commit comments

Comments
 (0)