Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes | Private Attributes
test.test_descr.ClassPropertiesAndMethods Class Reference

List of all members.

Public Member Functions

def test_python_dicts
def test_python_lists
def test_metaclass
def test_module_subclasses
def test_multiple_inheritance
def test_diamond_inheritence
def test_ex5_from_c3_switch
def test_monotonicity
def test_consistency_with_epg
def test_mro_disagreement
def test_object_class
def test_slots
def test_slots_special
def test_slots_descriptor
def test_dynamics
def test_errors
def test_classmethods
def test_classmethods_in_c
def test_staticmethods
def test_staticmethods_in_c
def test_classic
def test_compattr
def test_newslots
def test_altmro
def test_overloading
def test_methods
def test_special_method_lookup
def test_specials
def test_weakrefs
def test_properties
def test_properties_doc_attrib
def test_testcapi_no_segfault
def test_properties_plus
def test_dict_constructors
def test_dir
def test_supers
def test_basic_inheritance
 self.lineno is the 0-based ordinal of the last line read, up to a maximum of one greater than the number of lines in the file.
def test_keywords
def test_str_subclass_as_dict_key
def test_classic_comparisons
def test_rich_comparisons
def test_descrdoc
def test_doc_descriptor
def test_set_class
def test_set_dict
def test_pickles
def test_pickle_slots
def test_binary_operator_override
def test_subclass_propagation
def test_buffer_inheritance
def test_str_of_str_subclass
def test_keyword_arguments
def test_recursive_call
def test_delete_hook
def test_hash_inheritance
def test_str_operations
def test_deepcopy_recursive
def test_unintialized_modules
def test_funny_new
def test_imul_bug
def test_copy_setstate
def test_slices
def test_subtype_resurrection
def test_slots_trash
def test_slots_multiple_inheritance
def test_rmul
def test_ipow
def test_mutable_bases
def test_builtin_bases
def test_mutable_bases_with_failing_mro
def test_mutable_bases_catch_mro_conflict
def test_mutable_names
def test_subclass_right_op
def test_meth_class_get
def test_isinst_isclass
def test_proxy_super
def test_carloverre
def test_weakref_segfault
def test_wrapper_segfault
def test_file_fault
def test_vicious_descriptor_nonsense
def test_init
def test_method_wrapper
def test_not_implemented
def test_assign_slice
def test_set_and_no_get
def test_getattr_hooks
def test_abstractmethods
def test_proxy_call
def test_repr_as_str

Public Attributes

 state
 name
 bases
 dict
 a
 b
 foo
 setattr
 delattr
 setitem
 delitem
 x
 impl
 first
 last
 prec
 canonical
 hashcode
 value
 flag
 ref

Private Attributes

 __state
 __x
 __a
 __get
 __set
 __delete
 _foo
 __obj
 self.assertIn('self', dir(C.Cmethod))
 __super
 _rev
 __class__
 __foo

Detailed Description

Definition at line 387 of file test_descr.py.


Member Function Documentation

Definition at line 4228 of file test_descr.py.

04228 
04229     def test_abstractmethods(self):
04230         # type pretends not to have __abstractmethods__.
04231         self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
04232         class meta(type):
04233             pass
04234         self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
04235         class X(object):
04236             pass
04237         with self.assertRaises(AttributeError):
04238             del X.__abstractmethods__

Here is the call graph for this function:

Definition at line 1398 of file test_descr.py.

01398 
01399     def test_altmro(self):
01400         # Testing mro() and overriding it...
01401         class A(object):
01402             def f(self): return "A"
01403         class B(A):
01404             pass
01405         class C(A):
01406             def f(self): return "C"
01407         class D(B, C):
01408             pass
01409         self.assertEqual(D.mro(), [D, B, C, A, object])
01410         self.assertEqual(D.__mro__, (D, B, C, A, object))
01411         self.assertEqual(D().f(), "C")
01412 
01413         class PerverseMetaType(type):
01414             def mro(cls):
01415                 L = type.mro(cls)
01416                 L.reverse()
01417                 return L
01418         class X(D,B,C,A, metaclass=PerverseMetaType):
01419             pass
01420         self.assertEqual(X.__mro__, (object, A, C, B, D, X))
01421         self.assertEqual(X().f(), "A")
01422 
01423         try:
01424             class _metaclass(type):
01425                 def mro(self):
01426                     return [self, dict, object]
01427             class X(object, metaclass=_metaclass):
01428                 pass
01429             # In CPython, the class creation above already raises
01430             # TypeError, as a protection against the fact that
01431             # instances of X would segfault it.  In other Python
01432             # implementations it would be ok to let the class X
01433             # be created, but instead get a clean TypeError on the
01434             # __setitem__ below.
01435             x = object.__new__(X)
01436             x[5] = 6
01437         except TypeError:
01438             pass
01439         else:
01440             self.fail("devious mro() return not caught")
01441 
01442         try:
01443             class _metaclass(type):
01444                 def mro(self):
01445                     return [1]
01446             class X(object, metaclass=_metaclass):
01447                 pass
01448         except TypeError:
01449             pass
01450         else:
01451             self.fail("non-class mro() return not caught")
01452 
01453         try:
01454             class _metaclass(type):
01455                 def mro(self):
01456                     return 1
01457             class X(object, metaclass=_metaclass):
01458                 pass
01459         except TypeError:
01460             pass
01461         else:
01462             self.fail("non-sequence mro() return not caught")

Here is the call graph for this function:

Definition at line 4146 of file test_descr.py.

04146 
04147     def test_assign_slice(self):
04148         # ceval.c's assign_slice used to check for
04149         # tp->tp_as_sequence->sq_slice instead of
04150         # tp->tp_as_sequence->sq_ass_slice
04151 
04152         class C(object):
04153             def __setitem__(self, idx, value):
04154                 self.value = value
04155 
04156         c = C()
04157         c[1:2] = 3
04158         self.assertEqual(c.value, 3)

Here is the call graph for this function:

self.lineno is the 0-based ordinal of the last line read, up to a maximum of one greater than the number of lines in the file.

self.ateof is true if and only if the final "" line has been read,
at which point self.lineno stops incrementing, and further calls
to readline() continue to return "".
"""

lineno = 0
ateof = 0
def readline(self):
    if self.ateof:
        return ""
    s = file.readline(self)
    # Next line works too.
    # s = super(CountedInput, self).readline()
    self.lineno += 1
    if s == "":
        self.ateof = 1
   return s

f = file(name=support.TESTFN, mode='w') lines = ['a
', 'b
', 'c
'] try: f.writelines(lines) f.close() f = CountedInput(support.TESTFN) for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]): got = f.readline() self.assertEqual(expected, got) self.assertEqual(f.lineno, i) self.assertEqual(f.ateof, (i > len(lines))) f.close() finally: try: f.close() except: pass support.unlink(support.TESTFN)

Definition at line 2216 of file test_descr.py.

02216 
02217     def test_basic_inheritance(self):
02218         # Testing inheritance from basic types...
02219 
02220         class hexint(int):
02221             def __repr__(self):
02222                 return hex(self)
02223             def __add__(self, other):
02224                 return hexint(int.__add__(self, other))
02225             # (Note that overriding __radd__ doesn't work,
02226             # because the int type gets first dibs.)
02227         self.assertEqual(repr(hexint(7) + 9), "0x10")
02228         self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
02229         a = hexint(12345)
02230         self.assertEqual(a, 12345)
02231         self.assertEqual(int(a), 12345)
02232         self.assertTrue(int(a).__class__ is int)
02233         self.assertEqual(hash(a), hash(12345))
02234         self.assertTrue((+a).__class__ is int)
02235         self.assertTrue((a >> 0).__class__ is int)
02236         self.assertTrue((a << 0).__class__ is int)
02237         self.assertTrue((hexint(0) << 12).__class__ is int)
02238         self.assertTrue((hexint(0) >> 12).__class__ is int)
02239 
02240         class octlong(int):
02241             __slots__ = []
02242             def __str__(self):
02243                 return oct(self)
02244             def __add__(self, other):
02245                 return self.__class__(super(octlong, self).__add__(other))
02246             __radd__ = __add__
02247         self.assertEqual(str(octlong(3) + 5), "0o10")
02248         # (Note that overriding __radd__ here only seems to work
02249         # because the example uses a short int left argument.)
02250         self.assertEqual(str(5 + octlong(3000)), "0o5675")
02251         a = octlong(12345)
02252         self.assertEqual(a, 12345)
02253         self.assertEqual(int(a), 12345)
02254         self.assertEqual(hash(a), hash(12345))
02255         self.assertTrue(int(a).__class__ is int)
02256         self.assertTrue((+a).__class__ is int)
02257         self.assertTrue((-a).__class__ is int)
02258         self.assertTrue((-octlong(0)).__class__ is int)
02259         self.assertTrue((a >> 0).__class__ is int)
02260         self.assertTrue((a << 0).__class__ is int)
02261         self.assertTrue((a - 0).__class__ is int)
02262         self.assertTrue((a * 1).__class__ is int)
02263         self.assertTrue((a ** 1).__class__ is int)
02264         self.assertTrue((a // 1).__class__ is int)
02265         self.assertTrue((1 * a).__class__ is int)
02266         self.assertTrue((a | 0).__class__ is int)
02267         self.assertTrue((a ^ 0).__class__ is int)
02268         self.assertTrue((a & -1).__class__ is int)
02269         self.assertTrue((octlong(0) << 12).__class__ is int)
02270         self.assertTrue((octlong(0) >> 12).__class__ is int)
02271         self.assertTrue(abs(octlong(0)).__class__ is int)
02272 
02273         # Because octlong overrides __add__, we can't check the absence of +0
02274         # optimizations using octlong.
02275         class longclone(int):
02276             pass
02277         a = longclone(1)
02278         self.assertTrue((a + 0).__class__ is int)
02279         self.assertTrue((0 + a).__class__ is int)
02280 
02281         # Check that negative clones don't segfault
02282         a = longclone(-1)
02283         self.assertEqual(a.__dict__, {})
02284         self.assertEqual(int(a), -1)  # self.assertTrue PyNumber_Long() copies the sign bit
02285 
02286         class precfloat(float):
02287             __slots__ = ['prec']
02288             def __init__(self, value=0.0, prec=12):
02289                 self.prec = int(prec)
02290             def __repr__(self):
02291                 return "%.*g" % (self.prec, self)
02292         self.assertEqual(repr(precfloat(1.1)), "1.1")
02293         a = precfloat(12345)
02294         self.assertEqual(a, 12345.0)
02295         self.assertEqual(float(a), 12345.0)
02296         self.assertTrue(float(a).__class__ is float)
02297         self.assertEqual(hash(a), hash(12345.0))
02298         self.assertTrue((+a).__class__ is float)
02299 
02300         class madcomplex(complex):
02301             def __repr__(self):
02302                 return "%.17gj%+.17g" % (self.imag, self.real)
02303         a = madcomplex(-3, 4)
02304         self.assertEqual(repr(a), "4j-3")
02305         base = complex(-3, 4)
02306         self.assertEqual(base.__class__, complex)
02307         self.assertEqual(a, base)
02308         self.assertEqual(complex(a), base)
02309         self.assertEqual(complex(a).__class__, complex)
02310         a = madcomplex(a)  # just trying another form of the constructor
02311         self.assertEqual(repr(a), "4j-3")
02312         self.assertEqual(a, base)
02313         self.assertEqual(complex(a), base)
02314         self.assertEqual(complex(a).__class__, complex)
02315         self.assertEqual(hash(a), hash(base))
02316         self.assertEqual((+a).__class__, complex)
02317         self.assertEqual((a + 0).__class__, complex)
02318         self.assertEqual(a + 0, base)
02319         self.assertEqual((a - 0).__class__, complex)
02320         self.assertEqual(a - 0, base)
02321         self.assertEqual((a * 1).__class__, complex)
02322         self.assertEqual(a * 1, base)
02323         self.assertEqual((a / 1).__class__, complex)
02324         self.assertEqual(a / 1, base)
02325 
02326         class madtuple(tuple):
02327             _rev = None
02328             def rev(self):
02329                 if self._rev is not None:
02330                     return self._rev
02331                 L = list(self)
02332                 L.reverse()
02333                 self._rev = self.__class__(L)
02334                 return self._rev
02335         a = madtuple((1,2,3,4,5,6,7,8,9,0))
02336         self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
02337         self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
02338         self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
02339         for i in range(512):
02340             t = madtuple(range(i))
02341             u = t.rev()
02342             v = u.rev()
02343             self.assertEqual(v, t)
02344         a = madtuple((1,2,3,4,5))
02345         self.assertEqual(tuple(a), (1,2,3,4,5))
02346         self.assertTrue(tuple(a).__class__ is tuple)
02347         self.assertEqual(hash(a), hash((1,2,3,4,5)))
02348         self.assertTrue(a[:].__class__ is tuple)
02349         self.assertTrue((a * 1).__class__ is tuple)
02350         self.assertTrue((a * 0).__class__ is tuple)
02351         self.assertTrue((a + ()).__class__ is tuple)
02352         a = madtuple(())
02353         self.assertEqual(tuple(a), ())
02354         self.assertTrue(tuple(a).__class__ is tuple)
02355         self.assertTrue((a + a).__class__ is tuple)
02356         self.assertTrue((a * 0).__class__ is tuple)
02357         self.assertTrue((a * 1).__class__ is tuple)
02358         self.assertTrue((a * 2).__class__ is tuple)
02359         self.assertTrue(a[:].__class__ is tuple)
02360 
02361         class madstring(str):
02362             _rev = None
02363             def rev(self):
02364                 if self._rev is not None:
02365                     return self._rev
02366                 L = list(self)
02367                 L.reverse()
02368                 self._rev = self.__class__("".join(L))
02369                 return self._rev
02370         s = madstring("abcdefghijklmnopqrstuvwxyz")
02371         self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
02372         self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
02373         self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
02374         for i in range(256):
02375             s = madstring("".join(map(chr, range(i))))
02376             t = s.rev()
02377             u = t.rev()
02378             self.assertEqual(u, s)
02379         s = madstring("12345")
02380         self.assertEqual(str(s), "12345")
02381         self.assertTrue(str(s).__class__ is str)
02382 
02383         base = "\x00" * 5
02384         s = madstring(base)
02385         self.assertEqual(s, base)
02386         self.assertEqual(str(s), base)
02387         self.assertTrue(str(s).__class__ is str)
02388         self.assertEqual(hash(s), hash(base))
02389         self.assertEqual({s: 1}[base], 1)
02390         self.assertEqual({base: 1}[s], 1)
02391         self.assertTrue((s + "").__class__ is str)
02392         self.assertEqual(s + "", base)
02393         self.assertTrue(("" + s).__class__ is str)
02394         self.assertEqual("" + s, base)
02395         self.assertTrue((s * 0).__class__ is str)
02396         self.assertEqual(s * 0, "")
02397         self.assertTrue((s * 1).__class__ is str)
02398         self.assertEqual(s * 1, base)
02399         self.assertTrue((s * 2).__class__ is str)
02400         self.assertEqual(s * 2, base + base)
02401         self.assertTrue(s[:].__class__ is str)
02402         self.assertEqual(s[:], base)
02403         self.assertTrue(s[0:0].__class__ is str)
02404         self.assertEqual(s[0:0], "")
02405         self.assertTrue(s.strip().__class__ is str)
02406         self.assertEqual(s.strip(), base)
02407         self.assertTrue(s.lstrip().__class__ is str)
02408         self.assertEqual(s.lstrip(), base)
02409         self.assertTrue(s.rstrip().__class__ is str)
02410         self.assertEqual(s.rstrip(), base)
02411         identitytab = {}
02412         self.assertTrue(s.translate(identitytab).__class__ is str)
02413         self.assertEqual(s.translate(identitytab), base)
02414         self.assertTrue(s.replace("x", "x").__class__ is str)
02415         self.assertEqual(s.replace("x", "x"), base)
02416         self.assertTrue(s.ljust(len(s)).__class__ is str)
02417         self.assertEqual(s.ljust(len(s)), base)
02418         self.assertTrue(s.rjust(len(s)).__class__ is str)
02419         self.assertEqual(s.rjust(len(s)), base)
02420         self.assertTrue(s.center(len(s)).__class__ is str)
02421         self.assertEqual(s.center(len(s)), base)
02422         self.assertTrue(s.lower().__class__ is str)
02423         self.assertEqual(s.lower(), base)
02424 
02425         class madunicode(str):
02426             _rev = None
02427             def rev(self):
02428                 if self._rev is not None:
02429                     return self._rev
02430                 L = list(self)
02431                 L.reverse()
02432                 self._rev = self.__class__("".join(L))
02433                 return self._rev
02434         u = madunicode("ABCDEF")
02435         self.assertEqual(u, "ABCDEF")
02436         self.assertEqual(u.rev(), madunicode("FEDCBA"))
02437         self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
02438         base = "12345"
02439         u = madunicode(base)
02440         self.assertEqual(str(u), base)
02441         self.assertTrue(str(u).__class__ is str)
02442         self.assertEqual(hash(u), hash(base))
02443         self.assertEqual({u: 1}[base], 1)
02444         self.assertEqual({base: 1}[u], 1)
02445         self.assertTrue(u.strip().__class__ is str)
02446         self.assertEqual(u.strip(), base)
02447         self.assertTrue(u.lstrip().__class__ is str)
02448         self.assertEqual(u.lstrip(), base)
02449         self.assertTrue(u.rstrip().__class__ is str)
02450         self.assertEqual(u.rstrip(), base)
02451         self.assertTrue(u.replace("x", "x").__class__ is str)
02452         self.assertEqual(u.replace("x", "x"), base)
02453         self.assertTrue(u.replace("xy", "xy").__class__ is str)
02454         self.assertEqual(u.replace("xy", "xy"), base)
02455         self.assertTrue(u.center(len(u)).__class__ is str)
02456         self.assertEqual(u.center(len(u)), base)
02457         self.assertTrue(u.ljust(len(u)).__class__ is str)
02458         self.assertEqual(u.ljust(len(u)), base)
02459         self.assertTrue(u.rjust(len(u)).__class__ is str)
02460         self.assertEqual(u.rjust(len(u)), base)
02461         self.assertTrue(u.lower().__class__ is str)
02462         self.assertEqual(u.lower(), base)
02463         self.assertTrue(u.upper().__class__ is str)
02464         self.assertEqual(u.upper(), base)
02465         self.assertTrue(u.capitalize().__class__ is str)
02466         self.assertEqual(u.capitalize(), base)
02467         self.assertTrue(u.title().__class__ is str)
02468         self.assertEqual(u.title(), base)
02469         self.assertTrue((u + "").__class__ is str)
02470         self.assertEqual(u + "", base)
02471         self.assertTrue(("" + u).__class__ is str)
02472         self.assertEqual("" + u, base)
02473         self.assertTrue((u * 0).__class__ is str)
02474         self.assertEqual(u * 0, "")
02475         self.assertTrue((u * 1).__class__ is str)
02476         self.assertEqual(u * 1, base)
02477         self.assertTrue((u * 2).__class__ is str)
02478         self.assertEqual(u * 2, base + base)
02479         self.assertTrue(u[:].__class__ is str)
02480         self.assertEqual(u[:], base)
02481         self.assertTrue(u[0:0].__class__ is str)
02482         self.assertEqual(u[0:0], "")
02483 
02484         class sublist(list):
02485             pass
02486         a = sublist(range(5))
02487         self.assertEqual(a, list(range(5)))
02488         a.append("hello")
02489         self.assertEqual(a, list(range(5)) + ["hello"])
02490         a[5] = 5
02491         self.assertEqual(a, list(range(6)))
02492         a.extend(range(6, 20))
02493         self.assertEqual(a, list(range(20)))
02494         a[-5:] = []
02495         self.assertEqual(a, list(range(15)))
02496         del a[10:15]
02497         self.assertEqual(len(a), 10)
02498         self.assertEqual(a, list(range(10)))
02499         self.assertEqual(list(a), list(range(10)))
02500         self.assertEqual(a[0], 0)
02501         self.assertEqual(a[9], 9)
02502         self.assertEqual(a[-10], 0)
02503         self.assertEqual(a[-1], 9)
02504         self.assertEqual(a[:5], list(range(5)))
02505 
02506         ## class CountedInput(file):
02507         ##    """Counts lines read by self.readline().
02508         ##
02509         ##     self.lineno is the 0-based ordinal of the last line read, up to
02510         ##     a maximum of one greater than the number of lines in the file.
02511         ##
02512         ##     self.ateof is true if and only if the final "" line has been read,
02513         ##     at which point self.lineno stops incrementing, and further calls
02514         ##     to readline() continue to return "".
02515         ##     """
02516         ##
02517         ##     lineno = 0
02518         ##     ateof = 0
02519         ##     def readline(self):
02520         ##         if self.ateof:
02521         ##             return ""
02522         ##         s = file.readline(self)
02523         ##         # Next line works too.
02524         ##         # s = super(CountedInput, self).readline()
02525         ##         self.lineno += 1
02526         ##         if s == "":
02527         ##             self.ateof = 1
02528         ##        return s
02529         ##
02530         ## f = file(name=support.TESTFN, mode='w')
02531         ## lines = ['a\n', 'b\n', 'c\n']
02532         ## try:
02533         ##     f.writelines(lines)
02534         ##     f.close()
02535         ##     f = CountedInput(support.TESTFN)
02536         ##     for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
02537         ##         got = f.readline()
02538         ##         self.assertEqual(expected, got)
02539         ##         self.assertEqual(f.lineno, i)
02540         ##         self.assertEqual(f.ateof, (i > len(lines)))
02541         ##     f.close()
02542         ## finally:
02543         ##     try:
02544         ##         f.close()
02545         ##     except:
02546         ##         pass
02547         ##     support.unlink(support.TESTFN)

