test_utils.py 6.1 KB

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