summaryrefslogtreecommitdiffstats
path: root/Lib/test
diff options
context:
space:
mode:
authorGuido van Rossum <guido@python.org>2006-08-24 00:41:19 (GMT)
committerGuido van Rossum <guido@python.org>2006-08-24 00:41:19 (GMT)
commit47b9ff6ba11fab4c90556357c437cb4feec1e853 (patch)
treeb5319f74e08caf3276275462b14372b4da9f7dee /Lib/test
parent9a6e62b947ebb5547ca9a164f6145a461b98d86a (diff)
downloadcpython-47b9ff6ba11fab4c90556357c437cb4feec1e853.zip
cpython-47b9ff6ba11fab4c90556357c437cb4feec1e853.tar.gz
cpython-47b9ff6ba11fab4c90556357c437cb4feec1e853.tar.bz2
Restructure comparison dramatically. There is no longer a default
*ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
Diffstat (limited to 'Lib/test')
-rw-r--r--Lib/test/mapping_tests.py25
-rw-r--r--Lib/test/output/test_class20
-rw-r--r--Lib/test/pickletester.py4
-rw-r--r--Lib/test/test_bisect.py7
-rw-r--r--Lib/test/test_buffer.py44
-rw-r--r--Lib/test/test_builtin.py20
-rw-r--r--Lib/test/test_calendar.py2
-rw-r--r--Lib/test/test_cgi.py18
-rw-r--r--Lib/test/test_class.py24
-rw-r--r--Lib/test/test_compare.py6
-rw-r--r--Lib/test/test_copy.py70
-rw-r--r--Lib/test/test_decimal.py4
-rw-r--r--Lib/test/test_descr.py83
-rw-r--r--Lib/test/test_descrtut.py5
-rw-r--r--Lib/test/test_dict.py11
-rw-r--r--Lib/test/test_grammar.py4
-rw-r--r--Lib/test/test_heapq.py3
-rw-r--r--Lib/test/test_itertools.py6
-rw-r--r--Lib/test/test_mutants.py9
-rw-r--r--Lib/test/test_operations.py4
-rw-r--r--Lib/test/test_set.py23
-rw-r--r--Lib/test/test_sets.py15
-rw-r--r--Lib/test/test_slice.py6
-rw-r--r--Lib/test/test_sort.py6
-rw-r--r--Lib/test/test_support.py4
-rw-r--r--Lib/test/test_types.py1
-rw-r--r--Lib/test/test_userdict.py2
-rw-r--r--Lib/test/test_weakref.py6
28 files changed, 272 insertions, 160 deletions
diff --git a/Lib/test/mapping_tests.py b/Lib/test/mapping_tests.py
index b917540..15f9add 100644
--- a/Lib/test/mapping_tests.py
+++ b/Lib/test/mapping_tests.py
@@ -60,10 +60,10 @@ class BasicTestMappingProtocol(unittest.TestCase):
for k in self.other:
self.failIf(k in d)
#cmp
- self.assertEqual(cmp(p,p), 0)
- self.assertEqual(cmp(d,d), 0)
- self.assertEqual(cmp(p,d), -1)
- self.assertEqual(cmp(d,p), 1)
+ self.assertEqual(p, p)
+ self.assertEqual(d, d)
+ self.assertNotEqual(p, d)
+ self.assertNotEqual(d, p)
#__non__zero__
if p: self.fail("Empty mapping must compare to False")
if not d: self.fail("Full mapping must compare to True")
@@ -623,9 +623,10 @@ class TestHashMappingProtocol(TestMappingProtocol):
d = self._full_mapping({1: BadRepr()})
self.assertRaises(Exc, repr, d)
- def test_le(self):
- self.assert_(not (self._empty_mapping() < self._empty_mapping()))
- self.assert_(not (self._full_mapping({1: 2}) < self._full_mapping({1L: 2L})))
+ def test_eq(self):
+ self.assertEqual(self._empty_mapping(), self._empty_mapping())
+ self.assertEqual(self._full_mapping({1: 2}),
+ self._full_mapping({1L: 2L}))
class Exc(Exception): pass
@@ -633,16 +634,12 @@ class TestHashMappingProtocol(TestMappingProtocol):
def __eq__(self, other):
raise Exc()
def __hash__(self):
- return 42
+ return 1
d1 = self._full_mapping({BadCmp(): 1})
d2 = self._full_mapping({1: 1})
- try:
- d1 < d2
- except Exc:
- pass
- else:
- self.fail("< didn't raise Exc")
+ self.assertRaises(Exc, lambda: BadCmp()==1)
+ self.assertRaises(Exc, lambda: d1==d2)
def test_setdefault(self):
TestMappingProtocol.test_setdefault(self)
diff --git a/Lib/test/output/test_class b/Lib/test/output/test_class
index 14d43a8..7d8ab5e 100644
--- a/Lib/test/output/test_class
+++ b/Lib/test/output/test_class
@@ -51,16 +51,16 @@ __hex__: ()
__hash__: ()
__repr__: ()
__str__: ()
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
-__cmp__: (1,)
+__eq__: (1,)
+__lt__: (1,)
+__gt__: (1,)
+__ne__: (1,)
+__ne__: (1,)
+__eq__: (1,)
+__gt__: (1,)
+__lt__: (1,)
+__ne__: (1,)
+__ne__: (1,)
__del__: ()
__getattr__: ('spam',)
__setattr__: ('eggs', 'spam, spam, spam and ham')
diff --git a/Lib/test/pickletester.py b/Lib/test/pickletester.py
index 42853c4..30c1e7c 100644
--- a/Lib/test/pickletester.py
+++ b/Lib/test/pickletester.py
@@ -65,8 +65,8 @@ class ExtensionSaver:
copy_reg.add_extension(pair[0], pair[1], code)
class C:
- def __cmp__(self, other):
- return cmp(self.__dict__, other.__dict__)
+ def __eq__(self, other):
+ return self.__dict__ == other.__dict__
import __main__
__main__.C = C
diff --git a/Lib/test/test_bisect.py b/Lib/test/test_bisect.py
index 302ff63..772e808 100644
--- a/Lib/test/test_bisect.py
+++ b/Lib/test/test_bisect.py
@@ -174,8 +174,13 @@ class GetOnly:
class CmpErr:
"Dummy element that always raises an error during comparison"
- def __cmp__(self, other):
+ def __lt__(self, other):
raise ZeroDivisionError
+ __gt__ = __lt__
+ __le__ = __lt__
+ __ge__ = __lt__
+ __eq__ = __lt__
+ __ne__ = __lt__
class TestErrorHandling(unittest.TestCase):
diff --git a/Lib/test/test_buffer.py b/Lib/test/test_buffer.py
new file mode 100644
index 0000000..eb6e9ea
--- /dev/null
+++ b/Lib/test/test_buffer.py
@@ -0,0 +1,44 @@
+"""Unit tests for buffer objects.
+
+For now, we just test (the brand new) rich comparison.
+
+"""
+
+import unittest
+from test import test_support
+
+class BufferTests(unittest.TestCase):
+
+ def test_comparison(self):
+ a = buffer("a.b.c")
+ b = buffer("a.b" + ".c")
+ self.assert_(a == b)
+ self.assert_(a <= b)
+ self.assert_(a >= b)
+ self.assert_(a == "a.b.c")
+ self.assert_(a <= "a.b.c")
+ self.assert_(a >= "a.b.c")
+ b = buffer("a.b.c.d")
+ self.assert_(a != b)
+ self.assert_(a <= b)
+ self.assert_(a < b)
+ self.assert_(a != "a.b.c.d")
+ self.assert_(a < "a.b.c.d")
+ self.assert_(a <= "a.b.c.d")
+ b = buffer("a.b")
+ self.assert_(a != b)
+ self.assert_(a >= b)
+ self.assert_(a > b)
+ self.assert_(a != "a.b")
+ self.assert_(a > "a.b")
+ self.assert_(a >= "a.b")
+ b = object()
+ self.assert_(a != b)
+ self.failIf(a == b)
+ self.assertRaises(TypeError, lambda: a < b)
+
+def test_main():
+ test_support.run_unittest(BufferTests)
+
+if __name__ == "__main__":
+ test_main()
diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
index b0dbd4a..d3a272b 100644
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -179,7 +179,8 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises(ValueError, chr, 256)
self.assertRaises(TypeError, chr)
- def test_cmp(self):
+ def XXX_test_cmp(self):
+ # cmp() is no longer supported
self.assertEqual(cmp(-1, 1), -1)
self.assertEqual(cmp(1, -1), 1)
self.assertEqual(cmp(1, 1), 0)
@@ -1132,8 +1133,14 @@ class BuiltinTest(unittest.TestCase):
map(None, Squares(3), Squares(2)),
[(0,0), (1,1), (4,None)]
)
+ def Max(a, b):
+ if a is None:
+ return b
+ if b is None:
+ return a
+ return max(a, b)
self.assertEqual(
- map(max, Squares(3), Squares(2)),
+ map(Max, Squares(3), Squares(2)),
[0, 1, 4]
)
self.assertRaises(TypeError, map)
@@ -1201,7 +1208,7 @@ class BuiltinTest(unittest.TestCase):
class BadNumber:
def __cmp__(self, other):
raise ValueError
- self.assertRaises(ValueError, min, (42, BadNumber()))
+ self.assertRaises(TypeError, min, (42, BadNumber()))
for stmt in (
"min(key=int)", # no args
@@ -1379,8 +1386,11 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises(ValueError, range, a, a + 1, long(0))
class badzero(int):
- def __cmp__(self, other):
+ def __eq__(self, other):
raise RuntimeError
+ __ne__ = __lt__ = __gt__ = __le__ = __ge__ = __eq__
+
+ # XXX This won't (but should!) raise RuntimeError if a is an int...
self.assertRaises(RuntimeError, range, a, a + 1, badzero(1))
# Reject floats when it would require PyLongs to represent.
@@ -1594,7 +1604,7 @@ class TestSorted(unittest.TestCase):
data.reverse()
random.shuffle(copy)
- self.assertEqual(data, sorted(copy, cmp=lambda x, y: cmp(y,x)))
+ self.assertEqual(data, sorted(copy, cmp=lambda x, y: (x < y) - (x > y)))
self.assertNotEqual(data, copy)
random.shuffle(copy)
self.assertEqual(data, sorted(copy, key=lambda x: -x))
diff --git a/Lib/test/test_calendar.py b/Lib/test/test_calendar.py
index e414324..893890d 100644
--- a/Lib/test/test_calendar.py
+++ b/Lib/test/test_calendar.py
@@ -212,7 +212,7 @@ class CalendarTestCase(unittest.TestCase):
self.assertEqual(calendar.isleap(2003), 0)
def test_setfirstweekday(self):
- self.assertRaises(ValueError, calendar.setfirstweekday, 'flabber')
+ self.assertRaises(TypeError, calendar.setfirstweekday, 'flabber')
self.assertRaises(ValueError, calendar.setfirstweekday, -1)
self.assertRaises(ValueError, calendar.setfirstweekday, 200)
orig = calendar.firstweekday()
diff --git a/Lib/test/test_cgi.py b/Lib/test/test_cgi.py
index 8fe487b..f93fa55 100644
--- a/Lib/test/test_cgi.py
+++ b/Lib/test/test_cgi.py
@@ -25,13 +25,11 @@ class ComparableException:
def __str__(self):
return str(self.err)
- def __cmp__(self, anExc):
+ def __eq__(self, anExc):
if not isinstance(anExc, Exception):
- return -1
- x = cmp(self.err.__class__, anExc.__class__)
- if x != 0:
- return x
- return cmp(self.err.args, anExc.args)
+ return NotImplemented
+ return (self.err.__class__ == anExc.__class__ and
+ self.err.args == anExc.args)
def __getattr__(self, attr):
return getattr(self.err, attr)
@@ -118,10 +116,10 @@ parse_strict_test_cases = [
})
]
-def norm(list):
- if type(list) == type([]):
- list.sort()
- return list
+def norm(seq):
+ if isinstance(seq, list):
+ seq.sort(key=repr)
+ return seq
def first_elts(list):
return map(lambda x:x[0], list)
diff --git a/Lib/test/test_class.py b/Lib/test/test_class.py
index a0b3300..66f4265 100644
--- a/Lib/test/test_class.py
+++ b/Lib/test/test_class.py
@@ -100,6 +100,30 @@ class AllTests:
print "__cmp__:", args
return 0
+ def __eq__(self, *args):
+ print "__eq__:", args
+ return True
+
+ def __ne__(self, *args):
+ print "__ne__:", args
+ return False
+
+ def __lt__(self, *args):
+ print "__lt__:", args
+ return False
+
+ def __le__(self, *args):
+ print "__le__:", args
+ return True
+
+ def __gt__(self, *args):
+ print "__gt__:", args
+ return False
+
+ def __ge__(self, *args):
+ print "__ge__:", args
+ return True
+
def __del__(self, *args):
print "__del__:", args
diff --git a/Lib/test/test_compare.py b/Lib/test/test_compare.py
index 7c81194..8f38e3b 100644
--- a/Lib/test/test_compare.py
+++ b/Lib/test/test_compare.py
@@ -13,8 +13,8 @@ class Cmp:
def __repr__(self):
return '<Cmp %s>' % self.arg
- def __cmp__(self, other):
- return cmp(self.arg, other)
+ def __eq__(self, other):
+ return self.arg == other
class ComparisonTest(unittest.TestCase):
set1 = [2, 2.0, 2L, 2+0j, Cmp(2.0)]
@@ -36,7 +36,7 @@ class ComparisonTest(unittest.TestCase):
L.insert(len(L)//2, Empty())
for a in L:
for b in L:
- self.assertEqual(cmp(a, b), cmp(id(a), id(b)),
+ self.assertEqual(a == b, id(a) == id(b),
'a=%r, b=%r' % (a, b))
def test_main():
diff --git a/Lib/test/test_copy.py b/Lib/test/test_copy.py
index ff4c987..416a755 100644
--- a/Lib/test/test_copy.py
+++ b/Lib/test/test_copy.py
@@ -104,8 +104,8 @@ class TestCopy(unittest.TestCase):
class C:
def __init__(self, foo):
self.foo = foo
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C(42)
self.assertEqual(copy.copy(x), x)
@@ -115,8 +115,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __copy__(self):
return C(self.foo)
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C(42)
self.assertEqual(copy.copy(x), x)
@@ -126,8 +126,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __getinitargs__(self):
return (self.foo,)
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C(42)
self.assertEqual(copy.copy(x), x)
@@ -137,8 +137,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __getstate__(self):
return {"foo": self.foo}
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C(42)
self.assertEqual(copy.copy(x), x)
@@ -148,8 +148,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __setstate__(self, state):
self.foo = state["foo"]
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C(42)
self.assertEqual(copy.copy(x), x)
@@ -161,8 +161,8 @@ class TestCopy(unittest.TestCase):
return self.foo
def __setstate__(self, state):
self.foo = state
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C(42)
self.assertEqual(copy.copy(x), x)
@@ -304,7 +304,7 @@ class TestCopy(unittest.TestCase):
x = {}
x['foo'] = x
y = copy.deepcopy(x)
- self.assertRaises(RuntimeError, cmp, y, x)
+ self.assertRaises(TypeError, cmp, y, x)
self.assert_(y is not x)
self.assert_(y['foo'] is y)
self.assertEqual(len(y), 1)
@@ -319,8 +319,8 @@ class TestCopy(unittest.TestCase):
class C:
def __init__(self, foo):
self.foo = foo
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
@@ -332,8 +332,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __deepcopy__(self, memo):
return C(copy.deepcopy(self.foo, memo))
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
@@ -346,8 +346,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __getinitargs__(self):
return (self.foo,)
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
@@ -360,8 +360,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __getstate__(self):
return {"foo": self.foo}
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
@@ -374,8 +374,8 @@ class TestCopy(unittest.TestCase):
self.foo = foo
def __setstate__(self, state):
self.foo = state["foo"]
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
@@ -390,8 +390,8 @@ class TestCopy(unittest.TestCase):
return self.foo
def __setstate__(self, state):
self.foo = state
- def __cmp__(self, other):
- return cmp(self.foo, other.foo)
+ def __eq__(self, other):
+ return self.foo == other.foo
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
@@ -434,8 +434,8 @@ class TestCopy(unittest.TestCase):
class C(object):
def __reduce__(self):
return (C, (), self.__dict__)
- def __cmp__(self, other):
- return cmp(self.__dict__, other.__dict__)
+ def __eq__(self, other):
+ return self.__dict__ == other.__dict__
x = C()
x.foo = [42]
y = copy.copy(x)
@@ -450,8 +450,8 @@ class TestCopy(unittest.TestCase):
return (C, (), self.__dict__)
def __setstate__(self, state):
self.__dict__.update(state)
- def __cmp__(self, other):
- return cmp(self.__dict__, other.__dict__)
+ def __eq__(self, other):
+ return self.__dict__ == other.__dict__
x = C()
x.foo = [42]
y = copy.copy(x)
@@ -475,9 +475,9 @@ class TestCopy(unittest.TestCase):
class C(list):
def __reduce__(self):
return (C, (), self.__dict__, iter(self))
- def __cmp__(self, other):
- return (cmp(list(self), list(other)) or
- cmp(self.__dict__, other.__dict__))
+ def __eq__(self, other):
+ return (list(self) == list(other) and
+ self.__dict__ == other.__dict__)
x = C([[1, 2], 3])
y = copy.copy(x)
self.assertEqual(x, y)
@@ -492,9 +492,9 @@ class TestCopy(unittest.TestCase):
class C(dict):
def __reduce__(self):
return (C, (), self.__dict__, None, self.iteritems())
- def __cmp__(self, other):
- return (cmp(dict(self), list(dict)) or
- cmp(self.__dict__, other.__dict__))
+ def __eq__(self, other):
+ return (dict(self) == dict(other) and
+ self.__dict__ == other.__dict__)
x = C([("foo", [1, 2]), ("bar", 3)])
y = copy.copy(x)
self.assertEqual(x, y)
diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py
index 40c4466..5fef4eb 100644
--- a/Lib/test/test_decimal.py
+++ b/Lib/test/test_decimal.py
@@ -276,8 +276,8 @@ class DecimalTest(unittest.TestCase):
myexceptions = self.getexceptions()
self.context.clear_flags()
- myexceptions.sort()
- theirexceptions.sort()
+ myexceptions.sort(key=repr)
+ theirexceptions.sort(key=repr)
self.assertEqual(result, ans,
'Incorrect answer for ' + s + ' -- got ' + result)
diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py
index 00800a7..3fb01e7 100644
--- a/Lib/test/test_descr.py
+++ b/Lib/test/test_descr.py
@@ -151,7 +151,7 @@ def lists():
def dicts():
if verbose: print "Testing dict operations..."
- testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
+ ##testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
@@ -523,7 +523,7 @@ def spamdicts():
# This is an ugly hack:
copy._deepcopy_dispatch[spam.spamdict] = spamdict
- testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
+ ##testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
@@ -1641,7 +1641,7 @@ def specials():
verify(id(c1) != id(c2))
hash(c1)
hash(c2)
- vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
+ ##vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
vereq(c1, c1)
verify(c1 != c2)
verify(not c1 != c1)
@@ -1665,7 +1665,7 @@ def specials():
verify(id(d1) != id(d2))
hash(d1)
hash(d2)
- vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
+ ##vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
vereq(d1, d1)
verify(d1 != d2)
verify(not d1 != d1)
@@ -1758,21 +1758,21 @@ def specials():
for i in range(10):
verify(i in p10)
verify(10 not in p10)
- # Safety test for __cmp__
- def unsafecmp(a, b):
- try:
- a.__class__.__cmp__(a, b)
- except TypeError:
- pass
- else:
- raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
- a.__class__, a, b)
- unsafecmp(u"123", "123")
- unsafecmp("123", u"123")
- unsafecmp(1, 1.0)
- unsafecmp(1.0, 1)
- unsafecmp(1, 1L)
- unsafecmp(1L, 1)
+## # Safety test for __cmp__
+## def unsafecmp(a, b):
+## try:
+## a.__class__.__cmp__(a, b)
+## except TypeError:
+## pass
+## else:
+## raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
+## a.__class__, a, b)
+## unsafecmp(u"123", "123")
+## unsafecmp("123", u"123")
+## unsafecmp(1, 1.0)
+## unsafecmp(1.0, 1)
+## unsafecmp(1, 1L)
+## unsafecmp(1L, 1)
class Letter(str):
def __new__(cls, letter):
@@ -2469,12 +2469,43 @@ def classic_comparisons():
class C(base):
def __init__(self, value):
self.value = int(value)
- def __cmp__(self, other):
+ def __eq__(self, other):
+ if isinstance(other, C):
+ return self.value == other.value
+ if isinstance(other, int) or isinstance(other, long):
+ return self.value == other
+ return NotImplemented
+ def __ne__(self, other):
+ if isinstance(other, C):
+ return self.value != other.value
+ if isinstance(other, int) or isinstance(other, long):
+ return self.value != other
+ return NotImplemented
+ def __lt__(self, other):
+ if isinstance(other, C):
+ return self.value < other.value
+ if isinstance(other, int) or isinstance(other, long):
+ return self.value < other
+ return NotImplemented
+ def __le__(self, other):
+ if isinstance(other, C):
+ return self.value <= other.value
+ if isinstance(other, int) or isinstance(other, long):
+ return self.value <= other
+ return NotImplemented
+ def __gt__(self, other):
if isinstance(other, C):
- return cmp(self.value, other.value)
+ return self.value > other.value
+ if isinstance(other, int) or isinstance(other, long):
+ return self.value > other
+ return NotImplemented
+ def __ge__(self, other):
+ if isinstance(other, C):
+ return self.value >= other.value
if isinstance(other, int) or isinstance(other, long):
- return cmp(self.value, other)
+ return self.value >= other
return NotImplemented
+
c1 = C(1)
c2 = C(2)
c3 = C(3)
@@ -2482,12 +2513,12 @@ def classic_comparisons():
c = {1: c1, 2: c2, 3: c3}
for x in 1, 2, 3:
for y in 1, 2, 3:
- verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
+ ##verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
for op in "<", "<=", "==", "!=", ">", ">=":
verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
"x=%d, y=%d" % (x, y))
- verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
- verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
+ ##verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
+ ##verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
def rich_comparisons():
if verbose:
@@ -3875,6 +3906,8 @@ def methodwrapper():
if verbose:
print "Testing method-wrapper objects..."
+ return # XXX should methods really support __eq__?
+
l = []
vereq(l.__add__, l.__add__)
vereq(l.__add__, [].__add__)
diff --git a/Lib/test/test_descrtut.py b/Lib/test/test_descrtut.py
index 6a5310c..28d7d13 100644
--- a/Lib/test/test_descrtut.py
+++ b/Lib/test/test_descrtut.py
@@ -65,14 +65,11 @@ We can also use the new type in contexts where classic only allows "real"
dictionaries, such as the locals/globals dictionaries for the exec
statement or the built-in function eval():
- >>> def sorted(seq):
- ... seq.sort()
- ... return seq
>>> print sorted(a.keys())
[1, 2]
>>> exec "x = 3; print x" in a
3
- >>> print sorted(a.keys())
+ >>> print sorted(a.keys(), key=lambda x: (str(type(x)), x))
[1, 2, '__builtins__', 'x']
>>> print a['x']
3
diff --git a/Lib/test/test_dict.py b/Lib/test/test_dict.py
index 7295f41..717ed5e 100644
--- a/Lib/test/test_dict.py
+++ b/Lib/test/test_dict.py
@@ -5,6 +5,7 @@ import sys, UserDict, cStringIO
class DictTest(unittest.TestCase):
+
def test_constructor(self):
# calling built-in types without argument must return empty
self.assertEqual(dict(), {})
@@ -368,9 +369,9 @@ class DictTest(unittest.TestCase):
d = {1: BadRepr()}
self.assertRaises(Exc, repr, d)
- def test_le(self):
- self.assert_(not ({} < {}))
- self.assert_(not ({1: 2} < {1L: 2L}))
+ def test_eq(self):
+ self.assertEqual({}, {})
+ self.assertEqual({1: 2}, {1L: 2L})
class Exc(Exception): pass
@@ -378,12 +379,12 @@ class DictTest(unittest.TestCase):
def __eq__(self, other):
raise Exc()
def __hash__(self):
- return 42
+ return 1
d1 = {BadCmp(): 1}
d2 = {1: 1}
try:
- d1 < d2
+ d1 == d2
except Exc:
pass
else:
diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py
index 296dc9b..458bfa2 100644
--- a/Lib/test/test_grammar.py
+++ b/Lib/test/test_grammar.py
@@ -681,7 +681,7 @@ d[1,] = 2
d[1,2] = 3
d[1,2,3] = 4
L = list(d)
-L.sort()
+L.sort(key=lambda x: x if isinstance(x, tuple) else ())
print L
@@ -741,7 +741,7 @@ print [(i, s) for i in nums for s in [f for f in strs if "n" in f]]
print [(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)]
def test_in_func(l):
- return [None < x < 3 for x in l if x > 2]
+ return [0 < x < 3 for x in l if x > 2]
print test_in_func(nums)
diff --git a/Lib/test/test_heapq.py b/Lib/test/test_heapq.py
index 2da4f8c..1916449 100644
--- a/Lib/test/test_heapq.py
+++ b/Lib/test/test_heapq.py
@@ -136,6 +136,7 @@ class CmpErr:
"Dummy element that always raises an error during comparison"
def __cmp__(self, other):
raise ZeroDivisionError
+ __eq__ = __ne__ = __lt__ = __le__ = __gt__ = __ge__ = __cmp__
def R(seqn):
'Regular generator'
@@ -253,7 +254,7 @@ class TestErrorHandling(unittest.TestCase):
def test_iterable_args(self):
for f in (nlargest, nsmallest):
- for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
+ for s in ("123", "", range(1000), (1, 1.2), xrange(2000,2200,5)):
for g in (G, I, Ig, L, R):
self.assertEqual(f(2, g(s)), f(2,s))
self.assertEqual(f(2, S(s)), [])
diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
index b2a9b55..29abd4b 100644
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -132,13 +132,13 @@ class TestBasicOps(unittest.TestCase):
# __cmp__ failure
class DummyCmp:
- def __cmp__(self, dst):
+ def __eq__(self, dst):
raise ExpectedError
s = [DummyCmp(), DummyCmp(), None]
- # __cmp__ failure on outer object
+ # __eq__ failure on outer object
self.assertRaises(ExpectedError, gulp, s, func=id)
- # __cmp__ failure on inner object
+ # __eq__ failure on inner object
self.assertRaises(ExpectedError, gulp, s)
# keyfunc failure
diff --git a/Lib/test/test_mutants.py b/Lib/test/test_mutants.py
index df58944..39ea806 100644
--- a/Lib/test/test_mutants.py
+++ b/Lib/test/test_mutants.py
@@ -27,7 +27,7 @@ import os
# ran it. Indeed, at the start, the driver never got beyond 6 iterations
# before the test died.
-# The dicts are global to make it easy to mutate tham from within functions.
+# The dicts are global to make it easy to mutate them from within functions.
dict1 = {}
dict2 = {}
@@ -93,9 +93,9 @@ class Horrid:
def __hash__(self):
return self.hashcode
- def __cmp__(self, other):
+ def __eq__(self, other):
maybe_mutate() # The point of the test.
- return cmp(self.i, other.i)
+ return self.i == other.i
def __repr__(self):
return "Horrid(%d)" % self.i
@@ -132,7 +132,8 @@ def test_one(n):
while dict1 and len(dict1) == len(dict2):
if verbose:
print ".",
- c = cmp(dict1, dict2)
+ c = dict1 == dict2
+ XXX # Can't figure out how to make this work
if verbose:
print
diff --git a/Lib/test/test_operations.py b/Lib/test/test_operations.py
index 0b558de..67e77aa 100644
--- a/Lib/test/test_operations.py
+++ b/Lib/test/test_operations.py
@@ -12,7 +12,7 @@ class BadDictKey:
def __hash__(self):
return hash(self.__class__)
- def __cmp__(self, other):
+ def __eq__(self, other):
if isinstance(other, self.__class__):
print "raising error"
raise RuntimeError, "gotcha"
@@ -34,7 +34,7 @@ for stmt in ['d[x2] = 2',
except RuntimeError:
print "%s: caught the RuntimeError outside" % (stmt,)
else:
- print "%s: No exception passed through!" # old CPython behavior
+ print "%s: No exception passed through!" % (stmt,) # old CPython behavior
# Dict resizing bug, found by Jack Jansen in 2.2 CVS development.
diff --git a/Lib/test/test_set.py b/Lib/test/test_set.py
index 0268be2..23926be 100644
--- a/Lib/test/test_set.py
+++ b/Lib/test/test_set.py
@@ -18,7 +18,7 @@ def check_pass_thru():
class BadCmp:
def __hash__(self):
return 1
- def __cmp__(self, other):
+ def __eq__(self, other):
raise RuntimeError
class TestJointOps(unittest.TestCase):
@@ -781,11 +781,8 @@ class TestBinaryOps(unittest.TestCase):
a, b = set('a'), set('b')
self.assertRaises(TypeError, cmp, a, b)
- # You can view this as a buglet: cmp(a, a) does not raise TypeError,
- # because __eq__ is tried before __cmp__, and a.__eq__(a) returns True,
- # which Python thinks is good enough to synthesize a cmp() result
- # without calling __cmp__.
- self.assertEqual(cmp(a, a), 0)
+ # In py3k, this works!
+ self.assertRaises(TypeError, cmp, a, a)
self.assertRaises(TypeError, cmp, a, 12)
self.assertRaises(TypeError, cmp, "abc", a)
@@ -1201,8 +1198,8 @@ class TestCopying(unittest.TestCase):
def test_copy(self):
dup = self.set.copy()
- dup_list = list(dup); dup_list.sort()
- set_list = list(self.set); set_list.sort()
+ dup_list = sorted(dup, key=repr)
+ set_list = sorted(self.set, key=repr)
self.assertEqual(len(dup_list), len(set_list))
for i in range(len(dup_list)):
self.failUnless(dup_list[i] is set_list[i])
@@ -1210,8 +1207,8 @@ class TestCopying(unittest.TestCase):
def test_deep_copy(self):
dup = copy.deepcopy(self.set)
##print type(dup), repr(dup)
- dup_list = list(dup); dup_list.sort()
- set_list = list(self.set); set_list.sort()
+ dup_list = sorted(dup, key=repr)
+ set_list = sorted(self.set, key=repr)
self.assertEqual(len(dup_list), len(set_list))
for i in range(len(dup_list)):
self.assertEqual(dup_list[i], set_list[i])
@@ -1374,7 +1371,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
for cons in (set, frozenset):
for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
- self.assertEqual(sorted(cons(g(s))), sorted(g(s)))
+ self.assertEqual(sorted(cons(g(s)), key=repr), sorted(g(s), key=repr))
self.assertRaises(TypeError, cons , X(s))
self.assertRaises(TypeError, cons , N(s))
self.assertRaises(ZeroDivisionError, cons , E(s))
@@ -1386,7 +1383,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
for g in (G, I, Ig, L, R):
expected = meth(data)
actual = meth(G(data))
- self.assertEqual(sorted(actual), sorted(expected))
+ self.assertEqual(sorted(actual, key=repr), sorted(expected, key=repr))
self.assertRaises(TypeError, meth, X(s))
self.assertRaises(TypeError, meth, N(s))
self.assertRaises(ZeroDivisionError, meth, E(s))
@@ -1400,7 +1397,7 @@ class TestVariousIteratorArgs(unittest.TestCase):
t = s.copy()
getattr(s, methname)(list(g(data)))
getattr(t, methname)(g(data))
- self.assertEqual(sorted(s), sorted(t))
+ self.assertEqual(sorted(s, key=repr), sorted(t, key=repr))
self.assertRaises(TypeError, getattr(set('january'), methname), X(data))
self.assertRaises(TypeError, getattr(set('january'), methname), N(data))
diff --git a/Lib/test/test_sets.py b/Lib/test/test_sets.py
index 85e4a22..88cfcac 100644
--- a/Lib/test/test_sets.py
+++ b/Lib/test/test_sets.py
@@ -234,11 +234,8 @@ class TestBinaryOps(unittest.TestCase):
a, b = Set('a'), Set('b')
self.assertRaises(TypeError, cmp, a, b)
- # You can view this as a buglet: cmp(a, a) does not raise TypeError,
- # because __eq__ is tried before __cmp__, and a.__eq__(a) returns True,
- # which Python thinks is good enough to synthesize a cmp() result
- # without calling __cmp__.
- self.assertEqual(cmp(a, a), 0)
+ # In py3k, this works!
+ self.assertRaises(TypeError, cmp, a, a)
self.assertRaises(TypeError, cmp, a, 12)
self.assertRaises(TypeError, cmp, "abc", a)
@@ -675,8 +672,8 @@ class TestCopying(unittest.TestCase):
def test_copy(self):
dup = self.set.copy()
- dup_list = list(dup); dup_list.sort()
- set_list = list(self.set); set_list.sort()
+ dup_list = sorted(dup, key=repr)
+ set_list = sorted(self.set, key=repr)
self.assertEqual(len(dup_list), len(set_list))
for i in range(len(dup_list)):
self.failUnless(dup_list[i] is set_list[i])
@@ -684,8 +681,8 @@ class TestCopying(unittest.TestCase):
def test_deep_copy(self):
dup = copy.deepcopy(self.set)
##print type(dup), repr(dup)
- dup_list = list(dup); dup_list.sort()
- set_list = list(self.set); set_list.sort()
+ dup_list = sorted(dup, key=repr)
+ set_list = sorted(self.set, key=repr)
self.assertEqual(len(dup_list), len(set_list))
for i in range(len(dup_list)):
self.assertEqual(dup_list[i], set_list[i])
diff --git a/Lib/test/test_slice.py b/Lib/test/test_slice.py
index d8eb882..bd6e621 100644
--- a/Lib/test/test_slice.py
+++ b/Lib/test/test_slice.py
@@ -35,18 +35,18 @@ class SliceTest(unittest.TestCase):
s1 = slice(BadCmp())
s2 = slice(BadCmp())
- self.assertRaises(Exc, cmp, s1, s2)
self.assertEqual(s1, s1)
+ self.assertRaises(Exc, lambda: s1 == s2)
s1 = slice(1, BadCmp())
s2 = slice(1, BadCmp())
self.assertEqual(s1, s1)
- self.assertRaises(Exc, cmp, s1, s2)
+ self.assertRaises(Exc, lambda: s1 == s2)
s1 = slice(1, 2, BadCmp())
s2 = slice(1, 2, BadCmp())
self.assertEqual(s1, s1)
- self.assertRaises(Exc, cmp, s1, s2)
+ self.assertRaises(Exc, lambda: s1 == s2)
def test_members(self):
s = slice(1)
diff --git a/Lib/test/test_sort.py b/Lib/test/test_sort.py
index 84c92cc..031780a 100644
--- a/Lib/test/test_sort.py
+++ b/Lib/test/test_sort.py
@@ -68,8 +68,8 @@ class TestBase(unittest.TestCase):
self.key = key
self.index = i
- def __cmp__(self, other):
- return cmp(self.key, other.key)
+ def __lt__(self, other):
+ return self.key < other.key
def __repr__(self):
return "Stable(%d, %d)" % (self.key, self.index)
@@ -225,6 +225,8 @@ class TestDecorateSortUndecorate(unittest.TestCase):
def __del__(self):
del data[:]
data[:] = range(20)
+ def __lt__(self, other):
+ return id(self) < id(other)
self.assertRaises(ValueError, data.sort, key=SortKiller)
def test_key_with_mutating_del_and_exception(self):
diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py
index 0397118..d260fc5 100644
--- a/Lib/test/test_support.py
+++ b/Lib/test/test_support.py
@@ -122,8 +122,8 @@ def fcmp(x, y): # fuzzy comparison function
outcome = fcmp(x[i], y[i])
if outcome != 0:
return outcome
- return cmp(len(x), len(y))
- return cmp(x, y)
+ return (len(x) > len(y)) - (len(x) < len(y))
+ return (x > y) - (x < y)
try:
unicode
diff --git a/Lib/test/test_types.py b/Lib/test/test_types.py
index 2d299c3..f0bdfde 100644
--- a/Lib/test/test_types.py
+++ b/Lib/test/test_types.py
@@ -233,7 +233,6 @@ print 'Buffers'
try: buffer('asdf', -1)
except ValueError: pass
else: raise TestFailed, "buffer('asdf', -1) should raise ValueError"
-cmp(buffer("abc"), buffer("def")) # used to raise a warning: tp_compare didn't return -1, 0, or 1
try: buffer(None)
except TypeError: pass
diff --git a/Lib/test/test_userdict.py b/Lib/test/test_userdict.py
index ecb33d1..bc45bf3 100644
--- a/Lib/test/test_userdict.py
+++ b/Lib/test/test_userdict.py
@@ -52,7 +52,7 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol):
all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2]
for a in all:
for b in all:
- self.assertEqual(cmp(a, b), cmp(len(a), len(b)))
+ self.assertEqual(a == b, len(a) == len(b))
# Test __getitem__
self.assertEqual(u2["one"], 1)
diff --git a/Lib/test/test_weakref.py b/Lib/test/test_weakref.py
index a4fb7f3..f5114b2 100644
--- a/Lib/test/test_weakref.py
+++ b/Lib/test/test_weakref.py
@@ -701,6 +701,12 @@ class Object:
self.arg = arg
def __repr__(self):
return "<Object %r>" % self.arg
+ def __lt__(self, other):
+ if isinstance(other, Object):
+ return self.arg < other.arg
+ return NotImplemented
+ def __hash__(self):
+ return hash(self.arg)
class MappingTestCase(TestBase):