def test_structuring_lists_of_opt(converter, list_and_type): # type: (Converter, List[Any]) -> None """Test structuring lists of Optional primitive types.""" l, t = list_and_type l.append(None) args = t.__args__ is_optional = args[0] is Optional or (is_union_type(args[0]) and len(args[0].__args__) == 2 and args[0].__args__[1] is NoneType) if not is_bare(t) and (args[0] not in (Any, unicode, str) and not is_optional): with raises((TypeError, ValueError)): converter.structure(l, t) optional_t = Optional[args[0]] # We want to create a generic type annotation with an optional # type parameter. t = change_type_param(t, optional_t) converted = converter.structure(l, t) for x, y in zip(l, converted): assert x == y t.__args__ = args
def test_structuring_dicts_opts(converter, dict_and_type, data): # type: (Converter, Any, Any) -> None """Structure dicts, but with optional primitives.""" d, t = dict_and_type assume(not is_bare(t)) t.__args__ = (t.__args__[0], Optional[t.__args__[1]]) d = {k: v if data.draw(booleans()) else None for k, v in d.items()} converted = converter.structure(d, t) assert converted == d assert converted is not d
def test_stringifying_sets(set_and_type): """Test structuring generic sets and converting the contents to str.""" converter = Converter() set_, input_set_type = set_and_type if is_bare(input_set_type): input_set_type = input_set_type[str] else: input_set_type.__args__ = (str, ) converted = converter.structure(set_, input_set_type) assert len(converted) == len(set_) for e in set_: assert str(e) in converted
for k, v in d.items(): assert converted[_as_str(k)] == _as_str(v) @given(primitives_and_type) def test_structuring_optional_primitives(converter, primitive_and_type): # type: (Converter, Any) -> None """Test structuring Optional primitive types.""" val, type = primitive_and_type assert converter.structure(val, Optional[type]) == val assert converter.structure(None, Optional[type]) is None @given(lists_of_primitives().filter(lambda lp: not is_bare(lp[1]))) def test_structuring_lists_of_opt(converter, list_and_type): # type: (Converter, List[Any]) -> None """Test structuring lists of Optional primitive types.""" l, t = list_and_type l.append(None) args = t.__args__ is_optional = args[0] is Optional or (is_union_type(args[0]) and len(args[0].__args__) == 2 and args[0].__args__[1] is NoneType) if not is_bare(t) and (args[0] not in (Any, unicode, str) and not is_optional): with raises((TypeError, ValueError)):
def change_type_param(cl, new_params): if is_bare(cl): return cl[new_params] return cl.copy_with(new_params)