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