Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

185 lines · 5.5 KiB · Python

Last changed by

Merge branch '3.0.x'David Lordbefore adoptioncdbda09

History of this file

Take it

1import pickle2import random3from collections import deque4from copy import copy as shallow_copy56import pytest7from markupsafe import Markup89from jinja2.utils import consume10from jinja2.utils import generate_lorem_ipsum11from jinja2.utils import LRUCache12from jinja2.utils import missing13from jinja2.utils import object_type_repr14from jinja2.utils import select_autoescape15from jinja2.utils import urlize161718class TestLRUCache:19    def test_simple(self):20        d = LRUCache(3)21        d["a"] = 122        d["b"] = 223        d["c"] = 324        d["a"]25        d["d"] = 426        assert d.keys() == ["d", "a", "c"]2728    def test_values(self):29        cache = LRUCache(3)30        cache["b"] = 131        cache["a"] = 232        assert cache.values() == [2, 1]3334    def test_values_empty(self):35        cache = LRUCache(2)36        assert cache.values() == []3738    def test_pickleable(self):39        cache = LRUCache(2)40        cache["foo"] = 4241        cache["bar"] = 2342        cache["foo"]4344        for protocol in range(3):45            copy = pickle.loads(pickle.dumps(cache, protocol))46            assert copy.capacity == cache.capacity47            assert copy._mapping == cache._mapping48            assert copy._queue == cache._queue4950    @pytest.mark.parametrize("copy_func", [LRUCache.copy, shallow_copy])51    def test_copy(self, copy_func):52        cache = LRUCache(2)53        cache["a"] = 154        cache["b"] = 255        copy = copy_func(cache)56        assert copy._queue == cache._queue57        copy["c"] = 358        assert copy._queue != cache._queue59        assert copy.keys() == ["c", "b"]6061    def test_clear(self):62        d = LRUCache(3)63        d["a"] = 164        d["b"] = 265        d["c"] = 366        d.clear()67        assert d.__getstate__() == {"capacity": 3, "_mapping": {}, "_queue": deque([])}6869    def test_repr(self):70        d = LRUCache(3)71        d["a"] = 172        d["b"] = 273        d["c"] = 374        # Sort the strings - mapping is unordered75        assert sorted(repr(d)) == sorted("<LRUCache {'a': 1, 'b': 2, 'c': 3}>")7677    def test_items(self):78        """Test various items, keys, values and iterators of LRUCache."""79        d = LRUCache(3)80        d["a"] = 181        d["b"] = 282        d["c"] = 383        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"]8788        # Change the cache a little89        d["b"]90        d["a"] = 491        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"]9596    def test_setdefault(self):97        d = LRUCache(3)98        assert len(d) == 099        assert d.setdefault("a") is None100        assert d.setdefault("a", 1) is None101        assert len(d) == 1102        assert d.setdefault("b", 2) == 2103        assert len(d) == 2104105106class TestHelpers:107    def test_object_type_repr(self):108        class X:109            pass110111        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"116117    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        )124125        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")132133134class 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        )143144145class 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)149150    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)153154    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) * 2159160    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 - 1166167    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 - 1173174175def test_missing():176    """Test the repr of missing."""177    assert repr(missing) == "missing"178179180def 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)