From: <fwi...@us...> - 2008-06-16 15:54:19
|
Revision: 4651 http://jython.svn.sourceforge.net/jython/?rev=4651&view=rev Author: fwierzbicki Date: 2008-06-16 08:54:15 -0700 (Mon, 16 Jun 2008) Log Message: ----------- Merged revisions 4609-4612,4614-4627,4629-4631,4635-4639,4641,4649-4650 via svnmerge from https://jython.svn.sourceforge.net/svnroot/jython/trunk/jython ........ r4609 | pjenvey | 2008-06-12 21:34:13 -0400 (Thu, 12 Jun 2008) | 5 lines the compiler shouldn't inherit the compiler flags from the current frame on import as this causes futures to leak into different modules. this was done for #1691096 which is actaully an invalid bug fixes #1886758 ........ r4610 | pjenvey | 2008-06-12 21:38:54 -0400 (Thu, 12 Jun 2008) | 1 line re-enable test_email after r4609 ........ r4611 | pjenvey | 2008-06-13 00:26:20 -0400 (Fri, 13 Jun 2008) | 1 line a FIXME ........ r4612 | pjenvey | 2008-06-13 00:47:04 -0400 (Fri, 13 Jun 2008) | 1 line fix test_descr.test_dir dir(None) == dir(Ellipsis) ........ r4614 | pjenvey | 2008-06-13 15:20:35 -0400 (Fri, 13 Jun 2008) | 2 lines from: http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_time.py@50696 ........ r4615 | pjenvey | 2008-06-13 15:43:46 -0400 (Fri, 13 Jun 2008) | 5 lines pass 2.5's test_time: o support passing None to localtime, gmtime and ctime o support 0 for month day and julian day, and 2 leap seconds o disallow timestamps that overflow long. always validate the srftime tuple ........ r4616 | pjenvey | 2008-06-13 18:30:01 -0400 (Fri, 13 Jun 2008) | 2 lines move Jython's custom test_descr tests into test_descr_jy ........ r4617 | pjenvey | 2008-06-13 20:56:25 -0400 (Fri, 13 Jun 2008) | 5 lines fixes for test_descr: o disallow empty separators to str.split o don't expose complex.__cmp__ o be careful of kwargs in our file __new__ hack ........ r4618 | pjenvey | 2008-06-13 22:00:53 -0400 (Fri, 13 Jun 2008) | 2 lines handle super subclasses in its __get__. fixes test_descr.supers ........ r4619 | pjenvey | 2008-06-13 23:37:27 -0400 (Fri, 13 Jun 2008) | 1 line add toString, cleanup/coding standards ........ r4620 | pjenvey | 2008-06-13 23:51:58 -0400 (Fri, 13 Jun 2008) | 2 lines allow super to be used with a proxy for obj fixes test_descr.proxysuper ........ r4621 | pjenvey | 2008-06-14 01:37:36 -0400 (Sat, 14 Jun 2008) | 3 lines fix PyClassMethodDescr.__get__ called with one arg, or None as one of the args. convert to exposed annotations ........ r4622 | pjenvey | 2008-06-14 15:48:57 -0400 (Sat, 14 Jun 2008) | 4 lines lame hack to make derived class generation handle package and import statements for classes outside of org.python.core. a hacky solution because the java generation code is really difficult about letting me do this correctly ........ r4623 | pjenvey | 2008-06-14 15:59:37 -0400 (Sat, 14 Jun 2008) | 2 lines o __delslice__ step is optional o fix ProxyType to use the canonical version of __setslice__ ........ r4624 | pjenvey | 2008-06-14 16:25:11 -0400 (Sat, 14 Jun 2008) | 4 lines fix test_descr.overloading: dervied classes weren't supporting __set/delslice__. also fix __getslice__ eating LookupErrors while I'm here (like __getitem__ used to) ........ r4625 | pjenvey | 2008-06-14 17:19:39 -0400 (Sat, 14 Jun 2008) | 2 lines we pass the stock test_pow now ........ r4626 | pjenvey | 2008-06-14 18:27:30 -0400 (Sat, 14 Jun 2008) | 4 lines fix ternary pow to always attempt __pow__ even when coercion fails (__pow__ on 'new style numbers' doesn't require that types match). fallback to binary pow when modulo is None ........ r4627 | pjenvey | 2008-06-14 18:30:17 -0400 (Sat, 14 Jun 2008) | 3 lines fix deriveds not supporting the modulo arg to __pow__. with r4626, fixes test_descr.binopoverride ........ r4629 | pjenvey | 2008-06-14 19:52:25 -0400 (Sat, 14 Jun 2008) | 5 lines o make property use fget's docstring if one wasn't specified. fixes 2.5 test_descr.properties o cleanup. We don't need ExposedSets here because TypeErrors are thrown for us without them. coding standards ........ r4630 | pjenvey | 2008-06-14 20:38:46 -0400 (Sat, 14 Jun 2008) | 1 line more __get__ arg2 is optional ........ r4631 | pjenvey | 2008-06-14 20:42:42 -0400 (Sat, 14 Jun 2008) | 3 lines o fix PyModule's lack of getDict breaking 2.5 test_descr.setdict o match lack of __setitem__ exception to CPython ........ r4635 | pjenvey | 2008-06-14 23:11:06 -0400 (Sat, 14 Jun 2008) | 1 line match message to CPython's ........ r4636 | pjenvey | 2008-06-14 23:12:12 -0400 (Sat, 14 Jun 2008) | 3 lines raise a TypeError when __init__ returns anything other than None. Also prevents __init__ from being a generator. fixes 2.5 test_descr.test_init ........ r4637 | pjenvey | 2008-06-14 23:13:49 -0400 (Sat, 14 Jun 2008) | 2 lines update to: http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_descr.py@60060 ........ r4638 | pjenvey | 2008-06-14 23:17:48 -0400 (Sat, 14 Jun 2008) | 1 line re-integrate the ability to run one test from the command line ........ r4639 | pjenvey | 2008-06-15 00:35:29 -0400 (Sun, 15 Jun 2008) | 4 lines enable 2.5's test_descr in the regrtest with various tests disabled. give regrtest more memory for now until slices are fixed (they're currently broken, causing test_descr.slottrash to use a lot of memory) ........ r4641 | pjenvey | 2008-06-15 16:29:43 -0400 (Sun, 15 Jun 2008) | 2 lines context manager-ize file ........ r4649 | fwierzbicki | 2008-06-16 09:17:01 -0400 (Mon, 16 Jun 2008) | 3 lines Renamed test classes to clearly label them as testers. Eventually these should be moved out of the core src. ........ r4650 | fwierzbicki | 2008-06-16 09:20:35 -0400 (Mon, 16 Jun 2008) | 2 lines Oops some experimental code leaked into my last commit. Reverting. ........ Modified Paths: -------------- branches/asm/CoreExposed.includes branches/asm/Lib/test/regrtest.py branches/asm/Lib/test/test_descr.py branches/asm/Lib/test/test_descr_jy.py branches/asm/Lib/test/test_file.py branches/asm/build.xml branches/asm/src/org/python/compiler/Module.java branches/asm/src/org/python/core/PyArray.java branches/asm/src/org/python/core/PyArrayDerived.java branches/asm/src/org/python/core/PyBooleanDerived.java branches/asm/src/org/python/core/PyBuiltinFunction.java branches/asm/src/org/python/core/PyClassMethodDerived.java branches/asm/src/org/python/core/PyClassMethodDescr.java branches/asm/src/org/python/core/PyComplex.java branches/asm/src/org/python/core/PyComplexDerived.java branches/asm/src/org/python/core/PyDataDescr.java branches/asm/src/org/python/core/PyDictionaryDerived.java branches/asm/src/org/python/core/PyEllipsis.java branches/asm/src/org/python/core/PyFile.java branches/asm/src/org/python/core/PyFileDerived.java branches/asm/src/org/python/core/PyFloatDerived.java branches/asm/src/org/python/core/PyFrozenSetDerived.java branches/asm/src/org/python/core/PyInstance.java branches/asm/src/org/python/core/PyIntegerDerived.java branches/asm/src/org/python/core/PyList.java branches/asm/src/org/python/core/PyListDerived.java branches/asm/src/org/python/core/PyLongDerived.java branches/asm/src/org/python/core/PyMethodDescr.java branches/asm/src/org/python/core/PyModule.java branches/asm/src/org/python/core/PyModuleDerived.java branches/asm/src/org/python/core/PyNone.java branches/asm/src/org/python/core/PyObject.java branches/asm/src/org/python/core/PyObjectDerived.java branches/asm/src/org/python/core/PyProperty.java branches/asm/src/org/python/core/PyPropertyDerived.java branches/asm/src/org/python/core/PySetDerived.java branches/asm/src/org/python/core/PySliceDerived.java branches/asm/src/org/python/core/PyString.java branches/asm/src/org/python/core/PyStringDerived.java branches/asm/src/org/python/core/PySuper.java branches/asm/src/org/python/core/PySuperDerived.java branches/asm/src/org/python/core/PyTupleDerived.java branches/asm/src/org/python/core/PyTypeDerived.java branches/asm/src/org/python/core/PyUnicodeDerived.java branches/asm/src/org/python/core/__builtin__.java branches/asm/src/org/python/core/imp.java branches/asm/src/org/python/modules/_weakref/ProxyType.java branches/asm/src/org/python/modules/_weakref/ReferenceTypeDerived.java branches/asm/src/org/python/modules/collections/PyDefaultDictDerived.java branches/asm/src/org/python/modules/collections/PyDequeDerived.java branches/asm/src/org/python/modules/random/PyRandomDerived.java branches/asm/src/org/python/modules/time/Time.java branches/asm/src/org/python/modules/zipimport/zipimporterDerived.java branches/asm/src/templates/gderived.py branches/asm/src/templates/object.derived Added Paths: ----------- branches/asm/Lib/test/test_time.py branches/asm/src/org/python/antlr/GrammarTester.java branches/asm/src/org/python/antlr/PythonTreeTester.java branches/asm/src/org/python/antlr/WalkerTester.java Removed Paths: ------------- branches/asm/Lib/test/output/test_pow branches/asm/Lib/test/test_pow.py branches/asm/src/org/python/antlr/GrammarOnly.java branches/asm/src/org/python/antlr/Main.java branches/asm/src/org/python/antlr/PythonTreeWalker.java Property Changed: ---------------- branches/asm/ Property changes on: branches/asm ___________________________________________________________________ Name: svnmerge-integrated - /trunk/jython:1-4605 + /trunk/jython:1-4650 Modified: branches/asm/CoreExposed.includes =================================================================== --- branches/asm/CoreExposed.includes 2008-06-16 13:20:35 UTC (rev 4650) +++ branches/asm/CoreExposed.includes 2008-06-16 15:54:15 UTC (rev 4651) @@ -4,11 +4,13 @@ org/python/core/PyBuiltinFunction.class org/python/core/PyCell.class org/python/core/PyClassMethod.class +org/python/core/PyClassMethodDescr.class org/python/core/PyComplex.class org/python/core/PyDataDescr.class org/python/core/PyDictionary.class org/python/core/PyDictProxy.class org/python/core/PyEnumerate.class +org/python/core/PyEllipsis.class org/python/core/PyFile.class org/python/core/PyFloat.class org/python/core/PyFrozenSet.class Deleted: branches/asm/Lib/test/output/test_pow =================================================================== --- branches/asm/Lib/test/output/test_pow 2008-06-16 13:20:35 UTC (rev 4650) +++ branches/asm/Lib/test/output/test_pow 2008-06-16 15:54:15 UTC (rev 4651) @@ -1,17 +0,0 @@ -test_pow -power (test_pow.py) -integers -simple identities -cubes -powers of two -modpow -longs -simple identities -cubes -powers of two -modpow -floats -modpow -mixed-mode -Validate that TypeError is thrown with 3 args if first two args aren't integers -miscellaneous Modified: branches/asm/Lib/test/regrtest.py =================================================================== --- branches/asm/Lib/test/regrtest.py 2008-06-16 13:20:35 UTC (rev 4650) +++ branches/asm/Lib/test/regrtest.py 2008-06-16 15:54:15 UTC (rev 4651) @@ -1034,9 +1034,7 @@ test_class test_copy test_dis - test_descr test_descrtut - test_email test_eof test_frozen test_gc Modified: branches/asm/Lib/test/test_descr.py =================================================================== --- branches/asm/Lib/test/test_descr.py 2008-06-16 13:20:35 UTC (rev 4650) +++ branches/asm/Lib/test/test_descr.py 2008-06-16 15:54:15 UTC (rev 4651) @@ -1,15 +1,14 @@ # Test enhancements related to descriptors and new-style classes -# modified from CPython version by: -# - removed the tests classmethods_in_c, staticmethods_in_c, spamlists, and spamdicts which -# depend on the c extension module xxsubtype -# - merged code from the pypy version of this script to run all tests instead of stopping -# at the first failure -# - allow specific tests to be run by specifying them on the command line - -from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout +from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout, is_jython from copy import deepcopy import warnings +import types +if is_jython: + from test_weakref import extra_collect +else: + def extra_collect(): + pass warnings.filterwarnings("ignore", r'complex divmod\(\), // and % are deprecated$', @@ -479,18 +478,6 @@ pass else: raise TestFailed, "should have raised OverflowError" - try: - foo = int(None) - except TypeError: - pass - else: - raise TestFailed, "should have raised TypeError" - try: - foo = C(None) - except TypeError: - pass - else: - raise TestFailed, "should have raised TypeError" def longs(): if verbose: print "Testing long operations..." @@ -519,17 +506,98 @@ __str__ = __repr__ a = Number(3.14, prec=6) - vereq(`a`, "3.14") + vereq(repr(a), "3.14") vereq(a.prec, 6) a = Number(a, prec=2) - vereq(`a`, "3.1") + vereq(repr(a), "3.1") vereq(a.prec, 2) a = Number(234.5) - vereq(`a`, "234.5") + vereq(repr(a), "234.5") vereq(a.prec, 12) +def spamlists(): + if verbose: print "Testing spamlist operations..." + import copy, xxsubtype as spam + def spamlist(l, memo=None): + import xxsubtype as spam + return spam.spamlist(l) + # This is an ugly hack: + copy._deepcopy_dispatch[spam.spamlist] = spamlist + + testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__") + testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__") + testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__") + testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__") + testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]), + "a[b:c]", "__getslice__") + testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]), + "a+=b", "__iadd__") + testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__") + testunop(spamlist([1,2,3]), 3, "len(a)", "__len__") + testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__") + testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__") + testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__") + testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]), + spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__") + # Test subclassing + class C(spam.spamlist): + def foo(self): return 1 + a = C() + vereq(a, []) + vereq(a.foo(), 1) + a.append(100) + vereq(a, [100]) + vereq(a.getstate(), 0) + a.setstate(42) + vereq(a.getstate(), 42) + +def spamdicts(): + if verbose: print "Testing spamdict operations..." + import copy, xxsubtype as spam + def spamdict(d, memo=None): + import xxsubtype as spam + sd = spam.spamdict() + for k, v in d.items(): sd[k] = v + return sd + # This is an ugly hack: + copy._deepcopy_dispatch[spam.spamdict] = spamdict + + testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__") + testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__") + testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__") + testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__") + d = spamdict({1:2,3:4}) + l1 = [] + for i in d.keys(): l1.append(i) + l = [] + for i in iter(d): l.append(i) + vereq(l, l1) + l = [] + for i in d.__iter__(): l.append(i) + vereq(l, l1) + l = [] + for i in type(spamdict({})).__iter__(d): l.append(i) + vereq(l, l1) + straightd = {1:2, 3:4} + spamd = spamdict(straightd) + testunop(spamd, 2, "len(a)", "__len__") + testunop(spamd, repr(straightd), "repr(a)", "__repr__") + testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}), + "a[b]=c", "__setitem__") + # Test subclassing + class C(spam.spamdict): + def foo(self): return 1 + a = C() + vereq(a.items(), []) + vereq(a.foo(), 1) + a['foo'] = 'bar' + vereq(a.items(), [('foo', 'bar')]) + vereq(a.getstate(), 0) + a.setstate(100) + vereq(a.getstate(), 100) + def pydicts(): if verbose: print "Testing Python subclass of dict..." verify(issubclass(dict, dict)) @@ -629,6 +697,8 @@ class _instance(object): pass class M2(object): + # XXX: Jython 2.3 + #@staticmethod def __new__(cls, name, bases, dict): self = object.__new__(cls) self.name = name @@ -782,6 +852,16 @@ ("getattr", "foo"), ("delattr", "foo")]) + # http://python.org/sf/1174712 + try: + class Module(types.ModuleType, str): + pass + except TypeError: + pass + else: + raise TestFailed("inheriting from ModuleType and str at the " + "same time should fail") + def multi(): if verbose: print "Testing multiple inheritance..." class C(object): @@ -1147,6 +1227,29 @@ class C(object): __slots__ = ["a", "a_b", "_a", "A0123456789Z"] + # Test unicode slot names + try: + unichr + except NameError: + pass + else: + # _unicode_to_string used to modify slots in certain circumstances + slots = (unicode("foo"), unicode("bar")) + class C(object): + __slots__ = slots + x = C() + x.foo = 5 + vereq(x.foo, 5) + veris(type(slots[0]), unicode) + # this used to leak references + try: + class C(object): + __slots__ = [unichr(128)] + except (TypeError, UnicodeEncodeError): + pass + else: + raise TestFailed, "[unichr(128)] slots not caught" + # Test leaks class Counted(object): counter = 0 # counts the number of instances alive @@ -1430,6 +1533,28 @@ else: raise TestFailed, "classmethod should check for callability" + # Verify that classmethod() doesn't allow keyword args + try: + classmethod(f, kw=1) + except TypeError: + pass + else: + raise TestFailed, "classmethod shouldn't accept keyword args" + +def classmethods_in_c(): + if verbose: print "Testing C-based class methods..." + import xxsubtype as spam + a = (1, 2, 3) + d = {'abc': 123} + x, a1, d1 = spam.spamlist.classmeth(*a, **d) + veris(x, spam.spamlist) + vereq(a, a1) + vereq(d, d1) + x, a1, d1 = spam.spamlist().classmeth(*a, **d) + veris(x, spam.spamlist) + vereq(a, a1) + vereq(d, d1) + def staticmethods(): if verbose: print "Testing static methods..." class C(object): @@ -1447,6 +1572,20 @@ vereq(d.foo(1), (d, 1)) vereq(D.foo(d, 1), (d, 1)) +def staticmethods_in_c(): + if verbose: print "Testing C-based static methods..." + import xxsubtype as spam + a = (1, 2, 3) + d = {"abc": 123} + x, a1, d1 = spam.spamlist.staticmeth(*a, **d) + veris(x, None) + vereq(a, a1) + vereq(d, d1) + x, a1, d2 = spam.spamlist().staticmeth(*a, **d) + veris(x, None) + vereq(a, a1) + vereq(d, d1) + def classic(): if verbose: print "Testing classic classes..." class C: @@ -1544,6 +1683,37 @@ vereq(X.__mro__, (object, A, C, B, D, X)) vereq(X().f(), "A") + try: + class X(object): + class __metaclass__(type): + def mro(self): + return [self, dict, object] + except TypeError: + pass + else: + raise TestFailed, "devious mro() return not caught" + + try: + class X(object): + class __metaclass__(type): + def mro(self): + return [1] + except TypeError: + pass + else: + raise TestFailed, "non-class mro() return not caught" + + try: + class X(object): + class __metaclass__(type): + def mro(self): + return 1 + except TypeError: + pass + else: + raise TestFailed, "non-sequence mro() return not caught" + + def overloading(): if verbose: print "Testing operator overloading..." @@ -1633,7 +1803,9 @@ c1 = C() c2 = C() verify(not not c1) - vereq(hash(c1), id(c1)) + verify(id(c1) != id(c2)) + hash(c1) + hash(c2) vereq(cmp(c1, c2), cmp(id(c1), id(c2))) vereq(c1, c1) verify(c1 != c2) @@ -1655,7 +1827,9 @@ d1 = D() d2 = D() verify(not not d1) - vereq(hash(d1), id(d1)) + verify(id(d1) != id(d2)) + hash(d1) + hash(d2) vereq(cmp(d1, d2), cmp(id(d1), id(d2))) vereq(d1, d1) verify(d1 != d2) @@ -1797,6 +1971,7 @@ r = weakref.ref(c) verify(r() is c) del c + extra_collect() verify(r() is None) del r class NoWeak(object): @@ -1807,13 +1982,16 @@ except TypeError, msg: verify(str(msg).find("weak reference") >= 0) else: - verify(0, "weakref.ref(no) should be illegal") + # XXX: Jython allows a weakref here + if not is_jython: + verify(0, "weakref.ref(no) should be illegal") class Weak(object): __slots__ = ['foo', '__weakref__'] yes = Weak() r = weakref.ref(yes) verify(r() is yes) del yes + extra_collect() verify(r() is None) del r @@ -1878,6 +2056,28 @@ else: raise TestFailed, "expected ZeroDivisionError from bad property" + class E(object): + def getter(self): + "getter method" + return 0 + def setter(self, value): + "setter method" + pass + prop = property(getter) + vereq(prop.__doc__, "getter method") + prop2 = property(fset=setter) + vereq(prop2.__doc__, None) + + # this segfaulted in 2.5b2 + try: + import _testcapi + except ImportError: + pass + else: + class X(object): + p = property(_testcapi.test_with_docstring) + + def supers(): if verbose: print "Testing super..." @@ -1980,12 +2180,21 @@ aProp = property(lambda self: "foo") class Sub(Base): + # XXX: Jython 2.3 + #@classmethod def test(klass): return super(Sub,klass).aProp test = classmethod(test) veris(Sub.test(), Base.aProp) + # Verify that super() doesn't allow keyword args + try: + super(Base, kw=1) + except TypeError: + pass + else: + raise TestFailed, "super shouldn't accept keyword args" def inherits(): if verbose: print "Testing inheritance from basic types..." @@ -2202,22 +2411,6 @@ verify(s.lower().__class__ is str) vereq(s.lower(), base) - s = madstring("x y") - vereq(s, "x y") - verify(intern(s).__class__ is str) - verify(intern(s) is intern("x y")) - vereq(intern(s), "x y") - - i = intern("y x") - s = madstring("y x") - vereq(s, i) - verify(intern(s).__class__ is str) - verify(intern(s) is i) - - s = madstring(i) - verify(intern(s).__class__ is str) - verify(intern(s) is i) - class madunicode(unicode): _rev = None def rev(self): @@ -2621,6 +2814,7 @@ class Int(int): __slots__ = [] cant(2, Int) cant(Int(), int) + cant(True, int) cant(2, bool) o = object() cant(o, type(1)) @@ -2636,7 +2830,7 @@ def cant(x, dict): try: x.__dict__ = dict - except TypeError: + except (AttributeError, TypeError): pass else: raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict) @@ -2644,9 +2838,74 @@ cant(a, []) cant(a, 1) del a.__dict__ # Deleting __dict__ is allowed - # Classes don't allow __dict__ assignment - cant(C, {}) + class Base(object): + pass + def verify_dict_readonly(x): + """ + x has to be an instance of a class inheriting from Base. + """ + cant(x, {}) + try: + del x.__dict__ + except (AttributeError, TypeError): + pass + else: + raise TestFailed, "shouldn't allow del %r.__dict__" % x + dict_descr = Base.__dict__["__dict__"] + try: + dict_descr.__set__(x, {}) + except (AttributeError, TypeError): + pass + else: + raise TestFailed, "dict_descr allowed access to %r's dict" % x + + # Classes don't allow __dict__ assignment and have readonly dicts + class Meta1(type, Base): + pass + class Meta2(Base, type): + pass + class D(object): + __metaclass__ = Meta1 + class E(object): + __metaclass__ = Meta2 + for cls in C, D, E: + verify_dict_readonly(cls) + class_dict = cls.__dict__ + try: + class_dict["spam"] = "eggs" + except TypeError: + pass + else: + raise TestFailed, "%r's __dict__ can be modified" % cls + + # Modules also disallow __dict__ assignment + class Module1(types.ModuleType, Base): + pass + class Module2(Base, types.ModuleType): + pass + for ModuleType in Module1, Module2: + mod = ModuleType("spam") + verify_dict_readonly(mod) + mod.__dict__["spam"] = "eggs" + + # Exception's __dict__ can be replaced, but not deleted + class Exception1(Exception, Base): + pass + class Exception2(Base, Exception): + pass + for ExceptionType in Exception, Exception1, Exception2: + e = ExceptionType() + e.__dict__ = {"a": 1} + vereq(e.a, 1) + try: + del e.__dict__ + except (TypeError, AttributeError): + pass + else: + raise TestFaied, "%r's __dict__ can be deleted" % e + + def pickles(): if verbose: print "Testing pickling and copying new-style classes and objects..." @@ -2723,8 +2982,8 @@ vereq(sorteditems(x.__dict__), sorteditems(a.__dict__)) vereq(y.__class__, b.__class__) vereq(sorteditems(y.__dict__), sorteditems(b.__dict__)) - vereq(`x`, `a`) - vereq(`y`, `b`) + vereq(repr(x), repr(a)) + vereq(repr(y), repr(b)) if verbose: print "a = x =", a print "b = y =", b @@ -2757,8 +3016,8 @@ vereq(sorteditems(x.__dict__), sorteditems(a.__dict__)) vereq(y.__class__, b.__class__) vereq(sorteditems(y.__dict__), sorteditems(b.__dict__)) - vereq(`x`, `a`) - vereq(`y`, `b`) + vereq(repr(x), repr(a)) + vereq(repr(y), repr(b)) if verbose: print "a = x =", a print "b = y =", b @@ -2890,13 +3149,13 @@ else: return I(pow(int(other), int(self), int(mod))) - vereq(`I(1) + I(2)`, "I(3)") - vereq(`I(1) + 2`, "I(3)") - vereq(`1 + I(2)`, "I(3)") - vereq(`I(2) ** I(3)`, "I(8)") - vereq(`2 ** I(3)`, "I(8)") - vereq(`I(2) ** 3`, "I(8)") - vereq(`pow(I(2), I(3), I(5))`, "I(3)") + vereq(repr(I(1) + I(2)), "I(3)") + vereq(repr(I(1) + 2), "I(3)") + vereq(repr(1 + I(2)), "I(3)") + vereq(repr(I(2) ** I(3)), "I(8)") + vereq(repr(2 ** I(3)), "I(8)") + vereq(repr(I(2) ** 3), "I(8)") + vereq(repr(pow(I(2), I(3), I(5))), "I(3)") class S(str): def __eq__(self, other): return self.lower() == other.lower() @@ -2912,7 +3171,7 @@ class D(B, C): pass d = D() - vereq(hash(d), id(d)) + orig_hash = hash(d) # related to id(d) in platform-dependent ways A.__hash__ = lambda self: 42 vereq(hash(d), 42) C.__hash__ = lambda self: 314 @@ -2928,7 +3187,7 @@ del C.__hash__ vereq(hash(d), 42) del A.__hash__ - vereq(hash(d), id(d)) + vereq(hash(d), orig_hash) d.foo = 42 d.bar = 42 vereq(d.foo, 42) @@ -3040,6 +3299,21 @@ list.__init__(a, sequence=[0, 1, 2]) vereq(a, [0, 1, 2]) +def recursive__call__(): + if verbose: print ("Testing recursive __call__() by setting to instance of " + "class ...") + class A(object): + pass + + A.__call__ = A() + try: + A()() + except RuntimeError: + pass + else: + raise TestFailed("Recursion limit should have been reached for " + "__call__()") + def delhook(): if verbose: print "Testing __del__ hook..." log = [] @@ -3049,6 +3323,7 @@ c = C() vereq(log, []) del c + extra_collect() vereq(log, [1]) class D(object): pass @@ -3155,7 +3430,11 @@ if verbose: print "Testing dict-proxy iterkeys..." keys = [ key for key in C.__dict__.iterkeys() ] keys.sort() - vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) + if is_jython: + # XXX: It should include __doc__, but no __weakref__ (for now) + vereq(keys, ['__dict__', '__module__', 'meth']) + else: + vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) def dictproxyitervalues(): class C(object): @@ -3163,7 +3442,8 @@ pass if verbose: print "Testing dict-proxy itervalues..." values = [ values for values in C.__dict__.itervalues() ] - vereq(len(values), 5) + # XXX: See dictproxyiterkeys + vereq(len(values), is_jython and 3 or 5) def dictproxyiteritems(): class C(object): @@ -3172,7 +3452,10 @@ if verbose: print "Testing dict-proxy iteritems..." keys = [ key for (key, value) in C.__dict__.iteritems() ] keys.sort() - vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) + if is_jython: + vereq(keys, ['__dict__', '__module__', 'meth']) + else: + vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) def funnynew(): if verbose: print "Testing __new__ returning something unexpected..." @@ -3240,31 +3523,6 @@ vereq(NewClass.__doc__, 'object=None; type=NewClass') vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass') -def string_exceptions(): - if verbose: - print "Testing string exceptions ..." - - # Ensure builtin strings work OK as exceptions. - astring = "An exception string." - try: - raise astring - except astring: - pass - else: - raise TestFailed, "builtin string not usable as exception" - - # Ensure string subclass instances do not. - class MyStr(str): - pass - - newstring = MyStr("oops -- shouldn't work") - try: - raise newstring - except TypeError: - pass - except: - raise TestFailed, "string subclass allowed as exception" - def copy_setstate(): if verbose: print "Testing that copy.*copy() correctly uses __setstate__..." @@ -3691,55 +3949,6 @@ vereq(E() // C(), "C.__floordiv__") vereq(C() // E(), "C.__floordiv__") # This one would fail -def subclass_cmp_right_op(): - if verbose: - print "Testing correct dispatch of subclass overloading for comp ops" - - # Case 1: subclass of int - - class B(int): - def __ge__(self, other): - return "B.__ge__" - def __le__(self, other): - return "B.__le__" - - vereq(B(1) >= 1, "B.__ge__") - vereq(1 >= B(1), "B.__le__") - - # Case 2: subclass of object - - class C(object): - def __ge__(self, other): - return "C.__ge__" - def __le__(self, other): - return "C.__le__" - - vereq(C() >= 1, "C.__ge__") - vereq(1 >= C(), "C.__le__") - - # Case 3: subclass of new-style class; here it gets interesting - - class D(C): - def __ge__(self, other): - return "D.__ge__" - def __le__(self, other): - return "D.__le__" - - vereq(D() >= C(), "D.__ge__") - vereq(C() >= D(), "D.__le__") - - # Case 4: comparison is different than other binops - - class E(C): - pass - - vereq(E.__le__, C.__le__) - - vereq(E() >= 1, "C.__ge__") - vereq(1 >= E(), "C.__le__") - vereq(E() >= C(), "C.__ge__") - vereq(C() >= E(), "C.__le__") # different - def dict_type_with_metaclass(): if verbose: print "Testing type of __dict__ when __metaclass__ set..." @@ -3894,6 +4103,13 @@ o.whatever = Provoker(o) del o +def wrapper_segfault(): + # SF 927248: deeply nested wrappers could cause stack overflow + f = lambda:None + for i in xrange(1000000): + f = f.__call__ + f = None + # Fix SF #762455, segfault when sys.stdout is changed in getattr def filefault(): if verbose: @@ -3909,74 +4125,166 @@ except RuntimeError: pass -def subclass_binop(): +def vicious_descriptor_nonsense(): + # A potential segfault spotted by Thomas Wouters in mail to + # python-dev 2003-04-17, turned into an example & fixed by Michael + # Hudson just less than four months later... if verbose: - print "Testing binary ops with subclasses" + print "Testing vicious_descriptor_nonsense..." - def raises(exc, expected, callable, *args): - try: - callable(*args) - except exc, msg: - if str(msg) != expected: - raise TestFailed, "Message %r, expected %r" % (str(msg), - expected) - else: - raise TestFailed, "Expected %s" % exc + class Evil(object): + def __hash__(self): + return hash('attr') + def __eq__(self, other): + del C.attr + return 0 - class B(object): - pass + class Descr(object): + def __get__(self, ob, type=None): + return 1 class C(object): - def __radd__(self, o): - return '%r + C()' % (o,) + attr = Descr() - def __rmul__(self, o): - return '%r * C()' % (o,) + c = C() + if is_jython: + # XXX: 'attr' key is a Java String in PyStringMap, which + # prevents Evil's __eq__ from being called. Force __eq__ by + # using a dict instead + c.__dict__ = {} + c.__dict__[Evil()] = 0 - # Test strs, unicode, lists and tuples - mapping = [] + vereq(c.attr, 1) + # this makes a crash more likely: + import gc; gc.collect() + vereq(hasattr(c, 'attr'), False) - # + binop - mapping.append((lambda o: 'foo' + o, - TypeError, "cannot concatenate 'str' and 'B' objects", - "'foo' + C()")) - # XXX: There's probably work to be done here besides just emulating this - # message - #mapping.append((lambda o: u'foo' + o, - # TypeError, - # 'coercing to Unicode: need string or buffer, B found', - # "u'foo' + C()")) - mapping.append((lambda o: u'foo' + o, - TypeError, "cannot concatenate 'unicode' and 'B' objects", - "u'foo' + C()")) - mapping.append((lambda o: [1, 2] + o, - TypeError, 'can only concatenate list (not "B") to list', - '[1, 2] + C()')) - mapping.append((lambda o: ('foo', 'bar') + o, - TypeError, 'can only concatenate tuple (not "B") to tuple', - "('foo', 'bar') + C()")) +def test_init(): + # SF 1155938 + class Foo(object): + def __init__(self): + return 10 + try: + Foo() + except TypeError: + pass + else: + raise TestFailed, "did not test __init__() for None return" - # * binop - mapping.append((lambda o: 'foo' * o, - TypeError, "can't multiply sequence by non-int of type 'B'", - "'foo' * C()")) - mapping.append((lambda o: u'foo' * o, - TypeError, "can't multiply sequence by non-int of type 'B'", - "u'foo' * C()")) - mapping.append((lambda o: [1, 2] * o, - TypeError, "can't multiply sequence by non-int of type 'B'", - '[1, 2] * C()')) - mapping.append((lambda o: ('foo', 'bar') * o, - TypeError, "can't multiply sequence by non-int of type 'B'", - "('foo', 'bar') * C()")) +def methodwrapper(): + # <type 'method-wrapper'> did not support any reflection before 2.5 + if verbose: + print "Testing method-wrapper objects..." - for func, bexc, bexc_msg, cresult in mapping: - raises(bexc, bexc_msg, lambda : func(B())) - vereq(func(C()), cresult) + l = [] + vereq(l.__add__, l.__add__) + vereq(l.__add__, [].__add__) + verify(l.__add__ != [5].__add__) + verify(l.__add__ != l.__mul__) + verify(l.__add__.__name__ == '__add__') + verify(l.__add__.__self__ is l) + verify(l.__add__.__objclass__ is list) + vereq(l.__add__.__doc__, list.__add__.__doc__) + try: + hash(l.__add__) + except TypeError: + pass + else: + raise TestFailed("no TypeError from hash([].__add__)") + t = () + t += (7,) + vereq(t.__add__, (7,).__add__) + vereq(hash(t.__add__), hash((7,).__add__)) + +def notimplemented(): + # all binary methods should be able to return a NotImplemented + if verbose: + print "Testing NotImplemented..." + + import sys + import types + import operator + + def specialmethod(self, other): + return NotImplemented + + def check(expr, x, y): + try: + exec expr in {'x': x, 'y': y, 'operator': operator} + except TypeError: + pass + else: + raise TestFailed("no TypeError from %r" % (expr,)) + + N1 = sys.maxint + 1L # might trigger OverflowErrors instead of TypeErrors + N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger + # ValueErrors instead of TypeErrors + for metaclass in [type, types.ClassType]: + for name, expr, iexpr in [ + ('__add__', 'x + y', 'x += y'), + ('__sub__', 'x - y', 'x -= y'), + ('__mul__', 'x * y', 'x *= y'), + ('__truediv__', 'operator.truediv(x, y)', None), + ('__floordiv__', 'operator.floordiv(x, y)', None), + ('__div__', 'x / y', 'x /= y'), + ('__mod__', 'x % y', 'x %= y'), + ('__divmod__', 'divmod(x, y)', None), + ('__pow__', 'x ** y', 'x **= y'), + ('__lshift__', 'x << y', 'x <<= y'), + ('__rshift__', 'x >> y', 'x >>= y'), + ('__and__', 'x & y', 'x &= y'), + ('__or__', 'x | y', 'x |= y'), + ('__xor__', 'x ^ y', 'x ^= y'), + ('__coerce__', 'coerce(x, y)', None)]: + if name == '__coerce__': + rname = name + else: + rname = '__r' + name[2:] + A = metaclass('A', (), {name: specialmethod}) + B = metaclass('B', (), {rname: specialmethod}) + a = A() + b = B() + check(expr, a, a) + check(expr, a, b) + check(expr, b, a) + check(expr, b, b) + check(expr, a, N1) + check(expr, a, N2) + check(expr, N1, b) + check(expr, N2, b) + if iexpr: + check(iexpr, a, a) + check(iexpr, a, b) + check(iexpr, b, a) + check(iexpr, b, b) + check(iexpr, a, N1) + check(iexpr, a, N2) + iname = '__i' + name[2:] + C = metaclass('C', (), {iname: specialmethod}) + c = C() + check(iexpr, c, a) + check(iexpr, c, b) + check(iexpr, c, N1) + check(iexpr, c, N2) + +def test_assign_slice(): + # ceval.c's assign_slice used to check for + # tp->tp_as_sequence->sq_slice instead of + # tp->tp_as_sequence->sq_ass_slice + + class C(object): + def __setslice__(self, start, stop, value): + self.value = value + + c = C() + c[1:2] = 3 + vereq(c.value, 3) + def test_main(): testfuncs = [ weakref_segfault, # Must be first, somehow + wrapper_segfault, do_this_first, class_docstrings, lists, @@ -3987,6 +4295,8 @@ longs, floats, complexes, + spamlists, + spamdicts, pydicts, pylists, metaclass, @@ -4003,7 +4313,9 @@ dynamics, errors, classmethods, + classmethods_in_c, staticmethods, + staticmethods_in_c, classic, compattr, newslot, @@ -4031,6 +4343,7 @@ buffer_inherit, str_of_str_subclass, kwdargs, + recursive__call__, delhook, hashinherit, strops, @@ -4043,7 +4356,6 @@ funnynew, imulbug, docdescriptor, - string_exceptions, copy_setstate, slices, subtype_resurrection, @@ -4056,15 +4368,69 @@ test_mutable_bases_catch_mro_conflict, mutable_names, subclass_right_op, - subclass_cmp_right_op, dict_type_with_metaclass, meth_class_get, isinst_isclass, proxysuper, carloverre, filefault, - subclass_binop, + vicious_descriptor_nonsense, + test_init, + methodwrapper, + notimplemented, + test_assign_slice, ] + if is_jython: + for testfunc in [ + # Requires CPython specific xxsubtype module + spamlists, + spamdicts, + classmethods_in_c, + staticmethods_in_c, + + # pjenvey broke slots + slots, + slotspecials, + + # Jython allows subclassing of classes it shouldn't (like + # builtin_function_or_method): + # http://bugs.jython.org/issue1758319 + errors, + + # Requires validation of mro() results + # http://bugs.jython.org/issue1056 + altmro, + + # CPython's unicode.__cmp__ is derived from type (and only + # takes 1 arg) + specials, + + # Jython file lacks doc strings + descrdoc, + + # Already fixed on the pep352 branch + setdict, + + # New style classes don't support __del__: + # http://bugs.jython.org/issue1057 + delhook, + subtype_resurrection, + + # Lack __basicsize__: http://bugs.jython.org/issue1017 + slotmultipleinheritance, + + # Carlo hacked us: http://bugs.jython.org/issue1058 + carloverre, + + # Jython lacks CPython method-wrappers (though maybe this + # should pass anyway?) + methodwrapper, + + # __ixxx__ doesn't act like a binary op + # http://bugs.jython.org/issue1873148 + notimplemented + ]: + testfuncs.remove(testfunc) if __name__ == '__main__': import sys if len(sys.argv) > 1: @@ -4075,7 +4441,8 @@ for testfunc in testfuncs: try: - print "*"*40 + if verbose: + print "*"*40 testfunc() except Exception, e: if isinstance(e, KeyboardInterrupt) or n == 1: @@ -4083,7 +4450,8 @@ print "-->", testfunc.__name__, "FAILURE(%d/%d)" % (success, n), str(e) else: success += 1 - print "-->", testfunc.__name__, "OK(%d/%d)" % (success, n) + if verbose: + print "-->", testfunc.__name__, "OK(%d/%d)" % (success, n) if n != success: raise TestFailed, "%d/%d" % (success, n) Modified: branches/asm/Lib/test/test_descr_jy.py =================================================================== --- branches/asm/Lib/test/test_descr_jy.py 2008-06-16 13:20:35 UTC (rev 4650) +++ branches/asm/Lib/test/test_descr_jy.py 2008-06-16 15:54:15 UTC (rev 4651) @@ -46,9 +46,136 @@ self.assert_(isinstance(unbound, types.MethodType)) self.assert_(unbound.im_self is None) + def test_ints(self): + class C(int): + pass + try: + foo = int(None) + except TypeError: + pass + else: + self.assert_(False, "should have raised TypeError") + try: + foo = C(None) + except TypeError: + pass + else: + self.assert_(False, "should have raised TypeError") +class SubclassDescrTestCase(unittest.TestCase): + + def test_subclass_cmp_right_op(self): + # Case 1: subclass of int + + class B(int): + def __ge__(self, other): + return "B.__ge__" + def __le__(self, other): + return "B.__le__" + + self.assertEqual(B(1) >= 1, "B.__ge__") + self.assertEqual(1 >= B(1), "B.__le__") + + # Case 2: subclass of object + + class C(object): + def __ge__(self, other): + return "C.__ge__" + def __le__(self, other): + return "C.__le__" + + self.assertEqual(C() >= 1, "C.__ge__") + self.assertEqual(1 >= C(), "C.__le__") + + # Case 3: subclass of new-style class; here it gets interesting + + class D(C): + def __ge__(self, other): + return "D.__ge__" + def __le__(self, other): + return "D.__le__" + + self.assertEqual(D() >= C(), "D.__ge__") + self.assertEqual(C() >= D(), "D.__le__") + + # Case 4: comparison is different than other binops + + class E(C): + pass + + self.assertEqual(E.__le__, C.__le__) + + self.assertEqual(E() >= 1, "C.__ge__") + self.assertEqual(1 >= E(), "C.__le__") + self.assertEqual(E() >= C(), "C.__ge__") + self.assertEqual(C() >= E(), "C.__le__") # different + + def test_subclass_binop(self): + def raises(exc, expected, callable, *args): + try: + callable(*args) + except exc, msg: + if str(msg) != expected: + self.assert_(False, "Message %r, expected %r" % (str(msg), + expected)) + else: + self.assert_(False, "Expected %s" % exc) + + class B(object): + pass + + class C(object): + def __radd__(self, o): + return '%r + C()' % (o,) + + def __rmul__(self, o): + return '%r * C()' % (o,) + + # Test strs, unicode, lists and tuples + mapping = [] + + # + binop + mapping.append((lambda o: 'foo' + o, + TypeError, "cannot concatenate 'str' and 'B' objects", + "'foo' + C()")) + # XXX: There's probably work to be done here besides just emulating this + # message + #mapping.append((lambda o: u'foo' + o,<> + # TypeError, + # 'coercing to Unicode: need string or buffer, B found', + # "u'foo' + C()")) + mapping.append((lambda o: u'foo' + o, + TypeError, "cannot concatenate 'unicode' and 'B' objects", + "u'foo' + C()")) + mapping.append((lambda o: [1, 2] + o, + TypeError, 'can only concatenate list (not "B") to list', + '[1, 2] + C()')) + mapping.append((lambda o: ('foo', 'bar') + o, + TypeError, 'can only concatenate tuple (not "B") to tuple', + "('foo', 'bar') + C()")) + + # * binop + mapping.append((lambda o: 'foo' * o, + TypeError, "can't multiply sequence by non-int of type 'B'", + "'foo' * C()")) + mapping.append((lambda o: u'foo' * o, + TypeError, "can't multiply sequence by non-int of type 'B'", + "u'foo' * C()")) + mapping.append((lambda o: [1, 2] * o, + TypeError, "can't multiply sequence by non-int of type 'B'", + '[1, 2] * C()')) + mapping.append((lambda o: ('foo', 'bar') * o, + TypeError, "can't multiply sequence by non-int of type 'B'", + "('foo', 'bar') * C()")) + + for func, bexc, bexc_msg, cresult in mapping: + raises(bexc, bexc_msg, lambda : func(B())) + self.assertEqual(func(C()), cresult) + + def test_main(): - test_support.run_unittest(TestDescrTestCase) + test_support.run_unittest(TestDescrTestCase, + SubclassDescrTestCase) if __name__ == '__main__': test_main() Modified: branches/asm/Lib/test/test_file.py =================================================================== --- branches/asm/Lib/test/test_file.py 2008-06-16 13:20:35 UTC (rev 4650) +++ branches/asm/Lib/test/test_file.py 2008-06-16 15:54:15 UTC (rev 4651) @@ -5,7 +5,7 @@ from array import array from weakref import proxy -from test.test_support import TESTFN, findfile, run_unittest +from test.test_support import TESTFN, findfile, is_jython, run_unittest from UserList import UserList class AutoFileTests(unittest.TestCase): @@ -19,14 +19,16 @@ self.f.close() os.remove(TESTFN) - # XXX: assumes CPython style garbage collection - def _testWeakRefs(self): + def testWeakRefs(self): # verify weak references p = proxy(self.f) p.write('teststring') self.assertEquals(self.f.tell(), p.tell()) self.f.close() self.f = None + if is_jython: + from test_weakref import extra_collect + extra_collect() self.assertRaises(ReferenceError, getattr, p, 'tell') def testAttributes(self): @@ -111,9 +113,7 @@ methods.remove('truncate') # __exit__ should close the file - # XXX: __exit__ is 2.5 specific - #self.f.__exit__(None, None, None) - self.f.close() + self.f.__exit__(None, None, None) self.assert_(self.f.closed) for methodname, arg in methods.iteritems(): @@ -125,8 +125,6 @@ self.assertRaises(ValueError, method, arg) self.assertRaises(ValueError, self.f.writelines, []) - # XXX: __exit__ is 2.5 specific - return # file is closed, __exit__ shouldn't do anything self.assertEquals(self.f.__exit__(None, None, None), None) # it must also return None if an exception was given @@ -149,9 +147,7 @@ f.close() self.fail('%r is an invalid file mode' % mode) - # XXX: Jython's stdin can't seek, it's not backed by a - # RandomAccessFile - def _testStdin(self): + def testStdin(self): # This causes the interpreter to exit on OSF1 v5.1. if sys.platform != 'osf1V5': self.assertRaises(IOError, sys.stdin.seek, -1) @@ -232,8 +228,7 @@ finally: os.unlink(TESTFN) - # XXX: Jython allows mixing reads with iteration - def _testIteration(self): + def testIteration(self): # Test the complex interaction when mixing file-iteration and the # various read* methods. Ostensibly, the mixture could just be tested # to work when it should work according to the Python language, @@ -346,6 +341,13 @@ def test_main(): + if is_jython: + # Jython's stdin can't seek, it's not backed by a + # RandomAccessFile + del OtherFileTests.testStdin + # Jython allows mixing reads with iteration + del OtherFileTests.testIteration + # Historically, these tests have been sloppy about removing TESTFN. # So get rid of it no matter what. try: Deleted: branches/asm/Lib/test/test_pow.py =================================================================== --- branches/asm/Lib/test/test_pow.py 2008-06-16 13:20:35 UTC (rev 4650) +++ branches/asm/Lib/test/test_pow.py 2008-06-16 15:54:15 UTC (rev 4651) @@ -1,107 +0,0 @@ -import sys -from test_support import * - -print_test("power (test_pow.py)", 2) - -def powtest(type): - if (type!=float): - print_test("simple identities", 4) - for i in range(-1000, 1000): - assert type(i)**0 == 1 - assert type(i)**1 == type(i) - if i > 0: - assert type(0)**i == type(0) - assert type(1)**i == type(1) - - print_test("cubes") - for i in range(-100, 100): - assert type(i)**3 == i*i*i - - print_test("powers of two") - pow2=1 - for i in range(0,31): - assert 2**i == pow2 - if i!=30: pow2=pow2*2 - # modPow() has known assertion failures in all Sun 1.1 JDKs after 1.1.5. - # Apparently, Sun is not going to fix this for 1.1 since the bug still - # exists in 1.1.8 and the bug ID 4098742 is closed. - if sys.platform.startswith('java1.1') and type == long: - print_test('modpow... skipping due to JVM bugs', 4) - return - print_test("modpow", 4) - il, ih = -20, 20 - jl, jh = -5, 5 - kl, kh = -10, 10 - compare = cmp - if (type==float): - il=1 - compare = fcmp - elif (type==int): - jl=0 - elif (type==long): - jl,jh = 0, 15 - for i in range(il, ih+1): - for j in range(jl,jh+1): - for k in range(kl, kh+1): - if (k!=0): - try: - assert compare(pow(type(i),j,k), type(i)**j % type(k)) == 0, '%s, %s, %s' % (i,j,k) - except TypeError: - if type==float: - # Python 2.2 only allows 3rd arg if first 2 are integers - pass - else: - raise - -print_test("integers", 3) -powtest(int) -print_test("longs", 3) -powtest(long) -print_test("floats", 3) -powtest(float) - -print_test("mixed-mode", 3) - -assert 3**3%8 == pow(3,3,8) == 3 -assert 3**3%-8 == pow(3,3,-8) == -5 -assert 3**2%-2 == pow(3,2,-2) == -1 -assert -3**3%8 == pow(-3,3,8) == 5 -assert -3**3%-8 == pow(-3,3,-8) == -3 -assert 5**2%-8 == pow(5,2,-8) == -7 - -assert 3L**3%8 == pow(3L,3,8) == 3L -assert 3L**3%-8 == pow(3,3L,-8) == -5L -assert 3L**2%-2 == pow(3,2,-2L) == -1L -assert -3L**3%8 == pow(-3L,3,8) == 5L -assert -3L**3%-8 == pow(-3,3L,-8) == -3L -assert 5L**2%-8 == pow(5,2,-8L) == -7L - -# Python 2.2 only allows 3rd arg if first 2 are integers -assert 3.**3%8 == pow(3.,3) % 8 == 3. -assert 3.**3%-8 == pow(3,3.) % -8 == -5. -assert 3.**2%-2 == pow(3,2) %-2. == -1. -assert -3.**3%8 == pow(-3.,3) % 8 == 5. -assert -3.**3%-8 == pow(-3,3.) % -8 == -3. -assert 5.**2%-8 == pow(5,2) % -8. == -7. - -print_test( "Validate that TypeError is thrown with 3 args if first two args aren't integers" ) -import unittest -tc = unittest.TestCase( "fail" ) # get failUnlessRaises method -tc.failUnlessRaises( TypeError, pow, 3., 3, 8 ) -tc.failUnlessRaises( TypeError, pow, 3, 3., 8 ) - -if sys.platform.startswith('java1.1'): - print_test("miscellaneous... skipping due to JVM bugs", 3) -else: - print_test("miscellaneous", 3) - for i in range(-10, 11): - for j in range(0, 6): - for k in range(-7, 11): - if (j>=0 and k!=0): - o=pow(i,j) % k - n=pow(i,j,k) - assert o == n, 'Integer mismatch: %d, %d, %d' % (i,j,k) - if (j>=0 and k<>0): - o=pow(long(i),j) % k - n=pow(long(i),j,k) - assert o == n, 'Long mismatch: %s, %s, %s' % (i,j,k) Copied: branches/asm/Lib/test/test_time.py (from rev 4650, trunk/jython/Lib/test/test_time.py) =================================================================== --- branches/asm/Lib/test/test_time.py (rev 0) +++ branches/asm/Lib/test/test_time.py 2008-06-16 15:54:15 UTC (rev 4651) @@ -0,0 +1,228 @@ +from test import test_support +import time +import unittest + + +class TimeTestCase(unittest.TestCase): + + def setUp(self): + self.t = time.time() + + def test_data_attributes(self): + time.altzone + time.daylight + time.timezone + time.tzname + + def test_clock(self): + time.clock() + + def test_conversions(self): + self.assert_(time.ctime(self.t) + == time.asctime(time.localtime(self.t))) + self.assert_(long(time.mktime(time.localtime(self.t))) + == long(self.t)) + + def test_sleep(self): + time.sleep(1.2) + + def test_strftime(self): + tt = time.gmtime(self.t) + for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', + 'j', 'm', 'M', 'p', 'S', + 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): + format = ' %' + directive + try: + time.strftime(format, tt) + except ValueError: + self.fail('conversion specifier: %r failed.' % format) + + def test_strftime_bounds_checking(self): + # Make sure that strftime() checks the bounds of the various parts + #of the time tuple (0 is valid for *all* values). + + # XXX: Jython supports more dates than CPython + if not test_support.is_jython: + # Check year [1900, max(int)] + self.assertRaises(ValueError, time.strftime, '', + (1899, 1, 1, 0, 0, 0, 0, 1, -1)) + if time.accept2dyear: + self.assertRaises(ValueError, time.strftime, '', + (-1, 1, 1, 0, 0, 0, 0, 1, -1)) + self.assertRaises(ValueError, time.strftime, '', + (100, 1, 1, 0, 0, 0, 0, 1, -1)) + # Check month [1, 12] + zero support + self.assertRaises(ValueError, time.strftime, '', + (1900, -1, 1, 0, 0, 0, 0, 1, -1)) + self.assertRaises(ValueError, time.strftime, '', + (1900, 13, 1, 0, 0, 0, 0, 1, -1)) + # Check day of month [1, 31] + zero support + self.assertRaises(ValueError, time.strftime, '', + (1900, 1, -1, 0, 0, 0, 0, 1, -1)) + self.assertRaises(ValueError, time.strftime, '', + (1900, 1, 32, 0, 0, 0, 0, 1, -1)) + # Check hour [0, 23] + self.assertRaises(ValueError, time.strftime, '', + (1900, 1, 1, -1, 0, 0, 0, 1, -1)) + self.assertRaises(ValueError, time.strftime, '', + (1900, 1, 1, 24, 0, 0, 0, 1, -1)) + # Check minute [0, 59] + self.assertRaises(ValueError, time.strftime, '', + (1900, 1, 1, 0, -1, 0, 0, 1, -1)) + self.assertRaises(ValueError, time.strftime, '', + (1900, 1, 1, 0, 60, 0, 0, 1, -1)) + # Check second [0, 61] + self.assertRaises(ValueError, time.strftime, '', + (1900, 1, 1, 0, 0, -1, 0, 1, -1)) + # C99 only requires allowing for one leap second, but Python's docs say + # allow two leap seconds (0..61) + self.assertRaises(ValueError, time.strftime, '', + (1900, 1, 1, 0, 0, 62, 0, 1, -1)) + # No check for upper-bound day of week; + # value forced into range by a ``% 7`` calculation. + # Start check at -2 since gettmarg() increments value before taking + # modulo. + self.assertRaises(ValueError, time.strftime, '', + (1900, 1, 1, 0, 0, 0, -2, 1, -1)) + # Check day of the year [1, 366] + zero support + self.assertRaises(ValueError, time.strftime, '', + (1900, 1, 1, 0, 0, 0, 0, -1, -1)) + self.assertRaises(ValueError, t... [truncated message content] |