Here is the call graph for this function:

Definition at line 3119 of file test_descr.py.

03119 
03120     def test_binary_operator_override(self):
03121         # Testing overrides of binary operations...
03122         class I(int):
03123             def __repr__(self):
03124                 return "I(%r)" % int(self)
03125             def __add__(self, other):
03126                 return I(int(self) + int(other))
03127             __radd__ = __add__
03128             def __pow__(self, other, mod=None):
03129                 if mod is None:
03130                     return I(pow(int(self), int(other)))
03131                 else:
03132                     return I(pow(int(self), int(other), int(mod)))
03133             def __rpow__(self, other, mod=None):
03134                 if mod is None:
03135                     return I(pow(int(other), int(self), mod))
03136                 else:
03137                     return I(pow(int(other), int(self), int(mod)))
03138 
03139         self.assertEqual(repr(I(1) + I(2)), "I(3)")
03140         self.assertEqual(repr(I(1) + 2), "I(3)")
03141         self.assertEqual(repr(1 + I(2)), "I(3)")
03142         self.assertEqual(repr(I(2) ** I(3)), "I(8)")
03143         self.assertEqual(repr(2 ** I(3)), "I(8)")
03144         self.assertEqual(repr(I(2) ** 3), "I(8)")
03145         self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
03146         class S(str):
03147             def __eq__(self, other):
03148                 return self.lower() == other.lower()

Here is the call graph for this function:

Definition at line 3226 of file test_descr.py.

03226 
03227     def test_buffer_inheritance(self):
03228         # Testing that buffer interface is inherited ...
03229 
03230         import binascii
03231         # SF bug [#470040] ParseTuple t# vs subclasses.
03232 
03233         class MyBytes(bytes):
03234             pass
03235         base = b'abc'
03236         m = MyBytes(base)
03237         # b2a_hex uses the buffer interface to get its argument's value, via
03238         # PyArg_ParseTuple 't#' code.
03239         self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
03240 
03241         class MyInt(int):
03242             pass
03243         m = MyInt(42)
03244         try:
03245             binascii.b2a_hex(m)
03246             self.fail('subclass of int should not have a buffer interface')
03247         except TypeError:
03248             pass

Definition at line 3674 of file test_descr.py.

03674 
03675     def test_builtin_bases(self):
03676         # Make sure all the builtin types can have their base queried without
03677         # segfaulting. See issue #5787.
03678         builtin_types = [tp for tp in builtins.__dict__.values()
03679                          if isinstance(tp, type)]
03680         for tp in builtin_types:
03681             object.__getattribute__(tp, "__bases__")
03682             if tp is not object:
03683                 self.assertEqual(len(tp.__bases__), 1, tp)
03684 
03685         class L(list):
03686             pass
03687 
03688         class C(object):
03689             pass
03690 
03691         class D(C):
03692             pass
03693 
03694         try:
03695             L.__bases__ = (dict,)
03696         except TypeError:
03697             pass
03698         else:
03699             self.fail("shouldn't turn list subclass into dict subclass")
03700 
03701         try:
03702             list.__bases__ = (dict,)
03703         except TypeError:
03704             pass
03705         else:
03706             self.fail("shouldn't be able to assign to list.__bases__")
03707 
03708         try:
03709             D.__bases__ = (C, list)
03710         except TypeError:
03711             pass
03712         else:
03713             assert 0, "best_base calculation found wanting"
03714 

Here is the call graph for this function:

Definition at line 3964 of file test_descr.py.

03964 
03965     def test_carloverre(self):
03966         # Testing prohibition of Carlo Verre's hack...
03967         try:
03968             object.__setattr__(str, "foo", 42)
03969         except TypeError:
03970             pass
03971         else:
03972             self.fail("Carlo Verre __setattr__ succeeded!")
03973         try:
03974             object.__delattr__(str, "lower")
03975         except TypeError:
03976             pass
03977         else:
03978             self.fail("Carlo Verre __delattr__ succeeded!")

Here is the call graph for this function:

Definition at line 1325 of file test_descr.py.

01325 
01326     def test_classic(self):
01327         # Testing classic classes...
01328         class C:
01329             def foo(*a): return a
01330             goo = classmethod(foo)
01331         c = C()
01332         self.assertEqual(C.goo(1), (C, 1))
01333         self.assertEqual(c.goo(1), (C, 1))
01334         self.assertEqual(c.foo(1), (c, 1))
01335         class D(C):
01336             pass
01337         d = D()
01338         self.assertEqual(D.goo(1), (D, 1))
01339         self.assertEqual(d.goo(1), (D, 1))
01340         self.assertEqual(d.foo(1), (d, 1))
01341         self.assertEqual(D.foo(d, 1), (d, 1))
01342         class E: # *not* subclassing from C
01343             foo = C.foo
01344         self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
01345         self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))

Here is the call graph for this function:

Definition at line 2602 of file test_descr.py.

02602 
02603     def test_classic_comparisons(self):
02604         # Testing classic comparisons...
02605         class classic:
02606             pass
02607 
02608         for base in (classic, int, object):
02609             class C(base):
02610                 def __init__(self, value):
02611                     self.value = int(value)
02612                 def __eq__(self, other):
02613                     if isinstance(other, C):
02614                         return self.value == other.value
02615                     if isinstance(other, int) or isinstance(other, int):
02616                         return self.value == other
02617                     return NotImplemented
02618                 def __ne__(self, other):
02619                     if isinstance(other, C):
02620                         return self.value != other.value
02621                     if isinstance(other, int) or isinstance(other, int):
02622                         return self.value != other
02623                     return NotImplemented
02624                 def __lt__(self, other):
02625                     if isinstance(other, C):
02626                         return self.value < other.value
02627                     if isinstance(other, int) or isinstance(other, int):
02628                         return self.value < other
02629                     return NotImplemented
02630                 def __le__(self, other):
02631                     if isinstance(other, C):
02632                         return self.value <= other.value
02633                     if isinstance(other, int) or isinstance(other, int):
02634                         return self.value <= other
02635                     return NotImplemented
02636                 def __gt__(self, other):
02637                     if isinstance(other, C):
02638                         return self.value > other.value
02639                     if isinstance(other, int) or isinstance(other, int):
02640                         return self.value > other
02641                     return NotImplemented
02642                 def __ge__(self, other):
02643                     if isinstance(other, C):
02644                         return self.value >= other.value
02645                     if isinstance(other, int) or isinstance(other, int):
02646                         return self.value >= other
02647                     return NotImplemented
02648 
02649             c1 = C(1)
02650             c2 = C(2)
02651             c3 = C(3)
02652             self.assertEqual(c1, 1)
02653             c = {1: c1, 2: c2, 3: c3}
02654             for x in 1, 2, 3:
02655                 for y in 1, 2, 3:
02656                     for op in "<", "<=", "==", "!=", ">", ">=":
02657                         self.assertTrue(eval("c[x] %s c[y]" % op) ==
02658                                      eval("x %s y" % op),
02659                                      "x=%d, y=%d" % (x, y))
02660                         self.assertTrue(eval("c[x] %s y" % op) ==
02661                                      eval("x %s y" % op),
02662                                      "x=%d, y=%d" % (x, y))
02663                         self.assertTrue(eval("x %s c[y]" % op) ==
02664                                      eval("x %s y" % op),
02665                                      "x=%d, y=%d" % (x, y))

Definition at line 1236 of file test_descr.py.

01236 
01237     def test_classmethods(self):
01238         # Testing class methods...
01239         class C(object):
01240             def foo(*a): return a
01241             goo = classmethod(foo)
01242         c = C()
01243         self.assertEqual(C.goo(1), (C, 1))
01244         self.assertEqual(c.goo(1), (C, 1))
01245         self.assertEqual(c.foo(1), (c, 1))
01246         class D(C):
01247             pass
01248         d = D()
01249         self.assertEqual(D.goo(1), (D, 1))
01250         self.assertEqual(d.goo(1), (D, 1))
01251         self.assertEqual(d.foo(1), (d, 1))
01252         self.assertEqual(D.foo(d, 1), (d, 1))
01253         # Test for a specific crash (SF bug 528132)
01254         def f(cls, arg): return (cls, arg)
01255         ff = classmethod(f)
01256         self.assertEqual(ff.__get__(0, int)(42), (int, 42))
01257         self.assertEqual(ff.__get__(0)(42), (int, 42))
01258 
01259         # Test super() with classmethods (SF bug 535444)
01260         self.assertEqual(C.goo.__self__, C)
01261         self.assertEqual(D.goo.__self__, D)
01262         self.assertEqual(super(D,D).goo.__self__, D)
01263         self.assertEqual(super(D,d).goo.__self__, D)
01264         self.assertEqual(super(D,D).goo(), (D,))
01265         self.assertEqual(super(D,d).goo(), (D,))
01266 
01267         # Verify that a non-callable will raise
01268         meth = classmethod(1).__get__(1)
01269         self.assertRaises(TypeError, meth)
01270 
01271         # Verify that classmethod() doesn't allow keyword args
01272         try:
01273             classmethod(f, kw=1)
01274         except TypeError:
01275             pass
01276         else:
01277             self.fail("classmethod shouldn't accept keyword args")

Here is the call graph for this function:

Definition at line 1279 of file test_descr.py.

01279 
01280     def test_classmethods_in_c(self):
01281         # Testing C-based class methods...
01282         import xxsubtype as spam
01283         a = (1, 2, 3)
01284         d = {'abc': 123}
01285         x, a1, d1 = spam.spamlist.classmeth(*a, **d)
01286         self.assertEqual(x, spam.spamlist)
01287         self.assertEqual(a, a1)
01288         self.assertEqual(d, d1)
01289         x, a1, d1 = spam.spamlist().classmeth(*a, **d)
01290         self.assertEqual(x, spam.spamlist)
01291         self.assertEqual(a, a1)
01292         self.assertEqual(d, d1)

Here is the call graph for this function:

Definition at line 1346 of file test_descr.py.

01346 
01347     def test_compattr(self):
01348         # Testing computed attributes...
01349         class C(object):
01350             class computed_attribute(object):
01351                 def __init__(self, get, set=None, delete=None):
01352                     self.__get = get
01353                     self.__set = set
01354                     self.__delete = delete
01355                 def __get__(self, obj, type=None):
01356                     return self.__get(obj)
01357                 def __set__(self, obj, value):
01358                     return self.__set(obj, value)
01359                 def __delete__(self, obj):
01360                     return self.__delete(obj)
01361             def __init__(self):
01362                 self.__x = 0
01363             def __get_x(self):
01364                 x = self.__x
01365                 self.__x = x+1
01366                 return x
01367             def __set_x(self, x):
01368                 self.__x = x
01369             def __delete_x(self):
01370                 del self.__x
01371             x = computed_attribute(__get_x, __set_x, __delete_x)
01372         a = C()
01373         self.assertEqual(a.x, 0)
01374         self.assertEqual(a.x, 1)
01375         a.x = 10
01376         self.assertEqual(a.x, 10)
01377         self.assertEqual(a.x, 11)
01378         del a.x
01379         self.assertEqual(hasattr(a, 'x'), 0)

Here is the call graph for this function:

Definition at line 774 of file test_descr.py.

00774 
00775     def test_consistency_with_epg(self):
00776         # Testing consistency with EPG...
00777         class Pane(object): pass
00778         class ScrollingMixin(object): pass
00779         class EditingMixin(object): pass
00780         class ScrollablePane(Pane,ScrollingMixin): pass
00781         class EditablePane(Pane,EditingMixin): pass
00782         class EditableScrollablePane(ScrollablePane,EditablePane): pass
00783 
00784         self.assertEqual(EditableScrollablePane.__mro__,
00785               (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
00786                 ScrollingMixin, EditingMixin, object))

Here is the call graph for this function:

Definition at line 3454 of file test_descr.py.

03454 
03455     def test_copy_setstate(self):
03456         # Testing that copy.*copy() correctly uses __setstate__...
03457         import copy
03458         class C(object):
03459             def __init__(self, foo=None):
03460                 self.foo = foo
03461                 self.__foo = foo
03462             def setfoo(self, foo=None):
03463                 self.foo = foo
03464             def getfoo(self):
03465                 return self.__foo
03466             def __getstate__(self):
03467                 return [self.foo]
03468             def __setstate__(self_, lst):
03469                 self.assertEqual(len(lst), 1)
03470                 self_.__foo = self_.foo = lst[0]
03471         a = C(42)
03472         a.setfoo(24)
03473         self.assertEqual(a.foo, 24)
03474         self.assertEqual(a.getfoo(), 42)
03475         b = copy.copy(a)
03476         self.assertEqual(b.foo, 24)
03477         self.assertEqual(b.getfoo(), 24)
03478         b = copy.deepcopy(a)
03479         self.assertEqual(b.foo, 24)
03480         self.assertEqual(b.getfoo(), 24)

Here is the call graph for this function:

Definition at line 3385 of file test_descr.py.

03385 
03386     def test_deepcopy_recursive(self):
03387         # Testing deepcopy of recursive objects...
03388         class Node:
03389             pass
03390         a = Node()
03391         b = Node()
03392         a.b = b
03393         b.a = a
03394         z = deepcopy(a) # This blew up before

Definition at line 3298 of file test_descr.py.

03298 
03299     def test_delete_hook(self):
03300         # Testing __del__ hook...
03301         log = []
03302         class C(object):
03303             def __del__(self):
03304                 log.append(1)
03305         c = C()
03306         self.assertEqual(log, [])
03307         del c
03308         support.gc_collect()
03309         self.assertEqual(log, [1])
03310 
03311         class D(object): pass
03312         d = D()
03313         try: del d[0]
03314         except TypeError: pass
03315         else: self.fail("invalid del() didn't raise TypeError")

Here is the call graph for this function:

Definition at line 2742 of file test_descr.py.

02742 
02743     def test_descrdoc(self):
02744         # Testing descriptor doc strings...
02745         from _io import FileIO
02746         def check(descr, what):
02747             self.assertEqual(descr.__doc__, what)
02748         check(FileIO.closed, "True if the file is closed") # getset descriptor
02749         check(complex.real, "the real part of a complex number") # member descriptor

Here is the call graph for this function:

Definition at line 704 of file test_descr.py.

