test_collections.py 13 KB

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