test_saferef.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from __future__ import absolute_import
  2. from celery.five import range
  3. from celery.utils.dispatch.saferef import safe_ref
  4. from celery.tests.case import Case
  5. class Class1(object):
  6. def x(self):
  7. pass
  8. def fun(obj):
  9. pass
  10. class Class2(object):
  11. def __call__(self, obj):
  12. pass
  13. class SaferefTests(Case):
  14. def setUp(self):
  15. ts = []
  16. ss = []
  17. for x in range(5000):
  18. t = Class1()
  19. ts.append(t)
  20. s = safe_ref(t.x, self._closure)
  21. ss.append(s)
  22. ts.append(fun)
  23. ss.append(safe_ref(fun, self._closure))
  24. for x in range(30):
  25. t = Class2()
  26. ts.append(t)
  27. s = safe_ref(t, self._closure)
  28. ss.append(s)
  29. self.ts = ts
  30. self.ss = ss
  31. self.closureCount = 0
  32. def tearDown(self):
  33. del self.ts
  34. del self.ss
  35. def test_in(self):
  36. """test_in
  37. Test the "in" operator for safe references (cmp)
  38. """
  39. for t in self.ts[:50]:
  40. self.assertTrue(safe_ref(t.x) in self.ss)
  41. def test_valid(self):
  42. """test_value
  43. Test that the references are valid (return instance methods)
  44. """
  45. for s in self.ss:
  46. self.assertTrue(s())
  47. def test_shortcircuit(self):
  48. """test_shortcircuit
  49. Test that creation short-circuits to reuse existing references
  50. """
  51. sd = {}
  52. for s in self.ss:
  53. sd[s] = 1
  54. for t in self.ts:
  55. if hasattr(t, 'x'):
  56. self.assertIn(safe_ref(t.x), sd)
  57. else:
  58. self.assertIn(safe_ref(t), sd)
  59. def test_representation(self):
  60. """test_representation
  61. Test that the reference object's representation works
  62. XXX Doesn't currently check the results, just that no error
  63. is raised
  64. """
  65. repr(self.ss[-1])
  66. def _closure(self, ref):
  67. """Dumb utility mechanism to increment deletion counter"""
  68. self.closureCount += 1