00704 
00705     def test_diamond_inheritence(self):
00706         # Testing multiple inheritance special cases...
00707         class A(object):
00708             def spam(self): return "A"
00709         self.assertEqual(A().spam(), "A")
00710         class B(A):
00711             def boo(self): return "B"
00712             def spam(self): return "B"
00713         self.assertEqual(B().spam(), "B")
00714         self.assertEqual(B().boo(), "B")
00715         class C(A):
00716             def boo(self): return "C"
00717         self.assertEqual(C().spam(), "A")
00718         self.assertEqual(C().boo(), "C")
00719         class D(B, C): pass
00720         self.assertEqual(D().spam(), "B")
00721         self.assertEqual(D().boo(), "B")
00722         self.assertEqual(D.__mro__, (D, B, C, A, object))
00723         class E(C, B): pass
00724         self.assertEqual(E().spam(), "B")
00725         self.assertEqual(E().boo(), "C")
00726         self.assertEqual(E.__mro__, (E, C, B, A, object))
00727         # MRO order disagreement
00728         try:
00729             class F(D, E): pass
00730         except TypeError:
00731             pass
00732         else:
00733             self.fail("expected MRO order disagreement (F)")
00734         try:
00735             class G(E, D): pass
00736         except TypeError:
00737             pass
00738         else:
00739             self.fail("expected MRO order disagreement (G)")

Here is the call graph for this function:

Definition at line 1922 of file test_descr.py.

01922 
01923     def test_dict_constructors(self):
01924         # Testing dict constructor ...
01925         d = dict()
01926         self.assertEqual(d, {})
01927         d = dict({})
01928         self.assertEqual(d, {})
01929         d = dict({1: 2, 'a': 'b'})
01930         self.assertEqual(d, {1: 2, 'a': 'b'})
01931         self.assertEqual(d, dict(list(d.items())))
01932         self.assertEqual(d, dict(iter(d.items())))
01933         d = dict({'one':1, 'two':2})
01934         self.assertEqual(d, dict(one=1, two=2))
01935         self.assertEqual(d, dict(**d))
01936         self.assertEqual(d, dict({"one": 1}, two=2))
01937         self.assertEqual(d, dict([("two", 2)], one=1))
01938         self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
01939         self.assertEqual(d, dict(**d))
01940 
01941         for badarg in 0, 0, 0j, "0", [0], (0,):
01942             try:
01943                 dict(badarg)
01944             except TypeError:
01945                 pass
01946             except ValueError:
01947                 if badarg == "0":
01948                     # It's a sequence, and its elements are also sequences (gotta
01949                     # love strings <wink>), but they aren't of length 2, so this
01950                     # one seemed better as a ValueError than a TypeError.
01951                     pass
01952                 else:
01953                     self.fail("no TypeError from dict(%r)" % badarg)
01954             else:
01955                 self.fail("no TypeError from dict(%r)" % badarg)
01956 
01957         try:
01958             dict({}, {})
01959         except TypeError:
01960             pass
01961         else:
01962             self.fail("no TypeError from dict({}, {})")
01963 
01964         class Mapping:
01965             # Lacks a .keys() method; will be added later.
01966             dict = {1:2, 3:4, 'a':1j}
01967 
01968         try:
01969             dict(Mapping())
01970         except TypeError:
01971             pass
01972         else:
01973             self.fail("no TypeError from dict(incomplete mapping)")
01974 
01975         Mapping.keys = lambda self: list(self.dict.keys())
01976         Mapping.__getitem__ = lambda self, i: self.dict[i]
01977         d = dict(Mapping())
01978         self.assertEqual(d, Mapping.dict)
01979 
01980         # Init from sequence of iterable objects, each producing a 2-sequence.
01981         class AddressBookEntry:
01982             def __init__(self, first, last):
01983                 self.first = first
01984                 self.last = last
01985             def __iter__(self):
01986                 return iter([self.first, self.last])
01987 
01988         d = dict([AddressBookEntry('Tim', 'Warsaw'),
01989                   AddressBookEntry('Barry', 'Peters'),
01990                   AddressBookEntry('Tim', 'Peters'),
01991                   AddressBookEntry('Barry', 'Warsaw')])
01992         self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
01993 
01994         d = dict(zip(range(4), range(1, 5)))
01995         self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
01996 
01997         # Bad sequence lengths.
01998         for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
01999             try:
02000                 dict(bad)
02001             except ValueError:
02002                 pass
02003             else:
02004                 self.fail("no ValueError from dict(%r)" % bad)

Here is the call graph for this function:

Definition at line 2005 of file test_descr.py.

02005 
02006     def test_dir(self):
02007         # Testing dir() ...
02008         junk = 12
02009         self.assertEqual(dir(), ['junk', 'self'])
02010         del junk
02011 
02012         # Just make sure these don't blow up!
02013         for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
02014             dir(arg)
02015 
02016         # Test dir on new-style classes.  Since these have object as a
02017         # base class, a lot more gets sucked in.
02018         def interesting(strings):
02019             return [s for s in strings if not s.startswith('_')]
02020 
02021         class C(object):
02022             Cdata = 1
02023             def Cmethod(self): pass
02024 
02025         cstuff = ['Cdata', 'Cmethod']
02026         self.assertEqual(interesting(dir(C)), cstuff)
02027 
02028         c = C()
02029         self.assertEqual(interesting(dir(c)), cstuff)
02030         ## self.assertIn('__self__', dir(C.Cmethod))
02031 
02032         c.cdata = 2
02033         c.cmethod = lambda self: 0
02034         self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
02035         ## self.assertIn('__self__', dir(c.Cmethod))
02036 
02037         class A(C):
02038             Adata = 1
02039             def Amethod(self): pass
02040 
02041         astuff = ['Adata', 'Amethod'] + cstuff
02042         self.assertEqual(interesting(dir(A)), astuff)
02043         ## self.assertIn('__self__', dir(A.Amethod))
02044         a = A()
02045         self.assertEqual(interesting(dir(a)), astuff)
02046         a.adata = 42
02047         a.amethod = lambda self: 3
02048         self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
02049         ## self.assertIn('__self__', dir(a.Amethod))
02050 
02051         # Try a module subclass.
02052         class M(type(sys)):
02053             pass
02054         minstance = M("m")
02055         minstance.b = 2
02056         minstance.a = 1
02057         names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
02058         self.assertEqual(names, ['a', 'b'])
02059 
02060         class M2(M):
02061             def getdict(self):
02062                 return "Not a dict!"
02063             __dict__ = property(getdict)
02064 
02065         m2instance = M2("m2")
02066         m2instance.b = 2
02067         m2instance.a = 1
02068         self.assertEqual(m2instance.__dict__, "Not a dict!")
02069         try:
02070             dir(m2instance)
02071         except TypeError:
02072             pass
02073 
02074         # Two essentially featureless objects, just inheriting stuff from
02075         # object.
02076         self.assertEqual(dir(NotImplemented), dir(Ellipsis))
02077         if support.check_impl_detail():
02078             # None differs in PyPy: it has a __nonzero__
02079             self.assertEqual(dir(None), dir(Ellipsis))
02080 
02081         # Nasty test case for proxied objects
02082         class Wrapper(object):
02083             def __init__(self, obj):
02084                 self.__obj = obj
02085             def __repr__(self):
02086                 return "Wrapper(%s)" % repr(self.__obj)
02087             def __getitem__(self, key):
02088                 return Wrapper(self.__obj[key])
02089             def __len__(self):
02090                 return len(self.__obj)
02091             def __getattr__(self, name):
02092                 return Wrapper(getattr(self.__obj, name))
02093 
02094         class C(object):
02095             def __getclass(self):
02096                 return Wrapper(type(self))
02097             __class__ = property(__getclass)
02098 
02099         dir(C()) # This used to segfault

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 2750 of file test_descr.py.

02750 
02751     def test_doc_descriptor(self):
02752         # Testing __doc__ descriptor...
02753         # SF bug 542984
02754         class DocDescr(object):
02755             def __get__(self, object, otype):
02756                 if object:
02757                     object = object.__class__.__name__ + ' instance'
02758                 if otype:
02759                     otype = otype.__name__
02760                 return 'object=%s; type=%s' % (object, otype)
02761         class OldClass:
02762             __doc__ = DocDescr()
02763         class NewClass(object):
02764             __doc__ = DocDescr()
02765         self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
02766         self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
02767         self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
02768         self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')

Here is the call graph for this function:

Definition at line 1106 of file test_descr.py.

01106 
01107     def test_dynamics(self):
01108         # Testing class attribute propagation...
01109         class D(object):
01110             pass
01111         class E(D):
01112             pass
01113         class F(D):
01114             pass
01115         D.foo = 1
01116         self.assertEqual(D.foo, 1)
01117         # Test that dynamic attributes are inherited
01118         self.assertEqual(E.foo, 1)
01119         self.assertEqual(F.foo, 1)
01120         # Test dynamic instances
01121         class C(object):
01122             pass
01123         a = C()
01124         self.assertFalse(hasattr(a, "foobar"))
01125         C.foobar = 2
01126         self.assertEqual(a.foobar, 2)
01127         C.method = lambda self: 42
01128         self.assertEqual(a.method(), 42)
01129         C.__repr__ = lambda self: "C()"
01130         self.assertEqual(repr(a), "C()")
01131         C.__int__ = lambda self: 100
01132         self.assertEqual(int(a), 100)
01133         self.assertEqual(a.foobar, 2)
01134         self.assertFalse(hasattr(a, "spam"))
01135         def mygetattr(self, name):
01136             if name == "spam":
01137                 return "spam"
01138             raise AttributeError
01139         C.__getattr__ = mygetattr
01140         self.assertEqual(a.spam, "spam")
01141         a.new = 12
01142         self.assertEqual(a.new, 12)
01143         def mysetattr(self, name, value):
01144             if name == "spam":
01145                 raise AttributeError
01146             return object.__setattr__(self, name, value)
01147         C.__setattr__ = mysetattr
01148         try:
01149             a.spam = "not spam"
01150         except AttributeError:
01151             pass
01152         else:
01153             self.fail("expected AttributeError")
01154         self.assertEqual(a.spam, "spam")
01155         class D(C):
01156             pass
01157         d = D()
01158         d.foo = 1
01159         self.assertEqual(d.foo, 1)
01160 
01161         # Test handling of int*seq and seq*int
01162         class I(int):
01163             pass
01164         self.assertEqual("a"*I(2), "aa")
01165         self.assertEqual(I(2)*"a", "aa")
01166         self.assertEqual(2*I(3), 6)
01167         self.assertEqual(I(3)*2, 6)
01168         self.assertEqual(I(3)*I(2), 6)
01169 
01170         # Test comparison of classes with dynamic metaclasses
01171         class dynamicmetaclass(type):
01172             pass
01173         class someclass(metaclass=dynamicmetaclass):
01174             pass
01175         self.assertNotEqual(someclass, object)

Definition at line 1176 of file test_descr.py.

01176 
01177     def test_errors(self):
01178         # Testing errors...
01179         try:
01180             class C(list, dict):
01181                 pass
01182         except TypeError:
01183             pass
01184         else:
01185             self.fail("inheritance from both list and dict should be illegal")
01186 
01187         try:
01188             class C(object, None):
01189                 pass
01190         except TypeError:
01191             pass
01192         else:
01193             self.fail("inheritance from non-type should be illegal")
01194         class Classic:
01195             pass
01196 
01197         try:
01198             class C(type(len)):
01199                 pass
01200         except TypeError:
01201             pass
01202         else:
01203             self.fail("inheritance from CFunction should be illegal")
01204 
01205         try:
01206             class C(object):
01207                 __slots__ = 1
01208         except TypeError:
01209             pass
01210         else:
01211             self.fail("__slots__ = 1 should be illegal")
01212 
01213         try:
01214             class C(object):
01215                 __slots__ = [1]
01216         except TypeError:
01217             pass
01218         else:
01219             self.fail("__slots__ = [1] should be illegal")
01220 
01221         class M1(type):
01222             pass
01223         class M2(type):
01224             pass
01225         class A1(object, metaclass=M1):
01226             pass
01227         class A2(object, metaclass=M2):
01228             pass
01229         try:
01230             class B(A1, A2):
01231                 pass
01232         except TypeError:
01233             pass
01234         else:
01235             self.fail("finding the most derived metaclass should have failed")

Definition at line 741 of file test_descr.py.

00741 
00742     def test_ex5_from_c3_switch(self):
00743         # Testing ex5 from C3 switch discussion...
00744         class A(object): pass
00745         class B(object): pass
00746         class C(object): pass
00747         class X(A): pass
00748         class Y(A): pass
00749         class Z(X,B,Y,C): pass
00750         self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))

Here is the call graph for this function:

Definition at line 4005 of file test_descr.py.

04005 
04006     def test_file_fault(self):
04007         # Testing sys.stdout is changed in getattr...
04008         test_stdout = sys.stdout
04009         class StdoutGuard:
04010             def __getattr__(self, attr):
04011                 sys.stdout = sys.__stdout__
04012                 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
04013         sys.stdout = StdoutGuard()
04014         try:
04015             print("Oops!")
04016         except RuntimeError:
04017             pass
04018         finally:
04019             sys.stdout = test_stdout

Here is the call graph for this function:

Definition at line 3407 of file test_descr.py.

03407 
03408     def test_funny_new(self):
03409         # Testing __new__ returning something unexpected...
03410         class C(object):
03411             def __new__(cls, arg):
03412                 if isinstance(arg, str): return [1, 2, 3]
03413                 elif isinstance(arg, int): return object.__new__(D)
03414                 else: return object.__new__(cls)
03415         class D(C):
03416             def __init__(self, arg):
03417                 self.foo = arg
03418         self.assertEqual(C("1"), [1, 2, 3])
03419         self.assertEqual(D("1"), [1, 2, 3])
03420         d = D(None)
03421         self.assertEqual(d.foo, None)
03422         d = C(1)
03423         self.assertIsInstance(d, D)
03424         self.assertEqual(d.foo, 1)
03425         d = D(1)
03426         self.assertIsInstance(d, D)
03427         self.assertEqual(d.foo, 1)

Here is the call graph for this function:

Definition at line 4188 of file test_descr.py.

04188 
04189     def test_getattr_hooks(self):
04190         # issue 4230
04191 
04192         class Descriptor(object):
04193             counter = 0
04194             def __get__(self, obj, objtype=None):
04195                 def getter(name):
04196                     self.counter += 1
04197                     raise AttributeError(name)
04198                 return getter
04199 
04200         descr = Descriptor()
04201         class A(object):
04202             __getattribute__ = descr
04203         class B(object):
04204             __getattr__ = descr
04205         class C(object):
04206             __getattribute__ = descr
04207             __getattr__ = descr
04208 
04209         self.assertRaises(AttributeError, getattr, A(), "attr")
04210         self.assertEqual(descr.counter, 1)
04211         self.assertRaises(AttributeError, getattr, B(), "attr")
04212         self.assertEqual(descr.counter, 2)
04213         self.assertRaises(AttributeError, getattr, C(), "attr")
04214         self.assertEqual(descr.counter, 4)
04215 
04216         import gc
04217         class EvilGetattribute(object):
04218             # This used to segfault
04219             def __getattr__(self, name):
04220                 raise AttributeError(name)
04221             def __getattribute__(self, name):
04222                 del EvilGetattribute.__getattr__
04223                 for i in range(5):
04224                     gc.collect()
04225                 raise AttributeError(name)
04226 
04227         self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")

Here is the call graph for this function:

Definition at line 3316 of file test_descr.py.

03316 
03317     def test_hash_inheritance(self):
03318         # Testing hash of mutable subclasses...
03319 
03320         class mydict(dict):
03321             pass
03322         d = mydict()
03323         try:
03324             hash(d)
03325         except TypeError:
03326             pass
03327         else:
03328             self.fail("hash() of dict subclass should fail")
03329 
03330         class mylist(list):
03331             pass
03332         d = mylist()
03333         try:
03334             hash(d)
03335         except TypeError:
03336             pass
03337         else:
03338             self.fail("hash() of list subclass should fail")

Definition at line 3428 of file test_descr.py.

03428 
03429     def test_imul_bug(self):
03430         # Testing for __imul__ problems...
03431         # SF bug 544647
03432         class C(object):
03433             def __imul__(self, other):
03434                 return (self, other)
03435         x = C()
03436         y = x
03437         y *= 1.0
03438         self.assertEqual(y, (x, 1.0))
03439         y = x
03440         y *= 2
03441         self.assertEqual(y, (x, 2))
03442         y = x
03443         y *= 3
03444         self.assertEqual(y, (x, 3))
03445         y = x
03446         y *= 1<<100
03447         self.assertEqual(y, (x, 1<<100))
03448         y = x
03449         y *= None
03450         self.assertEqual(y, (x, None))
03451         y = x
03452         y *= "foo"
03453         self.assertEqual(y, (x, "foo"))

Here is the call graph for this function:

Definition at line 4049 of file test_descr.py.

04049 
04050     def test_init(self):
04051         # SF 1155938
04052         class Foo(object):
04053             def __init__(self):
04054                 return 10
04055         try:
04056             Foo()
04057         except TypeError:
04058             pass
04059         else:
04060             self.fail("did not test __init__() for None return")

Here is the call graph for this function:

Definition at line 3600 of file test_descr.py.

03600 
03601     def test_ipow(self):
03602         # Testing correct invocation of __ipow__...
03603         # [SF bug 620179]
03604         class C(object):
03605             def __ipow__(self, other):
03606                 pass
03607         a = C()
03608         a **= 2

Definition at line 3902 of file test_descr.py.

03902 
03903     def test_isinst_isclass(self):
03904         # Testing proxy isinstance() and isclass()...
03905         class Proxy(object):
03906             def __init__(self, obj):
03907                 self.__obj = obj
03908             def __getattribute__(self, name):
03909                 if name.startswith("_Proxy__"):
03910                     return object.__getattribute__(self, name)
03911                 else:
03912                     return getattr(self.__obj, name)
03913         # Test with a classic class
03914         class C:
03915             pass
03916         a = C()
03917         pa = Proxy(a)
03918         self.assertIsInstance(a, C)  # Baseline
03919         self.assertIsInstance(pa, C) # Test
03920         # Test with a classic subclass
03921         class D(C):
03922             pass
03923         a = D()
03924         pa = Proxy(a)
03925         self.assertIsInstance(a, C)  # Baseline
03926         self.assertIsInstance(pa, C) # Test
03927         # Test with a new-style class
03928         class C(object):
03929             pass
03930         a = C()
03931         pa = Proxy(a)
03932         self.assertIsInstance(a, C)  # Baseline
03933         self.assertIsInstance(pa, C) # Test
03934         # Test with a new-style subclass
03935         class D(C):
03936             pass
03937         a = D()
03938         pa = Proxy(a)
03939         self.assertIsInstance(a, C)  # Baseline
03940         self.assertIsInstance(pa, C) # Test

