test_collections.py 13 KB

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