Created
July 3, 2025 15:47
-
-
Save kejadlen/35fc6c244282ea401adde1c2d3322c7e to your computer and use it in GitHub Desktop.
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, ConfigDict, Field | |
class Foo(BaseModel): | |
class_id: int = Field(validation_alias="id", serialization_alias="id") | |
model_config = ConfigDict(validate_by_name=True, serialize_by_alias=True) | |
class TestFoo: | |
def test_serialization_with_alias(self): | |
foo = Foo(class_id=123) | |
json_data = foo.model_dump() | |
assert json_data == {"id": 123} | |
def test_deserialization_with_alias(self): | |
json_data = {"id": 456} | |
foo = Foo.model_validate(json_data) | |
assert foo.class_id == 456 | |
def test_serialization_without_alias(self): | |
foo = Foo(class_id=789) | |
json_data = foo.model_dump(by_alias=False) | |
assert json_data == {"class_id": 789} | |
def test_json_serialization_with_alias(self): | |
foo = Foo(class_id=101) | |
json_str = foo.model_dump_json() | |
assert json_str == '{"id":101}' | |
def test_json_deserialization_with_alias(self): | |
json_str = '{"id":202}' | |
foo = Foo.model_validate_json(json_str) | |
assert foo.class_id == 202 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment