Created
September 29, 2020 19:12
-
-
Save gidgid/0f785e5d5eacf348c1db59959da5ebe5 to your computer and use it in GitHub Desktop.
Defining non key-value models
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pydantic import BaseModel | |
class Age(BaseModel): | |
__root__: int | |
def test_specialized_models_are_not_equal_to_their_primitives(): | |
age = Age(__root__=42) | |
assert age != 42 | |
def test_age_can_also_be_parsed(): | |
age = Age.parse_obj(42) | |
assert age != 42 | |
def test_specialized_models_can_ensure_we_use_the_correct_types(): | |
age = Age(__root__='43') | |
assert age.__root__ == 43 | |
def age_in_days(age: Age) -> int: | |
return age.__root__ * 365 | |
def test_age_in_days_only_needs_to_deal_with_ints(): | |
age = Age.parse_obj('42') | |
assert age_in_days(age) == 42 * 365 | |
# note that mypy raises an error when trying the following | |
# will raise a mypy error | |
# age_in_days(age='not an age') | |
class Person(BaseModel): | |
age: Age | |
name: str | |
def test_age_is_converted_to_primitive_when_being_jsoned(): | |
person = Person.parse_obj({'age': 37, 'name': 'John'}) | |
assert person.json() == '{"age": 37, "name": "John"}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment