diff --git a/Src/IronPython/Lib/iptest/type_util.py b/Src/IronPython/Lib/iptest/type_util.py index 4fe442837..d5255a7e5 100644 --- a/Src/IronPython/Lib/iptest/type_util.py +++ b/Src/IronPython/Lib/iptest/type_util.py @@ -46,9 +46,12 @@ def remove_clr_specific_attrs(attr_list): array_object = System.Array[object] array_byte = System.Array[System.Byte] - # sample numberes? - clr_signed_types = (System.SByte, System.Int16, System.Int32, System.Int64, System.Decimal, System.Single, System.Double) + # sample numbers? + clr_float_types = (System.Decimal, System.Single, System.Double) + clr_int_signed_types = (System.SByte, System.Int16, System.Int32, System.Int64) + clr_signed_types = clr_int_signed_types + clr_float_types clr_unsigned_types = (System.Byte, System.UInt16, System.UInt32, System.UInt64) + clr_int_types = clr_int_signed_types + clr_unsigned_types clr_all_types = clr_signed_types + clr_unsigned_types clr_all_plus1 = [t.Parse("1") for t in clr_all_types] diff --git a/Src/IronPython/Runtime/Binding/PythonProtocol.cs b/Src/IronPython/Runtime/Binding/PythonProtocol.cs index 37f0eeace..a2b745927 100644 --- a/Src/IronPython/Runtime/Binding/PythonProtocol.cs +++ b/Src/IronPython/Runtime/Binding/PythonProtocol.cs @@ -89,7 +89,7 @@ internal static DynamicMetaObject ConvertToBool(DynamicMetaObjectBinder/*!*/ con callAsInt = DynamicExpression.Dynamic( state.Convert(typeof(int), ConversionResultKind.ExplicitCast), typeof(int), - call + Ast.Call(typeof(PythonOps).GetMethod(nameof(PythonOps.Index)), call) ); } @@ -104,7 +104,7 @@ internal static DynamicMetaObject ConvertToBool(DynamicMetaObjectBinder/*!*/ con Ast.Constant("__len__() should return >= 0"), Ast.NewArrayInit(typeof(object)) ) - ) + ) ), Ast.NotEqual(res, Ast.Constant(0)) ); diff --git a/Src/IronPython/Runtime/Operations/PythonOps.cs b/Src/IronPython/Runtime/Operations/PythonOps.cs index 32ec548ee..486593203 100644 --- a/Src/IronPython/Runtime/Operations/PythonOps.cs +++ b/Src/IronPython/Runtime/Operations/PythonOps.cs @@ -774,7 +774,9 @@ public static object Index(object? o) { throw TypeError("'{0}' object cannot be interpreted as an integer", PythonTypeOps.GetName(o)); } - internal static bool TryToIndex(object? o, [NotNullWhen(true)]out object? index) { + internal static bool TryToIndex(object? o, [NotNullWhen(true)] out object? index) { + var context = DefaultContext.Default; + switch (o) { case int i: index = Int32Ops.__index__(i); @@ -807,26 +809,42 @@ internal static bool TryToIndex(object? o, [NotNullWhen(true)]out object? index) break; } - if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, o, "__index__", out index)) { - if (!(index is int) && !(index is BigInteger)) - throw TypeError("__index__ returned non-int (type {0})", PythonTypeOps.GetName(index)); - return true; + if (PythonTypeOps.TryInvokeUnaryOperator(context, o, "__index__", out index)) { + if (index is int || index is BigInteger) + return true; + if (index is Extensible || index is Extensible) { + Warn(context, PythonExceptions.DeprecationWarning, $"__index__ returned non-int (type {PythonTypeOps.GetName(index)}). The ability to return an instance of a strict subclass of int is deprecated, and may be removed in a future version of Python."); + return true; + } + throw TypeError("__index__ returned non-int (type {0})", PythonTypeOps.GetName(index)); } index = default; return false; } - private static bool ObjectToInt(object o, out int res, out BigInteger longRes) { - if (o is BigInteger bi) { - if (!bi.AsInt32(out res)) { - longRes = bi; - return false; - } - } else if (o is int i) { - res = i; - } else { - res = Converter.ConvertToInt32(o); + private static bool IndexObjectToInt(object o, out int res, out BigInteger longRes) { + switch (o) { + case int i: + res = i; + break; + case Extensible ei: // deprecated + res = ei; + break; + case BigInteger bi: + if (!bi.AsInt32(out res)) { + longRes = bi; + return false; + } + break; + case Extensible ebi: // deprecated + if (!ebi.Value.AsInt32(out res)) { + longRes = ebi; + return false; + } + break; + default: + throw new InvalidOperationException(); } longRes = default; @@ -848,7 +866,9 @@ internal static bool Length(object? o, out int res, out BigInteger bigRes) { object len = PythonContext.InvokeUnaryOperator(DefaultContext.Default, UnaryOperators.Length, o, $"object of type '{GetPythonTypeName(o)}' has no len()"); - if (ObjectToInt(len, out res, out bigRes)) { + var indexObj = Index(len); + + if (IndexObjectToInt(indexObj, out res, out bigRes)) { if (res < 0) throw ValueError("__len__() should return >= 0"); return true; } else { diff --git a/Src/IronPythonTest/Cases/IronPythonCasesManifest.ini b/Src/IronPythonTest/Cases/IronPythonCasesManifest.ini index 90ac56c99..cbad60bf8 100644 --- a/Src/IronPythonTest/Cases/IronPythonCasesManifest.ini +++ b/Src/IronPythonTest/Cases/IronPythonCasesManifest.ini @@ -8,9 +8,6 @@ Timeout=120000 # 2 minute timeout RunCondition=NOT $(IS_MONO) Reason=Exception on adding DocTestSuite -[IronPython.test_class] -Ignore=true - [IronPython.test_cliclass] IsolationLevel=PROCESS # TODO: figure out - wpf fails to load otherwise diff --git a/Tests/test_class.py b/Tests/test_class.py index 7afda335b..25c0c43dc 100644 --- a/Tests/test_class.py +++ b/Tests/test_class.py @@ -3,6 +3,7 @@ # See the LICENSE file in the project root for more information. # from iptest.type_util import * +import os import sys import unittest @@ -53,24 +54,6 @@ def test_common_attributes(self): repr(getattr(i, "__init__")) repr(getattr(i, "__new__")) - def test_set_dict(self): - class C: pass - setdict = C.__dict__ - C.__dict__ = setdict - - o1 = C() - - class C: - def m(self): - return 42 - - o2 = C() - self.assertTrue(42 == o2.m()) - - self.assertTrue(o2.__class__ is C) - self.assertTrue(o2.__class__ is not o1.__class__) - - def test_attrs(self): class C:pass @@ -87,7 +70,7 @@ class C:pass def test_type_in(self): - self.assertEqual(type in (None, True, False, 1, {}, [], (), 1.0, 1, (1+0j)), False) + self.assertEqual(type in (None, True, False, 1, {}, [], (), 1.0, long(1), (1+0j)), False) def test_init_defaults(self): class A: @@ -106,7 +89,7 @@ def __init__(self, height=20, width=30): def test_getattr(self): class C: def __init__(self, name, flag): - self.f = file(name, flag) + self.f = open(name, flag) def __getattr__(self, name): return getattr(self.f, name) @@ -120,7 +103,6 @@ def __getattr__(self, name): c.close() try: - import os os.unlink(tmpfile) except: pass @@ -228,7 +210,9 @@ def __init__(self): def test_misc(self): - class C: + class B: pass + + class C(B): def x(self): return 'C.x' def y(self): @@ -245,17 +229,14 @@ def z(self): # verify repr and str on old-style class objects have the right format: # bug# 795 - self.assertEqual(str(C), __name__+'.C') - self.assertEqual(repr(C).index('".format(__name__, "" if is_cli else ".ClassTest.test_misc.")) + self.assertTrue(repr(C), str(C)) - success=0 - try: + with self.assertRaises(AttributeError): c.z() - except AttributeError: - success=1 - self.assertTrue(success==1) - C.__bases__+=(D,) + self.assertEqual(C.__bases__, (B,)) + C.__bases__ += (D,) self.assertEqual(c.z(), "D.z") @@ -274,6 +255,15 @@ def n(self, parm): self.assertTrue('__dict__' not in str.__dict__) + class E: pass + class F: pass + + if is_cli: + F.__bases__ = (E,) + else: + with self.assertRaises(TypeError): + F.__bases__ = (E,) + def test_dir_in_init(self): # both of these shouldn't throw @@ -283,7 +273,6 @@ def __init__(self): a = DirInInit() - def test_priv_class(self): class _PrivClass(object): def __Mangled(self): @@ -302,43 +291,42 @@ class bar(foo): def barfunc(self): return "barfunc" - class baz(foo, bar): + class baz(bar, foo): def bazfunc(self): return "bazfunc" - self.assertTrue('foofunc' in dir(foo)) - self.assertTrue(dir(foo).count('__doc__') == 1) - self.assertTrue(dir(foo).count('__module__') == 1) - self.assertTrue(len(dir(foo)) == 3) - self.assertTrue('foofunc' in dir(bar)) - self.assertTrue('barfunc' in dir(bar)) - self.assertTrue(dir(bar).count('__doc__') == 1) - self.assertTrue(dir(bar).count('__module__') == 1) - self.assertTrue(len(dir(bar)) == 4) - self.assertTrue('foofunc' in dir(baz)) - self.assertTrue('barfunc' in dir(baz)) - self.assertTrue('bazfunc' in dir(baz)) - self.assertTrue(dir(baz).count('__doc__') == 1) - self.assertTrue(dir(baz).count('__module__') == 1) - self.assertTrue(len(dir(baz)) == 5) + self.assertIn('foofunc', dir(foo)) + self.assertEqual(dir(foo).count('__doc__'), 1) + self.assertEqual(dir(foo).count('__module__'), 1) + self.assertEqual(len(dir(foo)) - len(dir(object)), 4) + self.assertIn('foofunc', dir(bar)) + self.assertIn('barfunc', dir(bar)) + self.assertEqual(dir(bar).count('__doc__'), 1) + self.assertEqual(dir(bar).count('__module__'), 1) + self.assertEqual(len(dir(bar)) - len(dir(object)), 5) + self.assertIn('foofunc', dir(baz)) + self.assertIn('barfunc', dir(baz)) + self.assertIn('bazfunc', dir(baz)) + self.assertEqual(dir(baz).count('__doc__'), 1) + self.assertEqual(dir(baz).count('__module__'), 1) + self.assertEqual(len(dir(baz)) - len(dir(object)), 6) bz = baz() - self.assertTrue('foofunc' in dir(bz)) - self.assertTrue('barfunc' in dir(bz)) - self.assertTrue('bazfunc' in dir(bz)) - self.assertTrue(dir(bz).count('__doc__') == 1) - self.assertTrue(dir(bz).count('__module__') == 1) - self.assertTrue(len(dir(bz)) == 5) + self.assertIn('foofunc', dir(bz)) + self.assertIn('barfunc', dir(bz)) + self.assertIn('bazfunc', dir(bz)) + self.assertEqual(dir(bz).count('__doc__'), 1) + self.assertEqual(dir(bz).count('__module__'), 1) + self.assertEqual(len(dir(bz)) - len(dir(object)), 6) bz.__module__ = "MODULE" - self.assertTrue(bz.__module__ == "MODULE") + self.assertEqual(bz.__module__, "MODULE") bz.__module__ = "SOMEOTHERMODULE" - self.assertTrue(bz.__module__ == "SOMEOTHERMODULE") + self.assertEqual(bz.__module__, "SOMEOTHERMODULE") bz.__module__ = 33 - self.assertTrue(bz.__module__ == 33) + self.assertEqual(bz.__module__, 33) bz.__module__ = [2, 3, 4] - self.assertTrue(bz.__module__ == [2, 3 , 4]) - + self.assertEqual(bz.__module__, [2, 3, 4]) def test_oldstyle_setattr(self): global called @@ -431,7 +419,7 @@ def __str__(self): self.assertEqual(str(A()), 'foo') self.assertEqual(repr(A()), 'foo') self.assertEqual(str(B()), 'foo') - self.assertTrue(repr(B()).find('B instance') != -1) + self.assertIn('B object', repr(B())) # use exec to define methods on classes: @@ -488,7 +476,7 @@ class C: pass def f(x): x.__module__ def g(x): getattr(x, '__module__') import errno - for thing in "", 1, errno, 1, 1+2j, (), [], {}: + for thing in "", 1, errno, long(1), 1+2j, (), [], {}: self.assertEqual(getattr(thing, '__module__', 'does_not_exist'), 'does_not_exist') self.assertEqual(hasattr(thing, '__module__'), False) self.assertRaises(AttributeError, f, thing) @@ -504,61 +492,43 @@ class x(object): pass def test_check_dictionary(self): """tests to verify that Symbol dictionaries do the right thing in dynamic scenarios""" - def CheckDictionary(C): - # add a new attribute to the type... - C.newClassAttr = 'xyz' - self.assertEqual(C.newClassAttr, 'xyz') - - # add non-string index into the class and instance dictionary - a = C() - a.__dict__[1] = '1' - if object in C.__bases__: - try: - C.__dict__[2] = '2' - self.fail("Unreachable code reached") - except TypeError: pass - self.assertEqual(2 in C.__dict__, False) - - self.assertEqual(1 in a.__dict__, True) - self.assertEqual(dir(a).__contains__(1), True) - - self.assertEqual(repr(a.__dict__), "{1: '1'}") - - # replace a class dictionary (containing non-string keys) w/ a normal dictionary - C.newTypeAttr = 1 - self.assertEqual(hasattr(C, 'newTypeAttr'), True) + class C(object): + def __init__(self): pass - class OldClass: pass + # add a new attribute to the type... + C.newClassAttr = 'xyz' + self.assertEqual(C.newClassAttr, 'xyz') - if isinstance(C, type(OldClass)): - C.__dict__ = dict(C.__dict__) - self.assertEqual(hasattr(C, 'newTypeAttr'), True) - else: - try: - C.__dict__ = {} - self.fail("Unreachable code reached") - except AttributeError: - pass + # add non-string index into the class and instance dictionary + a = C() + a.__dict__[1] = '1' + if object in C.__bases__: + with self.assertRaises(TypeError): + C.__dict__[2] = '2' + self.assertEqual(2 in C.__dict__, False) - # replace an instance dictionary (containing non-string keys) w/ a new one. - a.newInstanceAttr = 1 - self.assertEqual(hasattr(a, 'newInstanceAttr'), True) - a.__dict__ = dict(a.__dict__) - self.assertEqual(hasattr(a, 'newInstanceAttr'), True) + self.assertEqual(1 in a.__dict__, True) + with self.assertRaises(TypeError): # TypeError: unorderable types: str() < int() + dir(a) - a.abc = 'xyz' - self.assertEqual(hasattr(a, 'abc'), True) - self.assertEqual(getattr(a, 'abc'), 'xyz') + self.assertEqual(repr(a.__dict__), "{1: '1'}") + # replace a class dictionary (containing non-string keys) w/ a normal dictionary + C.newTypeAttr = 1 + self.assertEqual(hasattr(C, 'newTypeAttr'), True) - class OldClass: - def __init__(self): pass + with self.assertRaises(AttributeError): + C.__dict__ = {} - class NewClass(object): - def __init__(self): pass + # replace an instance dictionary (containing non-string keys) w/ a new one. + a.newInstanceAttr = 1 + self.assertEqual(hasattr(a, 'newInstanceAttr'), True) + a.__dict__ = dict(a.__dict__) + self.assertEqual(hasattr(a, 'newInstanceAttr'), True) - CheckDictionary(OldClass) - CheckDictionary(NewClass) + a.abc = 'xyz' + self.assertEqual(hasattr(a, 'abc'), True) + self.assertEqual(getattr(a, 'abc'), 'xyz') def test_call_type_call(self): for stuff in [object, int, str, bool, float]: @@ -573,36 +543,6 @@ def test_call_type_call(self): #User-defined old/new style classes call_mapper = {} - class KOld0: - def __call__(self): - return 2 - call_mapper[KOld0] = lambda: [type(KOld0()).__call__(KOld0())] - - class KOld1: - def __call__(self, p): - return 2 - call_mapper[KOld1] = lambda: [type(KOld1()).__call__(KOld1(), 3.14), - type(KOld1()).__call__(KOld1(), p=3.14), - type(KOld1()).__call__(KOld1(), **{"p":3.14}), - type(KOld1()).__call__(KOld1(), (1, 2, 3)) ] - - class KOldArgs: - def __call__(self, *args): - return 2 - call_mapper[KOldArgs] = lambda: [type(KOldArgs()).__call__(KOldArgs())] - - class KOldKwargs: - def __call__(self, **kwargs): - return 2 - call_mapper[KOldKwargs] = lambda: [type(KOldKwargs()).__call__(KOldKwargs())] - - class KOldArgsKwargs: - def __call__(self, *args, **kwargs): - return 2 - call_mapper[KOldArgsKwargs] = lambda: [type(KOldArgsKwargs()).__call__(KOldArgsKwargs())] - - - class KNew0(object): def __call__(self): return 2 @@ -614,7 +554,7 @@ def __call__(self, p): call_mapper[KNew1] = lambda: [type(KNew1()).__call__(KNew1(), 3.14), type(KNew1()).__call__(KNew1(), p=3.14), type(KNew1()).__call__(KNew1(), **{"p":3.14}), - type(KNew1()).__call__(KNew1(), []), + type(KNew1()).__call__(KNew1(), (1, 2, 3)), ] class KNewArgs(object): @@ -709,9 +649,9 @@ def test_newstyle_unbound_inheritance(self): class foo: def func(self): return self - class bar(object, foo): + class bar(foo): def barfunc(self): - return foo.func(self) + return foo.func(self) a = bar() self.assertEqual(a.barfunc(), a) @@ -734,17 +674,11 @@ class N(C,B,A): pass self.assertEqual(N.__mro__, (N, C, B, A, object)) - try: + with self.assertRaises(TypeError, msg="impossible MRO created"): class N(A, B,C): pass - self.fail("Unreachable code reached: impossible MRO created") - except TypeError: - pass - try: + with self.assertRaises(TypeError, msg="can't derive from the same base type twice"): class N(A, A): pass - self.fail("Unreachable code reached: can't dervie from the same base type twice") - except TypeError: - pass def test_mro_bases(self): """verify replacing base classes also updates MRO""" @@ -828,36 +762,32 @@ class C(A): pass class D(B, C):pass - class E(D, object): pass + class E(D): pass # old-style MRO of D is D, B, A, C, which should # be present in E's mro - self.assertEqual(E.__mro__, (E, D, B, A, C, object)) + self.assertEqual(E.__mro__, (E, D, B, C, A, object)) - class F(B, C, object): pass + class F(B, C): pass # but when inheriting from multiple old-style classes we switch # to new-style MRO, and respect local ordering of classes in the MRO self.assertEqual(F.__mro__, (F, B, C, A, object)) - class G(B, object, C): pass + class G(B, C): pass - self.assertEqual(G.__mro__, (G, B, object, C, A)) + self.assertEqual(G.__mro__, (G, B, C, A, object)) class H(E): pass - self.assertEqual(H.__mro__, (H, E, D, B, A, C, object)) + self.assertEqual(H.__mro__, (H, E, D, B, C, A, object)) - try: + with self.assertRaises(TypeError): class H(A,B,E): pass - self.fail("Unreachable code reached") - except TypeError: - pass - class H(E,B,A): pass - self.assertEqual(H.__mro__, (H, E, D, B, A, C, object)) + self.assertEqual(H.__mro__, (H, E, D, B, C, A, object)) def test_depth_first_mro_mixed(self): """Verify given two large, independent class hierarchies @@ -886,7 +816,7 @@ class K(H,I, object): pass class L(K,E): pass - self.assertEqual(L.__mro__, (L, K, H, I, G, E, D, B, A, C, object)) + self.assertEqual(L.__mro__, (L, K, H, I, G, E, D, B, C, A, object)) def test_depth_first_mro(self): @@ -936,11 +866,6 @@ def onearg(self): def onearg_str(self): return 'abc' - # create methods that we can then stick into Strange - twoargs = type(Strange.uselessMethod)(twoargs, None, Strange) - onearg = type(Strange.uselessMethod)(onearg, None, Strange) - - class ForwardAndReverseTests: testCases = [ #forward versions @@ -976,11 +901,8 @@ class ForwardAndReverseTests: def NegativeTest(method, testCase): setattr(obj, method, twoargs) - try: + with self.assertRaises(TypeError): eval(testCase) - self.fail("Unreachable code reached") - except TypeError as e: - pass delattr(obj, method) @@ -1014,11 +936,8 @@ class InPlaceTests: def NegativeTest(method, testCase): setattr(obj, method, twoargs) - try: + with self.assertRaises(TypeError): exec(testCase, globals(), locals()) - self.fail("Unreachable code reached") - except TypeError: - pass delattr(obj, method) @@ -1047,11 +966,8 @@ class SingleArgTests: def NegativeTest(method, testCase): setattr(obj, method, onearg) - try: + with self.assertRaises(TypeError): eval(testCase) - self.fail("Unreachable code reached") - except TypeError: - pass delattr(obj, method) @@ -1066,40 +982,16 @@ def PositiveTest(method, testCase): delattr(Strange, method) - class HexOctTests: - testCases = [ - ('__oct__', 'oct(obj)'), - ('__hex__', 'hex(obj)'), - ] - - @staticmethod - def NegativeTest(method, testCase): - setattr(obj, method, onearg) - - try: - eval(testCase) - self.fail("Unreachable code reached") - except TypeError: - pass - - delattr(obj, method) - - @staticmethod - def PositiveTest(method, testCase): - setattr(Strange, method, onearg_str) - - self.assertEqual(eval(testCase), 'abc') - - delattr(Strange, method) - class ConversionTests: testCases = [ (('__complex__', 2+0j), 'complex(obj)'), (('__int__', 1), 'int(obj)'), - (('__long__', 1), 'long(obj)'), (('__float__', 1.0), 'float(obj)'), ] + if is_cli: # https://github.com/IronLanguages/ironpython3/issues/894 + testCases.append((('__long__', long(1)), 'long(obj)')) + @staticmethod def NegativeTest(method, testCase): setattr(obj, method[0], onearg) @@ -1117,14 +1009,13 @@ def PositiveTest(method, testCase): def testMethod(self): return method[1] - testMethod = type(Strange.uselessMethod)(testMethod, None, Strange) setattr(Strange, method[0], testMethod) self.assertEqual(eval(testCase), method[1]) delattr(Strange, method[0]) - allTests = [ForwardAndReverseTests, InPlaceTests, SingleArgTests, ConversionTests, HexOctTests] + allTests = [ForwardAndReverseTests, InPlaceTests, SingleArgTests, ConversionTests] for test in allTests: for method,testCase in test.testCases: @@ -1176,7 +1067,7 @@ def meth(self): class G: pass - def gmeth(self): return 'G' + def gmeth(): return 'G' class A(object): @@ -1217,7 +1108,7 @@ class D(C, B, F): def meth(self): return "D" + super(D, self).meth() - self.assertEqual(D.__mro__, (D,C,B,A,object,F)) + self.assertEqual(D.__mro__, (D,C,B,A,F,object)) self.assertEqual(D().meth(), 'DCBAF') @@ -1226,7 +1117,7 @@ def meth(self): return "D" + super(D, self).meth() d = D() - d.meth = type(F.meth)(gmeth, d, G) + d.meth = gmeth self.assertEqual(d.meth(), 'G') @@ -1325,12 +1216,9 @@ class foo(object): # invalid __slots__ values for x in ['', None, '3.5']: - try: + with self.assertRaises(TypeError): class C(object): __slots__ = x - self.fail("Unreachable code reached") - except TypeError: - pass # including __dict__ in slots allows accessing __dict__ class A(object): __slots__ = '__dict__' @@ -1473,32 +1361,12 @@ class Foo(object): a.__dict__['bar'] = 'abc' self.assertRaises(AttributeError, lambda : a.bar) - # members defined the class take precedence over slots - global initCalled - class Foo(object): - __slots__ = ["__init__"] - def __init__(self): - global initCalled - initCalled = True - - initCalled = False - a = Foo() - self.assertEqual(initCalled, True) - - # the member is readonly because the member slot is gone. - def f(): a.__init__ = 'abc' - self.assertRaises(AttributeError, f) - - # make sure __init__ isn't special - class Foo(object): - __slots__ = ["abc"] - abc = 3 - - a = Foo() - self.assertEqual(a.abc, 3) - - def f(): a.abc = 'abc' - self.assertRaises(AttributeError, f) + # ValueError: '__init__' in __slots__ conflicts with class variable + with self.assertRaises(ValueError): + class Foo(object): + __slots__ = ["__init__"] + def __init__(self): + pass class Foo(object): __slots__ = 'abc' @@ -1544,17 +1412,12 @@ def test_inheritance_cycle(self): class CycleA: pass class CycleB: pass - try: + with self.assertRaises(TypeError): CycleA.__bases__ = (CycleA,) - self.self.fail("Unreachable code reached") - except TypeError: pass - try: + with self.assertRaises(TypeError): CycleA.__bases__ = (CycleB,) CycleB.__bases__ = (CycleA,) - self.self.fail("Unreachable code reached") - except TypeError: pass - def test_hexoct(self): """returning non-string from hex & oct should throw""" @@ -1581,8 +1444,8 @@ class x: pass for stuff in [object, int, float, bool, str, int, complex, dict, set, None, NotImplemented, Ellipsis, type(self.test_no_clr_attributes), classmethod, staticmethod, frozenset, property, sys, - BaseException, type(zip), slice, buffer, enumerate, file, - range, xrange, type(x), type(x())]: + BaseException, type(zip), slice, memoryview, enumerate, + range, range, type(x), type(x())]: for dir_stuff in dir(stuff): if dir_stuff[:1].isalpha(): self.assertTrue(dir_stuff[:1].islower(), @@ -1622,10 +1485,8 @@ class C: for x in [None, 'abc', 3]: class foo(object): pass a = foo() - try: + with self.assertRaises(TypeError): a.__dict__ = x - self.fail("Unreachable code reached") - except TypeError: pass def test_default_new_init(self): """test cases to verify we do the right thing for the default new & init @@ -1767,12 +1628,9 @@ def test_hash(self): class foo: def __hash__(self): return 1<<35 - def test_NoneSelf(seld): - try: + def test_NoneSelf(self): + with self.assertRaises(TypeError): set.add(None) - self.self.fail("Unreachable code reached") - except TypeError: - pass def test_builtin_classmethod(self): descr = dict.__dict__["fromkeys"] @@ -1781,12 +1639,9 @@ def test_builtin_classmethod(self): self.assertRaises(TypeError, descr.__get__, None, int) def test_classmethod(self): - if is_cli: #http://ironpython.codeplex.com/workitem/27908 - self.assertRaises(TypeError, classmethod, 1) - else: - cm = classmethod(1) - self.assertRaises(TypeError, cm.__get__, None) - self.assertRaises(TypeError, cm.__get__, None, None) + cm = classmethod(1) + self.assertRaises(TypeError, cm.__get__, None) + self.assertRaises(TypeError, cm.__get__, None, None) def foo(): pass @@ -1794,58 +1649,51 @@ def foo(): pass self.assertRaises(TypeError, cm.__get__, None) self.assertRaises(TypeError, cm.__get__, None, None) - def test_EmptyTypes(self): for x in [None, Ellipsis, NotImplemented]: self.assertTrue(type(x) != str) self.assertEqual(repr(Ellipsis), 'Ellipsis') self.assertEqual(repr(NotImplemented), 'NotImplemented') - self.assertEqual(repr(type(Ellipsis)), "") - self.assertEqual(repr(type(NotImplemented)), "") + self.assertEqual(repr(type(Ellipsis)), "") + self.assertEqual(repr(type(NotImplemented)), "") def test_property(self): prop = property() - try: prop.fget = self.test_classmethod - except TypeError: pass - else: self.fail("Unreachable code reached") - try: prop.fdel = self.test_classmethod - except TypeError: pass - else: self.fail("Unreachable code reached") + with self.assertRaises(AttributeError): + prop.fget = self.test_classmethod - try: prop.__doc__ = 'abc' - except TypeError: pass - else: self.fail("Unreachable code reached") + with self.assertRaises(AttributeError): + prop.fdel = self.test_classmethod - try: prop.fset = self.test_classmethod - except TypeError: pass - else: self.fail("Unreachable code reached") + with self.assertRaises(AttributeError): + prop.fset = self.test_classmethod + + if sys.version_info >= (3,5): + prop.__doc__ = 'abc' + else: + with self.assertRaises(AttributeError): + prop.__doc__ = 'abc' @unittest.skipUnless(is_cli, 'IronPython specific test') def test_override_mro(self): - try: + with self.assertRaises(NotImplementedError): class C(object): def __mro__(self): pass - except NotImplementedError: pass - else: self.fail("Expected NotImplementedError, got none") class C(object): def mro(self): pass - try: + with self.assertRaises(NotImplementedError): class C(type): def mro(self): pass - except NotImplementedError: pass - else: self.fail("Expected NotImplementedError, got none") class D(type): pass - try: + with self.assertRaises(NotImplementedError): class E(D): def mro(self): pass - except NotImplementedError: pass - else: self.fail("Expected NotImplementedError, got none") def test_type_mro(self): self.assertRaises(TypeError, type.mro) @@ -1913,7 +1761,6 @@ def __len__(self): return 2 if x is dict: self.assertEqual(C({1:1}), {1:1}) d = {1:1, 2:2, 3:3} - self.assertEqual(C(d).__cmp__({0:0, 1:1, 2:2}), 1) d[4] = 4 self.assertEqual(len(list(C(d).keys())), len(list(d.keys()))) else: @@ -1928,19 +1775,16 @@ def f(): self.assertRaises(TypeError, f) - class KOld: pass class KNew(object): pass #CodePlex 16001 self.assertEqual(int.__dict__.get(0, 'abc'), 'abc') self.assertEqual(int.__dict__.get('__new__'), int.__new__) - self.assertEqual(KOld.__dict__.get(0, 'abc'), 'abc') self.assertEqual(KNew.__dict__.get(0, 'abc'), 'abc') self.assertEqual(KNew.__dict__.get('__new__'), None) #CodePlex 15702 self.assertEqual(int.__dict__.copy(), dict(int.__dict__)) self.assertEqual(int.__class__.__dict__.copy(), dict(int.__class__.__dict__)) - self.assertEqual(KOld.__dict__.copy(), dict(KOld.__dict__)) self.assertEqual(KNew.__dict__.copy(), dict(KNew.__dict__)) #Dev10 4844754 self.assertEqual(KNew.__class__.__dict__.copy(), dict(KNew.__class__.__dict__)) @@ -1949,7 +1793,7 @@ class KNew(object): pass self.assertEqual(set(KNew.__dict__.keys()), set(dict(KNew.__dict__).keys())) self.assertEqual(set(KNew.__dict__.values()), set(dict(KNew.__dict__).values())) - for value in [None, 'abc', 1, object(), KNew(), KOld(), KNew, KOld, property(lambda x: x)]: + for value in [None, 'abc', 1, object(), KNew(), KNew, property(lambda x: x)]: class KNew(object): abc = value @@ -1961,7 +1805,6 @@ class KNew(object): if k == 'abc': self.assertEqual(v, value) - #@unittest.expectedFailure('Currently throws a StackOverflowException') @unittest.skip('Currently throws a StackOverflowException') def test_getattribute_getattr(self): # verify object.__getattribute__(name) will call __getattr__ @@ -2042,19 +1885,9 @@ def __setattr__(self, name, value): setCalled = True object.__setattr__(self, name, value) - class KOld: - def __setattr__(self, name, value): - global setCalled - setCalled = True - self.__dict__[name] = value - class KNewSub(KNew): pass - class KOldSub(KOld): pass - - for K in [ KOld, - KOldSub, #CodePlex 8018 - KNew, + for K in [ KNew, KNewSub]: setCalled = False x = K() @@ -2138,7 +1971,7 @@ def __int__(self): return 100 class C2: def __int__(self): return myint(100) class C3: - def __int__(self): return 100 + def __int__(self): return long(100) class C4: def __int__(self): return mylong(100) class C5: @@ -2157,7 +1990,7 @@ def __int__(self): return 100 class C2(object): def __int__(self): return myint(100) class C3(object): - def __int__(self): return 100 + def __int__(self): return long(100) class C4(object): def __int__(self): return mylong(100) class C5(object): @@ -2173,7 +2006,6 @@ def __int__(self): return "100" def test_type_type_is_type(self): - class OS: pass class NS(object): pass true_values = [type, NS, int, float, tuple, str] @@ -2184,7 +2016,7 @@ class NS(object): pass for x in true_values: self.assertTrue(type(x) is type) - false_values = [OS] + false_values = [] if is_cli: false_values += [ System.Boolean(1), System.Int32(3), System.Version(0, 0), System.Exception() ] @@ -2194,22 +2026,25 @@ class NS(object): pass def test_hash_return_values(self): # new-style classes do conversion to int - for retval in [1, 1.0, 1.1, 1, 1<<30]: + for retval in [1, long(1), 1<<30]: for type in [object, int, str, float, int]: class foo(object): def __hash__(self): return retval self.assertEqual(hash(foo()), int(retval)) - # old-style classes require int or long return value + # classes require int or long return value for retval in [1.0, 1.1]: class foo: def __hash__(self): return retval - self.assertRaises(TypeError, hash, foo()) + if is_cli: + self.assertEqual(hash(foo()), int(retval)) + else: + self.assertRaises(TypeError, hash, foo()) - tests = { 1:1, - 2:2, + tests = { long(1):1, + long(2):2, } for retval in list(tests.keys()): @@ -2218,86 +2053,14 @@ def __hash__(self): return retval self.assertEqual(hash(foo()), tests[retval]) - def test_cmp_notimplemented(self): - class foo(object): - def __eq__(self, other): - ran.append('foo.eq') - return NotImplemented - def __ne__(self, other): - ran.append('foo.ne') - return NotImplemented - def __le__(self, other): - ran.append('foo.le') - return NotImplemented - def __lt__(self, other): - ran.append('foo.lt') - return NotImplemented - def __gt__(self, other): - ran.append('foo.gt') - return NotImplemented - def __ge__(self, other): - ran.append('foo.ge') - return NotImplemented - def __cmp__(self, other): - ran.append('foo.cmp') - return NotImplemented - - - class bar: - def __eq__(self, other): - ran.append('bar.eq') - return NotImplemented - def __ne__(self, other): - ran.append('bar.ne') - return NotImplemented - def __le__(self, other): - ran.append('bar.le') - return NotImplemented - def __lt__(self, other): - ran.append('bar.lt') - return NotImplemented - def __gt__(self, other): - ran.append('bar.gt') - return NotImplemented - def __ge__(self, other): - ran.append('bar.ge') - return NotImplemented - def __cmp__(self, other): - ran.append('bar.cmp') - return NotImplemented - - ran = [] - cmp(foo(), bar()) - #self.assertEqual(ran, ['foo.eq', 'bar.eq', 'foo.lt', 'bar.gt', 'foo.gt', 'bar.lt', 'bar.cmp']) - - ran = [] - cmp(foo(), foo()) - #self.assertEqual(ran, ['foo.cmp', 'foo.cmp']) - - ran = [] - cmp(bar(), bar()) - #self.assertEqual(ran, ['bar.cmp', 'bar.cmp', 'bar.eq', 'bar.eq', 'bar.eq', 'bar.eq', 'bar.lt', 'bat.gt', 'bar.gt', 'bar.lt', 'bar.gt', 'bar.lt', 'bar.lt', 'bar.gt', 'bar.cmp', 'bar.cmp']) - - ran = [] - cmp(foo(), 1) - #self.assertEqual(ran, ['foo.eq', 'foo.lt', 'foo.gt', 'foo.cmp']) - - def test_override_repr(self): - class KOld: - def __repr__(self): - return "old" - - class KNew(object): + class K(object): def __repr__(self): return "new" - self.assertEqual(repr(KOld()), "old") - self.assertEqual(str(KOld()), "old") - self.assertEqual(repr(KNew()), "new") + self.assertEqual(repr(K()), "new") #IP breaks here because __str__ in new style classes does not call __repr__ - self.assertEqual(str(KNew()), "new") - + self.assertEqual(str(K()), "new") def test_mutate_base(self): class basetype(object): @@ -2428,19 +2191,6 @@ class foo(object): pass def f(): a.dne self.assertRaisesMessage(AttributeError, "'foo' object has no attribute 'dne'", f) - def test_method(self): - class tst_oc: - def root(): return 2 - - class tst_nc: - def root(): return 2 - - self.assertRaises(TypeError, tst_oc.root) - self.assertRaises(TypeError, tst_nc.root) - - instancemethod = type(tst_oc.root) - self.assertRaises(TypeError, instancemethod, lambda x:True, None) - def test_descriptors_custom_attrs(self): """verifies the interaction between descriptors and custom attribute access works properly""" class mydesc(object): @@ -2509,112 +2259,6 @@ def __mod__(self, other): return 1 if o % o: flag = 1 # the bug was causing cast error before self.assertEqual(flag, 1) - def test_unbound_class_method(self): - class C(object): - def f(): return 1 - - x = C() - self.assertRaisesPartialMessage(TypeError, "unbound method f() must be called with", lambda: C.f()) - self.assertRaisesPartialMessage(TypeError, "unbound method f() must be called with", lambda: C.f(C)) - self.assertRaisesPartialMessage(TypeError, "arguments (1 given)", lambda: C.f(x)) - self.assertRaisesPartialMessage(TypeError, "arguments (1 given)", lambda: x.f()) - - def test_oldinstance_operator_exceptions(self): - global called - def fmaker(name, ex = None): - def f(self, *args): - global called - called.append(name) - if ex: - raise ex(name) - def g(*args): - return NotImplemented - return g - return f - - def fthrowingmaker(name, ex): - def f(self): - global called - called.append(name) - def g(*args): - raise ex - return g - return f - - class OC: - __eq__ = property(fmaker('oc_eq', AttributeError)) - __ne__ = property(fmaker('oc_ne', AttributeError)) - - class OC2: - __eq__ = property(fthrowingmaker('oc_eq', AttributeError)) - __ne__ = property(fthrowingmaker('oc_ne', AttributeError)) - - class OC3: - def __getattr__(self, name): - return property(fmaker(name, AttributeError)).__get__(self, OC3) - - called = [] - self.assertTrue(not OC() == OC()) - self.assertEqual(called, ['oc_eq']*4) - - called = [] - type(OC()).__eq__(OC(), OC()) - self.assertEqual(called, ['oc_eq']*2) - - called =[] - self.assertTrue(OC() != OC()) - self.assertEqual(called, ['oc_ne']*4) - - called = [] - type(OC()).__ne__(OC(), OC()) - self.assertEqual(called, ['oc_ne']*2) - - - called = [] - self.assertRaises(AttributeError, lambda : not OC2() == OC2()) - self.assertEqual(called, ['oc_eq']) - - called = [] - self.assertRaises(AttributeError, lambda : type(OC2()).__eq__(OC2(), OC2())) - self.assertEqual(called, ['oc_eq']) - - called =[] - self.assertRaises(AttributeError, lambda : OC2() != OC2()) - self.assertEqual(called, ['oc_ne']) - - called = [] - self.assertRaises(AttributeError, lambda : type(OC2()).__ne__(OC2(), OC2())) - self.assertEqual(called, ['oc_ne']) - - called = [] - self.assertRaises(AttributeError, lambda : type(OC()).__getattribute__(OC(), '__eq__')) - self.assertEqual(called, ['oc_eq']) - - self.assertTrue(not hasattr(OC(), '__eq__')) - - # IronPython still differs on these from CPython: - # verify other attributes work correctly - #for x in ['__abs__', '__float__', '__long__', '__int__', '__hex__', '__oct__', '__pos__', '__neg__', '__invert__']: - # # unary operators which pass on AttributeError - # print x - # self.assertRaises(AttributeError, getattr(type(OC3()), x), OC3()) - - for x in ['__hash__', '__nonzero__', '__str__', '__repr__']: - # unary operators that catch AttributeError - getattr(type(OC3()), x)(OC3()) - - # IronPython still differs on these from CPython: - #for x in ['__iter__']: - # # unary operators that call, catch, and report another error - # called = [] - # self.assertRaises(TypeError, getattr(type(OC3()), x), OC3()) - # self.assertTrue(x in called) - - for x in ['__add__', '__iadd__', '__radd__', '__cmp__', '__coerce__']: - # binary operators catch AttributeError - getattr(type(OC3()), x)(OC3(), OC3()) - - def test_cp10291(self): class K1(object): def __call__(self): @@ -2624,39 +2268,23 @@ class K2(K1): def __call__(self): return "K2" + K1.__call__(self) - class K1Old: - def __call__(self): - return "K1" - - class K2Old(K1Old): - def __call__(self): - return "K2" + K1Old.__call__(self) - - for k1, k2 in [ (K1, K2), - (K1Old, K2Old), ]: self.assertEqual(k1()(), "K1") self.assertEqual(k2()(), "K2K1") - @unittest.skipUnless(is_cli, 'IronPython specific test') # should be reenabled against CPython26 def test_cp11760(self): - class KNew(object): + class K(object): def __str__(self): return "KNew" - class KOld: - def __str__(self): return "KOld" - - for K in [KNew, KOld]: - dir_str = dir(K().__str__) - for x in [ '__class__', '__delattr__', '__doc__', - '__get__', '__getattribute__', '__hash__', '__init__', - '__new__', '__reduce__', '__reduce_ex__', '__repr__', - '__setattr__', '__str__', 'im_class', - 'im_func', '__func__', 'im_self', '__self__', - #'__call__', '__cmp__', - ]: - self.assertTrue(x in dir_str, x + " is not in dir(K().__str__)") + dir_str = dir(K().__str__) + for x in [ '__class__', '__delattr__', '__doc__', + '__get__', '__getattribute__', '__hash__', '__init__', + '__new__', '__reduce__', '__reduce_ex__', '__repr__', + '__setattr__', '__str__', + '__func__', '__self__', '__call__', + ]: + self.assertTrue(x in dir_str, x + " is not in dir(K().__str__)") def test_delattr(self): global called @@ -2678,15 +2306,7 @@ def m2(self, a): x = lambda: 3.17 return x() - class KOld: - p1 = property(lambda self: 3.14) - m1 = lambda self: 3.15 - f1 = lambda: 3.16 - def m2(self, a): - x = lambda: 3.17 - return x() - - for temp in dir(KNew) + dir(KNew()) + dir(KOld) + dir(KOld()): + for temp in dir(KNew) + dir(KNew()): self.assertTrue("lambda" not in temp) def test_oldstyle_fancycallable(self): @@ -2734,50 +2354,7 @@ def test_cp13820(self): global GETATTRIBUTE_CALLED GETATTRIBUTE_CALLED = False - class KOld: - def __getattribute__(self, name): - global GETATTRIBUTE_CALLED - GETATTRIBUTE_CALLED = True - print("__getattribute__ was called by:", name) - return 1 - - def __init__(self): - return - - def __del__(self): - return - - def __str__(self): return "" - - def __cmp__(self, other): return 0 - - def __hash__(self): return 1 - - def __bool__(self): return 1 - - def __get__(self, instance, owner): return 3 - - def __delete__(self, instance): return - - def __len__(self): return 4 - - def __getitem__(self, key): return 5 - - def __setitem__(self, key, value): return - - def __getslice__(self, i, j): return 6 - - def __contains__(self, obj): return True - - def __add__(self, other): return 7 - - def __hex__(self): return hex(9) - - def __coerce__(self, other): return None - - def __lt__(self, other): return True - - class KNew(object): + class K(object): def __getattribute__(self, name): global GETATTRIBUTE_CALLED GETATTRIBUTE_CALLED = True @@ -2796,7 +2373,7 @@ def __cmp__(self, other): return 0 def __hash__(self): return 1 - def __bool__(self): return 1 + def __bool__(self): return True def __get__(self, instance, owner): return 3 @@ -2814,28 +2391,26 @@ def __contains__(self, obj): return True def __add__(self, other): return 7 - def __hex__(self): return hex(9) + def __index__(self): return 9 def __coerce__(self, other): return None def __lt__(self, other): return True - for K in [KOld, KNew]: - obj = K() - str(obj) - obj==3 - hash(obj) - bool(obj) - obj[3] - obj[3] = 4 - len(obj) - obj[1:3] - if K==KOld: hasattr(obj, "abc") - obj + 3 - hex(obj) - obj<9 - del obj - self.assertTrue(not GETATTRIBUTE_CALLED) + obj = K() + str(obj) + obj==3 + hash(obj) + bool(obj) + obj[3] + obj[3] = 4 + len(obj) + obj[1:3] + obj + 3 + hex(obj) + obj<9 + del obj + self.assertTrue(not GETATTRIBUTE_CALLED) def test_keyword_type_construction(self): """using type.__call__ should accept keyword arguments""" @@ -2968,16 +2543,16 @@ def __add__(self, other): return "__add__:" + str(type(self)) + " " + str(type(other)) self.assertRaisesMessage(TypeError, "unsupported operand type(s) for +: 'K' and 'K'", lambda: K() + K()) - self.assertEqual(K() + K0(), "__radd__: ") - self.assertEqual(K() + K1(), "__radd__: ") + self.assertEqual(K() + K0(), "__radd__: ".format(name=__name__, cls="" if is_cli else ".ClassTest.test_cp5803.")) + self.assertEqual(K() + K1(), "__radd__: ".format(name=__name__, cls="" if is_cli else ".ClassTest.test_cp5803.")) self.assertRaisesMessage(TypeError, "unsupported operand type(s) for +: 'K0' and 'K'", lambda: K0() + K()) self.assertRaisesMessage(TypeError, "unsupported operand type(s) for +: 'K0' and 'K0'", lambda: K0() + K0()) - self.assertEqual(K0() + K1(), "__radd__: ") + self.assertEqual(K0() + K1(), "__radd__: ".format(name=__name__, cls="" if is_cli else ".ClassTest.test_cp5803.")) - self.assertEqual(K1() + K(), "__add__: ") - self.assertEqual(K1() + K0(), "__add__: ") - self.assertEqual(K1() + K1(), "__add__: " ) + self.assertEqual(K1() + K(), "__add__: ".format(name=__name__, cls="" if is_cli else ".ClassTest.test_cp5803.")) + self.assertEqual(K1() + K0(), "__add__: ".format(name=__name__, cls="" if is_cli else ".ClassTest.test_cp5803.")) + self.assertEqual(K1() + K1(), "__add__: ".format(name=__name__, cls="" if is_cli else ".ClassTest.test_cp5803.")) #--Subtraction class K(object): pass @@ -2994,42 +2569,16 @@ def __sub__(self, other): return "__sub__:" + str(type(self)) + " " + str(type(other)) self.assertRaisesMessage(TypeError, "unsupported operand type(s) for -: 'K' and 'K'", lambda: K() - K()) - self.assertEqual(K() - K0(), "__rsub__: ") - self.assertEqual(K() - K1(), "__rsub__: ") + self.assertEqual(K() - K0(), "__rsub__: ".format(name=__name__, cls="" if is_cli else ".ClassTest.test_cp5803.")) + self.assertEqual(K() - K1(), "__rsub__: ".format(name=__name__, cls="" if is_cli else ".ClassTest.test_cp5803.")) self.assertRaisesMessage(TypeError, "unsupported operand type(s) for -: 'K0' and 'K'", lambda: K0() - K()) self.assertRaisesMessage(TypeError, "unsupported operand type(s) for -: 'K0' and 'K0'", lambda: K0() - K0()) - self.assertEqual(K0() - K1(), "__rsub__: ") - - self.assertEqual(K1() - K(), "__sub__: ") - self.assertEqual(K1() - K0(), "__sub__: ") - self.assertEqual(K1() - K1(), "__sub__: " ) - - #--Old style - class K: pass - - class K0: - def __radd__(self, other): - return "__radd__:" + str(type(self)) + " " + str(type(other)) - - class K1: - def __radd__(self, other): - return "__radd__:" + str(type(self)) + " " + str(type(other)) - - def __add__(self, other): - return "__add__:" + str(type(self)) + " " + str(type(other)) - - self.assertRaises(TypeError, lambda: K() + K()) - self.assertEqual(K() + K0(), "__radd__: ") - self.assertEqual(K() + K1(), "__radd__: ") + self.assertEqual(K0() - K1(), "__rsub__: ".format(name=__name__, cls="" if is_cli else ".ClassTest.test_cp5803.")) - self.assertRaises(TypeError, lambda: K0() + K()) - self.assertEqual(K0() + K0(), "__radd__: ") - self.assertEqual(K0() + K1(), "__radd__: ") - - self.assertEqual(K1() + K(), "__add__: ") - self.assertEqual(K1() + K0(), "__add__: ") - self.assertEqual(K1() + K1(), "__add__: ") + self.assertEqual(K1() - K(), "__sub__: ".format(name=__name__, cls="" if is_cli else ".ClassTest.test_cp5803.")) + self.assertEqual(K1() - K0(), "__sub__: ".format(name=__name__, cls="" if is_cli else ".ClassTest.test_cp5803.")) + self.assertEqual(K1() - K1(), "__sub__: ".format(name=__name__, cls="" if is_cli else ".ClassTest.test_cp5803.")) def test_special_type_attributes(self): # some attributes on new-style class are alwayed retrieved @@ -3221,20 +2770,13 @@ class C(A): pass self.assertEqual(a + c, ('a', 'A')) def test_cp2021(self): - class KOld: - def __rmul__(self, other): - return 7 - class KNew(object): def __rmul__(self, other): return 7 for testdata in [[], [1], [1,2]]: - self.assertEqual(testdata * KOld(), 7) self.assertEqual(testdata * KNew(), 7) - self.assertRaisesMessage(TypeError, "object cannot be interpreted as an index", - testdata.__mul__, KOld()) - self.assertRaisesMessage(TypeError, "'KNew' object cannot be interpreted as an index", + self.assertRaisesMessage(TypeError, "'KNew' object cannot be interpreted as an integer", testdata.__mul__, KNew()) def test_redundant_multiple_bases(self): @@ -3267,20 +2809,6 @@ def __init__(self, a, b='b', c=12, d=None, e=None): self.assertEqual(a.b, 'foo') self.assertEqual(a.d, 'boom') - def test_oldinstance_creation(self): - class C: pass - - inst = type(C()) - - d = {'a': 2} - i = inst(C, d) - - self.assertEqual(id(d), id(i.__dict__)) - self.assertTrue(isinstance(i, C)) - - x = inst(C, None) - self.assertEqual(x.__dict__, {}) - def test_metaclass_getattribute(self): class mc(type): def __getattr__(self, name): @@ -3347,17 +2875,12 @@ class D(B): pass def f(): del D.__getattribute__ # AttributeError expected. self.assertRaises(AttributeError, f) - def test_metaclass_oldstyle_only_bases(self): - class C: pass - - self.assertRaises(TypeError, type, 'foo', (C, ), {}) - def test_bad_mro_error_message(self): class A(object): pass class B(A): pass - self.assertRaisesPartialMessage(TypeError, "Cannot create a consistent method resolution\norder (MRO) for bases A, B", + self.assertRaisesPartialMessage(TypeError, "Cannot create a consistent method resolution\norder (MRO) for bases", type, "X", (A,B), {}) def test_finalizer(self): @@ -3409,17 +2932,29 @@ class l(object): def __int__(self): return 42 - vals = (l(), 42, 42.0) + class C(object): + def __init__(self, len): + self.len = len + def __len__(self): + return self.len + + vals = (42, long(42)) if is_cli: - from iptest.type_util import clr_all_types - vals += tuple(t(42) for t in clr_all_types) + from iptest.type_util import clr_int_types + vals += tuple(t(42) for t in clr_int_types) for x in vals: - class C(object): - def __len__(self): - return x - self.assertEqual(len(C()), 42) + self.assertEqual(len(C(x)), 42) + # object cannot be interpreted as an integer + vals = (l(), 42.0) + if is_cli: + from iptest.type_util import clr_float_types + vals += tuple(t(42) for t in clr_float_types) + + for x in vals: + with self.assertRaises(TypeError): + len(C(x)) def test_descriptor_exception(self): class desc(object): @@ -3451,17 +2986,6 @@ class x(object): desc.__get__ = lambda self, value, ctx: 23 self.assertEqual(x().a, 23) - def test_method_tuple_type(self): - """creates a method who's type is declared to be a tuple""" - class x(object): - def f(self): pass - - def f(self): return self - - self.assertEqual(type(x.f)(f, None, (int, str))(42), 42) - self.assertEqual(type(x.f)(f, None, (int, str))('abc'), 'abc') - self.assertRaises(TypeError, type(x.f)(f, None, (int, str)), 1) - def test_mutate_class(self): def f(): object.foo = 42 def g(): type.foo = 42 @@ -3577,7 +3101,6 @@ def __new__(cls): self.assertRaises(TypeError, X3) self.assertRaises(TypeError, X4) - def test_oldstyle_splat_dict(self): class C: pass @@ -3598,7 +3121,7 @@ def test_cp22832(self): class KOld: KOldStuff = 3 - class KNew(object, KOld): + class KNew(KOld): pass self.assertTrue("KOldStuff" in dir(KNew)) @@ -3635,7 +3158,6 @@ def __init__(self): def test_cp33622(self): self.assertEqual(object.__repr__ in (None,), False) self.assertEqual(object.__repr__ in (None,object.__repr__), True) - self.assertEqual(object.__repr__ in (None,object.__cmp__), False) self.assertEqual(object.__repr__ in (None,object.__str__), False) def test_cp24649_gh120(self): @@ -3675,46 +3197,34 @@ def __init__(self, x): cc = CC(1) self.assertEqual(cc.x, 1) -# # tests w/ special requirements that can't be run in methods.. -# #Testing the class attributes backed by globals + def test_global_backed_attr(self): + #Testing the class attributes backed by globals + global x + x = 10 -# x = 10 - -# class C: -# x = x -# del x -# x = x - -# self.assertEqual(C.x, 10) -# self.assertEqual(x, 10) - -# try: -# class C: -# x = x -# del x -# del x -# except NameError: -# pass -# else: -# self.assertTrue("Expecting name error") - -# self.assertEqual(x, 10) - -# class C: -# x = 10 -# del x -# b = x -# self.assertEqual(x, 10) + class C: + x = x + del x + x = x -# self.assertEqual(C.b, 10) -# self.assertEqual(x, 10) + self.assertEqual(C.x, 10) + self.assertEqual(x, 10) + with self.assertRaises(NameError): + class C: + x = x + del x + del x -# def test_suite(): -# return unittest.makeSuite(ClassTest) + self.assertEqual(x, 10) -# if __name__ == '__main__': -# unittest.main(defaultTest='test_suite') + class C: + x = 10 + del x + b = x + self.assertEqual(x, 10) + self.assertEqual(C.b, 10) + self.assertEqual(x, 10) run_test(__name__)