test_utils.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. import pickle
  2. import random
  3. from collections import deque
  4. from copy import copy as shallow_copy
  5. import pytest
  6. from markupsafe import Markup
  7. from jinja2.utils import consume
  8. from jinja2.utils import generate_lorem_ipsum
  9. from jinja2.utils import LRUCache
  10. from jinja2.utils import missing
  11. from jinja2.utils import object_type_repr
  12. from jinja2.utils import select_autoescape
  13. from jinja2.utils import urlize
  14. class TestLRUCache:
  15. def test_simple(self):
  16. d = LRUCache(3)
  17. d["a"] = 1
  18. d["b"] = 2
  19. d["c"] = 3
  20. d["a"]
  21. d["d"] = 4
  22. assert d.keys() == ["d", "a", "c"]
  23. def test_values(self):
  24. cache = LRUCache(3)
  25. cache["b"] = 1
  26. cache["a"] = 2
  27. assert cache.values() == [2, 1]
  28. def test_values_empty(self):
  29. cache = LRUCache(2)
  30. assert cache.values() == []
  31. def test_pickleable(self):
  32. cache = LRUCache(2)
  33. cache["foo"] = 42
  34. cache["bar"] = 23
  35. cache["foo"]
  36. for protocol in range(3):
  37. copy = pickle.loads(pickle.dumps(cache, protocol))
  38. assert copy.capacity == cache.capacity
  39. assert copy._mapping == cache._mapping
  40. assert copy._queue == cache._queue
  41. @pytest.mark.parametrize("copy_func", [LRUCache.copy, shallow_copy])
  42. def test_copy(self, copy_func):
  43. cache = LRUCache(2)
  44. cache["a"] = 1
  45. cache["b"] = 2
  46. copy = copy_func(cache)
  47. assert copy._queue == cache._queue
  48. copy["c"] = 3
  49. assert copy._queue != cache._queue
  50. assert copy.keys() == ["c", "b"]
  51. def test_clear(self):
  52. d = LRUCache(3)
  53. d["a"] = 1
  54. d["b"] = 2
  55. d["c"] = 3
  56. d.clear()
  57. assert d.__getstate__() == {"capacity": 3, "_mapping": {}, "_queue": deque([])}
  58. def test_repr(self):
  59. d = LRUCache(3)
  60. d["a"] = 1
  61. d["b"] = 2
  62. d["c"] = 3
  63. # Sort the strings - mapping is unordered
  64. assert sorted(repr(d)) == sorted("<LRUCache {'a': 1, 'b': 2, 'c': 3}>")
  65. def test_items(self):
  66. """Test various items, keys, values and iterators of LRUCache."""
  67. d = LRUCache(3)
  68. d["a"] = 1
  69. d["b"] = 2
  70. d["c"] = 3
  71. assert d.items() == [("c", 3), ("b", 2), ("a", 1)]
  72. assert d.keys() == ["c", "b", "a"]
  73. assert d.values() == [3, 2, 1]
  74. assert list(reversed(d)) == ["a", "b", "c"]
  75. # Change the cache a little
  76. d["b"]
  77. d["a"] = 4
  78. assert d.items() == [("a", 4), ("b", 2), ("c", 3)]
  79. assert d.keys() == ["a", "b", "c"]
  80. assert d.values() == [4, 2, 3]
  81. assert list(reversed(d)) == ["c", "b", "a"]
  82. def test_setdefault(self):
  83. d = LRUCache(3)
  84. assert len(d) == 0
  85. assert d.setdefault("a") is None
  86. assert d.setdefault("a", 1) is None
  87. assert len(d) == 1
  88. assert d.setdefault("b", 2) == 2
  89. assert len(d) == 2
  90. class TestHelpers:
  91. def test_object_type_repr(self):
  92. class X:
  93. pass
  94. assert object_type_repr(42) == "int object"
  95. assert object_type_repr([]) == "list object"
  96. assert object_type_repr(X()) == "__tests__.test_utils.X object"
  97. assert object_type_repr(None) == "None"
  98. assert object_type_repr(Ellipsis) == "Ellipsis"
  99. def test_autoescape_select(self):
  100. func = select_autoescape(
  101. enabled_extensions=("html", ".htm"),
  102. disabled_extensions=("txt",),
  103. default_for_string="STRING",
  104. default="NONE",
  105. )
  106. assert func(None) == "STRING"
  107. assert func("unknown.foo") == "NONE"
  108. assert func("foo.html")
  109. assert func("foo.htm")
  110. assert not func("foo.txt")
  111. assert func("FOO.HTML")
  112. assert not func("FOO.TXT")
  113. class TestEscapeUrlizeTarget:
  114. def test_escape_urlize_target(self):
  115. url = "http://example.org"
  116. target = "<script>"
  117. assert urlize(url, target=target) == (
  118. '<a href="http://example.org"'
  119. ' target="&lt;script&gt;">'
  120. "http://example.org</a>"
  121. )
  122. class TestLoremIpsum:
  123. def test_lorem_ipsum_markup(self):
  124. """Test that output of lorem_ipsum is Markup by default."""
  125. assert isinstance(generate_lorem_ipsum(), Markup)
  126. def test_lorem_ipsum_html(self):
  127. """Test that output of lorem_ipsum is a string_type when not html."""
  128. assert isinstance(generate_lorem_ipsum(html=False), str)
  129. def test_lorem_ipsum_n(self):
  130. """Test that the n (number of lines) works as expected."""
  131. assert generate_lorem_ipsum(n=0, html=False) == ""
  132. for n in range(1, 50):
  133. assert generate_lorem_ipsum(n=n, html=False).count("\n") == (n - 1) * 2
  134. def test_lorem_ipsum_min(self):
  135. """Test that at least min words are in the output of each line"""
  136. for _ in range(5):
  137. m = random.randrange(20, 99)
  138. for _ in range(10):
  139. assert generate_lorem_ipsum(n=1, min=m, html=False).count(" ") >= m - 1
  140. def test_lorem_ipsum_max(self):
  141. """Test that at least max words are in the output of each line"""
  142. for _ in range(5):
  143. m = random.randrange(21, 100)
  144. for _ in range(10):
  145. assert generate_lorem_ipsum(n=1, max=m, html=False).count(" ") < m - 1
  146. def test_missing():
  147. """Test the repr of missing."""
  148. assert repr(missing) == "missing"
  149. def test_consume():
  150. """Test that consume consumes an iterator."""
  151. x = iter([1, 2, 3, 4, 5])
  152. consume(x)
  153. with pytest.raises(StopIteration):
  154. next(x)