Merge pull request #1000 from EtiennePelletier/fix_deadlock_improve_tests
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fix deadlock in LRUCache and improve test coverage
authored by David Lord · committed by GitHub · parents 7113349, 69d8d98 · Browse files · 5 files·+117 added−14 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+117 added−14 removed
- tests:+111 added−4 removed
- other:+6 added−10 removed
Provenance
- Commit
d3b976b- Tree
f039555- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
7113349- Parent 2
69d8d98
5 files changed+117 added−14 removed
modified:jinja2/utils.py+5 added-10 removed
353 unmodified lines354 def setdefault(self, key, default=None):355 """Set `default` if the key is not in the cache otherwise356 leave unchanged. Return the value of this key.357 """358- self._wlock.acquire()358 try:360- try:361- return self[key]362- except KeyError:363- self[key] = default364- return default359+ return self[key]360+ except KeyError:361+ self[key] = default362+ return default365- finally:366- self._wlock.release()363 364 def clear(self):365 """Clear the cache."""366 self._wlock.acquire()63 unmodified lines430 del self._mapping[key]431 try:432 self._remove(key)433 except ValueError:438- # __getitem__ is not locked, it might happen434 pass435 finally:436 self._wlock.release()437 35 unmodified lines473 474 __iter__ = iterkeys475 476 def __reversed__(self):482- """Iterate over the values in the cache dict, oldest items477+ """Iterate over the keys in the cache dict, oldest items478 coming first.479 """480 return iter(tuple(self._queue))481 163 unmodified linesmodified:tests/conftest.py+1 added
40 unmodified lines41 'inheritance',42 'lexer',43 'lexnparse',44 'loaders',45+ 'loremIpsum',46 'lowlevel',47 'lrucache',48 'lstripblocks',49 'macros',71 unmodified linesmodified:tests/test_api.py+15 added
268 unmodified lines269 assert env.from_string('{{ foo.missing }}').render(foo=42) == ''270 assert env.from_string('{{ not missing }}').render() == 'True'271 pytest.raises(UndefinedError,272 env.from_string('{{ missing - 1}}').render)273+ und1 = Undefined(name='x')274+ und2 = Undefined(name='y')275+ assert und1 == und2276+ assert und1 != 42277+ assert hash(und1) == hash(und2) == hash(Undefined())278+ with pytest.raises(AttributeError):279+ getattr(Undefined, '__slots__')280 281 def test_chainable_undefined(self):282 env = Environment(undefined=ChainableUndefined)283 # The following tests are copied from test_default_undefined4 unmodified lines288 assert env.from_string('{{ foo.missing }}').render(foo=42) == ''289 assert env.from_string('{{ not missing }}').render() == 'True'290 pytest.raises(UndefinedError,291 env.from_string('{{ missing - 1}}').render)292+ with pytest.raises(AttributeError):293+ getattr(ChainableUndefined, '__slots__')294 295 # The following tests ensure subclass functionality works as expected296 assert env.from_string('{{ missing.bar["baz"] }}').render() == u''297 assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() \13 unmodified lines311 == 'True'312 assert env.from_string('{{ foo.missing }}').render(foo=42) \313 == u"{{ no such element: int object['missing'] }}"314 assert env.from_string('{{ not missing }}').render() == 'True'315+ undefined_hint = 'this is testing undefined hint of DebugUndefined'316+ assert str(DebugUndefined(hint=undefined_hint)) == u'{{ undefined value printed: %s }}' % undefined_hint317+ with pytest.raises(AttributeError):318+ getattr(DebugUndefined, '__slots__')319 320 def test_strict_undefined(self):321 env = Environment(undefined=StrictUndefined)322 pytest.raises(UndefinedError, env.from_string('{{ missing }}').render)8 unmodified lines331 pytest.raises(UndefinedError,332 env.from_string('{{ not missing }}').render)333 assert env.from_string('{{ missing|default("default", true) }}')\334 .render() == 'default'335+ with pytest.raises(AttributeError):336+ getattr(StrictUndefined, '__slots__')337 338 def test_indexing_gives_undefined(self):339 t = Template("{{ var[42].foo }}")340 pytest.raises(UndefinedError, t.render, var=0)49 unmodified linesmodified:tests/test_utils.py+95 added-4 removed
6 unmodified lines7 8 :copyright: (c) 2017 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11+12+from collections import deque13 import gc14+import pickle15+import random16 17 import pytest18 15-import pickle16-19+from jinja2._compat import string_types, range_type20 from jinja2.utils import LRUCache, escape, object_type_repr, urlize, \18- select_autoescape21+ select_autoescape, generate_lorem_ipsum, missing, consume22+from markupsafe import Markup23 20-24 @pytest.mark.utils25 @pytest.mark.lrucache26 class TestLRUCache(object):27 39 unmodified lines67 assert copy.capacity == cache.capacity68 assert copy._mapping == cache._mapping69 assert copy._queue == cache._queue70 71+ def test_clear(self):72+ d = LRUCache(3)73+ d["a"] = 174+ d["b"] = 275+ d["c"] = 376+ d.clear()77+ assert d.__getstate__() == {'capacity': 3, '_mapping': {}, '_queue': deque([])}78 79+ def test_repr(self):80+ d = LRUCache(3)81+ d["a"] = 182+ d["b"] = 283+ d["c"] = 384+ # Sort the strings - mapping is unordered85+ assert sorted(repr(d)) == sorted(u"<LRUCache {'a': 1, 'b': 2, 'c': 3}>")86+87+ def test_items(self):88+ """Test various items, keys, values and iterators of LRUCache."""89+ d = LRUCache(3)90+ d["a"] = 191+ d["b"] = 292+ d["c"] = 393+ assert d.items() == list(d.iteritems()) == [('c', 3), ('b', 2), ('a', 1)]94+ assert d.keys() == list(d.iterkeys()) == ['c', 'b', 'a']95+ assert d.values() == list(d.itervalues()) == [3, 2, 1]96+ assert list(reversed(d)) == ['a', 'b', 'c']97+98+ # Change the cache a little99+ d["b"]100+ d["a"] = 4101+ assert d.items() == list(d.iteritems()) == [('a', 4), ('b', 2), ('c', 3)]102+ assert d.keys() == list(d.iterkeys()) == ['a', 'b', 'c']103+ assert d.values() == list(d.itervalues()) == [4, 2, 3]104+ assert list(reversed(d)) == ['c', 'b', 'a']105+106+ def test_setdefault(self):107+ d = LRUCache(3)108+ assert len(d) == 0109+ assert d.setdefault("a") is None110+ assert d.setdefault("a", 1) is None111+ assert len(d) == 1112+ assert d.setdefault("b", 2) == 2113+ assert len(d) == 2114+115+116 @pytest.mark.utils117 @pytest.mark.helpers118 class TestHelpers(object):119 31 unmodified lines151 target = "<script>"152 assert urlize(url, target=target) == ('<a href="http://example.org"'153 ' target="<script>">'154 'http://example.org</a>')155+156+157+@pytest.mark.utils158+@pytest.mark.loremIpsum159+class TestLoremIpsum(object):160+ def test_lorem_ipsum_markup(self):161+ """Test that output of lorem_ipsum is Markup by default."""162+ assert isinstance(generate_lorem_ipsum(), Markup)163+164+ def test_lorem_ipsum_html(self):165+ """Test that output of lorem_ipsum is a string_type when not html."""166+ assert isinstance(generate_lorem_ipsum(html=False), string_types)167+168+ def test_lorem_ipsum_n(self):169+ """Test that the n (number of lines) works as expected."""170+ assert generate_lorem_ipsum(n=0, html=False) == u''171+ for n in range_type(1, 50):172+ assert generate_lorem_ipsum(n=n, html=False).count('\n') == (n - 1) * 2173+174+ def test_lorem_ipsum_min(self):175+ """Test that at least min words are in the output of each line"""176+ for _ in range_type(5):177+ m = random.randrange(20, 99)178+ for _ in range_type(10):179+ assert generate_lorem_ipsum(n=1, min=m, html=False).count(' ') >= m - 1180+181+ def test_lorem_ipsum_max(self):182+ """Test that at least max words are in the output of each line"""183+ for _ in range_type(5):184+ m = random.randrange(21, 100)185+ for _ in range_type(10):186+ assert generate_lorem_ipsum(n=1, max=m, html=False).count(' ') < m - 1187+188+189+def test_missing():190+ """Test the repr of missing."""191+ assert repr(missing) == u'missing'192+193+def test_consume():194+ """Test that consume consumes an iterator."""195+ x = iter([1, 2, 3, 4, 5])196+ consume(x)197+ with pytest.raises(StopIteration):198+ next(x)modified:CHANGES.rst+1 added
19 unmodified lines20 - Float literals can be written with scientific notation, like21 2.56e-3. :issue:`912`, :pr:`922`22 - Int and float literals can be written with the '_' separator for23 legibility, like 12_345. :pr:`923`24+- Fix a bug causing deadlocks in ``LRUCache.setdefault``. :pr:`1000`25 26 27 Version 2.10.228 --------------620 unmodified lines