示例#1
0
def test_from_json_obj_wrong_type():
    """ Test `to_json_obj` on wrong encodings for JSON base types and `decimal.Decimal`. """
    for t, encoding in WRONG_TYPE_ENCODINGS:
        try:
            from_json_obj(encoding, t)
            assert False, "Should not be decoding %s as %s." % (str(encoding),
                                                                str(t))
        except TypeError:
            assert True
示例#2
0
def test_from_json_obj_large_collections_namedtuple():
    class Pair(NamedTuple):
        left: int
        right: int

    large_list: List[Pair] = []
    for i in range(1000):
        large_list.append(Pair(i, i + 1))
    assert from_json_obj(
        to_json_obj(large_list, List[Pair], namedtuples_as_lists=False),
        List[Pair]) == large_list
    assert from_json_obj(
        to_json_obj(large_list, List[Pair], namedtuples_as_lists=True),
        List[Pair]) == large_list
示例#3
0
def test_from_json_obj_lists():
    """ Checks that lists are decoded correctly. """
    encoding = [1, 2, 3]
    val = from_json_obj(encoding, List[int])
    assert isinstance(val, list)
    assert len(val) == 3
    assert all(val[i] == encoding[i] for i in range(len(encoding)))
示例#4
0
def test_from_json_obj_deque():
    """ Checks that dequeues are decoded correctly. """
    encoding = [1, 2, 3]
    val = from_json_obj(encoding, Deque[int])
    assert isinstance(val, deque)
    assert len(val) == 3
    assert all(val[i] == encoding[i] for i in range(len(encoding)))
示例#5
0
def test_from_json_obj_tuples2():
    """ Checks that variadic tuples are decoded correctly. """
    encoding = [1, 2, 3]
    val = from_json_obj(encoding, Tuple[int, ...])
    assert isinstance(val, tuple)
    assert len(val) == 3
    assert all(val[i] == encoding[i] for i in range(len(encoding)))
示例#6
0
def test_from_json_obj_typeerrors():
    """ Checks that `from_json_obj` raises `TypeError` on non-typecheckable types or non-json-encodable types.
    """
    class NonTypechekableT:
        name: str
        val: int

        def __init__(self, name, val):
            self.name = name
            self.val = val

    x = NonTypechekableT("x", 0)
    try:
        from_json_obj(x, NonTypechekableT)
        assert False
    except TypeError:
        assert True
示例#7
0
def test_from_json_obj_ordereddicts():
    """ Checks that dicts are decoded into dicts with the correct key/value pairs. """
    def _assert_eq_ordered_dicts(d1, d2):
        assert isinstance(d1, OrderedDict)
        assert isinstance(d2, OrderedDict)
        assert len(d1) == len(d2)
        assert tuple(d1.keys()) == tuple(d2.keys())
        assert all(d1[key] == d2[key] for key in d1)

    for val, t, encoding in ORDERED_DICT_ENCODINGS:
        _assert_eq_ordered_dicts(from_json_obj(encoding, t), val)
示例#8
0
def test_is_json_encodable_namedtuple():
    """
        Tests the encoding of namedtuples.
    """
    t = NamedTupleExampleT("t", 1)
    t_encoding = OrderedDict([("name", "t"), ("value", 1)])
    assert from_json_obj(t_encoding, NamedTupleExampleT) == t
    nt = NamedTupleNastyExampleT("t", {"x": 1.0, "y": 0.0})
    nt_encoding_list = ["t", {"x": Decimal("1.0"), "y": 0}]
    assert from_json_obj(nt_encoding_list, NamedTupleNastyExampleT) == nt
    nt_encoding_list_long = ["t", {"x": Decimal("1.0"), "y": 0}, False]
    assert from_json_obj(nt_encoding_list_long, NamedTupleNastyExampleT) == nt
    try:
        nt_encoding_list_too_long = [
            "t", {
                "x": Decimal("1.0"),
                "y": 0
            }, False, 1
        ]
        from_json_obj(nt_encoding_list_too_long, NamedTupleNastyExampleT) == nt
    except TypeError:
        assert True
示例#9
0
def test_from_json_obj_numbers():
    assert from_json_obj(1.5, Decimal) == Decimal(1.5)
    assert from_json_obj(1, float) == 1.0
    assert from_json_obj(Decimal("1.5"), float) == 1.5
    assert from_json_obj(Decimal("1.0"), float) == 1.0
    try:
        from_json_obj(Decimal("1.5"), float, cast_decimal=False)
        assert False
    except TypeError:
        assert True
示例#10
0
def test_from_json_typed_dict():
    class Pair(TypedDict, total=True):
        left: int
        right: int

    assert from_json_obj({
        "left": 0,
        "right": 1
    }, Pair) == {
        "left": 0,
        "right": 1
    }
    try:
        from_json_obj("not a dict", Pair)
        assert False, "Should not be decoding string as TypedDict."
    except TypeError:
        assert True
    try:
        from_json_obj({"left": 0}, Pair)
        assert False, "Should not be decoding dict with missing key as TypedDict (total=True)."
    except TypeError:
        assert True
    try:
        from_json_obj({"left": 0, "right": 1, "center": 2}, Pair)
        assert False, "Should not be decoding dict with extra key as TypedDict (total=True)."
    except TypeError:
        assert True

    class PartialPair(TypedDict, total=False):
        left: int
        right: int

    try:
        from_json_obj({"left": 0}, PartialPair)
        assert True, "Should be decoding dict with missing key as TypedDict (total=False)."
    except TypeError:
        assert False