Here is the call graph for this function:

Definition at line 3277 of file test_descr.py.

03277 
03278     def test_keyword_arguments(self):
03279         # Testing keyword arguments to __init__, __call__...
03280         def f(a): return a
03281         self.assertEqual(f.__call__(a=42), 42)
03282         a = []
03283         list.__init__(a, sequence=[0, 1, 2])
03284         self.assertEqual(a, [0, 1, 2])

Here is the call graph for this function:

Definition at line 2548 of file test_descr.py.

02548 
02549     def test_keywords(self):
02550         # Testing keyword args to basic type constructors ...
02551         self.assertEqual(int(x=1), 1)
02552         self.assertEqual(float(x=2), 2.0)
02553         self.assertEqual(int(x=3), 3)
02554         self.assertEqual(complex(imag=42, real=666), complex(666, 42))
02555         self.assertEqual(str(object=500), '500')
02556         self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
02557         self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
02558         self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
02559         # note: as of Python 2.3, dict() no longer has an "items" keyword arg
02560 
02561         for constructor in (int, float, int, complex, str, str,
02562                             tuple, list):
02563             try:
02564                 constructor(bogus_keyword_arg=1)
02565             except TypeError:
02566                 pass
02567             else:
02568                 self.fail("expected TypeError from bogus keyword argument to %r"
02569                             % constructor)

Here is the call graph for this function:

Definition at line 455 of file test_descr.py.

00455 
00456     def test_metaclass(self):
00457         # Testing metaclasses...
00458         class C(metaclass=type):
00459             def __init__(self):
00460                 self.__state = 0
00461             def getstate(self):
00462                 return self.__state
00463             def setstate(self, state):
00464                 self.__state = state
00465         a = C()
00466         self.assertEqual(a.getstate(), 0)
00467         a.setstate(10)
00468         self.assertEqual(a.getstate(), 10)
00469         class _metaclass(type):
00470             def myself(cls): return cls
00471         class D(metaclass=_metaclass):
00472             pass
00473         self.assertEqual(D.myself(), D)
00474         d = D()
00475         self.assertEqual(d.__class__, D)
00476         class M1(type):
00477             def __new__(cls, name, bases, dict):
00478                 dict['__spam__'] = 1
00479                 return type.__new__(cls, name, bases, dict)
00480         class C(metaclass=M1):
00481             pass
00482         self.assertEqual(C.__spam__, 1)
00483         c = C()
00484         self.assertEqual(c.__spam__, 1)
00485 
00486         class _instance(object):
00487             pass
00488         class M2(object):
00489             @staticmethod
00490             def __new__(cls, name, bases, dict):
00491                 self = object.__new__(cls)
00492                 self.name = name
00493                 self.bases = bases
00494                 self.dict = dict
00495                 return self
00496             def __call__(self):
00497                 it = _instance()
00498                 # Early binding of methods
00499                 for key in self.dict:
00500                     if key.startswith("__"):
00501                         continue
00502                     setattr(it, key, self.dict[key].__get__(it, self))
00503                 return it
00504         class C(metaclass=M2):
00505             def spam(self):
00506                 return 42
00507         self.assertEqual(C.name, 'C')
00508         self.assertEqual(C.bases, ())
00509         self.assertIn('spam', C.dict)
00510         c = C()
00511         self.assertEqual(c.spam(), 42)
00512 
00513         # More metaclass examples
00514 
00515         class autosuper(type):
00516             # Automatically add __super to the class
00517             # This trick only works for dynamic classes
00518             def __new__(metaclass, name, bases, dict):
00519                 cls = super(autosuper, metaclass).__new__(metaclass,
00520                                                           name, bases, dict)
00521                 # Name mangling for __super removes leading underscores
00522                 while name[:1] == "_":
00523                     name = name[1:]
00524                 if name:
00525                     name = "_%s__super" % name
00526                 else:
00527                     name = "__super"
00528                 setattr(cls, name, super(cls))
00529                 return cls
00530         class A(metaclass=autosuper):
00531             def meth(self):
00532                 return "A"
00533         class B(A):
00534             def meth(self):
00535                 return "B" + self.__super.meth()
00536         class C(A):
00537             def meth(self):
00538                 return "C" + self.__super.meth()
00539         class D(C, B):
00540             def meth(self):
00541                 return "D" + self.__super.meth()
00542         self.assertEqual(D().meth(), "DCBA")
00543         class E(B, C):
00544             def meth(self):
00545                 return "E" + self.__super.meth()
00546         self.assertEqual(E().meth(), "EBCA")
00547 
00548         class autoproperty(type):
00549             # Automatically create property attributes when methods
00550             # named _get_x and/or _set_x are found
00551             def __new__(metaclass, name, bases, dict):
00552                 hits = {}
00553                 for key, val in dict.items():
00554                     if key.startswith("_get_"):
00555                         key = key[5:]
00556                         get, set = hits.get(key, (None, None))
00557                         get = val
00558                         hits[key] = get, set
00559                     elif key.startswith("_set_"):
00560                         key = key[5:]
00561                         get, set = hits.get(key, (None, None))
00562                         set = val
00563                         hits[key] = get, set
00564                 for key, (get, set) in hits.items():
00565                     dict[key] = property(get, set)
00566                 return super(autoproperty, metaclass).__new__(metaclass,
00567                                                             name, bases, dict)
00568         class A(metaclass=autoproperty):
00569             def _get_x(self):
00570                 return -self.__x
00571             def _set_x(self, x):
00572                 self.__x = -x
00573         a = A()
00574         self.assertTrue(not hasattr(a, "x"))
00575         a.x = 12
00576         self.assertEqual(a.x, 12)
00577         self.assertEqual(a._A__x, -12)
00578 
00579         class multimetaclass(autoproperty, autosuper):
00580             # Merge of multiple cooperating metaclasses
00581             pass
00582         class A(metaclass=multimetaclass):
00583             def _get_x(self):
00584                 return "A"
00585         class B(A):
00586             def _get_x(self):
00587                 return "B" + self.__super._get_x()
00588         class C(A):
00589             def _get_x(self):
00590                 return "C" + self.__super._get_x()
00591         class D(C, B):
00592             def _get_x(self):
00593                 return "D" + self.__super._get_x()
00594         self.assertEqual(D().x, "DCBA")
00595 
00596         # Make sure type(x) doesn't call x.__class__.__init__
00597         class T(type):
00598             counter = 0
00599             def __init__(self, *args):
00600                 T.counter += 1
00601         class C(metaclass=T):
00602             pass
00603         self.assertEqual(T.counter, 1)
00604         a = C()
00605         self.assertEqual(type(a), C)
00606         self.assertEqual(T.counter, 1)
00607 
00608         class C(object): pass
00609         c = C()
00610         try: c()
00611         except TypeError: pass
00612         else: self.fail("calling object w/o call method should raise "
00613                         "TypeError")
00614 
00615         # Testing code to find most derived baseclass
00616         class A(type):
00617             def __new__(*args, **kwargs):
00618                 return type.__new__(*args, **kwargs)
00619 
00620         class B(object):
00621             pass
00622 
00623         class C(object, metaclass=A):
00624             pass
00625 
00626         # The most derived metaclass of D is A rather than type.
00627         class D(B, C):
00628             pass

Here is the call graph for this function:

Definition at line 3859 of file test_descr.py.

03859 
03860     def test_meth_class_get(self):
03861         # Testing __get__ method of METH_CLASS C methods...
03862         # Full coverage of descrobject.c::classmethod_get()
03863 
03864         # Baseline
03865         arg = [1, 2, 3]
03866         res = {1: None, 2: None, 3: None}
03867         self.assertEqual(dict.fromkeys(arg), res)
03868         self.assertEqual({}.fromkeys(arg), res)
03869 
03870         # Now get the descriptor
03871         descr = dict.__dict__["fromkeys"]
03872 
03873         # More baseline using the descriptor directly
03874         self.assertEqual(descr.__get__(None, dict)(arg), res)
03875         self.assertEqual(descr.__get__({})(arg), res)
03876 
03877         # Now check various error cases
03878         try:
03879             descr.__get__(None, None)
03880         except TypeError:
03881             pass
03882         else:
03883             self.fail("shouldn't have allowed descr.__get__(None, None)")
03884         try:
03885             descr.__get__(42)
03886         except TypeError:
03887             pass
03888         else:
03889             self.fail("shouldn't have allowed descr.__get__(42)")
03890         try:
03891             descr.__get__(None, 42)
03892         except TypeError:
03893             pass
03894         else:
03895             self.fail("shouldn't have allowed descr.__get__(None, 42)")
03896         try:
03897             descr.__get__(None, int)
03898         except TypeError:
03899             pass
03900         else:
03901             self.fail("shouldn't have allowed descr.__get__(None, int)")

Here is the call graph for this function:

Definition at line 4061 of file test_descr.py.

04061 
04062     def test_method_wrapper(self):
04063         # Testing method-wrapper objects...
04064         # <type 'method-wrapper'> did not support any reflection before 2.5
04065 
04066         # XXX should methods really support __eq__?
04067 
04068         l = []
04069         self.assertEqual(l.__add__, l.__add__)
04070         self.assertEqual(l.__add__, [].__add__)
04071         self.assertTrue(l.__add__ != [5].__add__)
04072         self.assertTrue(l.__add__ != l.__mul__)
04073         self.assertTrue(l.__add__.__name__ == '__add__')
04074         if hasattr(l.__add__, '__self__'):
04075             # CPython
04076             self.assertTrue(l.__add__.__self__ is l)
04077             self.assertTrue(l.__add__.__objclass__ is list)
04078         else:
04079             # Python implementations where [].__add__ is a normal bound method
04080             self.assertTrue(l.__add__.im_self is l)
04081             self.assertTrue(l.__add__.im_class is list)
04082         self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
04083         try:
04084             hash(l.__add__)
04085         except TypeError:
04086             pass
04087         else:
04088             self.fail("no TypeError from hash([].__add__)")
04089 
04090         t = ()
04091         t += (7,)
04092         self.assertEqual(t.__add__, (7,).__add__)
04093         self.assertEqual(hash(t.__add__), hash((7,).__add__))

Here is the call graph for this function:

Definition at line 1512 of file test_descr.py.

01512 
01513     def test_methods(self):
01514         # Testing methods...
01515         class C(object):
01516             def __init__(self, x):
01517                 self.x = x
01518             def foo(self):
01519                 return self.x
01520         c1 = C(1)
01521         self.assertEqual(c1.foo(), 1)
01522         class D(C):
01523             boo = C.foo
01524             goo = c1.foo
01525         d2 = D(2)
01526         self.assertEqual(d2.foo(), 2)
01527         self.assertEqual(d2.boo(), 2)
01528         self.assertEqual(d2.goo(), 1)
01529         class E(object):
01530             foo = C.foo
01531         self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
01532         self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))

Here is the call graph for this function:

Definition at line 629 of file test_descr.py.

00629 
00630     def test_module_subclasses(self):
00631         # Testing Python subclass of module...
00632         log = []
00633         MT = type(sys)
00634         class MM(MT):
00635             def __init__(self, name):
00636                 MT.__init__(self, name)
00637             def __getattribute__(self, name):
00638                 log.append(("getattr", name))
00639                 return MT.__getattribute__(self, name)
00640             def __setattr__(self, name, value):
00641                 log.append(("setattr", name, value))
00642                 MT.__setattr__(self, name, value)
00643             def __delattr__(self, name):
00644                 log.append(("delattr", name))
00645                 MT.__delattr__(self, name)
00646         a = MM("a")
00647         a.foo = 12
00648         x = a.foo
00649         del a.foo
00650         self.assertEqual(log, [("setattr", "foo", 12),
00651                                ("getattr", "foo"),
00652                                ("delattr", "foo")])
00653 
00654         # http://python.org/sf/1174712
00655         try:
00656             class Module(types.ModuleType, str):
00657                 pass
00658         except TypeError:
00659             pass
00660         else:
00661             self.fail("inheriting from ModuleType and str at the same time "
00662                       "should fail")

Here is the call graph for this function:

Definition at line 753 of file test_descr.py.

