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
466 raise TestFailed
, "NotImplemented should have caused TypeError"
469 if verbose
: print "Testing long operations..."
473 if verbose
: print "Testing float operations..."
477 if verbose
: print "Testing complex operations..."
478 numops(100.0j
, 3.0j
, skip
=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
479 class Number(complex):
481 def __new__(cls
, *args
, **kwds
):
482 result
= complex.__new
__(cls
, *args
)
483 result
.prec
= kwds
.get('prec', 12)
488 return "%.*g" % (prec
, self
.real
)
490 return "%.*gj" % (prec
, self
.imag
)
491 return "(%.*g+%.*gj)" % (prec
, self
.real
, prec
, self
.imag
)
494 a
= Number(3.14, prec
=6)
498 a
= Number(a
, prec
=2)
507 if verbose
: print "Testing spamlist operations..."
508 import copy
, xxsubtype
as spam
509 def spamlist(l
, memo
=None):
510 import xxsubtype
as spam
511 return spam
.spamlist(l
)
512 # This is an ugly hack:
513 copy
._deepcopy
_dispatch
[spam
.spamlist
] = spamlist
515 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
516 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
517 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
518 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
519 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
520 "a[b:c]", "__getslice__")
521 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
523 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
524 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
525 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
526 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
527 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
528 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
529 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
531 class C(spam
.spamlist
):
532 def foo(self
): return 1
538 vereq(a
.getstate(), 0)
540 vereq(a
.getstate(), 42)
543 if verbose
: print "Testing spamdict operations..."
544 import copy
, xxsubtype
as spam
545 def spamdict(d
, memo
=None):
546 import xxsubtype
as spam
548 for k
, v
in d
.items(): sd
[k
] = v
550 # This is an ugly hack:
551 copy
._deepcopy
_dispatch
[spam
.spamdict
] = spamdict
553 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
554 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
555 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
556 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
557 d
= spamdict({1:2,3:4})
559 for i
in d
.keys(): l1
.append(i
)
561 for i
in iter(d
): l
.append(i
)
564 for i
in d
.__iter
__(): l
.append(i
)
567 for i
in type(spamdict({})).__iter
__(d
): l
.append(i
)
569 straightd
= {1:2, 3:4}
570 spamd
= spamdict(straightd
)
571 testunop(spamd
, 2, "len(a)", "__len__")
572 testunop(spamd
, repr(straightd
), "repr(a)", "__repr__")
573 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
574 "a[b]=c", "__setitem__")
576 class C(spam
.spamdict
):
577 def foo(self
): return 1
582 vereq(a
.items(), [('foo', 'bar')])
583 vereq(a
.getstate(), 0)
585 vereq(a
.getstate(), 100)
588 if verbose
: print "Testing Python subclass of dict..."
589 verify(issubclass(dict, dict))
590 verify(isinstance({}, dict))
593 verify(d
.__class
__ is dict)
594 verify(isinstance(d
, dict))
597 def __init__(self
, *a
, **kw
):
602 for k
, v
in kw
.items(): self
[v
] = k
603 def __getitem__(self
, key
):
604 return self
.get(key
, 0)
605 def __setitem__(self
, key
, value
):
606 verify(isinstance(key
, type(0)))
607 dict.__setitem
__(self
, key
, value
)
608 def setstate(self
, state
):
612 verify(issubclass(C
, dict))
616 vereq(a2
[1] == 'foo' and a2
[2], 'bar')
619 vereq(a
.getstate(), -1)
622 vereq(a
.getstate(), 0)
625 vereq(a
.getstate(), 10)
629 if verbose
: print "pydict stress test ..."
640 if verbose
: print "Testing Python subclass of list..."
642 def __getitem__(self
, i
):
643 return list.__getitem
__(self
, i
) + 100
644 def __getslice__(self
, i
, j
):
651 vereq(a
[100:200], (100,200))
654 if verbose
: print "Testing __metaclass__..."
661 def setstate(self
, state
):
664 vereq(a
.getstate(), 0)
666 vereq(a
.getstate(), 10)
668 class __metaclass__(type):
669 def myself(cls
): return cls
672 verify(d
.__class
__ is D
)
674 def __new__(cls
, name
, bases
, dict):
676 return type.__new
__(cls
, name
, bases
, dict)
683 class _instance(object):
686 def __new__(cls
, name
, bases
, dict):
687 self
= object.__new
__(cls
)
692 __new__
= staticmethod(__new__
)
695 # Early binding of methods
696 for key
in self
.dict:
697 if key
.startswith("__"):
699 setattr(it
, key
, self
.dict[key
].__get
__(it
, self
))
707 verify('spam' in C
.dict)
711 # More metaclass examples
713 class autosuper(type):
714 # Automatically add __super to the class
715 # This trick only works for dynamic classes
716 def __new__(metaclass
, name
, bases
, dict):
717 cls
= super(autosuper
, metaclass
).__new
__(metaclass
,
719 # Name mangling for __super removes leading underscores
720 while name
[:1] == "_":
723 name
= "_%s__super" % name
726 setattr(cls
, name
, super(cls
))
729 __metaclass__
= autosuper
734 return "B" + self
.__super
.meth()
737 return "C" + self
.__super
.meth()
740 return "D" + self
.__super
.meth()
741 vereq(D().meth(), "DCBA")
744 return "E" + self
.__super
.meth()
745 vereq(E().meth(), "EBCA")
747 class autoproperty(type):
748 # Automatically create property attributes when methods
749 # named _get_x and/or _set_x are found
750 def __new__(metaclass
, name
, bases
, dict):
752 for key
, val
in dict.iteritems():
753 if key
.startswith("_get_"):
755 get
, set = hits
.get(key
, (None, None))
758 elif key
.startswith("_set_"):
760 get
, set = hits
.get(key
, (None, None))
763 for key
, (get
, set) in hits
.iteritems():
764 dict[key
] = property(get
, set)
765 return super(autoproperty
, metaclass
).__new
__(metaclass
,
768 __metaclass__
= autoproperty
774 verify(not hasattr(a
, "x"))
779 class multimetaclass(autoproperty
, autosuper
):
780 # Merge of multiple cooperating metaclasses
783 __metaclass__
= multimetaclass
788 return "B" + self
.__super
._get
_x
()
791 return "C" + self
.__super
._get
_x
()
794 return "D" + self
.__super
._get
_x
()
797 # Make sure type(x) doesn't call x.__class__.__init__
800 def __init__(self
, *args
):
809 class C(object): pass
812 except TypeError: pass
813 else: raise TestFailed
, "calling object w/o call method should raise TypeError"
816 if verbose
: print "Testing Python subclass of module..."
821 def __init__(self
, name
):
822 MT
.__init
__(self
, name
)
823 def __getattribute__(self
, name
):
824 log
.append(("getattr", name
))
825 return MT
.__getattribute
__(self
, name
)
826 def __setattr__(self
, name
, value
):
827 log
.append(("setattr", name
, value
))
828 MT
.__setattr
__(self
, name
, value
)
829 def __delattr__(self
, name
):
830 log
.append(("delattr", name
))
831 MT
.__delattr
__(self
, name
)
836 vereq(log
, [("setattr", "foo", 12),
841 if verbose
: print "Testing multiple inheritance..."
847 def setstate(self
, state
):
850 vereq(a
.getstate(), 0)
852 vereq(a
.getstate(), 10)
855 type({}).__init
__(self
)
860 vereq(d
.items(), [("hello", "world")])
861 vereq(d
["hello"], "world")
862 vereq(d
.getstate(), 0)
864 vereq(d
.getstate(), 10)
865 vereq(D
.__mro
__, (D
, dict, C
, object))
870 return int(self
.foo())
873 class Frag(Node
, list):
876 vereq(Node().__int
__(), 23)
877 vereq(int(Node()), 23)
878 vereq(Frag().__int
__(), 42)
879 vereq(int(Frag()), 42)
881 # MI mixing classic and new-style classes.
896 # Classic MRO is preserved for a classic base class.
899 vereq(E
.__mro
__, (E
, D
, B
, A
, C
, object))
902 # But with a mix of classic bases, their MROs are combined using
904 class F(B
, C
, object):
906 vereq(F
.__mro
__, (F
, B
, C
, A
, object))
909 # Try something else.
913 def all_method(self
):
919 def all_method(self
):
922 vereq(M1
.__mro__
, (M1
, C
, object))
924 vereq(m
.cmethod(), "C a")
925 vereq(m
.m1method(), "M1 a")
926 vereq(m
.all_method(), "M1 b")
931 def all_method(self
):
937 def all_method(self
):
940 vereq(M2
.__mro__
, (M2
, D
, C
, object))
942 vereq(m
.cmethod(), "C a")
943 vereq(m
.dmethod(), "D a")
944 vereq(m
.m2method(), "M2 a")
945 vereq(m
.all_method(), "M2 b")
947 class M3(M1
, M2
, object):
950 def all_method(self
):
952 vereq(M3
.__mro__
, (M3
, M1
, M2
, D
, C
, object))
954 vereq(m
.cmethod(), "C a")
955 vereq(m
.dmethod(), "D a")
956 vereq(m
.m1method(), "M1 a")
957 vereq(m
.m2method(), "M2 a")
958 vereq(m
.m3method(), "M3 a")
959 vereq(m
.all_method(), "M3 b")
969 raise TestFailed
, "new class with only classic bases - shouldn't be"
972 if verbose
: print "Testing multiple inheritance special cases..."
974 def spam(self
): return "A"
975 vereq(A().spam(), "A")
977 def boo(self
): return "B"
978 def spam(self
): return "B"
979 vereq(B().spam(), "B")
980 vereq(B().boo(), "B")
982 def boo(self
): return "C"
983 vereq(C().spam(), "A")
984 vereq(C().boo(), "C")
986 vereq(D().spam(), "B")
987 vereq(D().boo(), "B")
988 vereq(D
.__mro
__, (D
, B
, C
, A
, object))
990 vereq(E().spam(), "B")
991 vereq(E().boo(), "C")
992 vereq(E
.__mro
__, (E
, C
, B
, A
, object))
993 # MRO order disagreement
999 raise TestFailed
, "expected MRO order disagreement (F)"
1005 raise TestFailed
, "expected MRO order disagreement (G)"
1008 # see thread python-dev/2002-October/029035.html
1010 if verbose
: print "Testing ex5 from C3 switch discussion..."
1011 class A(object): pass
1012 class B(object): pass
1013 class C(object): pass
1016 class Z(X
,B
,Y
,C
): pass
1017 vereq(Z
.__mro
__, (Z
, X
, B
, Y
, A
, C
, object))
1019 # see "A Monotonic Superclass Linearization for Dylan",
1020 # by Kim Barrett et al. (OOPSLA 1996)
1022 if verbose
: print "Testing MRO monotonicity..."
1023 class Boat(object): pass
1024 class DayBoat(Boat
): pass
1025 class WheelBoat(Boat
): pass
1026 class EngineLess(DayBoat
): pass
1027 class SmallMultihull(DayBoat
): pass
1028 class PedalWheelBoat(EngineLess
,WheelBoat
): pass
1029 class SmallCatamaran(SmallMultihull
): pass
1030 class Pedalo(PedalWheelBoat
,SmallCatamaran
): pass
1032 vereq(PedalWheelBoat
.__mro
__,
1033 (PedalWheelBoat
, EngineLess
, DayBoat
, WheelBoat
, Boat
,
1035 vereq(SmallCatamaran
.__mro
__,
1036 (SmallCatamaran
, SmallMultihull
, DayBoat
, Boat
, object))
1038 vereq(Pedalo
.__mro
__,
1039 (Pedalo
, PedalWheelBoat
, EngineLess
, SmallCatamaran
,
1040 SmallMultihull
, DayBoat
, WheelBoat
, Boat
, object))
1042 # see "A Monotonic Superclass Linearization for Dylan",
1043 # by Kim Barrett et al. (OOPSLA 1996)
1044 def consistency_with_epg():
1045 if verbose
: print "Testing consistentcy with EPG..."
1046 class Pane(object): pass
1047 class ScrollingMixin(object): pass
1048 class EditingMixin(object): pass
1049 class ScrollablePane(Pane
,ScrollingMixin
): pass
1050 class EditablePane(Pane
,EditingMixin
): pass
1051 class EditableScrollablePane(ScrollablePane
,EditablePane
): pass
1053 vereq(EditableScrollablePane
.__mro
__,
1054 (EditableScrollablePane
, ScrollablePane
, EditablePane
,
1055 Pane
, ScrollingMixin
, EditingMixin
, object))
1057 def mro_disagreement():
1058 if verbose
: print "Testing error messages for MRO disagreement..."
1059 def raises(exc
, expected
, callable, *args
):
1063 if not str(msg
).startswith(expected
):
1064 raise TestFailed
, "Message %r, expected %r" % (str(msg
),
1067 raise TestFailed
, "Expected %s" % exc
1068 class A(object): pass
1070 class C(object): pass
1071 # Test some very simple errors
1072 raises(TypeError, "duplicate base class A",
1073 type, "X", (A
, A
), {})
1074 raises(TypeError, "MRO conflict among bases ",
1075 type, "X", (A
, B
), {})
1076 raises(TypeError, "MRO conflict among bases ",
1077 type, "X", (A
, C
, B
), {})
1078 # Test a slightly more complex error
1079 class GridLayout(object): pass
1080 class HorizontalGrid(GridLayout
): pass
1081 class VerticalGrid(GridLayout
): pass
1082 class HVGrid(HorizontalGrid
, VerticalGrid
): pass
1083 class VHGrid(VerticalGrid
, HorizontalGrid
): pass
1084 raises(TypeError, "MRO conflict among bases ",
1085 type, "ConfusedGrid", (HVGrid
, VHGrid
), {})
1088 if verbose
: print "Testing object class..."
1090 vereq(a
.__class
__, object)
1091 vereq(type(a
), object)
1094 verify(not hasattr(a
, "foo"))
1097 except (AttributeError, TypeError):
1100 verify(0, "object() should not allow setting a foo attribute")
1101 verify(not hasattr(object(), "__dict__"))
1103 class Cdict(object):
1106 vereq(x
.__dict
__, {})
1109 vereq(x
.__dict
__, {'foo': 1})
1112 if verbose
: print "Testing __slots__..."
1116 verify(not hasattr(x
, "__dict__"))
1117 verify(not hasattr(x
, "foo"))
1122 verify(not hasattr(x
, "__dict__"))
1123 verify(not hasattr(x
, "a"))
1129 verify(not hasattr(x
, "a"))
1132 __slots__
= ['a', 'b', 'c']
1134 verify(not hasattr(x
, "__dict__"))
1135 verify(not hasattr(x
, 'a'))
1136 verify(not hasattr(x
, 'b'))
1137 verify(not hasattr(x
, 'c'))
1146 """Validate name mangling"""
1148 def __init__(self
, value
):
1153 verify(not hasattr(x
, '__dict__'))
1154 verify(not hasattr(x
, '__a'))
1158 except AttributeError:
1161 raise TestFailed
, "Double underscored names not mangled"
1163 # Make sure slot names are proper identifiers
1170 raise TestFailed
, "[None] slots not caught"
1173 __slots__
= ["foo bar"]
1177 raise TestFailed
, "['foo bar'] slots not caught"
1180 __slots__
= ["foo\0bar"]
1184 raise TestFailed
, "['foo\\0bar'] slots not caught"
1191 raise TestFailed
, "['1'] slots not caught"
1198 raise TestFailed
, "[''] slots not caught"
1200 __slots__
= ["a", "a_b", "_a", "A0123456789Z"]
1203 class Counted(object):
1204 counter
= 0 # counts the number of instances alive
1206 Counted
.counter
+= 1
1208 Counted
.counter
-= 1
1210 __slots__
= ['a', 'b', 'c']
1215 vereq(Counted
.counter
, 3)
1217 vereq(Counted
.counter
, 0)
1223 vereq(Counted
.counter
, 2)
1225 vereq(Counted
.counter
, 0)
1232 vereq(Counted
.counter
, 3)
1234 vereq(Counted
.counter
, 0)
1236 # Test cyclical leaks [SF bug 519621]
1238 __slots__
= ['a', 'b']
1241 s
.a
= [Counted(), s
]
1242 vereq(Counted
.counter
, 1)
1246 vereq(Counted
.counter
, 0)
1248 # Test lookup leaks [SF bug 572567]
1251 def __cmp__(self
, other
):
1254 orig_objects
= len(gc
.get_objects())
1255 for i
in xrange(10):
1257 new_objects
= len(gc
.get_objects())
1258 vereq(orig_objects
, new_objects
)
1261 if verbose
: print "Testing __dict__ and __weakref__ in __slots__..."
1264 __slots__
= ["__dict__"]
1266 verify(hasattr(a
, "__dict__"))
1267 verify(not hasattr(a
, "__weakref__"))
1269 vereq(a
.__dict
__, {"foo": 42})
1272 __slots__
= ["__weakref__"]
1274 verify(hasattr(a
, "__weakref__"))
1275 verify(not hasattr(a
, "__dict__"))
1278 except AttributeError:
1281 raise TestFailed
, "shouldn't be allowed to set a.foo"
1286 verify(hasattr(a
, "__dict__"))
1287 verify(hasattr(a
, "__weakref__"))
1289 vereq(a
.__dict
__, {"foo": 42})
1294 verify(hasattr(a
, "__dict__"))
1295 verify(hasattr(a
, "__weakref__"))
1297 vereq(a
.__dict
__, {"foo": 42})
1299 # MRO order disagreement
1308 if verbose
: print "Testing class attribute propagation..."
1317 # Test that dynamic attributes are inherited
1320 # Test dynamic instances
1324 verify(not hasattr(a
, "foobar"))
1327 C
.method
= lambda self
: 42
1328 vereq(a
.method(), 42)
1329 C
.__repr
__ = lambda self
: "C()"
1330 vereq(repr(a
), "C()")
1331 C
.__int
__ = lambda self
: 100
1334 verify(not hasattr(a
, "spam"))
1335 def mygetattr(self
, name
):
1338 raise AttributeError
1339 C
.__getattr
__ = mygetattr
1340 vereq(a
.spam
, "spam")
1343 def mysetattr(self
, name
, value
):
1345 raise AttributeError
1346 return object.__setattr
__(self
, name
, value
)
1347 C
.__setattr
__ = mysetattr
1350 except AttributeError:
1353 verify(0, "expected AttributeError")
1354 vereq(a
.spam
, "spam")
1361 # Test handling of int*seq and seq*int
1364 vereq("a"*I(2), "aa")
1365 vereq(I(2)*"a", "aa")
1370 # Test handling of long*seq and seq*long
1373 vereq("a"*L(2L), "aa")
1374 vereq(L(2L)*"a", "aa")
1379 # Test comparison of classes with dynamic metaclasses
1380 class dynamicmetaclass(type):
1383 __metaclass__
= dynamicmetaclass
1384 verify(someclass
!= object)
1387 if verbose
: print "Testing errors..."
1390 class C(list, dict):
1395 verify(0, "inheritance from both list and dict should be illegal")
1398 class C(object, None):
1403 verify(0, "inheritance from non-type should be illegal")
1413 verify(0, "inheritance from CFunction should be illegal")
1421 verify(0, "__slots__ = 1 should be illegal")
1429 verify(0, "__slots__ = [1] should be illegal")
1432 if verbose
: print "Testing class methods..."
1434 def foo(*a
): return a
1435 goo
= classmethod(foo
)
1437 vereq(C
.goo(1), (C
, 1))
1438 vereq(c
.goo(1), (C
, 1))
1439 vereq(c
.foo(1), (c
, 1))
1443 vereq(D
.goo(1), (D
, 1))
1444 vereq(d
.goo(1), (D
, 1))
1445 vereq(d
.foo(1), (d
, 1))
1446 vereq(D
.foo(d
, 1), (d
, 1))
1447 # Test for a specific crash (SF bug 528132)
1448 def f(cls
, arg
): return (cls
, arg
)
1450 vereq(ff
.__get
__(0, int)(42), (int, 42))
1451 vereq(ff
.__get
__(0)(42), (int, 42))
1453 # Test super() with classmethods (SF bug 535444)
1454 veris(C
.goo
.im_self
, C
)
1455 veris(D
.goo
.im_self
, D
)
1456 veris(super(D
,D
).goo
.im_self
, D
)
1457 veris(super(D
,d
).goo
.im_self
, D
)
1458 vereq(super(D
,D
).goo(), (D
,))
1459 vereq(super(D
,d
).goo(), (D
,))
1461 def classmethods_in_c():
1462 if verbose
: print "Testing C-based class methods..."
1463 import xxsubtype
as spam
1466 x
, a1
, d1
= spam
.spamlist
.classmeth(*a
, **d
)
1467 veris(x
, spam
.spamlist
)
1470 x
, a1
, d1
= spam
.spamlist().classmeth(*a
, **d
)
1471 veris(x
, spam
.spamlist
)
1475 def staticmethods():
1476 if verbose
: print "Testing static methods..."
1478 def foo(*a
): return a
1479 goo
= staticmethod(foo
)
1481 vereq(C
.goo(1), (1,))
1482 vereq(c
.goo(1), (1,))
1483 vereq(c
.foo(1), (c
, 1,))
1487 vereq(D
.goo(1), (1,))
1488 vereq(d
.goo(1), (1,))
1489 vereq(d
.foo(1), (d
, 1))
1490 vereq(D
.foo(d
, 1), (d
, 1))
1492 def staticmethods_in_c():
1493 if verbose
: print "Testing C-based static methods..."
1494 import xxsubtype
as spam
1497 x
, a1
, d1
= spam
.spamlist
.staticmeth(*a
, **d
)
1501 x
, a1
, d2
= spam
.spamlist().staticmeth(*a
, **d
)
1507 if verbose
: print "Testing classic classes..."
1509 def foo(*a
): return a
1510 goo
= classmethod(foo
)
1512 vereq(C
.goo(1), (C
, 1))
1513 vereq(c
.goo(1), (C
, 1))
1514 vereq(c
.foo(1), (c
, 1))
1518 vereq(D
.goo(1), (D
, 1))
1519 vereq(d
.goo(1), (D
, 1))
1520 vereq(d
.foo(1), (d
, 1))
1521 vereq(D
.foo(d
, 1), (d
, 1))
1522 class E
: # *not* subclassing from C
1524 vereq(E().foo
, C
.foo
) # i.e., unbound
1525 verify(repr(C
.foo
.__get
__(C())).startswith("<bound method "))
1528 if verbose
: print "Testing computed attributes..."
1530 class computed_attribute(object):
1531 def __init__(self
, get
, set=None, delete
=None):
1534 self
.__delete
= delete
1535 def __get__(self
, obj
, type=None):
1536 return self
.__get
(obj
)
1537 def __set__(self
, obj
, value
):
1538 return self
.__set
(obj
, value
)
1539 def __delete__(self
, obj
):
1540 return self
.__delete
(obj
)
1547 def __set_x(self
, x
):
1549 def __delete_x(self
):
1551 x
= computed_attribute(__get_x
, __set_x
, __delete_x
)
1559 vereq(hasattr(a
, 'x'), 0)
1562 if verbose
: print "Testing __new__ slot override..."
1565 self
= list.__new
__(cls
)
1569 self
.foo
= self
.foo
+ 2
1572 verify(a
.__class
__ is C
)
1577 verify(b
.__class
__ is D
)
1580 if verbose
: print "Testing mro() and overriding it..."
1582 def f(self
): return "A"
1586 def f(self
): return "C"
1589 vereq(D
.mro(), [D
, B
, C
, A
, object])
1590 vereq(D
.__mro
__, (D
, B
, C
, A
, object))
1593 class PerverseMetaType(type):
1599 __metaclass__
= PerverseMetaType
1600 vereq(X
.__mro
__, (object, A
, C
, B
, D
, X
))
1604 if verbose
: print "Testing operator overloading..."
1607 "Intermediate class because object doesn't have a __setattr__"
1611 def __getattr__(self
, name
):
1613 return ("getattr", name
)
1615 raise AttributeError
1616 def __setattr__(self
, name
, value
):
1618 self
.setattr = (name
, value
)
1620 return B
.__setattr
__(self
, name
, value
)
1621 def __delattr__(self
, name
):
1625 return B
.__delattr
__(self
, name
)
1627 def __getitem__(self
, key
):
1628 return ("getitem", key
)
1629 def __setitem__(self
, key
, value
):
1630 self
.setitem
= (key
, value
)
1631 def __delitem__(self
, key
):
1634 def __getslice__(self
, i
, j
):
1635 return ("getslice", i
, j
)
1636 def __setslice__(self
, i
, j
, value
):
1637 self
.setslice
= (i
, j
, value
)
1638 def __delslice__(self
, i
, j
):
1639 self
.delslice
= (i
, j
)
1642 vereq(a
.foo
, ("getattr", "foo"))
1644 vereq(a
.setattr, ("foo", 12))
1646 vereq(a
.delattr, "foo")
1648 vereq(a
[12], ("getitem", 12))
1650 vereq(a
.setitem
, (12, 21))
1652 vereq(a
.delitem
, 12)
1654 vereq(a
[0:10], ("getslice", 0, 10))
1656 vereq(a
.setslice
, (0, 10, "foo"))
1658 vereq(a
.delslice
, (0, 10))
1661 if verbose
: print "Testing methods..."
1663 def __init__(self
, x
):
1678 vereq(E().foo
, C
.foo
) # i.e., unbound
1679 verify(repr(C
.foo
.__get
__(C(1))).startswith("<bound method "))
1682 # Test operators like __hash__ for which a built-in default exists
1683 if verbose
: print "Testing special operators..."
1684 # Test the default behavior for static classes
1686 def __getitem__(self
, i
):
1687 if 0 <= i
< 10: return i
1692 vereq(hash(c1
), id(c1
))
1693 vereq(cmp(c1
, c2
), cmp(id(c1
), id(c2
)))
1696 verify(not c1
!= c1
)
1697 verify(not c1
== c2
)
1698 # Note that the module name appears in str/repr, and that varies
1699 # depending on whether this test is run standalone or from a framework.
1700 verify(str(c1
).find('C object at ') >= 0)
1701 vereq(str(c1
), repr(c1
))
1702 verify(-1 not in c1
)
1705 verify(10 not in c1
)
1706 # Test the default behavior for dynamic classes
1708 def __getitem__(self
, i
):
1709 if 0 <= i
< 10: return i
1714 vereq(hash(d1
), id(d1
))
1715 vereq(cmp(d1
, d2
), cmp(id(d1
), id(d2
)))
1718 verify(not d1
!= d1
)
1719 verify(not d1
== d2
)
1720 # Note that the module name appears in str/repr, and that varies
1721 # depending on whether this test is run standalone or from a framework.
1722 verify(str(d1
).find('D object at ') >= 0)
1723 vereq(str(d1
), repr(d1
))
1724 verify(-1 not in d1
)
1727 verify(10 not in d1
)
1728 # Test overridden behavior for static classes
1729 class Proxy(object):
1730 def __init__(self
, x
):
1732 def __nonzero__(self
):
1733 return not not self
.x
1736 def __eq__(self
, other
):
1737 return self
.x
== other
1738 def __ne__(self
, other
):
1739 return self
.x
!= other
1740 def __cmp__(self
, other
):
1741 return cmp(self
.x
, other
.x
)
1743 return "Proxy:%s" % self
.x
1745 return "Proxy(%r)" % self
.x
1746 def __contains__(self
, value
):
1747 return value
in self
.x
1753 vereq(hash(p0
), hash(0))
1756 verify(not p0
!= p0
)
1758 vereq(cmp(p0
, p1
), -1)
1759 vereq(cmp(p0
, p0
), 0)
1760 vereq(cmp(p0
, p_1
), 1)
1761 vereq(str(p0
), "Proxy:0")
1762 vereq(repr(p0
), "Proxy(0)")
1763 p10
= Proxy(range(10))
1764 verify(-1 not in p10
)
1767 verify(10 not in p10
)
1768 # Test overridden behavior for dynamic classes
1769 class DProxy(object):
1770 def __init__(self
, x
):
1772 def __nonzero__(self
):
1773 return not not self
.x
1776 def __eq__(self
, other
):
1777 return self
.x
== other
1778 def __ne__(self
, other
):
1779 return self
.x
!= other
1780 def __cmp__(self
, other
):
1781 return cmp(self
.x
, other
.x
)
1783 return "DProxy:%s" % self
.x
1785 return "DProxy(%r)" % self
.x
1786 def __contains__(self
, value
):
1787 return value
in self
.x
1793 vereq(hash(p0
), hash(0))
1796 verify(not p0
!= p0
)
1798 vereq(cmp(p0
, p1
), -1)
1799 vereq(cmp(p0
, p0
), 0)
1800 vereq(cmp(p0
, p_1
), 1)
1801 vereq(str(p0
), "DProxy:0")
1802 vereq(repr(p0
), "DProxy(0)")
1803 p10
= DProxy(range(10))
1804 verify(-1 not in p10
)
1807 verify(10 not in p10
)
1808 # Safety test for __cmp__
1809 def unsafecmp(a
, b
):
1811 a
.__class
__.__cmp
__(a
, b
)
1815 raise TestFailed
, "shouldn't allow %s.__cmp__(%r, %r)" % (
1817 unsafecmp(u
"123", "123")
1818 unsafecmp("123", u
"123")
1825 def __new__(cls
, letter
):
1827 return str.__new
__(cls
)
1828 return str.__new
__(cls
, letter
)
1834 # sys.stdout needs to be the original to trigger the recursion bug
1836 test_stdout
= sys
.stdout
1837 sys
.stdout
= get_original_stdout()
1839 # nothing should actually be printed, this should raise an exception
1841 except RuntimeError:
1844 raise TestFailed
, "expected a RuntimeError for print recursion"
1845 sys
.stdout
= test_stdout
1848 if verbose
: print "Testing weak references..."
1858 class NoWeak(object):
1863 except TypeError, msg
:
1864 verify(str(msg
).find("weak reference") >= 0)
1866 verify(0, "weakref.ref(no) should be illegal")
1868 __slots__
= ['foo', '__weakref__']
1870 r
= weakref
.ref(yes
)
1877 if verbose
: print "Testing property..."
1881 def setx(self
, value
):
1885 x
= property(getx
, setx
, delx
, doc
="I'm the x property.")
1887 verify(not hasattr(a
, "x"))
1892 verify(not hasattr(a
, "x"))
1893 verify(not hasattr(a
, "_C__x"))
1895 vereq(C
.x
.__get
__(a
), 100)
1897 verify(not hasattr(a
, "x"))
1899 raw
= C
.__dict
__['x']
1900 verify(isinstance(raw
, property))
1903 verify("__doc__" in attrs
)
1904 verify("fget" in attrs
)
1905 verify("fset" in attrs
)
1906 verify("fdel" in attrs
)
1908 vereq(raw
.__doc
__, "I'm the x property.")
1909 verify(raw
.fget
is C
.__dict
__['getx'])
1910 verify(raw
.fset
is C
.__dict
__['setx'])
1911 verify(raw
.fdel
is C
.__dict
__['delx'])
1913 for attr
in "__doc__", "fget", "fset", "fdel":
1915 setattr(raw
, attr
, 42)
1916 except TypeError, msg
:
1917 if str(msg
).find('readonly') < 0:
1918 raise TestFailed("when setting readonly attr %r on a "
1919 "property, got unexpected TypeError "
1920 "msg %r" % (attr
, str(msg
)))
1922 raise TestFailed("expected TypeError from trying to set "
1923 "readonly %r attr on a property" % attr
)
1926 __getitem__
= property(lambda s
: 1/0)
1932 except ZeroDivisionError:
1935 raise TestFailed
, "expected ZeroDivisionError from bad property"
1938 if verbose
: print "Testing super..."
1944 vereq(A().meth(1), "A(1)")
1948 self
.__super
= super(B
, self
)
1950 return "B(%r)" % a
+ self
.__super
.meth(a
)
1952 vereq(B().meth(2), "B(2)A(2)")
1956 return "C(%r)" % a
+ self
.__super
.meth(a
)
1957 C
._C
__super
= super(C
)
1959 vereq(C().meth(3), "C(3)A(3)")
1963 return "D(%r)" % a
+ super(D
, self
).meth(a
)
1965 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
1967 # Test for subclassing super
1969 class mysuper(super):
1970 def __init__(self
, *args
):
1971 return super(mysuper
, self
).__init
__(*args
)
1975 return "E(%r)" % a
+ mysuper(E
, self
).meth(a
)
1977 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
1982 return "F(%r)[%s]" % (a
, s
.__class
__.__name
__) + s
.meth(a
)
1983 F
._F
__super
= mysuper(F
)
1985 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
1987 # Make sure certain errors are raised
1994 raise TestFailed
, "shouldn't allow super(D, 42)"
2001 raise TestFailed
, "shouldn't allow super(D, C())"
2004 super(D
).__get
__(12)
2008 raise TestFailed
, "shouldn't allow super(D).__get__(12)"
2011 super(D
).__get
__(C())
2015 raise TestFailed
, "shouldn't allow super(D).__get__(C())"
2018 if verbose
: print "Testing inheritance from basic types..."
2023 def __add__(self
, other
):
2024 return hexint(int.__add
__(self
, other
))
2025 # (Note that overriding __radd__ doesn't work,
2026 # because the int type gets first dibs.)
2027 vereq(repr(hexint(7) + 9), "0x10")
2028 vereq(repr(hexint(1000) + 7), "0x3ef")
2031 vereq(int(a
), 12345)
2032 verify(int(a
).__class
__ is int)
2033 vereq(hash(a
), hash(12345))
2034 verify((+a
).__class
__ is int)
2035 verify((a
>> 0).__class
__ is int)
2036 verify((a
<< 0).__class
__ is int)
2037 verify((hexint(0) << 12).__class
__ is int)
2038 verify((hexint(0) >> 12).__class
__ is int)
2040 class octlong(long):
2047 def __add__(self
, other
):
2048 return self
.__class
__(super(octlong
, self
).__add
__(other
))
2050 vereq(str(octlong(3) + 5), "010")
2051 # (Note that overriding __radd__ here only seems to work
2052 # because the example uses a short int left argument.)
2053 vereq(str(5 + octlong(3000)), "05675")
2056 vereq(long(a
), 12345L)
2057 vereq(hash(a
), hash(12345L))
2058 verify(long(a
).__class
__ is long)
2059 verify((+a
).__class
__ is long)
2060 verify((-a
).__class
__ is long)
2061 verify((-octlong(0)).__class
__ is long)
2062 verify((a
>> 0).__class
__ is long)
2063 verify((a
<< 0).__class
__ is long)
2064 verify((a
- 0).__class
__ is long)
2065 verify((a
* 1).__class
__ is long)
2066 verify((a
** 1).__class
__ is long)
2067 verify((a
// 1).__class
__ is long)
2068 verify((1 * a
).__class
__ is long)
2069 verify((a |
0).__class
__ is long)
2070 verify((a ^
0).__class
__ is long)
2071 verify((a
& -1L).__class
__ is long)
2072 verify((octlong(0) << 12).__class
__ is long)
2073 verify((octlong(0) >> 12).__class
__ is long)
2074 verify(abs(octlong(0)).__class
__ is long)
2076 # Because octlong overrides __add__, we can't check the absence of +0
2077 # optimizations using octlong.
2078 class longclone(long):
2081 verify((a
+ 0).__class
__ is long)
2082 verify((0 + a
).__class
__ is long)
2084 # Check that negative clones don't segfault
2086 vereq(a
.__dict
__, {})
2087 vereq(long(a
), -1) # verify PyNumber_Long() copies the sign bit
2089 class precfloat(float):
2090 __slots__
= ['prec']
2091 def __init__(self
, value
=0.0, prec
=12):
2092 self
.prec
= int(prec
)
2093 float.__init
__(value
)
2095 return "%.*g" % (self
.prec
, self
)
2096 vereq(repr(precfloat(1.1)), "1.1")
2097 a
= precfloat(12345)
2099 vereq(float(a
), 12345.0)
2100 verify(float(a
).__class
__ is float)
2101 vereq(hash(a
), hash(12345.0))
2102 verify((+a
).__class
__ is float)
2104 class madcomplex(complex):
2106 return "%.17gj%+.17g" % (self
.imag
, self
.real
)
2107 a
= madcomplex(-3, 4)
2108 vereq(repr(a
), "4j-3")
2109 base
= complex(-3, 4)
2110 veris(base
.__class
__, complex)
2112 vereq(complex(a
), base
)
2113 veris(complex(a
).__class
__, complex)
2114 a
= madcomplex(a
) # just trying another form of the constructor
2115 vereq(repr(a
), "4j-3")
2117 vereq(complex(a
), base
)
2118 veris(complex(a
).__class
__, complex)
2119 vereq(hash(a
), hash(base
))
2120 veris((+a
).__class
__, complex)
2121 veris((a
+ 0).__class
__, complex)
2123 veris((a
- 0).__class
__, complex)
2125 veris((a
* 1).__class
__, complex)
2127 veris((a
/ 1).__class
__, complex)
2130 class madtuple(tuple):
2133 if self
._rev
is not None:
2137 self
._rev
= self
.__class
__(L
)
2139 a
= madtuple((1,2,3,4,5,6,7,8,9,0))
2140 vereq(a
, (1,2,3,4,5,6,7,8,9,0))
2141 vereq(a
.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2142 vereq(a
.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2143 for i
in range(512):
2144 t
= madtuple(range(i
))
2148 a
= madtuple((1,2,3,4,5))
2149 vereq(tuple(a
), (1,2,3,4,5))
2150 verify(tuple(a
).__class
__ is tuple)
2151 vereq(hash(a
), hash((1,2,3,4,5)))
2152 verify(a
[:].__class
__ is tuple)
2153 verify((a
* 1).__class
__ is tuple)
2154 verify((a
* 0).__class
__ is tuple)
2155 verify((a
+ ()).__class
__ is tuple)
2158 verify(tuple(a
).__class
__ is tuple)
2159 verify((a
+ a
).__class
__ is tuple)
2160 verify((a
* 0).__class
__ is tuple)
2161 verify((a
* 1).__class
__ is tuple)
2162 verify((a
* 2).__class
__ is tuple)
2163 verify(a
[:].__class
__ is tuple)
2165 class madstring(str):
2168 if self
._rev
is not None:
2172 self
._rev
= self
.__class
__("".join(L
))
2174 s
= madstring("abcdefghijklmnopqrstuvwxyz")
2175 vereq(s
, "abcdefghijklmnopqrstuvwxyz")
2176 vereq(s
.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2177 vereq(s
.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2178 for i
in range(256):
2179 s
= madstring("".join(map(chr, range(i
))))
2183 s
= madstring("12345")
2184 vereq(str(s
), "12345")
2185 verify(str(s
).__class
__ is str)
2191 verify(str(s
).__class
__ is str)
2192 vereq(hash(s
), hash(base
))
2193 vereq({s
: 1}[base
], 1)
2194 vereq({base
: 1}[s
], 1)
2195 verify((s
+ "").__class
__ is str)
2197 verify(("" + s
).__class
__ is str)
2199 verify((s
* 0).__class
__ is str)
2201 verify((s
* 1).__class
__ is str)
2203 verify((s
* 2).__class
__ is str)
2204 vereq(s
* 2, base
+ base
)
2205 verify(s
[:].__class
__ is str)
2207 verify(s
[0:0].__class
__ is str)
2209 verify(s
.strip().__class
__ is str)
2210 vereq(s
.strip(), base
)
2211 verify(s
.lstrip().__class
__ is str)
2212 vereq(s
.lstrip(), base
)
2213 verify(s
.rstrip().__class
__ is str)
2214 vereq(s
.rstrip(), base
)
2215 identitytab
= ''.join([chr(i
) for i
in range(256)])
2216 verify(s
.translate(identitytab
).__class
__ is str)
2217 vereq(s
.translate(identitytab
), base
)
2218 verify(s
.translate(identitytab
, "x").__class
__ is str)
2219 vereq(s
.translate(identitytab
, "x"), base
)
2220 vereq(s
.translate(identitytab
, "\x00"), "")
2221 verify(s
.replace("x", "x").__class
__ is str)
2222 vereq(s
.replace("x", "x"), base
)
2223 verify(s
.ljust(len(s
)).__class
__ is str)
2224 vereq(s
.ljust(len(s
)), base
)
2225 verify(s
.rjust(len(s
)).__class
__ is str)
2226 vereq(s
.rjust(len(s
)), base
)
2227 verify(s
.center(len(s
)).__class
__ is str)
2228 vereq(s
.center(len(s
)), base
)
2229 verify(s
.lower().__class
__ is str)
2230 vereq(s
.lower(), base
)
2232 s
= madstring("x y")
2234 verify(intern(s
).__class
__ is str)
2235 verify(intern(s
) is intern("x y"))
2236 vereq(intern(s
), "x y")
2239 s
= madstring("y x")
2241 verify(intern(s
).__class
__ is str)
2242 verify(intern(s
) is i
)
2245 verify(intern(s
).__class
__ is str)
2246 verify(intern(s
) is i
)
2248 class madunicode(unicode):
2251 if self
._rev
is not None:
2255 self
._rev
= self
.__class
__(u
"".join(L
))
2257 u
= madunicode("ABCDEF")
2259 vereq(u
.rev(), madunicode(u
"FEDCBA"))
2260 vereq(u
.rev().rev(), madunicode(u
"ABCDEF"))
2262 u
= madunicode(base
)
2263 vereq(unicode(u
), base
)
2264 verify(unicode(u
).__class
__ is unicode)
2265 vereq(hash(u
), hash(base
))
2266 vereq({u
: 1}[base
], 1)
2267 vereq({base
: 1}[u
], 1)
2268 verify(u
.strip().__class
__ is unicode)
2269 vereq(u
.strip(), base
)
2270 verify(u
.lstrip().__class
__ is unicode)
2271 vereq(u
.lstrip(), base
)
2272 verify(u
.rstrip().__class
__ is unicode)
2273 vereq(u
.rstrip(), base
)
2274 verify(u
.replace(u
"x", u
"x").__class
__ is unicode)
2275 vereq(u
.replace(u
"x", u
"x"), base
)
2276 verify(u
.replace(u
"xy", u
"xy").__class
__ is unicode)
2277 vereq(u
.replace(u
"xy", u
"xy"), base
)
2278 verify(u
.center(len(u
)).__class
__ is unicode)
2279 vereq(u
.center(len(u
)), base
)
2280 verify(u
.ljust(len(u
)).__class
__ is unicode)
2281 vereq(u
.ljust(len(u
)), base
)
2282 verify(u
.rjust(len(u
)).__class
__ is unicode)
2283 vereq(u
.rjust(len(u
)), base
)
2284 verify(u
.lower().__class
__ is unicode)
2285 vereq(u
.lower(), base
)
2286 verify(u
.upper().__class
__ is unicode)
2287 vereq(u
.upper(), base
)
2288 verify(u
.capitalize().__class
__ is unicode)
2289 vereq(u
.capitalize(), base
)
2290 verify(u
.title().__class
__ is unicode)
2291 vereq(u
.title(), base
)
2292 verify((u
+ u
"").__class
__ is unicode)
2293 vereq(u
+ u
"", base
)
2294 verify((u
"" + u
).__class
__ is unicode)
2295 vereq(u
"" + u
, base
)
2296 verify((u
* 0).__class
__ is unicode)
2298 verify((u
* 1).__class
__ is unicode)
2300 verify((u
* 2).__class
__ is unicode)
2301 vereq(u
* 2, base
+ base
)
2302 verify(u
[:].__class
__ is unicode)
2304 verify(u
[0:0].__class
__ is unicode)
2307 class sublist(list):
2309 a
= sublist(range(5))
2312 vereq(a
, range(5) + ["hello"])
2315 a
.extend(range(6, 20))
2322 vereq(list(a
), range(10))
2327 vereq(a
[:5], range(5))
2329 class CountedInput(file):
2330 """Counts lines read by self.readline().
2332 self.lineno is the 0-based ordinal of the last line read, up to
2333 a maximum of one greater than the number of lines in the file.
2335 self.ateof is true if and only if the final "" line has been read,
2336 at which point self.lineno stops incrementing, and further calls
2337 to readline() continue to return "".
2345 s
= file.readline(self
)
2346 # Next line works too.
2347 # s = super(CountedInput, self).readline()
2353 f
= file(name
=TESTFN
, mode
='w')
2354 lines
= ['a\n', 'b\n', 'c\n']
2358 f
= CountedInput(TESTFN
)
2359 for (i
, expected
) in zip(range(1, 5) + [4], lines
+ 2 * [""]):
2361 vereq(expected
, got
)
2363 vereq(f
.ateof
, (i
> len(lines
)))
2378 print "Testing keyword args to basic type constructors ..."
2380 vereq(float(x
=2), 2.0)
2381 vereq(long(x
=3), 3L)
2382 vereq(complex(imag
=42, real
=666), complex(666, 42))
2383 vereq(str(object=500), '500')
2384 vereq(unicode(string
='abc', errors
='strict'), u
'abc')
2385 vereq(tuple(sequence
=range(3)), (0, 1, 2))
2386 vereq(list(sequence
=(0, 1, 2)), range(3))
2387 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2389 for constructor
in (int, float, long, complex, str, unicode,
2392 constructor(bogus_keyword_arg
=1)
2396 raise TestFailed("expected TypeError from bogus keyword "
2397 "argument to %r" % constructor
)
2400 # XXX This test is disabled because rexec is not deemed safe
2404 print "Testing interaction with restricted execution ..."
2406 sandbox
= rexec
.RExec()
2408 code1
= """f = open(%r, 'w')""" % TESTFN
2409 code2
= """f = file(%r, 'w')""" % TESTFN
2412 t = type(f) # a sneaky way to get the file() constructor
2414 f = t(%r, 'w') # rexec can't catch this by itself
2415 """ % (TESTFN
, TESTFN
)
2417 f
= open(TESTFN
, 'w') # Create the file so code3 can find it.
2421 for code
in code1
, code2
, code3
:
2423 sandbox
.r_exec(code
)
2424 except IOError, msg
:
2425 if str(msg
).find("restricted") >= 0:
2428 outcome
= "got an exception, but not an expected one"
2430 outcome
= "expected a restricted-execution exception"
2433 raise TestFailed("%s, in %r" % (outcome
, code
))
2442 def str_subclass_as_dict_key():
2444 print "Testing a str subclass used as dict key .."
2447 """Sublcass of str that computes __eq__ case-insensitively.
2449 Also computes a hash code of the string in canonical form.
2452 def __init__(self
, value
):
2453 self
.canonical
= value
.lower()
2454 self
.hashcode
= hash(self
.canonical
)
2456 def __eq__(self
, other
):
2457 if not isinstance(other
, cistr
):
2458 other
= cistr(other
)
2459 return self
.canonical
== other
.canonical
2462 return self
.hashcode
2464 vereq(cistr('ABC'), 'abc')
2465 vereq('aBc', cistr('ABC'))
2466 vereq(str(cistr('ABC')), 'ABC')
2468 d
= {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2469 vereq(d
[cistr('one')], 1)
2470 vereq(d
[cistr('tWo')], 2)
2471 vereq(d
[cistr('THrEE')], 3)
2472 verify(cistr('ONe') in d
)
2473 vereq(d
.get(cistr('thrEE')), 3)
2475 def classic_comparisons():
2476 if verbose
: print "Testing classic comparisons..."
2479 for base
in (classic
, int, object):
2480 if verbose
: print " (base = %s)" % base
2482 def __init__(self
, value
):
2483 self
.value
= int(value
)
2484 def __cmp__(self
, other
):
2485 if isinstance(other
, C
):
2486 return cmp(self
.value
, other
.value
)
2487 if isinstance(other
, int) or isinstance(other
, long):
2488 return cmp(self
.value
, other
)
2489 return NotImplemented
2494 c
= {1: c1
, 2: c2
, 3: c3
}
2497 verify(cmp(c
[x
], c
[y
]) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2498 for op
in "<", "<=", "==", "!=", ">", ">=":
2499 verify(eval("c[x] %s c[y]" % op
) == eval("x %s y" % op
),
2500 "x=%d, y=%d" % (x
, y
))
2501 verify(cmp(c
[x
], y
) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2502 verify(cmp(x
, c
[y
]) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2504 def rich_comparisons():
2506 print "Testing rich comparisons..."
2513 def __eq__(self
, other
):
2515 return abs(self
- other
) <= 1e-6
2517 return NotImplemented
2524 for base
in (classic
, int, object, list):
2525 if verbose
: print " (base = %s)" % base
2527 def __init__(self
, value
):
2528 self
.value
= int(value
)
2529 def __cmp__(self
, other
):
2530 raise TestFailed
, "shouldn't call __cmp__"
2531 def __eq__(self
, other
):
2532 if isinstance(other
, C
):
2533 return self
.value
== other
.value
2534 if isinstance(other
, int) or isinstance(other
, long):
2535 return self
.value
== other
2536 return NotImplemented
2537 def __ne__(self
, other
):
2538 if isinstance(other
, C
):
2539 return self
.value
!= other
.value
2540 if isinstance(other
, int) or isinstance(other
, long):
2541 return self
.value
!= other
2542 return NotImplemented
2543 def __lt__(self
, other
):
2544 if isinstance(other
, C
):
2545 return self
.value
< other
.value
2546 if isinstance(other
, int) or isinstance(other
, long):
2547 return self
.value
< other
2548 return NotImplemented
2549 def __le__(self
, other
):
2550 if isinstance(other
, C
):
2551 return self
.value
<= other
.value
2552 if isinstance(other
, int) or isinstance(other
, long):
2553 return self
.value
<= other
2554 return NotImplemented
2555 def __gt__(self
, other
):
2556 if isinstance(other
, C
):
2557 return self
.value
> other
.value
2558 if isinstance(other
, int) or isinstance(other
, long):
2559 return self
.value
> other
2560 return NotImplemented
2561 def __ge__(self
, other
):
2562 if isinstance(other
, C
):
2563 return self
.value
>= other
.value
2564 if isinstance(other
, int) or isinstance(other
, long):
2565 return self
.value
>= other
2566 return NotImplemented
2571 c
= {1: c1
, 2: c2
, 3: c3
}
2574 for op
in "<", "<=", "==", "!=", ">", ">=":
2575 verify(eval("c[x] %s c[y]" % op
) == eval("x %s y" % op
),
2576 "x=%d, y=%d" % (x
, y
))
2577 verify(eval("c[x] %s y" % op
) == eval("x %s y" % op
),
2578 "x=%d, y=%d" % (x
, y
))
2579 verify(eval("x %s c[y]" % op
) == eval("x %s y" % op
),
2580 "x=%d, y=%d" % (x
, y
))
2583 if verbose
: print "Testing coercions..."
2592 class F(float): pass
2599 class C(complex): pass
2610 if verbose
: print "Testing descriptor doc strings..."
2611 def check(descr
, what
):
2612 vereq(descr
.__doc
__, what
)
2613 check(file.closed
, "True if the file is closed") # getset descriptor
2614 check(file.name
, "file name") # member descriptor
2617 if verbose
: print "Testing __class__ assignment..."
2618 class C(object): pass
2619 class D(object): pass
2620 class E(object): pass
2622 for cls
in C
, D
, E
, F
:
2623 for cls2
in C
, D
, E
, F
:
2626 verify(x
.__class
__ is cls2
)
2628 verify(x
.__class
__ is cls
)
2635 raise TestFailed
, "shouldn't allow %r.__class__ = %r" % (x
, C
)
2637 delattr(x
, "__class__")
2641 raise TestFailed
, "shouldn't allow del %r.__class__" % x
2646 cant(object(), list)
2647 cant(list(), object)
2648 class Int(int): __slots__
= []
2659 if verbose
: print "Testing __dict__ assignment..."
2660 class C(object): pass
2662 a
.__dict
__ = {'b': 1}
2670 raise TestFailed
, "shouldn't allow %r.__dict__ = %r" % (x
, dict)
2674 del a
.__dict
__ # Deleting __dict__ is allowed
2675 # Classes don't allow __dict__ assignment
2680 print "Testing pickling and copying new-style classes and objects..."
2681 import pickle
, cPickle
2690 def __init__(self
, a
, b
):
2691 super(C
, self
).__init
__()
2695 return "C(%r, %r)" % (self
.a
, self
.b
)
2699 def __new__(cls
, a
, b
):
2700 return super(C1
, cls
).__new
__(cls
)
2701 def __init__(self
, a
, b
):
2705 return "C1(%r, %r)<%r>" % (self
.a
, self
.b
, list(self
))
2709 def __new__(cls
, a
, b
, val
=0):
2710 return super(C2
, cls
).__new
__(cls
, val
)
2711 def __init__(self
, a
, b
, val
=0):
2715 return "C2(%r, %r)<%r>" % (self
.a
, self
.b
, int(self
))
2719 def __init__(self
, foo
):
2721 def __getstate__(self
):
2723 def __setstate__(self
, foo
):
2726 global C4classic
, C4
2727 class C4classic
: # classic
2729 class C4(C4classic
, object): # mixed inheritance
2732 for p
in pickle
, cPickle
:
2735 print p
.__name
__, ["text", "binary"][bin
]
2737 for cls
in C
, C1
, C2
:
2738 s
= p
.dumps(cls
, bin
)
2742 a
= C1(1, 2); a
.append(42); a
.append(24)
2743 b
= C2("hello", "world", 42)
2744 s
= p
.dumps((a
, b
), bin
)
2746 vereq(x
.__class
__, a
.__class
__)
2747 vereq(sorteditems(x
.__dict
__), sorteditems(a
.__dict
__))
2748 vereq(y
.__class
__, b
.__class
__)
2749 vereq(sorteditems(y
.__dict
__), sorteditems(b
.__dict
__))
2755 # Test for __getstate__ and __setstate__ on new style class
2759 veris(u
.__class
__, v
.__class
__)
2761 # Test for picklability of hybrid class
2766 veris(u
.__class
__, v
.__class
__)
2769 # Testing copy.deepcopy()
2773 for cls
in C
, C1
, C2
:
2774 cls2
= copy
.deepcopy(cls
)
2777 a
= C1(1, 2); a
.append(42); a
.append(24)
2778 b
= C2("hello", "world", 42)
2779 x
, y
= copy
.deepcopy((a
, b
))
2780 vereq(x
.__class
__, a
.__class
__)
2781 vereq(sorteditems(x
.__dict
__), sorteditems(a
.__dict
__))
2782 vereq(y
.__class
__, b
.__class
__)
2783 vereq(sorteditems(y
.__dict
__), sorteditems(b
.__dict
__))
2791 if verbose
: print "Testing pickling of classes with __slots__ ..."
2792 import pickle
, cPickle
2793 # Pickling of classes with __slots__ but without __getstate__ should fail
2797 for base
in [object, B
]:
2807 raise TestFailed
, "should fail: pickle C instance - %s" % base
2813 raise TestFailed
, "should fail: cPickle C instance - %s" % base
2819 raise TestFailed
, "should fail: pickle D instance - %s" % base
2825 raise TestFailed
, "should fail: cPickle D instance - %s" % base
2826 # Give C a __getstate__ and __setstate__
2829 def __getstate__(self
):
2831 d
= self
.__dict
__.copy()
2832 except AttributeError:
2836 except AttributeError:
2839 def __setstate__(self
, d
):
2840 for k
, v
in d
.items():
2844 # Now it should work
2846 y
= pickle
.loads(pickle
.dumps(x
))
2847 vereq(hasattr(y
, 'a'), 0)
2848 y
= cPickle
.loads(cPickle
.dumps(x
))
2849 vereq(hasattr(y
, 'a'), 0)
2851 y
= pickle
.loads(pickle
.dumps(x
))
2853 y
= cPickle
.loads(cPickle
.dumps(x
))
2858 y
= pickle
.loads(pickle
.dumps(x
))
2859 vereq(y
.a
+ y
.b
, 142)
2860 y
= cPickle
.loads(cPickle
.dumps(x
))
2861 vereq(y
.a
+ y
.b
, 142)
2862 # But a subclass that adds a slot should not work
2870 raise TestFailed
, "should fail: pickle E instance - %s" % base
2876 raise TestFailed
, "should fail: cPickle E instance - %s" % base
2879 if verbose
: print "Testing copy.copy() and copy.deepcopy()..."
2887 vereq(b
.__dict
__, a
.__dict
__)
2892 verify(c
.bar
is a
.bar
)
2894 d
= copy
.deepcopy(a
)
2895 vereq(d
.__dict
__, a
.__dict
__)
2897 vereq(d
.bar
, [1,2,3])
2899 def binopoverride():
2900 if verbose
: print "Testing overrides of binary operations..."
2903 return "I(%r)" % int(self
)
2904 def __add__(self
, other
):
2905 return I(int(self
) + int(other
))
2907 def __pow__(self
, other
, mod
=None):
2909 return I(pow(int(self
), int(other
)))
2911 return I(pow(int(self
), int(other
), int(mod
)))
2912 def __rpow__(self
, other
, mod
=None):
2914 return I(pow(int(other
), int(self
), mod
))
2916 return I(pow(int(other
), int(self
), int(mod
)))
2918 vereq(`
I(1) + I(2)`
, "I(3)")
2919 vereq(`
I(1) + 2`
, "I(3)")
2920 vereq(`
1 + I(2)`
, "I(3)")
2921 vereq(`
I(2) ** I(3)`
, "I(8)")
2922 vereq(`
2 ** I(3)`
, "I(8)")
2923 vereq(`
I(2) ** 3`
, "I(8)")
2924 vereq(`
pow(I(2), I(3), I(5))`
, "I(3)")
2926 def __eq__(self
, other
):
2927 return self
.lower() == other
.lower()
2929 def subclasspropagation():
2930 if verbose
: print "Testing propagation of slot functions to subclasses..."
2940 vereq(hash(d
), id(d
))
2941 A
.__hash
__ = lambda self
: 42
2943 C
.__hash
__ = lambda self
: 314
2945 B
.__hash
__ = lambda self
: 144
2947 D
.__hash
__ = lambda self
: 100
2956 vereq(hash(d
), id(d
))
2961 def __getattribute__(self
, name
):
2964 return object.__getattribute
__(self
, name
)
2965 A
.__getattribute
__ = __getattribute__
2968 def __getattr__(self
, name
):
2969 if name
in ("spam", "foo", "bar"):
2971 raise AttributeError, name
2972 B
.__getattr
__ = __getattr__
2973 vereq(d
.spam
, "hello")
2976 del A
.__getattribute
__
2979 vereq(d
.foo
, "hello")
2984 except AttributeError:
2987 raise TestFailed
, "d.foo should be undefined now"
2989 # Test a nasty bug in recurse_down_subclasses()
2997 A
.__setitem
__ = lambda *a
: None # crash
2999 def buffer_inherit():
3001 # SF bug [#470040] ParseTuple t# vs subclasses.
3003 print "Testing that buffer interface is inherited ..."
3009 # b2a_hex uses the buffer interface to get its argument's value, via
3010 # PyArg_ParseTuple 't#' code.
3011 vereq(binascii
.b2a_hex(m
), binascii
.b2a_hex(base
))
3013 # It's not clear that unicode will continue to support the character
3014 # buffer interface, and this test will fail if that's taken away.
3015 class MyUni(unicode):
3019 vereq(binascii
.b2a_hex(m
), binascii
.b2a_hex(base
))
3026 raise TestFailed('subclass of int should not have a buffer interface')
3030 def str_of_str_subclass():
3035 print "Testing __str__ defined in subclass of str ..."
3037 class octetstring(str):
3039 return binascii
.b2a_hex(self
)
3041 return self
+ " repr"
3043 o
= octetstring('A')
3044 vereq(type(o
), octetstring
)
3045 vereq(type(str(o
)), str)
3046 vereq(type(repr(o
)), str)
3049 vereq(repr(o
), 'A repr')
3050 vereq(o
.__str
__(), '41')
3051 vereq(o
.__repr
__(), 'A repr')
3053 capture
= cStringIO
.StringIO()
3054 # Calling str() or not exercises different internal paths.
3056 print >> capture
, str(o
)
3057 vereq(capture
.getvalue(), '41\n41\n')
3061 if verbose
: print "Testing keyword arguments to __init__, __call__..."
3063 vereq(f
.__call
__(a
=42), 42)
3065 list.__init
__(a
, sequence
=[0, 1, 2])
3069 if verbose
: print "Testing __del__ hook..."
3079 class D(object): pass
3082 except TypeError: pass
3083 else: raise TestFailed
, "invalid del() didn't raise TypeError"
3086 if verbose
: print "Testing hash of mutable subclasses..."
3096 raise TestFailed
, "hash() of dict subclass should fail"
3106 raise TestFailed
, "hash() of list subclass should fail"
3110 except TypeError: pass
3111 else: raise TestFailed
, "'' + 5 doesn't raise TypeError"
3114 except ValueError: pass
3115 else: raise TestFailed
, "''.split('') doesn't raise ValueError"
3118 except TypeError: pass
3119 else: raise TestFailed
, "''.join([0]) doesn't raise TypeError"
3122 except ValueError: pass
3123 else: raise TestFailed
, "''.rindex('5') doesn't raise ValueError"
3126 except TypeError: pass
3127 else: raise TestFailed
, "'%(n)s' % None doesn't raise TypeError"
3130 except ValueError: pass
3131 else: raise TestFailed
, "'%(n' % {} '' doesn't raise ValueError"
3133 try: '%*s' % ('abc')
3134 except TypeError: pass
3135 else: raise TestFailed
, "'%*s' % ('abc') doesn't raise TypeError"
3137 try: '%*.*s' % ('abc', 5)
3138 except TypeError: pass
3139 else: raise TestFailed
, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3142 except TypeError: pass
3143 else: raise TestFailed
, "'%s' % (1, 2) doesn't raise TypeError"
3146 except ValueError: pass
3147 else: raise TestFailed
, "'%' % None doesn't raise ValueError"
3149 vereq('534253'.isdigit(), 1)
3150 vereq('534253x'.isdigit(), 0)
3151 vereq('%c' % 5, '\x05')
3152 vereq('%c' % '5', '5')
3154 def deepcopyrecursive():
3155 if verbose
: print "Testing deepcopy of recursive objects..."
3162 z
= deepcopy(a
) # This blew up before
3165 if verbose
: print "Testing uninitialized module objects..."
3166 from types
import ModuleType
as M
3169 vereq(hasattr(m
, "__name__"), 0)
3170 vereq(hasattr(m
, "__file__"), 0)
3171 vereq(hasattr(m
, "foo"), 0)
3172 vereq(m
.__dict
__, None)
3174 vereq(m
.__dict
__, {"foo": 1})
3176 def dictproxyiterkeys():
3180 if verbose
: print "Testing dict-proxy iterkeys..."
3181 keys
= [ key
for key
in C
.__dict
__.iterkeys() ]
3183 vereq(keys
, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3185 def dictproxyitervalues():
3189 if verbose
: print "Testing dict-proxy itervalues..."
3190 values
= [ values
for values
in C
.__dict
__.itervalues() ]
3191 vereq(len(values
), 5)
3193 def dictproxyiteritems():
3197 if verbose
: print "Testing dict-proxy iteritems..."
3198 keys
= [ key
for (key
, value
) in C
.__dict
__.iteritems() ]
3200 vereq(keys
, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3203 if verbose
: print "Testing __new__ returning something unexpected..."
3205 def __new__(cls
, arg
):
3206 if isinstance(arg
, str): return [1, 2, 3]
3207 elif isinstance(arg
, int): return object.__new
__(D
)
3208 else: return object.__new
__(cls
)
3210 def __init__(self
, arg
):
3212 vereq(C("1"), [1, 2, 3])
3213 vereq(D("1"), [1, 2, 3])
3217 vereq(isinstance(d
, D
), True)
3220 vereq(isinstance(d
, D
), True)
3225 if verbose
: print "Testing for __imul__ problems..."
3227 def __imul__(self
, other
):
3228 return (self
, other
)
3241 vereq(y
, (x
, 1L<<100))
3247 vereq(y
, (x
, "foo"))
3249 def docdescriptor():
3251 if verbose
: print "Testing __doc__ descriptor..."
3252 class DocDescr(object):
3253 def __get__(self
, object, otype
):
3255 object = object.__class
__.__name
__ + ' instance'
3257 otype
= otype
.__name
__
3258 return 'object=%s; type=%s' % (object, otype
)
3260 __doc__
= DocDescr()
3261 class NewClass(object):
3262 __doc__
= DocDescr()
3263 vereq(OldClass
.__doc
__, 'object=None; type=OldClass')
3264 vereq(OldClass().__doc
__, 'object=OldClass instance; type=OldClass')
3265 vereq(NewClass
.__doc
__, 'object=None; type=NewClass')
3266 vereq(NewClass().__doc
__, 'object=NewClass instance; type=NewClass')
3268 def string_exceptions():
3270 print "Testing string exceptions ..."
3272 # Ensure builtin strings work OK as exceptions.
3273 astring
= "An exception string."
3279 raise TestFailed
, "builtin string not usable as exception"
3281 # Ensure string subclass instances do not.
3285 newstring
= MyStr("oops -- shouldn't work")
3291 raise TestFailed
, "string subclass allowed as exception"
3293 def copy_setstate():
3295 print "Testing that copy.*copy() correctly uses __setstate__..."
3298 def __init__(self
, foo
=None):
3301 def setfoo(self
, foo
=None):
3305 def __getstate__(self
):
3307 def __setstate__(self
, lst
):
3308 assert len(lst
) == 1
3309 self
.__foo
= self
.foo
= lst
[0]
3313 vereq(a
.getfoo(), 42)
3316 vereq(b
.getfoo(), 24)
3317 b
= copy
.deepcopy(a
)
3319 vereq(b
.getfoo(), 24)
3323 print "Testing cases with slices and overridden __getitem__ ..."
3325 vereq("hello"[:4], "hell")
3326 vereq("hello"[slice(4)], "hell")
3327 vereq(str.__getitem
__("hello", slice(4)), "hell")
3329 def __getitem__(self
, x
):
3330 return str.__getitem
__(self
, x
)
3331 vereq(S("hello")[:4], "hell")
3332 vereq(S("hello")[slice(4)], "hell")
3333 vereq(S("hello").__getitem
__(slice(4)), "hell")
3335 vereq((1,2,3)[:2], (1,2))
3336 vereq((1,2,3)[slice(2)], (1,2))
3337 vereq(tuple.__getitem
__((1,2,3), slice(2)), (1,2))
3339 def __getitem__(self
, x
):
3340 return tuple.__getitem
__(self
, x
)
3341 vereq(T((1,2,3))[:2], (1,2))
3342 vereq(T((1,2,3))[slice(2)], (1,2))
3343 vereq(T((1,2,3)).__getitem
__(slice(2)), (1,2))
3345 vereq([1,2,3][:2], [1,2])
3346 vereq([1,2,3][slice(2)], [1,2])
3347 vereq(list.__getitem
__([1,2,3], slice(2)), [1,2])
3349 def __getitem__(self
, x
):
3350 return list.__getitem
__(self
, x
)
3351 vereq(L([1,2,3])[:2], [1,2])
3352 vereq(L([1,2,3])[slice(2)], [1,2])
3353 vereq(L([1,2,3]).__getitem
__(slice(2)), [1,2])
3354 # Now do lists and __setitem__
3356 a
[slice(1, 3)] = [3,2]
3358 a
[slice(0, 2, 1)] = [3,1]
3360 a
.__setitem
__(slice(1, 3), [2,1])
3362 a
.__setitem
__(slice(0, 2, 1), [2,3])
3365 def subtype_resurrection():
3367 print "Testing resurrection of new-style instance..."
3373 # resurrect the instance
3374 C
.container
.append(self
)
3378 # The most interesting thing here is whether this blows up, due to flawed
3379 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
3382 # If that didn't blow up, it's also interesting to see whether clearing
3383 # the last container slot works: that will attempt to delete c again,
3384 # which will cause c to get appended back to the container again "during"
3387 vereq(len(C
.container
), 1)
3388 vereq(C
.container
[-1].attr
, 42)
3390 # Make c mortal again, so that the test framework with -l doesn't report
3395 # Deallocating deeply nested slotted trash caused stack overflows
3397 print "Testing slot trash..."
3398 class trash(object):
3400 def __init__(self
, x
):
3403 for i
in xrange(50000):
3407 def slotmultipleinheritance():
3408 # SF bug 575229, multiple inheritance w/ slots dumps core
3415 vereq(C
.__basicsize
__, B
.__basicsize
__)
3416 verify(hasattr(C
, '__dict__'))
3417 verify(hasattr(C
, '__weakref__'))
3423 print "Testing correct invocation of __rmul__..."
3425 def __mul__(self
, other
):
3427 def __rmul__(self
, other
):
3433 vereq(2.2*a
, "rmul")
3438 print "Testing correct invocation of __ipow__..."
3440 def __ipow__(self
, other
):
3445 def do_this_first():
3447 print "Testing SF bug 551412 ..."
3448 # This dumps core when SF bug 551412 isn't fixed --
3449 # but only when test_descr.py is run separately.
3450 # (That can't be helped -- as soon as PyType_Ready()
3451 # is called for PyLong_Type, the bug is gone.)
3452 class UserLong(object):
3453 def __pow__(self
, *args
):
3456 pow(0L, UserLong(), 0L)
3461 print "Testing SF bug 570483..."
3462 # Another segfault only when run early
3463 # (before PyType_Ready(tuple) is called)
3466 def test_mutable_bases():
3468 print "Testing mutable bases..."
3469 # stuff that should work:
3473 def __getattribute__(self
, attr
):
3477 return super(C2
, self
).__getattribute
__(attr
)
3492 vereq(C2
.__subclasses__(), [D
])
3494 # stuff that shouldn't:
3499 L
.__bases
__ = (dict,)
3503 raise TestFailed
, "shouldn't turn list subclass into dict subclass"
3506 list.__bases
__ = (dict,)
3510 raise TestFailed
, "shouldn't be able to assign to list.__bases__"
3517 raise TestFailed
, "shouldn't be able to delete .__bases__"
3521 except TypeError, msg
:
3522 if str(msg
) == "a new-style class can't have only classic bases":
3523 raise TestFailed
, "wrong error message for .__bases__ = ()"
3525 raise TestFailed
, "shouldn't be able to set .__bases__ to ()"
3532 # actually, we'll have crashed by here...
3533 raise TestFailed
, "shouldn't be able to create inheritance cycles"
3540 raise TestFailed
, "shouldn't be able to create inheritance cycles"
3542 # let's throw a classic class into the mix:
3547 D
.__bases
__ = (C
, Classic
)
3553 except AttributeError:
3556 raise TestFailed
, "attribute should have vanished"
3559 D
.__bases
__ = (Classic
,)
3563 raise TestFailed
, "new-style class must have a new-style base"
3565 def test_mutable_bases_with_failing_mro():
3567 print "Testing mutable bases with failing mro..."
3568 class WorkOnce(type):
3569 def __new__(self
, name
, bases
, ns
):
3571 return super(WorkOnce
, self
).__new
__(WorkOnce
, name
, bases
, ns
)
3574 raise RuntimeError, "bozo"
3577 return type.mro(self
)
3579 class WorkAlways(type):
3581 # this is here to make sure that .mro()s aren't called
3582 # with an exception set (which was possible at one point).
3583 # An error message will be printed in a debug build.
3584 # What's a good way to test for this?
3585 return type.mro(self
)
3600 __metaclass__
= WorkOnce
3603 __metaclass__
= WorkAlways
3605 # Immediate subclasses have their mro's adjusted in alphabetical
3606 # order, so E's will get adjusted before adjusting F's fails. We
3607 # check here that E's gets restored.
3609 E_mro_before
= E
.__mro
__
3610 D_mro_before
= D
.__mro
__
3614 except RuntimeError:
3615 vereq(E
.__mro
__, E_mro_before
)
3616 vereq(D
.__mro
__, D_mro_before
)
3618 raise TestFailed
, "exception not propagated"
3620 def test_mutable_bases_catch_mro_conflict():
3622 print "Testing mutable bases catch mro conflict..."
3639 C
.__bases
__ = (B
, A
)
3643 raise TestFailed
, "didn't catch MRO conflict"
3645 def mutable_names():
3647 print "Testing mutable names..."
3651 # C.__module__ could be 'test_descr' or '__main__'
3655 vereq((C
.__module
__, C
.__name
__), (mod
, 'D'))
3658 vereq((C
.__module
__, C
.__name
__), (mod
, 'D.E'))
3660 def subclass_right_op():
3662 print "Testing correct dispatch of subclass overloading __r<op>__..."
3664 # This code tests various cases where right-dispatch of a subclass
3665 # should be preferred over left-dispatch of a base class.
3667 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3670 def __div__(self
, other
):
3672 def __rdiv__(self
, other
):
3675 vereq(B(1) / 1, "B.__div__")
3676 vereq(1 / B(1), "B.__rdiv__")
3678 # Case 2: subclass of object; this is just the baseline for case 3
3681 def __div__(self
, other
):
3683 def __rdiv__(self
, other
):
3686 vereq(C(1) / 1, "C.__div__")
3687 vereq(1 / C(1), "C.__rdiv__")
3689 # Case 3: subclass of new-style class; here it gets interesting
3692 def __div__(self
, other
):
3694 def __rdiv__(self
, other
):
3697 vereq(D(1) / C(1), "D.__div__")
3698 vereq(C(1) / D(1), "D.__rdiv__")
3700 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3705 vereq(E
.__rdiv
__, C
.__rdiv
__)
3707 vereq(E(1) / 1, "C.__div__")
3708 vereq(1 / E(1), "C.__rdiv__")
3709 vereq(E(1) / C(1), "C.__div__")
3710 vereq(C(1) / E(1), "C.__div__") # This one would fail
3712 def dict_type_with_metaclass():
3714 print "Testing type of __dict__ when __metaclass__ set..."
3721 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
3723 veris(type(C
.__dict
__), type(B
.__dict
__))
3748 consistency_with_epg()
3757 staticmethods_in_c()
3771 str_subclass_as_dict_key()
3772 classic_comparisons()
3781 subclasspropagation()
3783 str_of_str_subclass()
3791 dictproxyitervalues()
3792 dictproxyiteritems()
3800 subtype_resurrection()
3802 slotmultipleinheritance()
3805 test_mutable_bases()
3806 test_mutable_bases_with_failing_mro()
3807 test_mutable_bases_catch_mro_conflict()
3810 dict_type_with_metaclass()
3812 if verbose
: print "All OK"
3814 if __name__
== "__main__":