MCPcopy
hub / github.com/pydantic/pydantic / test_cached_property

Function test_cached_property

tests/test_computed_fields.py:178–213  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

176
177
178def test_cached_property():
179 class Model(BaseModel):
180 minimum: int = Field(alias='min')
181 maximum: int = Field(alias='max')
182
183 @computed_field(alias='the magic number')
184 @cached_property
185 def random_number(self) -> int:
186 """An awesome area"""
187 return random.randint(self.minimum, self.maximum)
188
189 @cached_property
190 def cached_property_2(self) -> int:
191 return 42
192
193 @cached_property
194 def _cached_property_3(self) -> int:
195 return 43
196
197 rect = Model(min=10, max=10_000)
198 assert rect.__private_attributes__ == {}
199 assert rect.cached_property_2 == 42
200 assert rect._cached_property_3 == 43
201 first_n = rect.random_number
202 second_n = rect.random_number
203 assert first_n == second_n
204 assert rect.model_dump() == {'minimum': 10, 'maximum': 10_000, 'random_number': first_n}
205 assert rect.model_dump(by_alias=True) == {'min': 10, 'max': 10_000, 'the magic number': first_n}
206 assert rect.model_dump(by_alias=True, exclude={'random_number'}) == {'min': 10, 'max': 10000}
207
208 # `cached_property` is a non-data descriptor, assert that you can assign a value to it:
209 rect2 = Model(min=1, max=1)
210 rect2.cached_property_2 = 1
211 rect2._cached_property_3 = 2
212 assert rect2.cached_property_2 == 1
213 assert rect2._cached_property_3 == 2
214
215
216def test_properties_and_computed_fields():

Callers

nothing calls this directly

Calls 2

ModelClass · 0.70
model_dumpMethod · 0.45

Tested by

no test coverage detected