home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 2004 #2 / K-CD-2-2004.ISO / OpenOffice Sv / f_0397 / python-core-2.2.2 / lib / test / test_compare.py < prev    next >
Encoding:
Python Source  |  2003-07-18  |  1.3 KB  |  57 lines

  1. import sys
  2.  
  3. from test_support import *
  4.  
  5. class Empty:
  6.     def __repr__(self):
  7.         return '<Empty>'
  8.  
  9. class Coerce:
  10.     def __init__(self, arg):
  11.         self.arg = arg
  12.  
  13.     def __repr__(self):
  14.         return '<Coerce %s>' % self.arg
  15.  
  16.     def __coerce__(self, other):
  17.         if isinstance(other, Coerce):
  18.             return self.arg, other.arg
  19.         else:
  20.             return self.arg, other
  21.  
  22. class Cmp:
  23.     def __init__(self,arg):
  24.         self.arg = arg
  25.  
  26.     def __repr__(self):
  27.         return '<Cmp %s>' % self.arg
  28.  
  29.     def __cmp__(self, other):
  30.         return cmp(self.arg, other)
  31.  
  32.  
  33. candidates = [2, 2.0, 2L, 2+0j, [1], (3,), None, Empty(), Coerce(2), Cmp(2.0)]
  34.  
  35. def test():
  36.     for a in candidates:
  37.         for b in candidates:
  38.             try:
  39.                 x = a == b
  40.             except:
  41.                 print 'cmp(%s, %s) => %s' % (a, b, sys.exc_info()[0])
  42.             else:
  43.                 if x:
  44.                     print "%s == %s" % (a, b)
  45.                 else:
  46.                     print "%s != %s" % (a, b)
  47.     # Ensure default comparison compares id() of args
  48.     L = []
  49.     for i in range(10):
  50.         L.insert(len(L)//2, Empty())
  51.     for a in L:
  52.         for b in L:
  53.             if cmp(a, b) != cmp(id(a), id(b)):
  54.                 print "ERROR:", cmp(a, b), cmp(id(a), id(b)), id(a), id(b)
  55.  
  56. test()
  57.