示例#11
0
def loads(s: str,
          decoded_type: Type,
          cast_decimal: bool = True,
          cls=None,
          parse_float=Decimal,
          parse_int=None,
          parse_constant=None,
          **kw) -> Any:
    # pylint: disable = too-many-arguments
    """
        Calls `json.load`, then decodes `obj` from the resulting JSON object using `decoded_type` as a type hint.

        Raises `TypeError` is `decoded_type` is not JSON-encodable according to `typing_json.encoding.is_json_encodable`.
    """
    if not is_json_encodable(decoded_type):
        raise TypeError("Type %s is not json-encodable." % str(decoded_type))
    obj = json.loads(s,
                     cls=cls,
                     parse_float=parse_float,
                     parse_int=parse_int,
                     parse_constant=parse_constant,
                     object_pairs_hook=collections.OrderedDict,
                     **kw)
    return from_json_obj(obj, decoded_type, cast_decimal=cast_decimal)
示例#12
0
def test_from_json_obj_enums():
    assert from_json_obj("Red", EnumT) == EnumT.Red
示例#13
0
def test_from_json_obj_basetypes():
    """ Test `to_json_obj` on JSON base types and `decimal.Decimal`. """
    for val, t, encoding in BASETYPES_ENCODINGS:
        assert from_json_obj(encoding, t) == val
示例#14
0
def test_from_json_obj_frozenset():
    """ Checks that dequeues are decoded correctly. """
    encoding = [1, 2, 3]
    val = from_json_obj(encoding, FrozenSet[int])
    assert isinstance(val, frozenset)
    assert set(val) == set(encoding)
示例#15
0
def test_from_json_obj_errors():
    # pylint:disable=too-many-branches, too-many-statements
    try:
        from_json_obj(1.0j, complex)
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj("hi", int)
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj(1.0, None)
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj(1.0, type(None))
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj(1.0, ...)
        assert False
    except TypeError:
        assert True

    class A(NamedTuple):
        name: str
        value: int

    try:
        from_json_obj(1.0, A)
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj([1.0], A)
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj({"name": "hi"}, A)
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj({"name": "hi", "value": 0, "extra": None}, A)
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj("hi", Union[int, float, bool])
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj("hi", List[str])
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj("hi", Deque[str])
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj("hi", Set[str])
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj("hi", FrozenSet[str])
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj("hi", Tuple[str, ...])
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj("hi", Tuple[str, int])
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj("hi", Literal[0, 1])
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj(["hi"], Tuple[str, int])
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj("hi", Dict[str, str])
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj({0: "hi"}, Dict[str, str])
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj("hi", typing.OrderedDict[str, str])
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj(collections.OrderedDict({0: "hi"}),
                      typing.OrderedDict[str, str])
        assert False
    except TypeError:
        assert True
    try:
        from_json_obj({"name": "hi"}, typing.OrderedDict[str, str])
        assert False
    except TypeError:
        assert True
示例#16
0
def test_from_json_obj():
    # pylint:disable=missing-docstring,invalid-name
    for t in BASE_TYPES:
        obj = BASE_TYPES[t]
        if t is ...:
            assert from_json_obj(to_json_obj(obj, t), t) is ...
        else:
            assert from_json_obj(to_json_obj(obj, t), t) is obj
    assert from_json_obj(to_json_obj(None, None), None) is None

    class A(NamedTuple):
        name: str
        value: int

    a = A("hi", 0)
    # pylint:disable=line-too-long
    assert from_json_obj(to_json_obj(a, A), A) == a
    assert from_json_obj(["hi", 0], A) == a
    a._field_defaults["value"] = 0  # type:ignore #pylint:disable=no-member,protected-access
    assert from_json_obj({"name": "hi"}, A) == a
    assert from_json_obj(to_json_obj(1, Union[int, float]), Union[int,
                                                                  float]) == 1
    assert from_json_obj(to_json_obj(1.0, Union[int, float]),
                         Union[int, float]) == 1.0
    assert from_json_obj(to_json_obj("hi", Literal["hi", 1]),
                         Literal["hi", 1]) == "hi"
    assert from_json_obj(to_json_obj(1, Literal["hi", 1]), Literal["hi",
                                                                   1]) == 1
    assert from_json_obj(to_json_obj(["hi", "my"], List[str]),
                         List[str]) == ["hi", "my"]
    assert from_json_obj(to_json_obj(set(["hi", "my"]), Set[str]),
                         Set[str]) == set(["hi", "my"])
    assert from_json_obj(to_json_obj(deque(["hi", "my"]), Deque[str]),
                         Deque[str]) == deque(["hi", "my"])
    assert from_json_obj(to_json_obj(frozenset(["hi", "my"]), FrozenSet[str]),
                         FrozenSet[str]) == frozenset(["hi", "my"])
    assert from_json_obj(to_json_obj(tuple(["hi", "my"]), Tuple[str, ...]),
                         Tuple[str, ...]) == tuple(["hi", "my"])
    assert from_json_obj(to_json_obj(tuple(["hi", 0]), Tuple[str, int]),
                         Tuple[str, int]) == tuple(["hi", 0])
    d = {"name": "hi", "value": "zero"}
    assert from_json_obj(to_json_obj(d, Dict[str, str]), Dict[str, str]) == d
    od = collections.OrderedDict(d)
    assert from_json_obj(to_json_obj(od, typing.OrderedDict[str, str]),
                         typing.OrderedDict[str, str]) == od