jinja

Форк
0
/
test_utils.py 
185 строк · 5.5 Кб
1
import pickle
2
import random
3
from collections import deque
4
from copy import copy as shallow_copy
5

6
import pytest
7
from markupsafe import Markup
8

9
from jinja2.utils import consume
10
from jinja2.utils import generate_lorem_ipsum
11
from jinja2.utils import LRUCache
12
from jinja2.utils import missing
13
from jinja2.utils import object_type_repr
14
from jinja2.utils import select_autoescape
15
from jinja2.utils import urlize
16

17

18
class TestLRUCache:
19
    def test_simple(self):
20
        d = LRUCache(3)
21
        d["a"] = 1
22
        d["b"] = 2
23
        d["c"] = 3
24
        d["a"]
25
        d["d"] = 4
26
        assert d.keys() == ["d", "a", "c"]
27

28
    def test_values(self):
29
        cache = LRUCache(3)
30
        cache["b"] = 1
31
        cache["a"] = 2
32
        assert cache.values() == [2, 1]
33

34
    def test_values_empty(self):
35
        cache = LRUCache(2)
36
        assert cache.values() == []
37

38
    def test_pickleable(self):
39
        cache = LRUCache(2)
40
        cache["foo"] = 42
41
        cache["bar"] = 23
42
        cache["foo"]
43

44
        for protocol in range(3):
45
            copy = pickle.loads(pickle.dumps(cache, protocol))
46
            assert copy.capacity == cache.capacity
47
            assert copy._mapping == cache._mapping
48
            assert copy._queue == cache._queue
49

50
    @pytest.mark.parametrize("copy_func", [LRUCache.copy, shallow_copy])
51
    def test_copy(self, copy_func):
52
        cache = LRUCache(2)
53
        cache["a"] = 1
54
        cache["b"] = 2
55
        copy = copy_func(cache)
56
        assert copy._queue == cache._queue
57
        copy["c"] = 3
58
        assert copy._queue != cache._queue
59
        assert copy.keys() == ["c", "b"]
60

61
    def test_clear(self):
62
        d = LRUCache(3)
63
        d["a"] = 1
64
        d["b"] = 2
65
        d["c"] = 3
66
        d.clear()
67
        assert d.__getstate__() == {"capacity": 3, "_mapping": {}, "_queue": deque([])}
68

69
    def test_repr(self):
70
        d = LRUCache(3)
71
        d["a"] = 1
72
        d["b"] = 2
73
        d["c"] = 3
74
        # Sort the strings - mapping is unordered
75
        assert sorted(repr(d)) == sorted("<LRUCache {'a': 1, 'b': 2, 'c': 3}>")
76

77
    def test_items(self):
78
        """Test various items, keys, values and iterators of LRUCache."""
79
        d = LRUCache(3)
80
        d["a"] = 1
81
        d["b"] = 2
82
        d["c"] = 3
83
        assert d.items() == [("c", 3), ("b", 2), ("a", 1)]
84
        assert d.keys() == ["c", "b", "a"]
85
        assert d.values() == [3, 2, 1]
86
        assert list(reversed(d)) == ["a", "b", "c"]
87

88
        # Change the cache a little
89
        d["b"]
90
        d["a"] = 4
91
        assert d.items() == [("a", 4), ("b", 2), ("c", 3)]
92
        assert d.keys() == ["a", "b", "c"]
93
        assert d.values() == [4, 2, 3]
94
        assert list(reversed(d)) == ["c", "b", "a"]
95

96
    def test_setdefault(self):
97
        d = LRUCache(3)
98
        assert len(d) == 0
99
        assert d.setdefault("a") is None
100
        assert d.setdefault("a", 1) is None
101
        assert len(d) == 1
102
        assert d.setdefault("b", 2) == 2
103
        assert len(d) == 2
104

105

106
class TestHelpers:
107
    def test_object_type_repr(self):
108
        class X:
109
            pass
110

111
        assert object_type_repr(42) == "int object"
112
        assert object_type_repr([]) == "list object"
113
        assert object_type_repr(X()) == "test_utils.X object"
114
        assert object_type_repr(None) == "None"
115
        assert object_type_repr(Ellipsis) == "Ellipsis"
116

117
    def test_autoescape_select(self):
118
        func = select_autoescape(
119
            enabled_extensions=("html", ".htm"),
120
            disabled_extensions=("txt",),
121
            default_for_string="STRING",
122
            default="NONE",
123
        )
124

125
        assert func(None) == "STRING"
126
        assert func("unknown.foo") == "NONE"
127
        assert func("foo.html")
128
        assert func("foo.htm")
129
        assert not func("foo.txt")
130
        assert func("FOO.HTML")
131
        assert not func("FOO.TXT")
132

133

134
class TestEscapeUrlizeTarget:
135
    def test_escape_urlize_target(self):
136
        url = "http://example.org"
137
        target = "<script>"
138
        assert urlize(url, target=target) == (
139
            '<a href="http://example.org"'
140
            ' target="&lt;script&gt;">'
141
            "http://example.org</a>"
142
        )
143

144

145
class TestLoremIpsum:
146
    def test_lorem_ipsum_markup(self):
147
        """Test that output of lorem_ipsum is Markup by default."""
148
        assert isinstance(generate_lorem_ipsum(), Markup)
149

150
    def test_lorem_ipsum_html(self):
151
        """Test that output of lorem_ipsum is a string_type when not html."""
152
        assert isinstance(generate_lorem_ipsum(html=False), str)
153

154
    def test_lorem_ipsum_n(self):
155
        """Test that the n (number of lines) works as expected."""
156
        assert generate_lorem_ipsum(n=0, html=False) == ""
157
        for n in range(1, 50):
158
            assert generate_lorem_ipsum(n=n, html=False).count("\n") == (n - 1) * 2
159

160
    def test_lorem_ipsum_min(self):
161
        """Test that at least min words are in the output of each line"""
162
        for _ in range(5):
163
            m = random.randrange(20, 99)
164
            for _ in range(10):
165
                assert generate_lorem_ipsum(n=1, min=m, html=False).count(" ") >= m - 1
166

167
    def test_lorem_ipsum_max(self):
168
        """Test that at least max words are in the output of each line"""
169
        for _ in range(5):
170
            m = random.randrange(21, 100)
171
            for _ in range(10):
172
                assert generate_lorem_ipsum(n=1, max=m, html=False).count(" ") < m - 1
173

174

175
def test_missing():
176
    """Test the repr of missing."""
177
    assert repr(missing) == "missing"
178

179

180
def test_consume():
181
    """Test that consume consumes an iterator."""
182
    x = iter([1, 2, 3, 4, 5])
183
    consume(x)
184
    with pytest.raises(StopIteration):
185
        next(x)
186

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.