test_compare.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import unittest
  2. from test import test_support
  3. class Empty:
  4. def __repr__(self):
  5. return '<Empty>'
  6. class Coerce:
  7. def __init__(self, arg):
  8. self.arg = arg
  9. def __repr__(self):
  10. return '<Coerce %s>' % self.arg
  11. def __coerce__(self, other):
  12. if isinstance(other, Coerce):
  13. return self.arg, other.arg
  14. else:
  15. return self.arg, other
  16. class Cmp:
  17. def __init__(self,arg):
  18. self.arg = arg
  19. def __repr__(self):
  20. return '<Cmp %s>' % self.arg
  21. def __cmp__(self, other):
  22. return cmp(self.arg, other)
  23. class ComparisonTest(unittest.TestCase):
  24. set1 = [2, 2.0, 2L, 2+0j, Coerce(2), Cmp(2.0)]
  25. set2 = [[1], (3,), None, Empty()]
  26. candidates = set1 + set2
  27. def test_comparisons(self):
  28. for a in self.candidates:
  29. for b in self.candidates:
  30. if ((a in self.set1) and (b in self.set1)) or a is b:
  31. self.assertEqual(a, b)
  32. else:
  33. self.assertNotEqual(a, b)
  34. def test_id_comparisons(self):
  35. # Ensure default comparison compares id() of args
  36. L = []
  37. for i in range(10):
  38. L.insert(len(L)//2, Empty())
  39. for a in L:
  40. for b in L:
  41. self.assertEqual(cmp(a, b), cmp(id(a), id(b)),
  42. 'a=%r, b=%r' % (a, b))
  43. def test_main():
  44. test_support.run_unittest(ComparisonTest)
  45. if __name__ == '__main__':
  46. test_main()