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
8 raise TestFailed
, "%r is %r" % (a
, b
)
10 def testunop(a
, res
, expr
="len(a)", meth
="__len__"):
11 if verbose
: print "checking", expr
13 vereq(eval(expr
, dict), res
)
16 while meth
not in t
.__dict
__:
18 vereq(m
, t
.__dict
__[meth
])
23 def testbinop(a
, b
, res
, expr
="a+b", meth
="__add__"):
24 if verbose
: print "checking", expr
25 dict = {'a': a
, 'b': b
}
27 # XXX Hack so this passes before 2.3 when -Qnew is specified.
28 if meth
== "__div__" and 1/2 == 0.5:
31 vereq(eval(expr
, dict), res
)
34 while meth
not in t
.__dict
__:
36 vereq(m
, t
.__dict
__[meth
])
41 def testternop(a
, b
, c
, res
, expr
="a[b:c]", meth
="__getslice__"):
42 if verbose
: print "checking", expr
43 dict = {'a': a
, 'b': b
, 'c': c
}
44 vereq(eval(expr
, dict), res
)
47 while meth
not in t
.__dict
__:
49 vereq(m
, t
.__dict
__[meth
])
50 vereq(m(a
, b
, c
), res
)
54 def testsetop(a
, b
, res
, stmt
="a+=b", meth
="__iadd__"):
55 if verbose
: print "checking", stmt
56 dict = {'a': deepcopy(a
), 'b': b
}
61 while meth
not in t
.__dict
__:
63 vereq(m
, t
.__dict
__[meth
])
64 dict['a'] = deepcopy(a
)
67 dict['a'] = deepcopy(a
)
68 bm
= getattr(dict['a'], meth
)
72 def testset2op(a
, b
, c
, res
, stmt
="a[b]=c", meth
="__setitem__"):
73 if verbose
: print "checking", stmt
74 dict = {'a': deepcopy(a
), 'b': b
, 'c': c
}
79 while meth
not in t
.__dict
__:
81 vereq(m
, t
.__dict
__[meth
])
82 dict['a'] = deepcopy(a
)
85 dict['a'] = deepcopy(a
)
86 bm
= getattr(dict['a'], meth
)
90 def testset3op(a
, b
, c
, d
, res
, stmt
="a[b:c]=d", meth
="__setslice__"):
91 if verbose
: print "checking", stmt
92 dict = {'a': deepcopy(a
), 'b': b
, 'c': c
, 'd': d
}
96 while meth
not in t
.__dict
__:
99 vereq(m
, t
.__dict
__[meth
])
100 dict['a'] = deepcopy(a
)
101 m(dict['a'], b
, c
, d
)
102 vereq(dict['a'], res
)
103 dict['a'] = deepcopy(a
)
104 bm
= getattr(dict['a'], meth
)
106 vereq(dict['a'], res
)
108 def class_docstrings():
110 "A classic docstring."
111 vereq(Classic
.__doc
__, "A classic docstring.")
112 vereq(Classic
.__dict
__['__doc__'], "A classic docstring.")
116 verify(Classic2
.__doc__
is None)
118 class NewStatic(object):
120 vereq(NewStatic
.__doc
__, "Another docstring.")
121 vereq(NewStatic
.__dict
__['__doc__'], "Another docstring.")
123 class NewStatic2(object):
125 verify(NewStatic2
.__doc__
is None)
127 class NewDynamic(object):
129 vereq(NewDynamic
.__doc
__, "Another docstring.")
130 vereq(NewDynamic
.__dict
__['__doc__'], "Another docstring.")
132 class NewDynamic2(object):
134 verify(NewDynamic2
.__doc__
is None)
137 if verbose
: print "Testing list operations..."
138 testbinop([1], [2], [1,2], "a+b", "__add__")
139 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
140 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
141 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
142 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
143 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
144 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
145 testunop([1,2,3], 3, "len(a)", "__len__")
146 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
147 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
148 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
149 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
152 if verbose
: print "Testing dict operations..."
153 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
154 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
155 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
156 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
159 for i
in d
.keys(): l1
.append(i
)
161 for i
in iter(d
): l
.append(i
)
164 for i
in d
.__iter
__(): l
.append(i
)
167 for i
in dict.__iter
__(d
): l
.append(i
)
170 testunop(d
, 2, "len(a)", "__len__")
171 vereq(eval(repr(d
), {}), d
)
172 vereq(eval(d
.__repr
__(), {}), d
)
173 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
175 def dict_constructor():
177 print "Testing dict constructor ..."
184 d
= dict({1: 2, 'a': 'b'})
185 vereq(d
, {1: 2, 'a': 'b'})
186 vereq(d
, dict(d
.items()))
187 vereq(d
, dict(items
=d
.iteritems()))
188 for badarg
in 0, 0L, 0j
, "0", [0], (0,):
195 # It's a sequence, and its elements are also sequences (gotta
196 # love strings <wink>), but they aren't of length 2, so this
197 # one seemed better as a ValueError than a TypeError.
200 raise TestFailed("no TypeError from dict(%r)" % badarg
)
202 raise TestFailed("no TypeError from dict(%r)" % badarg
)
208 raise TestFailed("no TypeError from dict(senseless={})")
215 raise TestFailed("no TypeError from dict({}, {})")
218 # Lacks a .keys() method; will be added later.
219 dict = {1:2, 3:4, 'a':1j
}
226 raise TestFailed("no TypeError from dict(incomplete mapping)")
228 Mapping
.keys
= lambda self
: self
.dict.keys()
229 Mapping
.__getitem
__ = lambda self
, i
: self
.dict[i
]
230 d
= dict(items
=Mapping())
231 vereq(d
, Mapping
.dict)
233 # Init from sequence of iterable objects, each producing a 2-sequence.
234 class AddressBookEntry
:
235 def __init__(self
, first
, last
):
239 return iter([self
.first
, self
.last
])
241 d
= dict([AddressBookEntry('Tim', 'Warsaw'),
242 AddressBookEntry('Barry', 'Peters'),
243 AddressBookEntry('Tim', 'Peters'),
244 AddressBookEntry('Barry', 'Warsaw')])
245 vereq(d
, {'Barry': 'Warsaw', 'Tim': 'Peters'})
247 d
= dict(zip(range(4), range(1, 5)))
248 vereq(d
, dict([(i
, i
+1) for i
in range(4)]))
250 # Bad sequence lengths.
251 for bad
in [('tooshort',)], [('too', 'long', 'by 1')]:
257 raise TestFailed("no ValueError from dict(%r)" % bad
)
261 print "Testing dir() ..."
263 vereq(dir(), ['junk'])
266 # Just make sure these don't blow up!
267 for arg
in 2, 2L, 2j
, 2e0
, [2], "2", u
"2", (2,), {2:2}, type, test_dir
:
270 # Try classic classes.
273 def Cmethod(self
): pass
275 cstuff
= ['Cdata', 'Cmethod', '__doc__', '__module__']
276 vereq(dir(C
), cstuff
)
277 verify('im_self' in dir(C
.Cmethod
))
279 c
= C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
280 vereq(dir(c
), cstuff
)
283 c
.cmethod
= lambda self
: 0
284 vereq(dir(c
), cstuff
+ ['cdata', 'cmethod'])
285 verify('im_self' in dir(c
.Cmethod
))
289 def Amethod(self
): pass
291 astuff
= ['Adata', 'Amethod'] + cstuff
292 vereq(dir(A
), astuff
)
293 verify('im_self' in dir(A
.Amethod
))
295 vereq(dir(a
), astuff
)
296 verify('im_self' in dir(a
.Amethod
))
298 a
.amethod
= lambda self
: 3
299 vereq(dir(a
), astuff
+ ['adata', 'amethod'])
301 # The same, but with new-style classes. Since these have object as a
302 # base class, a lot more gets sucked in.
303 def interesting(strings
):
304 return [s
for s
in strings
if not s
.startswith('_')]
308 def Cmethod(self
): pass
310 cstuff
= ['Cdata', 'Cmethod']
311 vereq(interesting(dir(C
)), cstuff
)
314 vereq(interesting(dir(c
)), cstuff
)
315 verify('im_self' in dir(C
.Cmethod
))
318 c
.cmethod
= lambda self
: 0
319 vereq(interesting(dir(c
)), cstuff
+ ['cdata', 'cmethod'])
320 verify('im_self' in dir(c
.Cmethod
))
324 def Amethod(self
): pass
326 astuff
= ['Adata', 'Amethod'] + cstuff
327 vereq(interesting(dir(A
)), astuff
)
328 verify('im_self' in dir(A
.Amethod
))
330 vereq(interesting(dir(a
)), astuff
)
332 a
.amethod
= lambda self
: 3
333 vereq(interesting(dir(a
)), astuff
+ ['adata', 'amethod'])
334 verify('im_self' in dir(a
.Amethod
))
336 # Try a module subclass.
343 vereq(dir(minstance
), ['a', 'b'])
348 __dict__
= property(getdict
)
353 vereq(m2instance
.__dict
__, "Not a dict!")
359 # Two essentially featureless objects, just inheriting stuff from
361 vereq(dir(None), dir(Ellipsis))
385 for name
, expr
in binops
.items():
387 expr
= expr
+ "(a, b)"
389 expr
= 'a %s b' % expr
404 for name
, expr
in unops
.items():
411 def numops(a
, b
, skip
=[]):
412 dict = {'a': a
, 'b': b
}
413 for name
, expr
in binops
.items():
415 name
= "__%s__" % name
417 res
= eval(expr
, dict)
418 testbinop(a
, b
, res
, expr
, name
)
419 for name
, expr
in unops
.items():
421 name
= "__%s__" % name
423 res
= eval(expr
, dict)
424 testunop(a
, res
, expr
, name
)
427 if verbose
: print "Testing int operations..."
431 if verbose
: print "Testing long operations..."
435 if verbose
: print "Testing float operations..."
439 if verbose
: print "Testing complex operations..."
440 numops(100.0j
, 3.0j
, skip
=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
441 class Number(complex):
443 def __new__(cls
, *args
, **kwds
):
444 result
= complex.__new
__(cls
, *args
)
445 result
.prec
= kwds
.get('prec', 12)
450 return "%.*g" % (prec
, self
.real
)
452 return "%.*gj" % (prec
, self
.imag
)
453 return "(%.*g+%.*gj)" % (prec
, self
.real
, prec
, self
.imag
)
456 a
= Number(3.14, prec
=6)
460 a
= Number(a
, prec
=2)
469 if verbose
: print "Testing spamlist operations..."
470 import copy
, xxsubtype
as spam
471 def spamlist(l
, memo
=None):
472 import xxsubtype
as spam
473 return spam
.spamlist(l
)
474 # This is an ugly hack:
475 copy
._deepcopy
_dispatch
[spam
.spamlist
] = spamlist
477 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
478 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
479 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
480 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
481 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
482 "a[b:c]", "__getslice__")
483 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
485 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
486 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
487 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
488 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
489 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
490 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
491 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
493 class C(spam
.spamlist
):
494 def foo(self
): return 1
500 vereq(a
.getstate(), 0)
502 vereq(a
.getstate(), 42)
505 if verbose
: print "Testing spamdict operations..."
506 import copy
, xxsubtype
as spam
507 def spamdict(d
, memo
=None):
508 import xxsubtype
as spam
510 for k
, v
in d
.items(): sd
[k
] = v
512 # This is an ugly hack:
513 copy
._deepcopy
_dispatch
[spam
.spamdict
] = spamdict
515 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
516 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
517 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
518 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
519 d
= spamdict({1:2,3:4})
521 for i
in d
.keys(): l1
.append(i
)
523 for i
in iter(d
): l
.append(i
)
526 for i
in d
.__iter
__(): l
.append(i
)
529 for i
in type(spamdict({})).__iter
__(d
): l
.append(i
)
531 straightd
= {1:2, 3:4}
532 spamd
= spamdict(straightd
)
533 testunop(spamd
, 2, "len(a)", "__len__")
534 testunop(spamd
, repr(straightd
), "repr(a)", "__repr__")
535 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
536 "a[b]=c", "__setitem__")
538 class C(spam
.spamdict
):
539 def foo(self
): return 1
544 vereq(a
.items(), [('foo', 'bar')])
545 vereq(a
.getstate(), 0)
547 vereq(a
.getstate(), 100)
550 if verbose
: print "Testing Python subclass of dict..."
551 verify(issubclass(dict, dict))
552 verify(isinstance({}, dict))
555 verify(d
.__class
__ is dict)
556 verify(isinstance(d
, dict))
559 def __init__(self
, *a
, **kw
):
564 for k
, v
in kw
.items(): self
[v
] = k
565 def __getitem__(self
, key
):
566 return self
.get(key
, 0)
567 def __setitem__(self
, key
, value
):
568 verify(isinstance(key
, type(0)))
569 dict.__setitem
__(self
, key
, value
)
570 def setstate(self
, state
):
574 verify(issubclass(C
, dict))
578 vereq(a2
[1] == 'foo' and a2
[2], 'bar')
581 vereq(a
.getstate(), -1)
584 vereq(a
.getstate(), 0)
587 vereq(a
.getstate(), 10)
591 if verbose
: print "pydict stress test ..."
602 if verbose
: print "Testing Python subclass of list..."
604 def __getitem__(self
, i
):
605 return list.__getitem
__(self
, i
) + 100
606 def __getslice__(self
, i
, j
):
613 vereq(a
[100:200], (100,200))
616 if verbose
: print "Testing __metaclass__..."
623 def setstate(self
, state
):
626 vereq(a
.getstate(), 0)
628 vereq(a
.getstate(), 10)
630 class __metaclass__(type):
631 def myself(cls
): return cls
634 verify(d
.__class
__ is D
)
636 def __new__(cls
, name
, bases
, dict):
638 return type.__new
__(cls
, name
, bases
, dict)
645 class _instance(object):
648 def __new__(cls
, name
, bases
, dict):
649 self
= object.__new
__(cls
)
654 __new__
= staticmethod(__new__
)
657 # Early binding of methods
658 for key
in self
.dict:
659 if key
.startswith("__"):
661 setattr(it
, key
, self
.dict[key
].__get
__(it
, self
))
669 verify('spam' in C
.dict)
673 # More metaclass examples
675 class autosuper(type):
676 # Automatically add __super to the class
677 # This trick only works for dynamic classes
678 def __new__(metaclass
, name
, bases
, dict):
679 cls
= super(autosuper
, metaclass
).__new
__(metaclass
,
681 # Name mangling for __super removes leading underscores
682 while name
[:1] == "_":
685 name
= "_%s__super" % name
688 setattr(cls
, name
, super(cls
))
691 __metaclass__
= autosuper
696 return "B" + self
.__super
.meth()
699 return "C" + self
.__super
.meth()
702 return "D" + self
.__super
.meth()
703 vereq(D().meth(), "DCBA")
706 return "E" + self
.__super
.meth()
707 vereq(E().meth(), "EBCA")
709 class autoproperty(type):
710 # Automatically create property attributes when methods
711 # named _get_x and/or _set_x are found
712 def __new__(metaclass
, name
, bases
, dict):
714 for key
, val
in dict.iteritems():
715 if key
.startswith("_get_"):
717 get
, set = hits
.get(key
, (None, None))
720 elif key
.startswith("_set_"):
722 get
, set = hits
.get(key
, (None, None))
725 for key
, (get
, set) in hits
.iteritems():
726 dict[key
] = property(get
, set)
727 return super(autoproperty
, metaclass
).__new
__(metaclass
,
730 __metaclass__
= autoproperty
736 verify(not hasattr(a
, "x"))
741 class multimetaclass(autoproperty
, autosuper
):
742 # Merge of multiple cooperating metaclasses
745 __metaclass__
= multimetaclass
750 return "B" + self
.__super
._get
_x
()
753 return "C" + self
.__super
._get
_x
()
756 return "D" + self
.__super
._get
_x
()
759 # Make sure type(x) doesn't call x.__class__.__init__
762 def __init__(self
, *args
):
771 class C(object): pass
774 except TypeError: pass
775 else: raise TestError
, "calling object w/o call method should raise TypeError"
778 if verbose
: print "Testing Python subclass of module..."
785 def __getattribute__(self
, name
):
786 log
.append(("getattr", name
))
787 return MT
.__getattribute
__(self
, name
)
788 def __setattr__(self
, name
, value
):
789 log
.append(("setattr", name
, value
))
790 MT
.__setattr
__(self
, name
, value
)
791 def __delattr__(self
, name
):
792 log
.append(("delattr", name
))
793 MT
.__delattr
__(self
, name
)
798 vereq(log
, [("setattr", "foo", 12),
803 if verbose
: print "Testing multiple inheritance..."
809 def setstate(self
, state
):
812 vereq(a
.getstate(), 0)
814 vereq(a
.getstate(), 10)
817 type({}).__init
__(self
)
822 vereq(d
.items(), [("hello", "world")])
823 vereq(d
["hello"], "world")
824 vereq(d
.getstate(), 0)
826 vereq(d
.getstate(), 10)
827 vereq(D
.__mro
__, (D
, dict, C
, object))
832 return int(self
.foo())
835 class Frag(Node
, list):
838 vereq(Node().__int
__(), 23)
839 vereq(int(Node()), 23)
840 vereq(Frag().__int
__(), 42)
841 vereq(int(Frag()), 42)
843 # MI mixing classic and new-style classes.
858 # Classic MRO is preserved for a classic base class.
861 vereq(E
.__mro
__, (E
, D
, B
, A
, C
, object))
864 # But with a mix of classic bases, their MROs are combined using
866 class F(B
, C
, object):
868 vereq(F
.__mro
__, (F
, B
, C
, A
, object))
871 # Try something else.
875 def all_method(self
):
881 def all_method(self
):
884 vereq(M1
.__mro__
, (M1
, C
, object))
886 vereq(m
.cmethod(), "C a")
887 vereq(m
.m1method(), "M1 a")
888 vereq(m
.all_method(), "M1 b")
893 def all_method(self
):
899 def all_method(self
):
902 vereq(M2
.__mro__
, (M2
, object, D
, C
))
904 vereq(m
.cmethod(), "C a")
905 vereq(m
.dmethod(), "D a")
906 vereq(m
.m2method(), "M2 a")
907 vereq(m
.all_method(), "M2 b")
909 class M3(M1
, object, M2
):
912 def all_method(self
):
914 # XXX Expected this (the commented-out result):
915 # vereq(M3.__mro__, (M3, M1, M2, object, D, C))
916 vereq(M3
.__mro__
, (M3
, M1
, M2
, D
, C
, object)) # XXX ?
918 vereq(m
.cmethod(), "C a")
919 vereq(m
.dmethod(), "D a")
920 vereq(m
.m1method(), "M1 a")
921 vereq(m
.m2method(), "M2 a")
922 vereq(m
.m3method(), "M3 a")
923 vereq(m
.all_method(), "M3 b")
933 raise TestFailed
, "new class with only classic bases - shouldn't be"
936 if verbose
: print "Testing multiple inheritance special cases..."
938 def spam(self
): return "A"
939 vereq(A().spam(), "A")
941 def boo(self
): return "B"
942 def spam(self
): return "B"
943 vereq(B().spam(), "B")
944 vereq(B().boo(), "B")
946 def boo(self
): return "C"
947 vereq(C().spam(), "A")
948 vereq(C().boo(), "C")
950 vereq(D().spam(), "B")
951 vereq(D().boo(), "B")
952 vereq(D
.__mro
__, (D
, B
, C
, A
, object))
954 vereq(E().spam(), "B")
955 vereq(E().boo(), "C")
956 vereq(E
.__mro
__, (E
, C
, B
, A
, object))
958 vereq(F().spam(), "B")
959 vereq(F().boo(), "B")
960 vereq(F
.__mro
__, (F
, D
, E
, B
, C
, A
, object))
962 vereq(G().spam(), "B")
963 vereq(G().boo(), "C")
964 vereq(G
.__mro
__, (G
, E
, D
, C
, B
, A
, object))
967 if verbose
: print "Testing object class..."
969 vereq(a
.__class
__, object)
970 vereq(type(a
), object)
973 verify(not hasattr(a
, "foo"))
976 except (AttributeError, TypeError):
979 verify(0, "object() should not allow setting a foo attribute")
980 verify(not hasattr(object(), "__dict__"))
985 vereq(x
.__dict
__, {})
988 vereq(x
.__dict
__, {'foo': 1})
991 if verbose
: print "Testing __slots__..."
995 verify(not hasattr(x
, "__dict__"))
996 verify(not hasattr(x
, "foo"))
1001 verify(not hasattr(x
, "__dict__"))
1002 verify(not hasattr(x
, "a"))
1008 verify(not hasattr(x
, "a"))
1011 __slots__
= ['a', 'b', 'c']
1013 verify(not hasattr(x
, "__dict__"))
1014 verify(not hasattr(x
, 'a'))
1015 verify(not hasattr(x
, 'b'))
1016 verify(not hasattr(x
, 'c'))
1025 class Counted(object):
1026 counter
= 0 # counts the number of instances alive
1028 Counted
.counter
+= 1
1030 Counted
.counter
-= 1
1032 __slots__
= ['a', 'b', 'c']
1037 vereq(Counted
.counter
, 3)
1039 vereq(Counted
.counter
, 0)
1045 vereq(Counted
.counter
, 2)
1047 vereq(Counted
.counter
, 0)
1054 vereq(Counted
.counter
, 3)
1056 vereq(Counted
.counter
, 0)
1059 if verbose
: print "Testing class attribute propagation..."
1068 # Test that dynamic attributes are inherited
1071 # Test dynamic instances
1075 verify(not hasattr(a
, "foobar"))
1078 C
.method
= lambda self
: 42
1079 vereq(a
.method(), 42)
1080 C
.__repr
__ = lambda self
: "C()"
1081 vereq(repr(a
), "C()")
1082 C
.__int
__ = lambda self
: 100
1085 verify(not hasattr(a
, "spam"))
1086 def mygetattr(self
, name
):
1089 raise AttributeError
1090 C
.__getattr
__ = mygetattr
1091 vereq(a
.spam
, "spam")
1094 def mysetattr(self
, name
, value
):
1096 raise AttributeError
1097 return object.__setattr
__(self
, name
, value
)
1098 C
.__setattr
__ = mysetattr
1101 except AttributeError:
1104 verify(0, "expected AttributeError")
1105 vereq(a
.spam
, "spam")
1112 # Test handling of int*seq and seq*int
1115 vereq("a"*I(2), "aa")
1116 vereq(I(2)*"a", "aa")
1121 # Test handling of long*seq and seq*long
1124 vereq("a"*L(2L), "aa")
1125 vereq(L(2L)*"a", "aa")
1130 # Test comparison of classes with dynamic metaclasses
1131 class dynamicmetaclass(type):
1134 __metaclass__
= dynamicmetaclass
1135 verify(someclass
!= object)
1138 if verbose
: print "Testing errors..."
1141 class C(list, dict):
1146 verify(0, "inheritance from both list and dict should be illegal")
1149 class C(object, None):
1154 verify(0, "inheritance from non-type should be illegal")
1164 verify(0, "inheritance from CFunction should be illegal")
1172 verify(0, "__slots__ = 1 should be illegal")
1180 verify(0, "__slots__ = [1] should be illegal")
1183 if verbose
: print "Testing class methods..."
1185 def foo(*a
): return a
1186 goo
= classmethod(foo
)
1188 vereq(C
.goo(1), (C
, 1))
1189 vereq(c
.goo(1), (C
, 1))
1190 vereq(c
.foo(1), (c
, 1))
1194 vereq(D
.goo(1), (D
, 1))
1195 vereq(d
.goo(1), (D
, 1))
1196 vereq(d
.foo(1), (d
, 1))
1197 vereq(D
.foo(d
, 1), (d
, 1))
1199 def staticmethods():
1200 if verbose
: print "Testing static methods..."
1202 def foo(*a
): return a
1203 goo
= staticmethod(foo
)
1205 vereq(C
.goo(1), (1,))
1206 vereq(c
.goo(1), (1,))
1207 vereq(c
.foo(1), (c
, 1,))
1211 vereq(D
.goo(1), (1,))
1212 vereq(d
.goo(1), (1,))
1213 vereq(d
.foo(1), (d
, 1))
1214 vereq(D
.foo(d
, 1), (d
, 1))
1217 if verbose
: print "Testing classic classes..."
1219 def foo(*a
): return a
1220 goo
= classmethod(foo
)
1222 vereq(C
.goo(1), (C
, 1))
1223 vereq(c
.goo(1), (C
, 1))
1224 vereq(c
.foo(1), (c
, 1))
1228 vereq(D
.goo(1), (D
, 1))
1229 vereq(d
.goo(1), (D
, 1))
1230 vereq(d
.foo(1), (d
, 1))
1231 vereq(D
.foo(d
, 1), (d
, 1))
1232 class E
: # *not* subclassing from C
1234 vereq(E().foo
, C
.foo
) # i.e., unbound
1235 verify(repr(C
.foo
.__get
__(C())).startswith("<bound method "))
1238 if verbose
: print "Testing computed attributes..."
1240 class computed_attribute(object):
1241 def __init__(self
, get
, set=None):
1244 def __get__(self
, obj
, type=None):
1245 return self
.__get
(obj
)
1246 def __set__(self
, obj
, value
):
1247 return self
.__set
(obj
, value
)
1254 def __set_x(self
, x
):
1256 x
= computed_attribute(__get_x
, __set_x
)
1265 if verbose
: print "Testing __new__ slot override..."
1268 self
= list.__new
__(cls
)
1272 self
.foo
= self
.foo
+ 2
1275 verify(a
.__class
__ is C
)
1280 verify(b
.__class
__ is D
)
1283 if verbose
: print "Testing mro() and overriding it..."
1285 def f(self
): return "A"
1289 def f(self
): return "C"
1292 vereq(D
.mro(), [D
, B
, C
, A
, object])
1293 vereq(D
.__mro
__, (D
, B
, C
, A
, object))
1295 class PerverseMetaType(type):
1301 __metaclass__
= PerverseMetaType
1302 vereq(X
.__mro
__, (object, A
, C
, B
, D
, X
))
1306 if verbose
: print "Testing operator overloading..."
1309 "Intermediate class because object doesn't have a __setattr__"
1313 def __getattr__(self
, name
):
1315 return ("getattr", name
)
1317 raise AttributeError
1318 def __setattr__(self
, name
, value
):
1320 self
.setattr = (name
, value
)
1322 return B
.__setattr
__(self
, name
, value
)
1323 def __delattr__(self
, name
):
1327 return B
.__delattr
__(self
, name
)
1329 def __getitem__(self
, key
):
1330 return ("getitem", key
)
1331 def __setitem__(self
, key
, value
):
1332 self
.setitem
= (key
, value
)
1333 def __delitem__(self
, key
):
1336 def __getslice__(self
, i
, j
):
1337 return ("getslice", i
, j
)
1338 def __setslice__(self
, i
, j
, value
):
1339 self
.setslice
= (i
, j
, value
)
1340 def __delslice__(self
, i
, j
):
1341 self
.delslice
= (i
, j
)
1344 vereq(a
.foo
, ("getattr", "foo"))
1346 vereq(a
.setattr, ("foo", 12))
1348 vereq(a
.delattr, "foo")
1350 vereq(a
[12], ("getitem", 12))
1352 vereq(a
.setitem
, (12, 21))
1354 vereq(a
.delitem
, 12)
1356 vereq(a
[0:10], ("getslice", 0, 10))
1358 vereq(a
.setslice
, (0, 10, "foo"))
1360 vereq(a
.delslice
, (0, 10))
1363 if verbose
: print "Testing methods..."
1365 def __init__(self
, x
):
1380 vereq(E().foo
, C
.foo
) # i.e., unbound
1381 verify(repr(C
.foo
.__get
__(C(1))).startswith("<bound method "))
1384 # Test operators like __hash__ for which a built-in default exists
1385 if verbose
: print "Testing special operators..."
1386 # Test the default behavior for static classes
1388 def __getitem__(self
, i
):
1389 if 0 <= i
< 10: return i
1394 vereq(hash(c1
), id(c1
))
1395 vereq(cmp(c1
, c2
), cmp(id(c1
), id(c2
)))
1398 verify(not c1
!= c1
)
1399 verify(not c1
== c2
)
1400 # Note that the module name appears in str/repr, and that varies
1401 # depending on whether this test is run standalone or from a framework.
1402 verify(str(c1
).find('C object at ') >= 0)
1403 vereq(str(c1
), repr(c1
))
1404 verify(-1 not in c1
)
1407 verify(10 not in c1
)
1408 # Test the default behavior for dynamic classes
1410 def __getitem__(self
, i
):
1411 if 0 <= i
< 10: return i
1416 vereq(hash(d1
), id(d1
))
1417 vereq(cmp(d1
, d2
), cmp(id(d1
), id(d2
)))
1420 verify(not d1
!= d1
)
1421 verify(not d1
== d2
)
1422 # Note that the module name appears in str/repr, and that varies
1423 # depending on whether this test is run standalone or from a framework.
1424 verify(str(d1
).find('D object at ') >= 0)
1425 vereq(str(d1
), repr(d1
))
1426 verify(-1 not in d1
)
1429 verify(10 not in d1
)
1430 # Test overridden behavior for static classes
1431 class Proxy(object):
1432 def __init__(self
, x
):
1434 def __nonzero__(self
):
1435 return not not self
.x
1438 def __eq__(self
, other
):
1439 return self
.x
== other
1440 def __ne__(self
, other
):
1441 return self
.x
!= other
1442 def __cmp__(self
, other
):
1443 return cmp(self
.x
, other
.x
)
1445 return "Proxy:%s" % self
.x
1447 return "Proxy(%r)" % self
.x
1448 def __contains__(self
, value
):
1449 return value
in self
.x
1455 vereq(hash(p0
), hash(0))
1458 verify(not p0
!= p0
)
1460 vereq(cmp(p0
, p1
), -1)
1461 vereq(cmp(p0
, p0
), 0)
1462 vereq(cmp(p0
, p_1
), 1)
1463 vereq(str(p0
), "Proxy:0")
1464 vereq(repr(p0
), "Proxy(0)")
1465 p10
= Proxy(range(10))
1466 verify(-1 not in p10
)
1469 verify(10 not in p10
)
1470 # Test overridden behavior for dynamic classes
1471 class DProxy(object):
1472 def __init__(self
, x
):
1474 def __nonzero__(self
):
1475 return not not self
.x
1478 def __eq__(self
, other
):
1479 return self
.x
== other
1480 def __ne__(self
, other
):
1481 return self
.x
!= other
1482 def __cmp__(self
, other
):
1483 return cmp(self
.x
, other
.x
)
1485 return "DProxy:%s" % self
.x
1487 return "DProxy(%r)" % self
.x
1488 def __contains__(self
, value
):
1489 return value
in self
.x
1495 vereq(hash(p0
), hash(0))
1498 verify(not p0
!= p0
)
1500 vereq(cmp(p0
, p1
), -1)
1501 vereq(cmp(p0
, p0
), 0)
1502 vereq(cmp(p0
, p_1
), 1)
1503 vereq(str(p0
), "DProxy:0")
1504 vereq(repr(p0
), "DProxy(0)")
1505 p10
= DProxy(range(10))
1506 verify(-1 not in p10
)
1509 verify(10 not in p10
)
1510 # Safety test for __cmp__
1511 def unsafecmp(a
, b
):
1513 a
.__class
__.__cmp
__(a
, b
)
1517 raise TestFailed
, "shouldn't allow %s.__cmp__(%r, %r)" % (
1519 unsafecmp(u
"123", "123")
1520 unsafecmp("123", u
"123")
1527 if verbose
: print "Testing weak references..."
1537 class NoWeak(object):
1542 except TypeError, msg
:
1543 verify(str(msg
).find("weak reference") >= 0)
1545 verify(0, "weakref.ref(no) should be illegal")
1547 __slots__
= ['foo', '__weakref__']
1549 r
= weakref
.ref(yes
)
1556 if verbose
: print "Testing property..."
1560 def setx(self
, value
):
1564 x
= property(getx
, setx
, delx
, doc
="I'm the x property.")
1566 verify(not hasattr(a
, "x"))
1571 verify(not hasattr(a
, "x"))
1572 verify(not hasattr(a
, "_C__x"))
1574 vereq(C
.x
.__get
__(a
), 100)
1576 ## verify(not hasattr(a, "x"))
1578 raw
= C
.__dict
__['x']
1579 verify(isinstance(raw
, property))
1582 verify("__doc__" in attrs
)
1583 verify("fget" in attrs
)
1584 verify("fset" in attrs
)
1585 verify("fdel" in attrs
)
1587 vereq(raw
.__doc
__, "I'm the x property.")
1588 verify(raw
.fget
is C
.__dict
__['getx'])
1589 verify(raw
.fset
is C
.__dict
__['setx'])
1590 verify(raw
.fdel
is C
.__dict
__['delx'])
1592 for attr
in "__doc__", "fget", "fset", "fdel":
1594 setattr(raw
, attr
, 42)
1595 except TypeError, msg
:
1596 if str(msg
).find('readonly') < 0:
1597 raise TestFailed("when setting readonly attr %r on a "
1598 "property, got unexpected TypeError "
1599 "msg %r" % (attr
, str(msg
)))
1601 raise TestFailed("expected TypeError from trying to set "
1602 "readonly %r attr on a property" % attr
)
1605 if verbose
: print "Testing super..."
1611 vereq(A().meth(1), "A(1)")
1615 self
.__super
= super(B
, self
)
1617 return "B(%r)" % a
+ self
.__super
.meth(a
)
1619 vereq(B().meth(2), "B(2)A(2)")
1623 return "C(%r)" % a
+ self
.__super
.meth(a
)
1624 C
._C
__super
= super(C
)
1626 vereq(C().meth(3), "C(3)A(3)")
1630 return "D(%r)" % a
+ super(D
, self
).meth(a
)
1632 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
1634 # Test for subclassing super
1636 class mysuper(super):
1637 def __init__(self
, *args
):
1638 return super(mysuper
, self
).__init
__(*args
)
1642 return "E(%r)" % a
+ mysuper(E
, self
).meth(a
)
1644 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
1649 return "F(%r)[%s]" % (a
, s
.__class
__.__name
__) + s
.meth(a
)
1650 F
._F
__super
= mysuper(F
)
1652 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
1654 # Make sure certain errors are raised
1661 raise TestFailed
, "shouldn't allow super(D, 42)"
1668 raise TestFailed
, "shouldn't allow super(D, C())"
1671 super(D
).__get
__(12)
1675 raise TestFailed
, "shouldn't allow super(D).__get__(12)"
1678 super(D
).__get
__(C())
1682 raise TestFailed
, "shouldn't allow super(D).__get__(C())"
1685 if verbose
: print "Testing inheritance from basic types..."
1690 def __add__(self
, other
):
1691 return hexint(int.__add
__(self
, other
))
1692 # (Note that overriding __radd__ doesn't work,
1693 # because the int type gets first dibs.)
1694 vereq(repr(hexint(7) + 9), "0x10")
1695 vereq(repr(hexint(1000) + 7), "0x3ef")
1698 vereq(int(a
), 12345)
1699 verify(int(a
).__class
__ is int)
1700 vereq(hash(a
), hash(12345))
1701 verify((+a
).__class
__ is int)
1702 verify((a
>> 0).__class
__ is int)
1703 verify((a
<< 0).__class
__ is int)
1704 verify((hexint(0) << 12).__class
__ is int)
1705 verify((hexint(0) >> 12).__class
__ is int)
1707 class octlong(long):
1714 def __add__(self
, other
):
1715 return self
.__class
__(super(octlong
, self
).__add
__(other
))
1717 vereq(str(octlong(3) + 5), "010")
1718 # (Note that overriding __radd__ here only seems to work
1719 # because the example uses a short int left argument.)
1720 vereq(str(5 + octlong(3000)), "05675")
1723 vereq(long(a
), 12345L)
1724 vereq(hash(a
), hash(12345L))
1725 verify(long(a
).__class
__ is long)
1726 verify((+a
).__class
__ is long)
1727 verify((-a
).__class
__ is long)
1728 verify((-octlong(0)).__class
__ is long)
1729 verify((a
>> 0).__class
__ is long)
1730 verify((a
<< 0).__class
__ is long)
1731 verify((a
- 0).__class
__ is long)
1732 verify((a
* 1).__class
__ is long)
1733 verify((a
** 1).__class
__ is long)
1734 verify((a
// 1).__class
__ is long)
1735 verify((1 * a
).__class
__ is long)
1736 verify((a |
0).__class
__ is long)
1737 verify((a ^
0).__class
__ is long)
1738 verify((a
& -1L).__class
__ is long)
1739 verify((octlong(0) << 12).__class
__ is long)
1740 verify((octlong(0) >> 12).__class
__ is long)
1741 verify(abs(octlong(0)).__class
__ is long)
1743 # Because octlong overrides __add__, we can't check the absence of +0
1744 # optimizations using octlong.
1745 class longclone(long):
1748 verify((a
+ 0).__class
__ is long)
1749 verify((0 + a
).__class
__ is long)
1751 class precfloat(float):
1752 __slots__
= ['prec']
1753 def __init__(self
, value
=0.0, prec
=12):
1754 self
.prec
= int(prec
)
1755 float.__init
__(value
)
1757 return "%.*g" % (self
.prec
, self
)
1758 vereq(repr(precfloat(1.1)), "1.1")
1759 a
= precfloat(12345)
1761 vereq(float(a
), 12345.0)
1762 verify(float(a
).__class
__ is float)
1763 vereq(hash(a
), hash(12345.0))
1764 verify((+a
).__class
__ is float)
1766 class madcomplex(complex):
1768 return "%.17gj%+.17g" % (self
.imag
, self
.real
)
1769 a
= madcomplex(-3, 4)
1770 vereq(repr(a
), "4j-3")
1771 base
= complex(-3, 4)
1772 veris(base
.__class
__, complex)
1774 vereq(complex(a
), base
)
1775 veris(complex(a
).__class
__, complex)
1776 a
= madcomplex(a
) # just trying another form of the constructor
1777 vereq(repr(a
), "4j-3")
1779 vereq(complex(a
), base
)
1780 veris(complex(a
).__class
__, complex)
1781 vereq(hash(a
), hash(base
))
1782 veris((+a
).__class
__, complex)
1783 veris((a
+ 0).__class
__, complex)
1785 veris((a
- 0).__class
__, complex)
1787 veris((a
* 1).__class
__, complex)
1789 veris((a
/ 1).__class
__, complex)
1792 class madtuple(tuple):
1795 if self
._rev
is not None:
1799 self
._rev
= self
.__class
__(L
)
1801 a
= madtuple((1,2,3,4,5,6,7,8,9,0))
1802 vereq(a
, (1,2,3,4,5,6,7,8,9,0))
1803 vereq(a
.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
1804 vereq(a
.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
1805 for i
in range(512):
1806 t
= madtuple(range(i
))
1810 a
= madtuple((1,2,3,4,5))
1811 vereq(tuple(a
), (1,2,3,4,5))
1812 verify(tuple(a
).__class
__ is tuple)
1813 vereq(hash(a
), hash((1,2,3,4,5)))
1814 verify(a
[:].__class
__ is tuple)
1815 verify((a
* 1).__class
__ is tuple)
1816 verify((a
* 0).__class
__ is tuple)
1817 verify((a
+ ()).__class
__ is tuple)
1820 verify(tuple(a
).__class
__ is tuple)
1821 verify((a
+ a
).__class
__ is tuple)
1822 verify((a
* 0).__class
__ is tuple)
1823 verify((a
* 1).__class
__ is tuple)
1824 verify((a
* 2).__class
__ is tuple)
1825 verify(a
[:].__class
__ is tuple)
1827 class madstring(str):
1830 if self
._rev
is not None:
1834 self
._rev
= self
.__class
__("".join(L
))
1836 s
= madstring("abcdefghijklmnopqrstuvwxyz")
1837 vereq(s
, "abcdefghijklmnopqrstuvwxyz")
1838 vereq(s
.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
1839 vereq(s
.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
1840 for i
in range(256):
1841 s
= madstring("".join(map(chr, range(i
))))
1845 s
= madstring("12345")
1846 vereq(str(s
), "12345")
1847 verify(str(s
).__class
__ is str)
1853 verify(str(s
).__class
__ is str)
1854 vereq(hash(s
), hash(base
))
1855 vereq({s
: 1}[base
], 1)
1856 vereq({base
: 1}[s
], 1)
1857 verify((s
+ "").__class
__ is str)
1859 verify(("" + s
).__class
__ is str)
1861 verify((s
* 0).__class
__ is str)
1863 verify((s
* 1).__class
__ is str)
1865 verify((s
* 2).__class
__ is str)
1866 vereq(s
* 2, base
+ base
)
1867 verify(s
[:].__class
__ is str)
1869 verify(s
[0:0].__class
__ is str)
1871 verify(s
.strip().__class
__ is str)
1872 vereq(s
.strip(), base
)
1873 verify(s
.lstrip().__class
__ is str)
1874 vereq(s
.lstrip(), base
)
1875 verify(s
.rstrip().__class
__ is str)
1876 vereq(s
.rstrip(), base
)
1877 identitytab
= ''.join([chr(i
) for i
in range(256)])
1878 verify(s
.translate(identitytab
).__class
__ is str)
1879 vereq(s
.translate(identitytab
), base
)
1880 verify(s
.translate(identitytab
, "x").__class
__ is str)
1881 vereq(s
.translate(identitytab
, "x"), base
)
1882 vereq(s
.translate(identitytab
, "\x00"), "")
1883 verify(s
.replace("x", "x").__class
__ is str)
1884 vereq(s
.replace("x", "x"), base
)
1885 verify(s
.ljust(len(s
)).__class
__ is str)
1886 vereq(s
.ljust(len(s
)), base
)
1887 verify(s
.rjust(len(s
)).__class
__ is str)
1888 vereq(s
.rjust(len(s
)), base
)
1889 verify(s
.center(len(s
)).__class
__ is str)
1890 vereq(s
.center(len(s
)), base
)
1891 verify(s
.lower().__class
__ is str)
1892 vereq(s
.lower(), base
)
1894 s
= madstring("x y")
1896 verify(intern(s
).__class
__ is str)
1897 verify(intern(s
) is intern("x y"))
1898 vereq(intern(s
), "x y")
1901 s
= madstring("y x")
1903 verify(intern(s
).__class
__ is str)
1904 verify(intern(s
) is i
)
1907 verify(intern(s
).__class
__ is str)
1908 verify(intern(s
) is i
)
1910 class madunicode(unicode):
1913 if self
._rev
is not None:
1917 self
._rev
= self
.__class
__(u
"".join(L
))
1919 u
= madunicode("ABCDEF")
1921 vereq(u
.rev(), madunicode(u
"FEDCBA"))
1922 vereq(u
.rev().rev(), madunicode(u
"ABCDEF"))
1924 u
= madunicode(base
)
1925 vereq(unicode(u
), base
)
1926 verify(unicode(u
).__class
__ is unicode)
1927 vereq(hash(u
), hash(base
))
1928 vereq({u
: 1}[base
], 1)
1929 vereq({base
: 1}[u
], 1)
1930 verify(u
.strip().__class
__ is unicode)
1931 vereq(u
.strip(), base
)
1932 verify(u
.lstrip().__class
__ is unicode)
1933 vereq(u
.lstrip(), base
)
1934 verify(u
.rstrip().__class
__ is unicode)
1935 vereq(u
.rstrip(), base
)
1936 verify(u
.replace(u
"x", u
"x").__class
__ is unicode)
1937 vereq(u
.replace(u
"x", u
"x"), base
)
1938 verify(u
.replace(u
"xy", u
"xy").__class
__ is unicode)
1939 vereq(u
.replace(u
"xy", u
"xy"), base
)
1940 verify(u
.center(len(u
)).__class
__ is unicode)
1941 vereq(u
.center(len(u
)), base
)
1942 verify(u
.ljust(len(u
)).__class
__ is unicode)
1943 vereq(u
.ljust(len(u
)), base
)
1944 verify(u
.rjust(len(u
)).__class
__ is unicode)
1945 vereq(u
.rjust(len(u
)), base
)
1946 verify(u
.lower().__class
__ is unicode)
1947 vereq(u
.lower(), base
)
1948 verify(u
.upper().__class
__ is unicode)
1949 vereq(u
.upper(), base
)
1950 verify(u
.capitalize().__class
__ is unicode)
1951 vereq(u
.capitalize(), base
)
1952 verify(u
.title().__class
__ is unicode)
1953 vereq(u
.title(), base
)
1954 verify((u
+ u
"").__class
__ is unicode)
1955 vereq(u
+ u
"", base
)
1956 verify((u
"" + u
).__class
__ is unicode)
1957 vereq(u
"" + u
, base
)
1958 verify((u
* 0).__class
__ is unicode)
1960 verify((u
* 1).__class
__ is unicode)
1962 verify((u
* 2).__class
__ is unicode)
1963 vereq(u
* 2, base
+ base
)
1964 verify(u
[:].__class
__ is unicode)
1966 verify(u
[0:0].__class
__ is unicode)
1969 class sublist(list):
1971 a
= sublist(range(5))
1974 vereq(a
, range(5) + ["hello"])
1977 a
.extend(range(6, 20))
1984 vereq(list(a
), range(10))
1989 vereq(a
[:5], range(5))
1991 class CountedInput(file):
1992 """Counts lines read by self.readline().
1994 self.lineno is the 0-based ordinal of the last line read, up to
1995 a maximum of one greater than the number of lines in the file.
1997 self.ateof is true if and only if the final "" line has been read,
1998 at which point self.lineno stops incrementing, and further calls
1999 to readline() continue to return "".
2007 s
= file.readline(self
)
2008 # Next line works too.
2009 # s = super(CountedInput, self).readline()
2015 f
= file(name
=TESTFN
, mode
='w')
2016 lines
= ['a\n', 'b\n', 'c\n']
2020 f
= CountedInput(TESTFN
)
2021 for (i
, expected
) in zip(range(1, 5) + [4], lines
+ 2 * [""]):
2023 vereq(expected
, got
)
2025 vereq(f
.ateof
, (i
> len(lines
)))
2040 print "Testing keyword args to basic type constructors ..."
2042 vereq(float(x
=2), 2.0)
2043 vereq(long(x
=3), 3L)
2044 vereq(complex(imag
=42, real
=666), complex(666, 42))
2045 vereq(str(object=500), '500')
2046 vereq(unicode(string
='abc', errors
='strict'), u
'abc')
2047 vereq(tuple(sequence
=range(3)), (0, 1, 2))
2048 vereq(list(sequence
=(0, 1, 2)), range(3))
2049 vereq(dict(items
={1: 2}), {1: 2})
2051 for constructor
in (int, float, long, complex, str, unicode,
2052 tuple, list, dict, file):
2054 constructor(bogus_keyword_arg
=1)
2058 raise TestFailed("expected TypeError from bogus keyword "
2059 "argument to %r" % constructor
)
2064 print "Testing interaction with restricted execution ..."
2066 sandbox
= rexec
.RExec()
2068 code1
= """f = open(%r, 'w')""" % TESTFN
2069 code2
= """f = file(%r, 'w')""" % TESTFN
2072 t = type(f) # a sneaky way to get the file() constructor
2074 f = t(%r, 'w') # rexec can't catch this by itself
2075 """ % (TESTFN
, TESTFN
)
2077 f
= open(TESTFN
, 'w') # Create the file so code3 can find it.
2081 for code
in code1
, code2
, code3
:
2083 sandbox
.r_exec(code
)
2084 except IOError, msg
:
2085 if str(msg
).find("restricted") >= 0:
2088 outcome
= "got an exception, but not an expected one"
2090 outcome
= "expected a restricted-execution exception"
2093 raise TestFailed("%s, in %r" % (outcome
, code
))
2102 def str_subclass_as_dict_key():
2104 print "Testing a str subclass used as dict key .."
2107 """Sublcass of str that computes __eq__ case-insensitively.
2109 Also computes a hash code of the string in canonical form.
2112 def __init__(self
, value
):
2113 self
.canonical
= value
.lower()
2114 self
.hashcode
= hash(self
.canonical
)
2116 def __eq__(self
, other
):
2117 if not isinstance(other
, cistr
):
2118 other
= cistr(other
)
2119 return self
.canonical
== other
.canonical
2122 return self
.hashcode
2124 vereq(cistr('ABC'), 'abc')
2125 vereq('aBc', cistr('ABC'))
2126 vereq(str(cistr('ABC')), 'ABC')
2128 d
= {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2129 vereq(d
[cistr('one')], 1)
2130 vereq(d
[cistr('tWo')], 2)
2131 vereq(d
[cistr('THrEE')], 3)
2132 verify(cistr('ONe') in d
)
2133 vereq(d
.get(cistr('thrEE')), 3)
2135 def classic_comparisons():
2136 if verbose
: print "Testing classic comparisons..."
2139 for base
in (classic
, int, object):
2140 if verbose
: print " (base = %s)" % base
2142 def __init__(self
, value
):
2143 self
.value
= int(value
)
2144 def __cmp__(self
, other
):
2145 if isinstance(other
, C
):
2146 return cmp(self
.value
, other
.value
)
2147 if isinstance(other
, int) or isinstance(other
, long):
2148 return cmp(self
.value
, other
)
2149 return NotImplemented
2154 c
= {1: c1
, 2: c2
, 3: c3
}
2157 verify(cmp(c
[x
], c
[y
]) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2158 for op
in "<", "<=", "==", "!=", ">", ">=":
2159 verify(eval("c[x] %s c[y]" % op
) == eval("x %s y" % op
),
2160 "x=%d, y=%d" % (x
, y
))
2161 verify(cmp(c
[x
], y
) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2162 verify(cmp(x
, c
[y
]) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2164 def rich_comparisons():
2166 print "Testing rich comparisons..."
2173 def __eq__(self
, other
):
2175 return abs(self
- other
) <= 1e-6
2177 return NotImplemented
2184 for base
in (classic
, int, object, list):
2185 if verbose
: print " (base = %s)" % base
2187 def __init__(self
, value
):
2188 self
.value
= int(value
)
2189 def __cmp__(self
, other
):
2190 raise TestFailed
, "shouldn't call __cmp__"
2191 def __eq__(self
, other
):
2192 if isinstance(other
, C
):
2193 return self
.value
== other
.value
2194 if isinstance(other
, int) or isinstance(other
, long):
2195 return self
.value
== other
2196 return NotImplemented
2197 def __ne__(self
, other
):
2198 if isinstance(other
, C
):
2199 return self
.value
!= other
.value
2200 if isinstance(other
, int) or isinstance(other
, long):
2201 return self
.value
!= other
2202 return NotImplemented
2203 def __lt__(self
, other
):
2204 if isinstance(other
, C
):
2205 return self
.value
< other
.value
2206 if isinstance(other
, int) or isinstance(other
, long):
2207 return self
.value
< other
2208 return NotImplemented
2209 def __le__(self
, other
):
2210 if isinstance(other
, C
):
2211 return self
.value
<= other
.value
2212 if isinstance(other
, int) or isinstance(other
, long):
2213 return self
.value
<= other
2214 return NotImplemented
2215 def __gt__(self
, other
):
2216 if isinstance(other
, C
):
2217 return self
.value
> other
.value
2218 if isinstance(other
, int) or isinstance(other
, long):
2219 return self
.value
> other
2220 return NotImplemented
2221 def __ge__(self
, other
):
2222 if isinstance(other
, C
):
2223 return self
.value
>= other
.value
2224 if isinstance(other
, int) or isinstance(other
, long):
2225 return self
.value
>= other
2226 return NotImplemented
2231 c
= {1: c1
, 2: c2
, 3: c3
}
2234 for op
in "<", "<=", "==", "!=", ">", ">=":
2235 verify(eval("c[x] %s c[y]" % op
) == eval("x %s y" % op
),
2236 "x=%d, y=%d" % (x
, y
))
2237 verify(eval("c[x] %s y" % op
) == eval("x %s y" % op
),
2238 "x=%d, y=%d" % (x
, y
))
2239 verify(eval("x %s c[y]" % op
) == eval("x %s y" % op
),
2240 "x=%d, y=%d" % (x
, y
))
2243 if verbose
: print "Testing coercions..."
2252 class F(float): pass
2259 class C(complex): pass
2270 if verbose
: print "Testing descriptor doc strings..."
2271 def check(descr
, what
):
2272 vereq(descr
.__doc
__, what
)
2273 check(file.closed
, "flag set if the file is closed") # getset descriptor
2274 check(file.name
, "file name") # member descriptor
2277 if verbose
: print "Testing __class__ assignment..."
2278 class C(object): pass
2279 class D(object): pass
2280 class E(object): pass
2282 for cls
in C
, D
, E
, F
:
2283 for cls2
in C
, D
, E
, F
:
2286 verify(x
.__class
__ is cls2
)
2288 verify(x
.__class
__ is cls
)
2295 raise TestFailed
, "shouldn't allow %r.__class__ = %r" % (x
, C
)
2300 cant(object(), list)
2301 cant(list(), object)
2304 if verbose
: print "Testing __dict__ assignment..."
2305 class C(object): pass
2307 a
.__dict
__ = {'b': 1}
2315 raise TestFailed
, "shouldn't allow %r.__dict__ = %r" % (x
, dict)
2319 del a
.__dict
__ # Deleting __dict__ is allowed
2320 # Classes don't allow __dict__ assignment
2325 print "Testing pickling and copying new-style classes and objects..."
2326 import pickle
, cPickle
2335 def __init__(self
, a
, b
):
2336 super(C
, self
).__init
__()
2340 return "C(%r, %r)" % (self
.a
, self
.b
)
2344 def __new__(cls
, a
, b
):
2345 return super(C1
, cls
).__new
__(cls
)
2346 def __init__(self
, a
, b
):
2350 return "C1(%r, %r)<%r>" % (self
.a
, self
.b
, list(self
))
2354 def __new__(cls
, a
, b
, val
=0):
2355 return super(C2
, cls
).__new
__(cls
, val
)
2356 def __init__(self
, a
, b
, val
=0):
2360 return "C2(%r, %r)<%r>" % (self
.a
, self
.b
, int(self
))
2364 def __init__(self
, foo
):
2366 def __getstate__(self
):
2368 def __setstate__(self
, foo
):
2371 global C4classic
, C4
2372 class C4classic
: # classic
2374 class C4(C4classic
, object): # mixed inheritance
2377 for p
in pickle
, cPickle
:
2380 print p
.__name
__, ["text", "binary"][bin
]
2382 for cls
in C
, C1
, C2
:
2383 s
= p
.dumps(cls
, bin
)
2387 a
= C1(1, 2); a
.append(42); a
.append(24)
2388 b
= C2("hello", "world", 42)
2389 s
= p
.dumps((a
, b
), bin
)
2391 vereq(x
.__class
__, a
.__class
__)
2392 vereq(sorteditems(x
.__dict
__), sorteditems(a
.__dict
__))
2393 vereq(y
.__class
__, b
.__class
__)
2394 vereq(sorteditems(y
.__dict
__), sorteditems(b
.__dict
__))
2400 # Test for __getstate__ and __setstate__ on new style class
2404 veris(u
.__class
__, v
.__class
__)
2406 # Test for picklability of hybrid class
2411 veris(u
.__class
__, v
.__class
__)
2414 # Testing copy.deepcopy()
2418 for cls
in C
, C1
, C2
:
2419 cls2
= copy
.deepcopy(cls
)
2422 a
= C1(1, 2); a
.append(42); a
.append(24)
2423 b
= C2("hello", "world", 42)
2424 x
, y
= copy
.deepcopy((a
, b
))
2425 vereq(x
.__class
__, a
.__class
__)
2426 vereq(sorteditems(x
.__dict
__), sorteditems(a
.__dict
__))
2427 vereq(y
.__class
__, b
.__class
__)
2428 vereq(sorteditems(y
.__dict
__), sorteditems(b
.__dict
__))
2436 if verbose
: print "Testing copy.copy() and copy.deepcopy()..."
2444 vereq(b
.__dict
__, a
.__dict
__)
2449 verify(c
.bar
is a
.bar
)
2451 d
= copy
.deepcopy(a
)
2452 vereq(d
.__dict
__, a
.__dict
__)
2454 vereq(d
.bar
, [1,2,3])
2456 def binopoverride():
2457 if verbose
: print "Testing overrides of binary operations..."
2460 return "I(%r)" % int(self
)
2461 def __add__(self
, other
):
2462 return I(int(self
) + int(other
))
2464 def __pow__(self
, other
, mod
=None):
2466 return I(pow(int(self
), int(other
)))
2468 return I(pow(int(self
), int(other
), int(mod
)))
2469 def __rpow__(self
, other
, mod
=None):
2471 return I(pow(int(other
), int(self
), mod
))
2473 return I(pow(int(other
), int(self
), int(mod
)))
2475 vereq(`
I(1) + I(2)`
, "I(3)")
2476 vereq(`
I(1) + 2`
, "I(3)")
2477 vereq(`
1 + I(2)`
, "I(3)")
2478 vereq(`
I(2) ** I(3)`
, "I(8)")
2479 vereq(`
2 ** I(3)`
, "I(8)")
2480 vereq(`
I(2) ** 3`
, "I(8)")
2481 vereq(`
pow(I(2), I(3), I(5))`
, "I(3)")
2483 def __eq__(self
, other
):
2484 return self
.lower() == other
.lower()
2486 def subclasspropagation():
2487 if verbose
: print "Testing propagation of slot functions to subclasses..."
2497 vereq(hash(d
), id(d
))
2498 A
.__hash
__ = lambda self
: 42
2500 C
.__hash
__ = lambda self
: 314
2502 B
.__hash
__ = lambda self
: 144
2504 D
.__hash
__ = lambda self
: 100
2513 vereq(hash(d
), id(d
))
2518 def __getattribute__(self
, name
):
2521 return object.__getattribute
__(self
, name
)
2522 A
.__getattribute
__ = __getattribute__
2525 def __getattr__(self
, name
):
2526 if name
in ("spam", "foo", "bar"):
2528 raise AttributeError, name
2529 B
.__getattr
__ = __getattr__
2530 vereq(d
.spam
, "hello")
2533 del A
.__getattribute
__
2536 vereq(d
.foo
, "hello")
2541 except AttributeError:
2544 raise TestFailed
, "d.foo should be undefined now"
2546 def buffer_inherit():
2548 # SF bug [#470040] ParseTuple t# vs subclasses.
2550 print "Testing that buffer interface is inherited ..."
2556 # b2a_hex uses the buffer interface to get its argument's value, via
2557 # PyArg_ParseTuple 't#' code.
2558 vereq(binascii
.b2a_hex(m
), binascii
.b2a_hex(base
))
2560 # It's not clear that unicode will continue to support the character
2561 # buffer interface, and this test will fail if that's taken away.
2562 class MyUni(unicode):
2566 vereq(binascii
.b2a_hex(m
), binascii
.b2a_hex(base
))
2573 raise TestFailed('subclass of int should not have a buffer interface')
2577 def str_of_str_subclass():
2582 print "Testing __str__ defined in subclass of str ..."
2584 class octetstring(str):
2586 return binascii
.b2a_hex(self
)
2588 return self
+ " repr"
2590 o
= octetstring('A')
2591 vereq(type(o
), octetstring
)
2592 vereq(type(str(o
)), str)
2593 vereq(type(repr(o
)), str)
2596 vereq(repr(o
), 'A repr')
2597 vereq(o
.__str
__(), '41')
2598 vereq(o
.__repr
__(), 'A repr')
2600 capture
= cStringIO
.StringIO()
2601 # Calling str() or not exercises different internal paths.
2603 print >> capture
, str(o
)
2604 vereq(capture
.getvalue(), '41\n41\n')
2608 if verbose
: print "Testing keyword arguments to __init__, __call__..."
2610 vereq(f
.__call
__(a
=42), 42)
2612 list.__init
__(a
, sequence
=[0, 1, 2])
2616 if verbose
: print "Testing __del__ hook..."
2626 class D(object): pass
2629 except TypeError: pass
2630 else: raise TestFailed
, "invalid del() didn't raise TypeError"
2633 if verbose
: print "Testing hash of mutable subclasses..."
2643 raise TestFailed
, "hash() of dict subclass should fail"
2653 raise TestFailed
, "hash() of list subclass should fail"
2657 except TypeError: pass
2658 else: raise TestFailed
, "'' + 5 doesn't raise TypeError"
2661 except ValueError: pass
2662 else: raise TestFailed
, "''.split('') doesn't raise ValueError"
2665 except TypeError: pass
2666 else: raise TestFailed
, "''.join([0]) doesn't raise TypeError"
2669 except ValueError: pass
2670 else: raise TestFailed
, "''.rindex('5') doesn't raise ValueError"
2672 try: ''.replace('', '')
2673 except ValueError: pass
2674 else: raise TestFailed
, "''.replace('', '') doesn't raise ValueError"
2677 except TypeError: pass
2678 else: raise TestFailed
, "'%(n)s' % None doesn't raise TypeError"
2681 except ValueError: pass
2682 else: raise TestFailed
, "'%(n' % {} '' doesn't raise ValueError"
2684 try: '%*s' % ('abc')
2685 except TypeError: pass
2686 else: raise TestFailed
, "'%*s' % ('abc') doesn't raise TypeError"
2688 try: '%*.*s' % ('abc', 5)
2689 except TypeError: pass
2690 else: raise TestFailed
, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
2693 except TypeError: pass
2694 else: raise TestFailed
, "'%s' % (1, 2) doesn't raise TypeError"
2697 except ValueError: pass
2698 else: raise TestFailed
, "'%' % None doesn't raise ValueError"
2700 vereq('534253'.isdigit(), 1)
2701 vereq('534253x'.isdigit(), 0)
2702 vereq('%c' % 5, '\x05')
2703 vereq('%c' % '5', '5')
2745 str_subclass_as_dict_key()
2746 classic_comparisons()
2755 subclasspropagation()
2757 str_of_str_subclass()
2762 if verbose
: print "All OK"
2764 if __name__
== "__main__":