Skip to content
Myr

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

5 files+117 added−14 removed

modified:jinja2/utils.py+5 added-10 removed
353 unmodified lines
354 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()363364 def clear(self):365 """Clear the cache."""366 self._wlock.acquire()
63 unmodified lines
430 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 lines
473474 __iter__ = iterkeys475476 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 lines
modified:tests/conftest.py+1 added
40 unmodified lines
41 'inheritance',42 'lexer',43 'lexnparse',44 'loaders',45 'loremIpsum',46 'lowlevel',47 'lrucache',48 'lstripblocks',49 'macros',
71 unmodified lines
modified:tests/test_api.py+15 added
268 unmodified lines
269 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__')280281 def test_chainable_undefined(self):282 env = Environment(undefined=ChainableUndefined)283 # The following tests are copied from test_default_undefined
4 unmodified lines
288 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__')294295 # 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 lines
311 == '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__')319320 def test_strict_undefined(self):321 env = Environment(undefined=StrictUndefined)322 pytest.raises(UndefinedError, env.from_string('{{ missing }}').render)
8 unmodified lines
331 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__')337338 def test_indexing_gives_undefined(self):339 t = Template("{{ var[42].foo }}")340 pytest.raises(UndefinedError, t.render, var=0)
49 unmodified lines
modified:tests/test_utils.py+95 added-4 removed
6 unmodified lines
78 :copyright: (c) 2017 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""1112from collections import deque13import gc14import pickle15import random1617import pytest1815import pickle1619from jinja2._compat import string_types, range_type20from jinja2.utils import LRUCache, escape, object_type_repr, urlize, \18 select_autoescape21 select_autoescape, generate_lorem_ipsum, missing, consume22from markupsafe import Markup232024@pytest.mark.utils25@pytest.mark.lrucache26class TestLRUCache(object):27
39 unmodified lines
67 assert copy.capacity == cache.capacity68 assert copy._mapping == cache._mapping69 assert copy._queue == cache._queue7071 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([])}7879 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}>")8687 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']9798 # 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']105106 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) == 2114115116@pytest.mark.utils117@pytest.mark.helpers118class TestHelpers(object):119
31 unmodified lines
151 target = "<script>"152 assert urlize(url, target=target) == ('<a href="http://example.org"'153 ' target="&lt;script&gt;">'154 'http://example.org</a>')155156157@pytest.mark.utils158@pytest.mark.loremIpsum159class 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)163164 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)167168 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) * 2173174 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 - 1180181 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 - 1187188189def test_missing():190 """Test the repr of missing."""191 assert repr(missing) == u'missing'192193def 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 lines
20- 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`252627Version 2.10.228--------------
620 unmodified lines