diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py index 2ad302690..fc38a482e 100644 --- a/Lib/test/test_descr.py +++ b/Lib/test/test_descr.py @@ -7,6 +7,7 @@ import pickle import random import string import sys +import textwrap import types import unittest import warnings @@ -15,7 +16,7 @@ import weakref from copy import deepcopy from contextlib import redirect_stdout from test import support -from test.support.testcase import ExtraAssertions +from test.support.script_helper import assert_python_ok try: import _testcapi @@ -404,11 +405,11 @@ class OperatorsTest(unittest.TestCase): self.assertEqual(range(sys.maxsize).__len__(), sys.maxsize) -class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): +class ClassPropertiesAndMethods(unittest.TestCase): def test_python_dicts(self): # Testing Python subclass of dict... - self.assertTrue(issubclass(dict, dict)) + self.assertIsSubclass(dict, dict) self.assertIsInstance({}, dict) d = dict() self.assertEqual(d, {}) @@ -432,7 +433,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): self.state = state def getstate(self): return self.state - self.assertTrue(issubclass(C, dict)) + self.assertIsSubclass(C, dict) a1 = C(12) self.assertEqual(a1.state, 12) a2 = C(foo=1, bar=2) @@ -1047,15 +1048,15 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): m = types.ModuleType("m") self.assertTrue(m.__class__ is types.ModuleType) - self.assertFalse(hasattr(m, "a")) + self.assertNotHasAttr(m, "a") m.__class__ = SubType self.assertTrue(m.__class__ is SubType) - self.assertTrue(hasattr(m, "a")) + self.assertHasAttr(m, "a") m.__class__ = types.ModuleType self.assertTrue(m.__class__ is types.ModuleType) - self.assertFalse(hasattr(m, "a")) + self.assertNotHasAttr(m, "a") # Make sure that builtin immutable objects don't support __class__ # assignment, because the object instances may be interned. @@ -1102,7 +1103,8 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): with self.assertRaises(TypeError): frozenset().__class__ = MyFrozenSet - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON + @support.thread_unsafe def test_slots(self): # Testing __slots__... class C0(object): @@ -1319,7 +1321,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): with self.assertRaisesRegex(AttributeError, "'X' object has no attribute 'a'"): X().a - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_slots_special(self): # Testing __dict__ and __weakref__ in __slots__... class D(object): @@ -1358,7 +1360,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): a.foo = 42 self.assertEqual(a.__dict__, {"foo": 42}) - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_slots_special2(self): # Testing __qualname__ and __classcell__ in __slots__ class Meta(type): @@ -1543,6 +1545,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): else: self.fail("finding the most derived metaclass should have failed") + @unittest.expectedFailure # TODO: RUSTPYTHON def test_classmethods(self): # Testing class methods... class C(object): @@ -1588,8 +1591,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): self.fail("classmethod shouldn't accept keyword args") cm = classmethod(f) - cm_dict = {'__annotations__': {}, - '__doc__': ( + cm_dict = {'__doc__': ( "f docstring" if support.HAVE_PY_DOCSTRINGS else None @@ -1605,6 +1607,56 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): del cm.x self.assertNotHasAttr(cm, "x") + @unittest.expectedFailure # TODO: RUSTPYTHON + def test_classmethod_staticmethod_annotations(self): + for deco in (classmethod, staticmethod): + @deco + def unannotated(cls): pass + @deco + def annotated(cls) -> int: pass + + for method in (annotated, unannotated): + with self.subTest(deco=deco, method=method): + with self.assertRaises(AttributeError): + del unannotated.__annotations__ + + original_annotations = dict(method.__wrapped__.__annotations__) + self.assertNotIn('__annotations__', method.__dict__) + self.assertEqual(method.__annotations__, original_annotations) + self.assertIn('__annotations__', method.__dict__) + + new_annotations = {"a": "b"} + method.__annotations__ = new_annotations + self.assertEqual(method.__annotations__, new_annotations) + self.assertEqual(method.__wrapped__.__annotations__, original_annotations) + + del method.__annotations__ + self.assertEqual(method.__annotations__, original_annotations) + + original_annotate = method.__wrapped__.__annotate__ + self.assertNotIn('__annotate__', method.__dict__) + self.assertIs(method.__annotate__, original_annotate) + self.assertIn('__annotate__', method.__dict__) + + new_annotate = lambda: {"annotations": 1} + method.__annotate__ = new_annotate + self.assertIs(method.__annotate__, new_annotate) + self.assertIs(method.__wrapped__.__annotate__, original_annotate) + + del method.__annotate__ + self.assertIs(method.__annotate__, original_annotate) + + def test_staticmethod_annotations_without_dict_access(self): + # gh-125017: this used to crash + class Spam: + def __new__(cls, x, y): + pass + + self.assertEqual(Spam.__new__.__annotations__, {}) + obj = Spam.__dict__['__new__'] + self.assertIsInstance(obj, staticmethod) + self.assertEqual(obj.__annotations__, {}) + @support.refcount_test def test_refleaks_in_classmethod___init__(self): gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount') @@ -1733,7 +1785,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): class E: # *not* subclassing from C foo = C.foo self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound - self.assertTrue(repr(C.foo.__get__(C())).startswith("__... @@ -4382,7 +4457,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): self.assertIsInstance(a, C) # Baseline self.assertIsInstance(pa, C) # Test - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_proxy_super(self): # Testing super() for a proxy object... class Proxy(object): @@ -4406,7 +4481,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): p = Proxy(obj) self.assertEqual(C.__dict__["f"](p), "B.f->C.f") - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_carloverre(self): # Testing prohibition of Carlo Verre's hack... try: @@ -4439,7 +4514,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): except TypeError: self.fail("setattr through direct base types should be legal") - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_carloverre_multi_inherit_invalid(self): class A(type): def __setattr__(cls, key, value): @@ -4478,7 +4553,9 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): o.whatever = Provoker(o) del o - @unittest.skip('TODO: RUSTPYTHON; rustpython segmentation fault') + @unittest.skip("TODO: RUSTPYTHON; rustpython segmentation fault") + @support.skip_wasi_stack_overflow() + @support.skip_emscripten_stack_overflow() @support.requires_resource('cpu') def test_wrapper_segfault(self): # SF 927248: deeply nested wrappers could cause stack overflow @@ -4553,7 +4630,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): with self.assertRaises(TypeError): a >= b - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_method_wrapper(self): # Testing method-wrapper objects... # did not support any reflection before 2.5 @@ -4766,7 +4843,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): with self.assertRaises(AttributeError): del X.__abstractmethods__ - @unittest.skip('TODO: RUSTPYTHON; crash. "dict has non-string keys: [PyObject PyInt { value: 1 }]"') + @unittest.skip("TODO: RUSTPYTHON; crash. \"dict has non-string keys: [PyObject PyInt { value: 1 }]\"") def test_gh55664(self): # gh-55664: issue a warning when the # __dict__ of a class contains non-string keys @@ -4824,6 +4901,8 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): # CALL_METHOD_DESCRIPTOR_O deque.append(thing, thing) + @support.skip_emscripten_stack_overflow() + @support.skip_wasi_stack_overflow() def test_repr_as_str(self): # Issue #11603: crash or infinite loop when rebinding __str__ as # __repr__. @@ -4855,7 +4934,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): with self.assertRaises(TypeError): a + a - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_slot_shadows_class_variable(self): with self.assertRaises(ValueError) as cm: class X: @@ -4864,7 +4943,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): m = str(cm.exception) self.assertEqual("'foo' in __slots__ conflicts with class variable", m) - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_set_doc(self): class X: "elephant" @@ -4880,7 +4959,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): self.assertIn("cannot delete '__doc__' attribute of immutable type 'X'", str(cm.exception)) self.assertEqual(X.__doc__, "banana") - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_qualname(self): descriptors = [str.lower, complex.real, float.real, int.__add__] types = ['method', 'member', 'getset', 'wrapper'] @@ -4913,7 +4992,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): self.assertEqual(Y.__qualname__, 'Y') self.assertEqual(Y.Inside.__qualname__, 'Y.Inside') - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_qualname_dict(self): ns = {'__qualname__': 'some.name'} tp = type('Foo', (), ns) @@ -4924,7 +5003,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): ns = {'__qualname__': 1} self.assertRaises(TypeError, type, 'Foo', (), ns) - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_cycle_through_dict(self): # See bug #1469629 class X(dict): @@ -5039,7 +5118,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): cls.lst = [2**i for i in range(10000)] X.descr - @support.suppress_immortalization() + @unittest.expectedFailure # TODO: RUSTPYTHON def test_remove_subclass(self): # bpo-46417: when the last subclass of a type is deleted, # remove_subclass() clears the internal dictionary of subclasses: @@ -5057,7 +5136,7 @@ class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions): gc.collect() self.assertEqual(Parent.__subclasses__(), []) - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_instance_method_get_behavior(self): # test case for gh-113157 @@ -5107,7 +5186,7 @@ class DictProxyTests(unittest.TestCase): pass self.C = C - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), 'trace function introduces __local__') def test_iter_keys(self): @@ -5121,7 +5200,7 @@ class DictProxyTests(unittest.TestCase): '__static_attributes__', '__weakref__', 'meth']) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: 5 != 7 + @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: 5 != 7 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), 'trace function introduces __local__') def test_iter_values(self): @@ -5131,7 +5210,7 @@ class DictProxyTests(unittest.TestCase): values = list(it) self.assertEqual(len(values), 7) - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), 'trace function introduces __local__') def test_iter_items(self): @@ -5161,8 +5240,8 @@ class DictProxyTests(unittest.TestCase): # We can't blindly compare with the repr of another dict as ordering # of keys and values is arbitrary and may differ. r = repr(self.C.__dict__) - self.assertTrue(r.startswith('mappingproxy('), r) - self.assertTrue(r.endswith(')'), r) + self.assertStartsWith(r, 'mappingproxy(') + self.assertEndsWith(r, ')') for k, v in self.C.__dict__.items(): self.assertIn('{!r}: {!r}'.format(k, v), r) @@ -5198,6 +5277,7 @@ class MiscTests(unittest.TestCase): # Issue #14199: _PyType_Lookup() has to keep a strong reference to # the type MRO because it may be modified during the lookup, if # __bases__ is set during the lookup for example. + code = textwrap.dedent(""" class MyKey(object): def __hash__(self): return hash('mykey') @@ -5213,17 +5293,29 @@ class MiscTests(unittest.TestCase): mykey = 'from Base2' mykey2 = 'from Base2' - with self.assertWarnsRegex(RuntimeWarning, 'X'): - X = type('X', (Base,), {MyKey(): 5}) + X = type('X', (Base,), {MyKey(): 5}) - # Note that the access below uses getattr() rather than normally - # accessing the attribute. That is done to avoid the bytecode - # specializer activating on repeated runs of the test. + bases_before = ",".join([c.__name__ for c in X.__bases__]) + print(f"before={bases_before}") - # mykey is read from Base - self.assertEqual(getattr(X, 'mykey'), 'from Base') - # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__ - self.assertEqual(getattr(X, 'mykey2'), 'from Base2') + # mykey is initially read from Base, however, the lookup will be perfomed + # again if specialization fails. The second lookup will use the new + # mro set by __eq__. + print(X.mykey) + + bases_after = ",".join([c.__name__ for c in X.__bases__]) + print(f"after={bases_after}") + + # mykey2 is read from Base2 because MyKey.__eq__ has set __bases_ + print(f"mykey2={X.mykey2}") + """) + _, out, err = assert_python_ok("-c", code) + err = err.decode() + self.assertRegex(err, "RuntimeWarning: .*X") + out = out.decode() + self.assertRegex(out, "before=Base") + self.assertRegex(out, "after=Base2") + self.assertRegex(out, "mykey2=from Base2") class PicklingTests(unittest.TestCase): @@ -5446,6 +5538,7 @@ class PicklingTests(unittest.TestCase): {pickle.dumps, pickle._dumps}, {pickle.loads, pickle._loads})) + @support.thread_unsafe def test_pickle_slots(self): # Tests pickling of classes with __slots__. @@ -5513,6 +5606,7 @@ class PicklingTests(unittest.TestCase): y = pickle_copier.copy(x) self._assert_is_copy(x, y) + @support.thread_unsafe def test_reduce_copying(self): # Tests pickling and copying new-style classes and objects. global C1 @@ -5637,7 +5731,7 @@ class PicklingTests(unittest.TestCase): objcopy2 = deepcopy(objcopy) self._assert_is_copy(obj, objcopy2) - @unittest.skip('TODO: RUSTPYTHON') + @unittest.skip("TODO: RUSTPYTHON") def test_issue24097(self): # Slot name is freed inside __getattr__ and is later used. class S(str): # Not interned @@ -5778,7 +5872,7 @@ class MroTest(unittest.TestCase): class C(B): pass - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_reent_set_bases_tp_base_cycle(self): """ type_set_bases must check for an inheritance cycle not only through @@ -5815,7 +5909,7 @@ class MroTest(unittest.TestCase): with self.assertRaises(TypeError): B1.__bases__ += () - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_tp_subclasses_cycle_in_update_slots(self): """ type_set_bases must check for reentrancy upon finishing its job @@ -5852,7 +5946,7 @@ class MroTest(unittest.TestCase): self.assertEqual(B1.__bases__, (C,)) self.assertEqual(C.__subclasses__(), [B1]) - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_tp_subclasses_cycle_error_return_path(self): """ The same as test_tp_subclasses_cycle_in_update_slots, but tests @@ -5921,7 +6015,7 @@ class MroTest(unittest.TestCase): class A(metaclass=M): pass - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON def test_disappearing_custom_mro(self): """ gh-92112: A custom mro() returning a result conflicting with