2 changed files with 69 additions and 60 deletions
@ -0,0 +1,50 @@ |
|||
import pytest |
|||
from fastapi.encoders import jsonable_encoder |
|||
|
|||
|
|||
class Person: |
|||
def __init__(self, name: str): |
|||
self.name = name |
|||
|
|||
|
|||
class Pet: |
|||
def __init__(self, owner: Person, name: str): |
|||
self.owner = owner |
|||
self.name = name |
|||
|
|||
|
|||
class DictablePerson(Person): |
|||
def __iter__(self): |
|||
return ((k, v) for k, v in self.__dict__.items()) |
|||
|
|||
|
|||
class DictablePet(Pet): |
|||
def __iter__(self): |
|||
return ((k, v) for k, v in self.__dict__.items()) |
|||
|
|||
|
|||
class Unserializable: |
|||
def __iter__(self): |
|||
raise NotImplementedError() |
|||
|
|||
@property |
|||
def __dict__(self): |
|||
raise NotImplementedError() |
|||
|
|||
|
|||
def test_encode_class(): |
|||
person = Person(name="Foo") |
|||
pet = Pet(owner=person, name="Firulais") |
|||
assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} |
|||
|
|||
|
|||
def test_encode_dictable(): |
|||
person = DictablePerson(name="Foo") |
|||
pet = DictablePet(owner=person, name="Firulais") |
|||
assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} |
|||
|
|||
|
|||
def test_encode_unsupported(): |
|||
unserializable = Unserializable() |
|||
with pytest.raises(ValueError): |
|||
jsonable_encoder(unserializable) |
Loading…
Reference in new issue