Coverage for tests/test_pydantic_sqlalchemy.py: 100%

98 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-12-05 11:28 +0000

1from datetime import datetime, timezone 1abcd

2from typing import List 1abcd

3 

4from pydantic_sqlalchemy import sqlalchemy_to_pydantic 1abcd

5from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, create_engine 1abcd

6from sqlalchemy.ext.declarative import declarative_base 1abcd

7from sqlalchemy.orm import Session, relationship, sessionmaker 1abcd

8from sqlalchemy_utc import UtcDateTime 1abcd

9 

10Base = declarative_base() 1abcd

11 

12engine = create_engine("sqlite://", echo=True) 1abcd

13 

14 

15def utc_now() -> datetime: 1abcd

16 return datetime.now(tz=timezone.utc) 1abcd

17 

18 

19class User(Base): 1abcd

20 __tablename__ = "users" 1abcd

21 

22 id = Column(Integer, primary_key=True) 1abcd

23 name = Column(String) 1abcd

24 fullname = Column(String) 1abcd

25 nickname = Column(String) 1abcd

26 created = Column(DateTime, default=datetime.utcnow) 1abcd

27 updated = Column(UtcDateTime, default=utc_now, onupdate=utc_now) 1abcd

28 

29 addresses = relationship( 1abcd

30 "Address", back_populates="user", cascade="all, delete, delete-orphan" 

31 ) 

32 

33 

34class Address(Base): 1abcd

35 __tablename__ = "addresses" 1abcd

36 id = Column(Integer, primary_key=True) 1abcd

37 email_address = Column(String, nullable=False) 1abcd

38 user_id = Column(Integer, ForeignKey("users.id")) 1abcd

39 

40 user = relationship("User", back_populates="addresses") 1abcd

41 

42 

43Base.metadata.create_all(engine) 1abcd

44 

45 

46LocalSession = sessionmaker(bind=engine) 1abcd

47 

48db: Session = LocalSession() 1abcd

49 

50ed_user = User(name="ed", fullname="Ed Jones", nickname="edsnickname") 1abcd

51 

52address = Address(email_address="ed@example.com") 1abcd

53address2 = Address(email_address="eddy@example.com") 1abcd

54ed_user.addresses = [address, address2] 1abcd

55db.add(ed_user) 1abcd

56db.commit() 1abcd

57 

58 

59def test_defaults() -> None: 1abcd

60 PydanticUser = sqlalchemy_to_pydantic(User) 1efgh

61 PydanticAddress = sqlalchemy_to_pydantic(Address) 1efgh

62 

63 class PydanticUserWithAddresses(PydanticUser): 1efgh

64 addresses: List[PydanticAddress] = [] 1efgh

65 

66 user = db.query(User).first() 1efgh

67 pydantic_user = PydanticUser.from_orm(user) 1efgh

68 data = pydantic_user.dict() 1efgh

69 assert isinstance(data["created"], datetime) 1efgh

70 assert isinstance(data["updated"], datetime) 1efgh

71 check_data = data.copy() 1efgh

72 del check_data["created"] 1efgh

73 del check_data["updated"] 1efgh

74 assert check_data == { 1efgh

75 "fullname": "Ed Jones", 

76 "id": 1, 

77 "name": "ed", 

78 "nickname": "edsnickname", 

79 } 

80 pydantic_user_with_addresses = PydanticUserWithAddresses.from_orm(user) 1efgh

81 data = pydantic_user_with_addresses.dict() 1efgh

82 assert isinstance(data["updated"], datetime) 1efgh

83 assert isinstance(data["created"], datetime) 1efgh

84 check_data = data.copy() 1efgh

85 del check_data["updated"] 1efgh

86 del check_data["created"] 1efgh

87 assert check_data == { 1efgh

88 "fullname": "Ed Jones", 

89 "id": 1, 

90 "name": "ed", 

91 "nickname": "edsnickname", 

92 "addresses": [ 

93 {"email_address": "ed@example.com", "id": 1, "user_id": 1}, 

94 {"email_address": "eddy@example.com", "id": 2, "user_id": 1}, 

95 ], 

96 } 

97 

98 

99def test_schema() -> None: 1abcd

100 PydanticUser = sqlalchemy_to_pydantic(User) 1qrst

101 PydanticAddress = sqlalchemy_to_pydantic(Address) 1qrst

102 assert PydanticUser.schema() == { 1qrst

103 "title": "User", 

104 "type": "object", 

105 "properties": { 

106 "id": {"title": "Id", "type": "integer"}, 

107 "name": {"title": "Name", "type": "string"}, 

108 "fullname": {"title": "Fullname", "type": "string"}, 

109 "nickname": {"title": "Nickname", "type": "string"}, 

110 "created": {"title": "Created", "type": "string", "format": "date-time"}, 

111 "updated": {"title": "Updated", "type": "string", "format": "date-time"}, 

112 }, 

113 "required": ["id"], 

114 } 

115 assert PydanticAddress.schema() == { 1qrst

116 "title": "Address", 

117 "type": "object", 

118 "properties": { 

119 "id": {"title": "Id", "type": "integer"}, 

120 "email_address": {"title": "Email Address", "type": "string"}, 

121 "user_id": {"title": "User Id", "type": "integer"}, 

122 }, 

123 "required": ["id", "email_address"], 

124 } 

125 

126 

127def test_config() -> None: 1abcd

128 class Config: 1ijkl

129 orm_mode = True 1ijkl

130 allow_population_by_field_name = True 1ijkl

131 

132 @classmethod 1ijkl

133 def alias_generator(cls, string: str) -> str: 1ijkl

134 pascal_case = "".join(word.capitalize() for word in string.split("_")) 1ijkl

135 camel_case = pascal_case[0].lower() + pascal_case[1:] 1ijkl

136 return camel_case 1ijkl

137 

138 PydanticUser = sqlalchemy_to_pydantic(User) 1ijkl

139 PydanticAddress = sqlalchemy_to_pydantic(Address, config=Config) 1ijkl

140 

141 class PydanticUserWithAddresses(PydanticUser): 1ijkl

142 addresses: List[PydanticAddress] = [] 1ijkl

143 

144 user = db.query(User).first() 1ijkl

145 pydantic_user_with_addresses = PydanticUserWithAddresses.from_orm(user) 1ijkl

146 data = pydantic_user_with_addresses.dict(by_alias=True) 1ijkl

147 assert isinstance(data["created"], datetime) 1ijkl

148 assert isinstance(data["updated"], datetime) 1ijkl

149 check_data = data.copy() 1ijkl

150 del check_data["created"] 1ijkl

151 del check_data["updated"] 1ijkl

152 assert check_data == { 1ijkl

153 "fullname": "Ed Jones", 

154 "id": 1, 

155 "name": "ed", 

156 "nickname": "edsnickname", 

157 "addresses": [ 

158 {"emailAddress": "ed@example.com", "id": 1, "userId": 1}, 

159 {"emailAddress": "eddy@example.com", "id": 2, "userId": 1}, 

160 ], 

161 } 

162 

163 

164def test_exclude() -> None: 1abcd

165 PydanticUser = sqlalchemy_to_pydantic(User, exclude={"nickname"}) 1mnop

166 PydanticAddress = sqlalchemy_to_pydantic(Address, exclude={"user_id"}) 1mnop

167 

168 class PydanticUserWithAddresses(PydanticUser): 1mnop

169 addresses: List[PydanticAddress] = [] 1mnop

170 

171 user = db.query(User).first() 1mnop

172 pydantic_user_with_addresses = PydanticUserWithAddresses.from_orm(user) 1mnop

173 data = pydantic_user_with_addresses.dict(by_alias=True) 1mnop

174 assert isinstance(data["created"], datetime) 1mnop

175 assert isinstance(data["updated"], datetime) 1mnop

176 check_data = data.copy() 1mnop

177 del check_data["created"] 1mnop

178 del check_data["updated"] 1mnop

179 assert check_data == { 1mnop

180 "fullname": "Ed Jones", 

181 "id": 1, 

182 "name": "ed", 

183 "addresses": [ 

184 {"email_address": "ed@example.com", "id": 1}, 

185 {"email_address": "eddy@example.com", "id": 2}, 

186 ], 

187 }