Debian Codegraph @

tests/test_utils.py

raw ◀ ▶
1 Debian patch touch this file
1 import copy
2 import pickle
3 import random
•4 try:
5 from collections.abc import deque
6 except ImportError:
7 from collections import deque
8 from copy import copy as shallow_copy
9
10 import pytest
11 from markupsafe import Markup
12
13 from jinja2.utils import consume
14 from jinja2.utils import generate_lorem_ipsum
15 from jinja2.utils import LRUCache
16 from jinja2.utils import missing
17 from jinja2.utils import object_type_repr
18 from jinja2.utils import select_autoescape
19 from jinja2.utils import urlize
20
21
22 class TestLRUCache:
23 def test_simple(self):
24 d = LRUCache(3)
25 d["a"] = 1
26 d["b"] = 2
27 d["c"] = 3
28 d["a"]
29 d["d"] = 4
30 assert d.keys() == ["d", "a", "c"]
31
32 def test_values(self):
33 cache = LRUCache(3)
34 cache["b"] = 1
35 cache["a"] = 2
36 assert cache.values() == [2, 1]
37
38 def test_values_empty(self):
39 cache = LRUCache(2)
40 assert cache.values() == []
41
42 def test_pickleable(self):
43 cache = LRUCache(2)
44 cache["foo"] = 42
45 cache["bar"] = 23
46 cache["foo"]
47
48 for protocol in range(3):
49 copy = pickle.loads(pickle.dumps(cache, protocol))
50 assert copy.capacity == cache.capacity
51 assert copy._mapping == cache._mapping
52 assert copy._queue == cache._queue
53
54 @pytest.mark.parametrize("copy_func", [LRUCache.copy, shallow_copy])
55 def test_copy(self, copy_func):
56 cache = LRUCache(2)
57 cache["a"] = 1
58 cache["b"] = 2
59 copy = copy_func(cache)
60 assert copy._queue == cache._queue
61 copy["c"] = 3
62 assert copy._queue != cache._queue
63 assert copy.keys() == ["c", "b"]
64
65 def test_clear(self):
66 d = LRUCache(3)
67 d["a"] = 1
68 d["b"] = 2
69 d["c"] = 3
70 d.clear()
71 assert d.__getstate__() == {"capacity": 3, "_mapping": {}, "_queue": deque([])}
72
73 def test_repr(self):
74 d = LRUCache(3)
75 d["a"] = 1
76 d["b"] = 2
77 d["c"] = 3
78 # Sort the strings - mapping is unordered
79 assert sorted(repr(d)) == sorted("<LRUCache {'a': 1, 'b': 2, 'c': 3}>")
80
81 def test_items(self):
82 """Test various items, keys, values and iterators of LRUCache."""
83 d = LRUCache(3)
84 d["a"] = 1
85 d["b"] = 2
86 d["c"] = 3
87 assert d.items() == [("c", 3), ("b", 2), ("a", 1)]
88 assert d.keys() == ["c", "b", "a"]
89 assert d.values() == [3, 2, 1]
90 assert list(reversed(d)) == ["a", "b", "c"]
91
92 # Change the cache a little
93 d["b"]
94 d["a"] = 4
95 assert d.items() == [("a", 4), ("b", 2), ("c", 3)]
96 assert d.keys() == ["a", "b", "c"]
97 assert d.values() == [4, 2, 3]
98 assert list(reversed(d)) == ["c", "b", "a"]
99
100 def test_setdefault(self):
101 d = LRUCache(3)
102 assert len(d) == 0
103 assert d.setdefault("a") is None
104 assert d.setdefault("a", 1) is None
105 assert len(d) == 1
106 assert d.setdefault("b", 2) == 2
107 assert len(d) == 2
108
109
110 class TestHelpers:
111 def test_object_type_repr(self):
112 class X:
113 pass
114
115 assert object_type_repr(42) == "int object"
116 assert object_type_repr([]) == "list object"
117 assert object_type_repr(X()) == "test_utils.X object"
118 assert object_type_repr(None) == "None"
119 assert object_type_repr(Ellipsis) == "Ellipsis"
120
121 def test_autoescape_select(self):
122 func = select_autoescape(
123 enabled_extensions=("html", ".htm"),
124 disabled_extensions=("txt",),
125 default_for_string="STRING",
126 default="NONE",
127 )
128
129 assert func(None) == "STRING"
130 assert func("unknown.foo") == "NONE"
131 assert func("foo.html")
132 assert func("foo.htm")
133 assert not func("foo.txt")
134 assert func("FOO.HTML")
135 assert not func("FOO.TXT")
136
137
138 class TestEscapeUrlizeTarget:
139 def test_escape_urlize_target(self):
140 url = "http://example.org"
141 target = "<script>"
142 assert urlize(url, target=target) == (
143 '<a href="http://example.org"'
144 ' target="&lt;script&gt;">'
145 "http://example.org</a>"
146 )
147
148 def test_urlize_mail_mastodon(self):
149 fr = "[email protected]\n@[email protected]\n"
150 to = (
151 '<a href="mailto:[email protected]">'
152 "[email protected]</a>\n@[email protected]\n"
153 )
154 assert urlize(fr) == to
155
156
157 class TestLoremIpsum:
158 def test_lorem_ipsum_markup(self):
159 """Test that output of lorem_ipsum is Markup by default."""
160 assert isinstance(generate_lorem_ipsum(), Markup)
161
162 def test_lorem_ipsum_html(self):
163 """Test that output of lorem_ipsum is a string_type when not html."""
164 assert isinstance(generate_lorem_ipsum(html=False), str)
165
166 def test_lorem_ipsum_n(self):
167 """Test that the n (number of lines) works as expected."""
168 assert generate_lorem_ipsum(n=0, html=False) == ""
169 for n in range(1, 50):
170 assert generate_lorem_ipsum(n=n, html=False).count("\n") == (n - 1) * 2
171
172 def test_lorem_ipsum_min(self):
173 """Test that at least min words are in the output of each line"""
174 for _ in range(5):
175 m = random.randrange(20, 99)
176 for _ in range(10):
177 assert generate_lorem_ipsum(n=1, min=m, html=False).count(" ") >= m - 1
178
179 def test_lorem_ipsum_max(self):
180 """Test that at least max words are in the output of each line"""
181 for _ in range(5):
182 m = random.randrange(21, 100)
183 for _ in range(10):
184 assert generate_lorem_ipsum(n=1, max=m, html=False).count(" ") < m - 1
185
186
187 def test_missing():
188 """Test the repr of missing."""
189 assert repr(missing) == "missing"
190
191
192 def test_consume():
193 """Test that consume consumes an iterator."""
194 x = iter([1, 2, 3, 4, 5])
195 consume(x)
196 with pytest.raises(StopIteration):
197 next(x)
198
199
200 @pytest.mark.parametrize("protocol", range(pickle.HIGHEST_PROTOCOL + 1))
201 def test_pickle_missing(protocol: int) -> None:
202 """Test that missing can be pickled while remaining a singleton."""
203 assert pickle.loads(pickle.dumps(missing, protocol)) is missing
204
205
206 def test_copy_missing() -> None:
207 """Test that missing can be copied while remaining a singleton."""
208 assert copy.copy(missing) is missing