00753 
00754     def test_monotonicity(self):
00755         # Testing MRO monotonicity...
00756         class Boat(object): pass
00757         class DayBoat(Boat): pass
00758         class WheelBoat(Boat): pass
00759         class EngineLess(DayBoat): pass
00760         class SmallMultihull(DayBoat): pass
00761         class PedalWheelBoat(EngineLess,WheelBoat): pass
00762         class SmallCatamaran(SmallMultihull): pass
00763         class Pedalo(PedalWheelBoat,SmallCatamaran): pass
00764 
00765         self.assertEqual(PedalWheelBoat.__mro__,
00766               (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
00767         self.assertEqual(SmallCatamaran.__mro__,
00768               (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
00769         self.assertEqual(Pedalo.__mro__,
00770               (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
00771                SmallMultihull, DayBoat, WheelBoat, Boat, object))

Here is the call graph for this function:

Definition at line 787 of file test_descr.py.

00787 
00788     def test_mro_disagreement(self):
00789         # Testing error messages for MRO disagreement...
00790         mro_err_msg = """Cannot create a consistent method resolution
00791 order (MRO) for bases """
00792 
00793         def raises(exc, expected, callable, *args):
00794             try:
00795                 callable(*args)
00796             except exc as msg:
00797                 # the exact msg is generally considered an impl detail
00798                 if support.check_impl_detail():
00799                     if not str(msg).startswith(expected):
00800                         self.fail("Message %r, expected %r" %
00801                                   (str(msg), expected))
00802             else:
00803                 self.fail("Expected %s" % exc)
00804 
00805         class A(object): pass
00806         class B(A): pass
00807         class C(object): pass
00808 
00809         # Test some very simple errors
00810         raises(TypeError, "duplicate base class A",
00811                type, "X", (A, A), {})
00812         raises(TypeError, mro_err_msg,
00813                type, "X", (A, B), {})
00814         raises(TypeError, mro_err_msg,
00815                type, "X", (A, C, B), {})
00816         # Test a slightly more complex error
00817         class GridLayout(object): pass
00818         class HorizontalGrid(GridLayout): pass
00819         class VerticalGrid(GridLayout): pass
00820         class HVGrid(HorizontalGrid, VerticalGrid): pass
00821         class VHGrid(VerticalGrid, HorizontalGrid): pass
00822         raises(TypeError, mro_err_msg,
00823                type, "ConfusedGrid", (HVGrid, VHGrid), {})

Here is the call graph for this function:

Definition at line 663 of file test_descr.py.

00663 
00664     def test_multiple_inheritance(self):
00665         # Testing multiple inheritance...
00666         class C(object):
00667             def __init__(self):
00668                 self.__state = 0
00669             def getstate(self):
00670                 return self.__state
00671             def setstate(self, state):
00672                 self.__state = state
00673         a = C()
00674         self.assertEqual(a.getstate(), 0)
00675         a.setstate(10)
00676         self.assertEqual(a.getstate(), 10)
00677         class D(dict, C):
00678             def __init__(self):
00679                 type({}).__init__(self)
00680                 C.__init__(self)
00681         d = D()
00682         self.assertEqual(list(d.keys()), [])
00683         d["hello"] = "world"
00684         self.assertEqual(list(d.items()), [("hello", "world")])
00685         self.assertEqual(d["hello"], "world")
00686         self.assertEqual(d.getstate(), 0)
00687         d.setstate(10)
00688         self.assertEqual(d.getstate(), 10)
00689         self.assertEqual(D.__mro__, (D, dict, C, object))
00690 
00691         # SF bug #442833
00692         class Node(object):
00693             def __int__(self):
00694                 return int(self.foo())
00695             def foo(self):
00696                 return "23"
00697         class Frag(Node, list):
00698             def foo(self):
00699                 return "42"
00700         self.assertEqual(Node().__int__(), 23)
00701         self.assertEqual(int(Node()), 23)
00702         self.assertEqual(Frag().__int__(), 42)
00703         self.assertEqual(int(Frag()), 42)

Here is the call graph for this function:

Definition at line 3609 of file test_descr.py.

03609 
03610     def test_mutable_bases(self):
03611         # Testing mutable bases...
03612 
03613         # stuff that should work:
03614         class C(object):
03615             pass
03616         class C2(object):
03617             def __getattribute__(self, attr):
03618                 if attr == 'a':
03619                     return 2
03620                 else:
03621                     return super(C2, self).__getattribute__(attr)
03622             def meth(self):
03623                 return 1
03624         class D(C):
03625             pass
03626         class E(D):
03627             pass
03628         d = D()
03629         e = E()
03630         D.__bases__ = (C,)
03631         D.__bases__ = (C2,)
03632         self.assertEqual(d.meth(), 1)
03633         self.assertEqual(e.meth(), 1)
03634         self.assertEqual(d.a, 2)
03635         self.assertEqual(e.a, 2)
03636         self.assertEqual(C2.__subclasses__(), [D])
03637 
03638         try:
03639             del D.__bases__
03640         except (TypeError, AttributeError):
03641             pass
03642         else:
03643             self.fail("shouldn't be able to delete .__bases__")
03644 
03645         try:
03646             D.__bases__ = ()
03647         except TypeError as msg:
03648             if str(msg) == "a new-style class can't have only classic bases":
03649                 self.fail("wrong error message for .__bases__ = ()")
03650         else:
03651             self.fail("shouldn't be able to set .__bases__ to ()")
03652 
03653         try:
03654             D.__bases__ = (D,)
03655         except TypeError:
03656             pass
03657         else:
03658             # actually, we'll have crashed by here...
03659             self.fail("shouldn't be able to create inheritance cycles")
03660 
03661         try:
03662             D.__bases__ = (C, C)
03663         except TypeError:
03664             pass
03665         else:
03666             self.fail("didn't detect repeated base classes")
03667 
03668         try:
03669             D.__bases__ = (E,)
03670         except TypeError:
03671             pass
03672         else:
03673             self.fail("shouldn't be able to create inheritance cycles")

Definition at line 3769 of file test_descr.py.

03769 
03770     def test_mutable_bases_catch_mro_conflict(self):
03771         # Testing mutable bases catch mro conflict...
03772         class A(object):
03773             pass
03774 
03775         class B(object):
03776             pass
03777 
03778         class C(A, B):
03779             pass
03780 
03781         class D(A, B):
03782             pass
03783 
03784         class E(C, D):
03785             pass
03786 
03787         try:
03788             C.__bases__ = (B, A)
03789         except TypeError:
03790             pass
03791         else:
03792             self.fail("didn't catch MRO conflict")

Definition at line 3715 of file test_descr.py.

03715 
03716     def test_mutable_bases_with_failing_mro(self):
03717         # Testing mutable bases with failing mro...
03718         class WorkOnce(type):
03719             def __new__(self, name, bases, ns):
03720                 self.flag = 0
03721                 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
03722             def mro(self):
03723                 if self.flag > 0:
03724                     raise RuntimeError("bozo")
03725                 else:
03726                     self.flag += 1
03727                     return type.mro(self)
03728 
03729         class WorkAlways(type):
03730             def mro(self):
03731                 # this is here to make sure that .mro()s aren't called
03732                 # with an exception set (which was possible at one point).
03733                 # An error message will be printed in a debug build.
03734                 # What's a good way to test for this?
03735                 return type.mro(self)
03736 
03737         class C(object):
03738             pass
03739 
03740         class C2(object):
03741             pass
03742 
03743         class D(C):
03744             pass
03745 
03746         class E(D):
03747             pass
03748 
03749         class F(D, metaclass=WorkOnce):
03750             pass
03751 
03752         class G(D, metaclass=WorkAlways):
03753             pass
03754 
03755         # Immediate subclasses have their mro's adjusted in alphabetical
03756         # order, so E's will get adjusted before adjusting F's fails.  We
03757         # check here that E's gets restored.
03758 
03759         E_mro_before = E.__mro__
03760         D_mro_before = D.__mro__
03761 
03762         try:
03763             D.__bases__ = (C2,)
03764         except RuntimeError:
03765             self.assertEqual(E.__mro__, E_mro_before)
03766             self.assertEqual(D.__mro__, D_mro_before)
03767         else:
03768             self.fail("exception not propagated")

Definition at line 3793 of file test_descr.py.

03793 
03794     def test_mutable_names(self):
03795         # Testing mutable names...
03796         class C(object):
03797             pass
03798 
03799         # C.__module__ could be 'test_descr' or '__main__'
03800         mod = C.__module__
03801 
03802         C.__name__ = 'D'
03803         self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
03804 
03805         C.__name__ = 'D.E'
03806         self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))

Definition at line 1380 of file test_descr.py.

01380 
01381     def test_newslots(self):
01382         # Testing __new__ slot override...
01383         class C(list):
01384             def __new__(cls):
01385                 self = list.__new__(cls)
01386                 self.foo = 1
01387                 return self
01388             def __init__(self):
01389                 self.foo = self.foo + 2
01390         a = C()
01391         self.assertEqual(a.foo, 3)
01392         self.assertEqual(a.__class__, C)
01393         class D(C):
01394             pass
01395         b = D()
01396         self.assertEqual(b.foo, 3)
01397         self.assertEqual(b.__class__, D)

Definition at line 4094 of file test_descr.py.

04094 
04095     def test_not_implemented(self):
04096         # Testing NotImplemented...
04097         # all binary methods should be able to return a NotImplemented
04098         import operator
04099 
04100         def specialmethod(self, other):
04101             return NotImplemented
04102 
04103         def check(expr, x, y):
04104             try:
04105                 exec(expr, {'x': x, 'y': y, 'operator': operator})
04106             except TypeError:
04107                 pass
04108             else:
04109                 self.fail("no TypeError from %r" % (expr,))
04110 
04111         N1 = sys.maxsize + 1    # might trigger OverflowErrors instead of
04112                                 # TypeErrors
04113         N2 = sys.maxsize         # if sizeof(int) < sizeof(long), might trigger
04114                                 #   ValueErrors instead of TypeErrors
04115         for name, expr, iexpr in [
04116                 ('__add__',      'x + y',                   'x += y'),
04117                 ('__sub__',      'x - y',                   'x -= y'),
04118                 ('__mul__',      'x * y',                   'x *= y'),
04119                 ('__truediv__',  'operator.truediv(x, y)',  None),
04120                 ('__floordiv__', 'operator.floordiv(x, y)', None),
04121                 ('__div__',      'x / y',                   'x /= y'),
04122                 ('__mod__',      'x % y',                   'x %= y'),
04123                 ('__divmod__',   'divmod(x, y)',            None),
04124                 ('__pow__',      'x ** y',                  'x **= y'),
04125                 ('__lshift__',   'x << y',                  'x <<= y'),
04126                 ('__rshift__',   'x >> y',                  'x >>= y'),
04127                 ('__and__',      'x & y',                   'x &= y'),
04128                 ('__or__',       'x | y',                   'x |= y'),
04129                 ('__xor__',      'x ^ y',                   'x ^= y')]:
04130             rname = '__r' + name[2:]
04131             A = type('A', (), {name: specialmethod})
04132             a = A()
04133             check(expr, a, a)
04134             check(expr, a, N1)
04135             check(expr, a, N2)
04136             if iexpr:
04137                 check(iexpr, a, a)
04138                 check(iexpr, a, N1)
04139                 check(iexpr, a, N2)
04140                 iname = '__i' + name[2:]
04141                 C = type('C', (), {iname: specialmethod})
04142                 c = C()
04143                 check(iexpr, c, a)
04144                 check(iexpr, c, N1)
04145                 check(iexpr, c, N2)

Here is the call graph for this function:

Definition at line 824 of file test_descr.py.

00824 
00825     def test_object_class(self):
00826         # Testing object class...
00827         a = object()
00828         self.assertEqual(a.__class__, object)
00829         self.assertEqual(type(a), object)
00830         b = object()
00831         self.assertNotEqual(a, b)
00832         self.assertFalse(hasattr(a, "foo"))
00833         try:
00834             a.foo = 12
00835         except (AttributeError, TypeError):
00836             pass
00837         else:
00838             self.fail("object() should not allow setting a foo attribute")
00839         self.assertFalse(hasattr(object(), "__dict__"))
00840 
00841         class Cdict(object):
00842             pass
00843         x = Cdict()
00844         self.assertEqual(x.__dict__, {})
00845         x.foo = 1
00846         self.assertEqual(x.foo, 1)
00847         self.assertEqual(x.__dict__, {'foo': 1})

Here is the call graph for this function:

Definition at line 1463 of file test_descr.py.

01463 
01464     def test_overloading(self):
01465         # Testing operator overloading...
01466 
01467         class B(object):
01468             "Intermediate class because object doesn't have a __setattr__"
01469 
01470         class C(B):
01471             def __getattr__(self, name):
01472                 if name == "foo":
01473                     return ("getattr", name)
01474                 else:
01475                     raise AttributeError
01476             def __setattr__(self, name, value):
01477                 if name == "foo":
01478                     self.setattr = (name, value)
01479                 else:
01480                     return B.__setattr__(self, name, value)
01481             def __delattr__(self, name):
01482                 if name == "foo":
01483                     self.delattr = name
01484                 else:
01485                     return B.__delattr__(self, name)
01486 
01487             def __getitem__(self, key):
01488                 return ("getitem", key)
01489             def __setitem__(self, key, value):
01490                 self.setitem = (key, value)
01491             def __delitem__(self, key):
01492                 self.delitem = key
01493 
01494         a = C()
01495         self.assertEqual(a.foo, ("getattr", "foo"))
01496         a.foo = 12
01497         self.assertEqual(a.setattr, ("foo", 12))
01498         del a.foo
01499         self.assertEqual(a.delattr, "foo")
01500 
01501         self.assertEqual(a[12], ("getitem", 12))
01502         a[12] = 21
01503         self.assertEqual(a.setitem, (12, 21))
01504         del a[12]
01505         self.assertEqual(a.delitem, 12)
01506 
01507         self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
01508         a[0:10] = "foo"
01509         self.assertEqual(a.setitem, (slice(0, 10), "foo"))
01510         del a[0:10]
01511         self.assertEqual(a.delitem, (slice(0, 10)))

Definition at line 3052 of file test_descr.py.

03052 
03053     def test_pickle_slots(self):
03054         # Testing pickling of classes with __slots__ ...
03055         import pickle
03056         # Pickling of classes with __slots__ but without __getstate__ should fail
03057         # (if using protocol 0 or 1)
03058         global B, C, D, E
03059         class B(object):
03060             pass
03061         for base in [object, B]:
03062             class C(base):
03063                 __slots__ = ['a']
03064             class D(C):
03065                 pass
03066             try:
03067                 pickle.dumps(C(), 0)
03068             except TypeError:
03069                 pass
03070             else:
03071                 self.fail("should fail: pickle C instance - %s" % base)
03072             try:
03073                 pickle.dumps(C(), 0)
03074             except TypeError:
03075                 pass
03076             else:
03077                 self.fail("should fail: pickle D instance - %s" % base)
03078             # Give C a nice generic __getstate__ and __setstate__
03079             class C(base):
03080                 __slots__ = ['a']
03081                 def __getstate__(self):
03082                     try:
03083                         d = self.__dict__.copy()
03084                     except AttributeError:
03085                         d = {}
03086                     for cls in self.__class__.__mro__:
03087                         for sn in cls.__dict__.get('__slots__', ()):
03088                             try:
03089                                 d[sn] = getattr(self, sn)
03090                             except AttributeError:
03091                                 pass
03092                     return d
03093                 def __setstate__(self, d):
03094                     for k, v in list(d.items()):
03095                         setattr(self, k, v)
03096             class D(C):
03097                 pass
03098             # Now it should work
03099             x = C()
03100             y = pickle.loads(pickle.dumps(x))
03101             self.assertEqual(hasattr(y, 'a'), 0)
03102             x.a = 42
03103             y = pickle.loads(pickle.dumps(x))
03104             self.assertEqual(y.a, 42)
03105             x = D()
03106             x.a = 42
03107             x.b = 100
03108             y = pickle.loads(pickle.dumps(x))
03109             self.assertEqual(y.a + y.b, 142)
03110             # A subclass that adds a slot should also work
03111             class E(C):
03112                 __slots__ = ['b']
03113             x = E()
03114             x.a = 42
03115             x.b = "foo"
03116             y = pickle.loads(pickle.dumps(x))
03117             self.assertEqual(y.a, x.a)
03118             self.assertEqual(y.b, x.b)

Definition at line 2949 of file test_descr.py.

02949 
02950     def test_pickles(self):
02951         # Testing pickling and copying new-style classes and objects...
02952         import pickle
02953 
02954         def sorteditems(d):
02955             L = list(d.items())
02956             L.sort()
02957             return L
02958 
02959         global C
02960         class C(object):
02961             def __init__(self, a, b):
02962                 super(C, self).__init__()
02963                 self.a = a
02964                 self.b = b
02965             def __repr__(self):
02966                 return "C(%r, %r)" % (self.a, self.b)
02967 
02968         global C1
02969         class C1(list):
02970             def __new__(cls, a, b):
02971                 return super(C1, cls).__new__(cls)
02972             def __getnewargs__(self):
02973                 return (self.a, self.b)
02974             def __init__(self, a, b):
02975                 self.a = a
02976                 self.b = b
02977             def __repr__(self):
02978                 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
02979 
02980         global C2
02981         class C2(int):
02982             def __new__(cls, a, b, val=0):
02983                 return super(C2, cls).__new__(cls, val)
02984             def __getnewargs__(self):
02985                 return (self.a, self.b, int(self))
02986             def __init__(self, a, b, val=0):
02987                 self.a = a
02988                 self.b = b
02989             def __repr__(self):
02990                 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
02991 
02992         global C3
02993         class C3(object):
02994             def __init__(self, foo):
02995                 self.foo = foo
02996             def __getstate__(self):
02997                 return self.foo
02998             def __setstate__(self, foo):
02999                 self.foo = foo
03000 
03001         global C4classic, C4
03002         class C4classic: # classic
03003             pass
03004         class C4(C4classic, object): # mixed inheritance
03005             pass
03006 
03007         for bin in 0, 1:
03008             for cls in C, C1, C2:
03009                 s = pickle.dumps(cls, bin)
03010                 cls2 = pickle.loads(s)
03011                 self.assertTrue(cls2 is cls)
03012 
03013             a = C1(1, 2); a.append(42); a.append(24)
03014             b = C2("hello", "world", 42)
03015             s = pickle.dumps((a, b), bin)
03016             x, y = pickle.loads(s)
03017             self.assertEqual(x.__class__, a.__class__)
03018             self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
03019             self.assertEqual(y.__class__, b.__class__)
03020             self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
03021             self.assertEqual(repr(x), repr(a))
03022             self.assertEqual(repr(y), repr(b))
03023             # Test for __getstate__ and __setstate__ on new style class
03024             u = C3(42)
03025             s = pickle.dumps(u, bin)
03026             v = pickle.loads(s)
03027             self.assertEqual(u.__class__, v.__class__)
03028             self.assertEqual(u.foo, v.foo)
03029             # Test for picklability of hybrid class
03030             u = C4()
03031             u.foo = 42
03032             s = pickle.dumps(u, bin)
03033             v = pickle.loads(s)
03034             self.assertEqual(u.__class__, v.__class__)
03035             self.assertEqual(u.foo, v.foo)
03036 
03037         # Testing copy.deepcopy()
03038         import copy
03039         for cls in C, C1, C2:
03040             cls2 = copy.deepcopy(cls)
03041             self.assertTrue(cls2 is cls)
03042 
03043         a = C1(1, 2); a.append(42); a.append(24)
03044         b = C2("hello", "world", 42)
03045         x, y = copy.deepcopy((a, b))
03046         self.assertEqual(x.__class__, a.__class__)
03047         self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
03048         self.assertEqual(y.__class__, b.__class__)
03049         self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
03050         self.assertEqual(repr(x), repr(a))
03051         self.assertEqual(repr(y), repr(b))

Here is the call graph for this function:

Definition at line 1770 of file test_descr.py.

01770 
01771     def test_properties(self):
01772         # Testing property...
01773         class C(object):
01774             def getx(self):
01775                 return self.__x
01776             def setx(self, value):
01777                 self.__x = value
01778             def delx(self):
01779                 del self.__x
01780             x = property(getx, setx, delx, doc="I'm the x property.")
01781         a = C()
01782         self.assertFalse(hasattr(a, "x"))
01783         a.x = 42
01784         self.assertEqual(a._C__x, 42)
01785         self.assertEqual(a.x, 42)
01786         del a.x
01787         self.assertFalse(hasattr(a, "x"))
01788         self.assertFalse(hasattr(a, "_C__x"))
01789         C.x.__set__(a, 100)
01790         self.assertEqual(C.x.__get__(a), 100)
01791         C.x.__delete__(a)
01792         self.assertFalse(hasattr(a, "x"))
01793 
01794         raw = C.__dict__['x']
01795         self.assertIsInstance(raw, property)
01796 
01797         attrs = dir(raw)
01798         self.assertIn("__doc__", attrs)
01799         self.assertIn("fget", attrs)
01800         self.assertIn("fset", attrs)
01801         self.assertIn("fdel", attrs)
01802 
01803         self.assertEqual(raw.__doc__, "I'm the x property.")
01804         self.assertTrue(raw.fget is C.__dict__['getx'])
01805         self.assertTrue(raw.fset is C.__dict__['setx'])
01806         self.assertTrue(raw.fdel is C.__dict__['delx'])
01807 
01808         for attr in "__doc__", "fget", "fset", "fdel":
01809             try:
01810                 setattr(raw, attr, 42)
01811             except AttributeError as msg:
01812                 if str(msg).find('readonly') < 0:
01813                     self.fail("when setting readonly attr %r on a property, "
01814                               "got unexpected AttributeError msg %r" % (attr, str(msg)))
01815             else:
01816                 self.fail("expected AttributeError from trying to set readonly %r "
01817                           "attr on a property" % attr)
01818 
01819         class D(object):
01820             __getitem__ = property(lambda s: 1/0)
01821 
01822         d = D()
01823         try:
01824             for i in d:
01825                 str(i)
01826         except ZeroDivisionError:
01827             pass
01828         else:
01829             self.fail("expected ZeroDivisionError from bad property")

Here is the call graph for this function:

Definition at line 1832 of file test_descr.py.

01832 
01833     def test_properties_doc_attrib(self):
01834         class E(object):
01835             def getter(self):
01836                 "getter method"
01837                 return 0
01838             def setter(self_, value):
01839                 "setter method"
01840                 pass
01841             prop = property(getter)
01842             self.assertEqual(prop.__doc__, "getter method")
01843             prop2 = property(fset=setter)
01844             self.assertEqual(prop2.__doc__, None)

Definition at line 1855 of file test_descr.py.

01855 
01856     def test_properties_plus(self):
01857         class C(object):
01858             foo = property(doc="hello")
01859             @foo.getter
01860             def foo(self):
01861                 return self._foo
01862             @foo.setter
01863             def foo(self, value):
01864                 self._foo = abs(value)
01865             @foo.deleter
01866             def foo(self):
01867                 del self._foo
01868         c = C()
01869         self.assertEqual(C.foo.__doc__, "hello")
01870         self.assertFalse(hasattr(c, "foo"))
01871         c.foo = -42
01872         self.assertTrue(hasattr(c, '_foo'))
01873         self.assertEqual(c._foo, 42)
01874         self.assertEqual(c.foo, 42)
01875         del c.foo
01876         self.assertFalse(hasattr(c, '_foo'))
01877         self.assertFalse(hasattr(c, "foo"))
01878 
01879         class D(C):
01880             @C.foo.deleter
01881             def foo(self):
01882                 try:
01883                     del self._foo
01884                 except AttributeError:
01885                     pass
01886         d = D()
01887         d.foo = 24
01888         self.assertEqual(d.foo, 24)
01889         del d.foo
01890         del d.foo
01891 
01892         class E(object):
01893             @property
01894             def foo(self):
01895                 return self._foo
01896             @foo.setter
01897             def foo(self, value):
01898                 raise RuntimeError
01899             @foo.setter
01900             def foo(self, value):
01901                 self._foo = abs(value)
01902             @foo.deleter
01903             def foo(self, value=None):
01904                 del self._foo
01905 
01906         e = E()
01907         e.foo = -42
01908         self.assertEqual(e.foo, 42)
01909         del e.foo
01910 
01911         class F(E):
01912             @E.foo.deleter
01913             def foo(self):
01914                 del self._foo
01915             @foo.setter
01916             def foo(self, value):
01917                 self._foo = max(0, value)
01918         f = F()
01919         f.foo = -10
01920         self.assertEqual(f.foo, 0)
01921         del f.foo

Definition at line 4239 of file test_descr.py.

04239 
04240     def test_proxy_call(self):
04241         class FakeStr:
04242             __class__ = str
04243 
04244         fake_str = FakeStr()
04245         # isinstance() reads __class__
04246         self.assertTrue(isinstance(fake_str, str))
04247 
04248         # call a method descriptor
04249         with self.assertRaises(TypeError):
04250             str.split(fake_str)
04251 
04252         # call a slot wrapper descriptor
04253         with self.assertRaises(TypeError):
04254             str.__add__(fake_str, "abc")

Here is the call graph for this function:

Definition at line 3941 of file test_descr.py.

03941 
03942     def test_proxy_super(self):
03943         # Testing super() for a proxy object...
03944         class Proxy(object):
03945             def __init__(self, obj):
03946                 self.__obj = obj
03947             def __getattribute__(self, name):
03948                 if name.startswith("_Proxy__"):
03949                     return object.__getattribute__(self, name)
03950                 else:
03951                     return getattr(self.__obj, name)
03952 
03953         class B(object):
03954             def f(self):
03955                 return "B.f"
03956 
03957         class C(B):
03958             def f(self):
03959                 return super(C, self).f() + "->C.f"
03960 
03961         obj = C()
03962         p = Proxy(obj)
03963         self.assertEqual(C.__dict__["f"](p), "B.f->C.f")

Here is the call graph for this function:

Definition at line 389 of file test_descr.py.

00389 
00390     def test_python_dicts(self):
00391         # Testing Python subclass of dict...
00392         self.assertTrue(issubclass(dict, dict))
00393         self.assertIsInstance({}, dict)
00394         d = dict()
00395         self.assertEqual(d, {})
00396         self.assertTrue(d.__class__ is dict)
00397         self.assertIsInstance(d, dict)
00398         class C(dict):
00399             state = -1
00400             def __init__(self_local, *a, **kw):
00401                 if a:
00402                     self.assertEqual(len(a), 1)
00403                     self_local.state = a[0]
00404                 if kw:
00405                     for k, v in list(kw.items()):
00406                         self_local[v] = k
00407             def __getitem__(self, key):
00408                 return self.get(key, 0)
00409             def __setitem__(self_local, key, value):
00410                 self.assertIsInstance(key, type(0))
00411                 dict.__setitem__(self_local, key, value)
00412             def setstate(self, state):
00413                 self.state = state
00414             def getstate(self):
00415                 return self.state
00416         self.assertTrue(issubclass(C, dict))
00417         a1 = C(12)
00418         self.assertEqual(a1.state, 12)
00419         a2 = C(foo=1, bar=2)
00420         self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
00421         a = C()
00422         self.assertEqual(a.state, -1)
00423         self.assertEqual(a.getstate(), -1)
00424         a.setstate(0)
00425         self.assertEqual(a.state, 0)
00426         self.assertEqual(a.getstate(), 0)
00427         a.setstate(10)
00428         self.assertEqual(a.state, 10)
00429         self.assertEqual(a.getstate(), 10)
00430         self.assertEqual(a[42], 0)
00431         a[42] = 24
00432         self.assertEqual(a[42], 24)
00433         N = 50
00434         for i in range(N):
00435             a[i] = C()
00436             for j in range(N):
00437                 a[i][j] = i*j
00438         for i in range(N):
00439             for j in range(N):
00440                 self.assertEqual(a[i][j], i*j)

Definition at line 441 of file test_descr.py.

00441 
00442     def test_python_lists(self):
00443         # Testing Python subclass of list...
00444         class C(list):
00445             def __getitem__(self, i):
00446                 if isinstance(i, slice):
00447                     return i.start, i.stop
00448                 return list.__getitem__(self, i) + 100
00449         a = C()
00450         a.extend([0,1,2])
00451         self.assertEqual(a[0], 100)
00452         self.assertEqual(a[1], 101)
00453         self.assertEqual(a[2], 102)
00454         self.assertEqual(a[100:200], (100,200))

Here is the call graph for this function:

Definition at line 3285 of file test_descr.py.

03285 
03286     def test_recursive_call(self):
03287         # Testing recursive __call__() by setting to instance of class...
03288         class A(object):
03289             pass
03290 
03291         A.__call__ = A()
03292         try:
03293             A()()
03294         except RuntimeError:
03295             pass
03296         else:
03297             self.fail("Recursion limit should have been reached for __call__()")

Definition at line 4255 of file test_descr.py.

04255 
04256     def test_repr_as_str(self):
04257         # Issue #11603: crash or infinite loop when rebinding __str__ as
04258         # __repr__.
04259         class Foo:
04260             pass
04261         Foo.__repr__ = Foo.__str__
04262         foo = Foo()
04263         str(foo)

Definition at line 2666 of file test_descr.py.

02666 
02667     def test_rich_comparisons(self):
02668         # Testing rich comparisons...
02669         class Z(complex):
02670             pass
02671         z = Z(1)
02672         self.assertEqual(z, 1+0j)
02673         self.assertEqual(1+0j, z)
02674         class ZZ(complex):
02675             def __eq__(self, other):
02676                 try:
02677                     return abs(self - other) <= 1e-6
02678                 except:
02679                     return NotImplemented
02680         zz = ZZ(1.0000003)
02681         self.assertEqual(zz, 1+0j)
02682         self.assertEqual(1+0j, zz)
02683 
02684         class classic:
02685             pass
02686         for base in (classic, int, object, list):
02687             class C(base):
02688                 def __init__(self, value):
02689                     self.value = int(value)
02690                 def __cmp__(self_, other):
02691                     self.fail("shouldn't call __cmp__")
02692                 def __eq__(self, other):
02693                     if isinstance(other, C):
02694                         return self.value == other.value
02695                     if isinstance(other, int) or isinstance(other, int):
02696                         return self.value == other
02697                     return NotImplemented
02698                 def __ne__(self, other):
02699                     if isinstance(other, C):
02700                         return self.value != other.value
02701                     if isinstance(other, int) or isinstance(other, int):
02702                         return self.value != other
02703                     return NotImplemented
02704                 def __lt__(self, other):
02705                     if isinstance(other, C):
02706                         return self.value < other.value
02707                     if isinstance(other, int) or isinstance(other, int):
02708                         return self.value < other
02709                     return NotImplemented
02710                 def __le__(self, other):
02711                     if isinstance(other, C):
02712                         return self.value <= other.value
02713                     if isinstance(other, int) or isinstance(other, int):
02714                         return self.value <= other
02715                     return NotImplemented
02716                 def __gt__(self, other):
02717                     if isinstance(other, C):
02718                         return self.value > other.value
02719                     if isinstance(other, int) or isinstance(other, int):
02720                         return self.value > other
02721                     return NotImplemented
02722                 def __ge__(self, other):
02723                     if isinstance(other, C):
02724                         return self.value >= other.value
02725                     if isinstance(other, int) or isinstance(other, int):
02726                         return self.value >= other
02727                     return NotImplemented
02728             c1 = C(1)
02729             c2 = C(2)
02730             c3 = C(3)
02731             self.assertEqual(c1, 1)
02732             c = {1: c1, 2: c2, 3: c3}
02733             for x in 1, 2, 3:
02734                 for y in 1, 2, 3:
02735                     for op in "<", "<=", "==", "!=", ">", ">=":
02736                         self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
02737                                "x=%d, y=%d" % (x, y))
02738                         self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
02739                                "x=%d, y=%d" % (x, y))
02740                         self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
02741                                "x=%d, y=%d" % (x, y))

