You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.1 KiB

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)