1 # Test enhancements related to descriptors and new-style classes
3 from test
.test_support
import verify
, vereq
, verbose
, TestFailed
, TESTFN
, get_original_stdout
4 from copy
import deepcopy
7 warnings
.filterwarnings("ignore",
8 r
'complex divmod\(\), // and % are deprecated$',
9 DeprecationWarning, r
'(<string>|%s)$' % __name__
)
13 raise TestFailed
, "%r is %r" % (a
, b
)
15 def testunop(a
, res
, expr
="len(a)", meth
="__len__"):
16 if verbose
: print "checking", expr
18 vereq(eval(expr
, dict), res
)
21 while meth
not in t
.__dict
__:
23 vereq(m
, t
.__dict
__[meth
])
28 def testbinop(a
, b
, res
, expr
="a+b", meth
="__add__"):
29 if verbose
: print "checking", expr
30 dict = {'a': a
, 'b': b
}
32 # XXX Hack so this passes before 2.3 when -Qnew is specified.
33 if meth
== "__div__" and 1/2 == 0.5:
36 vereq(eval(expr
, dict), res
)
39 while meth
not in t
.__dict
__:
41 vereq(m
, t
.__dict
__[meth
])
46 def testternop(a
, b
, c
, res
, expr
="a[b:c]", meth
="__getslice__"):
47 if verbose
: print "checking", expr
48 dict = {'a': a
, 'b': b
, 'c': c
}
49 vereq(eval(expr
, dict), res
)
52 while meth
not in t
.__dict
__:
54 vereq(m
, t
.__dict
__[meth
])
55 vereq(m(a
, b
, c
), res
)
59 def testsetop(a
, b
, res
, stmt
="a+=b", meth
="__iadd__"):
60 if verbose
: print "checking", stmt
61 dict = {'a': deepcopy(a
), 'b': b
}
66 while meth
not in t
.__dict
__:
68 vereq(m
, t
.__dict
__[meth
])
69 dict['a'] = deepcopy(a
)
72 dict['a'] = deepcopy(a
)
73 bm
= getattr(dict['a'], meth
)
77 def testset2op(a
, b
, c
, res
, stmt
="a[b]=c", meth
="__setitem__"):
78 if verbose
: print "checking", stmt
79 dict = {'a': deepcopy(a
), 'b': b
, 'c': c
}
84 while meth
not in t
.__dict
__:
86 vereq(m
, t
.__dict
__[meth
])
87 dict['a'] = deepcopy(a
)
90 dict['a'] = deepcopy(a
)
91 bm
= getattr(dict['a'], meth
)
95 def testset3op(a
, b
, c
, d
, res
, stmt
="a[b:c]=d", meth
="__setslice__"):
96 if verbose
: print "checking", stmt
97 dict = {'a': deepcopy(a
), 'b': b
, 'c': c
, 'd': d
}
101 while meth
not in t
.__dict
__:
104 vereq(m
, t
.__dict
__[meth
])
105 dict['a'] = deepcopy(a
)
106 m(dict['a'], b
, c
, d
)
107 vereq(dict['a'], res
)
108 dict['a'] = deepcopy(a
)
109 bm
= getattr(dict['a'], meth
)
111 vereq(dict['a'], res
)
113 def class_docstrings():
115 "A classic docstring."
116 vereq(Classic
.__doc
__, "A classic docstring.")
117 vereq(Classic
.__dict
__['__doc__'], "A classic docstring.")
121 verify(Classic2
.__doc__
is None)
123 class NewStatic(object):
125 vereq(NewStatic
.__doc
__, "Another docstring.")
126 vereq(NewStatic
.__dict
__['__doc__'], "Another docstring.")
128 class NewStatic2(object):
130 verify(NewStatic2
.__doc__
is None)
132 class NewDynamic(object):
134 vereq(NewDynamic
.__doc
__, "Another docstring.")
135 vereq(NewDynamic
.__dict
__['__doc__'], "Another docstring.")
137 class NewDynamic2(object):
139 verify(NewDynamic2
.__doc__
is None)
142 if verbose
: print "Testing list operations..."
143 testbinop([1], [2], [1,2], "a+b", "__add__")
144 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
145 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
146 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
147 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
148 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
149 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
150 testunop([1,2,3], 3, "len(a)", "__len__")
151 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
152 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
153 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
154 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
157 if verbose
: print "Testing dict operations..."
158 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
159 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
160 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
161 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
164 for i
in d
.keys(): l1
.append(i
)
166 for i
in iter(d
): l
.append(i
)
169 for i
in d
.__iter
__(): l
.append(i
)
172 for i
in dict.__iter
__(d
): l
.append(i
)
175 testunop(d
, 2, "len(a)", "__len__")
176 vereq(eval(repr(d
), {}), d
)
177 vereq(eval(d
.__repr
__(), {}), d
)
178 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
180 def dict_constructor():
182 print "Testing dict constructor ..."
187 d
= dict({1: 2, 'a': 'b'})
188 vereq(d
, {1: 2, 'a': 'b'})
189 vereq(d
, dict(d
.items()))
190 vereq(d
, dict(d
.iteritems()))
191 d
= dict({'one':1, 'two':2})
192 vereq(d
, dict(one
=1, two
=2))
194 vereq(d
, dict({"one": 1}, two
=2))
195 vereq(d
, dict([("two", 2)], one
=1))
196 vereq(d
, dict([("one", 100), ("two", 200)], **d
))
197 verify(d
is not dict(**d
))
198 for badarg
in 0, 0L, 0j
, "0", [0], (0,):
205 # It's a sequence, and its elements are also sequences (gotta
206 # love strings <wink>), but they aren't of length 2, so this
207 # one seemed better as a ValueError than a TypeError.
210 raise TestFailed("no TypeError from dict(%r)" % badarg
)
212 raise TestFailed("no TypeError from dict(%r)" % badarg
)
219 raise TestFailed("no TypeError from dict({}, {})")
222 # Lacks a .keys() method; will be added later.
223 dict = {1:2, 3:4, 'a':1j
}
230 raise TestFailed("no TypeError from dict(incomplete mapping)")
232 Mapping
.keys
= lambda self
: self
.dict.keys()
233 Mapping
.__getitem
__ = lambda self
, i
: self
.dict[i
]
235 vereq(d
, Mapping
.dict)
237 # Init from sequence of iterable objects, each producing a 2-sequence.
238 class AddressBookEntry
:
239 def __init__(self
, first
, last
):
243 return iter([self
.first
, self
.last
])
245 d
= dict([AddressBookEntry('Tim', 'Warsaw'),
246 AddressBookEntry('Barry', 'Peters'),
247 AddressBookEntry('Tim', 'Peters'),
248 AddressBookEntry('Barry', 'Warsaw')])
249 vereq(d
, {'Barry': 'Warsaw', 'Tim': 'Peters'})
251 d
= dict(zip(range(4), range(1, 5)))
252 vereq(d
, dict([(i
, i
+1) for i
in range(4)]))
254 # Bad sequence lengths.
255 for bad
in [('tooshort',)], [('too', 'long', 'by 1')]:
261 raise TestFailed("no ValueError from dict(%r)" % bad
)
265 print "Testing dir() ..."
267 vereq(dir(), ['junk'])
270 # Just make sure these don't blow up!
271 for arg
in 2, 2L, 2j
, 2e0
, [2], "2", u
"2", (2,), {2:2}, type, test_dir
:
274 # Try classic classes.
277 def Cmethod(self
): pass
279 cstuff
= ['Cdata', 'Cmethod', '__doc__', '__module__']
280 vereq(dir(C
), cstuff
)
281 verify('im_self' in dir(C
.Cmethod
))
283 c
= C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
284 vereq(dir(c
), cstuff
)
287 c
.cmethod
= lambda self
: 0
288 vereq(dir(c
), cstuff
+ ['cdata', 'cmethod'])
289 verify('im_self' in dir(c
.Cmethod
))
293 def Amethod(self
): pass
295 astuff
= ['Adata', 'Amethod'] + cstuff
296 vereq(dir(A
), astuff
)
297 verify('im_self' in dir(A
.Amethod
))
299 vereq(dir(a
), astuff
)
300 verify('im_self' in dir(a
.Amethod
))
302 a
.amethod
= lambda self
: 3
303 vereq(dir(a
), astuff
+ ['adata', 'amethod'])
305 # The same, but with new-style classes. Since these have object as a
306 # base class, a lot more gets sucked in.
307 def interesting(strings
):
308 return [s
for s
in strings
if not s
.startswith('_')]
312 def Cmethod(self
): pass
314 cstuff
= ['Cdata', 'Cmethod']
315 vereq(interesting(dir(C
)), cstuff
)
318 vereq(interesting(dir(c
)), cstuff
)
319 verify('im_self' in dir(C
.Cmethod
))
322 c
.cmethod
= lambda self
: 0
323 vereq(interesting(dir(c
)), cstuff
+ ['cdata', 'cmethod'])
324 verify('im_self' in dir(c
.Cmethod
))
328 def Amethod(self
): pass
330 astuff
= ['Adata', 'Amethod'] + cstuff
331 vereq(interesting(dir(A
)), astuff
)
332 verify('im_self' in dir(A
.Amethod
))
334 vereq(interesting(dir(a
)), astuff
)
336 a
.amethod
= lambda self
: 3
337 vereq(interesting(dir(a
)), astuff
+ ['adata', 'amethod'])
338 verify('im_self' in dir(a
.Amethod
))
340 # Try a module subclass.
347 names
= [x
for x
in dir(minstance
) if x
not in ["__name__", "__doc__"]]
348 vereq(names
, ['a', 'b'])
353 __dict__
= property(getdict
)
355 m2instance
= M2("m2")
358 vereq(m2instance
.__dict
__, "Not a dict!")
364 # Two essentially featureless objects, just inheriting stuff from
366 vereq(dir(None), dir(Ellipsis))
368 # Nasty test case for proxied objects
369 class Wrapper(object):
370 def __init__(self
, obj
):
373 return "Wrapper(%s)" % repr(self
.__obj
)
374 def __getitem__(self
, key
):
375 return Wrapper(self
.__obj
[key
])
377 return len(self
.__obj
)
378 def __getattr__(self
, name
):
379 return Wrapper(getattr(self
.__obj
, name
))
382 def __getclass(self
):
383 return Wrapper(type(self
))
384 __class__
= property(__getclass
)
386 dir(C()) # This used to segfault
410 for name
, expr
in binops
.items():
412 expr
= expr
+ "(a, b)"
414 expr
= 'a %s b' % expr
429 for name
, expr
in unops
.items():
436 def numops(a
, b
, skip
=[]):
437 dict = {'a': a
, 'b': b
}
438 for name
, expr
in binops
.items():
440 name
= "__%s__" % name
442 res
= eval(expr
, dict)
443 testbinop(a
, b
, res
, expr
, name
)
444 for name
, expr
in unops
.items():
446 name
= "__%s__" % name
448 res
= eval(expr
, dict)
449 testunop(a
, res
, expr
, name
)
452 if verbose
: print "Testing int operations..."
454 # The following crashes in Python 2.2
455 vereq((1).__nonzero
__(), 1)
456 vereq((0).__nonzero
__(), 0)
457 # This returns 'NotImplemented' in Python 2.2
459 def __add__(self
, other
):
460 return NotImplemented
467 raise TestFailed
, "NotImplemented should have caused TypeError"
471 except OverflowError:
474 raise TestFailed
, "should have raised OverflowError"
477 if verbose
: print "Testing long operations..."
481 if verbose
: print "Testing float operations..."
485 if verbose
: print "Testing complex operations..."
486 numops(100.0j
, 3.0j
, skip
=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
487 class Number(complex):
489 def __new__(cls
, *args
, **kwds
):
490 result
= complex.__new
__(cls
, *args
)
491 result
.prec
= kwds
.get('prec', 12)
496 return "%.*g" % (prec
, self
.real
)
498 return "%.*gj" % (prec
, self
.imag
)
499 return "(%.*g+%.*gj)" % (prec
, self
.real
, prec
, self
.imag
)
502 a
= Number(3.14, prec
=6)
506 a
= Number(a
, prec
=2)
515 if verbose
: print "Testing spamlist operations..."
516 import copy
, xxsubtype
as spam
517 def spamlist(l
, memo
=None):
518 import xxsubtype
as spam
519 return spam
.spamlist(l
)
520 # This is an ugly hack:
521 copy
._deepcopy
_dispatch
[spam
.spamlist
] = spamlist
523 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
524 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
525 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
526 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
527 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
528 "a[b:c]", "__getslice__")
529 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
531 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
532 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
533 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
534 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
535 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
536 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
537 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
539 class C(spam
.spamlist
):
540 def foo(self
): return 1
546 vereq(a
.getstate(), 0)
548 vereq(a
.getstate(), 42)
551 if verbose
: print "Testing spamdict operations..."
552 import copy
, xxsubtype
as spam
553 def spamdict(d
, memo
=None):
554 import xxsubtype
as spam
556 for k
, v
in d
.items(): sd
[k
] = v
558 # This is an ugly hack:
559 copy
._deepcopy
_dispatch
[spam
.spamdict
] = spamdict
561 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
562 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
563 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
564 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
565 d
= spamdict({1:2,3:4})
567 for i
in d
.keys(): l1
.append(i
)
569 for i
in iter(d
): l
.append(i
)
572 for i
in d
.__iter
__(): l
.append(i
)
575 for i
in type(spamdict({})).__iter
__(d
): l
.append(i
)
577 straightd
= {1:2, 3:4}
578 spamd
= spamdict(straightd
)
579 testunop(spamd
, 2, "len(a)", "__len__")
580 testunop(spamd
, repr(straightd
), "repr(a)", "__repr__")
581 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
582 "a[b]=c", "__setitem__")
584 class C(spam
.spamdict
):
585 def foo(self
): return 1
590 vereq(a
.items(), [('foo', 'bar')])
591 vereq(a
.getstate(), 0)
593 vereq(a
.getstate(), 100)
596 if verbose
: print "Testing Python subclass of dict..."
597 verify(issubclass(dict, dict))
598 verify(isinstance({}, dict))
601 verify(d
.__class
__ is dict)
602 verify(isinstance(d
, dict))
605 def __init__(self
, *a
, **kw
):
610 for k
, v
in kw
.items(): self
[v
] = k
611 def __getitem__(self
, key
):
612 return self
.get(key
, 0)
613 def __setitem__(self
, key
, value
):
614 verify(isinstance(key
, type(0)))
615 dict.__setitem
__(self
, key
, value
)
616 def setstate(self
, state
):
620 verify(issubclass(C
, dict))
624 vereq(a2
[1] == 'foo' and a2
[2], 'bar')
627 vereq(a
.getstate(), -1)
630 vereq(a
.getstate(), 0)
633 vereq(a
.getstate(), 10)
637 if verbose
: print "pydict stress test ..."
648 if verbose
: print "Testing Python subclass of list..."
650 def __getitem__(self
, i
):
651 return list.__getitem
__(self
, i
) + 100
652 def __getslice__(self
, i
, j
):
659 vereq(a
[100:200], (100,200))
662 if verbose
: print "Testing __metaclass__..."
669 def setstate(self
, state
):
672 vereq(a
.getstate(), 0)
674 vereq(a
.getstate(), 10)
676 class __metaclass__(type):
677 def myself(cls
): return cls
680 verify(d
.__class
__ is D
)
682 def __new__(cls
, name
, bases
, dict):
684 return type.__new
__(cls
, name
, bases
, dict)
691 class _instance(object):
694 def __new__(cls
, name
, bases
, dict):
695 self
= object.__new
__(cls
)
700 __new__
= staticmethod(__new__
)
703 # Early binding of methods
704 for key
in self
.dict:
705 if key
.startswith("__"):
707 setattr(it
, key
, self
.dict[key
].__get
__(it
, self
))
715 verify('spam' in C
.dict)
719 # More metaclass examples
721 class autosuper(type):
722 # Automatically add __super to the class
723 # This trick only works for dynamic classes
724 def __new__(metaclass
, name
, bases
, dict):
725 cls
= super(autosuper
, metaclass
).__new
__(metaclass
,
727 # Name mangling for __super removes leading underscores
728 while name
[:1] == "_":
731 name
= "_%s__super" % name
734 setattr(cls
, name
, super(cls
))
737 __metaclass__
= autosuper
742 return "B" + self
.__super
.meth()
745 return "C" + self
.__super
.meth()
748 return "D" + self
.__super
.meth()
749 vereq(D().meth(), "DCBA")
752 return "E" + self
.__super
.meth()
753 vereq(E().meth(), "EBCA")
755 class autoproperty(type):
756 # Automatically create property attributes when methods
757 # named _get_x and/or _set_x are found
758 def __new__(metaclass
, name
, bases
, dict):
760 for key
, val
in dict.iteritems():
761 if key
.startswith("_get_"):
763 get
, set = hits
.get(key
, (None, None))
766 elif key
.startswith("_set_"):
768 get
, set = hits
.get(key
, (None, None))
771 for key
, (get
, set) in hits
.iteritems():
772 dict[key
] = property(get
, set)
773 return super(autoproperty
, metaclass
).__new
__(metaclass
,
776 __metaclass__
= autoproperty
782 verify(not hasattr(a
, "x"))
787 class multimetaclass(autoproperty
, autosuper
):
788 # Merge of multiple cooperating metaclasses
791 __metaclass__
= multimetaclass
796 return "B" + self
.__super
._get
_x
()
799 return "C" + self
.__super
._get
_x
()
802 return "D" + self
.__super
._get
_x
()
805 # Make sure type(x) doesn't call x.__class__.__init__
808 def __init__(self
, *args
):
817 class C(object): pass
820 except TypeError: pass
821 else: raise TestFailed
, "calling object w/o call method should raise TypeError"
824 if verbose
: print "Testing Python subclass of module..."
829 def __init__(self
, name
):
830 MT
.__init
__(self
, name
)
831 def __getattribute__(self
, name
):
832 log
.append(("getattr", name
))
833 return MT
.__getattribute
__(self
, name
)
834 def __setattr__(self
, name
, value
):
835 log
.append(("setattr", name
, value
))
836 MT
.__setattr
__(self
, name
, value
)
837 def __delattr__(self
, name
):
838 log
.append(("delattr", name
))
839 MT
.__delattr
__(self
, name
)
844 vereq(log
, [("setattr", "foo", 12),
849 if verbose
: print "Testing multiple inheritance..."
855 def setstate(self
, state
):
858 vereq(a
.getstate(), 0)
860 vereq(a
.getstate(), 10)
863 type({}).__init
__(self
)
868 vereq(d
.items(), [("hello", "world")])
869 vereq(d
["hello"], "world")
870 vereq(d
.getstate(), 0)
872 vereq(d
.getstate(), 10)
873 vereq(D
.__mro
__, (D
, dict, C
, object))
878 return int(self
.foo())
881 class Frag(Node
, list):
884 vereq(Node().__int
__(), 23)
885 vereq(int(Node()), 23)
886 vereq(Frag().__int
__(), 42)
887 vereq(int(Frag()), 42)
889 # MI mixing classic and new-style classes.
904 # Classic MRO is preserved for a classic base class.
907 vereq(E
.__mro
__, (E
, D
, B
, A
, C
, object))
910 # But with a mix of classic bases, their MROs are combined using
912 class F(B
, C
, object):
914 vereq(F
.__mro
__, (F
, B
, C
, A
, object))
917 # Try something else.
921 def all_method(self
):
927 def all_method(self
):
930 vereq(M1
.__mro__
, (M1
, C
, object))
932 vereq(m
.cmethod(), "C a")
933 vereq(m
.m1method(), "M1 a")
934 vereq(m
.all_method(), "M1 b")
939 def all_method(self
):
945 def all_method(self
):
948 vereq(M2
.__mro__
, (M2
, D
, C
, object))
950 vereq(m
.cmethod(), "C a")
951 vereq(m
.dmethod(), "D a")
952 vereq(m
.m2method(), "M2 a")
953 vereq(m
.all_method(), "M2 b")
955 class M3(M1
, M2
, object):
958 def all_method(self
):
960 vereq(M3
.__mro__
, (M3
, M1
, M2
, D
, C
, object))
962 vereq(m
.cmethod(), "C a")
963 vereq(m
.dmethod(), "D a")
964 vereq(m
.m1method(), "M1 a")
965 vereq(m
.m2method(), "M2 a")
966 vereq(m
.m3method(), "M3 a")
967 vereq(m
.all_method(), "M3 b")
977 raise TestFailed
, "new class with only classic bases - shouldn't be"
980 if verbose
: print "Testing multiple inheritance special cases..."
982 def spam(self
): return "A"
983 vereq(A().spam(), "A")
985 def boo(self
): return "B"
986 def spam(self
): return "B"
987 vereq(B().spam(), "B")
988 vereq(B().boo(), "B")
990 def boo(self
): return "C"
991 vereq(C().spam(), "A")
992 vereq(C().boo(), "C")
994 vereq(D().spam(), "B")
995 vereq(D().boo(), "B")
996 vereq(D
.__mro
__, (D
, B
, C
, A
, object))
998 vereq(E().spam(), "B")
999 vereq(E().boo(), "C")
1000 vereq(E
.__mro
__, (E
, C
, B
, A
, object))
1001 # MRO order disagreement
1007 raise TestFailed
, "expected MRO order disagreement (F)"
1013 raise TestFailed
, "expected MRO order disagreement (G)"
1016 # see thread python-dev/2002-October/029035.html
1018 if verbose
: print "Testing ex5 from C3 switch discussion..."
1019 class A(object): pass
1020 class B(object): pass
1021 class C(object): pass
1024 class Z(X
,B
,Y
,C
): pass
1025 vereq(Z
.__mro
__, (Z
, X
, B
, Y
, A
, C
, object))
1027 # see "A Monotonic Superclass Linearization for Dylan",
1028 # by Kim Barrett et al. (OOPSLA 1996)
1030 if verbose
: print "Testing MRO monotonicity..."
1031 class Boat(object): pass
1032 class DayBoat(Boat
): pass
1033 class WheelBoat(Boat
): pass
1034 class EngineLess(DayBoat
): pass
1035 class SmallMultihull(DayBoat
): pass
1036 class PedalWheelBoat(EngineLess
,WheelBoat
): pass
1037 class SmallCatamaran(SmallMultihull
): pass
1038 class Pedalo(PedalWheelBoat
,SmallCatamaran
): pass
1040 vereq(PedalWheelBoat
.__mro
__,
1041 (PedalWheelBoat
, EngineLess
, DayBoat
, WheelBoat
, Boat
,
1043 vereq(SmallCatamaran
.__mro
__,
1044 (SmallCatamaran
, SmallMultihull
, DayBoat
, Boat
, object))
1046 vereq(Pedalo
.__mro
__,
1047 (Pedalo
, PedalWheelBoat
, EngineLess
, SmallCatamaran
,
1048 SmallMultihull
, DayBoat
, WheelBoat
, Boat
, object))
1050 # see "A Monotonic Superclass Linearization for Dylan",
1051 # by Kim Barrett et al. (OOPSLA 1996)
1052 def consistency_with_epg():
1053 if verbose
: print "Testing consistentcy with EPG..."
1054 class Pane(object): pass
1055 class ScrollingMixin(object): pass
1056 class EditingMixin(object): pass
1057 class ScrollablePane(Pane
,ScrollingMixin
): pass
1058 class EditablePane(Pane
,EditingMixin
): pass
1059 class EditableScrollablePane(ScrollablePane
,EditablePane
): pass
1061 vereq(EditableScrollablePane
.__mro
__,
1062 (EditableScrollablePane
, ScrollablePane
, EditablePane
,
1063 Pane
, ScrollingMixin
, EditingMixin
, object))
1065 mro_err_msg
= """Cannot create a consistent method resolution
1066 order (MRO) for bases """
1068 def mro_disagreement():
1069 if verbose
: print "Testing error messages for MRO disagreement..."
1070 def raises(exc
, expected
, callable, *args
):
1074 if not str(msg
).startswith(expected
):
1075 raise TestFailed
, "Message %r, expected %r" % (str(msg
),
1078 raise TestFailed
, "Expected %s" % exc
1079 class A(object): pass
1081 class C(object): pass
1082 # Test some very simple errors
1083 raises(TypeError, "duplicate base class A",
1084 type, "X", (A
, A
), {})
1085 raises(TypeError, mro_err_msg
,
1086 type, "X", (A
, B
), {})
1087 raises(TypeError, mro_err_msg
,
1088 type, "X", (A
, C
, B
), {})
1089 # Test a slightly more complex error
1090 class GridLayout(object): pass
1091 class HorizontalGrid(GridLayout
): pass
1092 class VerticalGrid(GridLayout
): pass
1093 class HVGrid(HorizontalGrid
, VerticalGrid
): pass
1094 class VHGrid(VerticalGrid
, HorizontalGrid
): pass
1095 raises(TypeError, mro_err_msg
,
1096 type, "ConfusedGrid", (HVGrid
, VHGrid
), {})
1099 if verbose
: print "Testing object class..."
1101 vereq(a
.__class
__, object)
1102 vereq(type(a
), object)
1105 verify(not hasattr(a
, "foo"))
1108 except (AttributeError, TypeError):
1111 verify(0, "object() should not allow setting a foo attribute")
1112 verify(not hasattr(object(), "__dict__"))
1114 class Cdict(object):
1117 vereq(x
.__dict
__, {})
1120 vereq(x
.__dict
__, {'foo': 1})
1123 if verbose
: print "Testing __slots__..."
1127 verify(not hasattr(x
, "__dict__"))
1128 verify(not hasattr(x
, "foo"))
1133 verify(not hasattr(x
, "__dict__"))
1134 verify(not hasattr(x
, "a"))
1140 verify(not hasattr(x
, "a"))
1143 __slots__
= ['a', 'b', 'c']
1145 verify(not hasattr(x
, "__dict__"))
1146 verify(not hasattr(x
, 'a'))
1147 verify(not hasattr(x
, 'b'))
1148 verify(not hasattr(x
, 'c'))
1157 """Validate name mangling"""
1159 def __init__(self
, value
):
1164 verify(not hasattr(x
, '__dict__'))
1165 verify(not hasattr(x
, '__a'))
1169 except AttributeError:
1172 raise TestFailed
, "Double underscored names not mangled"
1174 # Make sure slot names are proper identifiers
1181 raise TestFailed
, "[None] slots not caught"
1184 __slots__
= ["foo bar"]
1188 raise TestFailed
, "['foo bar'] slots not caught"
1191 __slots__
= ["foo\0bar"]
1195 raise TestFailed
, "['foo\\0bar'] slots not caught"
1202 raise TestFailed
, "['1'] slots not caught"
1209 raise TestFailed
, "[''] slots not caught"
1211 __slots__
= ["a", "a_b", "_a", "A0123456789Z"]
1214 class Counted(object):
1215 counter
= 0 # counts the number of instances alive
1217 Counted
.counter
+= 1
1219 Counted
.counter
-= 1
1221 __slots__
= ['a', 'b', 'c']
1226 vereq(Counted
.counter
, 3)
1228 vereq(Counted
.counter
, 0)
1234 vereq(Counted
.counter
, 2)
1236 vereq(Counted
.counter
, 0)
1243 vereq(Counted
.counter
, 3)
1245 vereq(Counted
.counter
, 0)
1247 # Test cyclical leaks [SF bug 519621]
1249 __slots__
= ['a', 'b']
1252 s
.a
= [Counted(), s
]
1253 vereq(Counted
.counter
, 1)
1257 vereq(Counted
.counter
, 0)
1259 # Test lookup leaks [SF bug 572567]
1262 def __cmp__(self
, other
):
1265 orig_objects
= len(gc
.get_objects())
1266 for i
in xrange(10):
1268 new_objects
= len(gc
.get_objects())
1269 vereq(orig_objects
, new_objects
)
1271 __slots__
= ['a', 'b']
1279 save_stderr
= sys
.stderr
1280 sys
.stderr
= sys
.stdout
1285 sys
.stderr
= save_stderr
1288 if verbose
: print "Testing __dict__ and __weakref__ in __slots__..."
1291 __slots__
= ["__dict__"]
1293 verify(hasattr(a
, "__dict__"))
1294 verify(not hasattr(a
, "__weakref__"))
1296 vereq(a
.__dict
__, {"foo": 42})
1299 __slots__
= ["__weakref__"]
1301 verify(hasattr(a
, "__weakref__"))
1302 verify(not hasattr(a
, "__dict__"))
1305 except AttributeError:
1308 raise TestFailed
, "shouldn't be allowed to set a.foo"
1313 verify(hasattr(a
, "__dict__"))
1314 verify(hasattr(a
, "__weakref__"))
1316 vereq(a
.__dict
__, {"foo": 42})
1321 verify(hasattr(a
, "__dict__"))
1322 verify(hasattr(a
, "__weakref__"))
1324 vereq(a
.__dict
__, {"foo": 42})
1326 # MRO order disagreement
1335 if verbose
: print "Testing class attribute propagation..."
1344 # Test that dynamic attributes are inherited
1347 # Test dynamic instances
1351 verify(not hasattr(a
, "foobar"))
1354 C
.method
= lambda self
: 42
1355 vereq(a
.method(), 42)
1356 C
.__repr
__ = lambda self
: "C()"
1357 vereq(repr(a
), "C()")
1358 C
.__int
__ = lambda self
: 100
1361 verify(not hasattr(a
, "spam"))
1362 def mygetattr(self
, name
):
1365 raise AttributeError
1366 C
.__getattr
__ = mygetattr
1367 vereq(a
.spam
, "spam")
1370 def mysetattr(self
, name
, value
):
1372 raise AttributeError
1373 return object.__setattr
__(self
, name
, value
)
1374 C
.__setattr
__ = mysetattr
1377 except AttributeError:
1380 verify(0, "expected AttributeError")
1381 vereq(a
.spam
, "spam")
1388 # Test handling of int*seq and seq*int
1391 vereq("a"*I(2), "aa")
1392 vereq(I(2)*"a", "aa")
1397 # Test handling of long*seq and seq*long
1400 vereq("a"*L(2L), "aa")
1401 vereq(L(2L)*"a", "aa")
1406 # Test comparison of classes with dynamic metaclasses
1407 class dynamicmetaclass(type):
1410 __metaclass__
= dynamicmetaclass
1411 verify(someclass
!= object)
1414 if verbose
: print "Testing errors..."
1417 class C(list, dict):
1422 verify(0, "inheritance from both list and dict should be illegal")
1425 class C(object, None):
1430 verify(0, "inheritance from non-type should be illegal")
1440 verify(0, "inheritance from CFunction should be illegal")
1448 verify(0, "__slots__ = 1 should be illegal")
1456 verify(0, "__slots__ = [1] should be illegal")
1459 if verbose
: print "Testing class methods..."
1461 def foo(*a
): return a
1462 goo
= classmethod(foo
)
1464 vereq(C
.goo(1), (C
, 1))
1465 vereq(c
.goo(1), (C
, 1))
1466 vereq(c
.foo(1), (c
, 1))
1470 vereq(D
.goo(1), (D
, 1))
1471 vereq(d
.goo(1), (D
, 1))
1472 vereq(d
.foo(1), (d
, 1))
1473 vereq(D
.foo(d
, 1), (d
, 1))
1474 # Test for a specific crash (SF bug 528132)
1475 def f(cls
, arg
): return (cls
, arg
)
1477 vereq(ff
.__get
__(0, int)(42), (int, 42))
1478 vereq(ff
.__get
__(0)(42), (int, 42))
1480 # Test super() with classmethods (SF bug 535444)
1481 veris(C
.goo
.im_self
, C
)
1482 veris(D
.goo
.im_self
, D
)
1483 veris(super(D
,D
).goo
.im_self
, D
)
1484 veris(super(D
,d
).goo
.im_self
, D
)
1485 vereq(super(D
,D
).goo(), (D
,))
1486 vereq(super(D
,d
).goo(), (D
,))
1488 # Verify that argument is checked for callability (SF bug 753451)
1490 classmethod(1).__get
__(1)
1494 raise TestFailed
, "classmethod should check for callability"
1496 def classmethods_in_c():
1497 if verbose
: print "Testing C-based class methods..."
1498 import xxsubtype
as spam
1501 x
, a1
, d1
= spam
.spamlist
.classmeth(*a
, **d
)
1502 veris(x
, spam
.spamlist
)
1505 x
, a1
, d1
= spam
.spamlist().classmeth(*a
, **d
)
1506 veris(x
, spam
.spamlist
)
1510 def staticmethods():
1511 if verbose
: print "Testing static methods..."
1513 def foo(*a
): return a
1514 goo
= staticmethod(foo
)
1516 vereq(C
.goo(1), (1,))
1517 vereq(c
.goo(1), (1,))
1518 vereq(c
.foo(1), (c
, 1,))
1522 vereq(D
.goo(1), (1,))
1523 vereq(d
.goo(1), (1,))
1524 vereq(d
.foo(1), (d
, 1))
1525 vereq(D
.foo(d
, 1), (d
, 1))
1527 def staticmethods_in_c():
1528 if verbose
: print "Testing C-based static methods..."
1529 import xxsubtype
as spam
1532 x
, a1
, d1
= spam
.spamlist
.staticmeth(*a
, **d
)
1536 x
, a1
, d2
= spam
.spamlist().staticmeth(*a
, **d
)
1542 if verbose
: print "Testing classic classes..."
1544 def foo(*a
): return a
1545 goo
= classmethod(foo
)
1547 vereq(C
.goo(1), (C
, 1))
1548 vereq(c
.goo(1), (C
, 1))
1549 vereq(c
.foo(1), (c
, 1))
1553 vereq(D
.goo(1), (D
, 1))
1554 vereq(d
.goo(1), (D
, 1))
1555 vereq(d
.foo(1), (d
, 1))
1556 vereq(D
.foo(d
, 1), (d
, 1))
1557 class E
: # *not* subclassing from C
1559 vereq(E().foo
, C
.foo
) # i.e., unbound
1560 verify(repr(C
.foo
.__get
__(C())).startswith("<bound method "))
1563 if verbose
: print "Testing computed attributes..."
1565 class computed_attribute(object):
1566 def __init__(self
, get
, set=None, delete
=None):
1569 self
.__delete
= delete
1570 def __get__(self
, obj
, type=None):
1571 return self
.__get
(obj
)
1572 def __set__(self
, obj
, value
):
1573 return self
.__set
(obj
, value
)
1574 def __delete__(self
, obj
):
1575 return self
.__delete
(obj
)
1582 def __set_x(self
, x
):
1584 def __delete_x(self
):
1586 x
= computed_attribute(__get_x
, __set_x
, __delete_x
)
1594 vereq(hasattr(a
, 'x'), 0)
1597 if verbose
: print "Testing __new__ slot override..."
1600 self
= list.__new
__(cls
)
1604 self
.foo
= self
.foo
+ 2
1607 verify(a
.__class
__ is C
)
1612 verify(b
.__class
__ is D
)
1615 if verbose
: print "Testing mro() and overriding it..."
1617 def f(self
): return "A"
1621 def f(self
): return "C"
1624 vereq(D
.mro(), [D
, B
, C
, A
, object])
1625 vereq(D
.__mro
__, (D
, B
, C
, A
, object))
1628 class PerverseMetaType(type):
1634 __metaclass__
= PerverseMetaType
1635 vereq(X
.__mro
__, (object, A
, C
, B
, D
, X
))
1639 if verbose
: print "Testing operator overloading..."
1642 "Intermediate class because object doesn't have a __setattr__"
1646 def __getattr__(self
, name
):
1648 return ("getattr", name
)
1650 raise AttributeError
1651 def __setattr__(self
, name
, value
):
1653 self
.setattr = (name
, value
)
1655 return B
.__setattr
__(self
, name
, value
)
1656 def __delattr__(self
, name
):
1660 return B
.__delattr
__(self
, name
)
1662 def __getitem__(self
, key
):
1663 return ("getitem", key
)
1664 def __setitem__(self
, key
, value
):
1665 self
.setitem
= (key
, value
)
1666 def __delitem__(self
, key
):
1669 def __getslice__(self
, i
, j
):
1670 return ("getslice", i
, j
)
1671 def __setslice__(self
, i
, j
, value
):
1672 self
.setslice
= (i
, j
, value
)
1673 def __delslice__(self
, i
, j
):
1674 self
.delslice
= (i
, j
)
1677 vereq(a
.foo
, ("getattr", "foo"))
1679 vereq(a
.setattr, ("foo", 12))
1681 vereq(a
.delattr, "foo")
1683 vereq(a
[12], ("getitem", 12))
1685 vereq(a
.setitem
, (12, 21))
1687 vereq(a
.delitem
, 12)
1689 vereq(a
[0:10], ("getslice", 0, 10))
1691 vereq(a
.setslice
, (0, 10, "foo"))
1693 vereq(a
.delslice
, (0, 10))
1696 if verbose
: print "Testing methods..."
1698 def __init__(self
, x
):
1713 vereq(E().foo
, C
.foo
) # i.e., unbound
1714 verify(repr(C
.foo
.__get
__(C(1))).startswith("<bound method "))
1717 # Test operators like __hash__ for which a built-in default exists
1718 if verbose
: print "Testing special operators..."
1719 # Test the default behavior for static classes
1721 def __getitem__(self
, i
):
1722 if 0 <= i
< 10: return i
1727 vereq(hash(c1
), id(c1
))
1728 vereq(cmp(c1
, c2
), cmp(id(c1
), id(c2
)))
1731 verify(not c1
!= c1
)
1732 verify(not c1
== c2
)
1733 # Note that the module name appears in str/repr, and that varies
1734 # depending on whether this test is run standalone or from a framework.
1735 verify(str(c1
).find('C object at ') >= 0)
1736 vereq(str(c1
), repr(c1
))
1737 verify(-1 not in c1
)
1740 verify(10 not in c1
)
1741 # Test the default behavior for dynamic classes
1743 def __getitem__(self
, i
):
1744 if 0 <= i
< 10: return i
1749 vereq(hash(d1
), id(d1
))
1750 vereq(cmp(d1
, d2
), cmp(id(d1
), id(d2
)))
1753 verify(not d1
!= d1
)
1754 verify(not d1
== d2
)
1755 # Note that the module name appears in str/repr, and that varies
1756 # depending on whether this test is run standalone or from a framework.
1757 verify(str(d1
).find('D object at ') >= 0)
1758 vereq(str(d1
), repr(d1
))
1759 verify(-1 not in d1
)
1762 verify(10 not in d1
)
1763 # Test overridden behavior for static classes
1764 class Proxy(object):
1765 def __init__(self
, x
):
1767 def __nonzero__(self
):
1768 return not not self
.x
1771 def __eq__(self
, other
):
1772 return self
.x
== other
1773 def __ne__(self
, other
):
1774 return self
.x
!= other
1775 def __cmp__(self
, other
):
1776 return cmp(self
.x
, other
.x
)
1778 return "Proxy:%s" % self
.x
1780 return "Proxy(%r)" % self
.x
1781 def __contains__(self
, value
):
1782 return value
in self
.x
1788 vereq(hash(p0
), hash(0))
1791 verify(not p0
!= p0
)
1793 vereq(cmp(p0
, p1
), -1)
1794 vereq(cmp(p0
, p0
), 0)
1795 vereq(cmp(p0
, p_1
), 1)
1796 vereq(str(p0
), "Proxy:0")
1797 vereq(repr(p0
), "Proxy(0)")
1798 p10
= Proxy(range(10))
1799 verify(-1 not in p10
)
1802 verify(10 not in p10
)
1803 # Test overridden behavior for dynamic classes
1804 class DProxy(object):
1805 def __init__(self
, x
):
1807 def __nonzero__(self
):
1808 return not not self
.x
1811 def __eq__(self
, other
):
1812 return self
.x
== other
1813 def __ne__(self
, other
):
1814 return self
.x
!= other
1815 def __cmp__(self
, other
):
1816 return cmp(self
.x
, other
.x
)
1818 return "DProxy:%s" % self
.x
1820 return "DProxy(%r)" % self
.x
1821 def __contains__(self
, value
):
1822 return value
in self
.x
1828 vereq(hash(p0
), hash(0))
1831 verify(not p0
!= p0
)
1833 vereq(cmp(p0
, p1
), -1)
1834 vereq(cmp(p0
, p0
), 0)
1835 vereq(cmp(p0
, p_1
), 1)
1836 vereq(str(p0
), "DProxy:0")
1837 vereq(repr(p0
), "DProxy(0)")
1838 p10
= DProxy(range(10))
1839 verify(-1 not in p10
)
1842 verify(10 not in p10
)
1843 # Safety test for __cmp__
1844 def unsafecmp(a
, b
):
1846 a
.__class
__.__cmp
__(a
, b
)
1850 raise TestFailed
, "shouldn't allow %s.__cmp__(%r, %r)" % (
1852 unsafecmp(u
"123", "123")
1853 unsafecmp("123", u
"123")
1860 def __new__(cls
, letter
):
1862 return str.__new
__(cls
)
1863 return str.__new
__(cls
, letter
)
1869 # sys.stdout needs to be the original to trigger the recursion bug
1871 test_stdout
= sys
.stdout
1872 sys
.stdout
= get_original_stdout()
1874 # nothing should actually be printed, this should raise an exception
1876 except RuntimeError:
1879 raise TestFailed
, "expected a RuntimeError for print recursion"
1880 sys
.stdout
= test_stdout
1883 if verbose
: print "Testing weak references..."
1893 class NoWeak(object):
1898 except TypeError, msg
:
1899 verify(str(msg
).find("weak reference") >= 0)
1901 verify(0, "weakref.ref(no) should be illegal")
1903 __slots__
= ['foo', '__weakref__']
1905 r
= weakref
.ref(yes
)
1912 if verbose
: print "Testing property..."
1916 def setx(self
, value
):
1920 x
= property(getx
, setx
, delx
, doc
="I'm the x property.")
1922 verify(not hasattr(a
, "x"))
1927 verify(not hasattr(a
, "x"))
1928 verify(not hasattr(a
, "_C__x"))
1930 vereq(C
.x
.__get
__(a
), 100)
1932 verify(not hasattr(a
, "x"))
1934 raw
= C
.__dict
__['x']
1935 verify(isinstance(raw
, property))
1938 verify("__doc__" in attrs
)
1939 verify("fget" in attrs
)
1940 verify("fset" in attrs
)
1941 verify("fdel" in attrs
)
1943 vereq(raw
.__doc
__, "I'm the x property.")
1944 verify(raw
.fget
is C
.__dict
__['getx'])
1945 verify(raw
.fset
is C
.__dict
__['setx'])
1946 verify(raw
.fdel
is C
.__dict
__['delx'])
1948 for attr
in "__doc__", "fget", "fset", "fdel":
1950 setattr(raw
, attr
, 42)
1951 except TypeError, msg
:
1952 if str(msg
).find('readonly') < 0:
1953 raise TestFailed("when setting readonly attr %r on a "
1954 "property, got unexpected TypeError "
1955 "msg %r" % (attr
, str(msg
)))
1957 raise TestFailed("expected TypeError from trying to set "
1958 "readonly %r attr on a property" % attr
)
1961 __getitem__
= property(lambda s
: 1/0)
1967 except ZeroDivisionError:
1970 raise TestFailed
, "expected ZeroDivisionError from bad property"
1973 if verbose
: print "Testing super..."
1979 vereq(A().meth(1), "A(1)")
1983 self
.__super
= super(B
, self
)
1985 return "B(%r)" % a
+ self
.__super
.meth(a
)
1987 vereq(B().meth(2), "B(2)A(2)")
1991 return "C(%r)" % a
+ self
.__super
.meth(a
)
1992 C
._C
__super
= super(C
)
1994 vereq(C().meth(3), "C(3)A(3)")
1998 return "D(%r)" % a
+ super(D
, self
).meth(a
)
2000 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
2002 # Test for subclassing super
2004 class mysuper(super):
2005 def __init__(self
, *args
):
2006 return super(mysuper
, self
).__init
__(*args
)
2010 return "E(%r)" % a
+ mysuper(E
, self
).meth(a
)
2012 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2016 s
= self
.__super
# == mysuper(F, self)
2017 return "F(%r)[%s]" % (a
, s
.__class
__.__name
__) + s
.meth(a
)
2018 F
._F
__super
= mysuper(F
)
2020 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2022 # Make sure certain errors are raised
2029 raise TestFailed
, "shouldn't allow super(D, 42)"
2036 raise TestFailed
, "shouldn't allow super(D, C())"
2039 super(D
).__get
__(12)
2043 raise TestFailed
, "shouldn't allow super(D).__get__(12)"
2046 super(D
).__get
__(C())
2050 raise TestFailed
, "shouldn't allow super(D).__get__(C())"
2052 # Make sure data descriptors can be overridden and accessed via super
2053 # (new feature in Python 2.3)
2055 class DDbase(object):
2056 def getx(self
): return 42
2059 class DDsub(DDbase
):
2060 def getx(self
): return "hello"
2064 vereq(dd
.x
, "hello")
2065 vereq(super(DDsub
, dd
).x
, 42)
2068 if verbose
: print "Testing inheritance from basic types..."
2073 def __add__(self
, other
):
2074 return hexint(int.__add
__(self
, other
))
2075 # (Note that overriding __radd__ doesn't work,
2076 # because the int type gets first dibs.)
2077 vereq(repr(hexint(7) + 9), "0x10")
2078 vereq(repr(hexint(1000) + 7), "0x3ef")
2081 vereq(int(a
), 12345)
2082 verify(int(a
).__class
__ is int)
2083 vereq(hash(a
), hash(12345))
2084 verify((+a
).__class
__ is int)
2085 verify((a
>> 0).__class
__ is int)
2086 verify((a
<< 0).__class
__ is int)
2087 verify((hexint(0) << 12).__class
__ is int)
2088 verify((hexint(0) >> 12).__class
__ is int)
2090 class octlong(long):
2097 def __add__(self
, other
):
2098 return self
.__class
__(super(octlong
, self
).__add
__(other
))
2100 vereq(str(octlong(3) + 5), "010")
2101 # (Note that overriding __radd__ here only seems to work
2102 # because the example uses a short int left argument.)
2103 vereq(str(5 + octlong(3000)), "05675")
2106 vereq(long(a
), 12345L)
2107 vereq(hash(a
), hash(12345L))
2108 verify(long(a
).__class
__ is long)
2109 verify((+a
).__class
__ is long)
2110 verify((-a
).__class
__ is long)
2111 verify((-octlong(0)).__class
__ is long)
2112 verify((a
>> 0).__class
__ is long)
2113 verify((a
<< 0).__class
__ is long)
2114 verify((a
- 0).__class
__ is long)
2115 verify((a
* 1).__class
__ is long)
2116 verify((a
** 1).__class
__ is long)
2117 verify((a
// 1).__class
__ is long)
2118 verify((1 * a
).__class
__ is long)
2119 verify((a |
0).__class
__ is long)
2120 verify((a ^
0).__class
__ is long)
2121 verify((a
& -1L).__class
__ is long)
2122 verify((octlong(0) << 12).__class
__ is long)
2123 verify((octlong(0) >> 12).__class
__ is long)
2124 verify(abs(octlong(0)).__class
__ is long)
2126 # Because octlong overrides __add__, we can't check the absence of +0
2127 # optimizations using octlong.
2128 class longclone(long):
2131 verify((a
+ 0).__class
__ is long)
2132 verify((0 + a
).__class
__ is long)
2134 # Check that negative clones don't segfault
2136 vereq(a
.__dict
__, {})
2137 vereq(long(a
), -1) # verify PyNumber_Long() copies the sign bit
2139 class precfloat(float):
2140 __slots__
= ['prec']
2141 def __init__(self
, value
=0.0, prec
=12):
2142 self
.prec
= int(prec
)
2143 float.__init
__(value
)
2145 return "%.*g" % (self
.prec
, self
)
2146 vereq(repr(precfloat(1.1)), "1.1")
2147 a
= precfloat(12345)
2149 vereq(float(a
), 12345.0)
2150 verify(float(a
).__class
__ is float)
2151 vereq(hash(a
), hash(12345.0))
2152 verify((+a
).__class
__ is float)
2154 class madcomplex(complex):
2156 return "%.17gj%+.17g" % (self
.imag
, self
.real
)
2157 a
= madcomplex(-3, 4)
2158 vereq(repr(a
), "4j-3")
2159 base
= complex(-3, 4)
2160 veris(base
.__class
__, complex)
2162 vereq(complex(a
), base
)
2163 veris(complex(a
).__class
__, complex)
2164 a
= madcomplex(a
) # just trying another form of the constructor
2165 vereq(repr(a
), "4j-3")
2167 vereq(complex(a
), base
)
2168 veris(complex(a
).__class
__, complex)
2169 vereq(hash(a
), hash(base
))
2170 veris((+a
).__class
__, complex)
2171 veris((a
+ 0).__class
__, complex)
2173 veris((a
- 0).__class
__, complex)
2175 veris((a
* 1).__class
__, complex)
2177 veris((a
/ 1).__class
__, complex)
2180 class madtuple(tuple):
2183 if self
._rev
is not None:
2187 self
._rev
= self
.__class
__(L
)
2189 a
= madtuple((1,2,3,4,5,6,7,8,9,0))
2190 vereq(a
, (1,2,3,4,5,6,7,8,9,0))
2191 vereq(a
.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2192 vereq(a
.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2193 for i
in range(512):
2194 t
= madtuple(range(i
))
2198 a
= madtuple((1,2,3,4,5))
2199 vereq(tuple(a
), (1,2,3,4,5))
2200 verify(tuple(a
).__class
__ is tuple)
2201 vereq(hash(a
), hash((1,2,3,4,5)))
2202 verify(a
[:].__class
__ is tuple)
2203 verify((a
* 1).__class
__ is tuple)
2204 verify((a
* 0).__class
__ is tuple)
2205 verify((a
+ ()).__class
__ is tuple)
2208 verify(tuple(a
).__class
__ is tuple)
2209 verify((a
+ a
).__class
__ is tuple)
2210 verify((a
* 0).__class
__ is tuple)
2211 verify((a
* 1).__class
__ is tuple)
2212 verify((a
* 2).__class
__ is tuple)
2213 verify(a
[:].__class
__ is tuple)
2215 class madstring(str):
2218 if self
._rev
is not None:
2222 self
._rev
= self
.__class
__("".join(L
))
2224 s
= madstring("abcdefghijklmnopqrstuvwxyz")
2225 vereq(s
, "abcdefghijklmnopqrstuvwxyz")
2226 vereq(s
.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2227 vereq(s
.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2228 for i
in range(256):
2229 s
= madstring("".join(map(chr, range(i
))))
2233 s
= madstring("12345")
2234 vereq(str(s
), "12345")
2235 verify(str(s
).__class
__ is str)
2241 verify(str(s
).__class
__ is str)
2242 vereq(hash(s
), hash(base
))
2243 vereq({s
: 1}[base
], 1)
2244 vereq({base
: 1}[s
], 1)
2245 verify((s
+ "").__class
__ is str)
2247 verify(("" + s
).__class
__ is str)
2249 verify((s
* 0).__class
__ is str)
2251 verify((s
* 1).__class
__ is str)
2253 verify((s
* 2).__class
__ is str)
2254 vereq(s
* 2, base
+ base
)
2255 verify(s
[:].__class
__ is str)
2257 verify(s
[0:0].__class
__ is str)
2259 verify(s
.strip().__class
__ is str)
2260 vereq(s
.strip(), base
)
2261 verify(s
.lstrip().__class
__ is str)
2262 vereq(s
.lstrip(), base
)
2263 verify(s
.rstrip().__class
__ is str)
2264 vereq(s
.rstrip(), base
)
2265 identitytab
= ''.join([chr(i
) for i
in range(256)])
2266 verify(s
.translate(identitytab
).__class
__ is str)
2267 vereq(s
.translate(identitytab
), base
)
2268 verify(s
.translate(identitytab
, "x").__class
__ is str)
2269 vereq(s
.translate(identitytab
, "x"), base
)
2270 vereq(s
.translate(identitytab
, "\x00"), "")
2271 verify(s
.replace("x", "x").__class
__ is str)
2272 vereq(s
.replace("x", "x"), base
)
2273 verify(s
.ljust(len(s
)).__class
__ is str)
2274 vereq(s
.ljust(len(s
)), base
)
2275 verify(s
.rjust(len(s
)).__class
__ is str)
2276 vereq(s
.rjust(len(s
)), base
)
2277 verify(s
.center(len(s
)).__class
__ is str)
2278 vereq(s
.center(len(s
)), base
)
2279 verify(s
.lower().__class
__ is str)
2280 vereq(s
.lower(), base
)
2282 s
= madstring("x y")
2284 verify(intern(s
).__class
__ is str)
2285 verify(intern(s
) is intern("x y"))
2286 vereq(intern(s
), "x y")
2289 s
= madstring("y x")
2291 verify(intern(s
).__class
__ is str)
2292 verify(intern(s
) is i
)
2295 verify(intern(s
).__class
__ is str)
2296 verify(intern(s
) is i
)
2298 class madunicode(unicode):
2301 if self
._rev
is not None:
2305 self
._rev
= self
.__class
__(u
"".join(L
))
2307 u
= madunicode("ABCDEF")
2309 vereq(u
.rev(), madunicode(u
"FEDCBA"))
2310 vereq(u
.rev().rev(), madunicode(u
"ABCDEF"))
2312 u
= madunicode(base
)
2313 vereq(unicode(u
), base
)
2314 verify(unicode(u
).__class
__ is unicode)
2315 vereq(hash(u
), hash(base
))
2316 vereq({u
: 1}[base
], 1)
2317 vereq({base
: 1}[u
], 1)
2318 verify(u
.strip().__class
__ is unicode)
2319 vereq(u
.strip(), base
)
2320 verify(u
.lstrip().__class
__ is unicode)
2321 vereq(u
.lstrip(), base
)
2322 verify(u
.rstrip().__class
__ is unicode)
2323 vereq(u
.rstrip(), base
)
2324 verify(u
.replace(u
"x", u
"x").__class
__ is unicode)
2325 vereq(u
.replace(u
"x", u
"x"), base
)
2326 verify(u
.replace(u
"xy", u
"xy").__class
__ is unicode)
2327 vereq(u
.replace(u
"xy", u
"xy"), base
)
2328 verify(u
.center(len(u
)).__class
__ is unicode)
2329 vereq(u
.center(len(u
)), base
)
2330 verify(u
.ljust(len(u
)).__class
__ is unicode)
2331 vereq(u
.ljust(len(u
)), base
)
2332 verify(u
.rjust(len(u
)).__class
__ is unicode)
2333 vereq(u
.rjust(len(u
)), base
)
2334 verify(u
.lower().__class
__ is unicode)
2335 vereq(u
.lower(), base
)
2336 verify(u
.upper().__class
__ is unicode)
2337 vereq(u
.upper(), base
)
2338 verify(u
.capitalize().__class
__ is unicode)
2339 vereq(u
.capitalize(), base
)
2340 verify(u
.title().__class
__ is unicode)
2341 vereq(u
.title(), base
)
2342 verify((u
+ u
"").__class
__ is unicode)
2343 vereq(u
+ u
"", base
)
2344 verify((u
"" + u
).__class
__ is unicode)
2345 vereq(u
"" + u
, base
)
2346 verify((u
* 0).__class
__ is unicode)
2348 verify((u
* 1).__class
__ is unicode)
2350 verify((u
* 2).__class
__ is unicode)
2351 vereq(u
* 2, base
+ base
)
2352 verify(u
[:].__class
__ is unicode)
2354 verify(u
[0:0].__class
__ is unicode)
2357 class sublist(list):
2359 a
= sublist(range(5))
2362 vereq(a
, range(5) + ["hello"])
2365 a
.extend(range(6, 20))
2372 vereq(list(a
), range(10))
2377 vereq(a
[:5], range(5))
2379 class CountedInput(file):
2380 """Counts lines read by self.readline().
2382 self.lineno is the 0-based ordinal of the last line read, up to
2383 a maximum of one greater than the number of lines in the file.
2385 self.ateof is true if and only if the final "" line has been read,
2386 at which point self.lineno stops incrementing, and further calls
2387 to readline() continue to return "".
2395 s
= file.readline(self
)
2396 # Next line works too.
2397 # s = super(CountedInput, self).readline()
2403 f
= file(name
=TESTFN
, mode
='w')
2404 lines
= ['a\n', 'b\n', 'c\n']
2408 f
= CountedInput(TESTFN
)
2409 for (i
, expected
) in zip(range(1, 5) + [4], lines
+ 2 * [""]):
2411 vereq(expected
, got
)
2413 vereq(f
.ateof
, (i
> len(lines
)))
2428 print "Testing keyword args to basic type constructors ..."
2430 vereq(float(x
=2), 2.0)
2431 vereq(long(x
=3), 3L)
2432 vereq(complex(imag
=42, real
=666), complex(666, 42))
2433 vereq(str(object=500), '500')
2434 vereq(unicode(string
='abc', errors
='strict'), u
'abc')
2435 vereq(tuple(sequence
=range(3)), (0, 1, 2))
2436 vereq(list(sequence
=(0, 1, 2)), range(3))
2437 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2439 for constructor
in (int, float, long, complex, str, unicode,
2442 constructor(bogus_keyword_arg
=1)
2446 raise TestFailed("expected TypeError from bogus keyword "
2447 "argument to %r" % constructor
)
2450 # XXX This test is disabled because rexec is not deemed safe
2454 print "Testing interaction with restricted execution ..."
2456 sandbox
= rexec
.RExec()
2458 code1
= """f = open(%r, 'w')""" % TESTFN
2459 code2
= """f = file(%r, 'w')""" % TESTFN
2462 t = type(f) # a sneaky way to get the file() constructor
2464 f = t(%r, 'w') # rexec can't catch this by itself
2465 """ % (TESTFN
, TESTFN
)
2467 f
= open(TESTFN
, 'w') # Create the file so code3 can find it.
2471 for code
in code1
, code2
, code3
:
2473 sandbox
.r_exec(code
)
2474 except IOError, msg
:
2475 if str(msg
).find("restricted") >= 0:
2478 outcome
= "got an exception, but not an expected one"
2480 outcome
= "expected a restricted-execution exception"
2483 raise TestFailed("%s, in %r" % (outcome
, code
))
2492 def str_subclass_as_dict_key():
2494 print "Testing a str subclass used as dict key .."
2497 """Sublcass of str that computes __eq__ case-insensitively.
2499 Also computes a hash code of the string in canonical form.
2502 def __init__(self
, value
):
2503 self
.canonical
= value
.lower()
2504 self
.hashcode
= hash(self
.canonical
)
2506 def __eq__(self
, other
):
2507 if not isinstance(other
, cistr
):
2508 other
= cistr(other
)
2509 return self
.canonical
== other
.canonical
2512 return self
.hashcode
2514 vereq(cistr('ABC'), 'abc')
2515 vereq('aBc', cistr('ABC'))
2516 vereq(str(cistr('ABC')), 'ABC')
2518 d
= {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2519 vereq(d
[cistr('one')], 1)
2520 vereq(d
[cistr('tWo')], 2)
2521 vereq(d
[cistr('THrEE')], 3)
2522 verify(cistr('ONe') in d
)
2523 vereq(d
.get(cistr('thrEE')), 3)
2525 def classic_comparisons():
2526 if verbose
: print "Testing classic comparisons..."
2529 for base
in (classic
, int, object):
2530 if verbose
: print " (base = %s)" % base
2532 def __init__(self
, value
):
2533 self
.value
= int(value
)
2534 def __cmp__(self
, other
):
2535 if isinstance(other
, C
):
2536 return cmp(self
.value
, other
.value
)
2537 if isinstance(other
, int) or isinstance(other
, long):
2538 return cmp(self
.value
, other
)
2539 return NotImplemented
2544 c
= {1: c1
, 2: c2
, 3: c3
}
2547 verify(cmp(c
[x
], c
[y
]) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2548 for op
in "<", "<=", "==", "!=", ">", ">=":
2549 verify(eval("c[x] %s c[y]" % op
) == eval("x %s y" % op
),
2550 "x=%d, y=%d" % (x
, y
))
2551 verify(cmp(c
[x
], y
) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2552 verify(cmp(x
, c
[y
]) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2554 def rich_comparisons():
2556 print "Testing rich comparisons..."
2563 def __eq__(self
, other
):
2565 return abs(self
- other
) <= 1e-6
2567 return NotImplemented
2574 for base
in (classic
, int, object, list):
2575 if verbose
: print " (base = %s)" % base
2577 def __init__(self
, value
):
2578 self
.value
= int(value
)
2579 def __cmp__(self
, other
):
2580 raise TestFailed
, "shouldn't call __cmp__"
2581 def __eq__(self
, other
):
2582 if isinstance(other
, C
):
2583 return self
.value
== other
.value
2584 if isinstance(other
, int) or isinstance(other
, long):
2585 return self
.value
== other
2586 return NotImplemented
2587 def __ne__(self
, other
):
2588 if isinstance(other
, C
):
2589 return self
.value
!= other
.value
2590 if isinstance(other
, int) or isinstance(other
, long):
2591 return self
.value
!= other
2592 return NotImplemented
2593 def __lt__(self
, other
):
2594 if isinstance(other
, C
):
2595 return self
.value
< other
.value
2596 if isinstance(other
, int) or isinstance(other
, long):
2597 return self
.value
< other
2598 return NotImplemented
2599 def __le__(self
, other
):
2600 if isinstance(other
, C
):
2601 return self
.value
<= other
.value
2602 if isinstance(other
, int) or isinstance(other
, long):
2603 return self
.value
<= other
2604 return NotImplemented
2605 def __gt__(self
, other
):
2606 if isinstance(other
, C
):
2607 return self
.value
> other
.value
2608 if isinstance(other
, int) or isinstance(other
, long):
2609 return self
.value
> other
2610 return NotImplemented
2611 def __ge__(self
, other
):
2612 if isinstance(other
, C
):
2613 return self
.value
>= other
.value
2614 if isinstance(other
, int) or isinstance(other
, long):
2615 return self
.value
>= other
2616 return NotImplemented
2621 c
= {1: c1
, 2: c2
, 3: c3
}
2624 for op
in "<", "<=", "==", "!=", ">", ">=":
2625 verify(eval("c[x] %s c[y]" % op
) == eval("x %s y" % op
),
2626 "x=%d, y=%d" % (x
, y
))
2627 verify(eval("c[x] %s y" % op
) == eval("x %s y" % op
),
2628 "x=%d, y=%d" % (x
, y
))
2629 verify(eval("x %s c[y]" % op
) == eval("x %s y" % op
),
2630 "x=%d, y=%d" % (x
, y
))
2633 if verbose
: print "Testing coercions..."
2642 class F(float): pass
2649 class C(complex): pass
2660 if verbose
: print "Testing descriptor doc strings..."
2661 def check(descr
, what
):
2662 vereq(descr
.__doc
__, what
)
2663 check(file.closed
, "True if the file is closed") # getset descriptor
2664 check(file.name
, "file name") # member descriptor
2667 if verbose
: print "Testing __class__ assignment..."
2668 class C(object): pass
2669 class D(object): pass
2670 class E(object): pass
2672 for cls
in C
, D
, E
, F
:
2673 for cls2
in C
, D
, E
, F
:
2676 verify(x
.__class
__ is cls2
)
2678 verify(x
.__class
__ is cls
)
2685 raise TestFailed
, "shouldn't allow %r.__class__ = %r" % (x
, C
)
2687 delattr(x
, "__class__")
2691 raise TestFailed
, "shouldn't allow del %r.__class__" % x
2696 cant(object(), list)
2697 cant(list(), object)
2698 class Int(int): __slots__
= []
2709 if verbose
: print "Testing __dict__ assignment..."
2710 class C(object): pass
2712 a
.__dict
__ = {'b': 1}
2720 raise TestFailed
, "shouldn't allow %r.__dict__ = %r" % (x
, dict)
2724 del a
.__dict
__ # Deleting __dict__ is allowed
2725 # Classes don't allow __dict__ assignment
2730 print "Testing pickling and copying new-style classes and objects..."
2731 import pickle
, cPickle
2740 def __init__(self
, a
, b
):
2741 super(C
, self
).__init
__()
2745 return "C(%r, %r)" % (self
.a
, self
.b
)
2749 def __new__(cls
, a
, b
):
2750 return super(C1
, cls
).__new
__(cls
)
2751 def __getnewargs__(self
):
2752 return (self
.a
, self
.b
)
2753 def __init__(self
, a
, b
):
2757 return "C1(%r, %r)<%r>" % (self
.a
, self
.b
, list(self
))
2761 def __new__(cls
, a
, b
, val
=0):
2762 return super(C2
, cls
).__new
__(cls
, val
)
2763 def __getnewargs__(self
):
2764 return (self
.a
, self
.b
, int(self
))
2765 def __init__(self
, a
, b
, val
=0):
2769 return "C2(%r, %r)<%r>" % (self
.a
, self
.b
, int(self
))
2773 def __init__(self
, foo
):
2775 def __getstate__(self
):
2777 def __setstate__(self
, foo
):
2780 global C4classic
, C4
2781 class C4classic
: # classic
2783 class C4(C4classic
, object): # mixed inheritance
2786 for p
in pickle
, cPickle
:
2789 print p
.__name
__, ["text", "binary"][bin
]
2791 for cls
in C
, C1
, C2
:
2792 s
= p
.dumps(cls
, bin
)
2796 a
= C1(1, 2); a
.append(42); a
.append(24)
2797 b
= C2("hello", "world", 42)
2798 s
= p
.dumps((a
, b
), bin
)
2800 vereq(x
.__class
__, a
.__class
__)
2801 vereq(sorteditems(x
.__dict
__), sorteditems(a
.__dict
__))
2802 vereq(y
.__class
__, b
.__class
__)
2803 vereq(sorteditems(y
.__dict
__), sorteditems(b
.__dict
__))
2809 # Test for __getstate__ and __setstate__ on new style class
2813 veris(u
.__class
__, v
.__class
__)
2815 # Test for picklability of hybrid class
2820 veris(u
.__class
__, v
.__class
__)
2823 # Testing copy.deepcopy()
2827 for cls
in C
, C1
, C2
:
2828 cls2
= copy
.deepcopy(cls
)
2831 a
= C1(1, 2); a
.append(42); a
.append(24)
2832 b
= C2("hello", "world", 42)
2833 x
, y
= copy
.deepcopy((a
, b
))
2834 vereq(x
.__class
__, a
.__class
__)
2835 vereq(sorteditems(x
.__dict
__), sorteditems(a
.__dict
__))
2836 vereq(y
.__class
__, b
.__class
__)
2837 vereq(sorteditems(y
.__dict
__), sorteditems(b
.__dict
__))
2845 if verbose
: print "Testing pickling of classes with __slots__ ..."
2846 import pickle
, cPickle
2847 # Pickling of classes with __slots__ but without __getstate__ should fail
2851 for base
in [object, B
]:
2861 raise TestFailed
, "should fail: pickle C instance - %s" % base
2867 raise TestFailed
, "should fail: cPickle C instance - %s" % base
2873 raise TestFailed
, "should fail: pickle D instance - %s" % base
2879 raise TestFailed
, "should fail: cPickle D instance - %s" % base
2880 # Give C a nice generic __getstate__ and __setstate__
2883 def __getstate__(self
):
2885 d
= self
.__dict
__.copy()
2886 except AttributeError:
2888 for cls
in self
.__class
__.__mro
__:
2889 for sn
in cls
.__dict
__.get('__slots__', ()):
2891 d
[sn
] = getattr(self
, sn
)
2892 except AttributeError:
2895 def __setstate__(self
, d
):
2896 for k
, v
in d
.items():
2900 # Now it should work
2902 y
= pickle
.loads(pickle
.dumps(x
))
2903 vereq(hasattr(y
, 'a'), 0)
2904 y
= cPickle
.loads(cPickle
.dumps(x
))
2905 vereq(hasattr(y
, 'a'), 0)
2907 y
= pickle
.loads(pickle
.dumps(x
))
2909 y
= cPickle
.loads(cPickle
.dumps(x
))
2914 y
= pickle
.loads(pickle
.dumps(x
))
2915 vereq(y
.a
+ y
.b
, 142)
2916 y
= cPickle
.loads(cPickle
.dumps(x
))
2917 vereq(y
.a
+ y
.b
, 142)
2918 # A subclass that adds a slot should also work
2924 y
= pickle
.loads(pickle
.dumps(x
))
2927 y
= cPickle
.loads(cPickle
.dumps(x
))
2932 if verbose
: print "Testing copy.copy() and copy.deepcopy()..."
2940 vereq(b
.__dict
__, a
.__dict
__)
2945 verify(c
.bar
is a
.bar
)
2947 d
= copy
.deepcopy(a
)
2948 vereq(d
.__dict
__, a
.__dict
__)
2950 vereq(d
.bar
, [1,2,3])
2952 def binopoverride():
2953 if verbose
: print "Testing overrides of binary operations..."
2956 return "I(%r)" % int(self
)
2957 def __add__(self
, other
):
2958 return I(int(self
) + int(other
))
2960 def __pow__(self
, other
, mod
=None):
2962 return I(pow(int(self
), int(other
)))
2964 return I(pow(int(self
), int(other
), int(mod
)))
2965 def __rpow__(self
, other
, mod
=None):
2967 return I(pow(int(other
), int(self
), mod
))
2969 return I(pow(int(other
), int(self
), int(mod
)))
2971 vereq(`
I(1) + I(2)`
, "I(3)")
2972 vereq(`
I(1) + 2`
, "I(3)")
2973 vereq(`
1 + I(2)`
, "I(3)")
2974 vereq(`
I(2) ** I(3)`
, "I(8)")
2975 vereq(`
2 ** I(3)`
, "I(8)")
2976 vereq(`
I(2) ** 3`
, "I(8)")
2977 vereq(`
pow(I(2), I(3), I(5))`
, "I(3)")
2979 def __eq__(self
, other
):
2980 return self
.lower() == other
.lower()
2982 def subclasspropagation():
2983 if verbose
: print "Testing propagation of slot functions to subclasses..."
2993 vereq(hash(d
), id(d
))
2994 A
.__hash
__ = lambda self
: 42
2996 C
.__hash
__ = lambda self
: 314
2998 B
.__hash
__ = lambda self
: 144
3000 D
.__hash
__ = lambda self
: 100
3009 vereq(hash(d
), id(d
))
3014 def __getattribute__(self
, name
):
3017 return object.__getattribute
__(self
, name
)
3018 A
.__getattribute
__ = __getattribute__
3021 def __getattr__(self
, name
):
3022 if name
in ("spam", "foo", "bar"):
3024 raise AttributeError, name
3025 B
.__getattr
__ = __getattr__
3026 vereq(d
.spam
, "hello")
3029 del A
.__getattribute
__
3032 vereq(d
.foo
, "hello")
3037 except AttributeError:
3040 raise TestFailed
, "d.foo should be undefined now"
3042 # Test a nasty bug in recurse_down_subclasses()
3050 A
.__setitem
__ = lambda *a
: None # crash
3052 def buffer_inherit():
3054 # SF bug [#470040] ParseTuple t# vs subclasses.
3056 print "Testing that buffer interface is inherited ..."
3062 # b2a_hex uses the buffer interface to get its argument's value, via
3063 # PyArg_ParseTuple 't#' code.
3064 vereq(binascii
.b2a_hex(m
), binascii
.b2a_hex(base
))
3066 # It's not clear that unicode will continue to support the character
3067 # buffer interface, and this test will fail if that's taken away.
3068 class MyUni(unicode):
3072 vereq(binascii
.b2a_hex(m
), binascii
.b2a_hex(base
))
3079 raise TestFailed('subclass of int should not have a buffer interface')
3083 def str_of_str_subclass():
3088 print "Testing __str__ defined in subclass of str ..."
3090 class octetstring(str):
3092 return binascii
.b2a_hex(self
)
3094 return self
+ " repr"
3096 o
= octetstring('A')
3097 vereq(type(o
), octetstring
)
3098 vereq(type(str(o
)), str)
3099 vereq(type(repr(o
)), str)
3102 vereq(repr(o
), 'A repr')
3103 vereq(o
.__str
__(), '41')
3104 vereq(o
.__repr
__(), 'A repr')
3106 capture
= cStringIO
.StringIO()
3107 # Calling str() or not exercises different internal paths.
3109 print >> capture
, str(o
)
3110 vereq(capture
.getvalue(), '41\n41\n')
3114 if verbose
: print "Testing keyword arguments to __init__, __call__..."
3116 vereq(f
.__call
__(a
=42), 42)
3118 list.__init
__(a
, sequence
=[0, 1, 2])
3122 if verbose
: print "Testing __del__ hook..."
3132 class D(object): pass
3135 except TypeError: pass
3136 else: raise TestFailed
, "invalid del() didn't raise TypeError"
3139 if verbose
: print "Testing hash of mutable subclasses..."
3149 raise TestFailed
, "hash() of dict subclass should fail"
3159 raise TestFailed
, "hash() of list subclass should fail"
3163 except TypeError: pass
3164 else: raise TestFailed
, "'' + 5 doesn't raise TypeError"
3167 except ValueError: pass
3168 else: raise TestFailed
, "''.split('') doesn't raise ValueError"
3171 except TypeError: pass
3172 else: raise TestFailed
, "''.join([0]) doesn't raise TypeError"
3175 except ValueError: pass
3176 else: raise TestFailed
, "''.rindex('5') doesn't raise ValueError"
3179 except TypeError: pass
3180 else: raise TestFailed
, "'%(n)s' % None doesn't raise TypeError"
3183 except ValueError: pass
3184 else: raise TestFailed
, "'%(n' % {} '' doesn't raise ValueError"
3186 try: '%*s' % ('abc')
3187 except TypeError: pass
3188 else: raise TestFailed
, "'%*s' % ('abc') doesn't raise TypeError"
3190 try: '%*.*s' % ('abc', 5)
3191 except TypeError: pass
3192 else: raise TestFailed
, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3195 except TypeError: pass
3196 else: raise TestFailed
, "'%s' % (1, 2) doesn't raise TypeError"
3199 except ValueError: pass
3200 else: raise TestFailed
, "'%' % None doesn't raise ValueError"
3202 vereq('534253'.isdigit(), 1)
3203 vereq('534253x'.isdigit(), 0)
3204 vereq('%c' % 5, '\x05')
3205 vereq('%c' % '5', '5')
3207 def deepcopyrecursive():
3208 if verbose
: print "Testing deepcopy of recursive objects..."
3215 z
= deepcopy(a
) # This blew up before
3218 if verbose
: print "Testing uninitialized module objects..."
3219 from types
import ModuleType
as M
3222 vereq(hasattr(m
, "__name__"), 0)
3223 vereq(hasattr(m
, "__file__"), 0)
3224 vereq(hasattr(m
, "foo"), 0)
3225 vereq(m
.__dict
__, None)
3227 vereq(m
.__dict
__, {"foo": 1})
3229 def dictproxyiterkeys():
3233 if verbose
: print "Testing dict-proxy iterkeys..."
3234 keys
= [ key
for key
in C
.__dict
__.iterkeys() ]
3236 vereq(keys
, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3238 def dictproxyitervalues():
3242 if verbose
: print "Testing dict-proxy itervalues..."
3243 values
= [ values
for values
in C
.__dict
__.itervalues() ]
3244 vereq(len(values
), 5)
3246 def dictproxyiteritems():
3250 if verbose
: print "Testing dict-proxy iteritems..."
3251 keys
= [ key
for (key
, value
) in C
.__dict
__.iteritems() ]
3253 vereq(keys
, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3256 if verbose
: print "Testing __new__ returning something unexpected..."
3258 def __new__(cls
, arg
):
3259 if isinstance(arg
, str): return [1, 2, 3]
3260 elif isinstance(arg
, int): return object.__new
__(D
)
3261 else: return object.__new
__(cls
)
3263 def __init__(self
, arg
):
3265 vereq(C("1"), [1, 2, 3])
3266 vereq(D("1"), [1, 2, 3])
3270 vereq(isinstance(d
, D
), True)
3273 vereq(isinstance(d
, D
), True)
3278 if verbose
: print "Testing for __imul__ problems..."
3280 def __imul__(self
, other
):
3281 return (self
, other
)
3294 vereq(y
, (x
, 1L<<100))
3300 vereq(y
, (x
, "foo"))
3302 def docdescriptor():
3304 if verbose
: print "Testing __doc__ descriptor..."
3305 class DocDescr(object):
3306 def __get__(self
, object, otype
):
3308 object = object.__class
__.__name
__ + ' instance'
3310 otype
= otype
.__name
__
3311 return 'object=%s; type=%s' % (object, otype
)
3313 __doc__
= DocDescr()
3314 class NewClass(object):
3315 __doc__
= DocDescr()
3316 vereq(OldClass
.__doc
__, 'object=None; type=OldClass')
3317 vereq(OldClass().__doc
__, 'object=OldClass instance; type=OldClass')
3318 vereq(NewClass
.__doc
__, 'object=None; type=NewClass')
3319 vereq(NewClass().__doc
__, 'object=NewClass instance; type=NewClass')
3321 def string_exceptions():
3323 print "Testing string exceptions ..."
3325 # Ensure builtin strings work OK as exceptions.
3326 astring
= "An exception string."
3332 raise TestFailed
, "builtin string not usable as exception"
3334 # Ensure string subclass instances do not.
3338 newstring
= MyStr("oops -- shouldn't work")
3344 raise TestFailed
, "string subclass allowed as exception"
3346 def copy_setstate():
3348 print "Testing that copy.*copy() correctly uses __setstate__..."
3351 def __init__(self
, foo
=None):
3354 def setfoo(self
, foo
=None):
3358 def __getstate__(self
):
3360 def __setstate__(self
, lst
):
3361 assert len(lst
) == 1
3362 self
.__foo
= self
.foo
= lst
[0]
3366 vereq(a
.getfoo(), 42)
3369 vereq(b
.getfoo(), 24)
3370 b
= copy
.deepcopy(a
)
3372 vereq(b
.getfoo(), 24)
3376 print "Testing cases with slices and overridden __getitem__ ..."
3378 vereq("hello"[:4], "hell")
3379 vereq("hello"[slice(4)], "hell")
3380 vereq(str.__getitem
__("hello", slice(4)), "hell")
3382 def __getitem__(self
, x
):
3383 return str.__getitem
__(self
, x
)
3384 vereq(S("hello")[:4], "hell")
3385 vereq(S("hello")[slice(4)], "hell")
3386 vereq(S("hello").__getitem
__(slice(4)), "hell")
3388 vereq((1,2,3)[:2], (1,2))
3389 vereq((1,2,3)[slice(2)], (1,2))
3390 vereq(tuple.__getitem
__((1,2,3), slice(2)), (1,2))
3392 def __getitem__(self
, x
):
3393 return tuple.__getitem
__(self
, x
)
3394 vereq(T((1,2,3))[:2], (1,2))
3395 vereq(T((1,2,3))[slice(2)], (1,2))
3396 vereq(T((1,2,3)).__getitem
__(slice(2)), (1,2))
3398 vereq([1,2,3][:2], [1,2])
3399 vereq([1,2,3][slice(2)], [1,2])
3400 vereq(list.__getitem
__([1,2,3], slice(2)), [1,2])
3402 def __getitem__(self
, x
):
3403 return list.__getitem
__(self
, x
)
3404 vereq(L([1,2,3])[:2], [1,2])
3405 vereq(L([1,2,3])[slice(2)], [1,2])
3406 vereq(L([1,2,3]).__getitem
__(slice(2)), [1,2])
3407 # Now do lists and __setitem__
3409 a
[slice(1, 3)] = [3,2]
3411 a
[slice(0, 2, 1)] = [3,1]
3413 a
.__setitem
__(slice(1, 3), [2,1])
3415 a
.__setitem
__(slice(0, 2, 1), [2,3])
3418 def subtype_resurrection():
3420 print "Testing resurrection of new-style instance..."
3426 # resurrect the instance
3427 C
.container
.append(self
)
3431 # The most interesting thing here is whether this blows up, due to flawed
3432 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
3435 # If that didn't blow up, it's also interesting to see whether clearing
3436 # the last container slot works: that will attempt to delete c again,
3437 # which will cause c to get appended back to the container again "during"
3440 vereq(len(C
.container
), 1)
3441 vereq(C
.container
[-1].attr
, 42)
3443 # Make c mortal again, so that the test framework with -l doesn't report
3448 # Deallocating deeply nested slotted trash caused stack overflows
3450 print "Testing slot trash..."
3451 class trash(object):
3453 def __init__(self
, x
):
3456 for i
in xrange(50000):
3460 def slotmultipleinheritance():
3461 # SF bug 575229, multiple inheritance w/ slots dumps core
3468 vereq(C
.__basicsize
__, B
.__basicsize
__)
3469 verify(hasattr(C
, '__dict__'))
3470 verify(hasattr(C
, '__weakref__'))
3476 print "Testing correct invocation of __rmul__..."
3478 def __mul__(self
, other
):
3480 def __rmul__(self
, other
):
3486 vereq(2.2*a
, "rmul")
3491 print "Testing correct invocation of __ipow__..."
3493 def __ipow__(self
, other
):
3498 def do_this_first():
3500 print "Testing SF bug 551412 ..."
3501 # This dumps core when SF bug 551412 isn't fixed --
3502 # but only when test_descr.py is run separately.
3503 # (That can't be helped -- as soon as PyType_Ready()
3504 # is called for PyLong_Type, the bug is gone.)
3505 class UserLong(object):
3506 def __pow__(self
, *args
):
3509 pow(0L, UserLong(), 0L)
3514 print "Testing SF bug 570483..."
3515 # Another segfault only when run early
3516 # (before PyType_Ready(tuple) is called)
3519 def test_mutable_bases():
3521 print "Testing mutable bases..."
3522 # stuff that should work:
3526 def __getattribute__(self
, attr
):
3530 return super(C2
, self
).__getattribute
__(attr
)
3545 vereq(C2
.__subclasses__(), [D
])
3547 # stuff that shouldn't:
3552 L
.__bases
__ = (dict,)
3556 raise TestFailed
, "shouldn't turn list subclass into dict subclass"
3559 list.__bases
__ = (dict,)
3563 raise TestFailed
, "shouldn't be able to assign to list.__bases__"
3570 raise TestFailed
, "shouldn't be able to delete .__bases__"
3574 except TypeError, msg
:
3575 if str(msg
) == "a new-style class can't have only classic bases":
3576 raise TestFailed
, "wrong error message for .__bases__ = ()"
3578 raise TestFailed
, "shouldn't be able to set .__bases__ to ()"
3585 # actually, we'll have crashed by here...
3586 raise TestFailed
, "shouldn't be able to create inheritance cycles"
3593 raise TestFailed
, "shouldn't be able to create inheritance cycles"
3595 # let's throw a classic class into the mix:
3600 D
.__bases
__ = (C
, Classic
)
3606 except AttributeError:
3609 raise TestFailed
, "attribute should have vanished"
3612 D
.__bases
__ = (Classic
,)
3616 raise TestFailed
, "new-style class must have a new-style base"
3618 def test_mutable_bases_with_failing_mro():
3620 print "Testing mutable bases with failing mro..."
3621 class WorkOnce(type):
3622 def __new__(self
, name
, bases
, ns
):
3624 return super(WorkOnce
, self
).__new
__(WorkOnce
, name
, bases
, ns
)
3627 raise RuntimeError, "bozo"
3630 return type.mro(self
)
3632 class WorkAlways(type):
3634 # this is here to make sure that .mro()s aren't called
3635 # with an exception set (which was possible at one point).
3636 # An error message will be printed in a debug build.
3637 # What's a good way to test for this?
3638 return type.mro(self
)
3653 __metaclass__
= WorkOnce
3656 __metaclass__
= WorkAlways
3658 # Immediate subclasses have their mro's adjusted in alphabetical
3659 # order, so E's will get adjusted before adjusting F's fails. We
3660 # check here that E's gets restored.
3662 E_mro_before
= E
.__mro
__
3663 D_mro_before
= D
.__mro
__
3667 except RuntimeError:
3668 vereq(E
.__mro
__, E_mro_before
)
3669 vereq(D
.__mro
__, D_mro_before
)
3671 raise TestFailed
, "exception not propagated"
3673 def test_mutable_bases_catch_mro_conflict():
3675 print "Testing mutable bases catch mro conflict..."
3692 C
.__bases
__ = (B
, A
)
3696 raise TestFailed
, "didn't catch MRO conflict"
3698 def mutable_names():
3700 print "Testing mutable names..."
3704 # C.__module__ could be 'test_descr' or '__main__'
3708 vereq((C
.__module
__, C
.__name
__), (mod
, 'D'))
3711 vereq((C
.__module
__, C
.__name
__), (mod
, 'D.E'))
3713 def subclass_right_op():
3715 print "Testing correct dispatch of subclass overloading __r<op>__..."
3717 # This code tests various cases where right-dispatch of a subclass
3718 # should be preferred over left-dispatch of a base class.
3720 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3723 def __floordiv__(self
, other
):
3724 return "B.__floordiv__"
3725 def __rfloordiv__(self
, other
):
3726 return "B.__rfloordiv__"
3728 vereq(B(1) // 1, "B.__floordiv__")
3729 vereq(1 // B(1), "B.__rfloordiv__")
3731 # Case 2: subclass of object; this is just the baseline for case 3
3734 def __floordiv__(self
, other
):
3735 return "C.__floordiv__"
3736 def __rfloordiv__(self
, other
):
3737 return "C.__rfloordiv__"
3739 vereq(C() // 1, "C.__floordiv__")
3740 vereq(1 // C(), "C.__rfloordiv__")
3742 # Case 3: subclass of new-style class; here it gets interesting
3745 def __floordiv__(self
, other
):
3746 return "D.__floordiv__"
3747 def __rfloordiv__(self
, other
):
3748 return "D.__rfloordiv__"
3750 vereq(D() // C(), "D.__floordiv__")
3751 vereq(C() // D(), "D.__rfloordiv__")
3753 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3758 vereq(E
.__rfloordiv
__, C
.__rfloordiv
__)
3760 vereq(E() // 1, "C.__floordiv__")
3761 vereq(1 // E(), "C.__rfloordiv__")
3762 vereq(E() // C(), "C.__floordiv__")
3763 vereq(C() // E(), "C.__floordiv__") # This one would fail
3765 def dict_type_with_metaclass():
3767 print "Testing type of __dict__ when __metaclass__ set..."
3774 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
3776 veris(type(C
.__dict
__), type(B
.__dict
__))
3778 def meth_class_get():
3779 # Full coverage of descrobject.c::classmethod_get()
3781 print "Testing __get__ method of METH_CLASS C methods..."
3784 res
= {1: None, 2: None, 3: None}
3785 vereq(dict.fromkeys(arg
), res
)
3786 vereq({}.fromkeys(arg
), res
)
3787 # Now get the descriptor
3788 descr
= dict.__dict
__["fromkeys"]
3789 # More baseline using the descriptor directly
3790 vereq(descr
.__get
__(None, dict)(arg
), res
)
3791 vereq(descr
.__get
__({})(arg
), res
)
3792 # Now check various error cases
3794 descr
.__get
__(None, None)
3798 raise TestFailed
, "shouldn't have allowed descr.__get__(None, None)"
3804 raise TestFailed
, "shouldn't have allowed descr.__get__(42)"
3806 descr
.__get
__(None, 42)
3810 raise TestFailed
, "shouldn't have allowed descr.__get__(None, 42)"
3812 descr
.__get
__(None, int)
3816 raise TestFailed
, "shouldn't have allowed descr.__get__(None, int)"
3818 def isinst_isclass():
3820 print "Testing proxy isinstance() and isclass()..."
3821 class Proxy(object):
3822 def __init__(self
, obj
):
3824 def __getattribute__(self
, name
):
3825 if name
.startswith("_Proxy__"):
3826 return object.__getattribute
__(self
, name
)
3828 return getattr(self
.__obj
, name
)
3829 # Test with a classic class
3834 verify(isinstance(a
, C
)) # Baseline
3835 verify(isinstance(pa
, C
)) # Test
3836 # Test with a classic subclass
3841 verify(isinstance(a
, C
)) # Baseline
3842 verify(isinstance(pa
, C
)) # Test
3843 # Test with a new-style class
3848 verify(isinstance(a
, C
)) # Baseline
3849 verify(isinstance(pa
, C
)) # Test
3850 # Test with a new-style subclass
3855 verify(isinstance(a
, C
)) # Baseline
3856 verify(isinstance(pa
, C
)) # Test
3860 print "Testing super() for a proxy object..."
3861 class Proxy(object):
3862 def __init__(self
, obj
):
3864 def __getattribute__(self
, name
):
3865 if name
.startswith("_Proxy__"):
3866 return object.__getattribute
__(self
, name
)
3868 return getattr(self
.__obj
, name
)
3876 return super(C
, self
).f() + "->C.f"
3880 vereq(C
.__dict
__["f"](p
), "B.f->C.f")
3884 print "Testing prohibition of Carlo Verre's hack..."
3886 object.__setattr
__(str, "foo", 42)
3890 raise TestFailed
, "Carlo Verre __setattr__ suceeded!"
3892 object.__delattr
__(str, "lower")
3896 raise TestFailed
, "Carlo Verre __delattr__ succeeded!"
3898 def weakref_segfault():
3901 print "Testing weakref segfault..."
3906 def __init__(self
, referrent
):
3907 self
.ref
= weakref
.ref(referrent
)
3916 o
.whatever
= Provoker(o
)
3919 # Fix SF #762455, segfault when sys.stdout is changed in getattr
3922 print "Testing sys.stdout is changed in getattr..."
3925 def __getattr__(self
, attr
):
3926 sys
.stdout
= sys
.__stdout
__
3927 raise RuntimeError("Premature access to sys.stdout.%s" % attr
)
3928 sys
.stdout
= StdoutGuard()
3931 except RuntimeError:
3935 weakref_segfault() # Must be first, somehow
3957 consistency_with_epg()
3966 staticmethods_in_c()
3980 str_subclass_as_dict_key()
3981 classic_comparisons()
3990 subclasspropagation()
3992 str_of_str_subclass()
4000 dictproxyitervalues()
4001 dictproxyiteritems()
4009 subtype_resurrection()
4011 slotmultipleinheritance()
4014 test_mutable_bases()
4015 test_mutable_bases_with_failing_mro()
4016 test_mutable_bases_catch_mro_conflict()
4019 dict_type_with_metaclass()
4026 if verbose
: print "All OK"
4028 if __name__
== "__main__":