Definition at line 3586 of file test_descr.py.

03586 
03587     def test_rmul(self):
03588         # Testing correct invocation of __rmul__...
03589         # SF patch 592646
03590         class C(object):
03591             def __mul__(self, other):
03592                 return "mul"
03593             def __rmul__(self, other):
03594                 return "rmul"
03595         a = C()
03596         self.assertEqual(a*2, "mul")
03597         self.assertEqual(a*2.2, "mul")
03598         self.assertEqual(2*a, "rmul")
03599         self.assertEqual(2.2*a, "rmul")

Here is the call graph for this function:

Definition at line 4159 of file test_descr.py.

04159 
04160     def test_set_and_no_get(self):
04161         # See
04162         # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
04163         class Descr(object):
04164 
04165             def __init__(self, name):
04166                 self.name = name
04167 
04168             def __set__(self, obj, value):
04169                 obj.__dict__[self.name] = value
04170         descr = Descr("a")
04171 
04172         class X(object):
04173             a = descr
04174 
04175         x = X()
04176         self.assertIs(x.a, descr)
04177         x.a = 42
04178         self.assertEqual(x.a, 42)
04179 
04180         # Also check type_getattro for correctness.
04181         class Meta(type):
04182             pass
04183         class X(object):
04184             __metaclass__ = Meta
04185         X.a = 42
04186         Meta.a = Descr("a")
04187         self.assertEqual(X.a, 42)

Here is the call graph for this function:

Definition at line 2769 of file test_descr.py.

02769 
02770     def test_set_class(self):
02771         # Testing __class__ assignment...
02772         class C(object): pass
02773         class D(object): pass
02774         class E(object): pass
02775         class F(D, E): pass
02776         for cls in C, D, E, F:
02777             for cls2 in C, D, E, F:
02778                 x = cls()
02779                 x.__class__ = cls2
02780                 self.assertTrue(x.__class__ is cls2)
02781                 x.__class__ = cls
02782                 self.assertTrue(x.__class__ is cls)
02783         def cant(x, C):
02784             try:
02785                 x.__class__ = C
02786             except TypeError:
02787                 pass
02788             else:
02789                 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
02790             try:
02791                 delattr(x, "__class__")
02792             except (TypeError, AttributeError):
02793                 pass
02794             else:
02795                 self.fail("shouldn't allow del %r.__class__" % x)
02796         cant(C(), list)
02797         cant(list(), C)
02798         cant(C(), 1)
02799         cant(C(), object)
02800         cant(object(), list)
02801         cant(list(), object)
02802         class Int(int): __slots__ = []
02803         cant(2, Int)
02804         cant(Int(), int)
02805         cant(True, int)
02806         cant(2, bool)
02807         o = object()
02808         cant(o, type(1))
02809         cant(o, type(None))
02810         del o
02811         class G(object):
02812             __slots__ = ["a", "b"]
02813         class H(object):
02814             __slots__ = ["b", "a"]
02815         class I(object):
02816             __slots__ = ["a", "b"]
02817         class J(object):
02818             __slots__ = ["c", "b"]
02819         class K(object):
02820             __slots__ = ["a", "b", "d"]
02821         class L(H):
02822             __slots__ = ["e"]
02823         class M(I):
02824             __slots__ = ["e"]
02825         class N(J):
02826             __slots__ = ["__weakref__"]
02827         class P(J):
02828             __slots__ = ["__dict__"]
02829         class Q(J):
02830             pass
02831         class R(J):
02832             __slots__ = ["__dict__", "__weakref__"]
02833 
02834         for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
02835             x = cls()
02836             x.a = 1
02837             x.__class__ = cls2
02838             self.assertTrue(x.__class__ is cls2,
02839                    "assigning %r as __class__ for %r silently failed" % (cls2, x))
02840             self.assertEqual(x.a, 1)
02841             x.__class__ = cls
02842             self.assertTrue(x.__class__ is cls,
02843                    "assigning %r as __class__ for %r silently failed" % (cls, x))
02844             self.assertEqual(x.a, 1)
02845         for cls in G, J, K, L, M, N, P, R, list, Int:
02846             for cls2 in G, J, K, L, M, N, P, R, list, Int:
02847                 if cls is cls2:
02848                     continue
02849                 cant(cls(), cls2)
02850 
02851         # Issue5283: when __class__ changes in __del__, the wrong
02852         # type gets DECREF'd.
02853         class O(object):
02854             pass
02855         class A(object):
02856             def __del__(self):
02857                 self.__class__ = O
02858         l = [A() for x in range(100)]
02859         del l

Here is the call graph for this function:

Definition at line 2860 of file test_descr.py.

02860 
02861     def test_set_dict(self):
02862         # Testing __dict__ assignment...
02863         class C(object): pass
02864         a = C()
02865         a.__dict__ = {'b': 1}
02866         self.assertEqual(a.b, 1)
02867         def cant(x, dict):
02868             try:
02869                 x.__dict__ = dict
02870             except (AttributeError, TypeError):
02871                 pass
02872             else:
02873                 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
02874         cant(a, None)
02875         cant(a, [])
02876         cant(a, 1)
02877         del a.__dict__ # Deleting __dict__ is allowed
02878 
02879         class Base(object):
02880             pass
02881         def verify_dict_readonly(x):
02882             """
02883             x has to be an instance of a class inheriting from Base.
02884             """
02885             cant(x, {})
02886             try:
02887                 del x.__dict__
02888             except (AttributeError, TypeError):
02889                 pass
02890             else:
02891                 self.fail("shouldn't allow del %r.__dict__" % x)
02892             dict_descr = Base.__dict__["__dict__"]
02893             try:
02894                 dict_descr.__set__(x, {})
02895             except (AttributeError, TypeError):
02896                 pass
02897             else:
02898                 self.fail("dict_descr allowed access to %r's dict" % x)
02899 
02900         # Classes don't allow __dict__ assignment and have readonly dicts
02901         class Meta1(type, Base):
02902             pass
02903         class Meta2(Base, type):
02904             pass
02905         class D(object, metaclass=Meta1):
02906             pass
02907         class E(object, metaclass=Meta2):
02908             pass
02909         for cls in C, D, E:
02910             verify_dict_readonly(cls)
02911             class_dict = cls.__dict__
02912             try:
02913                 class_dict["spam"] = "eggs"
02914             except TypeError:
02915                 pass
02916             else:
02917                 self.fail("%r's __dict__ can be modified" % cls)
02918 
02919         # Modules also disallow __dict__ assignment
02920         class Module1(types.ModuleType, Base):
02921             pass
02922         class Module2(Base, types.ModuleType):
02923             pass
02924         for ModuleType in Module1, Module2:
02925             mod = ModuleType("spam")
02926             verify_dict_readonly(mod)
02927             mod.__dict__["spam"] = "eggs"
02928 
02929         # Exception's __dict__ can be replaced, but not deleted
02930         # (at least not any more than regular exception's __dict__ can
02931         # be deleted; on CPython it is not the case, whereas on PyPy they
02932         # can, just like any other new-style instance's __dict__.)
02933         def can_delete_dict(e):
02934             try:
02935                 del e.__dict__
02936             except (TypeError, AttributeError):
02937                 return False
02938             else:
02939                 return True
02940         class Exception1(Exception, Base):
02941             pass
02942         class Exception2(Base, Exception):
02943             pass
02944         for ExceptionType in Exception, Exception1, Exception2:
02945             e = ExceptionType()
02946             e.__dict__ = {"a": 1}
02947             self.assertEqual(e.a, 1)
02948             self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))

Here is the call graph for this function:

Definition at line 3481 of file test_descr.py.

03481 
03482     def test_slices(self):
03483         # Testing cases with slices and overridden __getitem__ ...
03484 
03485         # Strings
03486         self.assertEqual("hello"[:4], "hell")
03487         self.assertEqual("hello"[slice(4)], "hell")
03488         self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
03489         class S(str):
03490             def __getitem__(self, x):
03491                 return str.__getitem__(self, x)
03492         self.assertEqual(S("hello")[:4], "hell")
03493         self.assertEqual(S("hello")[slice(4)], "hell")
03494         self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
03495         # Tuples
03496         self.assertEqual((1,2,3)[:2], (1,2))
03497         self.assertEqual((1,2,3)[slice(2)], (1,2))
03498         self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
03499         class T(tuple):
03500             def __getitem__(self, x):
03501                 return tuple.__getitem__(self, x)
03502         self.assertEqual(T((1,2,3))[:2], (1,2))
03503         self.assertEqual(T((1,2,3))[slice(2)], (1,2))
03504         self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
03505         # Lists
03506         self.assertEqual([1,2,3][:2], [1,2])
03507         self.assertEqual([1,2,3][slice(2)], [1,2])
03508         self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
03509         class L(list):
03510             def __getitem__(self, x):
03511                 return list.__getitem__(self, x)
03512         self.assertEqual(L([1,2,3])[:2], [1,2])
03513         self.assertEqual(L([1,2,3])[slice(2)], [1,2])
03514         self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
03515         # Now do lists and __setitem__
03516         a = L([1,2,3])
03517         a[slice(1, 3)] = [3,2]
03518         self.assertEqual(a, [1,3,2])
03519         a[slice(0, 2, 1)] = [3,1]
03520         self.assertEqual(a, [3,1,2])
03521         a.__setitem__(slice(1, 3), [2,1])
03522         self.assertEqual(a, [3,2,1])
03523         a.__setitem__(slice(0, 2, 1), [2,3])
03524         self.assertEqual(a, [2,3,1])

Here is the call graph for this function:

Definition at line 848 of file test_descr.py.

