test_collections.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. from __future__ import absolute_import, unicode_literals
  2. import pickle
  3. from collections import Mapping
  4. from itertools import count
  5. import pytest
  6. from billiard.einfo import ExceptionInfo
  7. from case import skip
  8. from celery.five import items, monotonic
  9. from celery.utils.collections import (AttributeDict, BufferMap,
  10. ConfigurationView, DictAttribute,
  11. LimitedSet, Messagebuffer)
  12. from celery.utils.objects import Bunch
  13. class test_DictAttribute:
  14. def test_get_set_keys_values_items(self):
  15. x = DictAttribute(Bunch())
  16. x['foo'] = 'The quick brown fox'
  17. assert x['foo'] == 'The quick brown fox'
  18. assert x['foo'] == x.obj.foo
  19. assert x.get('foo') == 'The quick brown fox'
  20. assert x.get('bar') is None
  21. with pytest.raises(KeyError):
  22. x['bar']
  23. x.foo = 'The quick yellow fox'
  24. assert x['foo'] == 'The quick yellow fox'
  25. assert ('foo', 'The quick yellow fox') in list(x.items())
  26. assert 'foo' in list(x.keys())
  27. assert 'The quick yellow fox' in list(x.values())
  28. def test_setdefault(self):
  29. x = DictAttribute(Bunch())
  30. x.setdefault('foo', 'NEW')
  31. assert x['foo'] == 'NEW'
  32. x.setdefault('foo', 'XYZ')
  33. assert x['foo'] == 'NEW'
  34. def test_contains(self):
  35. x = DictAttribute(Bunch())
  36. x['foo'] = 1
  37. assert 'foo' in x
  38. assert 'bar' not in x
  39. def test_items(self):
  40. obj = Bunch(attr1=1)
  41. x = DictAttribute(obj)
  42. x['attr2'] = 2
  43. assert x['attr1'] == 1
  44. assert x['attr2'] == 2
  45. class test_ConfigurationView:
  46. def setup(self):
  47. self.view = ConfigurationView(
  48. {'changed_key': 1, 'both': 2},
  49. [
  50. {'default_key': 1, 'both': 1},
  51. ],
  52. )
  53. def test_setdefault(self):
  54. self.view.setdefault('both', 36)
  55. assert self.view['both'] == 2
  56. self.view.setdefault('new', 36)
  57. assert self.view['new'] == 36
  58. def test_get(self):
  59. assert self.view.get('both') == 2
  60. sp = object()
  61. assert self.view.get('nonexisting', sp) is sp
  62. def test_update(self):
  63. changes = dict(self.view.changes)
  64. self.view.update(a=1, b=2, c=3)
  65. assert self.view.changes == dict(changes, a=1, b=2, c=3)
  66. def test_contains(self):
  67. assert 'changed_key' in self.view
  68. assert 'default_key' in self.view
  69. assert 'new' not in self.view
  70. def test_repr(self):
  71. assert 'changed_key' in repr(self.view)
  72. assert 'default_key' in repr(self.view)
  73. def test_iter(self):
  74. expected = {
  75. 'changed_key': 1,
  76. 'default_key': 1,
  77. 'both': 2,
  78. }
  79. assert dict(items(self.view)) == expected
  80. assert sorted(list(iter(self.view))) == sorted(list(expected.keys()))
  81. assert sorted(list(self.view.keys())) == sorted(list(expected.keys()))
  82. assert (sorted(list(self.view.values())) ==
  83. sorted(list(expected.values())))
  84. assert 'changed_key' in list(self.view.keys())
  85. assert 2 in list(self.view.values())
  86. assert ('both', 2) in list(self.view.items())
  87. def test_add_defaults_dict(self):
  88. defaults = {'foo': 10}
  89. self.view.add_defaults(defaults)
  90. assert self.view.foo == 10
  91. def test_add_defaults_object(self):
  92. defaults = Bunch(foo=10)
  93. self.view.add_defaults(defaults)
  94. assert self.view.foo == 10
  95. def test_clear(self):
  96. self.view.clear()
  97. assert self.view.both == 1
  98. assert 'changed_key' not in self.view
  99. def test_bool(self):
  100. assert bool(self.view)
  101. self.view.maps[:] = []
  102. assert not bool(self.view)
  103. def test_len(self):
  104. assert len(self.view) == 3
  105. self.view.KEY = 33
  106. assert len(self.view) == 4
  107. self.view.clear()
  108. assert len(self.view) == 2
  109. def test_isa_mapping(self):
  110. from collections import Mapping
  111. assert issubclass(ConfigurationView, Mapping)
  112. def test_isa_mutable_mapping(self):
  113. from collections import MutableMapping
  114. assert issubclass(ConfigurationView, MutableMapping)
  115. class test_ExceptionInfo:
  116. def test_exception_info(self):
  117. try:
  118. raise LookupError('The quick brown fox jumps...')
  119. except Exception:
  120. einfo = ExceptionInfo()
  121. assert str(einfo) == einfo.traceback
  122. assert isinstance(einfo.exception, LookupError)
  123. assert einfo.exception.args == ('The quick brown fox jumps...',)
  124. assert einfo.traceback
  125. assert repr(einfo)
  126. @skip.if_win32()
  127. class test_LimitedSet:
  128. def test_add(self):
  129. s = LimitedSet(maxlen=2)
  130. s.add('foo')
  131. s.add('bar')
  132. for n in 'foo', 'bar':
  133. assert n in s
  134. s.add('baz')
  135. for n in 'bar', 'baz':
  136. assert n in s
  137. assert 'foo' not in s
  138. s = LimitedSet(maxlen=10)
  139. for i in range(150):
  140. s.add(i)
  141. assert len(s) <= 10
  142. # make sure heap is not leaking:
  143. assert len(s._heap) < len(s) * (
  144. 100. + s.max_heap_percent_overload) / 100
  145. def test_purge(self):
  146. # purge now enforces rules
  147. # cant purge(1) now. but .purge(now=...) still works
  148. s = LimitedSet(maxlen=10)
  149. [s.add(i) for i in range(10)]
  150. s.maxlen = 2
  151. s.purge()
  152. assert len(s) == 2
  153. # expired
  154. s = LimitedSet(maxlen=10, expires=1)
  155. [s.add(i) for i in range(10)]
  156. s.maxlen = 2
  157. s.purge(now=monotonic() + 100)
  158. assert len(s) == 0
  159. # not expired
  160. s = LimitedSet(maxlen=None, expires=1)
  161. [s.add(i) for i in range(10)]
  162. s.maxlen = 2
  163. s.purge(now=lambda: monotonic() - 100)
  164. assert len(s) == 2
  165. # expired -> minsize
  166. s = LimitedSet(maxlen=10, minlen=10, expires=1)
  167. [s.add(i) for i in range(20)]
  168. s.minlen = 3
  169. s.purge(now=monotonic() + 3)
  170. assert s.minlen == len(s)
  171. assert len(s._heap) <= s.maxlen * (
  172. 100. + s.max_heap_percent_overload) / 100
  173. def test_pickleable(self):
  174. s = LimitedSet(maxlen=2)
  175. s.add('foo')
  176. s.add('bar')
  177. assert pickle.loads(pickle.dumps(s)) == s
  178. def test_iter(self):
  179. s = LimitedSet(maxlen=3)
  180. items = ['foo', 'bar', 'baz', 'xaz']
  181. for item in items:
  182. s.add(item)
  183. l = list(iter(s))
  184. for item in items[1:]:
  185. assert item in l
  186. assert 'foo' not in l
  187. assert l == items[1:], 'order by insertion time'
  188. def test_repr(self):
  189. s = LimitedSet(maxlen=2)
  190. items = 'foo', 'bar'
  191. for item in items:
  192. s.add(item)
  193. assert 'LimitedSet(' in repr(s)
  194. def test_discard(self):
  195. s = LimitedSet(maxlen=2)
  196. s.add('foo')
  197. s.discard('foo')
  198. assert 'foo' not in s
  199. assert len(s._data) == 0
  200. s.discard('foo')
  201. def test_clear(self):
  202. s = LimitedSet(maxlen=2)
  203. s.add('foo')
  204. s.add('bar')
  205. assert len(s) == 2
  206. s.clear()
  207. assert not s
  208. def test_update(self):
  209. s1 = LimitedSet(maxlen=2)
  210. s1.add('foo')
  211. s1.add('bar')
  212. s2 = LimitedSet(maxlen=2)
  213. s2.update(s1)
  214. assert sorted(list(s2)) == ['bar', 'foo']
  215. s2.update(['bla'])
  216. assert sorted(list(s2)) == ['bar', 'bla']
  217. s2.update(['do', 're'])
  218. assert sorted(list(s2)) == ['do', 're']
  219. s1 = LimitedSet(maxlen=10, expires=None)
  220. s2 = LimitedSet(maxlen=10, expires=None)
  221. s3 = LimitedSet(maxlen=10, expires=None)
  222. s4 = LimitedSet(maxlen=10, expires=None)
  223. s5 = LimitedSet(maxlen=10, expires=None)
  224. for i in range(12):
  225. s1.add(i)
  226. s2.add(i * i)
  227. s3.update(s1)
  228. s3.update(s2)
  229. s4.update(s1.as_dict())
  230. s4.update(s2.as_dict())
  231. s5.update(s1._data) # revoke is using this
  232. s5.update(s2._data)
  233. assert s3 == s4
  234. assert s3 == s5
  235. s2.update(s4)
  236. s4.update(s2)
  237. assert s2 == s4
  238. def test_iterable_and_ordering(self):
  239. s = LimitedSet(maxlen=35, expires=None)
  240. clock = count(1)
  241. for i in reversed(range(15)):
  242. s.add(i, now=next(clock))
  243. j = 40
  244. for i in s:
  245. assert i < j # each item is smaller and smaller
  246. j = i
  247. assert i == 0 # last item is zero
  248. def test_pop_and_ordering_again(self):
  249. s = LimitedSet(maxlen=5)
  250. for i in range(10):
  251. s.add(i)
  252. j = -1
  253. for _ in range(5):
  254. i = s.pop()
  255. assert j < i
  256. i = s.pop()
  257. assert i is None
  258. def test_as_dict(self):
  259. s = LimitedSet(maxlen=2)
  260. s.add('foo')
  261. assert isinstance(s.as_dict(), Mapping)
  262. def test_add_removes_duplicate_from_small_heap(self):
  263. s = LimitedSet(maxlen=2)
  264. s.add('foo')
  265. s.add('foo')
  266. s.add('foo')
  267. assert len(s) == 1
  268. assert len(s._data) == 1
  269. assert len(s._heap) == 1
  270. def test_add_removes_duplicate_from_big_heap(self):
  271. s = LimitedSet(maxlen=1000)
  272. [s.add(i) for i in range(2000)]
  273. assert len(s) == 1000
  274. [s.add('foo') for i in range(1000)]
  275. # heap is refreshed when 15% larger than _data
  276. assert len(s._heap) < 1150
  277. [s.add('foo') for i in range(1000)]
  278. assert len(s._heap) < 1150
  279. class test_AttributeDict:
  280. def test_getattr__setattr(self):
  281. x = AttributeDict({'foo': 'bar'})
  282. assert x['foo'] == 'bar'
  283. with pytest.raises(AttributeError):
  284. x.bar
  285. x.bar = 'foo'
  286. assert x['bar'] == 'foo'
  287. class test_Messagebuffer:
  288. def assert_size_and_first(self, buf, size, expected_first_item):
  289. assert len(buf) == size
  290. assert buf.take() == expected_first_item
  291. def test_append_limited(self):
  292. b = Messagebuffer(10)
  293. for i in range(20):
  294. b.put(i)
  295. self.assert_size_and_first(b, 10, 10)
  296. def test_append_unlimited(self):
  297. b = Messagebuffer(None)
  298. for i in range(20):
  299. b.put(i)
  300. self.assert_size_and_first(b, 20, 0)
  301. def test_extend_limited(self):
  302. b = Messagebuffer(10)
  303. b.extend(list(range(20)))
  304. self.assert_size_and_first(b, 10, 10)
  305. def test_extend_unlimited(self):
  306. b = Messagebuffer(None)
  307. b.extend(list(range(20)))
  308. self.assert_size_and_first(b, 20, 0)
  309. def test_extend_eviction_time_limited(self):
  310. b = Messagebuffer(3000)
  311. b.extend(range(10000))
  312. assert len(b) > 3000
  313. b.evict()
  314. assert len(b) == 3000
  315. def test_pop_empty_with_default(self):
  316. b = Messagebuffer(10)
  317. sentinel = object()
  318. assert b.take(sentinel) is sentinel
  319. def test_pop_empty_no_default(self):
  320. b = Messagebuffer(10)
  321. with pytest.raises(b.Empty):
  322. b.take()
  323. def test_repr(self):
  324. assert repr(Messagebuffer(10, [1, 2, 3]))
  325. def test_iter(self):
  326. b = Messagebuffer(10, list(range(10)))
  327. assert len(b) == 10
  328. for i, item in enumerate(b):
  329. assert item == i
  330. assert len(b) == 0
  331. def test_contains(self):
  332. b = Messagebuffer(10, list(range(10)))
  333. assert 5 in b
  334. def test_reversed(self):
  335. assert (list(reversed(Messagebuffer(10, list(range(10))))) ==
  336. list(reversed(range(10))))
  337. def test_getitem(self):
  338. b = Messagebuffer(10, list(range(10)))
  339. for i in range(10):
  340. assert b[i] == i
  341. class test_BufferMap:
  342. def test_append_limited(self):
  343. b = BufferMap(10)
  344. for i in range(20):
  345. b.put(i, i)
  346. self.assert_size_and_first(b, 10, 10)
  347. def assert_size_and_first(self, buf, size, expected_first_item):
  348. assert buf.total == size
  349. assert buf._LRUpop() == expected_first_item
  350. def test_append_unlimited(self):
  351. b = BufferMap(None)
  352. for i in range(20):
  353. b.put(i, i)
  354. self.assert_size_and_first(b, 20, 0)
  355. def test_extend_limited(self):
  356. b = BufferMap(10)
  357. b.extend(1, list(range(20)))
  358. self.assert_size_and_first(b, 10, 10)
  359. def test_extend_unlimited(self):
  360. b = BufferMap(None)
  361. b.extend(1, list(range(20)))
  362. self.assert_size_and_first(b, 20, 0)
  363. def test_pop_empty_with_default(self):
  364. b = BufferMap(10)
  365. sentinel = object()
  366. assert b.take(1, sentinel) is sentinel
  367. def test_pop_empty_no_default(self):
  368. b = BufferMap(10)
  369. with pytest.raises(b.Empty):
  370. b.take(1)
  371. def test_repr(self):
  372. assert repr(Messagebuffer(10, [1, 2, 3]))