def test_isinstance(self): @dataclass class ExampleDataclass: int_field: int T = TypeVar("T") positive_test_cases = [ (1, int), ("Hello, world", str), ({ "key": "Value" }, dict), ({ "key": "Value" }, Dict), ({ "key": "Value" }, Dict[str, str]), ({ "key": 1 }, Dict[str, int]), ({ 1: 2 }, Dict[T, T][int]), (ExampleDataclass(1), ExampleDataclass), (ExampleDataclass(1), dataclass), ] for obj, type_ in positive_test_cases: with self.subTest(obj=obj, type_=type_): self.assertTrue(isinstance(obj, type_)) negative_test_cases = [ (1, str), ("Hello, world", int), ({ "key": "Value" }, Dict[str, int]), ({ "key": "Value" }, Dict[int, str]), ({ "key": 1 }, Dict[str, str]), ({ 1: 2 }, Dict[T, T][str]), (ExampleDataclass, dataclass), (ExampleDataclass, ExampleDataclass), ] for obj, type_ in negative_test_cases: with self.subTest(obj=obj, type_=type_): self.assertFalse(isinstance(obj, type_))
def bson_int_deserializer(cls, obj): """ Mongo implicitly converts ints to floats Attempt to coerce back Fail if coercion lossy """ if isinstance(obj, cls): return obj try: coerced_obj = cls(obj) except: coerced_obj = None if coerced_obj == obj: return coerced_obj raise DeserializationError("Cannot deserialize {} {!r} to type {}".format( type(obj).__name__, obj, cls.__name__))