00848 
00849     def test_slots(self):
00850         # Testing __slots__...
00851         class C0(object):
00852             __slots__ = []
00853         x = C0()
00854         self.assertFalse(hasattr(x, "__dict__"))
00855         self.assertFalse(hasattr(x, "foo"))
00856 
00857         class C1(object):
00858             __slots__ = ['a']
00859         x = C1()
00860         self.assertFalse(hasattr(x, "__dict__"))
00861         self.assertFalse(hasattr(x, "a"))
00862         x.a = 1
00863         self.assertEqual(x.a, 1)
00864         x.a = None
00865         self.assertEqual(x.a, None)
00866         del x.a
00867         self.assertFalse(hasattr(x, "a"))
00868 
00869         class C3(object):
00870             __slots__ = ['a', 'b', 'c']
00871         x = C3()
00872         self.assertFalse(hasattr(x, "__dict__"))
00873         self.assertFalse(hasattr(x, 'a'))
00874         self.assertFalse(hasattr(x, 'b'))
00875         self.assertFalse(hasattr(x, 'c'))
00876         x.a = 1
00877         x.b = 2
00878         x.c = 3
00879         self.assertEqual(x.a, 1)
00880         self.assertEqual(x.b, 2)
00881         self.assertEqual(x.c, 3)
00882 
00883         class C4(object):
00884             """Validate name mangling"""
00885             __slots__ = ['__a']
00886             def __init__(self, value):
00887                 self.__a = value
00888             def get(self):
00889                 return self.__a
00890         x = C4(5)
00891         self.assertFalse(hasattr(x, '__dict__'))
00892         self.assertFalse(hasattr(x, '__a'))
00893         self.assertEqual(x.get(), 5)
00894         try:
00895             x.__a = 6
00896         except AttributeError:
00897             pass
00898         else:
00899             self.fail("Double underscored names not mangled")
00900 
00901         # Make sure slot names are proper identifiers
00902         try:
00903             class C(object):
00904                 __slots__ = [None]
00905         except TypeError:
00906             pass
00907         else:
00908             self.fail("[None] slots not caught")
00909         try:
00910             class C(object):
00911                 __slots__ = ["foo bar"]
00912         except TypeError:
00913             pass
00914         else:
00915             self.fail("['foo bar'] slots not caught")
00916         try:
00917             class C(object):
00918                 __slots__ = ["foo\0bar"]
00919         except TypeError:
00920             pass
00921         else:
00922             self.fail("['foo\\0bar'] slots not caught")
00923         try:
00924             class C(object):
00925                 __slots__ = ["1"]
00926         except TypeError:
00927             pass
00928         else:
00929             self.fail("['1'] slots not caught")
00930         try:
00931             class C(object):
00932                 __slots__ = [""]
00933         except TypeError:
00934             pass
00935         else:
00936             self.fail("[''] slots not caught")
00937         class C(object):
00938             __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
00939         # XXX(nnorwitz): was there supposed to be something tested
00940         # from the class above?
00941 
00942         # Test a single string is not expanded as a sequence.
00943         class C(object):
00944             __slots__ = "abc"
00945         c = C()
00946         c.abc = 5
00947         self.assertEqual(c.abc, 5)
00948 
00949         # Test unicode slot names
00950         # Test a single unicode string is not expanded as a sequence.
00951         class C(object):
00952             __slots__ = "abc"
00953         c = C()
00954         c.abc = 5
00955         self.assertEqual(c.abc, 5)
00956 
00957         # _unicode_to_string used to modify slots in certain circumstances
00958         slots = ("foo", "bar")
00959         class C(object):
00960             __slots__ = slots
00961         x = C()
00962         x.foo = 5
00963         self.assertEqual(x.foo, 5)
00964         self.assertTrue(type(slots[0]) is str)
00965         # this used to leak references
00966         try:
00967             class C(object):
00968                 __slots__ = [chr(128)]
00969         except (TypeError, UnicodeEncodeError):
00970             pass
00971         else:
00972             raise TestFailed("[chr(128)] slots not caught")
00973 
00974         # Test leaks
00975         class Counted(object):
00976             counter = 0    # counts the number of instances alive
00977             def __init__(self):
00978                 Counted.counter += 1
00979             def __del__(self):
00980                 Counted.counter -= 1
00981         class C(object):
00982             __slots__ = ['a', 'b', 'c']
00983         x = C()
00984         x.a = Counted()
00985         x.b = Counted()
00986         x.c = Counted()
00987         self.assertEqual(Counted.counter, 3)
00988         del x
00989         support.gc_collect()
00990         self.assertEqual(Counted.counter, 0)
00991         class D(C):
00992             pass
00993         x = D()
00994         x.a = Counted()
00995         x.z = Counted()
00996         self.assertEqual(Counted.counter, 2)
00997         del x
00998         support.gc_collect()
00999         self.assertEqual(Counted.counter, 0)
01000         class E(D):
01001             __slots__ = ['e']
01002         x = E()
01003         x.a = Counted()
01004         x.z = Counted()
01005         x.e = Counted()
01006         self.assertEqual(Counted.counter, 3)
01007         del x
01008         support.gc_collect()
01009         self.assertEqual(Counted.counter, 0)
01010 
01011         # Test cyclical leaks [SF bug 519621]
01012         class F(object):
01013             __slots__ = ['a', 'b']
01014         s = F()
01015         s.a = [Counted(), s]
01016         self.assertEqual(Counted.counter, 1)
01017         s = None
01018         support.gc_collect()
01019         self.assertEqual(Counted.counter, 0)
01020 
01021         # Test lookup leaks [SF bug 572567]
01022         import gc
01023         if hasattr(gc, 'get_objects'):
01024             class G(object):
01025                 def __eq__(self, other):
01026                     return False
01027             g = G()
01028             orig_objects = len(gc.get_objects())
01029             for i in range(10):
01030                 g==g
01031             new_objects = len(gc.get_objects())
01032             self.assertEqual(orig_objects, new_objects)
01033 
01034         class H(object):
01035             __slots__ = ['a', 'b']
01036             def __init__(self):
01037                 self.a = 1
01038                 self.b = 2
01039             def __del__(self_):
01040                 self.assertEqual(self_.a, 1)
01041                 self.assertEqual(self_.b, 2)
01042         with support.captured_output('stderr') as s:
01043             h = H()
01044             del h
01045         self.assertEqual(s.getvalue(), '')
01046 
01047         class X(object):
01048             __slots__ = "a"
01049         with self.assertRaises(AttributeError):
01050             del X().a

Here is the call graph for this function:

Definition at line 1089 of file test_descr.py.

01089 
01090     def test_slots_descriptor(self):
01091         # Issue2115: slot descriptors did not correctly check
01092         # the type of the given object
01093         import abc
01094         class MyABC(metaclass=abc.ABCMeta):
01095             __slots__ = "a"
01096 
01097         class Unrelated(object):
01098             pass
01099         MyABC.register(Unrelated)
01100 
01101         u = Unrelated()
01102         self.assertIsInstance(u, MyABC)
01103 
01104         # This used to crash
01105         self.assertRaises(TypeError, MyABC.a.__set__, u, 3)

Definition at line 3572 of file test_descr.py.

03572 
03573     def test_slots_multiple_inheritance(self):
03574         # SF bug 575229, multiple inheritance w/ slots dumps core
03575         class A(object):
03576             __slots__=()
03577         class B(object):
03578             pass
03579         class C(A,B) :
03580             __slots__=()
03581         if support.check_impl_detail():
03582             self.assertEqual(C.__basicsize__, B.__basicsize__)
03583         self.assertTrue(hasattr(C, '__dict__'))
03584         self.assertTrue(hasattr(C, '__weakref__'))
03585         C().x = 2

Definition at line 1051 of file test_descr.py.

01051 
01052     def test_slots_special(self):
01053         # Testing __dict__ and __weakref__ in __slots__...
01054         class D(object):
01055             __slots__ = ["__dict__"]
01056         a = D()
01057         self.assertTrue(hasattr(a, "__dict__"))
01058         self.assertFalse(hasattr(a, "__weakref__"))
01059         a.foo = 42
01060         self.assertEqual(a.__dict__, {"foo": 42})
01061 
01062         class W(object):
01063             __slots__ = ["__weakref__"]
01064         a = W()
01065         self.assertTrue(hasattr(a, "__weakref__"))
01066         self.assertFalse(hasattr(a, "__dict__"))
01067         try:
01068             a.foo = 42
01069         except AttributeError:
01070             pass
01071         else:
01072             self.fail("shouldn't be allowed to set a.foo")
01073 
01074         class C1(W, D):
01075             __slots__ = []
01076         a = C1()
01077         self.assertTrue(hasattr(a, "__dict__"))
01078         self.assertTrue(hasattr(a, "__weakref__"))
01079         a.foo = 42
01080         self.assertEqual(a.__dict__, {"foo": 42})
01081 
01082         class C2(D, W):
01083             __slots__ = []
01084         a = C2()
01085         self.assertTrue(hasattr(a, "__dict__"))
01086         self.assertTrue(hasattr(a, "__weakref__"))
01087         a.foo = 42
01088         self.assertEqual(a.__dict__, {"foo": 42})

Here is the call graph for this function:

Definition at line 3560 of file test_descr.py.

03560 
03561     def test_slots_trash(self):
03562         # Testing slot trash...
03563         # Deallocating deeply nested slotted trash caused stack overflows
03564         class trash(object):
03565             __slots__ = ['x']
03566             def __init__(self, x):
03567                 self.x = x
03568         o = None
03569         for i in range(50000):
03570             o = trash(o)
03571         del o

Here is the call graph for this function:

Definition at line 1533 of file test_descr.py.

01533 
01534     def test_special_method_lookup(self):
01535         # The lookup of special methods bypasses __getattr__ and
01536         # __getattribute__, but they still can be descriptors.
01537 
01538         def run_context(manager):
01539             with manager:
01540                 pass
01541         def iden(self):
01542             return self
01543         def hello(self):
01544             return b"hello"
01545         def empty_seq(self):
01546             return []
01547         def zero(self):
01548             return 0
01549         def complex_num(self):
01550             return 1j
01551         def stop(self):
01552             raise StopIteration
01553         def return_true(self, thing=None):
01554             return True
01555         def do_isinstance(obj):
01556             return isinstance(int, obj)
01557         def do_issubclass(obj):
01558             return issubclass(int, obj)
01559         def do_dict_missing(checker):
01560             class DictSub(checker.__class__, dict):
01561                 pass
01562             self.assertEqual(DictSub()["hi"], 4)
01563         def some_number(self_, key):
01564             self.assertEqual(key, "hi")
01565             return 4
01566         def swallow(*args): pass
01567         def format_impl(self, spec):
01568             return "hello"
01569 
01570         # It would be nice to have every special method tested here, but I'm
01571         # only listing the ones I can remember outside of typeobject.c, since it
01572         # does it right.
01573         specials = [
01574             ("__bytes__", bytes, hello, set(), {}),
01575             ("__reversed__", reversed, empty_seq, set(), {}),
01576             ("__length_hint__", list, zero, set(),
01577              {"__iter__" : iden, "__next__" : stop}),
01578             ("__sizeof__", sys.getsizeof, zero, set(), {}),
01579             ("__instancecheck__", do_isinstance, return_true, set(), {}),
01580             ("__missing__", do_dict_missing, some_number,
01581              set(("__class__",)), {}),
01582             ("__subclasscheck__", do_issubclass, return_true,
01583              set(("__bases__",)), {}),
01584             ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
01585             ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
01586             ("__complex__", complex, complex_num, set(), {}),
01587             ("__format__", format, format_impl, set(), {}),
01588             ("__floor__", math.floor, zero, set(), {}),
01589             ("__trunc__", math.trunc, zero, set(), {}),
01590             ("__ceil__", math.ceil, zero, set(), {}),
01591             ("__dir__", dir, empty_seq, set(), {}),
01592             ]
01593 
01594         class Checker(object):
01595             def __getattr__(self, attr, test=self):
01596                 test.fail("__getattr__ called with {0}".format(attr))
01597             def __getattribute__(self, attr, test=self):
01598                 if attr not in ok:
01599                     test.fail("__getattribute__ called with {0}".format(attr))
01600                 return object.__getattribute__(self, attr)
01601         class SpecialDescr(object):
01602             def __init__(self, impl):
01603                 self.impl = impl
01604             def __get__(self, obj, owner):
01605                 record.append(1)
01606                 return self.impl.__get__(obj, owner)
01607         class MyException(Exception):
01608             pass
01609         class ErrDescr(object):
01610             def __get__(self, obj, owner):
01611                 raise MyException
01612 
01613         for name, runner, meth_impl, ok, env in specials:
01614             class X(Checker):
01615                 pass
01616             for attr, obj in env.items():
01617                 setattr(X, attr, obj)
01618             setattr(X, name, meth_impl)
01619             runner(X())
01620 
01621             record = []
01622             class X(Checker):
01623                 pass
01624             for attr, obj in env.items():
01625                 setattr(X, attr, obj)
01626             setattr(X, name, SpecialDescr(meth_impl))
01627             runner(X())
01628             self.assertEqual(record, [1], name)
01629 
01630             class X(Checker):
01631                 pass
01632             for attr, obj in env.items():
01633                 setattr(X, attr, obj)
01634             setattr(X, name, ErrDescr())
01635             try:
01636                 runner(X())
01637             except MyException:
01638                 pass
01639             else:
01640                 self.fail("{0!r} didn't raise".format(name))

Here is the call graph for this function:

Definition at line 1641 of file test_descr.py.

01641 
01642     def test_specials(self):
01643         # Testing special operators...
01644         # Test operators like __hash__ for which a built-in default exists
01645 
01646         # Test the default behavior for static classes
01647         class C(object):
01648             def __getitem__(self, i):
01649                 if 0 <= i < 10: return i
01650                 raise IndexError
01651         c1 = C()
01652         c2 = C()
01653         self.assertTrue(not not c1) # What?
01654         self.assertNotEqual(id(c1), id(c2))
01655         hash(c1)
01656         hash(c2)
01657         self.assertEqual(c1, c1)
01658         self.assertTrue(c1 != c2)
01659         self.assertTrue(not c1 != c1)
01660         self.assertTrue(not c1 == c2)
01661         # Note that the module name appears in str/repr, and that varies
01662         # depending on whether this test is run standalone or from a framework.
01663         self.assertTrue(str(c1).find('C object at ') >= 0)
01664         self.assertEqual(str(c1), repr(c1))
01665         self.assertNotIn(-1, c1)
01666         for i in range(10):
01667             self.assertIn(i, c1)
01668         self.assertNotIn(10, c1)
01669         # Test the default behavior for dynamic classes
01670         class D(object):
01671             def __getitem__(self, i):
01672                 if 0 <= i < 10: return i
01673                 raise IndexError
01674         d1 = D()
01675         d2 = D()
01676         self.assertTrue(not not d1)
01677         self.assertNotEqual(id(d1), id(d2))
01678         hash(d1)
01679         hash(d2)
01680         self.assertEqual(d1, d1)
01681         self.assertNotEqual(d1, d2)
01682         self.assertTrue(not d1 != d1)
01683         self.assertTrue(not d1 == d2)
01684         # Note that the module name appears in str/repr, and that varies
01685         # depending on whether this test is run standalone or from a framework.
01686         self.assertTrue(str(d1).find('D object at ') >= 0)
01687         self.assertEqual(str(d1), repr(d1))
01688         self.assertNotIn(-1, d1)
01689         for i in range(10):
01690             self.assertIn(i, d1)
01691         self.assertNotIn(10, d1)
01692         # Test overridden behavior
01693         class Proxy(object):
01694             def __init__(self, x):
01695                 self.x = x
01696             def __bool__(self):
01697                 return not not self.x
01698             def __hash__(self):
01699                 return hash(self.x)
01700             def __eq__(self, other):
01701                 return self.x == other
01702             def __ne__(self, other):
01703                 return self.x != other
01704             def __ge__(self, other):
01705                 return self.x >= other
01706             def __gt__(self, other):
01707                 return self.x > other
01708             def __le__(self, other):
01709                 return self.x <= other
01710             def __lt__(self, other):
01711                 return self.x < other
01712             def __str__(self):
01713                 return "Proxy:%s" % self.x
01714             def __repr__(self):
01715                 return "Proxy(%r)" % self.x
01716             def __contains__(self, value):
01717                 return value in self.x
01718         p0 = Proxy(0)
01719         p1 = Proxy(1)
01720         p_1 = Proxy(-1)
01721         self.assertFalse(p0)
01722         self.assertTrue(not not p1)
01723         self.assertEqual(hash(p0), hash(0))
01724         self.assertEqual(p0, p0)
01725         self.assertNotEqual(p0, p1)
01726         self.assertTrue(not p0 != p0)
01727         self.assertEqual(not p0, p1)
01728         self.assertTrue(p0 < p1)
01729         self.assertTrue(p0 <= p1)
01730         self.assertTrue(p1 > p0)
01731         self.assertTrue(p1 >= p0)
01732         self.assertEqual(str(p0), "Proxy:0")
01733         self.assertEqual(repr(p0), "Proxy(0)")
01734         p10 = Proxy(range(10))
01735         self.assertNotIn(-1, p10)
01736         for i in range(10):
01737             self.assertIn(i, p10)
01738         self.assertNotIn(10, p10)

Here is the call graph for this function:

Definition at line 1293 of file test_descr.py.

01293 
01294     def test_staticmethods(self):
01295         # Testing static methods...
01296         class C(object):
01297             def foo(*a): return a
01298             goo = staticmethod(foo)
01299         c = C()
01300         self.assertEqual(C.goo(1), (1,))
01301         self.assertEqual(c.goo(1), (1,))
01302         self.assertEqual(c.foo(1), (c, 1,))
01303         class D(C):
01304             pass
01305         d = D()
01306         self.assertEqual(D.goo(1), (1,))
01307         self.assertEqual(d.goo(1), (1,))
01308         self.assertEqual(d.foo(1), (d, 1))
01309         self.assertEqual(D.foo(d, 1), (d, 1))

Here is the call graph for this function:

Definition at line 1311 of file test_descr.py.

01311 
01312     def test_staticmethods_in_c(self):
01313         # Testing C-based static methods...
01314         import xxsubtype as spam
01315         a = (1, 2, 3)
01316         d = {"abc": 123}
01317         x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
01318         self.assertEqual(x, None)
01319         self.assertEqual(a, a1)
01320         self.assertEqual(d, d1)
01321         x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
01322         self.assertEqual(x, None)
01323         self.assertEqual(a, a1)
01324         self.assertEqual(d, d1)

Here is the call graph for this function:

Definition at line 3249 of file test_descr.py.

