Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

200 lines · 6.1 KiB · Python

Last changed by

remove custom pytest marksDavid Lordbefore adoptiondd5a050

History of this file

Take it

1# -*- coding: utf-8 -*-2import pickle3import random4from collections import deque5from copy import copy as shallow_copy67import pytest8from markupsafe import Markup910from jinja2._compat import range_type11from jinja2._compat import string_types12from jinja2.utils import consume13from jinja2.utils import generate_lorem_ipsum14from jinja2.utils import LRUCache15from jinja2.utils import missing16from jinja2.utils import object_type_repr17from jinja2.utils import select_autoescape18from jinja2.utils import urlize192021class TestLRUCache(object):22    def test_simple(self):23        d = LRUCache(3)24        d["a"] = 125        d["b"] = 226        d["c"] = 327        d["a"]28        d["d"] = 429        assert len(d) == 330        assert "a" in d and "c" in d and "d" in d and "b" not in d3132    def test_itervalue_deprecated(self):33        cache = LRUCache(3)34        cache["a"] = 135        cache["b"] = 236        with pytest.deprecated_call():37            cache.itervalue()3839    def test_itervalues(self):40        cache = LRUCache(3)41        cache["b"] = 142        cache["a"] = 243        values = [v for v in cache.values()]44        assert len(values) == 245        assert 1 in values46        assert 2 in values4748    def test_itervalues_empty(self):49        cache = LRUCache(2)50        values = [v for v in cache.values()]51        assert len(values) == 05253    def test_pickleable(self):54        cache = LRUCache(2)55        cache["foo"] = 4256        cache["bar"] = 2357        cache["foo"]5859        for protocol in range(3):60            copy = pickle.loads(pickle.dumps(cache, protocol))61            assert copy.capacity == cache.capacity62            assert copy._mapping == cache._mapping63            assert copy._queue == cache._queue6465    @pytest.mark.parametrize("copy_func", [LRUCache.copy, shallow_copy])66    def test_copy(self, copy_func):67        cache = LRUCache(2)68        cache["a"] = 169        cache["b"] = 270        copy = copy_func(cache)71        assert copy._queue == cache._queue72        copy["c"] = 373        assert copy._queue != cache._queue74        assert "a" not in copy and "b" in copy and "c" in copy7576    def test_clear(self):77        d = LRUCache(3)78        d["a"] = 179        d["b"] = 280        d["c"] = 381        d.clear()82        assert d.__getstate__() == {"capacity": 3, "_mapping": {}, "_queue": deque([])}8384    def test_repr(self):85        d = LRUCache(3)86        d["a"] = 187        d["b"] = 288        d["c"] = 389        # Sort the strings - mapping is unordered90        assert sorted(repr(d)) == sorted(u"<LRUCache {'a': 1, 'b': 2, 'c': 3}>")9192    def test_items(self):93        """Test various items, keys, values and iterators of LRUCache."""94        d = LRUCache(3)95        d["a"] = 196        d["b"] = 297        d["c"] = 398        assert d.items() == [("c", 3), ("b", 2), ("a", 1)]99        assert d.keys() == ["c", "b", "a"]100        assert d.values() == [3, 2, 1]101        assert list(reversed(d)) == ["a", "b", "c"]102103        # Change the cache a little104        d["b"]105        d["a"] = 4106        assert d.items() == [("a", 4), ("b", 2), ("c", 3)]107        assert d.keys() == ["a", "b", "c"]108        assert d.values() == [4, 2, 3]109        assert list(reversed(d)) == ["c", "b", "a"]110111    def test_setdefault(self):112        d = LRUCache(3)113        assert len(d) == 0114        assert d.setdefault("a") is None115        assert d.setdefault("a", 1) is None116        assert len(d) == 1117        assert d.setdefault("b", 2) == 2118        assert len(d) == 2119120121class TestHelpers(object):122    def test_object_type_repr(self):123        class X(object):124            pass125126        assert object_type_repr(42) == "int object"127        assert object_type_repr([]) == "list object"128        assert object_type_repr(X()) == "test_utils.X object"129        assert object_type_repr(None) == "None"130        assert object_type_repr(Ellipsis) == "Ellipsis"131132    def test_autoescape_select(self):133        func = select_autoescape(134            enabled_extensions=("html", ".htm"),135            disabled_extensions=("txt",),136            default_for_string="STRING",137            default="NONE",138        )139140        assert func(None) == "STRING"141        assert func("unknown.foo") == "NONE"142        assert func("foo.html")143        assert func("foo.htm")144        assert not func("foo.txt")145        assert func("FOO.HTML")146        assert not func("FOO.TXT")147148149class TestEscapeUrlizeTarget(object):150    def test_escape_urlize_target(self):151        url = "http://example.org"152        target = "<script>"153        assert urlize(url, target=target) == (154            '<a href="http://example.org"'155            ' target="&lt;script&gt;">'156            "http://example.org</a>"157        )158159160class TestLoremIpsum(object):161    def test_lorem_ipsum_markup(self):162        """Test that output of lorem_ipsum is Markup by default."""163        assert isinstance(generate_lorem_ipsum(), Markup)164165    def test_lorem_ipsum_html(self):166        """Test that output of lorem_ipsum is a string_type when not html."""167        assert isinstance(generate_lorem_ipsum(html=False), string_types)168169    def test_lorem_ipsum_n(self):170        """Test that the n (number of lines) works as expected."""171        assert generate_lorem_ipsum(n=0, html=False) == u""172        for n in range_type(1, 50):173            assert generate_lorem_ipsum(n=n, html=False).count("\n") == (n - 1) * 2174175    def test_lorem_ipsum_min(self):176        """Test that at least min words are in the output of each line"""177        for _ in range_type(5):178            m = random.randrange(20, 99)179            for _ in range_type(10):180                assert generate_lorem_ipsum(n=1, min=m, html=False).count(" ") >= m - 1181182    def test_lorem_ipsum_max(self):183        """Test that at least max words are in the output of each line"""184        for _ in range_type(5):185            m = random.randrange(21, 100)186            for _ in range_type(10):187                assert generate_lorem_ipsum(n=1, max=m, html=False).count(" ") < m - 1188189190def test_missing():191    """Test the repr of missing."""192    assert repr(missing) == u"missing"193194195def test_consume():196    """Test that consume consumes an iterator."""197    x = iter([1, 2, 3, 4, 5])198    consume(x)199    with pytest.raises(StopIteration):200        next(x)