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 consistency 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(), {}),
1721 ("__dir__", dir, empty_seq
, set(), {}),
1724 class Checker(object):
1725 def __getattr__(self
, attr
, test
=self
):
1726 test
.fail("__getattr__ called with {0}".format(attr
))
1727 def __getattribute__(self
, attr
, test
=self
):
1729 test
.fail("__getattribute__ called with {0}".format(attr
))
1730 return object.__getattribute
__(self
, attr
)
1731 class SpecialDescr(object):
1732 def __init__(self
, impl
):
1734 def __get__(self
, obj
, owner
):
1736 return self
.impl
.__get
__(obj
, owner
)
1737 class MyException(Exception):
1739 class ErrDescr(object):
1740 def __get__(self
, obj
, owner
):
1743 for name
, runner
, meth_impl
, ok
, env
in specials
:
1746 for attr
, obj
in env
.iteritems():
1747 setattr(X
, attr
, obj
)
1748 setattr(X
, name
, meth_impl
)
1754 for attr
, obj
in env
.iteritems():
1755 setattr(X
, attr
, obj
)
1756 setattr(X
, name
, SpecialDescr(meth_impl
))
1758 self
.assertEqual(record
, [1], name
)
1762 for attr
, obj
in env
.iteritems():
1763 setattr(X
, attr
, obj
)
1764 setattr(X
, name
, ErrDescr())
1770 self
.fail("{0!r} didn't raise".format(name
))
1772 def test_specials(self
):
1773 # Testing special operators...
1774 # Test operators like __hash__ for which a built-in default exists
1776 # Test the default behavior for static classes
1778 def __getitem__(self
, i
):
1779 if 0 <= i
< 10: return i
1783 self
.assertTrue(not not c1
) # What?
1784 self
.assertNotEqual(id(c1
), id(c2
))
1787 self
.assertEqual(cmp(c1
, c2
), cmp(id(c1
), id(c2
)))
1788 self
.assertEqual(c1
, c1
)
1789 self
.assertTrue(c1
!= c2
)
1790 self
.assertTrue(not c1
!= c1
)
1791 self
.assertTrue(not c1
== c2
)
1792 # Note that the module name appears in str/repr, and that varies
1793 # depending on whether this test is run standalone or from a framework.
1794 self
.assertTrue(str(c1
).find('C object at ') >= 0)
1795 self
.assertEqual(str(c1
), repr(c1
))
1796 self
.assertNotIn(-1, c1
)
1798 self
.assertIn(i
, c1
)
1799 self
.assertNotIn(10, c1
)
1800 # Test the default behavior for dynamic classes
1802 def __getitem__(self
, i
):
1803 if 0 <= i
< 10: return i
1807 self
.assertTrue(not not d1
)
1808 self
.assertNotEqual(id(d1
), id(d2
))
1811 self
.assertEqual(cmp(d1
, d2
), cmp(id(d1
), id(d2
)))
1812 self
.assertEqual(d1
, d1
)
1813 self
.assertNotEqual(d1
, d2
)
1814 self
.assertTrue(not d1
!= d1
)
1815 self
.assertTrue(not d1
== d2
)
1816 # Note that the module name appears in str/repr, and that varies
1817 # depending on whether this test is run standalone or from a framework.
1818 self
.assertTrue(str(d1
).find('D object at ') >= 0)
1819 self
.assertEqual(str(d1
), repr(d1
))
1820 self
.assertNotIn(-1, d1
)
1822 self
.assertIn(i
, d1
)
1823 self
.assertNotIn(10, d1
)
1824 # Test overridden behavior for static classes
1825 class Proxy(object):
1826 def __init__(self
, x
):
1828 def __nonzero__(self
):
1829 return not not self
.x
1832 def __eq__(self
, other
):
1833 return self
.x
== other
1834 def __ne__(self
, other
):
1835 return self
.x
!= other
1836 def __cmp__(self
, other
):
1837 return cmp(self
.x
, other
.x
)
1839 return "Proxy:%s" % self
.x
1841 return "Proxy(%r)" % self
.x
1842 def __contains__(self
, value
):
1843 return value
in self
.x
1847 self
.assertFalse(p0
)
1848 self
.assertTrue(not not p1
)
1849 self
.assertEqual(hash(p0
), hash(0))
1850 self
.assertEqual(p0
, p0
)
1851 self
.assertNotEqual(p0
, p1
)
1852 self
.assertTrue(not p0
!= p0
)
1853 self
.assertEqual(not p0
, p1
)
1854 self
.assertEqual(cmp(p0
, p1
), -1)
1855 self
.assertEqual(cmp(p0
, p0
), 0)
1856 self
.assertEqual(cmp(p0
, p_1
), 1)
1857 self
.assertEqual(str(p0
), "Proxy:0")
1858 self
.assertEqual(repr(p0
), "Proxy(0)")
1859 p10
= Proxy(range(10))
1860 self
.assertNotIn(-1, p10
)
1862 self
.assertIn(i
, p10
)
1863 self
.assertNotIn(10, p10
)
1864 # Test overridden behavior for dynamic classes
1865 class DProxy(object):
1866 def __init__(self
, x
):
1868 def __nonzero__(self
):
1869 return not not self
.x
1872 def __eq__(self
, other
):
1873 return self
.x
== other
1874 def __ne__(self
, other
):
1875 return self
.x
!= other
1876 def __cmp__(self
, other
):
1877 return cmp(self
.x
, other
.x
)
1879 return "DProxy:%s" % self
.x
1881 return "DProxy(%r)" % self
.x
1882 def __contains__(self
, value
):
1883 return value
in self
.x
1887 self
.assertFalse(p0
)
1888 self
.assertTrue(not not p1
)
1889 self
.assertEqual(hash(p0
), hash(0))
1890 self
.assertEqual(p0
, p0
)
1891 self
.assertNotEqual(p0
, p1
)
1892 self
.assertNotEqual(not p0
, p0
)
1893 self
.assertEqual(not p0
, p1
)
1894 self
.assertEqual(cmp(p0
, p1
), -1)
1895 self
.assertEqual(cmp(p0
, p0
), 0)
1896 self
.assertEqual(cmp(p0
, p_1
), 1)
1897 self
.assertEqual(str(p0
), "DProxy:0")
1898 self
.assertEqual(repr(p0
), "DProxy(0)")
1899 p10
= DProxy(range(10))
1900 self
.assertNotIn(-1, p10
)
1902 self
.assertIn(i
, p10
)
1903 self
.assertNotIn(10, p10
)
1905 # Safety test for __cmp__
1906 def unsafecmp(a
, b
):
1907 if not hasattr(a
, '__cmp__'):
1908 return # some types don't have a __cmp__ any more (so the
1909 # test doesn't make sense any more), or maybe they
1910 # never had a __cmp__ at all, e.g. in PyPy
1912 a
.__class
__.__cmp
__(a
, b
)
1916 self
.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1919 unsafecmp(u
"123", "123")
1920 unsafecmp("123", u
"123")
1926 @test_support.impl_detail("custom logic for printing to real file objects")
1927 def test_recursions_1(self
):
1928 # Testing recursion checks ...
1930 def __new__(cls
, letter
):
1932 return str.__new
__(cls
)
1933 return str.__new
__(cls
, letter
)
1938 # sys.stdout needs to be the original to trigger the recursion bug
1939 test_stdout
= sys
.stdout
1940 sys
.stdout
= test_support
.get_original_stdout()
1942 # nothing should actually be printed, this should raise an exception
1944 except RuntimeError:
1947 self
.fail("expected a RuntimeError for print recursion")
1949 sys
.stdout
= test_stdout
1951 def test_recursions_2(self
):
1955 A
.__mul
__ = types
.MethodType(lambda self
, x
: self
* x
, None, A
)
1958 except RuntimeError:
1961 self
.fail("expected a RuntimeError")
1963 def test_weakrefs(self
):
1964 # Testing weak references...
1970 self
.assertEqual(r(), c
)
1972 test_support
.gc_collect()
1973 self
.assertEqual(r(), None)
1975 class NoWeak(object):
1980 except TypeError, msg
:
1981 self
.assertTrue(str(msg
).find("weak reference") >= 0)
1983 self
.fail("weakref.ref(no) should be illegal")
1985 __slots__
= ['foo', '__weakref__']
1987 r
= weakref
.ref(yes
)
1988 self
.assertEqual(r(), yes
)
1990 test_support
.gc_collect()
1991 self
.assertEqual(r(), None)
1994 def test_properties(self
):
1995 # Testing property...
1999 def setx(self
, value
):
2003 x
= property(getx
, setx
, delx
, doc
="I'm the x property.")
2005 self
.assertFalse(hasattr(a
, "x"))
2007 self
.assertEqual(a
._C
__x
, 42)
2008 self
.assertEqual(a
.x
, 42)
2010 self
.assertFalse(hasattr(a
, "x"))
2011 self
.assertFalse(hasattr(a
, "_C__x"))
2013 self
.assertEqual(C
.x
.__get
__(a
), 100)
2015 self
.assertFalse(hasattr(a
, "x"))
2017 raw
= C
.__dict
__['x']
2018 self
.assertIsInstance(raw
, property)
2021 self
.assertIn("__doc__", attrs
)
2022 self
.assertIn("fget", attrs
)
2023 self
.assertIn("fset", attrs
)
2024 self
.assertIn("fdel", attrs
)
2026 self
.assertEqual(raw
.__doc
__, "I'm the x property.")
2027 self
.assertTrue(raw
.fget
is C
.__dict
__['getx'])
2028 self
.assertTrue(raw
.fset
is C
.__dict
__['setx'])
2029 self
.assertTrue(raw
.fdel
is C
.__dict
__['delx'])
2031 for attr
in "__doc__", "fget", "fset", "fdel":
2033 setattr(raw
, attr
, 42)
2034 except TypeError, msg
:
2035 if str(msg
).find('readonly') < 0:
2036 self
.fail("when setting readonly attr %r on a property, "
2037 "got unexpected TypeError msg %r" % (attr
, str(msg
)))
2039 self
.fail("expected TypeError from trying to set readonly %r "
2040 "attr on a property" % attr
)
2043 __getitem__
= property(lambda s
: 1/0)
2049 except ZeroDivisionError:
2052 self
.fail("expected ZeroDivisionError from bad property")
2054 @unittest.skipIf(sys
.flags
.optimize
>= 2,
2055 "Docstrings are omitted with -O2 and above")
2056 def test_properties_doc_attrib(self
):
2061 def setter(self_
, value
):
2064 prop
= property(getter
)
2065 self
.assertEqual(prop
.__doc
__, "getter method")
2066 prop2
= property(fset
=setter
)
2067 self
.assertEqual(prop2
.__doc__
, None)
2069 def test_testcapi_no_segfault(self
):
2070 # this segfaulted in 2.5b2
2077 p
= property(_testcapi
.test_with_docstring
)
2079 def test_properties_plus(self
):
2081 foo
= property(doc
="hello")
2086 def foo(self
, value
):
2087 self
._foo
= abs(value
)
2092 self
.assertEqual(C
.foo
.__doc
__, "hello")
2093 self
.assertFalse(hasattr(c
, "foo"))
2095 self
.assertTrue(hasattr(c
, '_foo'))
2096 self
.assertEqual(c
._foo
, 42)
2097 self
.assertEqual(c
.foo
, 42)
2099 self
.assertFalse(hasattr(c
, '_foo'))
2100 self
.assertFalse(hasattr(c
, "foo"))
2107 except AttributeError:
2111 self
.assertEqual(d
.foo
, 24)
2120 def foo(self
, value
):
2123 def foo(self
, value
):
2124 self
._foo
= abs(value
)
2126 def foo(self
, value
=None):
2131 self
.assertEqual(e
.foo
, 42)
2139 def foo(self
, value
):
2140 self
._foo
= max(0, value
)
2143 self
.assertEqual(f
.foo
, 0)
2146 def test_dict_constructors(self
):
2147 # Testing dict constructor ...
2149 self
.assertEqual(d
, {})
2151 self
.assertEqual(d
, {})
2152 d
= dict({1: 2, 'a': 'b'})
2153 self
.assertEqual(d
, {1: 2, 'a': 'b'})
2154 self
.assertEqual(d
, dict(d
.items()))
2155 self
.assertEqual(d
, dict(d
.iteritems()))
2156 d
= dict({'one':1, 'two':2})
2157 self
.assertEqual(d
, dict(one
=1, two
=2))
2158 self
.assertEqual(d
, dict(**d
))
2159 self
.assertEqual(d
, dict({"one": 1}, two
=2))
2160 self
.assertEqual(d
, dict([("two", 2)], one
=1))
2161 self
.assertEqual(d
, dict([("one", 100), ("two", 200)], **d
))
2162 self
.assertEqual(d
, dict(**d
))
2164 for badarg
in 0, 0L, 0j
, "0", [0], (0,):
2171 # It's a sequence, and its elements are also sequences (gotta
2172 # love strings <wink>), but they aren't of length 2, so this
2173 # one seemed better as a ValueError than a TypeError.
2176 self
.fail("no TypeError from dict(%r)" % badarg
)
2178 self
.fail("no TypeError from dict(%r)" % badarg
)
2185 self
.fail("no TypeError from dict({}, {})")
2188 # Lacks a .keys() method; will be added later.
2189 dict = {1:2, 3:4, 'a':1j
}
2196 self
.fail("no TypeError from dict(incomplete mapping)")
2198 Mapping
.keys
= lambda self
: self
.dict.keys()
2199 Mapping
.__getitem
__ = lambda self
, i
: self
.dict[i
]
2201 self
.assertEqual(d
, Mapping
.dict)
2203 # Init from sequence of iterable objects, each producing a 2-sequence.
2204 class AddressBookEntry
:
2205 def __init__(self
, first
, last
):
2209 return iter([self
.first
, self
.last
])
2211 d
= dict([AddressBookEntry('Tim', 'Warsaw'),
2212 AddressBookEntry('Barry', 'Peters'),
2213 AddressBookEntry('Tim', 'Peters'),
2214 AddressBookEntry('Barry', 'Warsaw')])
2215 self
.assertEqual(d
, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2217 d
= dict(zip(range(4), range(1, 5)))
2218 self
.assertEqual(d
, dict([(i
, i
+1) for i
in range(4)]))
2220 # Bad sequence lengths.
2221 for bad
in [('tooshort',)], [('too', 'long', 'by 1')]:
2227 self
.fail("no ValueError from dict(%r)" % bad
)
2232 self
.assertEqual(dir(), ['junk', 'self'])
2235 # Just make sure these don't blow up!
2236 for arg
in 2, 2L, 2j
, 2e0
, [2], "2", u
"2", (2,), {2:2}, type, self
.test_dir
:
2239 # Try classic classes.
2242 def Cmethod(self
): pass
2244 cstuff
= ['Cdata', 'Cmethod', '__doc__', '__module__']
2245 self
.assertEqual(dir(C
), cstuff
)
2246 self
.assertIn('im_self', dir(C
.Cmethod
))
2248 c
= C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2249 self
.assertEqual(dir(c
), cstuff
)
2252 c
.cmethod
= lambda self
: 0
2253 self
.assertEqual(dir(c
), cstuff
+ ['cdata', 'cmethod'])
2254 self
.assertIn('im_self', dir(c
.Cmethod
))
2258 def Amethod(self
): pass
2260 astuff
= ['Adata', 'Amethod'] + cstuff
2261 self
.assertEqual(dir(A
), astuff
)
2262 self
.assertIn('im_self', dir(A
.Amethod
))
2264 self
.assertEqual(dir(a
), astuff
)
2265 self
.assertIn('im_self', dir(a
.Amethod
))
2267 a
.amethod
= lambda self
: 3
2268 self
.assertEqual(dir(a
), astuff
+ ['adata', 'amethod'])
2270 # The same, but with new-style classes. Since these have object as a
2271 # base class, a lot more gets sucked in.
2272 def interesting(strings
):
2273 return [s
for s
in strings
if not s
.startswith('_')]
2277 def Cmethod(self
): pass
2279 cstuff
= ['Cdata', 'Cmethod']
2280 self
.assertEqual(interesting(dir(C
)), cstuff
)
2283 self
.assertEqual(interesting(dir(c
)), cstuff
)
2284 self
.assertIn('im_self', dir(C
.Cmethod
))
2287 c
.cmethod
= lambda self
: 0
2288 self
.assertEqual(interesting(dir(c
)), cstuff
+ ['cdata', 'cmethod'])
2289 self
.assertIn('im_self', dir(c
.Cmethod
))
2293 def Amethod(self
): pass
2295 astuff
= ['Adata', 'Amethod'] + cstuff
2296 self
.assertEqual(interesting(dir(A
)), astuff
)
2297 self
.assertIn('im_self', dir(A
.Amethod
))
2299 self
.assertEqual(interesting(dir(a
)), astuff
)
2301 a
.amethod
= lambda self
: 3
2302 self
.assertEqual(interesting(dir(a
)), astuff
+ ['adata', 'amethod'])
2303 self
.assertIn('im_self', dir(a
.Amethod
))
2305 # Try a module subclass.
2311 names
= [x
for x
in dir(minstance
) if x
not in ["__name__", "__doc__"]]
2312 self
.assertEqual(names
, ['a', 'b'])
2316 return "Not a dict!"
2317 __dict__
= property(getdict
)
2319 m2instance
= M2("m2")
2322 self
.assertEqual(m2instance
.__dict
__, "Not a dict!")
2328 # Two essentially featureless objects, just inheriting stuff from
2330 self
.assertEqual(dir(NotImplemented), dir(Ellipsis))
2331 if test_support
.check_impl_detail():
2332 # None differs in PyPy: it has a __nonzero__
2333 self
.assertEqual(dir(None), dir(Ellipsis))
2335 # Nasty test case for proxied objects
2336 class Wrapper(object):
2337 def __init__(self
, obj
):
2340 return "Wrapper(%s)" % repr(self
.__obj
)
2341 def __getitem__(self
, key
):
2342 return Wrapper(self
.__obj
[key
])
2344 return len(self
.__obj
)
2345 def __getattr__(self
, name
):
2346 return Wrapper(getattr(self
.__obj
, name
))
2349 def __getclass(self
):
2350 return Wrapper(type(self
))
2351 __class__
= property(__getclass
)
2353 dir(C()) # This used to segfault
2355 def test_supers(self
):
2362 self
.assertEqual(A().meth(1), "A(1)")
2366 self
.__super
= super(B
, self
)
2368 return "B(%r)" % a
+ self
.__super
.meth(a
)
2370 self
.assertEqual(B().meth(2), "B(2)A(2)")
2374 return "C(%r)" % a
+ self
.__super
.meth(a
)
2375 C
._C
__super
= super(C
)
2377 self
.assertEqual(C().meth(3), "C(3)A(3)")
2381 return "D(%r)" % a
+ super(D
, self
).meth(a
)
2383 self
.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2385 # Test for subclassing super
2387 class mysuper(super):
2388 def __init__(self
, *args
):
2389 return super(mysuper
, self
).__init
__(*args
)
2393 return "E(%r)" % a
+ mysuper(E
, self
).meth(a
)
2395 self
.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2399 s
= self
.__super
# == mysuper(F, self)
2400 return "F(%r)[%s]" % (a
, s
.__class
__.__name
__) + s
.meth(a
)
2401 F
._F
__super
= mysuper(F
)
2403 self
.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2405 # Make sure certain errors are raised
2412 self
.fail("shouldn't allow super(D, 42)")
2419 self
.fail("shouldn't allow super(D, C())")
2422 super(D
).__get
__(12)
2426 self
.fail("shouldn't allow super(D).__get__(12)")
2429 super(D
).__get
__(C())
2433 self
.fail("shouldn't allow super(D).__get__(C())")
2435 # Make sure data descriptors can be overridden and accessed via super
2436 # (new feature in Python 2.3)
2438 class DDbase(object):
2439 def getx(self
): return 42
2442 class DDsub(DDbase
):
2443 def getx(self
): return "hello"
2447 self
.assertEqual(dd
.x
, "hello")
2448 self
.assertEqual(super(DDsub
, dd
).x
, 42)
2450 # Ensure that super() lookup of descriptor from classmethod
2451 # works (SF ID# 743627)
2454 aProp
= property(lambda self
: "foo")
2459 return super(Sub
,klass
).aProp
2461 self
.assertEqual(Sub
.test(), Base
.aProp
)
2463 # Verify that super() doesn't allow keyword args
2469 self
.assertEqual("super shouldn't accept keyword args")
2471 def test_basic_inheritance(self
):
2472 # Testing inheritance from basic types...
2477 def __add__(self
, other
):
2478 return hexint(int.__add
__(self
, other
))
2479 # (Note that overriding __radd__ doesn't work,
2480 # because the int type gets first dibs.)
2481 self
.assertEqual(repr(hexint(7) + 9), "0x10")
2482 self
.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2484 self
.assertEqual(a
, 12345)
2485 self
.assertEqual(int(a
), 12345)
2486 self
.assertTrue(int(a
).__class
__ is int)
2487 self
.assertEqual(hash(a
), hash(12345))
2488 self
.assertTrue((+a
).__class
__ is int)
2489 self
.assertTrue((a
>> 0).__class
__ is int)
2490 self
.assertTrue((a
<< 0).__class
__ is int)
2491 self
.assertTrue((hexint(0) << 12).__class
__ is int)
2492 self
.assertTrue((hexint(0) >> 12).__class
__ is int)
2494 class octlong(long):
2501 def __add__(self
, other
):
2502 return self
.__class
__(super(octlong
, self
).__add
__(other
))
2504 self
.assertEqual(str(octlong(3) + 5), "010")
2505 # (Note that overriding __radd__ here only seems to work
2506 # because the example uses a short int left argument.)
2507 self
.assertEqual(str(5 + octlong(3000)), "05675")
2509 self
.assertEqual(a
, 12345L)
2510 self
.assertEqual(long(a
), 12345L)
2511 self
.assertEqual(hash(a
), hash(12345L))
2512 self
.assertTrue(long(a
).__class
__ is long)
2513 self
.assertTrue((+a
).__class
__ is long)
2514 self
.assertTrue((-a
).__class
__ is long)
2515 self
.assertTrue((-octlong(0)).__class
__ is long)
2516 self
.assertTrue((a
>> 0).__class
__ is long)
2517 self
.assertTrue((a
<< 0).__class
__ is long)
2518 self
.assertTrue((a
- 0).__class
__ is long)
2519 self
.assertTrue((a
* 1).__class
__ is long)
2520 self
.assertTrue((a
** 1).__class
__ is long)
2521 self
.assertTrue((a
// 1).__class
__ is long)
2522 self
.assertTrue((1 * a
).__class
__ is long)
2523 self
.assertTrue((a |
0).__class
__ is long)
2524 self
.assertTrue((a ^
0).__class
__ is long)
2525 self
.assertTrue((a
& -1L).__class
__ is long)
2526 self
.assertTrue((octlong(0) << 12).__class
__ is long)
2527 self
.assertTrue((octlong(0) >> 12).__class
__ is long)
2528 self
.assertTrue(abs(octlong(0)).__class
__ is long)
2530 # Because octlong overrides __add__, we can't check the absence of +0
2531 # optimizations using octlong.
2532 class longclone(long):
2535 self
.assertTrue((a
+ 0).__class
__ is long)
2536 self
.assertTrue((0 + a
).__class
__ is long)
2538 # Check that negative clones don't segfault
2540 self
.assertEqual(a
.__dict
__, {})
2541 self
.assertEqual(long(a
), -1) # self.assertTrue PyNumber_Long() copies the sign bit
2543 class precfloat(float):
2544 __slots__
= ['prec']
2545 def __init__(self
, value
=0.0, prec
=12):
2546 self
.prec
= int(prec
)
2548 return "%.*g" % (self
.prec
, self
)
2549 self
.assertEqual(repr(precfloat(1.1)), "1.1")
2550 a
= precfloat(12345)
2551 self
.assertEqual(a
, 12345.0)
2552 self
.assertEqual(float(a
), 12345.0)
2553 self
.assertTrue(float(a
).__class
__ is float)
2554 self
.assertEqual(hash(a
), hash(12345.0))
2555 self
.assertTrue((+a
).__class
__ is float)
2557 class madcomplex(complex):
2559 return "%.17gj%+.17g" % (self
.imag
, self
.real
)
2560 a
= madcomplex(-3, 4)
2561 self
.assertEqual(repr(a
), "4j-3")
2562 base
= complex(-3, 4)
2563 self
.assertEqual(base
.__class
__, complex)
2564 self
.assertEqual(a
, base
)
2565 self
.assertEqual(complex(a
), base
)
2566 self
.assertEqual(complex(a
).__class
__, complex)
2567 a
= madcomplex(a
) # just trying another form of the constructor
2568 self
.assertEqual(repr(a
), "4j-3")
2569 self
.assertEqual(a
, base
)
2570 self
.assertEqual(complex(a
), base
)
2571 self
.assertEqual(complex(a
).__class
__, complex)
2572 self
.assertEqual(hash(a
), hash(base
))
2573 self
.assertEqual((+a
).__class
__, complex)
2574 self
.assertEqual((a
+ 0).__class
__, complex)
2575 self
.assertEqual(a
+ 0, base
)
2576 self
.assertEqual((a
- 0).__class
__, complex)
2577 self
.assertEqual(a
- 0, base
)
2578 self
.assertEqual((a
* 1).__class
__, complex)
2579 self
.assertEqual(a
* 1, base
)
2580 self
.assertEqual((a
/ 1).__class
__, complex)
2581 self
.assertEqual(a
/ 1, base
)
2583 class madtuple(tuple):
2586 if self
._rev
is not None:
2590 self
._rev
= self
.__class
__(L
)
2592 a
= madtuple((1,2,3,4,5,6,7,8,9,0))
2593 self
.assertEqual(a
, (1,2,3,4,5,6,7,8,9,0))
2594 self
.assertEqual(a
.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2595 self
.assertEqual(a
.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2596 for i
in range(512):
2597 t
= madtuple(range(i
))
2600 self
.assertEqual(v
, t
)
2601 a
= madtuple((1,2,3,4,5))
2602 self
.assertEqual(tuple(a
), (1,2,3,4,5))
2603 self
.assertTrue(tuple(a
).__class
__ is tuple)
2604 self
.assertEqual(hash(a
), hash((1,2,3,4,5)))
2605 self
.assertTrue(a
[:].__class
__ is tuple)
2606 self
.assertTrue((a
* 1).__class
__ is tuple)
2607 self
.assertTrue((a
* 0).__class
__ is tuple)
2608 self
.assertTrue((a
+ ()).__class
__ is tuple)
2610 self
.assertEqual(tuple(a
), ())
2611 self
.assertTrue(tuple(a
).__class
__ is tuple)
2612 self
.assertTrue((a
+ a
).__class
__ is tuple)
2613 self
.assertTrue((a
* 0).__class
__ is tuple)
2614 self
.assertTrue((a
* 1).__class
__ is tuple)
2615 self
.assertTrue((a
* 2).__class
__ is tuple)
2616 self
.assertTrue(a
[:].__class
__ is tuple)
2618 class madstring(str):
2621 if self
._rev
is not None:
2625 self
._rev
= self
.__class
__("".join(L
))
2627 s
= madstring("abcdefghijklmnopqrstuvwxyz")
2628 self
.assertEqual(s
, "abcdefghijklmnopqrstuvwxyz")
2629 self
.assertEqual(s
.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2630 self
.assertEqual(s
.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2631 for i
in range(256):
2632 s
= madstring("".join(map(chr, range(i
))))
2635 self
.assertEqual(u
, s
)
2636 s
= madstring("12345")
2637 self
.assertEqual(str(s
), "12345")
2638 self
.assertTrue(str(s
).__class
__ is str)
2642 self
.assertEqual(s
, base
)
2643 self
.assertEqual(str(s
), base
)
2644 self
.assertTrue(str(s
).__class
__ is str)
2645 self
.assertEqual(hash(s
), hash(base
))
2646 self
.assertEqual({s
: 1}[base
], 1)
2647 self
.assertEqual({base
: 1}[s
], 1)
2648 self
.assertTrue((s
+ "").__class
__ is str)
2649 self
.assertEqual(s
+ "", base
)
2650 self
.assertTrue(("" + s
).__class
__ is str)
2651 self
.assertEqual("" + s
, base
)
2652 self
.assertTrue((s
* 0).__class
__ is str)
2653 self
.assertEqual(s
* 0, "")
2654 self
.assertTrue((s
* 1).__class
__ is str)
2655 self
.assertEqual(s
* 1, base
)
2656 self
.assertTrue((s
* 2).__class
__ is str)
2657 self
.assertEqual(s
* 2, base
+ base
)
2658 self
.assertTrue(s
[:].__class
__ is str)
2659 self
.assertEqual(s
[:], base
)
2660 self
.assertTrue(s
[0:0].__class
__ is str)
2661 self
.assertEqual(s
[0:0], "")
2662 self
.assertTrue(s
.strip().__class
__ is str)
2663 self
.assertEqual(s
.strip(), base
)
2664 self
.assertTrue(s
.lstrip().__class
__ is str)
2665 self
.assertEqual(s
.lstrip(), base
)
2666 self
.assertTrue(s
.rstrip().__class
__ is str)
2667 self
.assertEqual(s
.rstrip(), base
)
2668 identitytab
= ''.join([chr(i
) for i
in range(256)])
2669 self
.assertTrue(s
.translate(identitytab
).__class
__ is str)
2670 self
.assertEqual(s
.translate(identitytab
), base
)
2671 self
.assertTrue(s
.translate(identitytab
, "x").__class
__ is str)
2672 self
.assertEqual(s
.translate(identitytab
, "x"), base
)
2673 self
.assertEqual(s
.translate(identitytab
, "\x00"), "")
2674 self
.assertTrue(s
.replace("x", "x").__class
__ is str)
2675 self
.assertEqual(s
.replace("x", "x"), base
)
2676 self
.assertTrue(s
.ljust(len(s
)).__class
__ is str)
2677 self
.assertEqual(s
.ljust(len(s
)), base
)
2678 self
.assertTrue(s
.rjust(len(s
)).__class
__ is str)
2679 self
.assertEqual(s
.rjust(len(s
)), base
)
2680 self
.assertTrue(s
.center(len(s
)).__class
__ is str)
2681 self
.assertEqual(s
.center(len(s
)), base
)
2682 self
.assertTrue(s
.lower().__class
__ is str)
2683 self
.assertEqual(s
.lower(), base
)
2685 class madunicode(unicode):
2688 if self
._rev
is not None:
2692 self
._rev
= self
.__class
__(u
"".join(L
))
2694 u
= madunicode("ABCDEF")
2695 self
.assertEqual(u
, u
"ABCDEF")
2696 self
.assertEqual(u
.rev(), madunicode(u
"FEDCBA"))
2697 self
.assertEqual(u
.rev().rev(), madunicode(u
"ABCDEF"))
2699 u
= madunicode(base
)
2700 self
.assertEqual(unicode(u
), base
)
2701 self
.assertTrue(unicode(u
).__class
__ is unicode)
2702 self
.assertEqual(hash(u
), hash(base
))
2703 self
.assertEqual({u
: 1}[base
], 1)
2704 self
.assertEqual({base
: 1}[u
], 1)
2705 self
.assertTrue(u
.strip().__class
__ is unicode)
2706 self
.assertEqual(u
.strip(), base
)
2707 self
.assertTrue(u
.lstrip().__class
__ is unicode)
2708 self
.assertEqual(u
.lstrip(), base
)
2709 self
.assertTrue(u
.rstrip().__class
__ is unicode)
2710 self
.assertEqual(u
.rstrip(), base
)
2711 self
.assertTrue(u
.replace(u
"x", u
"x").__class
__ is unicode)
2712 self
.assertEqual(u
.replace(u
"x", u
"x"), base
)
2713 self
.assertTrue(u
.replace(u
"xy", u
"xy").__class
__ is unicode)
2714 self
.assertEqual(u
.replace(u
"xy", u
"xy"), base
)
2715 self
.assertTrue(u
.center(len(u
)).__class
__ is unicode)
2716 self
.assertEqual(u
.center(len(u
)), base
)
2717 self
.assertTrue(u
.ljust(len(u
)).__class
__ is unicode)
2718 self
.assertEqual(u
.ljust(len(u
)), base
)
2719 self
.assertTrue(u
.rjust(len(u
)).__class
__ is unicode)
2720 self
.assertEqual(u
.rjust(len(u
)), base
)
2721 self
.assertTrue(u
.lower().__class
__ is unicode)
2722 self
.assertEqual(u
.lower(), base
)
2723 self
.assertTrue(u
.upper().__class
__ is unicode)
2724 self
.assertEqual(u
.upper(), base
)
2725 self
.assertTrue(u
.capitalize().__class
__ is unicode)
2726 self
.assertEqual(u
.capitalize(), base
)
2727 self
.assertTrue(u
.title().__class
__ is unicode)
2728 self
.assertEqual(u
.title(), base
)
2729 self
.assertTrue((u
+ u
"").__class
__ is unicode)
2730 self
.assertEqual(u
+ u
"", base
)
2731 self
.assertTrue((u
"" + u
).__class
__ is unicode)
2732 self
.assertEqual(u
"" + u
, base
)
2733 self
.assertTrue((u
* 0).__class
__ is unicode)
2734 self
.assertEqual(u
* 0, u
"")
2735 self
.assertTrue((u
* 1).__class
__ is unicode)
2736 self
.assertEqual(u
* 1, base
)
2737 self
.assertTrue((u
* 2).__class
__ is unicode)
2738 self
.assertEqual(u
* 2, base
+ base
)
2739 self
.assertTrue(u
[:].__class
__ is unicode)
2740 self
.assertEqual(u
[:], base
)
2741 self
.assertTrue(u
[0:0].__class
__ is unicode)
2742 self
.assertEqual(u
[0:0], u
"")
2744 class sublist(list):
2746 a
= sublist(range(5))
2747 self
.assertEqual(a
, range(5))
2749 self
.assertEqual(a
, range(5) + ["hello"])
2751 self
.assertEqual(a
, range(6))
2752 a
.extend(range(6, 20))
2753 self
.assertEqual(a
, range(20))
2755 self
.assertEqual(a
, range(15))
2757 self
.assertEqual(len(a
), 10)
2758 self
.assertEqual(a
, range(10))
2759 self
.assertEqual(list(a
), range(10))
2760 self
.assertEqual(a
[0], 0)
2761 self
.assertEqual(a
[9], 9)
2762 self
.assertEqual(a
[-10], 0)
2763 self
.assertEqual(a
[-1], 9)
2764 self
.assertEqual(a
[:5], range(5))
2766 class CountedInput(file):
2767 """Counts lines read by self.readline().
2769 self.lineno is the 0-based ordinal of the last line read, up to
2770 a maximum of one greater than the number of lines in the file.
2772 self.ateof is true if and only if the final "" line has been read,
2773 at which point self.lineno stops incrementing, and further calls
2774 to readline() continue to return "".
2782 s
= file.readline(self
)
2783 # Next line works too.
2784 # s = super(CountedInput, self).readline()
2790 f
= file(name
=test_support
.TESTFN
, mode
='w')
2791 lines
= ['a\n', 'b\n', 'c\n']
2795 f
= CountedInput(test_support
.TESTFN
)
2796 for (i
, expected
) in zip(range(1, 5) + [4], lines
+ 2 * [""]):
2798 self
.assertEqual(expected
, got
)
2799 self
.assertEqual(f
.lineno
, i
)
2800 self
.assertEqual(f
.ateof
, (i
> len(lines
)))
2807 test_support
.unlink(test_support
.TESTFN
)
2809 def test_keywords(self
):
2810 # Testing keyword args to basic type constructors ...
2811 self
.assertEqual(int(x
=1), 1)
2812 self
.assertEqual(float(x
=2), 2.0)
2813 self
.assertEqual(long(x
=3), 3L)
2814 self
.assertEqual(complex(imag
=42, real
=666), complex(666, 42))
2815 self
.assertEqual(str(object=500), '500')
2816 self
.assertEqual(unicode(string
='abc', errors
='strict'), u
'abc')
2817 self
.assertEqual(tuple(sequence
=range(3)), (0, 1, 2))
2818 self
.assertEqual(list(sequence
=(0, 1, 2)), range(3))
2819 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2821 for constructor
in (int, float, long, complex, str, unicode,
2824 constructor(bogus_keyword_arg
=1)
2828 self
.fail("expected TypeError from bogus keyword argument to %r"
2831 def test_str_subclass_as_dict_key(self
):
2832 # Testing a str subclass used as dict key ..
2835 """Sublcass of str that computes __eq__ case-insensitively.
2837 Also computes a hash code of the string in canonical form.
2840 def __init__(self
, value
):
2841 self
.canonical
= value
.lower()
2842 self
.hashcode
= hash(self
.canonical
)
2844 def __eq__(self
, other
):
2845 if not isinstance(other
, cistr
):
2846 other
= cistr(other
)
2847 return self
.canonical
== other
.canonical
2850 return self
.hashcode
2852 self
.assertEqual(cistr('ABC'), 'abc')
2853 self
.assertEqual('aBc', cistr('ABC'))
2854 self
.assertEqual(str(cistr('ABC')), 'ABC')
2856 d
= {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2857 self
.assertEqual(d
[cistr('one')], 1)
2858 self
.assertEqual(d
[cistr('tWo')], 2)
2859 self
.assertEqual(d
[cistr('THrEE')], 3)
2860 self
.assertIn(cistr('ONe'), d
)
2861 self
.assertEqual(d
.get(cistr('thrEE')), 3)
2863 def test_classic_comparisons(self
):
2864 # Testing classic comparisons...
2868 for base
in (classic
, int, object):
2870 def __init__(self
, value
):
2871 self
.value
= int(value
)
2872 def __cmp__(self
, other
):
2873 if isinstance(other
, C
):
2874 return cmp(self
.value
, other
.value
)
2875 if isinstance(other
, int) or isinstance(other
, long):
2876 return cmp(self
.value
, other
)
2877 return NotImplemented
2878 __hash__
= None # Silence Py3k warning
2883 self
.assertEqual(c1
, 1)
2884 c
= {1: c1
, 2: c2
, 3: c3
}
2887 self
.assertTrue(cmp(c
[x
], c
[y
]) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2888 for op
in "<", "<=", "==", "!=", ">", ">=":
2889 self
.assertTrue(eval("c[x] %s c[y]" % op
) == eval("x %s y" % op
),
2890 "x=%d, y=%d" % (x
, y
))
2891 self
.assertTrue(cmp(c
[x
], y
) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2892 self
.assertTrue(cmp(x
, c
[y
]) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2894 def test_rich_comparisons(self
):
2895 # Testing rich comparisons...
2899 self
.assertEqual(z
, 1+0j
)
2900 self
.assertEqual(1+0j
, z
)
2902 def __eq__(self
, other
):
2904 return abs(self
- other
) <= 1e-6
2906 return NotImplemented
2907 __hash__
= None # Silence Py3k warning
2909 self
.assertEqual(zz
, 1+0j
)
2910 self
.assertEqual(1+0j
, zz
)
2914 for base
in (classic
, int, object, list):
2916 def __init__(self
, value
):
2917 self
.value
= int(value
)
2918 def __cmp__(self_
, other
):
2919 self
.fail("shouldn't call __cmp__")
2920 __hash__
= None # Silence Py3k warning
2921 def __eq__(self
, other
):
2922 if isinstance(other
, C
):
2923 return self
.value
== other
.value
2924 if isinstance(other
, int) or isinstance(other
, long):
2925 return self
.value
== other
2926 return NotImplemented
2927 def __ne__(self
, other
):
2928 if isinstance(other
, C
):
2929 return self
.value
!= other
.value
2930 if isinstance(other
, int) or isinstance(other
, long):
2931 return self
.value
!= other
2932 return NotImplemented
2933 def __lt__(self
, other
):
2934 if isinstance(other
, C
):
2935 return self
.value
< other
.value
2936 if isinstance(other
, int) or isinstance(other
, long):
2937 return self
.value
< other
2938 return NotImplemented
2939 def __le__(self
, other
):
2940 if isinstance(other
, C
):
2941 return self
.value
<= other
.value
2942 if isinstance(other
, int) or isinstance(other
, long):
2943 return self
.value
<= other
2944 return NotImplemented
2945 def __gt__(self
, other
):
2946 if isinstance(other
, C
):
2947 return self
.value
> other
.value
2948 if isinstance(other
, int) or isinstance(other
, long):
2949 return self
.value
> other
2950 return NotImplemented
2951 def __ge__(self
, other
):
2952 if isinstance(other
, C
):
2953 return self
.value
>= other
.value
2954 if isinstance(other
, int) or isinstance(other
, long):
2955 return self
.value
>= other
2956 return NotImplemented
2960 self
.assertEqual(c1
, 1)
2961 c
= {1: c1
, 2: c2
, 3: c3
}
2964 for op
in "<", "<=", "==", "!=", ">", ">=":
2965 self
.assertTrue(eval("c[x] %s c[y]" % op
) == eval("x %s y" % op
),
2966 "x=%d, y=%d" % (x
, y
))
2967 self
.assertTrue(eval("c[x] %s y" % op
) == eval("x %s y" % op
),
2968 "x=%d, y=%d" % (x
, y
))
2969 self
.assertTrue(eval("x %s c[y]" % op
) == eval("x %s y" % op
),
2970 "x=%d, y=%d" % (x
, y
))
2972 def test_coercions(self
):
2973 # Testing coercions...
2982 class F(float): pass
2989 class C(complex): pass
2999 def test_descrdoc(self
):
3000 # Testing descriptor doc strings...
3001 def check(descr
, what
):
3002 self
.assertEqual(descr
.__doc
__, what
)
3003 check(file.closed
, "True if the file is closed") # getset descriptor
3004 check(file.name
, "file name") # member descriptor
3006 def test_doc_descriptor(self
):
3007 # Testing __doc__ descriptor...
3009 class DocDescr(object):
3010 def __get__(self
, object, otype
):
3012 object = object.__class
__.__name
__ + ' instance'
3014 otype
= otype
.__name
__
3015 return 'object=%s; type=%s' % (object, otype
)
3017 __doc__
= DocDescr()
3018 class NewClass(object):
3019 __doc__
= DocDescr()
3020 self
.assertEqual(OldClass
.__doc
__, 'object=None; type=OldClass')
3021 self
.assertEqual(OldClass().__doc
__, 'object=OldClass instance; type=OldClass')
3022 self
.assertEqual(NewClass
.__doc
__, 'object=None; type=NewClass')
3023 self
.assertEqual(NewClass().__doc
__, 'object=NewClass instance; type=NewClass')
3025 def test_set_class(self
):
3026 # Testing __class__ assignment...
3027 class C(object): pass
3028 class D(object): pass
3029 class E(object): pass
3031 for cls
in C
, D
, E
, F
:
3032 for cls2
in C
, D
, E
, F
:
3035 self
.assertTrue(x
.__class
__ is cls2
)
3037 self
.assertTrue(x
.__class
__ is cls
)
3044 self
.fail("shouldn't allow %r.__class__ = %r" % (x
, C
))
3046 delattr(x
, "__class__")
3047 except (TypeError, AttributeError):
3050 self
.fail("shouldn't allow del %r.__class__" % x
)
3055 cant(object(), list)
3056 cant(list(), object)
3057 class Int(int): __slots__
= []
3067 __slots__
= ["a", "b"]
3069 __slots__
= ["b", "a"]
3074 __slots__
= ["a", "b"]
3077 __slots__
= [unicode("a"), unicode("b")]
3079 __slots__
= ["c", "b"]
3081 __slots__
= ["a", "b", "d"]
3087 __slots__
= ["__weakref__"]
3089 __slots__
= ["__dict__"]
3093 __slots__
= ["__dict__", "__weakref__"]
3095 for cls
, cls2
in ((G
, H
), (G
, I
), (I
, H
), (Q
, R
), (R
, Q
)):
3099 self
.assertTrue(x
.__class
__ is cls2
,
3100 "assigning %r as __class__ for %r silently failed" % (cls2
, x
))
3101 self
.assertEqual(x
.a
, 1)
3103 self
.assertTrue(x
.__class
__ is cls
,
3104 "assigning %r as __class__ for %r silently failed" % (cls
, x
))
3105 self
.assertEqual(x
.a
, 1)
3106 for cls
in G
, J
, K
, L
, M
, N
, P
, R
, list, Int
:
3107 for cls2
in G
, J
, K
, L
, M
, N
, P
, R
, list, Int
:
3112 # Issue5283: when __class__ changes in __del__, the wrong
3113 # type gets DECREF'd.
3119 l
= [A() for x
in range(100)]
3122 def test_set_dict(self
):
3123 # Testing __dict__ assignment...
3124 class C(object): pass
3126 a
.__dict
__ = {'b': 1}
3127 self
.assertEqual(a
.b
, 1)
3131 except (AttributeError, TypeError):
3134 self
.fail("shouldn't allow %r.__dict__ = %r" % (x
, dict))
3138 del a
.__dict
__ # Deleting __dict__ is allowed
3142 def verify_dict_readonly(x
):
3144 x has to be an instance of a class inheriting from Base.
3149 except (AttributeError, TypeError):
3152 self
.fail("shouldn't allow del %r.__dict__" % x
)
3153 dict_descr
= Base
.__dict
__["__dict__"]
3155 dict_descr
.__set
__(x
, {})
3156 except (AttributeError, TypeError):
3159 self
.fail("dict_descr allowed access to %r's dict" % x
)
3161 # Classes don't allow __dict__ assignment and have readonly dicts
3162 class Meta1(type, Base
):
3164 class Meta2(Base
, type):
3167 __metaclass__
= Meta1
3169 __metaclass__
= Meta2
3171 verify_dict_readonly(cls
)
3172 class_dict
= cls
.__dict
__
3174 class_dict
["spam"] = "eggs"
3178 self
.fail("%r's __dict__ can be modified" % cls
)
3180 # Modules also disallow __dict__ assignment
3181 class Module1(types
.ModuleType
, Base
):
3183 class Module2(Base
, types
.ModuleType
):
3185 for ModuleType
in Module1
, Module2
:
3186 mod
= ModuleType("spam")
3187 verify_dict_readonly(mod
)
3188 mod
.__dict
__["spam"] = "eggs"
3190 # Exception's __dict__ can be replaced, but not deleted
3191 # (at least not any more than regular exception's __dict__ can
3192 # be deleted; on CPython it is not the case, whereas on PyPy they
3193 # can, just like any other new-style instance's __dict__.)
3194 def can_delete_dict(e
):
3197 except (TypeError, AttributeError):
3201 class Exception1(Exception, Base
):
3203 class Exception2(Base
, Exception):
3205 for ExceptionType
in Exception, Exception1
, Exception2
:
3207 e
.__dict
__ = {"a": 1}
3208 self
.assertEqual(e
.a
, 1)
3209 self
.assertEqual(can_delete_dict(e
), can_delete_dict(ValueError()))
3211 def test_pickles(self
):
3212 # Testing pickling and copying new-style classes and objects...
3213 import pickle
, cPickle
3222 def __init__(self
, a
, b
):
3223 super(C
, self
).__init
__()
3227 return "C(%r, %r)" % (self
.a
, self
.b
)
3231 def __new__(cls
, a
, b
):
3232 return super(C1
, cls
).__new
__(cls
)
3233 def __getnewargs__(self
):
3234 return (self
.a
, self
.b
)
3235 def __init__(self
, a
, b
):
3239 return "C1(%r, %r)<%r>" % (self
.a
, self
.b
, list(self
))
3243 def __new__(cls
, a
, b
, val
=0):
3244 return super(C2
, cls
).__new
__(cls
, val
)
3245 def __getnewargs__(self
):
3246 return (self
.a
, self
.b
, int(self
))
3247 def __init__(self
, a
, b
, val
=0):
3251 return "C2(%r, %r)<%r>" % (self
.a
, self
.b
, int(self
))
3255 def __init__(self
, foo
):
3257 def __getstate__(self
):
3259 def __setstate__(self
, foo
):
3262 global C4classic
, C4
3263 class C4classic
: # classic
3265 class C4(C4classic
, object): # mixed inheritance
3268 for p
in pickle
, cPickle
:
3270 for cls
in C
, C1
, C2
:
3271 s
= p
.dumps(cls
, bin
)
3273 self
.assertTrue(cls2
is cls
)
3275 a
= C1(1, 2); a
.append(42); a
.append(24)
3276 b
= C2("hello", "world", 42)
3277 s
= p
.dumps((a
, b
), bin
)
3279 self
.assertEqual(x
.__class
__, a
.__class
__)
3280 self
.assertEqual(sorteditems(x
.__dict
__), sorteditems(a
.__dict
__))
3281 self
.assertEqual(y
.__class
__, b
.__class
__)
3282 self
.assertEqual(sorteditems(y
.__dict
__), sorteditems(b
.__dict
__))
3283 self
.assertEqual(repr(x
), repr(a
))
3284 self
.assertEqual(repr(y
), repr(b
))
3285 # Test for __getstate__ and __setstate__ on new style class
3289 self
.assertEqual(u
.__class
__, v
.__class
__)
3290 self
.assertEqual(u
.foo
, v
.foo
)
3291 # Test for picklability of hybrid class
3296 self
.assertEqual(u
.__class
__, v
.__class
__)
3297 self
.assertEqual(u
.foo
, v
.foo
)
3299 # Testing copy.deepcopy()
3301 for cls
in C
, C1
, C2
:
3302 cls2
= copy
.deepcopy(cls
)
3303 self
.assertTrue(cls2
is cls
)
3305 a
= C1(1, 2); a
.append(42); a
.append(24)
3306 b
= C2("hello", "world", 42)
3307 x
, y
= copy
.deepcopy((a
, b
))
3308 self
.assertEqual(x
.__class
__, a
.__class
__)
3309 self
.assertEqual(sorteditems(x
.__dict
__), sorteditems(a
.__dict
__))
3310 self
.assertEqual(y
.__class
__, b
.__class
__)
3311 self
.assertEqual(sorteditems(y
.__dict
__), sorteditems(b
.__dict
__))
3312 self
.assertEqual(repr(x
), repr(a
))
3313 self
.assertEqual(repr(y
), repr(b
))
3315 def test_pickle_slots(self
):
3316 # Testing pickling of classes with __slots__ ...
3317 import pickle
, cPickle
3318 # Pickling of classes with __slots__ but without __getstate__ should fail
3322 for base
in [object, B
]:
3332 self
.fail("should fail: pickle C instance - %s" % base
)
3338 self
.fail("should fail: cPickle C instance - %s" % base
)
3344 self
.fail("should fail: pickle D instance - %s" % base
)
3350 self
.fail("should fail: cPickle D instance - %s" % base
)
3351 # Give C a nice generic __getstate__ and __setstate__
3354 def __getstate__(self
):
3356 d
= self
.__dict
__.copy()
3357 except AttributeError:
3359 for cls
in self
.__class
__.__mro
__:
3360 for sn
in cls
.__dict
__.get('__slots__', ()):
3362 d
[sn
] = getattr(self
, sn
)
3363 except AttributeError:
3366 def __setstate__(self
, d
):
3367 for k
, v
in d
.items():
3371 # Now it should work
3373 y
= pickle
.loads(pickle
.dumps(x
))
3374 self
.assertEqual(hasattr(y
, 'a'), 0)
3375 y
= cPickle
.loads(cPickle
.dumps(x
))
3376 self
.assertEqual(hasattr(y
, 'a'), 0)
3378 y
= pickle
.loads(pickle
.dumps(x
))
3379 self
.assertEqual(y
.a
, 42)
3380 y
= cPickle
.loads(cPickle
.dumps(x
))
3381 self
.assertEqual(y
.a
, 42)
3385 y
= pickle
.loads(pickle
.dumps(x
))
3386 self
.assertEqual(y
.a
+ y
.b
, 142)
3387 y
= cPickle
.loads(cPickle
.dumps(x
))
3388 self
.assertEqual(y
.a
+ y
.b
, 142)
3389 # A subclass that adds a slot should also work
3395 y
= pickle
.loads(pickle
.dumps(x
))
3396 self
.assertEqual(y
.a
, x
.a
)
3397 self
.assertEqual(y
.b
, x
.b
)
3398 y
= cPickle
.loads(cPickle
.dumps(x
))
3399 self
.assertEqual(y
.a
, x
.a
)
3400 self
.assertEqual(y
.b
, x
.b
)
3402 def test_binary_operator_override(self
):
3403 # Testing overrides of binary operations...
3406 return "I(%r)" % int(self
)
3407 def __add__(self
, other
):
3408 return I(int(self
) + int(other
))
3410 def __pow__(self
, other
, mod
=None):
3412 return I(pow(int(self
), int(other
)))
3414 return I(pow(int(self
), int(other
), int(mod
)))
3415 def __rpow__(self
, other
, mod
=None):
3417 return I(pow(int(other
), int(self
), mod
))
3419 return I(pow(int(other
), int(self
), int(mod
)))
3421 self
.assertEqual(repr(I(1) + I(2)), "I(3)")
3422 self
.assertEqual(repr(I(1) + 2), "I(3)")
3423 self
.assertEqual(repr(1 + I(2)), "I(3)")
3424 self
.assertEqual(repr(I(2) ** I(3)), "I(8)")
3425 self
.assertEqual(repr(2 ** I(3)), "I(8)")
3426 self
.assertEqual(repr(I(2) ** 3), "I(8)")
3427 self
.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3429 def __eq__(self
, other
):
3430 return self
.lower() == other
.lower()
3431 __hash__
= None # Silence Py3k warning
3433 def test_subclass_propagation(self
):
3434 # Testing propagation of slot functions to subclasses...
3444 orig_hash
= hash(d
) # related to id(d) in platform-dependent ways
3445 A
.__hash
__ = lambda self
: 42
3446 self
.assertEqual(hash(d
), 42)
3447 C
.__hash
__ = lambda self
: 314
3448 self
.assertEqual(hash(d
), 314)
3449 B
.__hash
__ = lambda self
: 144
3450 self
.assertEqual(hash(d
), 144)
3451 D
.__hash
__ = lambda self
: 100
3452 self
.assertEqual(hash(d
), 100)
3454 self
.assertRaises(TypeError, hash, d
)
3456 self
.assertEqual(hash(d
), 144)
3458 self
.assertRaises(TypeError, hash, d
)
3460 self
.assertEqual(hash(d
), 314)
3462 self
.assertRaises(TypeError, hash, d
)
3464 self
.assertEqual(hash(d
), 42)
3466 self
.assertRaises(TypeError, hash, d
)
3468 self
.assertEqual(hash(d
), orig_hash
)
3471 self
.assertEqual(d
.foo
, 42)
3472 self
.assertEqual(d
.bar
, 42)
3473 def __getattribute__(self
, name
):
3476 return object.__getattribute
__(self
, name
)
3477 A
.__getattribute
__ = __getattribute__
3478 self
.assertEqual(d
.foo
, 24)
3479 self
.assertEqual(d
.bar
, 42)
3480 def __getattr__(self
, name
):
3481 if name
in ("spam", "foo", "bar"):
3483 raise AttributeError, name
3484 B
.__getattr
__ = __getattr__
3485 self
.assertEqual(d
.spam
, "hello")
3486 self
.assertEqual(d
.foo
, 24)
3487 self
.assertEqual(d
.bar
, 42)
3488 del A
.__getattribute
__
3489 self
.assertEqual(d
.foo
, 42)
3491 self
.assertEqual(d
.foo
, "hello")
3492 self
.assertEqual(d
.bar
, 42)
3496 except AttributeError:
3499 self
.fail("d.foo should be undefined now")
3501 # Test a nasty bug in recurse_down_subclasses()
3507 test_support
.gc_collect()
3508 A
.__setitem
__ = lambda *a
: None # crash
3510 def test_buffer_inheritance(self
):
3511 # Testing that buffer interface is inherited ...
3514 # SF bug [#470040] ParseTuple t# vs subclasses.
3520 # b2a_hex uses the buffer interface to get its argument's value, via
3521 # PyArg_ParseTuple 't#' code.
3522 self
.assertEqual(binascii
.b2a_hex(m
), binascii
.b2a_hex(base
))
3524 # It's not clear that unicode will continue to support the character
3525 # buffer interface, and this test will fail if that's taken away.
3526 class MyUni(unicode):
3530 self
.assertEqual(binascii
.b2a_hex(m
), binascii
.b2a_hex(base
))
3537 self
.fail('subclass of int should not have a buffer interface')
3541 def test_str_of_str_subclass(self
):
3542 # Testing __str__ defined in subclass of str ...
3546 class octetstring(str):
3548 return binascii
.b2a_hex(self
)
3550 return self
+ " repr"
3552 o
= octetstring('A')
3553 self
.assertEqual(type(o
), octetstring
)
3554 self
.assertEqual(type(str(o
)), str)
3555 self
.assertEqual(type(repr(o
)), str)
3556 self
.assertEqual(ord(o
), 0x41)
3557 self
.assertEqual(str(o
), '41')
3558 self
.assertEqual(repr(o
), 'A repr')
3559 self
.assertEqual(o
.__str
__(), '41')
3560 self
.assertEqual(o
.__repr
__(), 'A repr')
3562 capture
= cStringIO
.StringIO()
3563 # Calling str() or not exercises different internal paths.
3565 print >> capture
, str(o
)
3566 self
.assertEqual(capture
.getvalue(), '41\n41\n')
3569 def test_keyword_arguments(self
):
3570 # Testing keyword arguments to __init__, __call__...
3572 self
.assertEqual(f
.__call
__(a
=42), 42)
3574 list.__init
__(a
, sequence
=[0, 1, 2])
3575 self
.assertEqual(a
, [0, 1, 2])
3577 def test_recursive_call(self
):
3578 # Testing recursive __call__() by setting to instance of class...
3585 except RuntimeError:
3588 self
.fail("Recursion limit should have been reached for __call__()")
3590 def test_delete_hook(self
):
3591 # Testing __del__ hook...
3597 self
.assertEqual(log
, [])
3599 test_support
.gc_collect()
3600 self
.assertEqual(log
, [1])
3602 class D(object): pass
3605 except TypeError: pass
3606 else: self
.fail("invalid del() didn't raise TypeError")
3608 def test_hash_inheritance(self
):
3609 # Testing hash of mutable subclasses...
3619 self
.fail("hash() of dict subclass should fail")
3629 self
.fail("hash() of list subclass should fail")
3631 def test_str_operations(self
):
3633 except TypeError: pass
3634 else: self
.fail("'' + 5 doesn't raise TypeError")
3637 except ValueError: pass
3638 else: self
.fail("''.split('') doesn't raise ValueError")
3641 except TypeError: pass
3642 else: self
.fail("''.join([0]) doesn't raise TypeError")
3645 except ValueError: pass
3646 else: self
.fail("''.rindex('5') doesn't raise ValueError")
3649 except TypeError: pass
3650 else: self
.fail("'%(n)s' % None doesn't raise TypeError")
3653 except ValueError: pass
3654 else: self
.fail("'%(n' % {} '' doesn't raise ValueError")
3656 try: '%*s' % ('abc')
3657 except TypeError: pass
3658 else: self
.fail("'%*s' % ('abc') doesn't raise TypeError")
3660 try: '%*.*s' % ('abc', 5)
3661 except TypeError: pass
3662 else: self
.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3665 except TypeError: pass
3666 else: self
.fail("'%s' % (1, 2) doesn't raise TypeError")
3669 except ValueError: pass
3670 else: self
.fail("'%' % None doesn't raise ValueError")
3672 self
.assertEqual('534253'.isdigit(), 1)
3673 self
.assertEqual('534253x'.isdigit(), 0)
3674 self
.assertEqual('%c' % 5, '\x05')
3675 self
.assertEqual('%c' % '5', '5')
3677 def test_deepcopy_recursive(self
):
3678 # Testing deepcopy of recursive objects...
3685 z
= deepcopy(a
) # This blew up before
3687 def test_unintialized_modules(self
):
3688 # Testing uninitialized module objects...
3689 from types
import ModuleType
as M
3692 self
.assertEqual(hasattr(m
, "__name__"), 0)
3693 self
.assertEqual(hasattr(m
, "__file__"), 0)
3694 self
.assertEqual(hasattr(m
, "foo"), 0)
3695 self
.assertFalse(m
.__dict
__) # None or {} are both reasonable answers
3697 self
.assertEqual(m
.__dict
__, {"foo": 1})
3699 def test_funny_new(self
):
3700 # Testing __new__ returning something unexpected...
3702 def __new__(cls
, arg
):
3703 if isinstance(arg
, str): return [1, 2, 3]
3704 elif isinstance(arg
, int): return object.__new
__(D
)
3705 else: return object.__new
__(cls
)
3707 def __init__(self
, arg
):
3709 self
.assertEqual(C("1"), [1, 2, 3])
3710 self
.assertEqual(D("1"), [1, 2, 3])
3712 self
.assertEqual(d
.foo
, None)
3714 self
.assertEqual(isinstance(d
, D
), True)
3715 self
.assertEqual(d
.foo
, 1)
3717 self
.assertEqual(isinstance(d
, D
), True)
3718 self
.assertEqual(d
.foo
, 1)
3720 def test_imul_bug(self
):
3721 # Testing for __imul__ problems...
3724 def __imul__(self
, other
):
3725 return (self
, other
)
3729 self
.assertEqual(y
, (x
, 1.0))
3732 self
.assertEqual(y
, (x
, 2))
3735 self
.assertEqual(y
, (x
, 3L))
3738 self
.assertEqual(y
, (x
, 1L<<100))
3741 self
.assertEqual(y
, (x
, None))
3744 self
.assertEqual(y
, (x
, "foo"))
3746 def test_copy_setstate(self
):
3747 # Testing that copy.*copy() correctly uses __setstate__...
3750 def __init__(self
, foo
=None):
3753 def setfoo(self
, foo
=None):
3757 def __getstate__(self
):
3759 def __setstate__(self_
, lst
):
3760 self
.assertEqual(len(lst
), 1)
3761 self_
.__foo
= self_
.foo
= lst
[0]
3764 self
.assertEqual(a
.foo
, 24)
3765 self
.assertEqual(a
.getfoo(), 42)
3767 self
.assertEqual(b
.foo
, 24)
3768 self
.assertEqual(b
.getfoo(), 24)
3769 b
= copy
.deepcopy(a
)
3770 self
.assertEqual(b
.foo
, 24)
3771 self
.assertEqual(b
.getfoo(), 24)
3773 def test_slices(self
):
3774 # Testing cases with slices and overridden __getitem__ ...
3777 self
.assertEqual("hello"[:4], "hell")
3778 self
.assertEqual("hello"[slice(4)], "hell")
3779 self
.assertEqual(str.__getitem
__("hello", slice(4)), "hell")
3781 def __getitem__(self
, x
):
3782 return str.__getitem
__(self
, x
)
3783 self
.assertEqual(S("hello")[:4], "hell")
3784 self
.assertEqual(S("hello")[slice(4)], "hell")
3785 self
.assertEqual(S("hello").__getitem
__(slice(4)), "hell")
3787 self
.assertEqual((1,2,3)[:2], (1,2))
3788 self
.assertEqual((1,2,3)[slice(2)], (1,2))
3789 self
.assertEqual(tuple.__getitem
__((1,2,3), slice(2)), (1,2))
3791 def __getitem__(self
, x
):
3792 return tuple.__getitem
__(self
, x
)
3793 self
.assertEqual(T((1,2,3))[:2], (1,2))
3794 self
.assertEqual(T((1,2,3))[slice(2)], (1,2))
3795 self
.assertEqual(T((1,2,3)).__getitem
__(slice(2)), (1,2))
3797 self
.assertEqual([1,2,3][:2], [1,2])
3798 self
.assertEqual([1,2,3][slice(2)], [1,2])
3799 self
.assertEqual(list.__getitem
__([1,2,3], slice(2)), [1,2])
3801 def __getitem__(self
, x
):
3802 return list.__getitem
__(self
, x
)
3803 self
.assertEqual(L([1,2,3])[:2], [1,2])
3804 self
.assertEqual(L([1,2,3])[slice(2)], [1,2])
3805 self
.assertEqual(L([1,2,3]).__getitem
__(slice(2)), [1,2])
3806 # Now do lists and __setitem__
3808 a
[slice(1, 3)] = [3,2]
3809 self
.assertEqual(a
, [1,3,2])
3810 a
[slice(0, 2, 1)] = [3,1]
3811 self
.assertEqual(a
, [3,1,2])
3812 a
.__setitem
__(slice(1, 3), [2,1])
3813 self
.assertEqual(a
, [3,2,1])
3814 a
.__setitem
__(slice(0, 2, 1), [2,3])
3815 self
.assertEqual(a
, [2,3,1])
3817 def test_subtype_resurrection(self
):
3818 # Testing resurrection of new-style instance...
3824 # resurrect the instance
3825 C
.container
.append(self
)
3830 # The most interesting thing here is whether this blows up, due to
3831 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3835 # If that didn't blow up, it's also interesting to see whether clearing
3836 # the last container slot works: that will attempt to delete c again,
3837 # which will cause c to get appended back to the container again
3838 # "during" the del. (On non-CPython implementations, however, __del__
3839 # is typically not called again.)
3840 test_support
.gc_collect()
3841 self
.assertEqual(len(C
.container
), 1)
3843 if test_support
.check_impl_detail():
3844 test_support
.gc_collect()
3845 self
.assertEqual(len(C
.container
), 1)
3846 self
.assertEqual(C
.container
[-1].attr
, 42)
3848 # Make c mortal again, so that the test framework with -l doesn't report
3852 def test_slots_trash(self
):
3853 # Testing slot trash...
3854 # Deallocating deeply nested slotted trash caused stack overflows
3855 class trash(object):
3857 def __init__(self
, x
):
3860 for i
in xrange(50000):
3864 def test_slots_multiple_inheritance(self
):
3865 # SF bug 575229, multiple inheritance w/ slots dumps core
3872 if test_support
.check_impl_detail():
3873 self
.assertEqual(C
.__basicsize
__, B
.__basicsize
__)
3874 self
.assertTrue(hasattr(C
, '__dict__'))
3875 self
.assertTrue(hasattr(C
, '__weakref__'))
3878 def test_rmul(self
):
3879 # Testing correct invocation of __rmul__...
3882 def __mul__(self
, other
):
3884 def __rmul__(self
, other
):
3887 self
.assertEqual(a
*2, "mul")
3888 self
.assertEqual(a
*2.2, "mul")
3889 self
.assertEqual(2*a
, "rmul")
3890 self
.assertEqual(2.2*a
, "rmul")
3892 def test_ipow(self
):
3893 # Testing correct invocation of __ipow__...
3896 def __ipow__(self
, other
):
3901 def test_mutable_bases(self
):
3902 # Testing mutable bases...
3904 # stuff that should work:
3908 def __getattribute__(self
, attr
):
3912 return super(C2
, self
).__getattribute
__(attr
)
3923 self
.assertEqual(d
.meth(), 1)
3924 self
.assertEqual(e
.meth(), 1)
3925 self
.assertEqual(d
.a
, 2)
3926 self
.assertEqual(e
.a
, 2)
3927 self
.assertEqual(C2
.__subclasses__(), [D
])
3931 except (TypeError, AttributeError):
3934 self
.fail("shouldn't be able to delete .__bases__")
3938 except TypeError, msg
:
3939 if str(msg
) == "a new-style class can't have only classic bases":
3940 self
.fail("wrong error message for .__bases__ = ()")
3942 self
.fail("shouldn't be able to set .__bases__ to ()")
3949 # actually, we'll have crashed by here...
3950 self
.fail("shouldn't be able to create inheritance cycles")
3953 D
.__bases
__ = (C
, C
)
3957 self
.fail("didn't detect repeated base classes")
3964 self
.fail("shouldn't be able to create inheritance cycles")
3966 # let's throw a classic class into the mix:
3971 D
.__bases
__ = (C
, Classic
)
3973 self
.assertEqual(d
.meth2(), 3)
3974 self
.assertEqual(e
.meth2(), 3)
3977 except AttributeError:
3980 self
.fail("attribute should have vanished")
3983 D
.__bases
__ = (Classic
,)
3987 self
.fail("new-style class must have a new-style base")
3989 def test_builtin_bases(self
):
3990 # Make sure all the builtin types can have their base queried without
3991 # segfaulting. See issue #5787.
3992 builtin_types
= [tp
for tp
in __builtin__
.__dict
__.itervalues()
3993 if isinstance(tp
, type)]
3994 for tp
in builtin_types
:
3995 object.__getattribute
__(tp
, "__bases__")
3996 if tp
is not object:
3997 self
.assertEqual(len(tp
.__bases
__), 1, tp
)
4009 L
.__bases
__ = (dict,)
4013 self
.fail("shouldn't turn list subclass into dict subclass")
4016 list.__bases
__ = (dict,)
4020 self
.fail("shouldn't be able to assign to list.__bases__")
4023 D
.__bases
__ = (C
, list)
4027 assert 0, "best_base calculation found wanting"
4030 def test_mutable_bases_with_failing_mro(self
):
4031 # Testing mutable bases with failing mro...
4032 class WorkOnce(type):
4033 def __new__(self
, name
, bases
, ns
):
4035 return super(WorkOnce
, self
).__new
__(WorkOnce
, name
, bases
, ns
)
4038 raise RuntimeError, "bozo"
4041 return type.mro(self
)
4043 class WorkAlways(type):
4045 # this is here to make sure that .mro()s aren't called
4046 # with an exception set (which was possible at one point).
4047 # An error message will be printed in a debug build.
4048 # What's a good way to test for this?
4049 return type.mro(self
)
4064 __metaclass__
= WorkOnce
4067 __metaclass__
= WorkAlways
4069 # Immediate subclasses have their mro's adjusted in alphabetical
4070 # order, so E's will get adjusted before adjusting F's fails. We
4071 # check here that E's gets restored.
4073 E_mro_before
= E
.__mro
__
4074 D_mro_before
= D
.__mro
__
4078 except RuntimeError:
4079 self
.assertEqual(E
.__mro
__, E_mro_before
)
4080 self
.assertEqual(D
.__mro
__, D_mro_before
)
4082 self
.fail("exception not propagated")
4084 def test_mutable_bases_catch_mro_conflict(self
):
4085 # Testing mutable bases catch mro conflict...
4102 C
.__bases
__ = (B
, A
)
4106 self
.fail("didn't catch MRO conflict")
4108 def test_mutable_names(self
):
4109 # Testing mutable names...
4113 # C.__module__ could be 'test_descr' or '__main__'
4117 self
.assertEqual((C
.__module
__, C
.__name
__), (mod
, 'D'))
4120 self
.assertEqual((C
.__module
__, C
.__name
__), (mod
, 'D.E'))
4122 def test_subclass_right_op(self
):
4123 # Testing correct dispatch of subclass overloading __r<op>__...
4125 # This code tests various cases where right-dispatch of a subclass
4126 # should be preferred over left-dispatch of a base class.
4128 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4131 def __floordiv__(self
, other
):
4132 return "B.__floordiv__"
4133 def __rfloordiv__(self
, other
):
4134 return "B.__rfloordiv__"
4136 self
.assertEqual(B(1) // 1, "B.__floordiv__")
4137 self
.assertEqual(1 // B(1), "B.__rfloordiv__")
4139 # Case 2: subclass of object; this is just the baseline for case 3
4142 def __floordiv__(self
, other
):
4143 return "C.__floordiv__"
4144 def __rfloordiv__(self
, other
):
4145 return "C.__rfloordiv__"
4147 self
.assertEqual(C() // 1, "C.__floordiv__")
4148 self
.assertEqual(1 // C(), "C.__rfloordiv__")
4150 # Case 3: subclass of new-style class; here it gets interesting
4153 def __floordiv__(self
, other
):
4154 return "D.__floordiv__"
4155 def __rfloordiv__(self
, other
):
4156 return "D.__rfloordiv__"
4158 self
.assertEqual(D() // C(), "D.__floordiv__")
4159 self
.assertEqual(C() // D(), "D.__rfloordiv__")
4161 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4166 self
.assertEqual(E
.__rfloordiv
__, C
.__rfloordiv
__)
4168 self
.assertEqual(E() // 1, "C.__floordiv__")
4169 self
.assertEqual(1 // E(), "C.__rfloordiv__")
4170 self
.assertEqual(E() // C(), "C.__floordiv__")
4171 self
.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4173 @test_support.impl_detail("testing an internal kind of method object")
4174 def test_meth_class_get(self
):
4175 # Testing __get__ method of METH_CLASS C methods...
4176 # Full coverage of descrobject.c::classmethod_get()
4180 res
= {1: None, 2: None, 3: None}
4181 self
.assertEqual(dict.fromkeys(arg
), res
)
4182 self
.assertEqual({}.fromkeys(arg
), res
)
4184 # Now get the descriptor
4185 descr
= dict.__dict
__["fromkeys"]
4187 # More baseline using the descriptor directly
4188 self
.assertEqual(descr
.__get
__(None, dict)(arg
), res
)
4189 self
.assertEqual(descr
.__get
__({})(arg
), res
)
4191 # Now check various error cases
4193 descr
.__get
__(None, None)
4197 self
.fail("shouldn't have allowed descr.__get__(None, None)")
4203 self
.fail("shouldn't have allowed descr.__get__(42)")
4205 descr
.__get
__(None, 42)
4209 self
.fail("shouldn't have allowed descr.__get__(None, 42)")
4211 descr
.__get
__(None, int)
4215 self
.fail("shouldn't have allowed descr.__get__(None, int)")
4217 def test_isinst_isclass(self
):
4218 # Testing proxy isinstance() and isclass()...
4219 class Proxy(object):
4220 def __init__(self
, obj
):
4222 def __getattribute__(self
, name
):
4223 if name
.startswith("_Proxy__"):
4224 return object.__getattribute
__(self
, name
)
4226 return getattr(self
.__obj
, name
)
4227 # Test with a classic class
4232 self
.assertIsInstance(a
, C
) # Baseline
4233 self
.assertIsInstance(pa
, C
) # Test
4234 # Test with a classic subclass
4239 self
.assertIsInstance(a
, C
) # Baseline
4240 self
.assertIsInstance(pa
, C
) # Test
4241 # Test with a new-style class
4246 self
.assertIsInstance(a
, C
) # Baseline
4247 self
.assertIsInstance(pa
, C
) # Test
4248 # Test with a new-style subclass
4253 self
.assertIsInstance(a
, C
) # Baseline
4254 self
.assertIsInstance(pa
, C
) # Test
4256 def test_proxy_super(self
):
4257 # Testing super() for a proxy object...
4258 class Proxy(object):
4259 def __init__(self
, obj
):
4261 def __getattribute__(self
, name
):
4262 if name
.startswith("_Proxy__"):
4263 return object.__getattribute
__(self
, name
)
4265 return getattr(self
.__obj
, name
)
4273 return super(C
, self
).f() + "->C.f"
4277 self
.assertEqual(C
.__dict
__["f"](p
), "B.f->C.f")
4279 def test_carloverre(self
):
4280 # Testing prohibition of Carlo Verre's hack...
4282 object.__setattr
__(str, "foo", 42)
4286 self
.fail("Carlo Verre __setattr__ succeeded!")
4288 object.__delattr
__(str, "lower")
4292 self
.fail("Carlo Verre __delattr__ succeeded!")
4294 def test_weakref_segfault(self
):
4295 # Testing weakref segfault...
4300 def __init__(self
, referrent
):
4301 self
.ref
= weakref
.ref(referrent
)
4310 o
.whatever
= Provoker(o
)
4313 def test_wrapper_segfault(self
):
4314 # SF 927248: deeply nested wrappers could cause stack overflow
4316 for i
in xrange(1000000):
4320 def test_file_fault(self
):
4321 # Testing sys.stdout is changed in getattr...
4322 test_stdout
= sys
.stdout
4324 def __getattr__(self
, attr
):
4325 sys
.stdout
= sys
.__stdout
__
4326 raise RuntimeError("Premature access to sys.stdout.%s" % attr
)
4327 sys
.stdout
= StdoutGuard()
4330 except RuntimeError:
4333 sys
.stdout
= test_stdout
4335 def test_vicious_descriptor_nonsense(self
):
4336 # Testing vicious_descriptor_nonsense...
4338 # A potential segfault spotted by Thomas Wouters in mail to
4339 # python-dev 2003-04-17, turned into an example & fixed by Michael
4340 # Hudson just less than four months later...
4345 def __eq__(self
, other
):
4349 class Descr(object):
4350 def __get__(self
, ob
, type=None):
4357 c
.__dict
__[Evil()] = 0
4359 self
.assertEqual(c
.attr
, 1)
4360 # this makes a crash more likely:
4361 test_support
.gc_collect()
4362 self
.assertEqual(hasattr(c
, 'attr'), False)
4364 def test_init(self
):
4374 self
.fail("did not test __init__() for None return")
4376 def test_method_wrapper(self
):
4377 # Testing method-wrapper objects...
4378 # <type 'method-wrapper'> did not support any reflection before 2.5
4381 self
.assertEqual(l
.__add
__, l
.__add
__)
4382 self
.assertEqual(l
.__add
__, [].__add
__)
4383 self
.assertTrue(l
.__add
__ != [5].__add
__)
4384 self
.assertTrue(l
.__add
__ != l
.__mul
__)
4385 self
.assertTrue(l
.__add
__.__name
__ == '__add__')
4386 if hasattr(l
.__add
__, '__self__'):
4388 self
.assertTrue(l
.__add
__.__self
__ is l
)
4389 self
.assertTrue(l
.__add
__.__objclass
__ is list)
4391 # Python implementations where [].__add__ is a normal bound method
4392 self
.assertTrue(l
.__add
__.im_self
is l
)
4393 self
.assertTrue(l
.__add
__.im_class
is list)
4394 self
.assertEqual(l
.__add
__.__doc
__, list.__add
__.__doc
__)
4400 self
.fail("no TypeError from hash([].__add__)")
4404 self
.assertEqual(t
.__add
__, (7,).__add
__)
4405 self
.assertEqual(hash(t
.__add
__), hash((7,).__add
__))
4407 def test_not_implemented(self
):
4408 # Testing NotImplemented...
4409 # all binary methods should be able to return a NotImplemented
4412 def specialmethod(self
, other
):
4413 return NotImplemented
4415 def check(expr
, x
, y
):
4417 exec expr
in {'x': x
, 'y': y
, 'operator': operator
}
4421 self
.fail("no TypeError from %r" % (expr
,))
4423 N1
= sys
.maxint
+ 1L # might trigger OverflowErrors instead of
4425 N2
= sys
.maxint
# if sizeof(int) < sizeof(long), might trigger
4426 # ValueErrors instead of TypeErrors
4427 for metaclass
in [type, types
.ClassType
]:
4428 for name
, expr
, iexpr
in [
4429 ('__add__', 'x + y', 'x += y'),
4430 ('__sub__', 'x - y', 'x -= y'),
4431 ('__mul__', 'x * y', 'x *= y'),
4432 ('__truediv__', 'operator.truediv(x, y)', None),
4433 ('__floordiv__', 'operator.floordiv(x, y)', None),
4434 ('__div__', 'x / y', 'x /= y'),
4435 ('__mod__', 'x % y', 'x %= y'),
4436 ('__divmod__', 'divmod(x, y)', None),
4437 ('__pow__', 'x ** y', 'x **= y'),
4438 ('__lshift__', 'x << y', 'x <<= y'),
4439 ('__rshift__', 'x >> y', 'x >>= y'),
4440 ('__and__', 'x & y', 'x &= y'),
4441 ('__or__', 'x | y', 'x |= y'),
4442 ('__xor__', 'x ^ y', 'x ^= y'),
4443 ('__coerce__', 'coerce(x, y)', None)]:
4444 if name
== '__coerce__':
4447 rname
= '__r' + name
[2:]
4448 A
= metaclass('A', (), {name
: specialmethod
})
4449 B
= metaclass('B', (), {rname
: specialmethod
})
4467 iname
= '__i' + name
[2:]
4468 C
= metaclass('C', (), {iname
: specialmethod
})
4475 def test_assign_slice(self
):
4476 # ceval.c's assign_slice used to check for
4477 # tp->tp_as_sequence->sq_slice instead of
4478 # tp->tp_as_sequence->sq_ass_slice
4481 def __setslice__(self
, start
, stop
, value
):
4486 self
.assertEqual(c
.value
, 3)
4488 def test_set_and_no_get(self
):
4490 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4491 class Descr(object):
4493 def __init__(self
, name
):
4496 def __set__(self
, obj
, value
):
4497 obj
.__dict
__[self
.name
] = value
4504 self
.assertIs(x
.a
, descr
)
4506 self
.assertEqual(x
.a
, 42)
4508 # Also check type_getattro for correctness.
4512 __metaclass__
= Meta
4515 self
.assertEqual(X
.a
, 42)
4517 def test_getattr_hooks(self
):
4520 class Descriptor(object):
4522 def __get__(self
, obj
, objtype
=None):
4525 raise AttributeError(name
)
4528 descr
= Descriptor()
4530 __getattribute__
= descr
4534 __getattribute__
= descr
4537 self
.assertRaises(AttributeError, getattr, A(), "attr")
4538 self
.assertEqual(descr
.counter
, 1)
4539 self
.assertRaises(AttributeError, getattr, B(), "attr")
4540 self
.assertEqual(descr
.counter
, 2)
4541 self
.assertRaises(AttributeError, getattr, C(), "attr")
4542 self
.assertEqual(descr
.counter
, 4)
4545 class EvilGetattribute(object):
4546 # This used to segfault
4547 def __getattr__(self
, name
):
4548 raise AttributeError(name
)
4549 def __getattribute__(self
, name
):
4550 del EvilGetattribute
.__getattr
__
4553 raise AttributeError(name
)
4555 self
.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4557 def test_abstractmethods(self
):
4558 # type pretends not to have __abstractmethods__.
4559 self
.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4562 self
.assertRaises(AttributeError, getattr, meta
, "__abstractmethods__")
4565 with self
.assertRaises(AttributeError):
4566 del X
.__abstractmethods
__
4568 def test_proxy_call(self
):
4569 class FakeStr(object):
4572 fake_str
= FakeStr()
4573 # isinstance() reads __class__ on new style classes
4574 self
.assertTrue(isinstance(fake_str
, str))
4576 # call a method descriptor
4577 with self
.assertRaises(TypeError):
4580 # call a slot wrapper descriptor
4581 with self
.assertRaises(TypeError):
4582 str.__add
__(fake_str
, "abc")
4585 class DictProxyTests(unittest
.TestCase
):
4592 def test_iter_keys(self
):
4593 # Testing dict-proxy iterkeys...
4594 keys
= [ key
for key
in self
.C
.__dict
__.iterkeys() ]
4596 self
.assertEqual(keys
, ['__dict__', '__doc__', '__module__',
4597 '__weakref__', 'meth'])
4599 def test_iter_values(self
):
4600 # Testing dict-proxy itervalues...
4601 values
= [ values
for values
in self
.C
.__dict
__.itervalues() ]
4602 self
.assertEqual(len(values
), 5)
4604 def test_iter_items(self
):
4605 # Testing dict-proxy iteritems...
4606 keys
= [ key
for (key
, value
) in self
.C
.__dict
__.iteritems() ]
4608 self
.assertEqual(keys
, ['__dict__', '__doc__', '__module__',
4609 '__weakref__', 'meth'])
4611 def test_dict_type_with_metaclass(self
):
4612 # Testing type of __dict__ when __metaclass__ set...
4618 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4620 self
.assertEqual(type(C
.__dict
__), type(B
.__dict
__))
4623 class PTypesLongInitTest(unittest
.TestCase
):
4624 # This is in its own TestCase so that it can be run before any other tests.
4625 def test_pytype_long_ready(self
):
4626 # Testing SF bug 551412 ...
4628 # This dumps core when SF bug 551412 isn't fixed --
4629 # but only when test_descr.py is run separately.
4630 # (That can't be helped -- as soon as PyType_Ready()
4631 # is called for PyLong_Type, the bug is gone.)
4632 class UserLong(object):
4633 def __pow__(self
, *args
):
4636 pow(0L, UserLong(), 0L)
4640 # Another segfault only when run early
4641 # (before PyType_Ready(tuple) is called)
4646 deprecations
= [(r
'complex divmod\(\), // and % are deprecated$',
4647 DeprecationWarning)]
4650 ("classic (int|long) division", DeprecationWarning),
4651 ("coerce.. not supported", DeprecationWarning),
4652 (".+__(get|set|del)slice__ has been removed", DeprecationWarning)]
4653 with test_support
.check_warnings(*deprecations
):
4654 # Run all local test cases, with PTypesLongInitTest first.
4655 test_support
.run_unittest(PTypesLongInitTest
, OperatorsTest
,
4656 ClassPropertiesAndMethods
, DictProxyTests
)
4658 if __name__
== "__main__":