03249 
03250     def test_str_of_str_subclass(self):
03251         # Testing __str__ defined in subclass of str ...
03252         import binascii
03253         import io
03254 
03255         class octetstring(str):
03256             def __str__(self):
03257                 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
03258             def __repr__(self):
03259                 return self + " repr"
03260 
03261         o = octetstring('A')
03262         self.assertEqual(type(o), octetstring)
03263         self.assertEqual(type(str(o)), str)
03264         self.assertEqual(type(repr(o)), str)
03265         self.assertEqual(ord(o), 0x41)
03266         self.assertEqual(str(o), '41')
03267         self.assertEqual(repr(o), 'A repr')
03268         self.assertEqual(o.__str__(), '41')
03269         self.assertEqual(o.__repr__(), 'A repr')
03270 
03271         capture = io.StringIO()
03272         # Calling str() or not exercises different internal paths.
03273         print(o, file=capture)
03274         print(str(o), file=capture)
03275         self.assertEqual(capture.getvalue(), '41\n41\n')
03276         capture.close()

Definition at line 3339 of file test_descr.py.

03339 
03340     def test_str_operations(self):
03341         try: 'a' + 5
03342         except TypeError: pass
03343         else: self.fail("'' + 5 doesn't raise TypeError")
03344 
03345         try: ''.split('')
03346         except ValueError: pass
03347         else: self.fail("''.split('') doesn't raise ValueError")
03348 
03349         try: ''.join([0])
03350         except TypeError: pass
03351         else: self.fail("''.join([0]) doesn't raise TypeError")
03352 
03353         try: ''.rindex('5')
03354         except ValueError: pass
03355         else: self.fail("''.rindex('5') doesn't raise ValueError")
03356 
03357         try: '%(n)s' % None
03358         except TypeError: pass
03359         else: self.fail("'%(n)s' % None doesn't raise TypeError")
03360 
03361         try: '%(n' % {}
03362         except ValueError: pass
03363         else: self.fail("'%(n' % {} '' doesn't raise ValueError")
03364 
03365         try: '%*s' % ('abc')
03366         except TypeError: pass
03367         else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
03368 
03369         try: '%*.*s' % ('abc', 5)
03370         except TypeError: pass
03371         else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
03372 
03373         try: '%s' % (1, 2)
03374         except TypeError: pass
03375         else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
03376 
03377         try: '%' % None
03378         except ValueError: pass
03379         else: self.fail("'%' % None doesn't raise ValueError")
03380 
03381         self.assertEqual('534253'.isdigit(), 1)
03382         self.assertEqual('534253x'.isdigit(), 0)
03383         self.assertEqual('%c' % 5, '\x05')
03384         self.assertEqual('%c' % '5', '5')

Here is the call graph for this function:

Definition at line 2570 of file test_descr.py.

02570 
02571     def test_str_subclass_as_dict_key(self):
02572         # Testing a str subclass used as dict key ..
02573 
02574         class cistr(str):
02575             """Sublcass of str that computes __eq__ case-insensitively.
02576 
02577             Also computes a hash code of the string in canonical form.
02578             """
02579 
02580             def __init__(self, value):
02581                 self.canonical = value.lower()
02582                 self.hashcode = hash(self.canonical)
02583 
02584             def __eq__(self, other):
02585                 if not isinstance(other, cistr):
02586                     other = cistr(other)
02587                 return self.canonical == other.canonical
02588 
02589             def __hash__(self):
02590                 return self.hashcode
02591 
02592         self.assertEqual(cistr('ABC'), 'abc')
02593         self.assertEqual('aBc', cistr('ABC'))
02594         self.assertEqual(str(cistr('ABC')), 'ABC')
02595 
02596         d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
02597         self.assertEqual(d[cistr('one')], 1)
02598         self.assertEqual(d[cistr('tWo')], 2)
02599         self.assertEqual(d[cistr('THrEE')], 3)
02600         self.assertIn(cistr('ONe'), d)
02601         self.assertEqual(d.get(cistr('thrEE')), 3)

Here is the call graph for this function:

Definition at line 3149 of file test_descr.py.

03149 
03150     def test_subclass_propagation(self):
03151         # Testing propagation of slot functions to subclasses...
03152         class A(object):
03153             pass
03154         class B(A):
03155             pass
03156         class C(A):
03157             pass
03158         class D(B, C):
03159             pass
03160         d = D()
03161         orig_hash = hash(d) # related to id(d) in platform-dependent ways
03162         A.__hash__ = lambda self: 42
03163         self.assertEqual(hash(d), 42)
03164         C.__hash__ = lambda self: 314
03165         self.assertEqual(hash(d), 314)
03166         B.__hash__ = lambda self: 144
03167         self.assertEqual(hash(d), 144)
03168         D.__hash__ = lambda self: 100
03169         self.assertEqual(hash(d), 100)
03170         D.__hash__ = None
03171         self.assertRaises(TypeError, hash, d)
03172         del D.__hash__
03173         self.assertEqual(hash(d), 144)
03174         B.__hash__ = None
03175         self.assertRaises(TypeError, hash, d)
03176         del B.__hash__
03177         self.assertEqual(hash(d), 314)
03178         C.__hash__ = None
03179         self.assertRaises(TypeError, hash, d)
03180         del C.__hash__
03181         self.assertEqual(hash(d), 42)
03182         A.__hash__ = None
03183         self.assertRaises(TypeError, hash, d)
03184         del A.__hash__
03185         self.assertEqual(hash(d), orig_hash)
03186         d.foo = 42
03187         d.bar = 42
03188         self.assertEqual(d.foo, 42)
03189         self.assertEqual(d.bar, 42)
03190         def __getattribute__(self, name):
03191             if name == "foo":
03192                 return 24
03193             return object.__getattribute__(self, name)
03194         A.__getattribute__ = __getattribute__
03195         self.assertEqual(d.foo, 24)
03196         self.assertEqual(d.bar, 42)
03197         def __getattr__(self, name):
03198             if name in ("spam", "foo", "bar"):
03199                 return "hello"
03200             raise AttributeError(name)
03201         B.__getattr__ = __getattr__
03202         self.assertEqual(d.spam, "hello")
03203         self.assertEqual(d.foo, 24)
03204         self.assertEqual(d.bar, 42)
03205         del A.__getattribute__
03206         self.assertEqual(d.foo, 42)
03207         del d.foo
03208         self.assertEqual(d.foo, "hello")
03209         self.assertEqual(d.bar, 42)
03210         del B.__getattr__
03211         try:
03212             d.foo
03213         except AttributeError:
03214             pass
03215         else:
03216             self.fail("d.foo should be undefined now")
03217 
03218         # Test a nasty bug in recurse_down_subclasses()
03219         class A(object):
03220             pass
03221         class B(A):
03222             pass
03223         del B
03224         support.gc_collect()
03225         A.__setitem__ = lambda *a: None # crash

Definition at line 3807 of file test_descr.py.

03807 
03808     def test_subclass_right_op(self):
03809         # Testing correct dispatch of subclass overloading __r<op>__...
03810 
03811         # This code tests various cases where right-dispatch of a subclass
03812         # should be preferred over left-dispatch of a base class.
03813 
03814         # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
03815 
03816         class B(int):
03817             def __floordiv__(self, other):
03818                 return "B.__floordiv__"
03819             def __rfloordiv__(self, other):
03820                 return "B.__rfloordiv__"
03821 
03822         self.assertEqual(B(1) // 1, "B.__floordiv__")
03823         self.assertEqual(1 // B(1), "B.__rfloordiv__")
03824 
03825         # Case 2: subclass of object; this is just the baseline for case 3
03826 
03827         class C(object):
03828             def __floordiv__(self, other):
03829                 return "C.__floordiv__"
03830             def __rfloordiv__(self, other):
03831                 return "C.__rfloordiv__"
03832 
03833         self.assertEqual(C() // 1, "C.__floordiv__")
03834         self.assertEqual(1 // C(), "C.__rfloordiv__")
03835 
03836         # Case 3: subclass of new-style class; here it gets interesting
03837 
03838         class D(C):
03839             def __floordiv__(self, other):
03840                 return "D.__floordiv__"
03841             def __rfloordiv__(self, other):
03842                 return "D.__rfloordiv__"
03843 
03844         self.assertEqual(D() // C(), "D.__floordiv__")
03845         self.assertEqual(C() // D(), "D.__rfloordiv__")
03846 
03847         # Case 4: this didn't work right in 2.2.2 and 2.3a1
03848 
03849         class E(C):
03850             pass
03851 
03852         self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
03853 
03854         self.assertEqual(E() // 1, "C.__floordiv__")
03855         self.assertEqual(1 // E(), "C.__rfloordiv__")
03856         self.assertEqual(E() // C(), "C.__floordiv__")
03857         self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail

Here is the call graph for this function:

Definition at line 3525 of file test_descr.py.

03525 
03526     def test_subtype_resurrection(self):
03527         # Testing resurrection of new-style instance...
03528 
03529         class C(object):
03530             container = []
03531 
03532             def __del__(self):
03533                 # resurrect the instance
03534                 C.container.append(self)
03535 
03536         c = C()
03537         c.attr = 42
03538 
03539         # The most interesting thing here is whether this blows up, due to
03540         # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
03541         # bug).
03542         del c
03543 
03544         # If that didn't blow up, it's also interesting to see whether clearing
03545         # the last container slot works: that will attempt to delete c again,
03546         # which will cause c to get appended back to the container again
03547         # "during" the del.  (On non-CPython implementations, however, __del__
03548         # is typically not called again.)
03549         support.gc_collect()
03550         self.assertEqual(len(C.container), 1)
03551         del C.container[-1]
03552         if support.check_impl_detail():
03553             support.gc_collect()
03554             self.assertEqual(len(C.container), 1)
03555             self.assertEqual(C.container[-1].attr, 42)
03556 
03557         # Make c mortal again, so that the test framework with -l doesn't report
03558         # it as a leak.
03559         del C.__del__

Here is the call graph for this function:

Definition at line 2100 of file test_descr.py.

02100 
02101     def test_supers(self):
02102         # Testing super...
02103 
02104         class A(object):
02105             def meth(self, a):
02106                 return "A(%r)" % a
02107 
02108         self.assertEqual(A().meth(1), "A(1)")
02109 
02110         class B(A):
02111             def __init__(self):
02112                 self.__super = super(B, self)
02113             def meth(self, a):
02114                 return "B(%r)" % a + self.__super.meth(a)
02115 
02116         self.assertEqual(B().meth(2), "B(2)A(2)")
02117 
02118         class C(A):
02119             def meth(self, a):
02120                 return "C(%r)" % a + self.__super.meth(a)
02121         C._C__super = super(C)
02122 
02123         self.assertEqual(C().meth(3), "C(3)A(3)")
02124 
02125         class D(C, B):
02126             def meth(self, a):
02127                 return "D(%r)" % a + super(D, self).meth(a)
02128 
02129         self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
02130 
02131         # Test for subclassing super
02132 
02133         class mysuper(super):
02134             def __init__(self, *args):
02135                 return super(mysuper, self).__init__(*args)
02136 
02137         class E(D):
02138             def meth(self, a):
02139                 return "E(%r)" % a + mysuper(E, self).meth(a)
02140 
02141         self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
02142 
02143         class F(E):
02144             def meth(self, a):
02145                 s = self.__super # == mysuper(F, self)
02146                 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
02147         F._F__super = mysuper(F)
02148 
02149         self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
02150 
02151         # Make sure certain errors are raised
02152 
02153         try:
02154             super(D, 42)
02155         except TypeError:
02156             pass
02157         else:
02158             self.fail("shouldn't allow super(D, 42)")
02159 
02160         try:
02161             super(D, C())
02162         except TypeError:
02163             pass
02164         else:
02165             self.fail("shouldn't allow super(D, C())")
02166 
02167         try:
02168             super(D).__get__(12)
02169         except TypeError:
02170             pass
02171         else:
02172             self.fail("shouldn't allow super(D).__get__(12)")
02173 
02174         try:
02175             super(D).__get__(C())
02176         except TypeError:
02177             pass
02178         else:
02179             self.fail("shouldn't allow super(D).__get__(C())")
02180 
02181         # Make sure data descriptors can be overridden and accessed via super
02182         # (new feature in Python 2.3)
02183 
02184         class DDbase(object):
02185             def getx(self): return 42
02186             x = property(getx)
02187 
02188         class DDsub(DDbase):
02189             def getx(self): return "hello"
02190             x = property(getx)
02191 
02192         dd = DDsub()
02193         self.assertEqual(dd.x, "hello")
02194         self.assertEqual(super(DDsub, dd).x, 42)
02195 
02196         # Ensure that super() lookup of descriptor from classmethod
02197         # works (SF ID# 743627)
02198 
02199         class Base(object):
02200             aProp = property(lambda self: "foo")
02201 
02202         class Sub(Base):
02203             @classmethod
02204             def test(klass):
02205                 return super(Sub,klass).aProp
02206 
02207         self.assertEqual(Sub.test(), Base.aProp)
02208 
02209         # Verify that super() doesn't allow keyword args
02210         try:
02211             super(Base, kw=1)
02212         except TypeError:
02213             pass
02214         else:
02215             self.assertEqual("super shouldn't accept keyword args")

Here is the call graph for this function:

Definition at line 1845 of file test_descr.py.

01845 
01846     def test_testcapi_no_segfault(self):
01847         # this segfaulted in 2.5b2
01848         try:
01849             import _testcapi
01850         except ImportError:
01851             pass
01852         else:
01853             class X(object):
01854                 p = property(_testcapi.test_with_docstring)

Definition at line 3395 of file test_descr.py.

03395 
03396     def test_unintialized_modules(self):
03397         # Testing uninitialized module objects...
03398         from types import ModuleType as M
03399         m = M.__new__(M)
03400         str(m)
03401         self.assertEqual(hasattr(m, "__name__"), 0)
03402         self.assertEqual(hasattr(m, "__file__"), 0)
03403         self.assertEqual(hasattr(m, "foo"), 0)
03404         self.assertFalse(m.__dict__)   # None or {} are both reasonable answers
03405         m.foo = 1
03406         self.assertEqual(m.__dict__, {"foo": 1})

Here is the call graph for this function:

Definition at line 4020 of file test_descr.py.

04020 
04021     def test_vicious_descriptor_nonsense(self):
04022         # Testing vicious_descriptor_nonsense...
04023 
04024         # A potential segfault spotted by Thomas Wouters in mail to
04025         # python-dev 2003-04-17, turned into an example & fixed by Michael
04026         # Hudson just less than four months later...
04027 
04028         class Evil(object):
04029             def __hash__(self):
04030                 return hash('attr')
04031             def __eq__(self, other):
04032                 del C.attr
04033                 return 0
04034 
04035         class Descr(object):
04036             def __get__(self, ob, type=None):
04037                 return 1
04038 
04039         class C(object):
04040             attr = Descr()
04041 
04042         c = C()
04043         c.__dict__[Evil()] = 0
04044 
04045         self.assertEqual(c.attr, 1)
04046         # this makes a crash more likely:
04047         support.gc_collect()
04048         self.assertEqual(hasattr(c, 'attr'), False)

Here is the call graph for this function:

Definition at line 3979 of file test_descr.py.

03979 
03980     def test_weakref_segfault(self):
03981         # Testing weakref segfault...
03982         # SF 742911
03983         import weakref
03984 
03985         class Provoker:
03986             def __init__(self, referrent):
03987                 self.ref = weakref.ref(referrent)
03988 
03989             def __del__(self):
03990                 x = self.ref()
03991 
03992         class Oops(object):
03993             pass
03994 
03995         o = Oops()
03996         o.whatever = Provoker(o)
03997         del o

Here is the call graph for this function:

Definition at line 1739 of file test_descr.py.

01739 
01740     def test_weakrefs(self):
01741         # Testing weak references...
01742         import weakref
01743         class C(object):
01744             pass
01745         c = C()
01746         r = weakref.ref(c)
01747         self.assertEqual(r(), c)
01748         del c
01749         support.gc_collect()
01750         self.assertEqual(r(), None)
01751         del r
01752         class NoWeak(object):
01753             __slots__ = ['foo']
01754         no = NoWeak()
01755         try:
01756             weakref.ref(no)
01757         except TypeError as msg:
01758             self.assertTrue(str(msg).find("weak reference") >= 0)
01759         else:
01760             self.fail("weakref.ref(no) should be illegal")
01761         class Weak(object):
01762             __slots__ = ['foo', '__weakref__']
01763         yes = Weak()
01764         r = weakref.ref(yes)
01765         self.assertEqual(r(), yes)
01766         del yes
01767         support.gc_collect()
01768         self.assertEqual(r(), None)
01769         del r

Definition at line 3998 of file test_descr.py.

03998 
03999     def test_wrapper_segfault(self):
04000         # SF 927248: deeply nested wrappers could cause stack overflow
04001         f = lambda:None
04002         for i in range(1000000):
04003             f = f.__call__
04004         f = None


Member Data Documentation

Definition at line 886 of file test_descr.py.

Definition at line 2856 of file test_descr.py.

Definition at line 1353 of file test_descr.py.

Definition at line 3460 of file test_descr.py.

Definition at line 1351 of file test_descr.py.

self.assertIn('self', dir(C.Cmethod))

self.assertIn('self', dir(c.Cmethod)) self.assertIn('self', dir(A.Amethod)) self.assertIn('self', dir(a.Amethod))

Definition at line 2083 of file test_descr.py.

Definition at line 1352 of file test_descr.py.

Definition at line 459 of file test_descr.py.

Definition at line 2111 of file test_descr.py.

Definition at line 571 of file test_descr.py.

Definition at line 1863 of file test_descr.py.

Definition at line 2332 of file test_descr.py.

Definition at line 1036 of file test_descr.py.

Definition at line 1037 of file test_descr.py.

Definition at line 492 of file test_descr.py.

Definition at line 2580 of file test_descr.py.

Definition at line 1482 of file test_descr.py.

Definition at line 1491 of file test_descr.py.

Definition at line 493 of file test_descr.py.

Definition at line 1982 of file test_descr.py.

Definition at line 3719 of file test_descr.py.

Definition at line 1385 of file test_descr.py.

Definition at line 2581 of file test_descr.py.

Definition at line 1602 of file test_descr.py.

Definition at line 1983 of file test_descr.py.

Definition at line 491 of file test_descr.py.

Definition at line 2288 of file test_descr.py.

Definition at line 3986 of file test_descr.py.

Definition at line 1477 of file test_descr.py.

Definition at line 1489 of file test_descr.py.

Definition at line 412 of file test_descr.py.

Definition at line 2610 of file test_descr.py.

Definition at line 1516 of file test_descr.py.


The documentation for this class was generated from the following file: