6 from copy
import deepcopy
7 from test
import test_support
10 class OperatorsTest(unittest
.TestCase
):
12 def __init__(self
, *args
, **kwargs
):
13 unittest
.TestCase
.__init
__(self
, *args
, **kwargs
)
35 for name
, expr
in self
.binops
.items():
37 expr
= expr
+ "(a, b)"
39 expr
= 'a %s b' % expr
40 self
.binops
[name
] = expr
54 for name
, expr
in self
.unops
.items():
59 self
.unops
[name
] = expr
61 def unop_test(self
, a
, res
, expr
="len(a)", meth
="__len__"):
63 self
.assertEqual(eval(expr
, d
), res
)
67 # Find method in parent class
68 while meth
not in t
.__dict
__:
70 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
71 # method object; the getattr() below obtains its underlying function.
72 self
.assertEqual(getattr(m
, 'im_func', m
), t
.__dict
__[meth
])
73 self
.assertEqual(m(a
), res
)
75 self
.assertEqual(bm(), res
)
77 def binop_test(self
, a
, b
, res
, expr
="a+b", meth
="__add__"):
80 # XXX Hack so this passes before 2.3 when -Qnew is specified.
81 if meth
== "__div__" and 1/2 == 0.5:
84 if meth
== '__divmod__': pass
86 self
.assertEqual(eval(expr
, d
), res
)
89 while meth
not in t
.__dict
__:
91 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
92 # method object; the getattr() below obtains its underlying function.
93 self
.assertEqual(getattr(m
, 'im_func', m
), t
.__dict
__[meth
])
94 self
.assertEqual(m(a
, b
), res
)
96 self
.assertEqual(bm(b
), res
)
98 def ternop_test(self
, a
, b
, c
, res
, expr
="a[b:c]", meth
="__getslice__"):
99 d
= {'a': a
, 'b': b
, 'c': c
}
100 self
.assertEqual(eval(expr
, d
), res
)
103 while meth
not in t
.__dict
__:
105 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
106 # method object; the getattr() below obtains its underlying function.
107 self
.assertEqual(getattr(m
, 'im_func', m
), t
.__dict
__[meth
])
108 self
.assertEqual(m(a
, b
, c
), res
)
109 bm
= getattr(a
, meth
)
110 self
.assertEqual(bm(b
, c
), res
)
112 def setop_test(self
, a
, b
, res
, stmt
="a+=b", meth
="__iadd__"):
113 d
= {'a': deepcopy(a
), 'b': b
}
115 self
.assertEqual(d
['a'], res
)
118 while meth
not in t
.__dict
__:
120 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
121 # method object; the getattr() below obtains its underlying function.
122 self
.assertEqual(getattr(m
, 'im_func', m
), t
.__dict
__[meth
])
125 self
.assertEqual(d
['a'], res
)
127 bm
= getattr(d
['a'], meth
)
129 self
.assertEqual(d
['a'], res
)
131 def set2op_test(self
, a
, b
, c
, res
, stmt
="a[b]=c", meth
="__setitem__"):
132 d
= {'a': deepcopy(a
), 'b': b
, 'c': c
}
134 self
.assertEqual(d
['a'], res
)
137 while meth
not in t
.__dict
__:
139 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
140 # method object; the getattr() below obtains its underlying function.
141 self
.assertEqual(getattr(m
, 'im_func', m
), t
.__dict
__[meth
])
144 self
.assertEqual(d
['a'], res
)
146 bm
= getattr(d
['a'], meth
)
148 self
.assertEqual(d
['a'], res
)
150 def set3op_test(self
, a
, b
, c
, d
, res
, stmt
="a[b:c]=d", meth
="__setslice__"):
151 dictionary
= {'a': deepcopy(a
), 'b': b
, 'c': c
, 'd': d
}
152 exec stmt
in dictionary
153 self
.assertEqual(dictionary
['a'], res
)
155 while meth
not in t
.__dict
__:
158 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
159 # method object; the getattr() below obtains its underlying function.
160 self
.assertEqual(getattr(m
, 'im_func', m
), t
.__dict
__[meth
])
161 dictionary
['a'] = deepcopy(a
)
162 m(dictionary
['a'], b
, c
, d
)
163 self
.assertEqual(dictionary
['a'], res
)
164 dictionary
['a'] = deepcopy(a
)
165 bm
= getattr(dictionary
['a'], meth
)
167 self
.assertEqual(dictionary
['a'], res
)
169 def test_lists(self
):
170 # Testing list operations...
171 # Asserts are within individual test methods
172 self
.binop_test([1], [2], [1,2], "a+b", "__add__")
173 self
.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
174 self
.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
175 self
.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
176 self
.ternop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
177 self
.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
178 self
.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
179 self
.unop_test([1,2,3], 3, "len(a)", "__len__")
180 self
.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
181 self
.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
182 self
.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
183 self
.set3op_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
186 def test_dicts(self
):
187 # Testing dict operations...
188 if hasattr(dict, '__cmp__'): # PyPy has only rich comparison on dicts
189 self
.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
191 self
.binop_test({1:2}, {2:1}, True, "a < b", "__lt__")
192 self
.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
193 self
.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
194 self
.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
203 self
.assertEqual(l
, l1
)
205 for i
in d
.__iter
__():
207 self
.assertEqual(l
, l1
)
209 for i
in dict.__iter
__(d
):
211 self
.assertEqual(l
, l1
)
213 self
.unop_test(d
, 2, "len(a)", "__len__")
214 self
.assertEqual(eval(repr(d
), {}), d
)
215 self
.assertEqual(eval(d
.__repr
__(), {}), d
)
216 self
.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
219 # Tests for unary and binary operators
220 def number_operators(self
, a
, b
, skip
=[]):
221 dict = {'a': a
, 'b': b
}
223 for name
, expr
in self
.binops
.items():
225 name
= "__%s__" % name
227 res
= eval(expr
, dict)
228 self
.binop_test(a
, b
, res
, expr
, name
)
230 for name
, expr
in self
.unops
.items():
232 name
= "__%s__" % name
234 res
= eval(expr
, dict)
235 self
.unop_test(a
, res
, expr
, name
)
238 # Testing int operations...
239 self
.number_operators(100, 3)
240 # The following crashes in Python 2.2
241 self
.assertEqual((1).__nonzero
__(), 1)
242 self
.assertEqual((0).__nonzero
__(), 0)
243 # This returns 'NotImplemented' in Python 2.2
245 def __add__(self
, other
):
246 return NotImplemented
247 self
.assertEqual(C(5L), 5)
253 self
.fail("NotImplemented should have caused TypeError")
256 except OverflowError:
259 self
.fail("should have raised OverflowError")
261 def test_longs(self
):
262 # Testing long operations...
263 self
.number_operators(100L, 3L)
265 def test_floats(self
):
266 # Testing float operations...
267 self
.number_operators(100.0, 3.0)
269 def test_complexes(self
):
270 # Testing complex operations...
271 self
.number_operators(100.0j
, 3.0j
, skip
=['lt', 'le', 'gt', 'ge',
272 'int', 'long', 'float'])
274 class Number(complex):
276 def __new__(cls
, *args
, **kwds
):
277 result
= complex.__new
__(cls
, *args
)
278 result
.prec
= kwds
.get('prec', 12)
283 return "%.*g" % (prec
, self
.real
)
285 return "%.*gj" % (prec
, self
.imag
)
286 return "(%.*g+%.*gj)" % (prec
, self
.real
, prec
, self
.imag
)
289 a
= Number(3.14, prec
=6)
290 self
.assertEqual(repr(a
), "3.14")
291 self
.assertEqual(a
.prec
, 6)
293 a
= Number(a
, prec
=2)
294 self
.assertEqual(repr(a
), "3.1")
295 self
.assertEqual(a
.prec
, 2)
298 self
.assertEqual(repr(a
), "234.5")
299 self
.assertEqual(a
.prec
, 12)
301 @test_support.impl_detail("the module 'xxsubtype' is internal")
302 def test_spam_lists(self
):
303 # Testing spamlist operations...
304 import copy
, xxsubtype
as spam
306 def spamlist(l
, memo
=None):
307 import xxsubtype
as spam
308 return spam
.spamlist(l
)
310 # This is an ugly hack:
311 copy
._deepcopy
_dispatch
[spam
.spamlist
] = spamlist
313 self
.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
315 self
.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
316 self
.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
317 self
.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
318 self
.ternop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
320 self
.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
322 self
.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
324 self
.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
325 self
.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
327 self
.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
329 self
.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
331 self
.set3op_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
332 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
334 class C(spam
.spamlist
):
335 def foo(self
): return 1
337 self
.assertEqual(a
, [])
338 self
.assertEqual(a
.foo(), 1)
340 self
.assertEqual(a
, [100])
341 self
.assertEqual(a
.getstate(), 0)
343 self
.assertEqual(a
.getstate(), 42)
345 @test_support.impl_detail("the module 'xxsubtype' is internal")
346 def test_spam_dicts(self
):
347 # Testing spamdict operations...
348 import copy
, xxsubtype
as spam
349 def spamdict(d
, memo
=None):
350 import xxsubtype
as spam
352 for k
, v
in d
.items():
355 # This is an ugly hack:
356 copy
._deepcopy
_dispatch
[spam
.spamdict
] = spamdict
358 self
.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)",
360 self
.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
361 self
.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
362 self
.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
363 d
= spamdict({1:2,3:4})
370 self
.assertEqual(l
, l1
)
372 for i
in d
.__iter
__():
374 self
.assertEqual(l
, l1
)
376 for i
in type(spamdict({})).__iter
__(d
):
378 self
.assertEqual(l
, l1
)
379 straightd
= {1:2, 3:4}
380 spamd
= spamdict(straightd
)
381 self
.unop_test(spamd
, 2, "len(a)", "__len__")
382 self
.unop_test(spamd
, repr(straightd
), "repr(a)", "__repr__")
383 self
.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
384 "a[b]=c", "__setitem__")
386 class C(spam
.spamdict
):
387 def foo(self
): return 1
389 self
.assertEqual(a
.items(), [])
390 self
.assertEqual(a
.foo(), 1)
392 self
.assertEqual(a
.items(), [('foo', 'bar')])
393 self
.assertEqual(a
.getstate(), 0)
395 self
.assertEqual(a
.getstate(), 100)
397 class ClassPropertiesAndMethods(unittest
.TestCase
):
399 def test_python_dicts(self
):
400 # Testing Python subclass of dict...
401 self
.assertTrue(issubclass(dict, dict))
402 self
.assertIsInstance({}, dict)
404 self
.assertEqual(d
, {})
405 self
.assertTrue(d
.__class
__ is dict)
406 self
.assertIsInstance(d
, dict)
409 def __init__(self_local
, *a
, **kw
):
411 self
.assertEqual(len(a
), 1)
412 self_local
.state
= a
[0]
414 for k
, v
in kw
.items():
416 def __getitem__(self
, key
):
417 return self
.get(key
, 0)
418 def __setitem__(self_local
, key
, value
):
419 self
.assertIsInstance(key
, type(0))
420 dict.__setitem
__(self_local
, key
, value
)
421 def setstate(self
, state
):
425 self
.assertTrue(issubclass(C
, dict))
427 self
.assertEqual(a1
.state
, 12)
429 self
.assertEqual(a2
[1] == 'foo' and a2
[2], 'bar')
431 self
.assertEqual(a
.state
, -1)
432 self
.assertEqual(a
.getstate(), -1)
434 self
.assertEqual(a
.state
, 0)
435 self
.assertEqual(a
.getstate(), 0)
437 self
.assertEqual(a
.state
, 10)
438 self
.assertEqual(a
.getstate(), 10)
439 self
.assertEqual(a
[42], 0)
441 self
.assertEqual(a
[42], 24)
449 self
.assertEqual(a
[i
][j
], i
*j
)
451 def test_python_lists(self
):
452 # Testing Python subclass of list...
454 def __getitem__(self
, i
):
455 return list.__getitem
__(self
, i
) + 100
456 def __getslice__(self
, i
, j
):
460 self
.assertEqual(a
[0], 100)
461 self
.assertEqual(a
[1], 101)
462 self
.assertEqual(a
[2], 102)
463 self
.assertEqual(a
[100:200], (100,200))
465 def test_metaclass(self
):
466 # Testing __metaclass__...
473 def setstate(self
, state
):
476 self
.assertEqual(a
.getstate(), 0)
478 self
.assertEqual(a
.getstate(), 10)
480 class __metaclass__(type):
481 def myself(cls
): return cls
482 self
.assertEqual(D
.myself(), D
)
484 self
.assertEqual(d
.__class
__, D
)
486 def __new__(cls
, name
, bases
, dict):
488 return type.__new
__(cls
, name
, bases
, dict)
491 self
.assertEqual(C
.__spam
__, 1)
493 self
.assertEqual(c
.__spam
__, 1)
495 class _instance(object):
499 def __new__(cls
, name
, bases
, dict):
500 self
= object.__new
__(cls
)
507 # Early binding of methods
508 for key
in self
.dict:
509 if key
.startswith("__"):
511 setattr(it
, key
, self
.dict[key
].__get
__(it
, self
))
517 self
.assertEqual(C
.name
, 'C')
518 self
.assertEqual(C
.bases
, ())
519 self
.assertIn('spam', C
.dict)
521 self
.assertEqual(c
.spam(), 42)
523 # More metaclass examples
525 class autosuper(type):
526 # Automatically add __super to the class
527 # This trick only works for dynamic classes
528 def __new__(metaclass
, name
, bases
, dict):
529 cls
= super(autosuper
, metaclass
).__new
__(metaclass
,
531 # Name mangling for __super removes leading underscores
532 while name
[:1] == "_":
535 name
= "_%s__super" % name
538 setattr(cls
, name
, super(cls
))
541 __metaclass__
= autosuper
546 return "B" + self
.__super
.meth()
549 return "C" + self
.__super
.meth()
552 return "D" + self
.__super
.meth()
553 self
.assertEqual(D().meth(), "DCBA")
556 return "E" + self
.__super
.meth()
557 self
.assertEqual(E().meth(), "EBCA")
559 class autoproperty(type):
560 # Automatically create property attributes when methods
561 # named _get_x and/or _set_x are found
562 def __new__(metaclass
, name
, bases
, dict):
564 for key
, val
in dict.iteritems():
565 if key
.startswith("_get_"):
567 get
, set = hits
.get(key
, (None, None))
570 elif key
.startswith("_set_"):
572 get
, set = hits
.get(key
, (None, None))
575 for key
, (get
, set) in hits
.iteritems():
576 dict[key
] = property(get
, set)
577 return super(autoproperty
, metaclass
).__new
__(metaclass
,
580 __metaclass__
= autoproperty
586 self
.assertTrue(not hasattr(a
, "x"))
588 self
.assertEqual(a
.x
, 12)
589 self
.assertEqual(a
._A
__x
, -12)
591 class multimetaclass(autoproperty
, autosuper
):
592 # Merge of multiple cooperating metaclasses
595 __metaclass__
= multimetaclass
600 return "B" + self
.__super
._get
_x
()
603 return "C" + self
.__super
._get
_x
()
606 return "D" + self
.__super
._get
_x
()
607 self
.assertEqual(D().x
, "DCBA")
609 # Make sure type(x) doesn't call x.__class__.__init__
612 def __init__(self
, *args
):
616 self
.assertEqual(T
.counter
, 1)
618 self
.assertEqual(type(a
), C
)
619 self
.assertEqual(T
.counter
, 1)
621 class C(object): pass
624 except TypeError: pass
625 else: self
.fail("calling object w/o call method should raise "
628 # Testing code to find most derived baseclass
630 def __new__(*args
, **kwargs
):
631 return type.__new
__(*args
, **kwargs
)
639 # The most derived metaclass of D is A rather than type.
643 def test_module_subclasses(self
):
644 # Testing Python subclass of module...
648 def __init__(self
, name
):
649 MT
.__init
__(self
, name
)
650 def __getattribute__(self
, name
):
651 log
.append(("getattr", name
))
652 return MT
.__getattribute
__(self
, name
)
653 def __setattr__(self
, name
, value
):
654 log
.append(("setattr", name
, value
))
655 MT
.__setattr
__(self
, name
, value
)
656 def __delattr__(self
, name
):
657 log
.append(("delattr", name
))
658 MT
.__delattr
__(self
, name
)
663 self
.assertEqual(log
, [("setattr", "foo", 12),
667 # http://python.org/sf/1174712
669 class Module(types
.ModuleType
, str):
674 self
.fail("inheriting from ModuleType and str at the same time "
677 def test_multiple_inheritence(self
):
678 # Testing multiple inheritance...
684 def setstate(self
, state
):
687 self
.assertEqual(a
.getstate(), 0)
689 self
.assertEqual(a
.getstate(), 10)
692 type({}).__init
__(self
)
695 self
.assertEqual(d
.keys(), [])
697 self
.assertEqual(d
.items(), [("hello", "world")])
698 self
.assertEqual(d
["hello"], "world")
699 self
.assertEqual(d
.getstate(), 0)
701 self
.assertEqual(d
.getstate(), 10)
702 self
.assertEqual(D
.__mro
__, (D
, dict, C
, object))
707 return int(self
.foo())
710 class Frag(Node
, list):
713 self
.assertEqual(Node().__int
__(), 23)
714 self
.assertEqual(int(Node()), 23)
715 self
.assertEqual(Frag().__int
__(), 42)
716 self
.assertEqual(int(Frag()), 42)
718 # MI mixing classic and new-style classes.
731 self
.assertEqual(D
.x
, 1)
733 # Classic MRO is preserved for a classic base class.
736 self
.assertEqual(E
.__mro
__, (E
, D
, B
, A
, C
, object))
737 self
.assertEqual(E
.x
, 1)
739 # But with a mix of classic bases, their MROs are combined using
741 class F(B
, C
, object):
743 self
.assertEqual(F
.__mro
__, (F
, B
, C
, A
, object))
744 self
.assertEqual(F
.x
, 2)
746 # Try something else.
750 def all_method(self
):
756 def all_method(self
):
759 self
.assertEqual(M1
.__mro__
, (M1
, C
, object))
761 self
.assertEqual(m
.cmethod(), "C a")
762 self
.assertEqual(m
.m1method(), "M1 a")
763 self
.assertEqual(m
.all_method(), "M1 b")
768 def all_method(self
):
774 def all_method(self
):
777 self
.assertEqual(M2
.__mro__
, (M2
, D
, C
, object))
779 self
.assertEqual(m
.cmethod(), "C a")
780 self
.assertEqual(m
.dmethod(), "D a")
781 self
.assertEqual(m
.m2method(), "M2 a")
782 self
.assertEqual(m
.all_method(), "M2 b")
784 class M3(M1
, M2
, object):
787 def all_method(self
):
789 self
.assertEqual(M3
.__mro__
, (M3
, M1
, M2
, D
, C
, object))
791 self
.assertEqual(m
.cmethod(), "C a")
792 self
.assertEqual(m
.dmethod(), "D a")
793 self
.assertEqual(m
.m1method(), "M1 a")
794 self
.assertEqual(m
.m2method(), "M2 a")
795 self
.assertEqual(m
.m3method(), "M3 a")
796 self
.assertEqual(m
.all_method(), "M3 b")
806 self
.fail("new class with only classic bases - shouldn't be")
808 def test_diamond_inheritence(self
):
809 # Testing multiple inheritance special cases...
811 def spam(self
): return "A"
812 self
.assertEqual(A().spam(), "A")
814 def boo(self
): return "B"
815 def spam(self
): return "B"
816 self
.assertEqual(B().spam(), "B")
817 self
.assertEqual(B().boo(), "B")
819 def boo(self
): return "C"
820 self
.assertEqual(C().spam(), "A")
821 self
.assertEqual(C().boo(), "C")
823 self
.assertEqual(D().spam(), "B")
824 self
.assertEqual(D().boo(), "B")
825 self
.assertEqual(D
.__mro
__, (D
, B
, C
, A
, object))
827 self
.assertEqual(E().spam(), "B")
828 self
.assertEqual(E().boo(), "C")
829 self
.assertEqual(E
.__mro
__, (E
, C
, B
, A
, object))
830 # MRO order disagreement
836 self
.fail("expected MRO order disagreement (F)")
842 self
.fail("expected MRO order disagreement (G)")
844 # see thread python-dev/2002-October/029035.html
845 def test_ex5_from_c3_switch(self
):
846 # Testing ex5 from C3 switch discussion...
847 class A(object): pass
848 class B(object): pass
849 class C(object): pass
852 class Z(X
,B
,Y
,C
): pass
853 self
.assertEqual(Z
.__mro
__, (Z
, X
, B
, Y
, A
, C
, object))
855 # see "A Monotonic Superclass Linearization for Dylan",
856 # by Kim Barrett et al. (OOPSLA 1996)
857 def test_monotonicity(self
):
858 # Testing MRO monotonicity...
859 class Boat(object): pass
860 class DayBoat(Boat
): pass
861 class WheelBoat(Boat
): pass
862 class EngineLess(DayBoat
): pass
863 class SmallMultihull(DayBoat
): pass
864 class PedalWheelBoat(EngineLess
,WheelBoat
): pass
865 class SmallCatamaran(SmallMultihull
): pass
866 class Pedalo(PedalWheelBoat
,SmallCatamaran
): pass
868 self
.assertEqual(PedalWheelBoat
.__mro
__,
869 (PedalWheelBoat
, EngineLess
, DayBoat
, WheelBoat
, Boat
, object))
870 self
.assertEqual(SmallCatamaran
.__mro
__,
871 (SmallCatamaran
, SmallMultihull
, DayBoat
, Boat
, object))
872 self
.assertEqual(Pedalo
.__mro
__,
873 (Pedalo
, PedalWheelBoat
, EngineLess
, SmallCatamaran
,
874 SmallMultihull
, DayBoat
, WheelBoat
, Boat
, object))
876 # see "A Monotonic Superclass Linearization for Dylan",
877 # by Kim Barrett et al. (OOPSLA 1996)
878 def test_consistency_with_epg(self
):
879 # Testing consistentcy with EPG...
880 class Pane(object): pass
881 class ScrollingMixin(object): pass
882 class EditingMixin(object): pass
883 class ScrollablePane(Pane
,ScrollingMixin
): pass
884 class EditablePane(Pane
,EditingMixin
): pass
885 class EditableScrollablePane(ScrollablePane
,EditablePane
): pass
887 self
.assertEqual(EditableScrollablePane
.__mro
__,
888 (EditableScrollablePane
, ScrollablePane
, EditablePane
, Pane
,
889 ScrollingMixin
, EditingMixin
, object))
891 def test_mro_disagreement(self
):
892 # Testing error messages for MRO disagreement...
893 mro_err_msg
= """Cannot create a consistent method resolution
894 order (MRO) for bases """
896 def raises(exc
, expected
, callable, *args
):
900 # the exact msg is generally considered an impl detail
901 if test_support
.check_impl_detail():
902 if not str(msg
).startswith(expected
):
903 self
.fail("Message %r, expected %r" %
904 (str(msg
), expected
))
906 self
.fail("Expected %s" % exc
)
908 class A(object): pass
910 class C(object): pass
912 # Test some very simple errors
913 raises(TypeError, "duplicate base class A",
914 type, "X", (A
, A
), {})
915 raises(TypeError, mro_err_msg
,
916 type, "X", (A
, B
), {})
917 raises(TypeError, mro_err_msg
,
918 type, "X", (A
, C
, B
), {})
919 # Test a slightly more complex error
920 class GridLayout(object): pass
921 class HorizontalGrid(GridLayout
): pass
922 class VerticalGrid(GridLayout
): pass
923 class HVGrid(HorizontalGrid
, VerticalGrid
): pass
924 class VHGrid(VerticalGrid
, HorizontalGrid
): pass
925 raises(TypeError, mro_err_msg
,
926 type, "ConfusedGrid", (HVGrid
, VHGrid
), {})
928 def test_object_class(self
):
929 # Testing object class...
931 self
.assertEqual(a
.__class
__, object)
932 self
.assertEqual(type(a
), object)
934 self
.assertNotEqual(a
, b
)
935 self
.assertFalse(hasattr(a
, "foo"))
938 except (AttributeError, TypeError):
941 self
.fail("object() should not allow setting a foo attribute")
942 self
.assertFalse(hasattr(object(), "__dict__"))
947 self
.assertEqual(x
.__dict
__, {})
949 self
.assertEqual(x
.foo
, 1)
950 self
.assertEqual(x
.__dict
__, {'foo': 1})
952 def test_slots(self
):
953 # Testing __slots__...
957 self
.assertFalse(hasattr(x
, "__dict__"))
958 self
.assertFalse(hasattr(x
, "foo"))
963 self
.assertFalse(hasattr(x
, "__dict__"))
964 self
.assertFalse(hasattr(x
, "a"))
966 self
.assertEqual(x
.a
, 1)
968 self
.assertEqual(x
.a
, None)
970 self
.assertFalse(hasattr(x
, "a"))
973 __slots__
= ['a', 'b', 'c']
975 self
.assertFalse(hasattr(x
, "__dict__"))
976 self
.assertFalse(hasattr(x
, 'a'))
977 self
.assertFalse(hasattr(x
, 'b'))
978 self
.assertFalse(hasattr(x
, 'c'))
982 self
.assertEqual(x
.a
, 1)
983 self
.assertEqual(x
.b
, 2)
984 self
.assertEqual(x
.c
, 3)
987 """Validate name mangling"""
989 def __init__(self
, value
):
994 self
.assertFalse(hasattr(x
, '__dict__'))
995 self
.assertFalse(hasattr(x
, '__a'))
996 self
.assertEqual(x
.get(), 5)
999 except AttributeError:
1002 self
.fail("Double underscored names not mangled")
1004 # Make sure slot names are proper identifiers
1011 self
.fail("[None] slots not caught")
1014 __slots__
= ["foo bar"]
1018 self
.fail("['foo bar'] slots not caught")
1021 __slots__
= ["foo\0bar"]
1025 self
.fail("['foo\\0bar'] slots not caught")
1032 self
.fail("['1'] slots not caught")
1039 self
.fail("[''] slots not caught")
1041 __slots__
= ["a", "a_b", "_a", "A0123456789Z"]
1042 # XXX(nnorwitz): was there supposed to be something tested
1043 # from the class above?
1045 # Test a single string is not expanded as a sequence.
1050 self
.assertEqual(c
.abc
, 5)
1052 # Test unicode slot names
1058 # Test a single unicode string is not expanded as a sequence.
1060 __slots__
= unicode("abc")
1063 self
.assertEqual(c
.abc
, 5)
1065 # _unicode_to_string used to modify slots in certain circumstances
1066 slots
= (unicode("foo"), unicode("bar"))
1071 self
.assertEqual(x
.foo
, 5)
1072 self
.assertEqual(type(slots
[0]), unicode)
1073 # this used to leak references
1076 __slots__
= [unichr(128)]
1077 except (TypeError, UnicodeEncodeError):
1080 self
.fail("[unichr(128)] slots not caught")
1083 class Counted(object):
1084 counter
= 0 # counts the number of instances alive
1086 Counted
.counter
+= 1
1088 Counted
.counter
-= 1
1090 __slots__
= ['a', 'b', 'c']
1095 self
.assertEqual(Counted
.counter
, 3)
1097 test_support
.gc_collect()
1098 self
.assertEqual(Counted
.counter
, 0)
1104 self
.assertEqual(Counted
.counter
, 2)
1106 test_support
.gc_collect()
1107 self
.assertEqual(Counted
.counter
, 0)
1114 self
.assertEqual(Counted
.counter
, 3)
1116 test_support
.gc_collect()
1117 self
.assertEqual(Counted
.counter
, 0)
1119 # Test cyclical leaks [SF bug 519621]
1121 __slots__
= ['a', 'b']
1123 s
.a
= [Counted(), s
]
1124 self
.assertEqual(Counted
.counter
, 1)
1126 test_support
.gc_collect()
1127 self
.assertEqual(Counted
.counter
, 0)
1129 # Test lookup leaks [SF bug 572567]
1131 if hasattr(gc
, 'get_objects'):
1133 def __cmp__(self
, other
):
1135 __hash__
= None # Silence Py3k warning
1137 orig_objects
= len(gc
.get_objects())
1138 for i
in xrange(10):
1140 new_objects
= len(gc
.get_objects())
1141 self
.assertEqual(orig_objects
, new_objects
)
1144 __slots__
= ['a', 'b']
1149 self
.assertEqual(self_
.a
, 1)
1150 self
.assertEqual(self_
.b
, 2)
1151 with test_support
.captured_output('stderr') as s
:
1154 self
.assertEqual(s
.getvalue(), '')
1158 with self
.assertRaises(AttributeError):
1161 def test_slots_special(self
):
1162 # Testing __dict__ and __weakref__ in __slots__...
1164 __slots__
= ["__dict__"]
1166 self
.assertTrue(hasattr(a
, "__dict__"))
1167 self
.assertFalse(hasattr(a
, "__weakref__"))
1169 self
.assertEqual(a
.__dict
__, {"foo": 42})
1172 __slots__
= ["__weakref__"]
1174 self
.assertTrue(hasattr(a
, "__weakref__"))
1175 self
.assertFalse(hasattr(a
, "__dict__"))
1178 except AttributeError:
1181 self
.fail("shouldn't be allowed to set a.foo")
1186 self
.assertTrue(hasattr(a
, "__dict__"))
1187 self
.assertTrue(hasattr(a
, "__weakref__"))
1189 self
.assertEqual(a
.__dict
__, {"foo": 42})
1194 self
.assertTrue(hasattr(a
, "__dict__"))
1195 self
.assertTrue(hasattr(a
, "__weakref__"))
1197 self
.assertEqual(a
.__dict
__, {"foo": 42})
1199 def test_slots_descriptor(self
):
1200 # Issue2115: slot descriptors did not correctly check
1201 # the type of the given object
1204 __metaclass__
= abc
.ABCMeta
1207 class Unrelated(object):
1209 MyABC
.register(Unrelated
)
1212 self
.assertIsInstance(u
, MyABC
)
1214 # This used to crash
1215 self
.assertRaises(TypeError, MyABC
.a
.__set
__, u
, 3)
1217 def test_metaclass_cmp(self
):
1220 def __cmp__(self
, other
):
1224 self
.assertTrue(X
< M
)
1226 def test_dynamics(self
):
1227 # Testing class attribute propagation...
1235 self
.assertEqual(D
.foo
, 1)
1236 # Test that dynamic attributes are inherited
1237 self
.assertEqual(E
.foo
, 1)
1238 self
.assertEqual(F
.foo
, 1)
1239 # Test dynamic instances
1243 self
.assertFalse(hasattr(a
, "foobar"))
1245 self
.assertEqual(a
.foobar
, 2)
1246 C
.method
= lambda self
: 42
1247 self
.assertEqual(a
.method(), 42)
1248 C
.__repr
__ = lambda self
: "C()"
1249 self
.assertEqual(repr(a
), "C()")
1250 C
.__int
__ = lambda self
: 100
1251 self
.assertEqual(int(a
), 100)
1252 self
.assertEqual(a
.foobar
, 2)
1253 self
.assertFalse(hasattr(a
, "spam"))
1254 def mygetattr(self
, name
):
1257 raise AttributeError
1258 C
.__getattr
__ = mygetattr
1259 self
.assertEqual(a
.spam
, "spam")
1261 self
.assertEqual(a
.new
, 12)
1262 def mysetattr(self
, name
, value
):
1264 raise AttributeError
1265 return object.__setattr
__(self
, name
, value
)
1266 C
.__setattr
__ = mysetattr
1269 except AttributeError:
1272 self
.fail("expected AttributeError")
1273 self
.assertEqual(a
.spam
, "spam")
1278 self
.assertEqual(d
.foo
, 1)
1280 # Test handling of int*seq and seq*int
1283 self
.assertEqual("a"*I(2), "aa")
1284 self
.assertEqual(I(2)*"a", "aa")
1285 self
.assertEqual(2*I(3), 6)
1286 self
.assertEqual(I(3)*2, 6)
1287 self
.assertEqual(I(3)*I(2), 6)
1289 # Test handling of long*seq and seq*long
1292 self
.assertEqual("a"*L(2L), "aa")
1293 self
.assertEqual(L(2L)*"a", "aa")
1294 self
.assertEqual(2*L(3), 6)
1295 self
.assertEqual(L(3)*2, 6)
1296 self
.assertEqual(L(3)*L(2), 6)
1298 # Test comparison of classes with dynamic metaclasses
1299 class dynamicmetaclass(type):
1302 __metaclass__
= dynamicmetaclass
1303 self
.assertNotEqual(someclass
, object)
1305 def test_errors(self
):
1308 class C(list, dict):
1313 self
.fail("inheritance from both list and dict should be illegal")
1316 class C(object, None):
1321 self
.fail("inheritance from non-type should be illegal")
1331 self
.fail("inheritance from CFunction should be illegal")
1339 self
.fail("__slots__ = 1 should be illegal")
1347 self
.fail("__slots__ = [1] should be illegal")
1363 self
.fail("finding the most derived metaclass should have failed")
1365 def test_classmethods(self
):
1366 # Testing class methods...
1368 def foo(*a
): return a
1369 goo
= classmethod(foo
)
1371 self
.assertEqual(C
.goo(1), (C
, 1))
1372 self
.assertEqual(c
.goo(1), (C
, 1))
1373 self
.assertEqual(c
.foo(1), (c
, 1))
1377 self
.assertEqual(D
.goo(1), (D
, 1))
1378 self
.assertEqual(d
.goo(1), (D
, 1))
1379 self
.assertEqual(d
.foo(1), (d
, 1))
1380 self
.assertEqual(D
.foo(d
, 1), (d
, 1))
1381 # Test for a specific crash (SF bug 528132)
1382 def f(cls
, arg
): return (cls
, arg
)
1384 self
.assertEqual(ff
.__get
__(0, int)(42), (int, 42))
1385 self
.assertEqual(ff
.__get
__(0)(42), (int, 42))
1387 # Test super() with classmethods (SF bug 535444)
1388 self
.assertEqual(C
.goo
.im_self
, C
)
1389 self
.assertEqual(D
.goo
.im_self
, D
)
1390 self
.assertEqual(super(D
,D
).goo
.im_self
, D
)
1391 self
.assertEqual(super(D
,d
).goo
.im_self
, D
)
1392 self
.assertEqual(super(D
,D
).goo(), (D
,))
1393 self
.assertEqual(super(D
,d
).goo(), (D
,))
1395 # Verify that a non-callable will raise
1396 meth
= classmethod(1).__get
__(1)
1397 self
.assertRaises(TypeError, meth
)
1399 # Verify that classmethod() doesn't allow keyword args
1401 classmethod(f
, kw
=1)
1405 self
.fail("classmethod shouldn't accept keyword args")
1407 @test_support.impl_detail("the module 'xxsubtype' is internal")
1408 def test_classmethods_in_c(self
):
1409 # Testing C-based class methods...
1410 import xxsubtype
as spam
1413 x
, a1
, d1
= spam
.spamlist
.classmeth(*a
, **d
)
1414 self
.assertEqual(x
, spam
.spamlist
)
1415 self
.assertEqual(a
, a1
)
1416 self
.assertEqual(d
, d1
)
1417 x
, a1
, d1
= spam
.spamlist().classmeth(*a
, **d
)
1418 self
.assertEqual(x
, spam
.spamlist
)
1419 self
.assertEqual(a
, a1
)
1420 self
.assertEqual(d
, d1
)
1422 def test_staticmethods(self
):
1423 # Testing static methods...
1425 def foo(*a
): return a
1426 goo
= staticmethod(foo
)
1428 self
.assertEqual(C
.goo(1), (1,))
1429 self
.assertEqual(c
.goo(1), (1,))
1430 self
.assertEqual(c
.foo(1), (c
, 1,))
1434 self
.assertEqual(D
.goo(1), (1,))
1435 self
.assertEqual(d
.goo(1), (1,))
1436 self
.assertEqual(d
.foo(1), (d
, 1))
1437 self
.assertEqual(D
.foo(d
, 1), (d
, 1))
1439 @test_support.impl_detail("the module 'xxsubtype' is internal")
1440 def test_staticmethods_in_c(self
):
1441 # Testing C-based static methods...
1442 import xxsubtype
as spam
1445 x
, a1
, d1
= spam
.spamlist
.staticmeth(*a
, **d
)
1446 self
.assertEqual(x
, None)
1447 self
.assertEqual(a
, a1
)
1448 self
.assertEqual(d
, d1
)
1449 x
, a1
, d2
= spam
.spamlist().staticmeth(*a
, **d
)
1450 self
.assertEqual(x
, None)
1451 self
.assertEqual(a
, a1
)
1452 self
.assertEqual(d
, d1
)
1454 def test_classic(self
):
1455 # Testing classic classes...
1457 def foo(*a
): return a
1458 goo
= classmethod(foo
)
1460 self
.assertEqual(C
.goo(1), (C
, 1))
1461 self
.assertEqual(c
.goo(1), (C
, 1))
1462 self
.assertEqual(c
.foo(1), (c
, 1))
1466 self
.assertEqual(D
.goo(1), (D
, 1))
1467 self
.assertEqual(d
.goo(1), (D
, 1))
1468 self
.assertEqual(d
.foo(1), (d
, 1))
1469 self
.assertEqual(D
.foo(d
, 1), (d
, 1))
1470 class E
: # *not* subclassing from C
1472 self
.assertEqual(E().foo
, C
.foo
) # i.e., unbound
1473 self
.assertTrue(repr(C
.foo
.__get
__(C())).startswith("<bound method "))
1475 def test_compattr(self
):
1476 # Testing computed attributes...
1478 class computed_attribute(object):
1479 def __init__(self
, get
, set=None, delete
=None):
1482 self
.__delete
= delete
1483 def __get__(self
, obj
, type=None):
1484 return self
.__get
(obj
)
1485 def __set__(self
, obj
, value
):
1486 return self
.__set
(obj
, value
)
1487 def __delete__(self
, obj
):
1488 return self
.__delete
(obj
)
1495 def __set_x(self
, x
):
1497 def __delete_x(self
):
1499 x
= computed_attribute(__get_x
, __set_x
, __delete_x
)
1501 self
.assertEqual(a
.x
, 0)
1502 self
.assertEqual(a
.x
, 1)
1504 self
.assertEqual(a
.x
, 10)
1505 self
.assertEqual(a
.x
, 11)
1507 self
.assertEqual(hasattr(a
, 'x'), 0)
1509 def test_newslots(self
):
1510 # Testing __new__ slot override...
1513 self
= list.__new
__(cls
)
1517 self
.foo
= self
.foo
+ 2
1519 self
.assertEqual(a
.foo
, 3)
1520 self
.assertEqual(a
.__class
__, C
)
1524 self
.assertEqual(b
.foo
, 3)
1525 self
.assertEqual(b
.__class
__, D
)
1527 def test_altmro(self
):
1528 # Testing mro() and overriding it...
1530 def f(self
): return "A"
1534 def f(self
): return "C"
1537 self
.assertEqual(D
.mro(), [D
, B
, C
, A
, object])
1538 self
.assertEqual(D
.__mro
__, (D
, B
, C
, A
, object))
1539 self
.assertEqual(D().f(), "C")
1541 class PerverseMetaType(type):
1547 __metaclass__
= PerverseMetaType
1548 self
.assertEqual(X
.__mro
__, (object, A
, C
, B
, D
, X
))
1549 self
.assertEqual(X().f(), "A")
1553 class __metaclass__(type):
1555 return [self
, dict, object]
1556 # In CPython, the class creation above already raises
1557 # TypeError, as a protection against the fact that
1558 # instances of X would segfault it. In other Python
1559 # implementations it would be ok to let the class X
1560 # be created, but instead get a clean TypeError on the
1561 # __setitem__ below.
1562 x
= object.__new
__(X
)
1567 self
.fail("devious mro() return not caught")
1571 class __metaclass__(type):
1577 self
.fail("non-class mro() return not caught")
1581 class __metaclass__(type):
1587 self
.fail("non-sequence mro() return not caught")
1589 def test_overloading(self
):
1590 # Testing operator overloading...
1593 "Intermediate class because object doesn't have a __setattr__"
1596 def __getattr__(self
, name
):
1598 return ("getattr", name
)
1600 raise AttributeError
1601 def __setattr__(self
, name
, value
):
1603 self
.setattr = (name
, value
)
1605 return B
.__setattr
__(self
, name
, value
)
1606 def __delattr__(self
, name
):
1610 return B
.__delattr
__(self
, name
)
1612 def __getitem__(self
, key
):
1613 return ("getitem", key
)
1614 def __setitem__(self
, key
, value
):
1615 self
.setitem
= (key
, value
)
1616 def __delitem__(self
, key
):
1619 def __getslice__(self
, i
, j
):
1620 return ("getslice", i
, j
)
1621 def __setslice__(self
, i
, j
, value
):
1622 self
.setslice
= (i
, j
, value
)
1623 def __delslice__(self
, i
, j
):
1624 self
.delslice
= (i
, j
)
1627 self
.assertEqual(a
.foo
, ("getattr", "foo"))
1629 self
.assertEqual(a
.setattr, ("foo", 12))
1631 self
.assertEqual(a
.delattr, "foo")
1633 self
.assertEqual(a
[12], ("getitem", 12))
1635 self
.assertEqual(a
.setitem
, (12, 21))
1637 self
.assertEqual(a
.delitem
, 12)
1639 self
.assertEqual(a
[0:10], ("getslice", 0, 10))
1641 self
.assertEqual(a
.setslice
, (0, 10, "foo"))
1643 self
.assertEqual(a
.delslice
, (0, 10))
1645 def test_methods(self
):
1646 # Testing methods...
1648 def __init__(self
, x
):
1653 self
.assertEqual(c1
.foo(), 1)
1658 self
.assertEqual(d2
.foo(), 2)
1659 self
.assertEqual(d2
.boo(), 2)
1660 self
.assertEqual(d2
.goo(), 1)
1663 self
.assertEqual(E().foo
, C
.foo
) # i.e., unbound
1664 self
.assertTrue(repr(C
.foo
.__get
__(C(1))).startswith("<bound method "))
1666 def test_special_method_lookup(self
):
1667 # The lookup of special methods bypasses __getattr__ and
1668 # __getattribute__, but they still can be descriptors.
1670 def run_context(manager
):
1677 def empty_seq(self
):
1681 def complex_num(self
):
1685 def return_true(self
, thing
=None):
1687 def do_isinstance(obj
):
1688 return isinstance(int, obj
)
1689 def do_issubclass(obj
):
1690 return issubclass(int, obj
)
1693 def do_dict_missing(checker
):
1694 class DictSub(checker
.__class
__, dict):
1696 self
.assertEqual(DictSub()["hi"], 4)
1697 def some_number(self_
, key
):
1698 self
.assertEqual(key
, "hi")
1700 def format_impl(self
, spec
):
1703 # It would be nice to have every special method tested here, but I'm
1704 # only listing the ones I can remember outside of typeobject.c, since it
1707 ("__unicode__", unicode, hello
, set(), {}),
1708 ("__reversed__", reversed, empty_seq
, set(), {}),
1709 ("__length_hint__", list, zero
, set(),
1710 {"__iter__" : iden
, "next" : stop
}),
1711 ("__sizeof__", sys
.getsizeof
, zero
, set(), {}),
1712 ("__instancecheck__", do_isinstance
, return_true
, set(), {}),
1713 ("__missing__", do_dict_missing
, some_number
,
1714 set(("__class__",)), {}),
1715 ("__subclasscheck__", do_issubclass
, return_true
,
1716 set(("__bases__",)), {}),
1717 ("__enter__", run_context
, iden
, set(), {"__exit__" : swallow
}),
1718 ("__exit__", run_context
, swallow
, set(), {"__enter__" : iden
}),
1719 ("__complex__", complex, complex_num
, set(), {}),
1720 ("__format__", format
, format_impl
, set(), {}),
1723 class Checker(object):
1724 def __getattr__(self
, attr
, test
=self
):
1725 test
.fail("__getattr__ called with {0}".format(attr
))
1726 def __getattribute__(self
, attr
, test
=self
):
1728 test
.fail("__getattribute__ called with {0}".format(attr
))
1729 return object.__getattribute
__(self
, attr
)
1730 class SpecialDescr(object):
1731 def __init__(self
, impl
):
1733 def __get__(self
, obj
, owner
):
1735 return self
.impl
.__get
__(obj
, owner
)
1736 class MyException(Exception):
1738 class ErrDescr(object):
1739 def __get__(self
, obj
, owner
):
1742 for name
, runner
, meth_impl
, ok
, env
in specials
:
1745 for attr
, obj
in env
.iteritems():
1746 setattr(X
, attr
, obj
)
1747 setattr(X
, name
, meth_impl
)
1753 for attr
, obj
in env
.iteritems():
1754 setattr(X
, attr
, obj
)
1755 setattr(X
, name
, SpecialDescr(meth_impl
))
1757 self
.assertEqual(record
, [1], name
)
1761 for attr
, obj
in env
.iteritems():
1762 setattr(X
, attr
, obj
)
1763 setattr(X
, name
, ErrDescr())
1769 self
.fail("{0!r} didn't raise".format(name
))
1771 def test_specials(self
):
1772 # Testing special operators...
1773 # Test operators like __hash__ for which a built-in default exists
1775 # Test the default behavior for static classes
1777 def __getitem__(self
, i
):
1778 if 0 <= i
< 10: return i
1782 self
.assertTrue(not not c1
) # What?
1783 self
.assertNotEqual(id(c1
), id(c2
))
1786 self
.assertEqual(cmp(c1
, c2
), cmp(id(c1
), id(c2
)))
1787 self
.assertEqual(c1
, c1
)
1788 self
.assertTrue(c1
!= c2
)
1789 self
.assertTrue(not c1
!= c1
)
1790 self
.assertTrue(not c1
== c2
)
1791 # Note that the module name appears in str/repr, and that varies
1792 # depending on whether this test is run standalone or from a framework.
1793 self
.assertTrue(str(c1
).find('C object at ') >= 0)
1794 self
.assertEqual(str(c1
), repr(c1
))
1795 self
.assertNotIn(-1, c1
)
1797 self
.assertIn(i
, c1
)
1798 self
.assertNotIn(10, c1
)
1799 # Test the default behavior for dynamic classes
1801 def __getitem__(self
, i
):
1802 if 0 <= i
< 10: return i
1806 self
.assertTrue(not not d1
)
1807 self
.assertNotEqual(id(d1
), id(d2
))
1810 self
.assertEqual(cmp(d1
, d2
), cmp(id(d1
), id(d2
)))
1811 self
.assertEqual(d1
, d1
)
1812 self
.assertNotEqual(d1
, d2
)
1813 self
.assertTrue(not d1
!= d1
)
1814 self
.assertTrue(not d1
== d2
)
1815 # Note that the module name appears in str/repr, and that varies
1816 # depending on whether this test is run standalone or from a framework.
1817 self
.assertTrue(str(d1
).find('D object at ') >= 0)
1818 self
.assertEqual(str(d1
), repr(d1
))
1819 self
.assertNotIn(-1, d1
)
1821 self
.assertIn(i
, d1
)
1822 self
.assertNotIn(10, d1
)
1823 # Test overridden behavior for static classes
1824 class Proxy(object):
1825 def __init__(self
, x
):
1827 def __nonzero__(self
):
1828 return not not self
.x
1831 def __eq__(self
, other
):
1832 return self
.x
== other
1833 def __ne__(self
, other
):
1834 return self
.x
!= other
1835 def __cmp__(self
, other
):
1836 return cmp(self
.x
, other
.x
)
1838 return "Proxy:%s" % self
.x
1840 return "Proxy(%r)" % self
.x
1841 def __contains__(self
, value
):
1842 return value
in self
.x
1846 self
.assertFalse(p0
)
1847 self
.assertTrue(not not p1
)
1848 self
.assertEqual(hash(p0
), hash(0))
1849 self
.assertEqual(p0
, p0
)
1850 self
.assertNotEqual(p0
, p1
)
1851 self
.assertTrue(not p0
!= p0
)
1852 self
.assertEqual(not p0
, p1
)
1853 self
.assertEqual(cmp(p0
, p1
), -1)
1854 self
.assertEqual(cmp(p0
, p0
), 0)
1855 self
.assertEqual(cmp(p0
, p_1
), 1)
1856 self
.assertEqual(str(p0
), "Proxy:0")
1857 self
.assertEqual(repr(p0
), "Proxy(0)")
1858 p10
= Proxy(range(10))
1859 self
.assertNotIn(-1, p10
)
1861 self
.assertIn(i
, p10
)
1862 self
.assertNotIn(10, p10
)
1863 # Test overridden behavior for dynamic classes
1864 class DProxy(object):
1865 def __init__(self
, x
):
1867 def __nonzero__(self
):
1868 return not not self
.x
1871 def __eq__(self
, other
):
1872 return self
.x
== other
1873 def __ne__(self
, other
):
1874 return self
.x
!= other
1875 def __cmp__(self
, other
):
1876 return cmp(self
.x
, other
.x
)
1878 return "DProxy:%s" % self
.x
1880 return "DProxy(%r)" % self
.x
1881 def __contains__(self
, value
):
1882 return value
in self
.x
1886 self
.assertFalse(p0
)
1887 self
.assertTrue(not not p1
)
1888 self
.assertEqual(hash(p0
), hash(0))
1889 self
.assertEqual(p0
, p0
)
1890 self
.assertNotEqual(p0
, p1
)
1891 self
.assertNotEqual(not p0
, p0
)
1892 self
.assertEqual(not p0
, p1
)
1893 self
.assertEqual(cmp(p0
, p1
), -1)
1894 self
.assertEqual(cmp(p0
, p0
), 0)
1895 self
.assertEqual(cmp(p0
, p_1
), 1)
1896 self
.assertEqual(str(p0
), "DProxy:0")
1897 self
.assertEqual(repr(p0
), "DProxy(0)")
1898 p10
= DProxy(range(10))
1899 self
.assertNotIn(-1, p10
)
1901 self
.assertIn(i
, p10
)
1902 self
.assertNotIn(10, p10
)
1904 # Safety test for __cmp__
1905 def unsafecmp(a
, b
):
1906 if not hasattr(a
, '__cmp__'):
1907 return # some types don't have a __cmp__ any more (so the
1908 # test doesn't make sense any more), or maybe they
1909 # never had a __cmp__ at all, e.g. in PyPy
1911 a
.__class
__.__cmp
__(a
, b
)
1915 self
.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1918 unsafecmp(u
"123", "123")
1919 unsafecmp("123", u
"123")
1925 @test_support.impl_detail("custom logic for printing to real file objects")
1926 def test_recursions_1(self
):
1927 # Testing recursion checks ...
1929 def __new__(cls
, letter
):
1931 return str.__new
__(cls
)
1932 return str.__new
__(cls
, letter
)
1937 # sys.stdout needs to be the original to trigger the recursion bug
1938 test_stdout
= sys
.stdout
1939 sys
.stdout
= test_support
.get_original_stdout()
1941 # nothing should actually be printed, this should raise an exception
1943 except RuntimeError:
1946 self
.fail("expected a RuntimeError for print recursion")
1948 sys
.stdout
= test_stdout
1950 def test_recursions_2(self
):
1954 A
.__mul
__ = types
.MethodType(lambda self
, x
: self
* x
, None, A
)
1957 except RuntimeError:
1960 self
.fail("expected a RuntimeError")
1962 def test_weakrefs(self
):
1963 # Testing weak references...
1969 self
.assertEqual(r(), c
)
1971 test_support
.gc_collect()
1972 self
.assertEqual(r(), None)
1974 class NoWeak(object):
1979 except TypeError, msg
:
1980 self
.assertTrue(str(msg
).find("weak reference") >= 0)
1982 self
.fail("weakref.ref(no) should be illegal")
1984 __slots__
= ['foo', '__weakref__']
1986 r
= weakref
.ref(yes
)
1987 self
.assertEqual(r(), yes
)
1989 test_support
.gc_collect()
1990 self
.assertEqual(r(), None)
1993 def test_properties(self
):
1994 # Testing property...
1998 def setx(self
, value
):
2002 x
= property(getx
, setx
, delx
, doc
="I'm the x property.")
2004 self
.assertFalse(hasattr(a
, "x"))
2006 self
.assertEqual(a
._C
__x
, 42)
2007 self
.assertEqual(a
.x
, 42)
2009 self
.assertFalse(hasattr(a
, "x"))
2010 self
.assertFalse(hasattr(a
, "_C__x"))
2012 self
.assertEqual(C
.x
.__get
__(a
), 100)
2014 self
.assertFalse(hasattr(a
, "x"))
2016 raw
= C
.__dict
__['x']
2017 self
.assertIsInstance(raw
, property)
2020 self
.assertIn("__doc__", attrs
)
2021 self
.assertIn("fget", attrs
)
2022 self
.assertIn("fset", attrs
)
2023 self
.assertIn("fdel", attrs
)
2025 self
.assertEqual(raw
.__doc
__, "I'm the x property.")
2026 self
.assertTrue(raw
.fget
is C
.__dict
__['getx'])
2027 self
.assertTrue(raw
.fset
is C
.__dict
__['setx'])
2028 self
.assertTrue(raw
.fdel
is C
.__dict
__['delx'])
2030 for attr
in "__doc__", "fget", "fset", "fdel":
2032 setattr(raw
, attr
, 42)
2033 except TypeError, msg
:
2034 if str(msg
).find('readonly') < 0:
2035 self
.fail("when setting readonly attr %r on a property, "
2036 "got unexpected TypeError msg %r" % (attr
, str(msg
)))
2038 self
.fail("expected TypeError from trying to set readonly %r "
2039 "attr on a property" % attr
)
2042 __getitem__
= property(lambda s
: 1/0)
2048 except ZeroDivisionError:
2051 self
.fail("expected ZeroDivisionError from bad property")
2053 @unittest.skipIf(sys
.flags
.optimize
>= 2,
2054 "Docstrings are omitted with -O2 and above")
2055 def test_properties_doc_attrib(self
):
2060 def setter(self_
, value
):
2063 prop
= property(getter
)
2064 self
.assertEqual(prop
.__doc
__, "getter method")
2065 prop2
= property(fset
=setter
)
2066 self
.assertEqual(prop2
.__doc__
, None)
2068 def test_testcapi_no_segfault(self
):
2069 # this segfaulted in 2.5b2
2076 p
= property(_testcapi
.test_with_docstring
)
2078 def test_properties_plus(self
):
2080 foo
= property(doc
="hello")
2085 def foo(self
, value
):
2086 self
._foo
= abs(value
)
2091 self
.assertEqual(C
.foo
.__doc
__, "hello")
2092 self
.assertFalse(hasattr(c
, "foo"))
2094 self
.assertTrue(hasattr(c
, '_foo'))
2095 self
.assertEqual(c
._foo
, 42)
2096 self
.assertEqual(c
.foo
, 42)
2098 self
.assertFalse(hasattr(c
, '_foo'))
2099 self
.assertFalse(hasattr(c
, "foo"))
2106 except AttributeError:
2110 self
.assertEqual(d
.foo
, 24)
2119 def foo(self
, value
):
2122 def foo(self
, value
):
2123 self
._foo
= abs(value
)
2125 def foo(self
, value
=None):
2130 self
.assertEqual(e
.foo
, 42)
2138 def foo(self
, value
):
2139 self
._foo
= max(0, value
)
2142 self
.assertEqual(f
.foo
, 0)
2145 def test_dict_constructors(self
):
2146 # Testing dict constructor ...
2148 self
.assertEqual(d
, {})
2150 self
.assertEqual(d
, {})
2151 d
= dict({1: 2, 'a': 'b'})
2152 self
.assertEqual(d
, {1: 2, 'a': 'b'})
2153 self
.assertEqual(d
, dict(d
.items()))
2154 self
.assertEqual(d
, dict(d
.iteritems()))
2155 d
= dict({'one':1, 'two':2})
2156 self
.assertEqual(d
, dict(one
=1, two
=2))
2157 self
.assertEqual(d
, dict(**d
))
2158 self
.assertEqual(d
, dict({"one": 1}, two
=2))
2159 self
.assertEqual(d
, dict([("two", 2)], one
=1))
2160 self
.assertEqual(d
, dict([("one", 100), ("two", 200)], **d
))
2161 self
.assertEqual(d
, dict(**d
))
2163 for badarg
in 0, 0L, 0j
, "0", [0], (0,):
2170 # It's a sequence, and its elements are also sequences (gotta
2171 # love strings <wink>), but they aren't of length 2, so this
2172 # one seemed better as a ValueError than a TypeError.
2175 self
.fail("no TypeError from dict(%r)" % badarg
)
2177 self
.fail("no TypeError from dict(%r)" % badarg
)
2184 self
.fail("no TypeError from dict({}, {})")
2187 # Lacks a .keys() method; will be added later.
2188 dict = {1:2, 3:4, 'a':1j
}
2195 self
.fail("no TypeError from dict(incomplete mapping)")
2197 Mapping
.keys
= lambda self
: self
.dict.keys()
2198 Mapping
.__getitem
__ = lambda self
, i
: self
.dict[i
]
2200 self
.assertEqual(d
, Mapping
.dict)
2202 # Init from sequence of iterable objects, each producing a 2-sequence.
2203 class AddressBookEntry
:
2204 def __init__(self
, first
, last
):
2208 return iter([self
.first
, self
.last
])
2210 d
= dict([AddressBookEntry('Tim', 'Warsaw'),
2211 AddressBookEntry('Barry', 'Peters'),
2212 AddressBookEntry('Tim', 'Peters'),
2213 AddressBookEntry('Barry', 'Warsaw')])
2214 self
.assertEqual(d
, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2216 d
= dict(zip(range(4), range(1, 5)))
2217 self
.assertEqual(d
, dict([(i
, i
+1) for i
in range(4)]))
2219 # Bad sequence lengths.
2220 for bad
in [('tooshort',)], [('too', 'long', 'by 1')]:
2226 self
.fail("no ValueError from dict(%r)" % bad
)
2231 self
.assertEqual(dir(), ['junk', 'self'])
2234 # Just make sure these don't blow up!
2235 for arg
in 2, 2L, 2j
, 2e0
, [2], "2", u
"2", (2,), {2:2}, type, self
.test_dir
:
2238 # Try classic classes.
2241 def Cmethod(self
): pass
2243 cstuff
= ['Cdata', 'Cmethod', '__doc__', '__module__']
2244 self
.assertEqual(dir(C
), cstuff
)
2245 self
.assertIn('im_self', dir(C
.Cmethod
))
2247 c
= C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2248 self
.assertEqual(dir(c
), cstuff
)
2251 c
.cmethod
= lambda self
: 0
2252 self
.assertEqual(dir(c
), cstuff
+ ['cdata', 'cmethod'])
2253 self
.assertIn('im_self', dir(c
.Cmethod
))
2257 def Amethod(self
): pass
2259 astuff
= ['Adata', 'Amethod'] + cstuff
2260 self
.assertEqual(dir(A
), astuff
)
2261 self
.assertIn('im_self', dir(A
.Amethod
))
2263 self
.assertEqual(dir(a
), astuff
)
2264 self
.assertIn('im_self', dir(a
.Amethod
))
2266 a
.amethod
= lambda self
: 3
2267 self
.assertEqual(dir(a
), astuff
+ ['adata', 'amethod'])
2269 # The same, but with new-style classes. Since these have object as a
2270 # base class, a lot more gets sucked in.
2271 def interesting(strings
):
2272 return [s
for s
in strings
if not s
.startswith('_')]
2276 def Cmethod(self
): pass
2278 cstuff
= ['Cdata', 'Cmethod']
2279 self
.assertEqual(interesting(dir(C
)), cstuff
)
2282 self
.assertEqual(interesting(dir(c
)), cstuff
)
2283 self
.assertIn('im_self', dir(C
.Cmethod
))
2286 c
.cmethod
= lambda self
: 0
2287 self
.assertEqual(interesting(dir(c
)), cstuff
+ ['cdata', 'cmethod'])
2288 self
.assertIn('im_self', dir(c
.Cmethod
))
2292 def Amethod(self
): pass
2294 astuff
= ['Adata', 'Amethod'] + cstuff
2295 self
.assertEqual(interesting(dir(A
)), astuff
)
2296 self
.assertIn('im_self', dir(A
.Amethod
))
2298 self
.assertEqual(interesting(dir(a
)), astuff
)
2300 a
.amethod
= lambda self
: 3
2301 self
.assertEqual(interesting(dir(a
)), astuff
+ ['adata', 'amethod'])
2302 self
.assertIn('im_self', dir(a
.Amethod
))
2304 # Try a module subclass.
2310 names
= [x
for x
in dir(minstance
) if x
not in ["__name__", "__doc__"]]
2311 self
.assertEqual(names
, ['a', 'b'])
2315 return "Not a dict!"
2316 __dict__
= property(getdict
)
2318 m2instance
= M2("m2")
2321 self
.assertEqual(m2instance
.__dict
__, "Not a dict!")
2327 # Two essentially featureless objects, just inheriting stuff from
2329 self
.assertEqual(dir(NotImplemented), dir(Ellipsis))
2330 if test_support
.check_impl_detail():
2331 # None differs in PyPy: it has a __nonzero__
2332 self
.assertEqual(dir(None), dir(Ellipsis))
2334 # Nasty test case for proxied objects
2335 class Wrapper(object):
2336 def __init__(self
, obj
):
2339 return "Wrapper(%s)" % repr(self
.__obj
)
2340 def __getitem__(self
, key
):
2341 return Wrapper(self
.__obj
[key
])
2343 return len(self
.__obj
)
2344 def __getattr__(self
, name
):
2345 return Wrapper(getattr(self
.__obj
, name
))
2348 def __getclass(self
):
2349 return Wrapper(type(self
))
2350 __class__
= property(__getclass
)
2352 dir(C()) # This used to segfault
2354 def test_supers(self
):
2361 self
.assertEqual(A().meth(1), "A(1)")
2365 self
.__super
= super(B
, self
)
2367 return "B(%r)" % a
+ self
.__super
.meth(a
)
2369 self
.assertEqual(B().meth(2), "B(2)A(2)")
2373 return "C(%r)" % a
+ self
.__super
.meth(a
)
2374 C
._C
__super
= super(C
)
2376 self
.assertEqual(C().meth(3), "C(3)A(3)")
2380 return "D(%r)" % a
+ super(D
, self
).meth(a
)
2382 self
.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2384 # Test for subclassing super
2386 class mysuper(super):
2387 def __init__(self
, *args
):
2388 return super(mysuper
, self
).__init
__(*args
)
2392 return "E(%r)" % a
+ mysuper(E
, self
).meth(a
)
2394 self
.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2398 s
= self
.__super
# == mysuper(F, self)
2399 return "F(%r)[%s]" % (a
, s
.__class
__.__name
__) + s
.meth(a
)
2400 F
._F
__super
= mysuper(F
)
2402 self
.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2404 # Make sure certain errors are raised
2411 self
.fail("shouldn't allow super(D, 42)")
2418 self
.fail("shouldn't allow super(D, C())")
2421 super(D
).__get
__(12)
2425 self
.fail("shouldn't allow super(D).__get__(12)")
2428 super(D
).__get
__(C())
2432 self
.fail("shouldn't allow super(D).__get__(C())")
2434 # Make sure data descriptors can be overridden and accessed via super
2435 # (new feature in Python 2.3)
2437 class DDbase(object):
2438 def getx(self
): return 42
2441 class DDsub(DDbase
):
2442 def getx(self
): return "hello"
2446 self
.assertEqual(dd
.x
, "hello")
2447 self
.assertEqual(super(DDsub
, dd
).x
, 42)
2449 # Ensure that super() lookup of descriptor from classmethod
2450 # works (SF ID# 743627)
2453 aProp
= property(lambda self
: "foo")
2458 return super(Sub
,klass
).aProp
2460 self
.assertEqual(Sub
.test(), Base
.aProp
)
2462 # Verify that super() doesn't allow keyword args
2468 self
.assertEqual("super shouldn't accept keyword args")
2470 def test_basic_inheritance(self
):
2471 # Testing inheritance from basic types...
2476 def __add__(self
, other
):
2477 return hexint(int.__add
__(self
, other
))
2478 # (Note that overriding __radd__ doesn't work,
2479 # because the int type gets first dibs.)
2480 self
.assertEqual(repr(hexint(7) + 9), "0x10")
2481 self
.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2483 self
.assertEqual(a
, 12345)
2484 self
.assertEqual(int(a
), 12345)
2485 self
.assertTrue(int(a
).__class
__ is int)
2486 self
.assertEqual(hash(a
), hash(12345))
2487 self
.assertTrue((+a
).__class
__ is int)
2488 self
.assertTrue((a
>> 0).__class
__ is int)
2489 self
.assertTrue((a
<< 0).__class
__ is int)
2490 self
.assertTrue((hexint(0) << 12).__class
__ is int)
2491 self
.assertTrue((hexint(0) >> 12).__class
__ is int)
2493 class octlong(long):
2500 def __add__(self
, other
):
2501 return self
.__class
__(super(octlong
, self
).__add
__(other
))
2503 self
.assertEqual(str(octlong(3) + 5), "010")
2504 # (Note that overriding __radd__ here only seems to work
2505 # because the example uses a short int left argument.)
2506 self
.assertEqual(str(5 + octlong(3000)), "05675")
2508 self
.assertEqual(a
, 12345L)
2509 self
.assertEqual(long(a
), 12345L)
2510 self
.assertEqual(hash(a
), hash(12345L))
2511 self
.assertTrue(long(a
).__class
__ is long)
2512 self
.assertTrue((+a
).__class
__ is long)
2513 self
.assertTrue((-a
).__class
__ is long)
2514 self
.assertTrue((-octlong(0)).__class
__ is long)
2515 self
.assertTrue((a
>> 0).__class
__ is long)
2516 self
.assertTrue((a
<< 0).__class
__ is long)
2517 self
.assertTrue((a
- 0).__class
__ is long)
2518 self
.assertTrue((a
* 1).__class
__ is long)
2519 self
.assertTrue((a
** 1).__class
__ is long)
2520 self
.assertTrue((a
// 1).__class
__ is long)
2521 self
.assertTrue((1 * a
).__class
__ is long)
2522 self
.assertTrue((a |
0).__class
__ is long)
2523 self
.assertTrue((a ^
0).__class
__ is long)
2524 self
.assertTrue((a
& -1L).__class
__ is long)
2525 self
.assertTrue((octlong(0) << 12).__class
__ is long)
2526 self
.assertTrue((octlong(0) >> 12).__class
__ is long)
2527 self
.assertTrue(abs(octlong(0)).__class
__ is long)
2529 # Because octlong overrides __add__, we can't check the absence of +0
2530 # optimizations using octlong.
2531 class longclone(long):
2534 self
.assertTrue((a
+ 0).__class
__ is long)
2535 self
.assertTrue((0 + a
).__class
__ is long)
2537 # Check that negative clones don't segfault
2539 self
.assertEqual(a
.__dict
__, {})
2540 self
.assertEqual(long(a
), -1) # self.assertTrue PyNumber_Long() copies the sign bit
2542 class precfloat(float):
2543 __slots__
= ['prec']
2544 def __init__(self
, value
=0.0, prec
=12):
2545 self
.prec
= int(prec
)
2547 return "%.*g" % (self
.prec
, self
)
2548 self
.assertEqual(repr(precfloat(1.1)), "1.1")
2549 a
= precfloat(12345)
2550 self
.assertEqual(a
, 12345.0)
2551 self
.assertEqual(float(a
), 12345.0)
2552 self
.assertTrue(float(a
).__class
__ is float)
2553 self
.assertEqual(hash(a
), hash(12345.0))
2554 self
.assertTrue((+a
).__class
__ is float)
2556 class madcomplex(complex):
2558 return "%.17gj%+.17g" % (self
.imag
, self
.real
)
2559 a
= madcomplex(-3, 4)
2560 self
.assertEqual(repr(a
), "4j-3")
2561 base
= complex(-3, 4)
2562 self
.assertEqual(base
.__class
__, complex)
2563 self
.assertEqual(a
, base
)
2564 self
.assertEqual(complex(a
), base
)
2565 self
.assertEqual(complex(a
).__class
__, complex)
2566 a
= madcomplex(a
) # just trying another form of the constructor
2567 self
.assertEqual(repr(a
), "4j-3")
2568 self
.assertEqual(a
, base
)
2569 self
.assertEqual(complex(a
), base
)
2570 self
.assertEqual(complex(a
).__class
__, complex)
2571 self
.assertEqual(hash(a
), hash(base
))
2572 self
.assertEqual((+a
).__class
__, complex)
2573 self
.assertEqual((a
+ 0).__class
__, complex)
2574 self
.assertEqual(a
+ 0, base
)
2575 self
.assertEqual((a
- 0).__class
__, complex)
2576 self
.assertEqual(a
- 0, base
)
2577 self
.assertEqual((a
* 1).__class
__, complex)
2578 self
.assertEqual(a
* 1, base
)
2579 self
.assertEqual((a
/ 1).__class
__, complex)
2580 self
.assertEqual(a
/ 1, base
)
2582 class madtuple(tuple):
2585 if self
._rev
is not None:
2589 self
._rev
= self
.__class
__(L
)
2591 a
= madtuple((1,2,3,4,5,6,7,8,9,0))
2592 self
.assertEqual(a
, (1,2,3,4,5,6,7,8,9,0))
2593 self
.assertEqual(a
.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2594 self
.assertEqual(a
.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2595 for i
in range(512):
2596 t
= madtuple(range(i
))
2599 self
.assertEqual(v
, t
)
2600 a
= madtuple((1,2,3,4,5))
2601 self
.assertEqual(tuple(a
), (1,2,3,4,5))
2602 self
.assertTrue(tuple(a
).__class
__ is tuple)
2603 self
.assertEqual(hash(a
), hash((1,2,3,4,5)))
2604 self
.assertTrue(a
[:].__class
__ is tuple)
2605 self
.assertTrue((a
* 1).__class
__ is tuple)
2606 self
.assertTrue((a
* 0).__class
__ is tuple)
2607 self
.assertTrue((a
+ ()).__class
__ is tuple)
2609 self
.assertEqual(tuple(a
), ())
2610 self
.assertTrue(tuple(a
).__class
__ is tuple)
2611 self
.assertTrue((a
+ a
).__class
__ is tuple)
2612 self
.assertTrue((a
* 0).__class
__ is tuple)
2613 self
.assertTrue((a
* 1).__class
__ is tuple)
2614 self
.assertTrue((a
* 2).__class
__ is tuple)
2615 self
.assertTrue(a
[:].__class
__ is tuple)
2617 class madstring(str):
2620 if self
._rev
is not None:
2624 self
._rev
= self
.__class
__("".join(L
))
2626 s
= madstring("abcdefghijklmnopqrstuvwxyz")
2627 self
.assertEqual(s
, "abcdefghijklmnopqrstuvwxyz")
2628 self
.assertEqual(s
.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2629 self
.assertEqual(s
.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2630 for i
in range(256):
2631 s
= madstring("".join(map(chr, range(i
))))
2634 self
.assertEqual(u
, s
)
2635 s
= madstring("12345")
2636 self
.assertEqual(str(s
), "12345")
2637 self
.assertTrue(str(s
).__class
__ is str)
2641 self
.assertEqual(s
, base
)
2642 self
.assertEqual(str(s
), base
)
2643 self
.assertTrue(str(s
).__class
__ is str)
2644 self
.assertEqual(hash(s
), hash(base
))
2645 self
.assertEqual({s
: 1}[base
], 1)
2646 self
.assertEqual({base
: 1}[s
], 1)
2647 self
.assertTrue((s
+ "").__class
__ is str)
2648 self
.assertEqual(s
+ "", base
)
2649 self
.assertTrue(("" + s
).__class
__ is str)
2650 self
.assertEqual("" + s
, base
)
2651 self
.assertTrue((s
* 0).__class
__ is str)
2652 self
.assertEqual(s
* 0, "")
2653 self
.assertTrue((s
* 1).__class
__ is str)
2654 self
.assertEqual(s
* 1, base
)
2655 self
.assertTrue((s
* 2).__class
__ is str)
2656 self
.assertEqual(s
* 2, base
+ base
)
2657 self
.assertTrue(s
[:].__class
__ is str)
2658 self
.assertEqual(s
[:], base
)
2659 self
.assertTrue(s
[0:0].__class
__ is str)
2660 self
.assertEqual(s
[0:0], "")
2661 self
.assertTrue(s
.strip().__class
__ is str)
2662 self
.assertEqual(s
.strip(), base
)
2663 self
.assertTrue(s
.lstrip().__class
__ is str)
2664 self
.assertEqual(s
.lstrip(), base
)
2665 self
.assertTrue(s
.rstrip().__class
__ is str)
2666 self
.assertEqual(s
.rstrip(), base
)
2667 identitytab
= ''.join([chr(i
) for i
in range(256)])
2668 self
.assertTrue(s
.translate(identitytab
).__class
__ is str)
2669 self
.assertEqual(s
.translate(identitytab
), base
)
2670 self
.assertTrue(s
.translate(identitytab
, "x").__class
__ is str)
2671 self
.assertEqual(s
.translate(identitytab
, "x"), base
)
2672 self
.assertEqual(s
.translate(identitytab
, "\x00"), "")
2673 self
.assertTrue(s
.replace("x", "x").__class
__ is str)
2674 self
.assertEqual(s
.replace("x", "x"), base
)
2675 self
.assertTrue(s
.ljust(len(s
)).__class
__ is str)
2676 self
.assertEqual(s
.ljust(len(s
)), base
)
2677 self
.assertTrue(s
.rjust(len(s
)).__class
__ is str)
2678 self
.assertEqual(s
.rjust(len(s
)), base
)
2679 self
.assertTrue(s
.center(len(s
)).__class
__ is str)
2680 self
.assertEqual(s
.center(len(s
)), base
)
2681 self
.assertTrue(s
.lower().__class
__ is str)
2682 self
.assertEqual(s
.lower(), base
)
2684 class madunicode(unicode):
2687 if self
._rev
is not None:
2691 self
._rev
= self
.__class
__(u
"".join(L
))
2693 u
= madunicode("ABCDEF")
2694 self
.assertEqual(u
, u
"ABCDEF")
2695 self
.assertEqual(u
.rev(), madunicode(u
"FEDCBA"))
2696 self
.assertEqual(u
.rev().rev(), madunicode(u
"ABCDEF"))
2698 u
= madunicode(base
)
2699 self
.assertEqual(unicode(u
), base
)
2700 self
.assertTrue(unicode(u
).__class
__ is unicode)
2701 self
.assertEqual(hash(u
), hash(base
))
2702 self
.assertEqual({u
: 1}[base
], 1)
2703 self
.assertEqual({base
: 1}[u
], 1)
2704 self
.assertTrue(u
.strip().__class
__ is unicode)
2705 self
.assertEqual(u
.strip(), base
)
2706 self
.assertTrue(u
.lstrip().__class
__ is unicode)
2707 self
.assertEqual(u
.lstrip(), base
)
2708 self
.assertTrue(u
.rstrip().__class
__ is unicode)
2709 self
.assertEqual(u
.rstrip(), base
)
2710 self
.assertTrue(u
.replace(u
"x", u
"x").__class
__ is unicode)
2711 self
.assertEqual(u
.replace(u
"x", u
"x"), base
)
2712 self
.assertTrue(u
.replace(u
"xy", u
"xy").__class
__ is unicode)
2713 self
.assertEqual(u
.replace(u
"xy", u
"xy"), base
)
2714 self
.assertTrue(u
.center(len(u
)).__class
__ is unicode)
2715 self
.assertEqual(u
.center(len(u
)), base
)
2716 self
.assertTrue(u
.ljust(len(u
)).__class
__ is unicode)
2717 self
.assertEqual(u
.ljust(len(u
)), base
)
2718 self
.assertTrue(u
.rjust(len(u
)).__class
__ is unicode)
2719 self
.assertEqual(u
.rjust(len(u
)), base
)
2720 self
.assertTrue(u
.lower().__class
__ is unicode)
2721 self
.assertEqual(u
.lower(), base
)
2722 self
.assertTrue(u
.upper().__class
__ is unicode)
2723 self
.assertEqual(u
.upper(), base
)
2724 self
.assertTrue(u
.capitalize().__class
__ is unicode)
2725 self
.assertEqual(u
.capitalize(), base
)
2726 self
.assertTrue(u
.title().__class
__ is unicode)
2727 self
.assertEqual(u
.title(), base
)
2728 self
.assertTrue((u
+ u
"").__class
__ is unicode)
2729 self
.assertEqual(u
+ u
"", base
)
2730 self
.assertTrue((u
"" + u
).__class
__ is unicode)
2731 self
.assertEqual(u
"" + u
, base
)
2732 self
.assertTrue((u
* 0).__class
__ is unicode)
2733 self
.assertEqual(u
* 0, u
"")
2734 self
.assertTrue((u
* 1).__class
__ is unicode)
2735 self
.assertEqual(u
* 1, base
)
2736 self
.assertTrue((u
* 2).__class
__ is unicode)
2737 self
.assertEqual(u
* 2, base
+ base
)
2738 self
.assertTrue(u
[:].__class
__ is unicode)
2739 self
.assertEqual(u
[:], base
)
2740 self
.assertTrue(u
[0:0].__class
__ is unicode)
2741 self
.assertEqual(u
[0:0], u
"")
2743 class sublist(list):
2745 a
= sublist(range(5))
2746 self
.assertEqual(a
, range(5))
2748 self
.assertEqual(a
, range(5) + ["hello"])
2750 self
.assertEqual(a
, range(6))
2751 a
.extend(range(6, 20))
2752 self
.assertEqual(a
, range(20))
2754 self
.assertEqual(a
, range(15))
2756 self
.assertEqual(len(a
), 10)
2757 self
.assertEqual(a
, range(10))
2758 self
.assertEqual(list(a
), range(10))
2759 self
.assertEqual(a
[0], 0)
2760 self
.assertEqual(a
[9], 9)
2761 self
.assertEqual(a
[-10], 0)
2762 self
.assertEqual(a
[-1], 9)
2763 self
.assertEqual(a
[:5], range(5))
2765 class CountedInput(file):
2766 """Counts lines read by self.readline().
2768 self.lineno is the 0-based ordinal of the last line read, up to
2769 a maximum of one greater than the number of lines in the file.
2771 self.ateof is true if and only if the final "" line has been read,
2772 at which point self.lineno stops incrementing, and further calls
2773 to readline() continue to return "".
2781 s
= file.readline(self
)
2782 # Next line works too.
2783 # s = super(CountedInput, self).readline()
2789 f
= file(name
=test_support
.TESTFN
, mode
='w')
2790 lines
= ['a\n', 'b\n', 'c\n']
2794 f
= CountedInput(test_support
.TESTFN
)
2795 for (i
, expected
) in zip(range(1, 5) + [4], lines
+ 2 * [""]):
2797 self
.assertEqual(expected
, got
)
2798 self
.assertEqual(f
.lineno
, i
)
2799 self
.assertEqual(f
.ateof
, (i
> len(lines
)))
2806 test_support
.unlink(test_support
.TESTFN
)
2808 def test_keywords(self
):
2809 # Testing keyword args to basic type constructors ...
2810 self
.assertEqual(int(x
=1), 1)
2811 self
.assertEqual(float(x
=2), 2.0)
2812 self
.assertEqual(long(x
=3), 3L)
2813 self
.assertEqual(complex(imag
=42, real
=666), complex(666, 42))
2814 self
.assertEqual(str(object=500), '500')
2815 self
.assertEqual(unicode(string
='abc', errors
='strict'), u
'abc')
2816 self
.assertEqual(tuple(sequence
=range(3)), (0, 1, 2))
2817 self
.assertEqual(list(sequence
=(0, 1, 2)), range(3))
2818 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2820 for constructor
in (int, float, long, complex, str, unicode,
2823 constructor(bogus_keyword_arg
=1)
2827 self
.fail("expected TypeError from bogus keyword argument to %r"
2830 def test_str_subclass_as_dict_key(self
):
2831 # Testing a str subclass used as dict key ..
2834 """Sublcass of str that computes __eq__ case-insensitively.
2836 Also computes a hash code of the string in canonical form.
2839 def __init__(self
, value
):
2840 self
.canonical
= value
.lower()
2841 self
.hashcode
= hash(self
.canonical
)
2843 def __eq__(self
, other
):
2844 if not isinstance(other
, cistr
):
2845 other
= cistr(other
)
2846 return self
.canonical
== other
.canonical
2849 return self
.hashcode
2851 self
.assertEqual(cistr('ABC'), 'abc')
2852 self
.assertEqual('aBc', cistr('ABC'))
2853 self
.assertEqual(str(cistr('ABC')), 'ABC')
2855 d
= {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2856 self
.assertEqual(d
[cistr('one')], 1)
2857 self
.assertEqual(d
[cistr('tWo')], 2)
2858 self
.assertEqual(d
[cistr('THrEE')], 3)
2859 self
.assertIn(cistr('ONe'), d
)
2860 self
.assertEqual(d
.get(cistr('thrEE')), 3)
2862 def test_classic_comparisons(self
):
2863 # Testing classic comparisons...
2867 for base
in (classic
, int, object):
2869 def __init__(self
, value
):
2870 self
.value
= int(value
)
2871 def __cmp__(self
, other
):
2872 if isinstance(other
, C
):
2873 return cmp(self
.value
, other
.value
)
2874 if isinstance(other
, int) or isinstance(other
, long):
2875 return cmp(self
.value
, other
)
2876 return NotImplemented
2877 __hash__
= None # Silence Py3k warning
2882 self
.assertEqual(c1
, 1)
2883 c
= {1: c1
, 2: c2
, 3: c3
}
2886 self
.assertTrue(cmp(c
[x
], c
[y
]) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2887 for op
in "<", "<=", "==", "!=", ">", ">=":
2888 self
.assertTrue(eval("c[x] %s c[y]" % op
) == eval("x %s y" % op
),
2889 "x=%d, y=%d" % (x
, y
))
2890 self
.assertTrue(cmp(c
[x
], y
) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2891 self
.assertTrue(cmp(x
, c
[y
]) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2893 def test_rich_comparisons(self
):
2894 # Testing rich comparisons...
2898 self
.assertEqual(z
, 1+0j
)
2899 self
.assertEqual(1+0j
, z
)
2901 def __eq__(self
, other
):
2903 return abs(self
- other
) <= 1e-6
2905 return NotImplemented
2906 __hash__
= None # Silence Py3k warning
2908 self
.assertEqual(zz
, 1+0j
)
2909 self
.assertEqual(1+0j
, zz
)
2913 for base
in (classic
, int, object, list):
2915 def __init__(self
, value
):
2916 self
.value
= int(value
)
2917 def __cmp__(self_
, other
):
2918 self
.fail("shouldn't call __cmp__")
2919 __hash__
= None # Silence Py3k warning
2920 def __eq__(self
, other
):
2921 if isinstance(other
, C
):
2922 return self
.value
== other
.value
2923 if isinstance(other
, int) or isinstance(other
, long):
2924 return self
.value
== other
2925 return NotImplemented
2926 def __ne__(self
, other
):
2927 if isinstance(other
, C
):
2928 return self
.value
!= other
.value
2929 if isinstance(other
, int) or isinstance(other
, long):
2930 return self
.value
!= other
2931 return NotImplemented
2932 def __lt__(self
, other
):
2933 if isinstance(other
, C
):
2934 return self
.value
< other
.value
2935 if isinstance(other
, int) or isinstance(other
, long):
2936 return self
.value
< other
2937 return NotImplemented
2938 def __le__(self
, other
):
2939 if isinstance(other
, C
):
2940 return self
.value
<= other
.value
2941 if isinstance(other
, int) or isinstance(other
, long):
2942 return self
.value
<= other
2943 return NotImplemented
2944 def __gt__(self
, other
):
2945 if isinstance(other
, C
):
2946 return self
.value
> other
.value
2947 if isinstance(other
, int) or isinstance(other
, long):
2948 return self
.value
> other
2949 return NotImplemented
2950 def __ge__(self
, other
):
2951 if isinstance(other
, C
):
2952 return self
.value
>= other
.value
2953 if isinstance(other
, int) or isinstance(other
, long):
2954 return self
.value
>= other
2955 return NotImplemented
2959 self
.assertEqual(c1
, 1)
2960 c
= {1: c1
, 2: c2
, 3: c3
}
2963 for op
in "<", "<=", "==", "!=", ">", ">=":
2964 self
.assertTrue(eval("c[x] %s c[y]" % op
) == eval("x %s y" % op
),
2965 "x=%d, y=%d" % (x
, y
))
2966 self
.assertTrue(eval("c[x] %s y" % op
) == eval("x %s y" % op
),
2967 "x=%d, y=%d" % (x
, y
))
2968 self
.assertTrue(eval("x %s c[y]" % op
) == eval("x %s y" % op
),
2969 "x=%d, y=%d" % (x
, y
))
2971 def test_coercions(self
):
2972 # Testing coercions...
2981 class F(float): pass
2988 class C(complex): pass
2998 def test_descrdoc(self
):
2999 # Testing descriptor doc strings...
3000 def check(descr
, what
):
3001 self
.assertEqual(descr
.__doc
__, what
)
3002 check(file.closed
, "True if the file is closed") # getset descriptor
3003 check(file.name
, "file name") # member descriptor
3005 def test_doc_descriptor(self
):
3006 # Testing __doc__ descriptor...
3008 class DocDescr(object):
3009 def __get__(self
, object, otype
):
3011 object = object.__class
__.__name
__ + ' instance'
3013 otype
= otype
.__name
__
3014 return 'object=%s; type=%s' % (object, otype
)
3016 __doc__
= DocDescr()
3017 class NewClass(object):
3018 __doc__
= DocDescr()
3019 self
.assertEqual(OldClass
.__doc
__, 'object=None; type=OldClass')
3020 self
.assertEqual(OldClass().__doc
__, 'object=OldClass instance; type=OldClass')
3021 self
.assertEqual(NewClass
.__doc
__, 'object=None; type=NewClass')
3022 self
.assertEqual(NewClass().__doc
__, 'object=NewClass instance; type=NewClass')
3024 def test_set_class(self
):
3025 # Testing __class__ assignment...
3026 class C(object): pass
3027 class D(object): pass
3028 class E(object): pass
3030 for cls
in C
, D
, E
, F
:
3031 for cls2
in C
, D
, E
, F
:
3034 self
.assertTrue(x
.__class
__ is cls2
)
3036 self
.assertTrue(x
.__class
__ is cls
)
3043 self
.fail("shouldn't allow %r.__class__ = %r" % (x
, C
))
3045 delattr(x
, "__class__")
3046 except (TypeError, AttributeError):
3049 self
.fail("shouldn't allow del %r.__class__" % x
)
3054 cant(object(), list)
3055 cant(list(), object)
3056 class Int(int): __slots__
= []
3066 __slots__
= ["a", "b"]
3068 __slots__
= ["b", "a"]
3073 __slots__
= ["a", "b"]
3076 __slots__
= [unicode("a"), unicode("b")]
3078 __slots__
= ["c", "b"]
3080 __slots__
= ["a", "b", "d"]
3086 __slots__
= ["__weakref__"]
3088 __slots__
= ["__dict__"]
3092 __slots__
= ["__dict__", "__weakref__"]
3094 for cls
, cls2
in ((G
, H
), (G
, I
), (I
, H
), (Q
, R
), (R
, Q
)):
3098 self
.assertTrue(x
.__class
__ is cls2
,
3099 "assigning %r as __class__ for %r silently failed" % (cls2
, x
))
3100 self
.assertEqual(x
.a
, 1)
3102 self
.assertTrue(x
.__class
__ is cls
,
3103 "assigning %r as __class__ for %r silently failed" % (cls
, x
))
3104 self
.assertEqual(x
.a
, 1)
3105 for cls
in G
, J
, K
, L
, M
, N
, P
, R
, list, Int
:
3106 for cls2
in G
, J
, K
, L
, M
, N
, P
, R
, list, Int
:
3111 # Issue5283: when __class__ changes in __del__, the wrong
3112 # type gets DECREF'd.
3118 l
= [A() for x
in range(100)]
3121 def test_set_dict(self
):
3122 # Testing __dict__ assignment...
3123 class C(object): pass
3125 a
.__dict
__ = {'b': 1}
3126 self
.assertEqual(a
.b
, 1)
3130 except (AttributeError, TypeError):
3133 self
.fail("shouldn't allow %r.__dict__ = %r" % (x
, dict))
3137 del a
.__dict
__ # Deleting __dict__ is allowed
3141 def verify_dict_readonly(x
):
3143 x has to be an instance of a class inheriting from Base.
3148 except (AttributeError, TypeError):
3151 self
.fail("shouldn't allow del %r.__dict__" % x
)
3152 dict_descr
= Base
.__dict
__["__dict__"]
3154 dict_descr
.__set
__(x
, {})
3155 except (AttributeError, TypeError):
3158 self
.fail("dict_descr allowed access to %r's dict" % x
)
3160 # Classes don't allow __dict__ assignment and have readonly dicts
3161 class Meta1(type, Base
):
3163 class Meta2(Base
, type):
3166 __metaclass__
= Meta1
3168 __metaclass__
= Meta2
3170 verify_dict_readonly(cls
)
3171 class_dict
= cls
.__dict
__
3173 class_dict
["spam"] = "eggs"
3177 self
.fail("%r's __dict__ can be modified" % cls
)
3179 # Modules also disallow __dict__ assignment
3180 class Module1(types
.ModuleType
, Base
):
3182 class Module2(Base
, types
.ModuleType
):
3184 for ModuleType
in Module1
, Module2
:
3185 mod
= ModuleType("spam")
3186 verify_dict_readonly(mod
)
3187 mod
.__dict
__["spam"] = "eggs"
3189 # Exception's __dict__ can be replaced, but not deleted
3190 # (at least not any more than regular exception's __dict__ can
3191 # be deleted; on CPython it is not the case, whereas on PyPy they
3192 # can, just like any other new-style instance's __dict__.)
3193 def can_delete_dict(e
):
3196 except (TypeError, AttributeError):
3200 class Exception1(Exception, Base
):
3202 class Exception2(Base
, Exception):
3204 for ExceptionType
in Exception, Exception1
, Exception2
:
3206 e
.__dict
__ = {"a": 1}
3207 self
.assertEqual(e
.a
, 1)
3208 self
.assertEqual(can_delete_dict(e
), can_delete_dict(ValueError()))
3210 def test_pickles(self
):
3211 # Testing pickling and copying new-style classes and objects...
3212 import pickle
, cPickle
3221 def __init__(self
, a
, b
):
3222 super(C
, self
).__init
__()
3226 return "C(%r, %r)" % (self
.a
, self
.b
)
3230 def __new__(cls
, a
, b
):
3231 return super(C1
, cls
).__new
__(cls
)
3232 def __getnewargs__(self
):
3233 return (self
.a
, self
.b
)
3234 def __init__(self
, a
, b
):
3238 return "C1(%r, %r)<%r>" % (self
.a
, self
.b
, list(self
))
3242 def __new__(cls
, a
, b
, val
=0):
3243 return super(C2
, cls
).__new
__(cls
, val
)
3244 def __getnewargs__(self
):
3245 return (self
.a
, self
.b
, int(self
))
3246 def __init__(self
, a
, b
, val
=0):
3250 return "C2(%r, %r)<%r>" % (self
.a
, self
.b
, int(self
))
3254 def __init__(self
, foo
):
3256 def __getstate__(self
):
3258 def __setstate__(self
, foo
):
3261 global C4classic
, C4
3262 class C4classic
: # classic
3264 class C4(C4classic
, object): # mixed inheritance
3267 for p
in pickle
, cPickle
:
3269 for cls
in C
, C1
, C2
:
3270 s
= p
.dumps(cls
, bin
)
3272 self
.assertTrue(cls2
is cls
)
3274 a
= C1(1, 2); a
.append(42); a
.append(24)
3275 b
= C2("hello", "world", 42)
3276 s
= p
.dumps((a
, b
), bin
)
3278 self
.assertEqual(x
.__class
__, a
.__class
__)
3279 self
.assertEqual(sorteditems(x
.__dict
__), sorteditems(a
.__dict
__))
3280 self
.assertEqual(y
.__class
__, b
.__class
__)
3281 self
.assertEqual(sorteditems(y
.__dict
__), sorteditems(b
.__dict
__))
3282 self
.assertEqual(repr(x
), repr(a
))
3283 self
.assertEqual(repr(y
), repr(b
))
3284 # Test for __getstate__ and __setstate__ on new style class
3288 self
.assertEqual(u
.__class
__, v
.__class
__)
3289 self
.assertEqual(u
.foo
, v
.foo
)
3290 # Test for picklability of hybrid class
3295 self
.assertEqual(u
.__class
__, v
.__class
__)
3296 self
.assertEqual(u
.foo
, v
.foo
)
3298 # Testing copy.deepcopy()
3300 for cls
in C
, C1
, C2
:
3301 cls2
= copy
.deepcopy(cls
)
3302 self
.assertTrue(cls2
is cls
)
3304 a
= C1(1, 2); a
.append(42); a
.append(24)
3305 b
= C2("hello", "world", 42)
3306 x
, y
= copy
.deepcopy((a
, b
))
3307 self
.assertEqual(x
.__class
__, a
.__class
__)
3308 self
.assertEqual(sorteditems(x
.__dict
__), sorteditems(a
.__dict
__))
3309 self
.assertEqual(y
.__class
__, b
.__class
__)
3310 self
.assertEqual(sorteditems(y
.__dict
__), sorteditems(b
.__dict
__))
3311 self
.assertEqual(repr(x
), repr(a
))
3312 self
.assertEqual(repr(y
), repr(b
))
3314 def test_pickle_slots(self
):
3315 # Testing pickling of classes with __slots__ ...
3316 import pickle
, cPickle
3317 # Pickling of classes with __slots__ but without __getstate__ should fail
3321 for base
in [object, B
]:
3331 self
.fail("should fail: pickle C instance - %s" % base
)
3337 self
.fail("should fail: cPickle C instance - %s" % base
)
3343 self
.fail("should fail: pickle D instance - %s" % base
)
3349 self
.fail("should fail: cPickle D instance - %s" % base
)
3350 # Give C a nice generic __getstate__ and __setstate__
3353 def __getstate__(self
):
3355 d
= self
.__dict
__.copy()
3356 except AttributeError:
3358 for cls
in self
.__class
__.__mro
__:
3359 for sn
in cls
.__dict
__.get('__slots__', ()):
3361 d
[sn
] = getattr(self
, sn
)
3362 except AttributeError:
3365 def __setstate__(self
, d
):
3366 for k
, v
in d
.items():
3370 # Now it should work
3372 y
= pickle
.loads(pickle
.dumps(x
))
3373 self
.assertEqual(hasattr(y
, 'a'), 0)
3374 y
= cPickle
.loads(cPickle
.dumps(x
))
3375 self
.assertEqual(hasattr(y
, 'a'), 0)
3377 y
= pickle
.loads(pickle
.dumps(x
))
3378 self
.assertEqual(y
.a
, 42)
3379 y
= cPickle
.loads(cPickle
.dumps(x
))
3380 self
.assertEqual(y
.a
, 42)
3384 y
= pickle
.loads(pickle
.dumps(x
))
3385 self
.assertEqual(y
.a
+ y
.b
, 142)
3386 y
= cPickle
.loads(cPickle
.dumps(x
))
3387 self
.assertEqual(y
.a
+ y
.b
, 142)
3388 # A subclass that adds a slot should also work
3394 y
= pickle
.loads(pickle
.dumps(x
))
3395 self
.assertEqual(y
.a
, x
.a
)
3396 self
.assertEqual(y
.b
, x
.b
)
3397 y
= cPickle
.loads(cPickle
.dumps(x
))
3398 self
.assertEqual(y
.a
, x
.a
)
3399 self
.assertEqual(y
.b
, x
.b
)
3401 def test_binary_operator_override(self
):
3402 # Testing overrides of binary operations...
3405 return "I(%r)" % int(self
)
3406 def __add__(self
, other
):
3407 return I(int(self
) + int(other
))
3409 def __pow__(self
, other
, mod
=None):
3411 return I(pow(int(self
), int(other
)))
3413 return I(pow(int(self
), int(other
), int(mod
)))
3414 def __rpow__(self
, other
, mod
=None):
3416 return I(pow(int(other
), int(self
), mod
))
3418 return I(pow(int(other
), int(self
), int(mod
)))
3420 self
.assertEqual(repr(I(1) + I(2)), "I(3)")
3421 self
.assertEqual(repr(I(1) + 2), "I(3)")
3422 self
.assertEqual(repr(1 + I(2)), "I(3)")
3423 self
.assertEqual(repr(I(2) ** I(3)), "I(8)")
3424 self
.assertEqual(repr(2 ** I(3)), "I(8)")
3425 self
.assertEqual(repr(I(2) ** 3), "I(8)")
3426 self
.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3428 def __eq__(self
, other
):
3429 return self
.lower() == other
.lower()
3430 __hash__
= None # Silence Py3k warning
3432 def test_subclass_propagation(self
):
3433 # Testing propagation of slot functions to subclasses...
3443 orig_hash
= hash(d
) # related to id(d) in platform-dependent ways
3444 A
.__hash
__ = lambda self
: 42
3445 self
.assertEqual(hash(d
), 42)
3446 C
.__hash
__ = lambda self
: 314
3447 self
.assertEqual(hash(d
), 314)
3448 B
.__hash
__ = lambda self
: 144
3449 self
.assertEqual(hash(d
), 144)
3450 D
.__hash
__ = lambda self
: 100
3451 self
.assertEqual(hash(d
), 100)
3453 self
.assertRaises(TypeError, hash, d
)
3455 self
.assertEqual(hash(d
), 144)
3457 self
.assertRaises(TypeError, hash, d
)
3459 self
.assertEqual(hash(d
), 314)
3461 self
.assertRaises(TypeError, hash, d
)
3463 self
.assertEqual(hash(d
), 42)
3465 self
.assertRaises(TypeError, hash, d
)
3467 self
.assertEqual(hash(d
), orig_hash
)
3470 self
.assertEqual(d
.foo
, 42)
3471 self
.assertEqual(d
.bar
, 42)
3472 def __getattribute__(self
, name
):
3475 return object.__getattribute
__(self
, name
)
3476 A
.__getattribute
__ = __getattribute__
3477 self
.assertEqual(d
.foo
, 24)
3478 self
.assertEqual(d
.bar
, 42)
3479 def __getattr__(self
, name
):
3480 if name
in ("spam", "foo", "bar"):
3482 raise AttributeError, name
3483 B
.__getattr
__ = __getattr__
3484 self
.assertEqual(d
.spam
, "hello")
3485 self
.assertEqual(d
.foo
, 24)
3486 self
.assertEqual(d
.bar
, 42)
3487 del A
.__getattribute
__
3488 self
.assertEqual(d
.foo
, 42)
3490 self
.assertEqual(d
.foo
, "hello")
3491 self
.assertEqual(d
.bar
, 42)
3495 except AttributeError:
3498 self
.fail("d.foo should be undefined now")
3500 # Test a nasty bug in recurse_down_subclasses()
3506 test_support
.gc_collect()
3507 A
.__setitem
__ = lambda *a
: None # crash
3509 def test_buffer_inheritance(self
):
3510 # Testing that buffer interface is inherited ...
3513 # SF bug [#470040] ParseTuple t# vs subclasses.
3519 # b2a_hex uses the buffer interface to get its argument's value, via
3520 # PyArg_ParseTuple 't#' code.
3521 self
.assertEqual(binascii
.b2a_hex(m
), binascii
.b2a_hex(base
))
3523 # It's not clear that unicode will continue to support the character
3524 # buffer interface, and this test will fail if that's taken away.
3525 class MyUni(unicode):
3529 self
.assertEqual(binascii
.b2a_hex(m
), binascii
.b2a_hex(base
))
3536 self
.fail('subclass of int should not have a buffer interface')
3540 def test_str_of_str_subclass(self
):
3541 # Testing __str__ defined in subclass of str ...
3545 class octetstring(str):
3547 return binascii
.b2a_hex(self
)
3549 return self
+ " repr"
3551 o
= octetstring('A')
3552 self
.assertEqual(type(o
), octetstring
)
3553 self
.assertEqual(type(str(o
)), str)
3554 self
.assertEqual(type(repr(o
)), str)
3555 self
.assertEqual(ord(o
), 0x41)
3556 self
.assertEqual(str(o
), '41')
3557 self
.assertEqual(repr(o
), 'A repr')
3558 self
.assertEqual(o
.__str
__(), '41')
3559 self
.assertEqual(o
.__repr
__(), 'A repr')
3561 capture
= cStringIO
.StringIO()
3562 # Calling str() or not exercises different internal paths.
3564 print >> capture
, str(o
)
3565 self
.assertEqual(capture
.getvalue(), '41\n41\n')
3568 def test_keyword_arguments(self
):
3569 # Testing keyword arguments to __init__, __call__...
3571 self
.assertEqual(f
.__call
__(a
=42), 42)
3573 list.__init
__(a
, sequence
=[0, 1, 2])
3574 self
.assertEqual(a
, [0, 1, 2])
3576 def test_recursive_call(self
):
3577 # Testing recursive __call__() by setting to instance of class...
3584 except RuntimeError:
3587 self
.fail("Recursion limit should have been reached for __call__()")
3589 def test_delete_hook(self
):
3590 # Testing __del__ hook...
3596 self
.assertEqual(log
, [])
3598 test_support
.gc_collect()
3599 self
.assertEqual(log
, [1])
3601 class D(object): pass
3604 except TypeError: pass
3605 else: self
.fail("invalid del() didn't raise TypeError")
3607 def test_hash_inheritance(self
):
3608 # Testing hash of mutable subclasses...
3618 self
.fail("hash() of dict subclass should fail")
3628 self
.fail("hash() of list subclass should fail")
3630 def test_str_operations(self
):
3632 except TypeError: pass
3633 else: self
.fail("'' + 5 doesn't raise TypeError")
3636 except ValueError: pass
3637 else: self
.fail("''.split('') doesn't raise ValueError")
3640 except TypeError: pass
3641 else: self
.fail("''.join([0]) doesn't raise TypeError")
3644 except ValueError: pass
3645 else: self
.fail("''.rindex('5') doesn't raise ValueError")
3648 except TypeError: pass
3649 else: self
.fail("'%(n)s' % None doesn't raise TypeError")
3652 except ValueError: pass
3653 else: self
.fail("'%(n' % {} '' doesn't raise ValueError")
3655 try: '%*s' % ('abc')
3656 except TypeError: pass
3657 else: self
.fail("'%*s' % ('abc') doesn't raise TypeError")
3659 try: '%*.*s' % ('abc', 5)
3660 except TypeError: pass
3661 else: self
.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3664 except TypeError: pass
3665 else: self
.fail("'%s' % (1, 2) doesn't raise TypeError")
3668 except ValueError: pass
3669 else: self
.fail("'%' % None doesn't raise ValueError")
3671 self
.assertEqual('534253'.isdigit(), 1)
3672 self
.assertEqual('534253x'.isdigit(), 0)
3673 self
.assertEqual('%c' % 5, '\x05')
3674 self
.assertEqual('%c' % '5', '5')
3676 def test_deepcopy_recursive(self
):
3677 # Testing deepcopy of recursive objects...
3684 z
= deepcopy(a
) # This blew up before
3686 def test_unintialized_modules(self
):
3687 # Testing uninitialized module objects...
3688 from types
import ModuleType
as M
3691 self
.assertEqual(hasattr(m
, "__name__"), 0)
3692 self
.assertEqual(hasattr(m
, "__file__"), 0)
3693 self
.assertEqual(hasattr(m
, "foo"), 0)
3694 self
.assertFalse(m
.__dict
__) # None or {} are both reasonable answers
3696 self
.assertEqual(m
.__dict
__, {"foo": 1})
3698 def test_funny_new(self
):
3699 # Testing __new__ returning something unexpected...
3701 def __new__(cls
, arg
):
3702 if isinstance(arg
, str): return [1, 2, 3]
3703 elif isinstance(arg
, int): return object.__new
__(D
)
3704 else: return object.__new
__(cls
)
3706 def __init__(self
, arg
):
3708 self
.assertEqual(C("1"), [1, 2, 3])
3709 self
.assertEqual(D("1"), [1, 2, 3])
3711 self
.assertEqual(d
.foo
, None)
3713 self
.assertEqual(isinstance(d
, D
), True)
3714 self
.assertEqual(d
.foo
, 1)
3716 self
.assertEqual(isinstance(d
, D
), True)
3717 self
.assertEqual(d
.foo
, 1)
3719 def test_imul_bug(self
):
3720 # Testing for __imul__ problems...
3723 def __imul__(self
, other
):
3724 return (self
, other
)
3728 self
.assertEqual(y
, (x
, 1.0))
3731 self
.assertEqual(y
, (x
, 2))
3734 self
.assertEqual(y
, (x
, 3L))
3737 self
.assertEqual(y
, (x
, 1L<<100))
3740 self
.assertEqual(y
, (x
, None))
3743 self
.assertEqual(y
, (x
, "foo"))
3745 def test_copy_setstate(self
):
3746 # Testing that copy.*copy() correctly uses __setstate__...
3749 def __init__(self
, foo
=None):
3752 def setfoo(self
, foo
=None):
3756 def __getstate__(self
):
3758 def __setstate__(self_
, lst
):
3759 self
.assertEqual(len(lst
), 1)
3760 self_
.__foo
= self_
.foo
= lst
[0]
3763 self
.assertEqual(a
.foo
, 24)
3764 self
.assertEqual(a
.getfoo(), 42)
3766 self
.assertEqual(b
.foo
, 24)
3767 self
.assertEqual(b
.getfoo(), 24)
3768 b
= copy
.deepcopy(a
)
3769 self
.assertEqual(b
.foo
, 24)
3770 self
.assertEqual(b
.getfoo(), 24)
3772 def test_slices(self
):
3773 # Testing cases with slices and overridden __getitem__ ...
3776 self
.assertEqual("hello"[:4], "hell")
3777 self
.assertEqual("hello"[slice(4)], "hell")
3778 self
.assertEqual(str.__getitem
__("hello", slice(4)), "hell")
3780 def __getitem__(self
, x
):
3781 return str.__getitem
__(self
, x
)
3782 self
.assertEqual(S("hello")[:4], "hell")
3783 self
.assertEqual(S("hello")[slice(4)], "hell")
3784 self
.assertEqual(S("hello").__getitem
__(slice(4)), "hell")
3786 self
.assertEqual((1,2,3)[:2], (1,2))
3787 self
.assertEqual((1,2,3)[slice(2)], (1,2))
3788 self
.assertEqual(tuple.__getitem
__((1,2,3), slice(2)), (1,2))
3790 def __getitem__(self
, x
):
3791 return tuple.__getitem
__(self
, x
)
3792 self
.assertEqual(T((1,2,3))[:2], (1,2))
3793 self
.assertEqual(T((1,2,3))[slice(2)], (1,2))
3794 self
.assertEqual(T((1,2,3)).__getitem
__(slice(2)), (1,2))
3796 self
.assertEqual([1,2,3][:2], [1,2])
3797 self
.assertEqual([1,2,3][slice(2)], [1,2])
3798 self
.assertEqual(list.__getitem
__([1,2,3], slice(2)), [1,2])
3800 def __getitem__(self
, x
):
3801 return list.__getitem
__(self
, x
)
3802 self
.assertEqual(L([1,2,3])[:2], [1,2])
3803 self
.assertEqual(L([1,2,3])[slice(2)], [1,2])
3804 self
.assertEqual(L([1,2,3]).__getitem
__(slice(2)), [1,2])
3805 # Now do lists and __setitem__
3807 a
[slice(1, 3)] = [3,2]
3808 self
.assertEqual(a
, [1,3,2])
3809 a
[slice(0, 2, 1)] = [3,1]
3810 self
.assertEqual(a
, [3,1,2])
3811 a
.__setitem
__(slice(1, 3), [2,1])
3812 self
.assertEqual(a
, [3,2,1])
3813 a
.__setitem
__(slice(0, 2, 1), [2,3])
3814 self
.assertEqual(a
, [2,3,1])
3816 def test_subtype_resurrection(self
):
3817 # Testing resurrection of new-style instance...
3823 # resurrect the instance
3824 C
.container
.append(self
)
3829 # The most interesting thing here is whether this blows up, due to
3830 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3834 # If that didn't blow up, it's also interesting to see whether clearing
3835 # the last container slot works: that will attempt to delete c again,
3836 # which will cause c to get appended back to the container again
3837 # "during" the del. (On non-CPython implementations, however, __del__
3838 # is typically not called again.)
3839 test_support
.gc_collect()
3840 self
.assertEqual(len(C
.container
), 1)
3842 if test_support
.check_impl_detail():
3843 test_support
.gc_collect()
3844 self
.assertEqual(len(C
.container
), 1)
3845 self
.assertEqual(C
.container
[-1].attr
, 42)
3847 # Make c mortal again, so that the test framework with -l doesn't report
3851 def test_slots_trash(self
):
3852 # Testing slot trash...
3853 # Deallocating deeply nested slotted trash caused stack overflows
3854 class trash(object):
3856 def __init__(self
, x
):
3859 for i
in xrange(50000):
3863 def test_slots_multiple_inheritance(self
):
3864 # SF bug 575229, multiple inheritance w/ slots dumps core
3871 if test_support
.check_impl_detail():
3872 self
.assertEqual(C
.__basicsize
__, B
.__basicsize
__)
3873 self
.assertTrue(hasattr(C
, '__dict__'))
3874 self
.assertTrue(hasattr(C
, '__weakref__'))
3877 def test_rmul(self
):
3878 # Testing correct invocation of __rmul__...
3881 def __mul__(self
, other
):
3883 def __rmul__(self
, other
):
3886 self
.assertEqual(a
*2, "mul")
3887 self
.assertEqual(a
*2.2, "mul")
3888 self
.assertEqual(2*a
, "rmul")
3889 self
.assertEqual(2.2*a
, "rmul")
3891 def test_ipow(self
):
3892 # Testing correct invocation of __ipow__...
3895 def __ipow__(self
, other
):
3900 def test_mutable_bases(self
):
3901 # Testing mutable bases...
3903 # stuff that should work:
3907 def __getattribute__(self
, attr
):
3911 return super(C2
, self
).__getattribute
__(attr
)
3922 self
.assertEqual(d
.meth(), 1)
3923 self
.assertEqual(e
.meth(), 1)
3924 self
.assertEqual(d
.a
, 2)
3925 self
.assertEqual(e
.a
, 2)
3926 self
.assertEqual(C2
.__subclasses__(), [D
])
3930 except (TypeError, AttributeError):
3933 self
.fail("shouldn't be able to delete .__bases__")
3937 except TypeError, msg
:
3938 if str(msg
) == "a new-style class can't have only classic bases":
3939 self
.fail("wrong error message for .__bases__ = ()")
3941 self
.fail("shouldn't be able to set .__bases__ to ()")
3948 # actually, we'll have crashed by here...
3949 self
.fail("shouldn't be able to create inheritance cycles")
3952 D
.__bases
__ = (C
, C
)
3956 self
.fail("didn't detect repeated base classes")
3963 self
.fail("shouldn't be able to create inheritance cycles")
3965 # let's throw a classic class into the mix:
3970 D
.__bases
__ = (C
, Classic
)
3972 self
.assertEqual(d
.meth2(), 3)
3973 self
.assertEqual(e
.meth2(), 3)
3976 except AttributeError:
3979 self
.fail("attribute should have vanished")
3982 D
.__bases
__ = (Classic
,)
3986 self
.fail("new-style class must have a new-style base")
3988 def test_builtin_bases(self
):
3989 # Make sure all the builtin types can have their base queried without
3990 # segfaulting. See issue #5787.
3991 builtin_types
= [tp
for tp
in __builtin__
.__dict
__.itervalues()
3992 if isinstance(tp
, type)]
3993 for tp
in builtin_types
:
3994 object.__getattribute
__(tp
, "__bases__")
3995 if tp
is not object:
3996 self
.assertEqual(len(tp
.__bases
__), 1, tp
)
4008 L
.__bases
__ = (dict,)
4012 self
.fail("shouldn't turn list subclass into dict subclass")
4015 list.__bases
__ = (dict,)
4019 self
.fail("shouldn't be able to assign to list.__bases__")
4022 D
.__bases
__ = (C
, list)
4026 assert 0, "best_base calculation found wanting"
4029 def test_mutable_bases_with_failing_mro(self
):
4030 # Testing mutable bases with failing mro...
4031 class WorkOnce(type):
4032 def __new__(self
, name
, bases
, ns
):
4034 return super(WorkOnce
, self
).__new
__(WorkOnce
, name
, bases
, ns
)
4037 raise RuntimeError, "bozo"
4040 return type.mro(self
)
4042 class WorkAlways(type):
4044 # this is here to make sure that .mro()s aren't called
4045 # with an exception set (which was possible at one point).
4046 # An error message will be printed in a debug build.
4047 # What's a good way to test for this?
4048 return type.mro(self
)
4063 __metaclass__
= WorkOnce
4066 __metaclass__
= WorkAlways
4068 # Immediate subclasses have their mro's adjusted in alphabetical
4069 # order, so E's will get adjusted before adjusting F's fails. We
4070 # check here that E's gets restored.
4072 E_mro_before
= E
.__mro
__
4073 D_mro_before
= D
.__mro
__
4077 except RuntimeError:
4078 self
.assertEqual(E
.__mro
__, E_mro_before
)
4079 self
.assertEqual(D
.__mro
__, D_mro_before
)
4081 self
.fail("exception not propagated")
4083 def test_mutable_bases_catch_mro_conflict(self
):
4084 # Testing mutable bases catch mro conflict...
4101 C
.__bases
__ = (B
, A
)
4105 self
.fail("didn't catch MRO conflict")
4107 def test_mutable_names(self
):
4108 # Testing mutable names...
4112 # C.__module__ could be 'test_descr' or '__main__'
4116 self
.assertEqual((C
.__module
__, C
.__name
__), (mod
, 'D'))
4119 self
.assertEqual((C
.__module
__, C
.__name
__), (mod
, 'D.E'))
4121 def test_subclass_right_op(self
):
4122 # Testing correct dispatch of subclass overloading __r<op>__...
4124 # This code tests various cases where right-dispatch of a subclass
4125 # should be preferred over left-dispatch of a base class.
4127 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4130 def __floordiv__(self
, other
):
4131 return "B.__floordiv__"
4132 def __rfloordiv__(self
, other
):
4133 return "B.__rfloordiv__"
4135 self
.assertEqual(B(1) // 1, "B.__floordiv__")
4136 self
.assertEqual(1 // B(1), "B.__rfloordiv__")
4138 # Case 2: subclass of object; this is just the baseline for case 3
4141 def __floordiv__(self
, other
):
4142 return "C.__floordiv__"
4143 def __rfloordiv__(self
, other
):
4144 return "C.__rfloordiv__"
4146 self
.assertEqual(C() // 1, "C.__floordiv__")
4147 self
.assertEqual(1 // C(), "C.__rfloordiv__")
4149 # Case 3: subclass of new-style class; here it gets interesting
4152 def __floordiv__(self
, other
):
4153 return "D.__floordiv__"
4154 def __rfloordiv__(self
, other
):
4155 return "D.__rfloordiv__"
4157 self
.assertEqual(D() // C(), "D.__floordiv__")
4158 self
.assertEqual(C() // D(), "D.__rfloordiv__")
4160 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4165 self
.assertEqual(E
.__rfloordiv
__, C
.__rfloordiv
__)
4167 self
.assertEqual(E() // 1, "C.__floordiv__")
4168 self
.assertEqual(1 // E(), "C.__rfloordiv__")
4169 self
.assertEqual(E() // C(), "C.__floordiv__")
4170 self
.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4172 @test_support.impl_detail("testing an internal kind of method object")
4173 def test_meth_class_get(self
):
4174 # Testing __get__ method of METH_CLASS C methods...
4175 # Full coverage of descrobject.c::classmethod_get()
4179 res
= {1: None, 2: None, 3: None}
4180 self
.assertEqual(dict.fromkeys(arg
), res
)
4181 self
.assertEqual({}.fromkeys(arg
), res
)
4183 # Now get the descriptor
4184 descr
= dict.__dict
__["fromkeys"]
4186 # More baseline using the descriptor directly
4187 self
.assertEqual(descr
.__get
__(None, dict)(arg
), res
)
4188 self
.assertEqual(descr
.__get
__({})(arg
), res
)
4190 # Now check various error cases
4192 descr
.__get
__(None, None)
4196 self
.fail("shouldn't have allowed descr.__get__(None, None)")
4202 self
.fail("shouldn't have allowed descr.__get__(42)")
4204 descr
.__get
__(None, 42)
4208 self
.fail("shouldn't have allowed descr.__get__(None, 42)")
4210 descr
.__get
__(None, int)
4214 self
.fail("shouldn't have allowed descr.__get__(None, int)")
4216 def test_isinst_isclass(self
):
4217 # Testing proxy isinstance() and isclass()...
4218 class Proxy(object):
4219 def __init__(self
, obj
):
4221 def __getattribute__(self
, name
):
4222 if name
.startswith("_Proxy__"):
4223 return object.__getattribute
__(self
, name
)
4225 return getattr(self
.__obj
, name
)
4226 # Test with a classic class
4231 self
.assertIsInstance(a
, C
) # Baseline
4232 self
.assertIsInstance(pa
, C
) # Test
4233 # Test with a classic subclass
4238 self
.assertIsInstance(a
, C
) # Baseline
4239 self
.assertIsInstance(pa
, C
) # Test
4240 # Test with a new-style class
4245 self
.assertIsInstance(a
, C
) # Baseline
4246 self
.assertIsInstance(pa
, C
) # Test
4247 # Test with a new-style subclass
4252 self
.assertIsInstance(a
, C
) # Baseline
4253 self
.assertIsInstance(pa
, C
) # Test
4255 def test_proxy_super(self
):
4256 # Testing super() for a proxy object...
4257 class Proxy(object):
4258 def __init__(self
, obj
):
4260 def __getattribute__(self
, name
):
4261 if name
.startswith("_Proxy__"):
4262 return object.__getattribute
__(self
, name
)
4264 return getattr(self
.__obj
, name
)
4272 return super(C
, self
).f() + "->C.f"
4276 self
.assertEqual(C
.__dict
__["f"](p
), "B.f->C.f")
4278 def test_carloverre(self
):
4279 # Testing prohibition of Carlo Verre's hack...
4281 object.__setattr
__(str, "foo", 42)
4285 self
.fail("Carlo Verre __setattr__ suceeded!")
4287 object.__delattr
__(str, "lower")
4291 self
.fail("Carlo Verre __delattr__ succeeded!")
4293 def test_weakref_segfault(self
):
4294 # Testing weakref segfault...
4299 def __init__(self
, referrent
):
4300 self
.ref
= weakref
.ref(referrent
)
4309 o
.whatever
= Provoker(o
)
4312 def test_wrapper_segfault(self
):
4313 # SF 927248: deeply nested wrappers could cause stack overflow
4315 for i
in xrange(1000000):
4319 def test_file_fault(self
):
4320 # Testing sys.stdout is changed in getattr...
4321 test_stdout
= sys
.stdout
4323 def __getattr__(self
, attr
):
4324 sys
.stdout
= sys
.__stdout
__
4325 raise RuntimeError("Premature access to sys.stdout.%s" % attr
)
4326 sys
.stdout
= StdoutGuard()
4329 except RuntimeError:
4332 sys
.stdout
= test_stdout
4334 def test_vicious_descriptor_nonsense(self
):
4335 # Testing vicious_descriptor_nonsense...
4337 # A potential segfault spotted by Thomas Wouters in mail to
4338 # python-dev 2003-04-17, turned into an example & fixed by Michael
4339 # Hudson just less than four months later...
4344 def __eq__(self
, other
):
4348 class Descr(object):
4349 def __get__(self
, ob
, type=None):
4356 c
.__dict
__[Evil()] = 0
4358 self
.assertEqual(c
.attr
, 1)
4359 # this makes a crash more likely:
4360 test_support
.gc_collect()
4361 self
.assertEqual(hasattr(c
, 'attr'), False)
4363 def test_init(self
):
4373 self
.fail("did not test __init__() for None return")
4375 def test_method_wrapper(self
):
4376 # Testing method-wrapper objects...
4377 # <type 'method-wrapper'> did not support any reflection before 2.5
4380 self
.assertEqual(l
.__add
__, l
.__add
__)
4381 self
.assertEqual(l
.__add
__, [].__add
__)
4382 self
.assertTrue(l
.__add
__ != [5].__add
__)
4383 self
.assertTrue(l
.__add
__ != l
.__mul
__)
4384 self
.assertTrue(l
.__add
__.__name
__ == '__add__')
4385 if hasattr(l
.__add
__, '__self__'):
4387 self
.assertTrue(l
.__add
__.__self
__ is l
)
4388 self
.assertTrue(l
.__add
__.__objclass
__ is list)
4390 # Python implementations where [].__add__ is a normal bound method
4391 self
.assertTrue(l
.__add
__.im_self
is l
)
4392 self
.assertTrue(l
.__add
__.im_class
is list)
4393 self
.assertEqual(l
.__add
__.__doc
__, list.__add
__.__doc
__)
4399 self
.fail("no TypeError from hash([].__add__)")
4403 self
.assertEqual(t
.__add
__, (7,).__add
__)
4404 self
.assertEqual(hash(t
.__add
__), hash((7,).__add
__))
4406 def test_not_implemented(self
):
4407 # Testing NotImplemented...
4408 # all binary methods should be able to return a NotImplemented
4411 def specialmethod(self
, other
):
4412 return NotImplemented
4414 def check(expr
, x
, y
):
4416 exec expr
in {'x': x
, 'y': y
, 'operator': operator
}
4420 self
.fail("no TypeError from %r" % (expr
,))
4422 N1
= sys
.maxint
+ 1L # might trigger OverflowErrors instead of
4424 N2
= sys
.maxint
# if sizeof(int) < sizeof(long), might trigger
4425 # ValueErrors instead of TypeErrors
4426 for metaclass
in [type, types
.ClassType
]:
4427 for name
, expr
, iexpr
in [
4428 ('__add__', 'x + y', 'x += y'),
4429 ('__sub__', 'x - y', 'x -= y'),
4430 ('__mul__', 'x * y', 'x *= y'),
4431 ('__truediv__', 'operator.truediv(x, y)', None),
4432 ('__floordiv__', 'operator.floordiv(x, y)', None),
4433 ('__div__', 'x / y', 'x /= y'),
4434 ('__mod__', 'x % y', 'x %= y'),
4435 ('__divmod__', 'divmod(x, y)', None),
4436 ('__pow__', 'x ** y', 'x **= y'),
4437 ('__lshift__', 'x << y', 'x <<= y'),
4438 ('__rshift__', 'x >> y', 'x >>= y'),
4439 ('__and__', 'x & y', 'x &= y'),
4440 ('__or__', 'x | y', 'x |= y'),
4441 ('__xor__', 'x ^ y', 'x ^= y'),
4442 ('__coerce__', 'coerce(x, y)', None)]:
4443 if name
== '__coerce__':
4446 rname
= '__r' + name
[2:]
4447 A
= metaclass('A', (), {name
: specialmethod
})
4448 B
= metaclass('B', (), {rname
: specialmethod
})
4466 iname
= '__i' + name
[2:]
4467 C
= metaclass('C', (), {iname
: specialmethod
})
4474 def test_assign_slice(self
):
4475 # ceval.c's assign_slice used to check for
4476 # tp->tp_as_sequence->sq_slice instead of
4477 # tp->tp_as_sequence->sq_ass_slice
4480 def __setslice__(self
, start
, stop
, value
):
4485 self
.assertEqual(c
.value
, 3)
4487 def test_set_and_no_get(self
):
4489 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4490 class Descr(object):
4492 def __init__(self
, name
):
4495 def __set__(self
, obj
, value
):
4496 obj
.__dict
__[self
.name
] = value
4503 self
.assertIs(x
.a
, descr
)
4505 self
.assertEqual(x
.a
, 42)
4507 # Also check type_getattro for correctness.
4511 __metaclass__
= Meta
4514 self
.assertEqual(X
.a
, 42)
4516 def test_getattr_hooks(self
):
4519 class Descriptor(object):
4521 def __get__(self
, obj
, objtype
=None):
4524 raise AttributeError(name
)
4527 descr
= Descriptor()
4529 __getattribute__
= descr
4533 __getattribute__
= descr
4536 self
.assertRaises(AttributeError, getattr, A(), "attr")
4537 self
.assertEquals(descr
.counter
, 1)
4538 self
.assertRaises(AttributeError, getattr, B(), "attr")
4539 self
.assertEquals(descr
.counter
, 2)
4540 self
.assertRaises(AttributeError, getattr, C(), "attr")
4541 self
.assertEquals(descr
.counter
, 4)
4544 class EvilGetattribute(object):
4545 # This used to segfault
4546 def __getattr__(self
, name
):
4547 raise AttributeError(name
)
4548 def __getattribute__(self
, name
):
4549 del EvilGetattribute
.__getattr
__
4552 raise AttributeError(name
)
4554 self
.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4557 class DictProxyTests(unittest
.TestCase
):
4564 def test_iter_keys(self
):
4565 # Testing dict-proxy iterkeys...
4566 keys
= [ key
for key
in self
.C
.__dict
__.iterkeys() ]
4568 self
.assertEquals(keys
, ['__dict__', '__doc__', '__module__',
4569 '__weakref__', 'meth'])
4571 def test_iter_values(self
):
4572 # Testing dict-proxy itervalues...
4573 values
= [ values
for values
in self
.C
.__dict
__.itervalues() ]
4574 self
.assertEqual(len(values
), 5)
4576 def test_iter_items(self
):
4577 # Testing dict-proxy iteritems...
4578 keys
= [ key
for (key
, value
) in self
.C
.__dict
__.iteritems() ]
4580 self
.assertEqual(keys
, ['__dict__', '__doc__', '__module__',
4581 '__weakref__', 'meth'])
4583 def test_dict_type_with_metaclass(self
):
4584 # Testing type of __dict__ when __metaclass__ set...
4590 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4592 self
.assertEqual(type(C
.__dict
__), type(B
.__dict
__))
4595 class PTypesLongInitTest(unittest
.TestCase
):
4596 # This is in its own TestCase so that it can be run before any other tests.
4597 def test_pytype_long_ready(self
):
4598 # Testing SF bug 551412 ...
4600 # This dumps core when SF bug 551412 isn't fixed --
4601 # but only when test_descr.py is run separately.
4602 # (That can't be helped -- as soon as PyType_Ready()
4603 # is called for PyLong_Type, the bug is gone.)
4604 class UserLong(object):
4605 def __pow__(self
, *args
):
4608 pow(0L, UserLong(), 0L)
4612 # Another segfault only when run early
4613 # (before PyType_Ready(tuple) is called)
4618 deprecations
= [(r
'complex divmod\(\), // and % are deprecated$',
4619 DeprecationWarning)]
4622 ("classic (int|long) division", DeprecationWarning),
4623 ("coerce.. not supported", DeprecationWarning),
4624 (".+__(get|set|del)slice__ has been removed", DeprecationWarning)]
4625 with test_support
.check_warnings(*deprecations
):
4626 # Run all local test cases, with PTypesLongInitTest first.
4627 test_support
.run_unittest(PTypesLongInitTest
, OperatorsTest
,
4628 ClassPropertiesAndMethods
, DictProxyTests
)
4630 if __name__
== "__main__":