1 # Test enhancements related to descriptors and new-style classes
3 from test_support
import verify
, vereq
, verbose
, TestFailed
, TESTFN
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 ..."
189 d
= dict({1: 2, 'a': 'b'})
190 vereq(d
, {1: 2, 'a': 'b'})
191 vereq(d
, dict(d
.items()))
192 vereq(d
, dict(items
=d
.iteritems()))
193 for badarg
in 0, 0L, 0j
, "0", [0], (0,):
200 # It's a sequence, and its elements are also sequences (gotta
201 # love strings <wink>), but they aren't of length 2, so this
202 # one seemed better as a ValueError than a TypeError.
205 raise TestFailed("no TypeError from dict(%r)" % badarg
)
207 raise TestFailed("no TypeError from dict(%r)" % badarg
)
213 raise TestFailed("no TypeError from dict(senseless={})")
220 raise TestFailed("no TypeError from dict({}, {})")
223 # Lacks a .keys() method; will be added later.
224 dict = {1:2, 3:4, 'a':1j
}
231 raise TestFailed("no TypeError from dict(incomplete mapping)")
233 Mapping
.keys
= lambda self
: self
.dict.keys()
234 Mapping
.__getitem
__ = lambda self
, i
: self
.dict[i
]
235 d
= dict(items
=Mapping())
236 vereq(d
, Mapping
.dict)
238 # Init from sequence of iterable objects, each producing a 2-sequence.
239 class AddressBookEntry
:
240 def __init__(self
, first
, last
):
244 return iter([self
.first
, self
.last
])
246 d
= dict([AddressBookEntry('Tim', 'Warsaw'),
247 AddressBookEntry('Barry', 'Peters'),
248 AddressBookEntry('Tim', 'Peters'),
249 AddressBookEntry('Barry', 'Warsaw')])
250 vereq(d
, {'Barry': 'Warsaw', 'Tim': 'Peters'})
252 d
= dict(zip(range(4), range(1, 5)))
253 vereq(d
, dict([(i
, i
+1) for i
in range(4)]))
255 # Bad sequence lengths.
256 for bad
in [('tooshort',)], [('too', 'long', 'by 1')]:
262 raise TestFailed("no ValueError from dict(%r)" % bad
)
266 print "Testing dir() ..."
268 vereq(dir(), ['junk'])
271 # Just make sure these don't blow up!
272 for arg
in 2, 2L, 2j
, 2e0
, [2], "2", u
"2", (2,), {2:2}, type, test_dir
:
275 # Try classic classes.
278 def Cmethod(self
): pass
280 cstuff
= ['Cdata', 'Cmethod', '__doc__', '__module__']
281 vereq(dir(C
), cstuff
)
282 verify('im_self' in dir(C
.Cmethod
))
284 c
= C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
285 vereq(dir(c
), cstuff
)
288 c
.cmethod
= lambda self
: 0
289 vereq(dir(c
), cstuff
+ ['cdata', 'cmethod'])
290 verify('im_self' in dir(c
.Cmethod
))
294 def Amethod(self
): pass
296 astuff
= ['Adata', 'Amethod'] + cstuff
297 vereq(dir(A
), astuff
)
298 verify('im_self' in dir(A
.Amethod
))
300 vereq(dir(a
), astuff
)
301 verify('im_self' in dir(a
.Amethod
))
303 a
.amethod
= lambda self
: 3
304 vereq(dir(a
), astuff
+ ['adata', 'amethod'])
306 # The same, but with new-style classes. Since these have object as a
307 # base class, a lot more gets sucked in.
308 def interesting(strings
):
309 return [s
for s
in strings
if not s
.startswith('_')]
313 def Cmethod(self
): pass
315 cstuff
= ['Cdata', 'Cmethod']
316 vereq(interesting(dir(C
)), cstuff
)
319 vereq(interesting(dir(c
)), cstuff
)
320 verify('im_self' in dir(C
.Cmethod
))
323 c
.cmethod
= lambda self
: 0
324 vereq(interesting(dir(c
)), cstuff
+ ['cdata', 'cmethod'])
325 verify('im_self' in dir(c
.Cmethod
))
329 def Amethod(self
): pass
331 astuff
= ['Adata', 'Amethod'] + cstuff
332 vereq(interesting(dir(A
)), astuff
)
333 verify('im_self' in dir(A
.Amethod
))
335 vereq(interesting(dir(a
)), astuff
)
337 a
.amethod
= lambda self
: 3
338 vereq(interesting(dir(a
)), astuff
+ ['adata', 'amethod'])
339 verify('im_self' in dir(a
.Amethod
))
341 # Try a module subclass.
348 names
= [x
for x
in dir(minstance
) if x
not in ["__name__", "__doc__"]]
349 vereq(names
, ['a', 'b'])
354 __dict__
= property(getdict
)
356 m2instance
= M2("m2")
359 vereq(m2instance
.__dict
__, "Not a dict!")
365 # Two essentially featureless objects, just inheriting stuff from
367 vereq(dir(None), dir(Ellipsis))
369 # Nasty test case for proxied objects
370 class Wrapper(object):
371 def __init__(self
, obj
):
374 return "Wrapper(%s)" % repr(self
.__obj
)
375 def __getitem__(self
, key
):
376 return Wrapper(self
.__obj
[key
])
378 return len(self
.__obj
)
379 def __getattr__(self
, name
):
380 return Wrapper(getattr(self
.__obj
, name
))
383 def __getclass(self
):
384 return Wrapper(type(self
))
385 __class__
= property(__getclass
)
387 dir(C()) # This used to segfault
411 for name
, expr
in binops
.items():
413 expr
= expr
+ "(a, b)"
415 expr
= 'a %s b' % expr
430 for name
, expr
in unops
.items():
437 def numops(a
, b
, skip
=[]):
438 dict = {'a': a
, 'b': b
}
439 for name
, expr
in binops
.items():
441 name
= "__%s__" % name
443 res
= eval(expr
, dict)
444 testbinop(a
, b
, res
, expr
, name
)
445 for name
, expr
in unops
.items():
447 name
= "__%s__" % name
449 res
= eval(expr
, dict)
450 testunop(a
, res
, expr
, name
)
453 if verbose
: print "Testing int operations..."
455 # The following crashes in Python 2.2
456 vereq((1).__nonzero
__(), 1)
457 vereq((0).__nonzero
__(), 0)
458 # This returns 'NotImplemented' in Python 2.2
460 def __add__(self
, other
):
461 return NotImplemented
467 raise TestFailed
, "NotImplemented should have caused TypeError"
470 if verbose
: print "Testing long operations..."
474 if verbose
: print "Testing float operations..."
478 if verbose
: print "Testing complex operations..."
479 numops(100.0j
, 3.0j
, skip
=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
480 class Number(complex):
482 def __new__(cls
, *args
, **kwds
):
483 result
= complex.__new
__(cls
, *args
)
484 result
.prec
= kwds
.get('prec', 12)
489 return "%.*g" % (prec
, self
.real
)
491 return "%.*gj" % (prec
, self
.imag
)
492 return "(%.*g+%.*gj)" % (prec
, self
.real
, prec
, self
.imag
)
495 a
= Number(3.14, prec
=6)
499 a
= Number(a
, prec
=2)
508 if verbose
: print "Testing spamlist operations..."
509 import copy
, xxsubtype
as spam
510 def spamlist(l
, memo
=None):
511 import xxsubtype
as spam
512 return spam
.spamlist(l
)
513 # This is an ugly hack:
514 copy
._deepcopy
_dispatch
[spam
.spamlist
] = spamlist
516 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
517 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
518 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
519 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
520 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
521 "a[b:c]", "__getslice__")
522 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
524 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
525 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
526 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
527 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
528 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
529 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
530 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
532 class C(spam
.spamlist
):
533 def foo(self
): return 1
539 vereq(a
.getstate(), 0)
541 vereq(a
.getstate(), 42)
544 if verbose
: print "Testing spamdict operations..."
545 import copy
, xxsubtype
as spam
546 def spamdict(d
, memo
=None):
547 import xxsubtype
as spam
549 for k
, v
in d
.items(): sd
[k
] = v
551 # This is an ugly hack:
552 copy
._deepcopy
_dispatch
[spam
.spamdict
] = spamdict
554 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
555 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
556 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
557 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
558 d
= spamdict({1:2,3:4})
560 for i
in d
.keys(): l1
.append(i
)
562 for i
in iter(d
): l
.append(i
)
565 for i
in d
.__iter
__(): l
.append(i
)
568 for i
in type(spamdict({})).__iter
__(d
): l
.append(i
)
570 straightd
= {1:2, 3:4}
571 spamd
= spamdict(straightd
)
572 testunop(spamd
, 2, "len(a)", "__len__")
573 testunop(spamd
, repr(straightd
), "repr(a)", "__repr__")
574 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
575 "a[b]=c", "__setitem__")
577 class C(spam
.spamdict
):
578 def foo(self
): return 1
583 vereq(a
.items(), [('foo', 'bar')])
584 vereq(a
.getstate(), 0)
586 vereq(a
.getstate(), 100)
589 if verbose
: print "Testing Python subclass of dict..."
590 verify(issubclass(dict, dict))
591 verify(isinstance({}, dict))
594 verify(d
.__class
__ is dict)
595 verify(isinstance(d
, dict))
598 def __init__(self
, *a
, **kw
):
603 for k
, v
in kw
.items(): self
[v
] = k
604 def __getitem__(self
, key
):
605 return self
.get(key
, 0)
606 def __setitem__(self
, key
, value
):
607 verify(isinstance(key
, type(0)))
608 dict.__setitem
__(self
, key
, value
)
609 def setstate(self
, state
):
613 verify(issubclass(C
, dict))
617 vereq(a2
[1] == 'foo' and a2
[2], 'bar')
620 vereq(a
.getstate(), -1)
623 vereq(a
.getstate(), 0)
626 vereq(a
.getstate(), 10)
630 if verbose
: print "pydict stress test ..."
641 if verbose
: print "Testing Python subclass of list..."
643 def __getitem__(self
, i
):
644 return list.__getitem
__(self
, i
) + 100
645 def __getslice__(self
, i
, j
):
652 vereq(a
[100:200], (100,200))
655 if verbose
: print "Testing __metaclass__..."
662 def setstate(self
, state
):
665 vereq(a
.getstate(), 0)
667 vereq(a
.getstate(), 10)
669 class __metaclass__(type):
670 def myself(cls
): return cls
673 verify(d
.__class
__ is D
)
675 def __new__(cls
, name
, bases
, dict):
677 return type.__new
__(cls
, name
, bases
, dict)
684 class _instance(object):
687 def __new__(cls
, name
, bases
, dict):
688 self
= object.__new
__(cls
)
693 __new__
= staticmethod(__new__
)
696 # Early binding of methods
697 for key
in self
.dict:
698 if key
.startswith("__"):
700 setattr(it
, key
, self
.dict[key
].__get
__(it
, self
))
708 verify('spam' in C
.dict)
712 # More metaclass examples
714 class autosuper(type):
715 # Automatically add __super to the class
716 # This trick only works for dynamic classes
717 def __new__(metaclass
, name
, bases
, dict):
718 cls
= super(autosuper
, metaclass
).__new
__(metaclass
,
720 # Name mangling for __super removes leading underscores
721 while name
[:1] == "_":
724 name
= "_%s__super" % name
727 setattr(cls
, name
, super(cls
))
730 __metaclass__
= autosuper
735 return "B" + self
.__super
.meth()
738 return "C" + self
.__super
.meth()
741 return "D" + self
.__super
.meth()
742 vereq(D().meth(), "DCBA")
745 return "E" + self
.__super
.meth()
746 vereq(E().meth(), "EBCA")
748 class autoproperty(type):
749 # Automatically create property attributes when methods
750 # named _get_x and/or _set_x are found
751 def __new__(metaclass
, name
, bases
, dict):
753 for key
, val
in dict.iteritems():
754 if key
.startswith("_get_"):
756 get
, set = hits
.get(key
, (None, None))
759 elif key
.startswith("_set_"):
761 get
, set = hits
.get(key
, (None, None))
764 for key
, (get
, set) in hits
.iteritems():
765 dict[key
] = property(get
, set)
766 return super(autoproperty
, metaclass
).__new
__(metaclass
,
769 __metaclass__
= autoproperty
775 verify(not hasattr(a
, "x"))
780 class multimetaclass(autoproperty
, autosuper
):
781 # Merge of multiple cooperating metaclasses
784 __metaclass__
= multimetaclass
789 return "B" + self
.__super
._get
_x
()
792 return "C" + self
.__super
._get
_x
()
795 return "D" + self
.__super
._get
_x
()
798 # Make sure type(x) doesn't call x.__class__.__init__
801 def __init__(self
, *args
):
810 class C(object): pass
813 except TypeError: pass
814 else: raise TestFailed
, "calling object w/o call method should raise TypeError"
817 if verbose
: print "Testing Python subclass of module..."
822 def __init__(self
, name
):
823 MT
.__init
__(self
, name
)
824 def __getattribute__(self
, name
):
825 log
.append(("getattr", name
))
826 return MT
.__getattribute
__(self
, name
)
827 def __setattr__(self
, name
, value
):
828 log
.append(("setattr", name
, value
))
829 MT
.__setattr
__(self
, name
, value
)
830 def __delattr__(self
, name
):
831 log
.append(("delattr", name
))
832 MT
.__delattr
__(self
, name
)
837 vereq(log
, [("setattr", "foo", 12),
842 if verbose
: print "Testing multiple inheritance..."
848 def setstate(self
, state
):
851 vereq(a
.getstate(), 0)
853 vereq(a
.getstate(), 10)
856 type({}).__init
__(self
)
861 vereq(d
.items(), [("hello", "world")])
862 vereq(d
["hello"], "world")
863 vereq(d
.getstate(), 0)
865 vereq(d
.getstate(), 10)
866 vereq(D
.__mro
__, (D
, dict, C
, object))
871 return int(self
.foo())
874 class Frag(Node
, list):
877 vereq(Node().__int
__(), 23)
878 vereq(int(Node()), 23)
879 vereq(Frag().__int
__(), 42)
880 vereq(int(Frag()), 42)
882 # MI mixing classic and new-style classes.
897 # Classic MRO is preserved for a classic base class.
900 vereq(E
.__mro
__, (E
, D
, B
, A
, C
, object))
903 # But with a mix of classic bases, their MROs are combined using
905 class F(B
, C
, object):
907 vereq(F
.__mro
__, (F
, B
, C
, A
, object))
910 # Try something else.
914 def all_method(self
):
920 def all_method(self
):
923 vereq(M1
.__mro__
, (M1
, C
, object))
925 vereq(m
.cmethod(), "C a")
926 vereq(m
.m1method(), "M1 a")
927 vereq(m
.all_method(), "M1 b")
932 def all_method(self
):
938 def all_method(self
):
941 vereq(M2
.__mro__
, (M2
, object, D
, C
))
943 vereq(m
.cmethod(), "C a")
944 vereq(m
.dmethod(), "D a")
945 vereq(m
.m2method(), "M2 a")
946 vereq(m
.all_method(), "M2 b")
948 class M3(M1
, object, M2
):
951 def all_method(self
):
953 # XXX Expected this (the commented-out result):
954 # vereq(M3.__mro__, (M3, M1, M2, object, D, C))
955 vereq(M3
.__mro__
, (M3
, M1
, M2
, D
, C
, object)) # XXX ?
957 vereq(m
.cmethod(), "C a")
958 vereq(m
.dmethod(), "D a")
959 vereq(m
.m1method(), "M1 a")
960 vereq(m
.m2method(), "M2 a")
961 vereq(m
.m3method(), "M3 a")
962 vereq(m
.all_method(), "M3 b")
972 raise TestFailed
, "new class with only classic bases - shouldn't be"
975 if verbose
: print "Testing multiple inheritance special cases..."
977 def spam(self
): return "A"
978 vereq(A().spam(), "A")
980 def boo(self
): return "B"
981 def spam(self
): return "B"
982 vereq(B().spam(), "B")
983 vereq(B().boo(), "B")
985 def boo(self
): return "C"
986 vereq(C().spam(), "A")
987 vereq(C().boo(), "C")
989 vereq(D().spam(), "B")
990 vereq(D().boo(), "B")
991 vereq(D
.__mro
__, (D
, B
, C
, A
, object))
993 vereq(E().spam(), "B")
994 vereq(E().boo(), "C")
995 vereq(E
.__mro
__, (E
, C
, B
, A
, object))
997 vereq(F().spam(), "B")
998 vereq(F().boo(), "B")
999 vereq(F
.__mro
__, (F
, D
, E
, B
, C
, A
, object))
1001 vereq(G().spam(), "B")
1002 vereq(G().boo(), "C")
1003 vereq(G
.__mro
__, (G
, E
, D
, C
, B
, A
, object))
1006 if verbose
: print "Testing object class..."
1008 vereq(a
.__class
__, object)
1009 vereq(type(a
), object)
1012 verify(not hasattr(a
, "foo"))
1015 except (AttributeError, TypeError):
1018 verify(0, "object() should not allow setting a foo attribute")
1019 verify(not hasattr(object(), "__dict__"))
1021 class Cdict(object):
1024 vereq(x
.__dict
__, {})
1027 vereq(x
.__dict
__, {'foo': 1})
1030 if verbose
: print "Testing __slots__..."
1034 verify(not hasattr(x
, "__dict__"))
1035 verify(not hasattr(x
, "foo"))
1040 verify(not hasattr(x
, "__dict__"))
1041 verify(not hasattr(x
, "a"))
1047 verify(not hasattr(x
, "a"))
1050 __slots__
= ['a', 'b', 'c']
1052 verify(not hasattr(x
, "__dict__"))
1053 verify(not hasattr(x
, 'a'))
1054 verify(not hasattr(x
, 'b'))
1055 verify(not hasattr(x
, 'c'))
1064 """Validate name mangling"""
1066 def __init__(self
, value
):
1071 verify(not hasattr(x
, '__dict__'))
1072 verify(not hasattr(x
, '__a'))
1076 except AttributeError:
1079 raise TestFailed
, "Double underscored names not mangled"
1081 # Make sure slot names are proper identifiers
1088 raise TestFailed
, "[None] slots not caught"
1091 __slots__
= ["foo bar"]
1095 raise TestFailed
, "['foo bar'] slots not caught"
1098 __slots__
= ["foo\0bar"]
1102 raise TestFailed
, "['foo\\0bar'] slots not caught"
1109 raise TestFailed
, "['1'] slots not caught"
1116 raise TestFailed
, "[''] slots not caught"
1118 __slots__
= ["a", "a_b", "_a", "A0123456789Z"]
1121 class Counted(object):
1122 counter
= 0 # counts the number of instances alive
1124 Counted
.counter
+= 1
1126 Counted
.counter
-= 1
1128 __slots__
= ['a', 'b', 'c']
1133 vereq(Counted
.counter
, 3)
1135 vereq(Counted
.counter
, 0)
1141 vereq(Counted
.counter
, 2)
1143 vereq(Counted
.counter
, 0)
1150 vereq(Counted
.counter
, 3)
1152 vereq(Counted
.counter
, 0)
1154 # Test cyclical leaks [SF bug 519621]
1156 __slots__
= ['a', 'b']
1159 s
.a
= [Counted(), s
]
1160 vereq(Counted
.counter
, 1)
1164 vereq(Counted
.counter
, 0)
1167 if verbose
: print "Testing class attribute propagation..."
1176 # Test that dynamic attributes are inherited
1179 # Test dynamic instances
1183 verify(not hasattr(a
, "foobar"))
1186 C
.method
= lambda self
: 42
1187 vereq(a
.method(), 42)
1188 C
.__repr
__ = lambda self
: "C()"
1189 vereq(repr(a
), "C()")
1190 C
.__int
__ = lambda self
: 100
1193 verify(not hasattr(a
, "spam"))
1194 def mygetattr(self
, name
):
1197 raise AttributeError
1198 C
.__getattr
__ = mygetattr
1199 vereq(a
.spam
, "spam")
1202 def mysetattr(self
, name
, value
):
1204 raise AttributeError
1205 return object.__setattr
__(self
, name
, value
)
1206 C
.__setattr
__ = mysetattr
1209 except AttributeError:
1212 verify(0, "expected AttributeError")
1213 vereq(a
.spam
, "spam")
1220 # Test handling of int*seq and seq*int
1223 vereq("a"*I(2), "aa")
1224 vereq(I(2)*"a", "aa")
1229 # Test handling of long*seq and seq*long
1232 vereq("a"*L(2L), "aa")
1233 vereq(L(2L)*"a", "aa")
1238 # Test comparison of classes with dynamic metaclasses
1239 class dynamicmetaclass(type):
1242 __metaclass__
= dynamicmetaclass
1243 verify(someclass
!= object)
1246 if verbose
: print "Testing errors..."
1249 class C(list, dict):
1254 verify(0, "inheritance from both list and dict should be illegal")
1257 class C(object, None):
1262 verify(0, "inheritance from non-type should be illegal")
1272 verify(0, "inheritance from CFunction should be illegal")
1280 verify(0, "__slots__ = 1 should be illegal")
1288 verify(0, "__slots__ = [1] should be illegal")
1291 if verbose
: print "Testing class methods..."
1293 def foo(*a
): return a
1294 goo
= classmethod(foo
)
1296 vereq(C
.goo(1), (C
, 1))
1297 vereq(c
.goo(1), (C
, 1))
1298 vereq(c
.foo(1), (c
, 1))
1302 vereq(D
.goo(1), (D
, 1))
1303 vereq(d
.goo(1), (D
, 1))
1304 vereq(d
.foo(1), (d
, 1))
1305 vereq(D
.foo(d
, 1), (d
, 1))
1306 # Test for a specific crash (SF bug 528132)
1307 def f(cls
, arg
): return (cls
, arg
)
1309 vereq(ff
.__get
__(0, int)(42), (int, 42))
1310 vereq(ff
.__get
__(0)(42), (int, 42))
1312 # Test super() with classmethods (SF bug 535444)
1313 veris(C
.goo
.im_self
, C
)
1314 veris(D
.goo
.im_self
, D
)
1315 veris(super(D
,D
).goo
.im_self
, D
)
1316 veris(super(D
,d
).goo
.im_self
, D
)
1317 vereq(super(D
,D
).goo(), (D
,))
1318 vereq(super(D
,d
).goo(), (D
,))
1320 def classmethods_in_c():
1321 if verbose
: print "Testing C-based class methods..."
1322 import xxsubtype
as spam
1325 x
, a1
, d1
= spam
.spamlist
.classmeth(*a
, **d
)
1327 vereq((spam
.spamlist
,) + a
, a1
)
1329 x
, a1
, d1
= spam
.spamlist().classmeth(*a
, **d
)
1331 vereq((spam
.spamlist
,) + a
, a1
)
1334 def staticmethods():
1335 if verbose
: print "Testing static methods..."
1337 def foo(*a
): return a
1338 goo
= staticmethod(foo
)
1340 vereq(C
.goo(1), (1,))
1341 vereq(c
.goo(1), (1,))
1342 vereq(c
.foo(1), (c
, 1,))
1346 vereq(D
.goo(1), (1,))
1347 vereq(d
.goo(1), (1,))
1348 vereq(d
.foo(1), (d
, 1))
1349 vereq(D
.foo(d
, 1), (d
, 1))
1351 def staticmethods_in_c():
1352 if verbose
: print "Testing C-based static methods..."
1353 import xxsubtype
as spam
1356 x
, a1
, d1
= spam
.spamlist
.staticmeth(*a
, **d
)
1360 x
, a1
, d2
= spam
.spamlist().staticmeth(*a
, **d
)
1366 if verbose
: print "Testing classic classes..."
1368 def foo(*a
): return a
1369 goo
= classmethod(foo
)
1371 vereq(C
.goo(1), (C
, 1))
1372 vereq(c
.goo(1), (C
, 1))
1373 vereq(c
.foo(1), (c
, 1))
1377 vereq(D
.goo(1), (D
, 1))
1378 vereq(d
.goo(1), (D
, 1))
1379 vereq(d
.foo(1), (d
, 1))
1380 vereq(D
.foo(d
, 1), (d
, 1))
1381 class E
: # *not* subclassing from C
1383 vereq(E().foo
, C
.foo
) # i.e., unbound
1384 verify(repr(C
.foo
.__get
__(C())).startswith("<bound method "))
1387 if verbose
: print "Testing computed attributes..."
1389 class computed_attribute(object):
1390 def __init__(self
, get
, set=None):
1393 def __get__(self
, obj
, type=None):
1394 return self
.__get
(obj
)
1395 def __set__(self
, obj
, value
):
1396 return self
.__set
(obj
, value
)
1403 def __set_x(self
, x
):
1405 x
= computed_attribute(__get_x
, __set_x
)
1414 if verbose
: print "Testing __new__ slot override..."
1417 self
= list.__new
__(cls
)
1421 self
.foo
= self
.foo
+ 2
1424 verify(a
.__class
__ is C
)
1429 verify(b
.__class
__ is D
)
1432 if verbose
: print "Testing mro() and overriding it..."
1434 def f(self
): return "A"
1438 def f(self
): return "C"
1441 vereq(D
.mro(), [D
, B
, C
, A
, object])
1442 vereq(D
.__mro
__, (D
, B
, C
, A
, object))
1444 class PerverseMetaType(type):
1450 __metaclass__
= PerverseMetaType
1451 vereq(X
.__mro
__, (object, A
, C
, B
, D
, X
))
1455 if verbose
: print "Testing operator overloading..."
1458 "Intermediate class because object doesn't have a __setattr__"
1462 def __getattr__(self
, name
):
1464 return ("getattr", name
)
1466 raise AttributeError
1467 def __setattr__(self
, name
, value
):
1469 self
.setattr = (name
, value
)
1471 return B
.__setattr
__(self
, name
, value
)
1472 def __delattr__(self
, name
):
1476 return B
.__delattr
__(self
, name
)
1478 def __getitem__(self
, key
):
1479 return ("getitem", key
)
1480 def __setitem__(self
, key
, value
):
1481 self
.setitem
= (key
, value
)
1482 def __delitem__(self
, key
):
1485 def __getslice__(self
, i
, j
):
1486 return ("getslice", i
, j
)
1487 def __setslice__(self
, i
, j
, value
):
1488 self
.setslice
= (i
, j
, value
)
1489 def __delslice__(self
, i
, j
):
1490 self
.delslice
= (i
, j
)
1493 vereq(a
.foo
, ("getattr", "foo"))
1495 vereq(a
.setattr, ("foo", 12))
1497 vereq(a
.delattr, "foo")
1499 vereq(a
[12], ("getitem", 12))
1501 vereq(a
.setitem
, (12, 21))
1503 vereq(a
.delitem
, 12)
1505 vereq(a
[0:10], ("getslice", 0, 10))
1507 vereq(a
.setslice
, (0, 10, "foo"))
1509 vereq(a
.delslice
, (0, 10))
1512 if verbose
: print "Testing methods..."
1514 def __init__(self
, x
):
1529 vereq(E().foo
, C
.foo
) # i.e., unbound
1530 verify(repr(C
.foo
.__get
__(C(1))).startswith("<bound method "))
1533 # Test operators like __hash__ for which a built-in default exists
1534 if verbose
: print "Testing special operators..."
1535 # Test the default behavior for static classes
1537 def __getitem__(self
, i
):
1538 if 0 <= i
< 10: return i
1543 vereq(hash(c1
), id(c1
))
1544 vereq(cmp(c1
, c2
), cmp(id(c1
), id(c2
)))
1547 verify(not c1
!= c1
)
1548 verify(not c1
== c2
)
1549 # Note that the module name appears in str/repr, and that varies
1550 # depending on whether this test is run standalone or from a framework.
1551 verify(str(c1
).find('C object at ') >= 0)
1552 vereq(str(c1
), repr(c1
))
1553 verify(-1 not in c1
)
1556 verify(10 not in c1
)
1557 # Test the default behavior for dynamic classes
1559 def __getitem__(self
, i
):
1560 if 0 <= i
< 10: return i
1565 vereq(hash(d1
), id(d1
))
1566 vereq(cmp(d1
, d2
), cmp(id(d1
), id(d2
)))
1569 verify(not d1
!= d1
)
1570 verify(not d1
== d2
)
1571 # Note that the module name appears in str/repr, and that varies
1572 # depending on whether this test is run standalone or from a framework.
1573 verify(str(d1
).find('D object at ') >= 0)
1574 vereq(str(d1
), repr(d1
))
1575 verify(-1 not in d1
)
1578 verify(10 not in d1
)
1579 # Test overridden behavior for static classes
1580 class Proxy(object):
1581 def __init__(self
, x
):
1583 def __nonzero__(self
):
1584 return not not self
.x
1587 def __eq__(self
, other
):
1588 return self
.x
== other
1589 def __ne__(self
, other
):
1590 return self
.x
!= other
1591 def __cmp__(self
, other
):
1592 return cmp(self
.x
, other
.x
)
1594 return "Proxy:%s" % self
.x
1596 return "Proxy(%r)" % self
.x
1597 def __contains__(self
, value
):
1598 return value
in self
.x
1604 vereq(hash(p0
), hash(0))
1607 verify(not p0
!= p0
)
1609 vereq(cmp(p0
, p1
), -1)
1610 vereq(cmp(p0
, p0
), 0)
1611 vereq(cmp(p0
, p_1
), 1)
1612 vereq(str(p0
), "Proxy:0")
1613 vereq(repr(p0
), "Proxy(0)")
1614 p10
= Proxy(range(10))
1615 verify(-1 not in p10
)
1618 verify(10 not in p10
)
1619 # Test overridden behavior for dynamic classes
1620 class DProxy(object):
1621 def __init__(self
, x
):
1623 def __nonzero__(self
):
1624 return not not self
.x
1627 def __eq__(self
, other
):
1628 return self
.x
== other
1629 def __ne__(self
, other
):
1630 return self
.x
!= other
1631 def __cmp__(self
, other
):
1632 return cmp(self
.x
, other
.x
)
1634 return "DProxy:%s" % self
.x
1636 return "DProxy(%r)" % self
.x
1637 def __contains__(self
, value
):
1638 return value
in self
.x
1644 vereq(hash(p0
), hash(0))
1647 verify(not p0
!= p0
)
1649 vereq(cmp(p0
, p1
), -1)
1650 vereq(cmp(p0
, p0
), 0)
1651 vereq(cmp(p0
, p_1
), 1)
1652 vereq(str(p0
), "DProxy:0")
1653 vereq(repr(p0
), "DProxy(0)")
1654 p10
= DProxy(range(10))
1655 verify(-1 not in p10
)
1658 verify(10 not in p10
)
1659 # Safety test for __cmp__
1660 def unsafecmp(a
, b
):
1662 a
.__class
__.__cmp
__(a
, b
)
1666 raise TestFailed
, "shouldn't allow %s.__cmp__(%r, %r)" % (
1668 unsafecmp(u
"123", "123")
1669 unsafecmp("123", u
"123")
1676 if verbose
: print "Testing weak references..."
1686 class NoWeak(object):
1691 except TypeError, msg
:
1692 verify(str(msg
).find("weak reference") >= 0)
1694 verify(0, "weakref.ref(no) should be illegal")
1696 __slots__
= ['foo', '__weakref__']
1698 r
= weakref
.ref(yes
)
1705 if verbose
: print "Testing property..."
1709 def setx(self
, value
):
1713 x
= property(getx
, setx
, delx
, doc
="I'm the x property.")
1715 verify(not hasattr(a
, "x"))
1720 verify(not hasattr(a
, "x"))
1721 verify(not hasattr(a
, "_C__x"))
1723 vereq(C
.x
.__get
__(a
), 100)
1725 ## verify(not hasattr(a, "x"))
1727 raw
= C
.__dict
__['x']
1728 verify(isinstance(raw
, property))
1731 verify("__doc__" in attrs
)
1732 verify("fget" in attrs
)
1733 verify("fset" in attrs
)
1734 verify("fdel" in attrs
)
1736 vereq(raw
.__doc
__, "I'm the x property.")
1737 verify(raw
.fget
is C
.__dict
__['getx'])
1738 verify(raw
.fset
is C
.__dict
__['setx'])
1739 verify(raw
.fdel
is C
.__dict
__['delx'])
1741 for attr
in "__doc__", "fget", "fset", "fdel":
1743 setattr(raw
, attr
, 42)
1744 except TypeError, msg
:
1745 if str(msg
).find('readonly') < 0:
1746 raise TestFailed("when setting readonly attr %r on a "
1747 "property, got unexpected TypeError "
1748 "msg %r" % (attr
, str(msg
)))
1750 raise TestFailed("expected TypeError from trying to set "
1751 "readonly %r attr on a property" % attr
)
1754 if verbose
: print "Testing super..."
1760 vereq(A().meth(1), "A(1)")
1764 self
.__super
= super(B
, self
)
1766 return "B(%r)" % a
+ self
.__super
.meth(a
)
1768 vereq(B().meth(2), "B(2)A(2)")
1772 return "C(%r)" % a
+ self
.__super
.meth(a
)
1773 C
._C
__super
= super(C
)
1775 vereq(C().meth(3), "C(3)A(3)")
1779 return "D(%r)" % a
+ super(D
, self
).meth(a
)
1781 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
1783 # Test for subclassing super
1785 class mysuper(super):
1786 def __init__(self
, *args
):
1787 return super(mysuper
, self
).__init
__(*args
)
1791 return "E(%r)" % a
+ mysuper(E
, self
).meth(a
)
1793 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
1798 return "F(%r)[%s]" % (a
, s
.__class
__.__name
__) + s
.meth(a
)
1799 F
._F
__super
= mysuper(F
)
1801 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
1803 # Make sure certain errors are raised
1810 raise TestFailed
, "shouldn't allow super(D, 42)"
1817 raise TestFailed
, "shouldn't allow super(D, C())"
1820 super(D
).__get
__(12)
1824 raise TestFailed
, "shouldn't allow super(D).__get__(12)"
1827 super(D
).__get
__(C())
1831 raise TestFailed
, "shouldn't allow super(D).__get__(C())"
1834 if verbose
: print "Testing inheritance from basic types..."
1839 def __add__(self
, other
):
1840 return hexint(int.__add
__(self
, other
))
1841 # (Note that overriding __radd__ doesn't work,
1842 # because the int type gets first dibs.)
1843 vereq(repr(hexint(7) + 9), "0x10")
1844 vereq(repr(hexint(1000) + 7), "0x3ef")
1847 vereq(int(a
), 12345)
1848 verify(int(a
).__class
__ is int)
1849 vereq(hash(a
), hash(12345))
1850 verify((+a
).__class
__ is int)
1851 verify((a
>> 0).__class
__ is int)
1852 verify((a
<< 0).__class
__ is int)
1853 verify((hexint(0) << 12).__class
__ is int)
1854 verify((hexint(0) >> 12).__class
__ is int)
1856 class octlong(long):
1863 def __add__(self
, other
):
1864 return self
.__class
__(super(octlong
, self
).__add
__(other
))
1866 vereq(str(octlong(3) + 5), "010")
1867 # (Note that overriding __radd__ here only seems to work
1868 # because the example uses a short int left argument.)
1869 vereq(str(5 + octlong(3000)), "05675")
1872 vereq(long(a
), 12345L)
1873 vereq(hash(a
), hash(12345L))
1874 verify(long(a
).__class
__ is long)
1875 verify((+a
).__class
__ is long)
1876 verify((-a
).__class
__ is long)
1877 verify((-octlong(0)).__class
__ is long)
1878 verify((a
>> 0).__class
__ is long)
1879 verify((a
<< 0).__class
__ is long)
1880 verify((a
- 0).__class
__ is long)
1881 verify((a
* 1).__class
__ is long)
1882 verify((a
** 1).__class
__ is long)
1883 verify((a
// 1).__class
__ is long)
1884 verify((1 * a
).__class
__ is long)
1885 verify((a |
0).__class
__ is long)
1886 verify((a ^
0).__class
__ is long)
1887 verify((a
& -1L).__class
__ is long)
1888 verify((octlong(0) << 12).__class
__ is long)
1889 verify((octlong(0) >> 12).__class
__ is long)
1890 verify(abs(octlong(0)).__class
__ is long)
1892 # Because octlong overrides __add__, we can't check the absence of +0
1893 # optimizations using octlong.
1894 class longclone(long):
1897 verify((a
+ 0).__class
__ is long)
1898 verify((0 + a
).__class
__ is long)
1900 # Check that negative clones don't segfault
1902 vereq(a
.__dict
__, {})
1903 vereq(long(a
), -1) # verify PyNumber_Long() copies the sign bit
1905 class precfloat(float):
1906 __slots__
= ['prec']
1907 def __init__(self
, value
=0.0, prec
=12):
1908 self
.prec
= int(prec
)
1909 float.__init
__(value
)
1911 return "%.*g" % (self
.prec
, self
)
1912 vereq(repr(precfloat(1.1)), "1.1")
1913 a
= precfloat(12345)
1915 vereq(float(a
), 12345.0)
1916 verify(float(a
).__class
__ is float)
1917 vereq(hash(a
), hash(12345.0))
1918 verify((+a
).__class
__ is float)
1920 class madcomplex(complex):
1922 return "%.17gj%+.17g" % (self
.imag
, self
.real
)
1923 a
= madcomplex(-3, 4)
1924 vereq(repr(a
), "4j-3")
1925 base
= complex(-3, 4)
1926 veris(base
.__class
__, complex)
1928 vereq(complex(a
), base
)
1929 veris(complex(a
).__class
__, complex)
1930 a
= madcomplex(a
) # just trying another form of the constructor
1931 vereq(repr(a
), "4j-3")
1933 vereq(complex(a
), base
)
1934 veris(complex(a
).__class
__, complex)
1935 vereq(hash(a
), hash(base
))
1936 veris((+a
).__class
__, complex)
1937 veris((a
+ 0).__class
__, complex)
1939 veris((a
- 0).__class
__, complex)
1941 veris((a
* 1).__class
__, complex)
1943 veris((a
/ 1).__class
__, complex)
1946 class madtuple(tuple):
1949 if self
._rev
is not None:
1953 self
._rev
= self
.__class
__(L
)
1955 a
= madtuple((1,2,3,4,5,6,7,8,9,0))
1956 vereq(a
, (1,2,3,4,5,6,7,8,9,0))
1957 vereq(a
.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
1958 vereq(a
.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
1959 for i
in range(512):
1960 t
= madtuple(range(i
))
1964 a
= madtuple((1,2,3,4,5))
1965 vereq(tuple(a
), (1,2,3,4,5))
1966 verify(tuple(a
).__class
__ is tuple)
1967 vereq(hash(a
), hash((1,2,3,4,5)))
1968 verify(a
[:].__class
__ is tuple)
1969 verify((a
* 1).__class
__ is tuple)
1970 verify((a
* 0).__class
__ is tuple)
1971 verify((a
+ ()).__class
__ is tuple)
1974 verify(tuple(a
).__class
__ is tuple)
1975 verify((a
+ a
).__class
__ is tuple)
1976 verify((a
* 0).__class
__ is tuple)
1977 verify((a
* 1).__class
__ is tuple)
1978 verify((a
* 2).__class
__ is tuple)
1979 verify(a
[:].__class
__ is tuple)
1981 class madstring(str):
1984 if self
._rev
is not None:
1988 self
._rev
= self
.__class
__("".join(L
))
1990 s
= madstring("abcdefghijklmnopqrstuvwxyz")
1991 vereq(s
, "abcdefghijklmnopqrstuvwxyz")
1992 vereq(s
.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
1993 vereq(s
.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
1994 for i
in range(256):
1995 s
= madstring("".join(map(chr, range(i
))))
1999 s
= madstring("12345")
2000 vereq(str(s
), "12345")
2001 verify(str(s
).__class
__ is str)
2007 verify(str(s
).__class
__ is str)
2008 vereq(hash(s
), hash(base
))
2009 vereq({s
: 1}[base
], 1)
2010 vereq({base
: 1}[s
], 1)
2011 verify((s
+ "").__class
__ is str)
2013 verify(("" + s
).__class
__ is str)
2015 verify((s
* 0).__class
__ is str)
2017 verify((s
* 1).__class
__ is str)
2019 verify((s
* 2).__class
__ is str)
2020 vereq(s
* 2, base
+ base
)
2021 verify(s
[:].__class
__ is str)
2023 verify(s
[0:0].__class
__ is str)
2025 verify(s
.strip().__class
__ is str)
2026 vereq(s
.strip(), base
)
2027 verify(s
.lstrip().__class
__ is str)
2028 vereq(s
.lstrip(), base
)
2029 verify(s
.rstrip().__class
__ is str)
2030 vereq(s
.rstrip(), base
)
2031 identitytab
= ''.join([chr(i
) for i
in range(256)])
2032 verify(s
.translate(identitytab
).__class
__ is str)
2033 vereq(s
.translate(identitytab
), base
)
2034 verify(s
.translate(identitytab
, "x").__class
__ is str)
2035 vereq(s
.translate(identitytab
, "x"), base
)
2036 vereq(s
.translate(identitytab
, "\x00"), "")
2037 verify(s
.replace("x", "x").__class
__ is str)
2038 vereq(s
.replace("x", "x"), base
)
2039 verify(s
.ljust(len(s
)).__class
__ is str)
2040 vereq(s
.ljust(len(s
)), base
)
2041 verify(s
.rjust(len(s
)).__class
__ is str)
2042 vereq(s
.rjust(len(s
)), base
)
2043 verify(s
.center(len(s
)).__class
__ is str)
2044 vereq(s
.center(len(s
)), base
)
2045 verify(s
.lower().__class
__ is str)
2046 vereq(s
.lower(), base
)
2048 s
= madstring("x y")
2050 verify(intern(s
).__class
__ is str)
2051 verify(intern(s
) is intern("x y"))
2052 vereq(intern(s
), "x y")
2055 s
= madstring("y x")
2057 verify(intern(s
).__class
__ is str)
2058 verify(intern(s
) is i
)
2061 verify(intern(s
).__class
__ is str)
2062 verify(intern(s
) is i
)
2064 class madunicode(unicode):
2067 if self
._rev
is not None:
2071 self
._rev
= self
.__class
__(u
"".join(L
))
2073 u
= madunicode("ABCDEF")
2075 vereq(u
.rev(), madunicode(u
"FEDCBA"))
2076 vereq(u
.rev().rev(), madunicode(u
"ABCDEF"))
2078 u
= madunicode(base
)
2079 vereq(unicode(u
), base
)
2080 verify(unicode(u
).__class
__ is unicode)
2081 vereq(hash(u
), hash(base
))
2082 vereq({u
: 1}[base
], 1)
2083 vereq({base
: 1}[u
], 1)
2084 verify(u
.strip().__class
__ is unicode)
2085 vereq(u
.strip(), base
)
2086 verify(u
.lstrip().__class
__ is unicode)
2087 vereq(u
.lstrip(), base
)
2088 verify(u
.rstrip().__class
__ is unicode)
2089 vereq(u
.rstrip(), base
)
2090 verify(u
.replace(u
"x", u
"x").__class
__ is unicode)
2091 vereq(u
.replace(u
"x", u
"x"), base
)
2092 verify(u
.replace(u
"xy", u
"xy").__class
__ is unicode)
2093 vereq(u
.replace(u
"xy", u
"xy"), base
)
2094 verify(u
.center(len(u
)).__class
__ is unicode)
2095 vereq(u
.center(len(u
)), base
)
2096 verify(u
.ljust(len(u
)).__class
__ is unicode)
2097 vereq(u
.ljust(len(u
)), base
)
2098 verify(u
.rjust(len(u
)).__class
__ is unicode)
2099 vereq(u
.rjust(len(u
)), base
)
2100 verify(u
.lower().__class
__ is unicode)
2101 vereq(u
.lower(), base
)
2102 verify(u
.upper().__class
__ is unicode)
2103 vereq(u
.upper(), base
)
2104 verify(u
.capitalize().__class
__ is unicode)
2105 vereq(u
.capitalize(), base
)
2106 verify(u
.title().__class
__ is unicode)
2107 vereq(u
.title(), base
)
2108 verify((u
+ u
"").__class
__ is unicode)
2109 vereq(u
+ u
"", base
)
2110 verify((u
"" + u
).__class
__ is unicode)
2111 vereq(u
"" + u
, base
)
2112 verify((u
* 0).__class
__ is unicode)
2114 verify((u
* 1).__class
__ is unicode)
2116 verify((u
* 2).__class
__ is unicode)
2117 vereq(u
* 2, base
+ base
)
2118 verify(u
[:].__class
__ is unicode)
2120 verify(u
[0:0].__class
__ is unicode)
2123 class sublist(list):
2125 a
= sublist(range(5))
2128 vereq(a
, range(5) + ["hello"])
2131 a
.extend(range(6, 20))
2138 vereq(list(a
), range(10))
2143 vereq(a
[:5], range(5))
2145 class CountedInput(file):
2146 """Counts lines read by self.readline().
2148 self.lineno is the 0-based ordinal of the last line read, up to
2149 a maximum of one greater than the number of lines in the file.
2151 self.ateof is true if and only if the final "" line has been read,
2152 at which point self.lineno stops incrementing, and further calls
2153 to readline() continue to return "".
2161 s
= file.readline(self
)
2162 # Next line works too.
2163 # s = super(CountedInput, self).readline()
2169 f
= file(name
=TESTFN
, mode
='w')
2170 lines
= ['a\n', 'b\n', 'c\n']
2174 f
= CountedInput(TESTFN
)
2175 for (i
, expected
) in zip(range(1, 5) + [4], lines
+ 2 * [""]):
2177 vereq(expected
, got
)
2179 vereq(f
.ateof
, (i
> len(lines
)))
2194 print "Testing keyword args to basic type constructors ..."
2196 vereq(float(x
=2), 2.0)
2197 vereq(long(x
=3), 3L)
2198 vereq(complex(imag
=42, real
=666), complex(666, 42))
2199 vereq(str(object=500), '500')
2200 vereq(unicode(string
='abc', errors
='strict'), u
'abc')
2201 vereq(tuple(sequence
=range(3)), (0, 1, 2))
2202 vereq(list(sequence
=(0, 1, 2)), range(3))
2203 vereq(dict(items
={1: 2}), {1: 2})
2205 for constructor
in (int, float, long, complex, str, unicode,
2206 tuple, list, dict, file):
2208 constructor(bogus_keyword_arg
=1)
2212 raise TestFailed("expected TypeError from bogus keyword "
2213 "argument to %r" % constructor
)
2218 print "Testing interaction with restricted execution ..."
2220 sandbox
= rexec
.RExec()
2222 code1
= """f = open(%r, 'w')""" % TESTFN
2223 code2
= """f = file(%r, 'w')""" % TESTFN
2226 t = type(f) # a sneaky way to get the file() constructor
2228 f = t(%r, 'w') # rexec can't catch this by itself
2229 """ % (TESTFN
, TESTFN
)
2231 f
= open(TESTFN
, 'w') # Create the file so code3 can find it.
2235 for code
in code1
, code2
, code3
:
2237 sandbox
.r_exec(code
)
2238 except IOError, msg
:
2239 if str(msg
).find("restricted") >= 0:
2242 outcome
= "got an exception, but not an expected one"
2244 outcome
= "expected a restricted-execution exception"
2247 raise TestFailed("%s, in %r" % (outcome
, code
))
2256 def str_subclass_as_dict_key():
2258 print "Testing a str subclass used as dict key .."
2261 """Sublcass of str that computes __eq__ case-insensitively.
2263 Also computes a hash code of the string in canonical form.
2266 def __init__(self
, value
):
2267 self
.canonical
= value
.lower()
2268 self
.hashcode
= hash(self
.canonical
)
2270 def __eq__(self
, other
):
2271 if not isinstance(other
, cistr
):
2272 other
= cistr(other
)
2273 return self
.canonical
== other
.canonical
2276 return self
.hashcode
2278 vereq(cistr('ABC'), 'abc')
2279 vereq('aBc', cistr('ABC'))
2280 vereq(str(cistr('ABC')), 'ABC')
2282 d
= {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2283 vereq(d
[cistr('one')], 1)
2284 vereq(d
[cistr('tWo')], 2)
2285 vereq(d
[cistr('THrEE')], 3)
2286 verify(cistr('ONe') in d
)
2287 vereq(d
.get(cistr('thrEE')), 3)
2289 def classic_comparisons():
2290 if verbose
: print "Testing classic comparisons..."
2293 for base
in (classic
, int, object):
2294 if verbose
: print " (base = %s)" % base
2296 def __init__(self
, value
):
2297 self
.value
= int(value
)
2298 def __cmp__(self
, other
):
2299 if isinstance(other
, C
):
2300 return cmp(self
.value
, other
.value
)
2301 if isinstance(other
, int) or isinstance(other
, long):
2302 return cmp(self
.value
, other
)
2303 return NotImplemented
2308 c
= {1: c1
, 2: c2
, 3: c3
}
2311 verify(cmp(c
[x
], c
[y
]) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2312 for op
in "<", "<=", "==", "!=", ">", ">=":
2313 verify(eval("c[x] %s c[y]" % op
) == eval("x %s y" % op
),
2314 "x=%d, y=%d" % (x
, y
))
2315 verify(cmp(c
[x
], y
) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2316 verify(cmp(x
, c
[y
]) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2318 def rich_comparisons():
2320 print "Testing rich comparisons..."
2327 def __eq__(self
, other
):
2329 return abs(self
- other
) <= 1e-6
2331 return NotImplemented
2338 for base
in (classic
, int, object, list):
2339 if verbose
: print " (base = %s)" % base
2341 def __init__(self
, value
):
2342 self
.value
= int(value
)
2343 def __cmp__(self
, other
):
2344 raise TestFailed
, "shouldn't call __cmp__"
2345 def __eq__(self
, other
):
2346 if isinstance(other
, C
):
2347 return self
.value
== other
.value
2348 if isinstance(other
, int) or isinstance(other
, long):
2349 return self
.value
== other
2350 return NotImplemented
2351 def __ne__(self
, other
):
2352 if isinstance(other
, C
):
2353 return self
.value
!= other
.value
2354 if isinstance(other
, int) or isinstance(other
, long):
2355 return self
.value
!= other
2356 return NotImplemented
2357 def __lt__(self
, other
):
2358 if isinstance(other
, C
):
2359 return self
.value
< other
.value
2360 if isinstance(other
, int) or isinstance(other
, long):
2361 return self
.value
< other
2362 return NotImplemented
2363 def __le__(self
, other
):
2364 if isinstance(other
, C
):
2365 return self
.value
<= other
.value
2366 if isinstance(other
, int) or isinstance(other
, long):
2367 return self
.value
<= other
2368 return NotImplemented
2369 def __gt__(self
, other
):
2370 if isinstance(other
, C
):
2371 return self
.value
> other
.value
2372 if isinstance(other
, int) or isinstance(other
, long):
2373 return self
.value
> other
2374 return NotImplemented
2375 def __ge__(self
, other
):
2376 if isinstance(other
, C
):
2377 return self
.value
>= other
.value
2378 if isinstance(other
, int) or isinstance(other
, long):
2379 return self
.value
>= other
2380 return NotImplemented
2385 c
= {1: c1
, 2: c2
, 3: c3
}
2388 for op
in "<", "<=", "==", "!=", ">", ">=":
2389 verify(eval("c[x] %s c[y]" % op
) == eval("x %s y" % op
),
2390 "x=%d, y=%d" % (x
, y
))
2391 verify(eval("c[x] %s y" % op
) == eval("x %s y" % op
),
2392 "x=%d, y=%d" % (x
, y
))
2393 verify(eval("x %s c[y]" % op
) == eval("x %s y" % op
),
2394 "x=%d, y=%d" % (x
, y
))
2397 if verbose
: print "Testing coercions..."
2406 class F(float): pass
2413 class C(complex): pass
2424 if verbose
: print "Testing descriptor doc strings..."
2425 def check(descr
, what
):
2426 vereq(descr
.__doc
__, what
)
2427 check(file.closed
, "True if the file is closed") # getset descriptor
2428 check(file.name
, "file name") # member descriptor
2431 if verbose
: print "Testing __class__ assignment..."
2432 class C(object): pass
2433 class D(object): pass
2434 class E(object): pass
2436 for cls
in C
, D
, E
, F
:
2437 for cls2
in C
, D
, E
, F
:
2440 verify(x
.__class
__ is cls2
)
2442 verify(x
.__class
__ is cls
)
2449 raise TestFailed
, "shouldn't allow %r.__class__ = %r" % (x
, C
)
2451 delattr(x
, "__class__")
2455 raise TestFailed
, "shouldn't allow del %r.__class__" % x
2460 cant(object(), list)
2461 cant(list(), object)
2464 if verbose
: print "Testing __dict__ assignment..."
2465 class C(object): pass
2467 a
.__dict
__ = {'b': 1}
2475 raise TestFailed
, "shouldn't allow %r.__dict__ = %r" % (x
, dict)
2479 del a
.__dict
__ # Deleting __dict__ is allowed
2480 # Classes don't allow __dict__ assignment
2485 print "Testing pickling and copying new-style classes and objects..."
2486 import pickle
, cPickle
2495 def __init__(self
, a
, b
):
2496 super(C
, self
).__init
__()
2500 return "C(%r, %r)" % (self
.a
, self
.b
)
2504 def __new__(cls
, a
, b
):
2505 return super(C1
, cls
).__new
__(cls
)
2506 def __init__(self
, a
, b
):
2510 return "C1(%r, %r)<%r>" % (self
.a
, self
.b
, list(self
))
2514 def __new__(cls
, a
, b
, val
=0):
2515 return super(C2
, cls
).__new
__(cls
, val
)
2516 def __init__(self
, a
, b
, val
=0):
2520 return "C2(%r, %r)<%r>" % (self
.a
, self
.b
, int(self
))
2524 def __init__(self
, foo
):
2526 def __getstate__(self
):
2528 def __setstate__(self
, foo
):
2531 global C4classic
, C4
2532 class C4classic
: # classic
2534 class C4(C4classic
, object): # mixed inheritance
2537 for p
in pickle
, cPickle
:
2540 print p
.__name
__, ["text", "binary"][bin
]
2542 for cls
in C
, C1
, C2
:
2543 s
= p
.dumps(cls
, bin
)
2547 a
= C1(1, 2); a
.append(42); a
.append(24)
2548 b
= C2("hello", "world", 42)
2549 s
= p
.dumps((a
, b
), bin
)
2551 vereq(x
.__class
__, a
.__class
__)
2552 vereq(sorteditems(x
.__dict
__), sorteditems(a
.__dict
__))
2553 vereq(y
.__class
__, b
.__class
__)
2554 vereq(sorteditems(y
.__dict
__), sorteditems(b
.__dict
__))
2560 # Test for __getstate__ and __setstate__ on new style class
2564 veris(u
.__class
__, v
.__class
__)
2566 # Test for picklability of hybrid class
2571 veris(u
.__class
__, v
.__class
__)
2574 # Testing copy.deepcopy()
2578 for cls
in C
, C1
, C2
:
2579 cls2
= copy
.deepcopy(cls
)
2582 a
= C1(1, 2); a
.append(42); a
.append(24)
2583 b
= C2("hello", "world", 42)
2584 x
, y
= copy
.deepcopy((a
, b
))
2585 vereq(x
.__class
__, a
.__class
__)
2586 vereq(sorteditems(x
.__dict
__), sorteditems(a
.__dict
__))
2587 vereq(y
.__class
__, b
.__class
__)
2588 vereq(sorteditems(y
.__dict
__), sorteditems(b
.__dict
__))
2596 if verbose
: print "Testing pickling of classes with __slots__ ..."
2597 import pickle
, cPickle
2598 # Pickling of classes with __slots__ but without __getstate__ should fail
2602 for base
in [object, B
]:
2612 raise TestFailed
, "should fail: pickle C instance - %s" % base
2618 raise TestFailed
, "should fail: cPickle C instance - %s" % base
2624 raise TestFailed
, "should fail: pickle D instance - %s" % base
2630 raise TestFailed
, "should fail: cPickle D instance - %s" % base
2631 # Give C a __getstate__ and __setstate__
2634 def __getstate__(self
):
2636 d
= self
.__dict
__.copy()
2637 except AttributeError:
2641 except AttributeError:
2644 def __setstate__(self
, d
):
2645 for k
, v
in d
.items():
2649 # Now it should work
2651 y
= pickle
.loads(pickle
.dumps(x
))
2652 vereq(hasattr(y
, 'a'), 0)
2653 y
= cPickle
.loads(cPickle
.dumps(x
))
2654 vereq(hasattr(y
, 'a'), 0)
2656 y
= pickle
.loads(pickle
.dumps(x
))
2658 y
= cPickle
.loads(cPickle
.dumps(x
))
2663 y
= pickle
.loads(pickle
.dumps(x
))
2664 vereq(y
.a
+ y
.b
, 142)
2665 y
= cPickle
.loads(cPickle
.dumps(x
))
2666 vereq(y
.a
+ y
.b
, 142)
2667 # But a subclass that adds a slot should not work
2675 raise TestFailed
, "should fail: pickle E instance - %s" % base
2681 raise TestFailed
, "should fail: cPickle E instance - %s" % base
2684 if verbose
: print "Testing copy.copy() and copy.deepcopy()..."
2692 vereq(b
.__dict
__, a
.__dict
__)
2697 verify(c
.bar
is a
.bar
)
2699 d
= copy
.deepcopy(a
)
2700 vereq(d
.__dict
__, a
.__dict
__)
2702 vereq(d
.bar
, [1,2,3])
2704 def binopoverride():
2705 if verbose
: print "Testing overrides of binary operations..."
2708 return "I(%r)" % int(self
)
2709 def __add__(self
, other
):
2710 return I(int(self
) + int(other
))
2712 def __pow__(self
, other
, mod
=None):
2714 return I(pow(int(self
), int(other
)))
2716 return I(pow(int(self
), int(other
), int(mod
)))
2717 def __rpow__(self
, other
, mod
=None):
2719 return I(pow(int(other
), int(self
), mod
))
2721 return I(pow(int(other
), int(self
), int(mod
)))
2723 vereq(`
I(1) + I(2)`
, "I(3)")
2724 vereq(`
I(1) + 2`
, "I(3)")
2725 vereq(`
1 + I(2)`
, "I(3)")
2726 vereq(`
I(2) ** I(3)`
, "I(8)")
2727 vereq(`
2 ** I(3)`
, "I(8)")
2728 vereq(`
I(2) ** 3`
, "I(8)")
2729 vereq(`
pow(I(2), I(3), I(5))`
, "I(3)")
2731 def __eq__(self
, other
):
2732 return self
.lower() == other
.lower()
2734 def subclasspropagation():
2735 if verbose
: print "Testing propagation of slot functions to subclasses..."
2745 vereq(hash(d
), id(d
))
2746 A
.__hash
__ = lambda self
: 42
2748 C
.__hash
__ = lambda self
: 314
2750 B
.__hash
__ = lambda self
: 144
2752 D
.__hash
__ = lambda self
: 100
2761 vereq(hash(d
), id(d
))
2766 def __getattribute__(self
, name
):
2769 return object.__getattribute
__(self
, name
)
2770 A
.__getattribute
__ = __getattribute__
2773 def __getattr__(self
, name
):
2774 if name
in ("spam", "foo", "bar"):
2776 raise AttributeError, name
2777 B
.__getattr
__ = __getattr__
2778 vereq(d
.spam
, "hello")
2781 del A
.__getattribute
__
2784 vereq(d
.foo
, "hello")
2789 except AttributeError:
2792 raise TestFailed
, "d.foo should be undefined now"
2794 # Test a nasty bug in recurse_down_subclasses()
2802 A
.__setitem
__ = lambda *a
: None # crash
2804 def buffer_inherit():
2806 # SF bug [#470040] ParseTuple t# vs subclasses.
2808 print "Testing that buffer interface is inherited ..."
2814 # b2a_hex uses the buffer interface to get its argument's value, via
2815 # PyArg_ParseTuple 't#' code.
2816 vereq(binascii
.b2a_hex(m
), binascii
.b2a_hex(base
))
2818 # It's not clear that unicode will continue to support the character
2819 # buffer interface, and this test will fail if that's taken away.
2820 class MyUni(unicode):
2824 vereq(binascii
.b2a_hex(m
), binascii
.b2a_hex(base
))
2831 raise TestFailed('subclass of int should not have a buffer interface')
2835 def str_of_str_subclass():
2840 print "Testing __str__ defined in subclass of str ..."
2842 class octetstring(str):
2844 return binascii
.b2a_hex(self
)
2846 return self
+ " repr"
2848 o
= octetstring('A')
2849 vereq(type(o
), octetstring
)
2850 vereq(type(str(o
)), str)
2851 vereq(type(repr(o
)), str)
2854 vereq(repr(o
), 'A repr')
2855 vereq(o
.__str
__(), '41')
2856 vereq(o
.__repr
__(), 'A repr')
2858 capture
= cStringIO
.StringIO()
2859 # Calling str() or not exercises different internal paths.
2861 print >> capture
, str(o
)
2862 vereq(capture
.getvalue(), '41\n41\n')
2866 if verbose
: print "Testing keyword arguments to __init__, __call__..."
2868 vereq(f
.__call
__(a
=42), 42)
2870 list.__init
__(a
, sequence
=[0, 1, 2])
2874 if verbose
: print "Testing __del__ hook..."
2884 class D(object): pass
2887 except TypeError: pass
2888 else: raise TestFailed
, "invalid del() didn't raise TypeError"
2891 if verbose
: print "Testing hash of mutable subclasses..."
2901 raise TestFailed
, "hash() of dict subclass should fail"
2911 raise TestFailed
, "hash() of list subclass should fail"
2915 except TypeError: pass
2916 else: raise TestFailed
, "'' + 5 doesn't raise TypeError"
2919 except ValueError: pass
2920 else: raise TestFailed
, "''.split('') doesn't raise ValueError"
2923 except TypeError: pass
2924 else: raise TestFailed
, "''.join([0]) doesn't raise TypeError"
2927 except ValueError: pass
2928 else: raise TestFailed
, "''.rindex('5') doesn't raise ValueError"
2930 try: ''.replace('', '')
2931 except ValueError: pass
2932 else: raise TestFailed
, "''.replace('', '') doesn't raise ValueError"
2935 except TypeError: pass
2936 else: raise TestFailed
, "'%(n)s' % None doesn't raise TypeError"
2939 except ValueError: pass
2940 else: raise TestFailed
, "'%(n' % {} '' doesn't raise ValueError"
2942 try: '%*s' % ('abc')
2943 except TypeError: pass
2944 else: raise TestFailed
, "'%*s' % ('abc') doesn't raise TypeError"
2946 try: '%*.*s' % ('abc', 5)
2947 except TypeError: pass
2948 else: raise TestFailed
, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
2951 except TypeError: pass
2952 else: raise TestFailed
, "'%s' % (1, 2) doesn't raise TypeError"
2955 except ValueError: pass
2956 else: raise TestFailed
, "'%' % None doesn't raise ValueError"
2958 vereq('534253'.isdigit(), 1)
2959 vereq('534253x'.isdigit(), 0)
2960 vereq('%c' % 5, '\x05')
2961 vereq('%c' % '5', '5')
2963 def deepcopyrecursive():
2964 if verbose
: print "Testing deepcopy of recursive objects..."
2971 z
= deepcopy(a
) # This blew up before
2974 if verbose
: print "Testing uninitialized module objects..."
2975 from types
import ModuleType
as M
2978 vereq(hasattr(m
, "__name__"), 0)
2979 vereq(hasattr(m
, "__file__"), 0)
2980 vereq(hasattr(m
, "foo"), 0)
2981 vereq(m
.__dict
__, None)
2983 vereq(m
.__dict
__, {"foo": 1})
2985 def dictproxyiterkeys():
2989 if verbose
: print "Testing dict-proxy iterkeys..."
2990 keys
= [ key
for key
in C
.__dict
__.iterkeys() ]
2992 vereq(keys
, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
2994 def dictproxyitervalues():
2998 if verbose
: print "Testing dict-proxy itervalues..."
2999 values
= [ values
for values
in C
.__dict
__.itervalues() ]
3000 vereq(len(values
), 5)
3002 def dictproxyiteritems():
3006 if verbose
: print "Testing dict-proxy iteritems..."
3007 keys
= [ key
for (key
, value
) in C
.__dict
__.iteritems() ]
3009 vereq(keys
, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3012 if verbose
: print "Testing __new__ returning something unexpected..."
3014 def __new__(cls
, arg
):
3015 if isinstance(arg
, str): return [1, 2, 3]
3016 elif isinstance(arg
, int): return object.__new
__(D
)
3017 else: return object.__new
__(cls
)
3019 def __init__(self
, arg
):
3021 vereq(C("1"), [1, 2, 3])
3022 vereq(D("1"), [1, 2, 3])
3026 vereq(isinstance(d
, D
), True)
3029 vereq(isinstance(d
, D
), True)
3034 if verbose
: print "Testing for __imul__ problems..."
3036 def __imul__(self
, other
):
3037 return (self
, other
)
3050 vereq(y
, (x
, 1L<<100))
3056 vereq(y
, (x
, "foo"))
3058 def docdescriptor():
3060 if verbose
: print "Testing __doc__ descriptor..."
3061 class DocDescr(object):
3062 def __get__(self
, object, otype
):
3064 object = object.__class
__.__name
__ + ' instance'
3066 otype
= otype
.__name
__
3067 return 'object=%s; type=%s' % (object, otype
)
3069 __doc__
= DocDescr()
3070 class NewClass(object):
3071 __doc__
= DocDescr()
3072 vereq(OldClass
.__doc
__, 'object=None; type=OldClass')
3073 vereq(OldClass().__doc
__, 'object=OldClass instance; type=OldClass')
3074 vereq(NewClass
.__doc
__, 'object=None; type=NewClass')
3075 vereq(NewClass().__doc
__, 'object=NewClass instance; type=NewClass')
3077 def string_exceptions():
3079 print "Testing string exceptions ..."
3081 # Ensure builtin strings work OK as exceptions.
3082 astring
= "An exception string."
3088 raise TestFailed
, "builtin string not usable as exception"
3090 # Ensure string subclass instances do not.
3094 newstring
= MyStr("oops -- shouldn't work")
3100 raise TestFailed
, "string subclass allowed as exception"
3102 def copy_setstate():
3104 print "Testing that copy.*copy() correctly uses __setstate__..."
3107 def __init__(self
, foo
=None):
3110 def setfoo(self
, foo
=None):
3114 def __getstate__(self
):
3116 def __setstate__(self
, lst
):
3117 assert len(lst
) == 1
3118 self
.__foo
= self
.foo
= lst
[0]
3122 vereq(a
.getfoo(), 42)
3125 vereq(b
.getfoo(), 24)
3126 b
= copy
.deepcopy(a
)
3128 vereq(b
.getfoo(), 24)
3132 print "Testing cases with slices and overridden __getitem__ ..."
3134 vereq("hello"[:4], "hell")
3135 vereq("hello"[slice(4)], "hell")
3136 vereq(str.__getitem
__("hello", slice(4)), "hell")
3138 def __getitem__(self
, x
):
3139 return str.__getitem
__(self
, x
)
3140 vereq(S("hello")[:4], "hell")
3141 vereq(S("hello")[slice(4)], "hell")
3142 vereq(S("hello").__getitem
__(slice(4)), "hell")
3144 vereq((1,2,3)[:2], (1,2))
3145 vereq((1,2,3)[slice(2)], (1,2))
3146 vereq(tuple.__getitem
__((1,2,3), slice(2)), (1,2))
3148 def __getitem__(self
, x
):
3149 return tuple.__getitem
__(self
, x
)
3150 vereq(T((1,2,3))[:2], (1,2))
3151 vereq(T((1,2,3))[slice(2)], (1,2))
3152 vereq(T((1,2,3)).__getitem
__(slice(2)), (1,2))
3154 vereq([1,2,3][:2], [1,2])
3155 vereq([1,2,3][slice(2)], [1,2])
3156 vereq(list.__getitem
__([1,2,3], slice(2)), [1,2])
3158 def __getitem__(self
, x
):
3159 return list.__getitem
__(self
, x
)
3160 vereq(L([1,2,3])[:2], [1,2])
3161 vereq(L([1,2,3])[slice(2)], [1,2])
3162 vereq(L([1,2,3]).__getitem
__(slice(2)), [1,2])
3163 # Now do lists and __setitem__
3165 a
[slice(1, 3)] = [3,2]
3167 a
[slice(0, 2, 1)] = [3,1]
3169 a
.__setitem
__(slice(1, 3), [2,1])
3171 a
.__setitem
__(slice(0, 2, 1), [2,3])
3175 def do_this_first():
3177 print "Testing SF bug 551412 ..."
3178 # This dumps core when SF bug 551412 isn't fixed --
3179 # but only when test_descr.py is run separately.
3180 # (That can't be helped -- as soon as PyType_Ready()
3181 # is called for PyLong_Type, the bug is gone.)
3182 class UserLong(object):
3183 def __pow__(self
, *args
):
3186 pow(0L, UserLong(), 0L)
3191 print "Testing SF bug 570483..."
3192 # Another segfault only when run early
3193 # (before PyType_Ready(tuple) is called)
3222 staticmethods_in_c()
3236 str_subclass_as_dict_key()
3237 classic_comparisons()
3246 subclasspropagation()
3248 str_of_str_subclass()
3256 dictproxyitervalues()
3257 dictproxyiteritems()
3265 if verbose
: print "All OK"
3267 if __name__
== "__main__":