Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_removal(self):
loader = dataloader.Loader()
assert loader.load(3, int) == 3
loader.handlers.pop(loader.index(int))
with self.assertRaises(TypeError):
loader.load(3, int)
def test_load_dict(self):
loader = dataloader.Loader()
class State(Enum):
OK = 'ok'
FAILED = 'failed'
v = {'1': 'ok', '15': 'failed'}
r = {1: State.OK, 15: State.FAILED}
assert loader.load(v, Dict[int, State]) == r
def test_known_refs(self):
class Node(NamedTuple):
value: int = 1
next: Optional['Node'] = None
l = {'next': {}, 'value': 12}
loader = dataloader.Loader()
assert loader.load(l, Node) == Node(value=12,next=Node())
def test_optional(self):
loader = dataloader.Loader()
assert loader.load(1, Optional[int]) == 1
assert loader.load(None, Optional[int]) == None
assert loader.load('1', Optional[int]) == 1
with self.assertRaises(ValueError):
loader.load('ciao', Optional[int])
loader.basiccast = False
loader.load('1', Optional[int])
def test_load_set(self):
loader = dataloader.Loader()
r = {(1, 1), (2, 2), (0, 0)}
assert loader.load(zip(range(3), range(3)), Set[Tuple[int,int]]) == r
assert loader.load([1, '2', 2], Set[int]) == {1, 2}
def test_dict_exception(self):
loader = dataloader.Loader()
with self.assertRaises(exceptions.TypedloadAttributeError):
loader.load(None, Dict[int, int])
def test_union(self):
loader = dataloader.Loader()
loader.basiccast = False
assert loader.load(1, Optional[Union[int, str]]) == 1
assert loader.load('a', Optional[Union[int, str]]) == 'a'
assert loader.load(None, Optional[Union[int, str]]) == None
assert type(loader.load(1, Optional[Union[int, float]])) == int
assert type(loader.load(1.0, Optional[Union[int, float]])) == float
with self.assertRaises(ValueError):
loader.load('', Optional[Union[int, float]])
loader.basiccast = True
assert type(loader.load(1, Optional[Union[int, float]])) == int
assert type(loader.load(1.0, Optional[Union[int, float]])) == float
assert loader.load(None, Optional[str]) is None
def test_custom_handler(self):
class Q:
def __eq__(self, other):
return isinstance(other, Q)
loader = dataloader.Loader()
loader.handlers.append((
lambda t: t == Q,
lambda l, v, t: Q()
))
assert loader.load('test', Q) == Q()
def test_kwargs(self):
with self.assertRaises(ValueError):
load(1, str, basiccast=False)
load(1, int, handlers=[])
def test_nestedload(self):
@dataclass
class A:
a: int
b: str
@dataclass
class B:
a: A
b: List[A]
assert load({'a': {'a': 101, 'b': 'ciao'}, 'b': []}, B) == B(A(101, 'ciao'), [])
assert load(
{'a': {'a': 101, 'b': 'ciao'}, 'b': [{'a': 1, 'b': 'a'},{'a': 0, 'b': 'b'}]},
B
) == B(A(101, 'ciao'), [A(1, 'a'),A(0, 'b')])