Coverage for tests/test_future_annotations.py: 100%

47 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-16 00:02 +0000

1from __future__ import annotations 1ABCDEFGHIJKLM

2 

3from typing import Annotated 1ABCDEFGHIJKLM

4 

5from sqlalchemy import Engine 1ABCDEFGHIJKLM

6from sqlmodel import Field, Session, SQLModel, select 1ABCDEFGHIJKLM

7 

8 

9def test_model_with_future_annotations(database_engine: Engine): 1ABCDEFGHIJKLM

10 class Hero(SQLModel, table=True): 1nopqrstuvwxyz

11 id: Annotated[int | None, Field(primary_key=True)] = None 1nopqrstuvwxyz

12 name: str 1nopqrstuvwxyz

13 secret_name: str 1nopqrstuvwxyz

14 age: int | None = None 1nopqrstuvwxyz

15 

16 hero = Hero(name="Deadpond", secret_name="Dive Wilson", age=25) 1nopqrstuvwxyz

17 

18 engine = database_engine 1nopqrstuvwxyz

19 SQLModel.metadata.create_all(engine) 1nopqrstuvwxyz

20 

21 with Session(engine) as session: 1nopqrstuvwxyz

22 session.add(hero) 1nopqrstuvwxyz

23 session.commit() 1nopqrstuvwxyz

24 session.refresh(hero) 1nopqrstuvwxyz

25 

26 assert hero.id is not None 1nopqrstuvwxyz

27 assert hero.name == "Deadpond" 1nopqrstuvwxyz

28 assert hero.secret_name == "Dive Wilson" 1nopqrstuvwxyz

29 assert hero.age == 25 1nopqrstuvwxyz

30 

31 with Session(engine) as session: 1nopqrstuvwxyz

32 heroes = session.exec(select(Hero)).all() 1nopqrstuvwxyz

33 assert len(heroes) == 1 1nopqrstuvwxyz

34 assert heroes[0].name == "Deadpond" 1nopqrstuvwxyz

35 

36 

37def test_model_with_string_annotations(database_engine: Engine): 1ABCDEFGHIJKLM

38 class Team(SQLModel, table=True): 1abcdefghijklm

39 id: Annotated[int | None, Field(primary_key=True)] = None 1abcdefghijklm

40 name: str 1abcdefghijklm

41 

42 class Player(SQLModel, table=True): 1abcdefghijklm

43 id: Annotated[int | None, Field(primary_key=True)] = None 1abcdefghijklm

44 name: str 1abcdefghijklm

45 team_id: Annotated[int | None, Field(foreign_key="team.id")] = None 1abcdefghijklm

46 

47 engine = database_engine 1abcdefghijklm

48 SQLModel.metadata.create_all(engine) 1abcdefghijklm

49 

50 team = Team(name="Champions") 1abcdefghijklm

51 player = Player(name="Alice", team_id=None) 1abcdefghijklm

52 

53 with Session(engine) as session: 1abcdefghijklm

54 session.add(team) 1abcdefghijklm

55 session.commit() 1abcdefghijklm

56 session.refresh(team) 1abcdefghijklm

57 

58 player.team_id = team.id 1abcdefghijklm

59 session.add(player) 1abcdefghijklm

60 session.commit() 1abcdefghijklm

61 session.refresh(player) 1abcdefghijklm

62 

63 assert team.id is not None 1abcdefghijklm

64 assert player.team_id == team.id 1abcdefghijklm