forked from pallets/flask
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_json_tag.py
More file actions
86 lines (64 loc) · 1.95 KB
/
test_json_tag.py
File metadata and controls
86 lines (64 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
from datetime import datetime
from datetime import timezone
from uuid import uuid4
import pytest
from markupsafe import Markup
from flask.json.tag import JSONTag
from flask.json.tag import TaggedJSONSerializer
@pytest.mark.parametrize(
"data",
(
{" t": (1, 2, 3)},
{" t__": b"a"},
{" di": " di"},
{"x": (1, 2, 3), "y": 4},
(1, 2, 3),
[(1, 2, 3)],
b"\xff",
Markup("<html>"),
uuid4(),
datetime.now(tz=timezone.utc).replace(microsecond=0),
),
)
def test_dump_load_unchanged(data):
s = TaggedJSONSerializer()
assert s.loads(s.dumps(data)) == data
def test_duplicate_tag():
class TagDict(JSONTag):
key = " d"
s = TaggedJSONSerializer()
pytest.raises(KeyError, s.register, TagDict)
s.register(TagDict, force=True, index=0)
assert isinstance(s.tags[" d"], TagDict)
assert isinstance(s.order[0], TagDict)
def test_custom_tag():
class Foo: # noqa: B903, for Python2 compatibility
def __init__(self, data):
self.data = data
class TagFoo(JSONTag):
__slots__ = ()
key = " f"
def check(self, value):
return isinstance(value, Foo)
def to_json(self, value):
return self.serializer.tag(value.data)
def to_python(self, value):
return Foo(value)
s = TaggedJSONSerializer()
s.register(TagFoo)
assert s.loads(s.dumps(Foo("bar"))).data == "bar"
def test_tag_interface():
t = JSONTag(None)
pytest.raises(NotImplementedError, t.check, None)
pytest.raises(NotImplementedError, t.to_json, None)
pytest.raises(NotImplementedError, t.to_python, None)
def test_tag_order():
class Tag1(JSONTag):
key = " 1"
class Tag2(JSONTag):
key = " 2"
s = TaggedJSONSerializer()
s.register(Tag1, index=-1)
assert isinstance(s.order[-2], Tag1)
s.register(Tag2, index=None)
assert isinstance(s.order[-1], Tag2)