test_saferef.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import unittest
  2. from django.dispatch.saferef import safeRef
  3. from django.utils.six.moves import xrange
  4. class Test1(object):
  5. def x(self):
  6. pass
  7. def test2(obj):
  8. pass
  9. class Test2(object):
  10. def __call__(self, obj):
  11. pass
  12. class SaferefTests(unittest.TestCase):
  13. def setUp(self):
  14. ts = []
  15. ss = []
  16. for x in xrange(5000):
  17. t = Test1()
  18. ts.append(t)
  19. s = safeRef(t.x, self._closure)
  20. ss.append(s)
  21. ts.append(test2)
  22. ss.append(safeRef(test2, self._closure))
  23. for x in xrange(30):
  24. t = Test2()
  25. ts.append(t)
  26. s = safeRef(t, self._closure)
  27. ss.append(s)
  28. self.ts = ts
  29. self.ss = ss
  30. self.closureCount = 0
  31. def tearDown(self):
  32. del self.ts
  33. del self.ss
  34. def testIn(self):
  35. """Test the "in" operator for safe references (cmp)"""
  36. for t in self.ts[:50]:
  37. self.assertTrue(safeRef(t.x) in self.ss)
  38. def testValid(self):
  39. """Test that the references are valid (return instance methods)"""
  40. for s in self.ss:
  41. self.assertTrue(s())
  42. def testShortCircuit(self):
  43. """Test that creation short-circuits to reuse existing references"""
  44. sd = {}
  45. for s in self.ss:
  46. sd[s] = 1
  47. for t in self.ts:
  48. if hasattr(t, 'x'):
  49. self.assertTrue(safeRef(t.x) in sd)
  50. else:
  51. self.assertTrue(safeRef(t) in sd)
  52. def testRepresentation(self):
  53. """Test that the reference object's representation works
  54. XXX Doesn't currently check the results, just that no error
  55. is raised
  56. """
  57. repr(self.ss[-1])
  58. def _closure(self, ref):
  59. """Dumb utility mechanism to increment deletion counter"""
  60. self.closureCount += 1