From: <fwi...@us...> - 2009-08-10 17:32:56
|
Revision: 6649 http://jython.svn.sourceforge.net/jython/?rev=6649&view=rev Author: fwierzbicki Date: 2009-08-10 17:32:50 +0000 (Mon, 10 Aug 2009) Log Message: ----------- Trivial reindents. Modified Paths: -------------- trunk/jython/Lib/test/regrtest.py trunk/jython/Lib/test/test_java_list_delegate.py trunk/jython/Lib/test/test_jy_internals.py trunk/jython/Lib/test/test_timeit.py Modified: trunk/jython/Lib/test/regrtest.py =================================================================== --- trunk/jython/Lib/test/regrtest.py 2009-08-10 17:24:15 UTC (rev 6648) +++ trunk/jython/Lib/test/regrtest.py 2009-08-10 17:32:50 UTC (rev 6649) @@ -1577,7 +1577,7 @@ print >>f," ]" finally: f.close() - + if __name__ == '__main__': # Remove regrtest.py's own directory from the module search path. This # prevents relative imports from working, and relative imports will screw Modified: trunk/jython/Lib/test/test_java_list_delegate.py =================================================================== --- trunk/jython/Lib/test/test_java_list_delegate.py 2009-08-10 17:24:15 UTC (rev 6648) +++ trunk/jython/Lib/test/test_java_list_delegate.py 2009-08-10 17:32:50 UTC (rev 6649) @@ -9,10 +9,10 @@ def _perform_op(self, value, op_func): """ Perform an operation - + value - the value to operate on op_func - the function that applies the operation to value - + Returns: the result of calling op_func, OR the exception that was raised in op_func """ @@ -20,7 +20,7 @@ return op_func(value) except Exception, e: return type(e) - + def check_list(self, control, results, initial): for result in results: try: @@ -34,48 +34,48 @@ def _list_op_test(self, initial_value, op_func, check_value): """ Tests a list operation - + Ensures that performing an operation on: - a python list - a java.util.List instance - + givens the same result in both cases """ lists = [list(initial_value), ArrayList(initial_value), Vector(initial_value)] - + results = [self._perform_op(l, op_func) for l in lists] self.check_list(lists[0], lists[1:], initial_value) if check_value or not isinstance(results[0], list): for r in results[1:]: - self.assertEquals(results[0], r) + self.assertEquals(results[0], r) else: self.check_list(results[0], results[1:], initial_value) - + def test_get_integer(self): initial_value = range(0, 5) - + for i in xrange(-7, 7): self._list_op_test(initial_value, lambda xs: xs[i], True) def test_set_integer(self): initial_value = range(0, 5) - + def make_op_func(index): def _f(xs): xs[index] = 100 return _f - + for i in xrange(-7, 7): self._list_op_test(initial_value, make_op_func(i), True) def test_set_slice(self): initial_value = range(0, 10) - + def make_op_func(i, j, k, v): def _f(xs): xs[i:j:k] = v return _f - + for i in xrange(-12, 12): for j in xrange(-12, 12): for k in xrange(-12, 12): @@ -86,44 +86,44 @@ def test_del_integer(self): initial_value = range(0,5) - + def make_op_func(index): def _f(xs): del xs[index] return _f - + for i in xrange(-7, 7): self._list_op_test(initial_value, make_op_func(i), True) def test_del_slice(self): initial_value = range(0,10) - + def make_op_func(i, j, k): def _f(xs): del xs[i:j:k] return _f - + for i in xrange(-12, 12): for j in xrange(-12, 12): for k in xrange(-12, 12): self._list_op_test(initial_value, make_op_func(i, j, k), True) - + def test_len(self): jlist = ArrayList() jlist.addAll(range(0, 10)) - + self.assert_(len(jlist) == 10) - + def test_iter(self): jlist = ArrayList() jlist.addAll(range(0, 10)) - + i = iter(jlist) - + x = list(i) - + self.assert_(x == range(0, 10)) - + def test_override_len(self): class MyList (ArrayList): def __len__(self): @@ -131,20 +131,20 @@ m = MyList() m.addAll(range(0,10)) - + self.assert_(len(m) == 11) def test_override_iter(self): class MyList (ArrayList): def __iter__(self): return iter(self.subList(0, self.size() - 1)); - - + + m = MyList() m.addAll(range(0,10)) i = iter(m) x = list(i) - + self.assert_(x == range(0, 9)) def test_override_getsetdelitem(self): @@ -155,21 +155,21 @@ def __setitem__(self, key, value): return self.set(key, value * 2); - + def __delitem__(self, key): self.add(84) m = MyList() m.addAll(range(0,10)) - + self.assert_(m[1] == 2) self.assert_(m.get(1) == 1) - + m[0] = 3 self.assert_(m.get(0) == 6) self.assert_(m[0] == 12) - + del m[0] self.assert_(m.size() == 11) self.assert_(m.get(10) == 84) Modified: trunk/jython/Lib/test/test_jy_internals.py =================================================================== --- trunk/jython/Lib/test/test_jy_internals.py 2009-08-10 17:24:15 UTC (rev 6648) +++ trunk/jython/Lib/test/test_jy_internals.py 2009-08-10 17:32:50 UTC (rev 6649) @@ -97,9 +97,9 @@ assert e[0] == 0 for d in range(8): - for y in [0,255]: - assert float((v+d)*256+y) == sdv(((v+d)*256+y)*256, e) - assert e[0] == 1 + for y in [0,255]: + assert float((v+d)*256+y) == sdv(((v+d)*256+y)*256, e) + assert e[0] == 1 class ExtraMathTests(unittest.TestCase): def test_epsilon(self): @@ -198,7 +198,7 @@ self = frame.f_locals[frame.f_code.co_varnames[0]] myclass = self.__class__ if type(myclass) == ClassType: - classname = myclass.__name__ + classname = myclass.__name__ else: classname = None @@ -210,14 +210,14 @@ assert (g[0] == "__main__" or g[0] == "test.test_jy_internals") self.assertEquals(g[1], None) self.assertEquals(g[2], "foo") - + class Bar: def baz(self): g = getinfo() assert (g[0] == "__main__" or g[0] == "test.test_jy_internals") assert (g[1] == "Bar") assert (g[2] == "baz") - + g = getinfo() assert (g[0] == "__main__" or g[0] == "test.test_jy_internals") self.assertEquals(g[1], None) @@ -253,4 +253,3 @@ if __name__ == "__main__": test_main() - Modified: trunk/jython/Lib/test/test_timeit.py =================================================================== --- trunk/jython/Lib/test/test_timeit.py 2009-08-10 17:24:15 UTC (rev 6648) +++ trunk/jython/Lib/test/test_timeit.py 2009-08-10 17:32:50 UTC (rev 6649) @@ -7,7 +7,7 @@ # module in the regrtest class TestTimeit(unittest.TestCase): - + def test_oct(self): timing = timeit.Timer('for i in xrange(10): oct(i)', 'gc.enable()').timeit(number=10000) self.assertTrue(timing > 0.) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-08-10 17:36:03
|
Revision: 6650 http://jython.svn.sourceforge.net/jython/?rev=6650&view=rev Author: fwierzbicki Date: 2009-08-10 17:35:54 +0000 (Mon, 10 Aug 2009) Log Message: ----------- Reindents. Modified Paths: -------------- trunk/jython/Lib/test/test_dict2java.py trunk/jython/Lib/test/test_javashell.py trunk/jython/Lib/test/test_jbasic.py trunk/jython/Lib/test/test_jy_generators.py trunk/jython/Lib/test/test_marshal.py trunk/jython/Lib/test/test_thread_local.py trunk/jython/Lib/test/test_tuple.py Modified: trunk/jython/Lib/test/test_dict2java.py =================================================================== --- trunk/jython/Lib/test/test_dict2java.py 2009-08-10 17:32:50 UTC (rev 6649) +++ trunk/jython/Lib/test/test_dict2java.py 2009-08-10 17:35:54 UTC (rev 6650) @@ -45,7 +45,7 @@ self.checksize(oldlen + 3) self.checkvalues(('e', '1'), ('f', None), ('g', '2')) - # test Map.get method, get "g" and "d" test will throw an exception if fail + # test Map.get method, get "g" and "d" test will throw an exception if fail self.failUnless(self.testmap.test_get_gd()) # remove elements with keys "a" and "c" with the Map.remove method Modified: trunk/jython/Lib/test/test_javashell.py =================================================================== --- trunk/jython/Lib/test/test_javashell.py 2009-08-10 17:32:50 UTC (rev 6649) +++ trunk/jython/Lib/test/test_javashell.py 2009-08-10 17:35:54 UTC (rev 6650) @@ -41,12 +41,12 @@ # should print 'testKey=' on 95 before initialization, # and 'testKey=testValue' after ("echo %s=%%%s%%" % (key,key), - "(%s=)" % (key,)), + "(%s=)" % (key,)), # should print PATH (on Unix) ( "echo PATH=$PATH", "PATH=.*" ), # should print 'testKey=testValue' on Unix after initialization ( "echo %s=$%s" % (key,key), - "(%s=$%s)|(%s=)|(%s=%s)" % (key, key, key, key, value ) ), + "(%s=$%s)|(%s=)|(%s=%s)" % (key, key, key, key, value ) ), # should output quotes on NT but not on Unix ( 'echo "hello there"', '"?hello there"?' ), # should print 'why' to stdout. @@ -138,4 +138,3 @@ if __name__ == "__main__": test_main() - Modified: trunk/jython/Lib/test/test_jbasic.py =================================================================== --- trunk/jython/Lib/test/test_jbasic.py 2009-08-10 17:32:50 UTC (rev 6649) +++ trunk/jython/Lib/test/test_jbasic.py 2009-08-10 17:35:54 UTC (rev 6650) @@ -28,12 +28,12 @@ vec = Vector() items = range(10) for i in items: - vec.addElement(i) + vec.addElement(i) expected = 0 for i in vec: - assert i == expected, 'testing __iter__ on java.util.Vector' - expected = expected+1 + assert i == expected, 'testing __iter__ on java.util.Vector' + expected = expected+1 expected = 0 for i in iter(vec): @@ -76,11 +76,11 @@ #Make sure non-existent fields fail try: - print d.foo + print d.foo except AttributeError: - pass + pass else: - raise AssertionError, 'd.foo should throw type error' + raise AssertionError, 'd.foo should throw type error' print 'get/set bean properties' @@ -94,8 +94,8 @@ # Test bean event properties - single and multiple flag = 0 def testAction(event): - global flag - flag = flag + 1 + global flag + flag = flag + 1 from java.awt.event import ActionEvent Modified: trunk/jython/Lib/test/test_jy_generators.py =================================================================== --- trunk/jython/Lib/test/test_jy_generators.py 2009-08-10 17:32:50 UTC (rev 6649) +++ trunk/jython/Lib/test/test_jy_generators.py 2009-08-10 17:35:54 UTC (rev 6650) @@ -43,7 +43,7 @@ try: for i in range(3): try: - try: + try: 1//0 finally: yield i @@ -85,7 +85,7 @@ finally: for k in range(j): try: - try: + try: 1//0 finally: yield (i, j, k) @@ -98,7 +98,7 @@ 1//0 finally: for k in range(3): - try: + try: 1//0 finally: yield (j, k) @@ -115,7 +115,7 @@ 1//0 finally: for k in range(3): - try: + try: 1//0 finally: yield (i, j, k) @@ -127,7 +127,7 @@ self.assertEquals([0, 1, 2], list(self.genPass())) self.assertEquals([1], list(self.genLocal())) self.assertEquals( - [1, 2, 1, 2, 0, 1], + [1, 2, 1, 2, 0, 1], list(self.genConditional())) self.assertEquals([0, 1, 2, 3], list(self.genTryExceptAroundFinally())) self.assertEquals( @@ -137,7 +137,7 @@ [(0, 0), (0, 1), (1, 0), (1, 1)], list(self.genNestedReversed())) self.assertEquals( - [(2, 1, 0), (3, 1, 0), (3, 2, 0), (3, 2, 1)], + [(2, 1, 0), (3, 1, 0), (3, 2, 0), (3, 2, 1)], list(self.genNestedDeeply())) self.assertEquals( [(0, 0), (1, 0), (2, 0)], @@ -162,4 +162,3 @@ if __name__ == "__main__": unittest.main() - Modified: trunk/jython/Lib/test/test_marshal.py =================================================================== --- trunk/jython/Lib/test/test_marshal.py 2009-08-10 17:32:50 UTC (rev 6649) +++ trunk/jython/Lib/test/test_marshal.py 2009-08-10 17:35:54 UTC (rev 6650) @@ -18,8 +18,8 @@ with open(test_support.TESTFN, "rb") as test_file: got = marshal.load(test_file) return got - + class IntTestCase(unittest.TestCase): def test_ints(self): # Test the full range of Python ints. Modified: trunk/jython/Lib/test/test_thread_local.py =================================================================== --- trunk/jython/Lib/test/test_thread_local.py 2009-08-10 17:32:50 UTC (rev 6649) +++ trunk/jython/Lib/test/test_thread_local.py 2009-08-10 17:35:54 UTC (rev 6650) @@ -1,12 +1,12 @@ #! /usr/bin/env python -""" Simple test script for Thread.local +""" Simple test script for Thread.local """ from thread import _local as local import unittest from test import test_support import threading -class ThreadLocalTestCase(unittest.TestCase): +class ThreadLocalTestCase(unittest.TestCase): def test_two_locals(self): '''Ensures that two locals in the same thread have separate dicts.''' @@ -20,19 +20,19 @@ def test_local(self): mydata = local() mydata.number = 42 - self.assertEqual(mydata.number,42) + self.assertEqual(mydata.number,42) self.assertEqual(mydata.__dict__,{'number': 42}) mydata.__dict__.setdefault('widgets', []) self.assertEqual(mydata.widgets,[]) log=[] - - def f(): - items = mydata.__dict__.items() - items.sort() + + def f(): + items = mydata.__dict__.items() + items.sort() log.append(items) - mydata.number = 11 - log.append(mydata.number) - + mydata.number = 11 + log.append(mydata.number) + thread = threading.Thread(target=f) thread.start() thread.join() @@ -40,12 +40,12 @@ self.assertEqual(mydata.number,42) def test_subclass_local(self): - def f(): - items = mydata.__dict__.items() - items.sort() + def f(): + items = mydata.__dict__.items() + items.sort() log.append(items) - mydata.number = 11 - log.append(mydata.number) + mydata.number = 11 + log.append(mydata.number) class MyLocal(local): number = 2 @@ -54,13 +54,13 @@ if self.initialized: raise SystemError('__init__ called too many times') self.initialized = True - self.__dict__.update(kw) + self.__dict__.update(kw) def squared(self): return self.number ** 2 - + class SubSubLocal(MyLocal): pass - + mydata = MyLocal(color='red') self.assertEqual(mydata.number,2) self.assertEqual(mydata.color,'red') Modified: trunk/jython/Lib/test/test_tuple.py =================================================================== --- trunk/jython/Lib/test/test_tuple.py 2009-08-10 17:32:50 UTC (rev 6649) +++ trunk/jython/Lib/test/test_tuple.py 2009-08-10 17:35:54 UTC (rev 6650) @@ -48,7 +48,7 @@ except OutOfMemoryError, oome: oome.printStackTrace() raise - + def _test_hash(self): # See SF bug 942952: Weakness in tuple hash # The hash should: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-08-10 17:39:29
|
Revision: 6651 http://jython.svn.sourceforge.net/jython/?rev=6651&view=rev Author: fwierzbicki Date: 2009-08-10 17:39:21 +0000 (Mon, 10 Aug 2009) Log Message: ----------- Trivial reindents. Modified Paths: -------------- trunk/jython/Lib/test/test_builtin_jy.py trunk/jython/Lib/test/test_concat_jy.py trunk/jython/Lib/test/test_descr_jy.py trunk/jython/Lib/test/test_importhooks.py trunk/jython/Lib/test/test_java_subclasses.py trunk/jython/Lib/test/test_jser.py trunk/jython/Lib/test/test_pbcvm.py trunk/jython/Lib/test/test_re_jy.py trunk/jython/Lib/test/test_subclasses.py trunk/jython/Lib/test/test_sys_jy.py Modified: trunk/jython/Lib/test/test_builtin_jy.py =================================================================== --- trunk/jython/Lib/test/test_builtin_jy.py 2009-08-10 17:35:54 UTC (rev 6650) +++ trunk/jython/Lib/test/test_builtin_jy.py 2009-08-10 17:39:21 UTC (rev 6651) @@ -7,7 +7,7 @@ from codecs import BOM_UTF8 class BuiltinTest(unittest.TestCase): - + def test_in_sys_modules(self): self.assert_("__builtin__" in sys.modules, "__builtin__ not found in sys.modules") @@ -79,7 +79,7 @@ def test_unbound(self): "Unbound methods indicated properly in repr" class Foo: - def bar(s): + def bar(s): pass self.failUnless(repr(Foo.bar).startswith('<unbound method')) @@ -210,8 +210,8 @@ self.assertEqual(eval('locals()', g, d), d) # Verify locals stores (used by list comps) - eval('[locals() for i in (2,3)]', g, d) - eval('[locals() for i in (2,3)]', g, UserDict.UserDict()) + eval('[locals() for i in (2,3)]', g, d) + eval('[locals() for i in (2,3)]', g, UserDict.UserDict()) class SpreadSheet: "Sample application showing nested, calculated lookups." Modified: trunk/jython/Lib/test/test_concat_jy.py =================================================================== --- trunk/jython/Lib/test/test_concat_jy.py 2009-08-10 17:35:54 UTC (rev 6650) +++ trunk/jython/Lib/test/test_concat_jy.py 2009-08-10 17:39:21 UTC (rev 6651) @@ -83,8 +83,8 @@ def test_main(): - test.test_support.run_unittest(StrUnicodeConcatTestCase, - StrUnicodeConcatOverridesTestCase) + test.test_support.run_unittest(StrUnicodeConcatTestCase, + StrUnicodeConcatOverridesTestCase) if __name__ == "__main__": - test_main() + test_main() Modified: trunk/jython/Lib/test/test_descr_jy.py =================================================================== --- trunk/jython/Lib/test/test_descr_jy.py 2009-08-10 17:35:54 UTC (rev 6650) +++ trunk/jython/Lib/test/test_descr_jy.py 2009-08-10 17:39:21 UTC (rev 6651) @@ -230,7 +230,7 @@ pass class Bar(object): def __radd__(self, other): - return 3 + return 3 self.assertEqual(Foo() + Bar(), 3) def test_int_mul(self): Modified: trunk/jython/Lib/test/test_importhooks.py =================================================================== --- trunk/jython/Lib/test/test_importhooks.py 2009-08-10 17:35:54 UTC (rev 6650) +++ trunk/jython/Lib/test/test_importhooks.py 2009-08-10 17:39:21 UTC (rev 6651) @@ -212,4 +212,3 @@ if __name__ == "__main__": test_main() - Modified: trunk/jython/Lib/test/test_java_subclasses.py =================================================================== --- trunk/jython/Lib/test/test_java_subclasses.py 2009-08-10 17:35:54 UTC (rev 6650) +++ trunk/jython/Lib/test/test_java_subclasses.py 2009-08-10 17:39:21 UTC (rev 6651) @@ -45,7 +45,7 @@ c = ComparableRunner() c.compareTo(None) c.run() - self.assertEquals(calls, ["ComparableRunner.compareTo", "Runner.run"]) + self.assertEquals(calls, ["ComparableRunner.compareTo", "Runner.run"]) class TableModelTest(unittest.TestCase): def test_class_coercion(self): @@ -56,19 +56,19 @@ def getColumnCount(self): return len(self.columnNames) - + def getRowCount(self): return len(self.data) - + def getColumnName(self, col): return self.columnNames[col] def getValueAt(self, row, col): return self.data[row][col] - + def getColumnClass(self, c): return Object.getClass(self.getValueAt(0, c)) - + def isCellEditable(self, row, col): return col >= 2 @@ -127,13 +127,13 @@ def method(self): return "SubDateMethod" - def toString(self): + def toString(self): s = Date.toString(self) return 'SubDate -> Date' class SubSubDate(SubDate, Runnable): def toString(self): - return 'SubSubDate -> ' + SubDate.toString(self) + return 'SubSubDate -> ' + SubDate.toString(self) self.assertEquals("SubDate -> Date", SubDate().toString()) self.assertEquals("SubSubDate -> SubDate -> Date", SubSubDate().toString()) @@ -175,7 +175,7 @@ class A(Component): pass A() - + def test_return_proxy(self): "Jython proxies properly return back from Java code" class FooVector(Vector): @@ -256,7 +256,7 @@ class AbstractOnSyspathTest(unittest.TestCase): '''Subclasses an abstract class that isn't on the startup classpath. - + Checks for http://jython.org/bugs/1861985 ''' def setUp(self): @@ -272,7 +272,7 @@ def test_can_subclass_abstract(self): import Abstract - + class A(Abstract): def method(self): pass @@ -297,7 +297,7 @@ """.decode('base64').decode('zlib') class ContextClassloaderTest(unittest.TestCase): '''Classes on the context classloader should be importable and subclassable. - + http://bugs.jython.org/issue1216''' def setUp(self): self.orig_context = Thread.currentThread().contextClassLoader @@ -360,7 +360,7 @@ import static_proxy # Use the existing environment with the proxy dir added on the classpath - env = dict(os.environ) + env = dict(os.environ) env["CLASSPATH"] = sys.javaproxy_dir script = test_support.findfile("import_as_java_class.py") self.assertEquals(subprocess.call([sys.executable, "-J-Dpython.cachedir.skip=true", Modified: trunk/jython/Lib/test/test_jser.py =================================================================== --- trunk/jython/Lib/test/test_jser.py 2009-08-10 17:35:54 UTC (rev 6650) +++ trunk/jython/Lib/test/test_jser.py 2009-08-10 17:39:21 UTC (rev 6651) @@ -8,8 +8,8 @@ object1 = 42 object2 = ['a', 1, 1.0] class Foo: - def bar(self): - return 'bar' + def bar(self): + return 'bar' object3 = Foo() object3.baz = 99 Modified: trunk/jython/Lib/test/test_pbcvm.py =================================================================== --- trunk/jython/Lib/test/test_pbcvm.py 2009-08-10 17:35:54 UTC (rev 6650) +++ trunk/jython/Lib/test/test_pbcvm.py 2009-08-10 17:39:21 UTC (rev 6651) @@ -49,7 +49,7 @@ def test_regrtest_pyc(self): for test in ( # change the names a bit so we don't have to worry about module unloading or spawning a separate JVM - # however, this testing approach too limits the tests that can be run, so we should rewrite to + # however, this testing approach too limits the tests that can be run, so we should rewrite to # use subprocess asap 'test_types_pyc', 'test_exceptions_pyc'): @@ -61,9 +61,9 @@ # typical unsafe ops we have to do in testing... test_support.verbose = self.old_verbosity sys.path.pop(0) - sys.meta_path.pop(0) - + sys.meta_path.pop(0) + def test_main(): test_support.run_unittest(PyBytecodeTest, AdhocRegrtest) Modified: trunk/jython/Lib/test/test_re_jy.py =================================================================== --- trunk/jython/Lib/test/test_re_jy.py 2009-08-10 17:35:54 UTC (rev 6650) +++ trunk/jython/Lib/test/test_re_jy.py 2009-08-10 17:39:21 UTC (rev 6651) @@ -25,14 +25,14 @@ result = re.sub('bar', 'baz', Foo2('bar')) self.assertEqual(result, Foo2('baz')) self.assert_(isinstance(result, Foo2)) - + def test_unkown_groupname(self): self.assertRaises(IndexError, re.match("(?P<int>\d+)\.(\d*)", '3.14').group, "misspelled") def test_main(): - test.test_support.run_unittest(ReTest) + test.test_support.run_unittest(ReTest) if __name__ == "__main__": - test_main() + test_main() Modified: trunk/jython/Lib/test/test_subclasses.py =================================================================== --- trunk/jython/Lib/test/test_subclasses.py 2009-08-10 17:35:54 UTC (rev 6650) +++ trunk/jython/Lib/test/test_subclasses.py 2009-08-10 17:39:21 UTC (rev 6651) @@ -1,7 +1,7 @@ from test import test_support import unittest import pickle - + #myint and its test taken from pickletester, the other "my" classes and tests # are based on it. class myint(int): @@ -82,7 +82,7 @@ self.assertEqual(Spam(), 0L) self.assertEqual(str(Spam()), "hi") - + def test_tuple(self): class Spam(tuple): def __str__(self): @@ -181,7 +181,7 @@ s = pickle.dumps(picklee) y = pickle.loads(s) self.assertEqual(picklee, y) - + def test_pickle_builtins(self): #ignores cPickle for now. Modified: trunk/jython/Lib/test/test_sys_jy.py =================================================================== --- trunk/jython/Lib/test/test_sys_jy.py 2009-08-10 17:35:54 UTC (rev 6650) +++ trunk/jython/Lib/test/test_sys_jy.py 2009-08-10 17:39:21 UTC (rev 6651) @@ -75,12 +75,12 @@ from org.python.core import Py from org.python.util import PythonInterpreter from org.python.core import PySystemState - + ps = PySystemState() pi = PythonInterpreter({}, ps) if not sharing: ps.shadow() - ps.builtins = ps.builtins.copy() + ps.builtins = ps.builtins.copy() pi.exec(function.func_code) import threading @@ -94,7 +94,7 @@ import test.sys_jy_test_module # used as a probe # can't use 'foo', test_with wants to have that undefined - sys.builtins['test_sys_jy_foo'] = 42 + sys.builtins['test_sys_jy_foo'] = 42 def set_shadow(): @@ -127,8 +127,8 @@ def test_sys_modules_per_instance(self): import sys self.assertTrue('sys_jy_test_module' not in sys.modules, "sys.modules should be per PySystemState instance") - + def test_main(): test.test_support.run_unittest(SysTest, ShadowingTest) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-08-10 17:58:24
|
Revision: 6652 http://jython.svn.sourceforge.net/jython/?rev=6652&view=rev Author: fwierzbicki Date: 2009-08-10 17:58:16 +0000 (Mon, 10 Aug 2009) Log Message: ----------- Reindents. Modified Paths: -------------- trunk/jython/Lib/test/anygui.py trunk/jython/Lib/test/jser2_classes.py trunk/jython/Lib/test/test_cmath_jy.py trunk/jython/Lib/test/test_codeop_jy.py trunk/jython/Lib/test/test_import_jy.py trunk/jython/Lib/test/test_java_integration.py trunk/jython/Lib/test/test_module.py trunk/jython/Lib/test/test_set_jy.py trunk/jython/Lib/test/test_xml_etree_jy.py trunk/jython/Lib/test/test_zipimport_jy.py Modified: trunk/jython/Lib/test/anygui.py =================================================================== --- trunk/jython/Lib/test/anygui.py 2009-08-10 17:39:21 UTC (rev 6651) +++ trunk/jython/Lib/test/anygui.py 2009-08-10 17:58:16 UTC (rev 6652) @@ -27,7 +27,7 @@ candidates = wishlist + candidates for name in candidates: - backend = self.__try_to_get('%sgui' % name) + backend = self.__try_to_get('%sgui' % name) if not backend: raise Exception, 'not able to import any GUI backends' self.__backend = backend Modified: trunk/jython/Lib/test/jser2_classes.py =================================================================== --- trunk/jython/Lib/test/jser2_classes.py 2009-08-10 17:39:21 UTC (rev 6651) +++ trunk/jython/Lib/test/jser2_classes.py 2009-08-10 17:58:16 UTC (rev 6652) @@ -45,4 +45,3 @@ self.__dict__ == other.__dict__) def __ne__(self, other): return not (self == other) - Modified: trunk/jython/Lib/test/test_cmath_jy.py =================================================================== --- trunk/jython/Lib/test/test_cmath_jy.py 2009-08-10 17:39:21 UTC (rev 6651) +++ trunk/jython/Lib/test/test_cmath_jy.py 2009-08-10 17:58:16 UTC (rev 6652) @@ -20,55 +20,55 @@ unittest.TestCase.assertAlmostEqual(self, x.imag, y.imag, places, msg) def test_acos(self): - self.assertAlmostEqual(complex(0.936812, -2.30551), + self.assertAlmostEqual(complex(0.936812, -2.30551), cmath.acos(complex(3, 4))) - + def test_acosh(self): - self.assertAlmostEqual(complex(2.30551, 0.93681), + self.assertAlmostEqual(complex(2.30551, 0.93681), cmath.acosh(complex(3, 4))) def test_asin(self): - self.assertAlmostEqual(complex(0.633984, 2.30551), + self.assertAlmostEqual(complex(0.633984, 2.30551), cmath.asin(complex(3, 4))) def test_asinh(self): - self.assertAlmostEqual(complex(2.29991, 0.917617), + self.assertAlmostEqual(complex(2.29991, 0.917617), cmath.asinh(complex(3, 4))) def test_atan(self): - self.assertAlmostEqual(complex(1.44831, 0.158997), + self.assertAlmostEqual(complex(1.44831, 0.158997), cmath.atan(complex(3, 4))) def test_atanh(self): - self.assertAlmostEqual(complex(0.11750, 1.40992), + self.assertAlmostEqual(complex(0.11750, 1.40992), cmath.atanh(complex(3, 4))) def test_cos(self): - self.assertAlmostEqual(complex(-27.03495, -3.851153), + self.assertAlmostEqual(complex(-27.03495, -3.851153), cmath.cos(complex(3, 4))) def test_cosh(self): - self.assertAlmostEqual(complex(-6.58066, -7.58155), + self.assertAlmostEqual(complex(-6.58066, -7.58155), cmath.cosh(complex(3, 4))) def test_exp(self): - self.assertAlmostEqual(complex(-13.12878, -15.20078), + self.assertAlmostEqual(complex(-13.12878, -15.20078), cmath.exp(complex(3, 4))) def test_log(self): - self.assertAlmostEqual(complex(1.60944, 0.927295), + self.assertAlmostEqual(complex(1.60944, 0.927295), cmath.log(complex(3, 4))) def test_log10(self): - self.assertAlmostEqual(complex(0.69897, 0.40272), + self.assertAlmostEqual(complex(0.69897, 0.40272), cmath.log10(complex(3, 4))) def test_sin(self): - self.assertAlmostEqual(complex(3.853738, -27.01681), + self.assertAlmostEqual(complex(3.853738, -27.01681), cmath.sin(complex(3, 4))) def test_sinh(self): - self.assertAlmostEqual(complex(-6.54812, -7.61923), + self.assertAlmostEqual(complex(-6.54812, -7.61923), cmath.sinh(complex(3, 4))) def test_sqrt_real_positive(self): @@ -78,7 +78,7 @@ def test_sqrt_real_zero(self): self.assertAlmostEqual(complex(1.41421, 1.41421), cmath.sqrt(complex(0, 4))) - + def test_sqrt_real_negative(self): self.assertAlmostEqual(complex(1, 2), cmath.sqrt(complex(-3, 4))) @@ -92,11 +92,11 @@ cmath.sqrt(complex(-3, -4))) def test_tan(self): - self.assertAlmostEqual(complex(-0.000187346, 0.999356), + self.assertAlmostEqual(complex(-0.000187346, 0.999356), cmath.tan(complex(3, 4))) def test_tanh(self): - self.assertAlmostEqual(complex(1.00071, 0.00490826), + self.assertAlmostEqual(complex(1.00071, 0.00490826), cmath.tanh(complex(3, 4))) def test_main(): @@ -104,6 +104,3 @@ if __name__ == "__main__": test_main() - - - Modified: trunk/jython/Lib/test/test_codeop_jy.py =================================================================== --- trunk/jython/Lib/test/test_codeop_jy.py 2009-08-10 17:39:21 UTC (rev 6651) +++ trunk/jython/Lib/test/test_codeop_jy.py 2009-08-10 17:58:16 UTC (rev 6652) @@ -16,14 +16,14 @@ '''succeed iff str is a valid piece of code''' code = compile_(str, "<input>", symbol) if values: - d = {} + d = {} exec code in d self.assertEquals(d,values) elif value is not None: self.assertEquals(eval(code,self.eval_d),value) else: self.assert_(code) - + def assertInvalid(self, str, symbol='single', is_syntax=1): '''succeed iff str is the start of an invalid piece of code''' try: @@ -58,7 +58,7 @@ # can be deleted. def test_invalid(self): ai = self.assertInvalid - + ai("del 1") ai("del ()") ai("del (1,)") Modified: trunk/jython/Lib/test/test_import_jy.py =================================================================== --- trunk/jython/Lib/test/test_import_jy.py 2009-08-10 17:39:21 UTC (rev 6651) +++ trunk/jython/Lib/test/test_import_jy.py 2009-08-10 17:58:16 UTC (rev 6652) @@ -181,7 +181,7 @@ module = os.path.basename(sym) module_obj = __import__(module) self.assertEquals(module_obj.test, 'imported') - + finally: shutil.rmtree(test_support.TESTFN) test_support.unlink(sym) Modified: trunk/jython/Lib/test/test_java_integration.py =================================================================== --- trunk/jython/Lib/test/test_java_integration.py 2009-08-10 17:39:21 UTC (rev 6651) +++ trunk/jython/Lib/test/test_java_integration.py 2009-08-10 17:58:16 UTC (rev 6652) @@ -4,7 +4,7 @@ import subprocess import sys import re - + from test import test_support from java.lang import (ClassCastException, ExceptionInInitializerError, String, Runnable, System, @@ -62,7 +62,7 @@ self.assertEquals(1, len(called)) m.fireComponentHidden(ComponentEvent(Container(), 0)) self.assertEquals(2, len(called)) - + def test_bean_interface(self): b = BeanImplementation() self.assertEquals("name", b.getName()) @@ -111,7 +111,7 @@ f = open(test_support.TESTFN) self.assertEquals('hello', f.read()) f.close() - + class IOTest(unittest.TestCase): def test_io_errors(self): "Check that IOException isn't mangled into an IOError" @@ -132,11 +132,11 @@ def test_system_in(self): s = System.in self.assert_("java.io.BufferedInputStream" in str(s)) - + def test_runtime_exec(self): e = Runtime.getRuntime().exec self.assert_(re.search("method .*exec", str(e)) is not None) - + def test_byte_class(self): b = Byte(10) self.assert_("java.lang.Byte" in str(b.class)) @@ -183,7 +183,7 @@ def test_in(self): self.assertEquals(self.kws.in(), "in") - + def test_exec(self): self.assertEquals(self.kws.exec(), "exec") @@ -284,7 +284,7 @@ def test_static_fields(self): self.assertEquals(Color(255, 0, 0), Color.RED) - # The bean accessor for getRed should be active on instances, but the static field red + # The bean accessor for getRed should be active on instances, but the static field red # should be visible on the class self.assertEquals(255, Color.red.red) self.assertEquals(Color(0, 0, 255), Color.blue) @@ -416,7 +416,7 @@ self.assertTrue(not x.equals(z)) self.assertNotEquals(x, z) self.assertTrue(not (x == z)) - + class SecurityManagerTest(unittest.TestCase): def test_nonexistent_import_with_security(self): script = test_support.findfile("import_nonexistent.py") @@ -452,13 +452,13 @@ self.assertEquals(7, m.held["initial"], "Existing fields should still be accessible") self.assertEquals(7, m.initial) self.assertEquals(None, m.nonexistent, "Nonexistent fields should be passed on to the Map") - - def test_adding_on_interface(self): + + def test_adding_on_interface(self): GetitemAdder.addPredefined() class UsesInterfaceMethod(FirstPredefinedGetitem): pass self.assertEquals("key", UsesInterfaceMethod()["key"]) - + def test_add_on_mro_conflict(self): """Adding same-named methods to Java classes with MRO conflicts produces TypeError""" GetitemAdder.addPredefined() @@ -479,8 +479,8 @@ self.assertEqual(date_list, unserializer.readObject()) def test_main(): - test_support.run_unittest(InstantiationTest, - BeanTest, + test_support.run_unittest(InstantiationTest, + BeanTest, SysIntegrationTest, IOTest, JavaReservedNamesTest, Modified: trunk/jython/Lib/test/test_module.py =================================================================== --- trunk/jython/Lib/test/test_module.py 2009-08-10 17:39:21 UTC (rev 6651) +++ trunk/jython/Lib/test/test_module.py 2009-08-10 17:58:16 UTC (rev 6652) @@ -12,7 +12,7 @@ pass else: raise TestFailed, "__name__ = %s" % repr(s) -# __doc__ is None by default in CPython but not in Jython. +# __doc__ is None by default in CPython but not in Jython. # We're not worrying about that now. #vereq(foo.__doc__, module.__doc__) Modified: trunk/jython/Lib/test/test_set_jy.py =================================================================== --- trunk/jython/Lib/test/test_set_jy.py 2009-08-10 17:39:21 UTC (rev 6651) +++ trunk/jython/Lib/test/test_set_jy.py 2009-08-10 17:58:16 UTC (rev 6652) @@ -20,7 +20,7 @@ self.assertEqual(s & foo, 'rand') self.assertEqual(s ^ foo, 'rxor') - + class SetInJavaTestCase(unittest.TestCase): """Tests for derived dict behaviour""" Modified: trunk/jython/Lib/test/test_xml_etree_jy.py =================================================================== --- trunk/jython/Lib/test/test_xml_etree_jy.py 2009-08-10 17:39:21 UTC (rev 6651) +++ trunk/jython/Lib/test/test_xml_etree_jy.py 2009-08-10 17:58:16 UTC (rev 6652) @@ -110,7 +110,7 @@ >>> parser = expat.ParserCreate(namespace_separator='!') >>> HANDLER_NAMES = [ ... 'StartElementHandler', 'EndElementHandler', - ... 'CharacterDataHandler', + ... 'CharacterDataHandler', ... 'ProcessingInstructionHandler', ... 'UnparsedEntityDeclHandler', 'NotationDeclHandler', ... 'StartNamespaceDeclHandler', 'EndNamespaceDeclHandler', @@ -451,9 +451,9 @@ def test_entity(): """ - + TODO: need a fallback for entity-resolver so that empty source is returned. - + >>> xml = ''' <!DOCTYPE doc SYSTEM "external.dtd" [ ... <!ENTITY ext-entity SYSTEM "external-entity"> ... ]> Modified: trunk/jython/Lib/test/test_zipimport_jy.py =================================================================== --- trunk/jython/Lib/test/test_zipimport_jy.py 2009-08-10 17:39:21 UTC (rev 6651) +++ trunk/jython/Lib/test/test_zipimport_jy.py 2009-08-10 17:58:16 UTC (rev 6652) @@ -27,5 +27,3 @@ if __name__ == "__main__": test_main() - - This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-08-10 18:15:34
|
Revision: 6653 http://jython.svn.sourceforge.net/jython/?rev=6653&view=rev Author: fwierzbicki Date: 2009-08-10 18:15:24 +0000 (Mon, 10 Aug 2009) Log Message: ----------- Trivial reindents. Modified Paths: -------------- trunk/jython/Lib/test/test_SimpleXMLRPCServer.py trunk/jython/Lib/test/test_float_jy.py trunk/jython/Lib/test/test_joverload.py trunk/jython/Lib/test/test_list_jy.py trunk/jython/Lib/test/test_random.py trunk/jython/Lib/test/test_socket.py trunk/jython/Lib/test/test_thread_jy.py trunk/jython/Lib/test/test_trace_threaded.py trunk/jython/Lib/test/test_weakref.py Modified: trunk/jython/Lib/test/test_SimpleXMLRPCServer.py =================================================================== --- trunk/jython/Lib/test/test_SimpleXMLRPCServer.py 2009-08-10 17:58:16 UTC (rev 6652) +++ trunk/jython/Lib/test/test_SimpleXMLRPCServer.py 2009-08-10 18:15:24 UTC (rev 6653) @@ -14,9 +14,9 @@ class MyService: """This test class is going to be used to test an entire class being exposed via XML-RPC.""" - + def _dispatch(self, method, params): - """This method is called whenever a call is made to the + """This method is called whenever a call is made to the service.""" func = getattr(self, 'expose_' + method) return func(*params) @@ -37,7 +37,7 @@ self.server.allow_reuse_address = 1 self.server.handle_request() self.server.server_close() - + class SimpleXMLRPCServerTestCase(unittest.TestCase): """Test case for the Python SimpleXMLRPCServer module.""" def test_exposeLambda(self): Modified: trunk/jython/Lib/test/test_float_jy.py =================================================================== --- trunk/jython/Lib/test/test_float_jy.py 2009-08-10 17:58:16 UTC (rev 6652) +++ trunk/jython/Lib/test/test_float_jy.py 2009-08-10 18:15:24 UTC (rev 6653) @@ -101,7 +101,7 @@ def test_faux(self): class F(object): def __float__(self): - return 1.6 + return 1.6 self.assertEqual(math.cos(1.6), math.cos(F())) Modified: trunk/jython/Lib/test/test_joverload.py =================================================================== --- trunk/jython/Lib/test/test_joverload.py 2009-08-10 17:58:16 UTC (rev 6652) +++ trunk/jython/Lib/test/test_joverload.py 2009-08-10 18:15:24 UTC (rev 6653) @@ -12,7 +12,7 @@ def __init__(self,name,meths): self.reflfunc = PyReflectedFunction(meths) - + def __call__(self,inst,args): return self.reflfunc(inst,*args) @@ -21,8 +21,8 @@ names = [ m.name for m in meths] meth_dict = {} for name in names: - if name.startswith('ov_') and not meth_dict.has_key(name): - meth_dict[name] = envl_class(name,[ m for m in meths if m.name == name ]) + if name.startswith('ov_') and not meth_dict.has_key(name): + meth_dict[name] = envl_class(name,[ m for m in meths if m.name == name ]) return meth_dict from javatests import JOverload @@ -58,7 +58,7 @@ (java.io.Serializable) (java.io.Serializable) (java.io.Serializable) -(java.lang.Object) +(java.lang.Object) """) def test_scal_string(self): @@ -115,7 +115,7 @@ (java.io.Serializable) (java.io.Serializable) (java.io.Serializable) -(java.lang.Object) +(java.lang.Object) """) @@ -132,5 +132,3 @@ unittest.main() else: test_support.run_unittest(OverloadedDispatchTests) - - Modified: trunk/jython/Lib/test/test_list_jy.py =================================================================== --- trunk/jython/Lib/test/test_list_jy.py 2009-08-10 17:58:16 UTC (rev 6652) +++ trunk/jython/Lib/test/test_list_jy.py 2009-08-10 18:15:24 UTC (rev 6653) @@ -53,7 +53,7 @@ self.assertEqual([(1,), [1]].count([1]), 1) # http://bugs.jython.org/issue1317 class ThreadSafetyTestCase(unittest.TestCase): - + def run_threads(self, f, num=10): threads = [] for i in xrange(num): Modified: trunk/jython/Lib/test/test_random.py =================================================================== --- trunk/jython/Lib/test/test_random.py 2009-08-10 17:58:16 UTC (rev 6652) +++ trunk/jython/Lib/test/test_random.py 2009-08-10 18:15:24 UTC (rev 6653) @@ -532,7 +532,7 @@ if test_support.is_jython: del MersenneTwister_TestBasicOps.test_genrandbits - del MersenneTwister_TestBasicOps.test_referenceImplementation + del MersenneTwister_TestBasicOps.test_referenceImplementation del MersenneTwister_TestBasicOps.test_setstate_middle_arg del MersenneTwister_TestBasicOps.test_strong_reference_implementation Modified: trunk/jython/Lib/test/test_socket.py =================================================================== --- trunk/jython/Lib/test/test_socket.py 2009-08-10 17:58:16 UTC (rev 6652) +++ trunk/jython/Lib/test/test_socket.py 2009-08-10 18:15:24 UTC (rev 6653) @@ -819,12 +819,12 @@ def testBindSpecific(self): self.sock.bind( (self.HOST, self.PORT) ) # Use a specific port actual_port = self.sock.getsockname()[1] - self.failUnless(actual_port == self.PORT, - "Binding to specific port number should have returned same number: %d != %d" % (actual_port, self.PORT)) + self.failUnless(actual_port == self.PORT, + "Binding to specific port number should have returned same number: %d != %d" % (actual_port, self.PORT)) def testBindEphemeral(self): self.sock.bind( (self.HOST, 0) ) # let system choose a free port - self.failUnless(self.sock.getsockname()[1] != 0, "Binding to port zero should have allocated an ephemeral port number") + self.failUnless(self.sock.getsockname()[1] != 0, "Binding to port zero should have allocated an ephemeral port number") def testShutdown(self): self.sock.bind( (self.HOST, self.PORT) ) @@ -1003,7 +1003,7 @@ # AMAK: 20070311 # Introduced a new test for non-blocking connect # Renamed old testConnect to testBlockingConnect - # + # def testBlockingConnect(self): # Testing blocking connect @@ -1032,7 +1032,7 @@ # # AMAK: 20070518 # Introduced a new test for connect with bind to specific local address - # + # def testConnectWithLocalBind(self): # Test blocking connect @@ -1387,7 +1387,7 @@ self.failUnlessRaises(socket.timeout, raise_timeout, "TCP socket recv failed to generate a timeout exception (TCP)") - # Disable this test, but leave it present for documentation purposes + # Disable this test, but leave it present for documentation purposes # socket timeouts only work for read and accept, not for write # http://java.sun.com/j2se/1.4.2/docs/api/java/net/SocketTimeoutException.html def estSendTimeout(self): @@ -1683,11 +1683,11 @@ def test_main(): tests = [ - GeneralModuleTests, + GeneralModuleTests, TestSupportedOptions, TestUnsupportedOptions, - BasicTCPTest, - TCPServerTimeoutTest, + BasicTCPTest, + TCPServerTimeoutTest, TCPClientTimeoutTest, TestExceptions, TestInvalidUsage, Modified: trunk/jython/Lib/test/test_thread_jy.py =================================================================== --- trunk/jython/Lib/test/test_thread_jy.py 2009-08-10 17:58:16 UTC (rev 6652) +++ trunk/jython/Lib/test/test_thread_jy.py 2009-08-10 18:15:24 UTC (rev 6653) @@ -6,11 +6,11 @@ from java.util.concurrent import CountDownLatch class AllocateLockTest(unittest.TestCase): - + def test_lock_type(self): "thread.LockType should exist" t = thread.LockType - self.assertEquals(t, type(thread.allocate_lock()), + self.assertEquals(t, type(thread.allocate_lock()), "thread.LockType has wrong value") class SynchronizeTest(unittest.TestCase): Modified: trunk/jython/Lib/test/test_trace_threaded.py =================================================================== --- trunk/jython/Lib/test/test_trace_threaded.py 2009-08-10 17:58:16 UTC (rev 6652) +++ trunk/jython/Lib/test/test_trace_threaded.py 2009-08-10 18:15:24 UTC (rev 6653) @@ -8,47 +8,47 @@ class UntracedThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) - + def run(self): sys.settrace(None) for i in range(10): self.untracedcall() - + def untracedcall(self): pass - + class TracedThread(threading.Thread): def __init__(self, on_trace): threading.Thread.__init__(self) self.on_trace = on_trace - + def trace(self, frame, event, arg): self.on_trace(frame.f_code.co_name) - + def tracedcall(self): pass - + def run(self): sys.settrace(self.trace) for i in range(10): self.tracedcall() - + class TracePerThreadTest(unittest.TestCase): def testTracePerThread(self): called = [] def ontrace(co_name): called.append(str(co_name)) - + untraced = UntracedThread() traced = TracedThread(ontrace) untraced.start() traced.start() untraced.join() traced.join() - + self.assertEquals(10, called.count('tracedcall'), "10 tracedcall should be in %s" % called) - self.assert_('untracedcall' not in called, + self.assert_('untracedcall' not in called, "untracedcall shouldn't be in %s" % called) def test_main(): Modified: trunk/jython/Lib/test/test_weakref.py =================================================================== --- trunk/jython/Lib/test/test_weakref.py 2009-08-10 17:58:16 UTC (rev 6652) +++ trunk/jython/Lib/test/test_weakref.py 2009-08-10 18:15:24 UTC (rev 6653) @@ -659,7 +659,7 @@ weakref.ref(referenced, callback) finally: - # XXX: threshold not applicable to Jython + # XXX: threshold not applicable to Jython if not test_support.is_jython: gc.set_threshold(*thresholds) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-08-10 18:30:25
|
Revision: 6654 http://jython.svn.sourceforge.net/jython/?rev=6654&view=rev Author: fwierzbicki Date: 2009-08-10 18:30:18 +0000 (Mon, 10 Aug 2009) Log Message: ----------- Merge test_bugfixes into test_exceptions, since test_bugfixes is a poor name and it was testing exception behaviors. Modified Paths: -------------- trunk/jython/Lib/test/test_exceptions_jy.py Removed Paths: ------------- trunk/jython/Lib/test/test_bugfixes.py Deleted: trunk/jython/Lib/test/test_bugfixes.py =================================================================== --- trunk/jython/Lib/test/test_bugfixes.py 2009-08-10 18:15:24 UTC (rev 6653) +++ trunk/jython/Lib/test/test_bugfixes.py 2009-08-10 18:30:18 UTC (rev 6654) @@ -1,31 +0,0 @@ - -import unittest -from test_support import run_suite - -class C: - def __str__(self): - raise Exception("E") - def __repr__(self): - raise Exception("S") - -class ExceptionHandling(unittest.TestCase): - def testBugFix1149372(self): - try: - c = C() - str(c) - except Exception, e: - assert e.args[0] == "E" - return - unittest.fail("if __str__ raises an exception, re-raise") - -def test_main(): - test_suite = unittest.TestSuite() - test_loader = unittest.TestLoader() - def suite_add(case): - test_suite.addTest(test_loader.loadTestsFromTestCase(case)) - suite_add(ExceptionHandling) - run_suite(test_suite) - -if __name__ == "__main__": - test_main() - Modified: trunk/jython/Lib/test/test_exceptions_jy.py =================================================================== --- trunk/jython/Lib/test/test_exceptions_jy.py 2009-08-10 18:15:24 UTC (rev 6653) +++ trunk/jython/Lib/test/test_exceptions_jy.py 2009-08-10 18:30:18 UTC (rev 6654) @@ -5,6 +5,12 @@ from test import test_support import unittest +class C: + def __str__(self): + raise Exception("E") + def __repr__(self): + raise Exception("S") + class ExceptionsTestCase(unittest.TestCase): def test_keyerror_str(self): @@ -26,6 +32,16 @@ self.assertEquals(r, "dummy") + def testBugFix1149372(self): + try: + c = C() + str(c) + except Exception, e: + assert e.args[0] == "E" + return + unittest.fail("if __str__ raises an exception, re-raise") + + def test_main(): test_support.run_unittest(ExceptionsTestCase) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-08-10 18:57:04
|
Revision: 6655 http://jython.svn.sourceforge.net/jython/?rev=6655&view=rev Author: fwierzbicki Date: 2009-08-10 18:56:57 +0000 (Mon, 10 Aug 2009) Log Message: ----------- Reindent. Modified Paths: -------------- trunk/jython/Lib/test/test__rawffi.py trunk/jython/Lib/test/test_array_jy.py trunk/jython/Lib/test/test_coerce_jy.py trunk/jython/Lib/test/test_func_syntax_jy.py trunk/jython/Lib/test/test_grammar_jy.py trunk/jython/Lib/test/test_java_visibility.py trunk/jython/Lib/test/test_sort_jy.py trunk/jython/Lib/test/test_str2unicode.py trunk/jython/Lib/test/test_stringmap.py trunk/jython/Lib/test/test_with.py Modified: trunk/jython/Lib/test/test__rawffi.py =================================================================== --- trunk/jython/Lib/test/test__rawffi.py 2009-08-10 18:30:18 UTC (rev 6654) +++ trunk/jython/Lib/test/test__rawffi.py 2009-08-10 18:56:57 UTC (rev 6655) @@ -3,7 +3,7 @@ # xxx - forces a skip in the case we haven't built ctypes_test module in ant (which is not yet a task as of now) -try: +try: import _rawffi _rawffi.CDLL("ctypes_test") except: Modified: trunk/jython/Lib/test/test_array_jy.py =================================================================== --- trunk/jython/Lib/test/test_array_jy.py 2009-08-10 18:30:18 UTC (rev 6654) +++ trunk/jython/Lib/test/test_array_jy.py 2009-08-10 18:56:57 UTC (rev 6655) @@ -24,7 +24,7 @@ jStringArr = array(String, [String("a"), String("b"), String("c")]) self.assert_( Arrays.equals(jStringArr.typecode, 'java.lang.String'), - "String array typecode of wrong type, expected %s, found %s" % + "String array typecode of wrong type, expected %s, found %s" % (jStringArr.typecode, str(String))) self.assertEqual(zeros(String, 5), Array.newInstance(String, 5)) Modified: trunk/jython/Lib/test/test_coerce_jy.py =================================================================== --- trunk/jython/Lib/test/test_coerce_jy.py 2009-08-10 18:30:18 UTC (rev 6654) +++ trunk/jython/Lib/test/test_coerce_jy.py 2009-08-10 18:56:57 UTC (rev 6655) @@ -25,4 +25,3 @@ if __name__ == "__main__": test_main() - Modified: trunk/jython/Lib/test/test_func_syntax_jy.py =================================================================== --- trunk/jython/Lib/test/test_func_syntax_jy.py 2009-08-10 18:30:18 UTC (rev 6654) +++ trunk/jython/Lib/test/test_func_syntax_jy.py 2009-08-10 18:56:57 UTC (rev 6655) @@ -4,17 +4,17 @@ def parrot(**args): pass class FuncSyntaxTest(unittest.TestCase): - - def test_keywords_before_normal(self): - self.assertRaises(SyntaxError, eval, - "parrot(voltage=.5, \'dead\')") - def test_dup_keywords(self): - self.assertRaises(TypeError, eval, - "complex(imag=4, imag=2)") + def test_keywords_before_normal(self): + self.assertRaises(SyntaxError, eval, + "parrot(voltage=.5, \'dead\')") + def test_dup_keywords(self): + self.assertRaises(TypeError, eval, + "complex(imag=4, imag=2)") + def test_main(): - test.test_support.run_unittest(FuncSyntaxTest) + test.test_support.run_unittest(FuncSyntaxTest) if __name__ == "__main__": - test_main() + test_main() Modified: trunk/jython/Lib/test/test_grammar_jy.py =================================================================== --- trunk/jython/Lib/test/test_grammar_jy.py 2009-08-10 18:30:18 UTC (rev 6654) +++ trunk/jython/Lib/test/test_grammar_jy.py 2009-08-10 18:56:57 UTC (rev 6655) @@ -6,12 +6,12 @@ class GrammarTest(unittest.TestCase): def test_triple_quote_len(self): - s1 = r""" + s1 = r""" \""" 1.triple-quote \""" 2.triple-quote """ - s2 = r''' + s2 = r''' \""" 1.triple-quote \""" 2.triple-quote ''' Modified: trunk/jython/Lib/test/test_java_visibility.py =================================================================== --- trunk/jython/Lib/test/test_java_visibility.py 2009-08-10 18:30:18 UTC (rev 6654) +++ trunk/jython/Lib/test/test_java_visibility.py 2009-08-10 18:56:57 UTC (rev 6655) @@ -4,7 +4,7 @@ import sys from test import test_support from java.lang import Byte, Class, Integer -from java.util import ArrayList, Collections, HashMap, LinkedList, Observable, Observer +from java.util import ArrayList, Collections, HashMap, LinkedList, Observable, Observer from org.python.tests import (Coercions, HiddenSuper, InterfaceCombination, Invisible, Matryoshka, OnlySubclassable, OtherSubVisible, SomePyMethods, SubVisible, Visible, VisibleOverride) from org.python.tests import VisibilityResults as Results @@ -81,7 +81,7 @@ self.assertEquals(Results.OVERLOADED_EXTRA_ARG_PUBLIC_METHOD, v.visibleInstance('a', 'b')) self.assertEquals(Results.PUBLIC_STATIC_METHOD, Visible.visibleStatic(0)) - self.assertEquals(Results.OVERLOADED_PUBLIC_STATIC_METHOD, + self.assertEquals(Results.OVERLOADED_PUBLIC_STATIC_METHOD, v.visibleStatic('a')) self.assertEquals(Results.EXTRA_ARG_PUBLIC_STATIC_METHOD, v.visibleStatic(0, 'a')) @@ -103,11 +103,11 @@ self.assertEquals(Results.SUBCLASS_OVERRIDE, s.visibleInstance(3)) self.assertEquals(Results.SUBCLASS_OVERLOAD, s.visibleInstance(3.0, 'a')) self.assertEquals(Results.PACKAGE_METHOD, s.packageMethod()) - # Java methods don't allow direct calling of the superclass method, so it should + # Java methods don't allow direct calling of the superclass method, so it should # return the subclass value here. self.assertEquals(Results.SUBCLASS_OVERRIDE, Visible.visibleInstance(s, 3)) self.assertEquals(Results.PUBLIC_STATIC_FIELD, SubVisible.StaticInner.visibleStaticField) - + self.assertEquals(Results.VISIBLE_SHARED_NAME_FIELD, Visible.sharedNameField) self.assertEquals(Results.SUBVISIBLE_SHARED_NAME_FIELD, SubVisible.sharedNameField) self.assertEquals(Results.VISIBLE_SHARED_NAME_FIELD * 10, Visible().sharedNameField) @@ -129,7 +129,7 @@ "methods from IIFace should be visible on Implementation") self.assertEquals(InterfaceCombination.TWO_ARG_RESULT, i.getValue("one arg", "two arg"), "methods from Base should be visible on Implementation") - self.assertRaises(TypeError, i.getValue, "one arg", "two arg", "three arg", + self.assertRaises(TypeError, i.getValue, "one arg", "two arg", "three arg", "methods defined solely on Implementation shouldn't be visible") self.assertFalse(hasattr(i, "internalMethod"), "methods from private interfaces shouldn't be visible on a private class") Modified: trunk/jython/Lib/test/test_sort_jy.py =================================================================== --- trunk/jython/Lib/test/test_sort_jy.py 2009-08-10 18:30:18 UTC (rev 6654) +++ trunk/jython/Lib/test/test_sort_jy.py 2009-08-10 18:56:57 UTC (rev 6655) @@ -20,4 +20,4 @@ test_support.run_unittest(SortTest) if __name__ == "__main__": - test_main() + test_main() Modified: trunk/jython/Lib/test/test_str2unicode.py =================================================================== --- trunk/jython/Lib/test/test_str2unicode.py 2009-08-10 18:30:18 UTC (rev 6654) +++ trunk/jython/Lib/test/test_str2unicode.py 2009-08-10 18:56:57 UTC (rev 6655) @@ -19,7 +19,7 @@ self.assertEquals(unicode, type('%r %r' % (u'x', 'y'))) self.assertEquals(unicode, type('%(x)r' % {'x' : u'x'})) - def test_string_formatting_c(self): + def test_string_formatting_c(self): self.assertEquals(unicode, type('%c' % u'x')) self.assertEquals(unicode, type('%c %c' % (u'x', 'y'))) self.assertEquals(unicode, type('%(x)c' % {'x' : u'x'})) @@ -42,7 +42,7 @@ self.assertEquals(str, type('%r' % 'x')) self.assertEquals(str, type('%r %r' % ('x', 'y'))) self.assertEquals(str, type('%(x)r' % {'x' : 'x'})) - + def test_string_formatting_c(self): self.assertEquals(str, type('%c' % 'x')) self.assertEquals(str, type('%c %c' % ('x', 'y'))) Modified: trunk/jython/Lib/test/test_stringmap.py =================================================================== --- trunk/jython/Lib/test/test_stringmap.py 2009-08-10 18:30:18 UTC (rev 6654) +++ trunk/jython/Lib/test/test_stringmap.py 2009-08-10 18:56:57 UTC (rev 6655) @@ -12,7 +12,7 @@ class ClassDictTests(StringMapTest): """Check that class dicts conform to the mapping protocol""" - + def _empty_mapping(self): for key in SimpleClass.__dict__.copy(): SimpleClass.__dict__.pop(key) Modified: trunk/jython/Lib/test/test_with.py =================================================================== --- trunk/jython/Lib/test/test_with.py 2009-08-10 18:30:18 UTC (rev 6654) +++ trunk/jython/Lib/test/test_with.py 2009-08-10 18:56:57 UTC (rev 6655) @@ -704,14 +704,14 @@ NonLocalFlowControlTestCase, AssignmentTargetTestCase, ExitSwallowsExceptionTestCase, - ) + ) #XXX: punting NewKeywordsWarningTestCase at least for the # short term making "with" and "as" anything but true # keywords is not easy with the antlr parser though it is # probably doable. Just not a high priority compared to # other problems and in 2.6+ it is a non-problem since # these become true keywords in CPython. - # + # #NewKeywordsWarningTestCase) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-08-10 19:01:55
|
Revision: 6657 http://jython.svn.sourceforge.net/jython/?rev=6657&view=rev Author: fwierzbicki Date: 2009-08-10 19:01:48 +0000 (Mon, 10 Aug 2009) Log Message: ----------- Trivial reindents. Modified Paths: -------------- trunk/jython/Lib/test/test_bigmem.py trunk/jython/Lib/test/test_compile_jy.py trunk/jython/Lib/test/test_pythoninterpreter_jy.py trunk/jython/Lib/test/test_sax.py trunk/jython/Lib/test/test_sort.py trunk/jython/Lib/test/test_threading_jy.py trunk/jython/Lib/test/test_trace.py trunk/jython/Lib/test/test_unicode_jy.py trunk/jython/Lib/test/test_userdict.py Modified: trunk/jython/Lib/test/test_bigmem.py =================================================================== --- trunk/jython/Lib/test/test_bigmem.py 2009-08-10 18:58:58 UTC (rev 6656) +++ trunk/jython/Lib/test/test_bigmem.py 2009-08-10 19:01:48 UTC (rev 6657) @@ -519,7 +519,7 @@ # this might make sense for virtually managed collections, # but PyObjectArray is backed by PyObject[], so that's a hard # limitation of the JVM - + # self.assertRaises(IndexError, operator.getitem, s, len(s) + 1<<31) @bigmemtest(minsize=_2G, memuse=2) @@ -549,7 +549,7 @@ # changed for Jython because the hash code of a java.lang.String # of 0x00's is 0 regardless of size - + @bigmemtest(minsize=_2G + 10, memuse=1) def test_hash(self, size): # Not sure if we can do any meaningful tests here... Even if we Modified: trunk/jython/Lib/test/test_compile_jy.py =================================================================== --- trunk/jython/Lib/test/test_compile_jy.py 2009-08-10 18:58:58 UTC (rev 6656) +++ trunk/jython/Lib/test/test_compile_jy.py 2009-08-10 19:01:48 UTC (rev 6657) @@ -54,4 +54,4 @@ run_unittest(TestMtime) if __name__ == "__main__": - test_main() + test_main() Modified: trunk/jython/Lib/test/test_pythoninterpreter_jy.py =================================================================== --- trunk/jython/Lib/test/test_pythoninterpreter_jy.py 2009-08-10 18:58:58 UTC (rev 6656) +++ trunk/jython/Lib/test/test_pythoninterpreter_jy.py 2009-08-10 19:01:48 UTC (rev 6657) @@ -13,7 +13,7 @@ from org.python.core import Py from org.python.util import PythonInterpreter from org.python.core import PySystemState - + ps = PySystemState() pi = PythonInterpreter({}, ps) if locals: @@ -47,7 +47,7 @@ # Some language names from wikipedia u'Català · Česky · Dansk · Deutsch · English · Español · Esperanto · Français · Bahasa Indonesia · Italiano · Magyar · Nederlands · 日本語 · Norsk (bokmål) · Polski · Português · Русский · Română · Slovenčina · Suomi · Svenska · Türkçe · Українська · Volapük · 中文', ] - + def f(): global text for x in text: @@ -65,7 +65,7 @@ out = java.io.StringWriter() err = java.io.StringWriter() exec_code_in_pi(f, out, err) - self.assertEquals(u"42\n", out.toString()) + self.assertEquals(u"42\n", out.toString()) def test_more_output(self): def f(): Modified: trunk/jython/Lib/test/test_sax.py =================================================================== --- trunk/jython/Lib/test/test_sax.py 2009-08-10 18:58:58 UTC (rev 6656) +++ trunk/jython/Lib/test/test_sax.py 2009-08-10 19:01:48 UTC (rev 6657) @@ -157,7 +157,7 @@ def test_xmlgen_escaped_attr(): result = StringIO() gen = XMLGenerator(result) - + gen.startDocument() gen.startElement("doc", {"x": unicode("\\u3042", "unicode-escape")}) gen.endElement("doc") Modified: trunk/jython/Lib/test/test_sort.py =================================================================== --- trunk/jython/Lib/test/test_sort.py 2009-08-10 18:58:58 UTC (rev 6656) +++ trunk/jython/Lib/test/test_sort.py 2009-08-10 19:01:48 UTC (rev 6657) @@ -275,17 +275,17 @@ TestDecorateSortUndecorate, TestBugs, ) - + # In the following test cases, class obj, which has function that changes # the data upon which sort is invoked, is passed for "key" argument. - # It can not be checked if that function changes data as long as it is - # invoked(e.g. __del__ in SortKiller). so these are currently commented out. + # It can not be checked if that function changes data as long as it is + # invoked(e.g. __del__ in SortKiller). so these are currently commented out. del TestDecorateSortUndecorate.test_key_with_mutating_del del TestDecorateSortUndecorate.test_key_with_mutating_del_and_exception # test_support.run_unittest(*test_classes) - + # verify reference counting if verbose and hasattr(sys, "gettotalrefcount"): import gc Modified: trunk/jython/Lib/test/test_threading_jy.py =================================================================== --- trunk/jython/Lib/test/test_threading_jy.py 2009-08-10 18:58:58 UTC (rev 6656) +++ trunk/jython/Lib/test/test_threading_jy.py 2009-08-10 19:01:48 UTC (rev 6657) @@ -16,21 +16,21 @@ self.assertEqual(t.getName(), '1') t.setName(2) self.assertEqual(t.getName(), '2') - + # make sure activeCount() gets decremented (see issue 1348) def test_activeCount(self): - activeBefore = threading.activeCount() + activeBefore = threading.activeCount() activeCount = 10 for i in range(activeCount): - t = Thread(target=self._sleep, args=(i,)) - t.setDaemon(0) - t.start() + t = Thread(target=self._sleep, args=(i,)) + t.setDaemon(0) + t.start() polls = activeCount while activeCount > activeBefore and polls > 0: time.sleep(1) activeCount = threading.activeCount() polls -= 1 - self.assertTrue(activeCount <= activeBefore, 'activeCount should to be <= %s, instead of %s' % (activeBefore, activeCount)) + self.assertTrue(activeCount <= activeBefore, 'activeCount should to be <= %s, instead of %s' % (activeBefore, activeCount)) def _sleep(self, n): time.sleep(random.random()) Modified: trunk/jython/Lib/test/test_trace.py =================================================================== --- trunk/jython/Lib/test/test_trace.py 2009-08-10 18:58:58 UTC (rev 6656) +++ trunk/jython/Lib/test/test_trace.py 2009-08-10 19:01:48 UTC (rev 6657) @@ -740,10 +740,10 @@ tests.append(JumpTestCase) else: del TraceTestCase.test_02_arigo - del TraceTestCase.test_05_no_pop_tops - del TraceTestCase.test_07_raise + del TraceTestCase.test_05_no_pop_tops + del TraceTestCase.test_07_raise del TraceTestCase.test_09_settrace_and_raise - del TraceTestCase.test_10_ireturn + del TraceTestCase.test_10_ireturn del TraceTestCase.test_11_tightloop del TraceTestCase.test_12_tighterloop del TraceTestCase.test_13_genexp Modified: trunk/jython/Lib/test/test_unicode_jy.py =================================================================== --- trunk/jython/Lib/test/test_unicode_jy.py 2009-08-10 18:58:58 UTC (rev 6656) +++ trunk/jython/Lib/test/test_unicode_jy.py 2009-08-10 19:01:48 UTC (rev 6657) @@ -123,7 +123,7 @@ return f = open(test_support.TESTFN, "w") - self.assertRaises(UnicodeEncodeError, f, write, EURO_SIGN, + self.assertRaises(UnicodeEncodeError, f, write, EURO_SIGN, "Shouldn't be able to write out a Euro sign without first encoding") f.close() @@ -140,7 +140,7 @@ class UnicodeFormatTestCase(unittest.TestCase): - + def test_unicode_mapping(self): assertTrue = self.assertTrue class EnsureUnicode(dict): @@ -158,7 +158,7 @@ class UnicodeStdIOTestCase(unittest.TestCase): - + def setUp(self): self.stdout = sys.stdout Modified: trunk/jython/Lib/test/test_userdict.py =================================================================== --- trunk/jython/Lib/test/test_userdict.py 2009-08-10 18:58:58 UTC (rev 6656) +++ trunk/jython/Lib/test/test_userdict.py 2009-08-10 19:01:48 UTC (rev 6657) @@ -175,7 +175,7 @@ self.assertEqual(eval(`u2`), eval(`d2`)) # end zyasoft ~ - + # Test __cmp__ and __len__ all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2] for a in all: @@ -219,7 +219,7 @@ # zyasoft - changed the following three assertions to use sets # to remove order dependency - + # Test keys, items, values self.assertEqual(set(u2.keys()), set(d2.keys())) self.assertEqual(set(u2.items()), set(d2.items())) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-08-10 19:05:19
|
Revision: 6659 http://jython.svn.sourceforge.net/jython/?rev=6659&view=rev Author: fwierzbicki Date: 2009-08-10 19:05:11 +0000 (Mon, 10 Aug 2009) Log Message: ----------- Trivial reindents. Modified Paths: -------------- trunk/jython/Lib/test/test_builtin.py trunk/jython/Lib/test/test_codeop.py trunk/jython/Lib/test/test_javalist.py trunk/jython/Lib/test/test_re.py trunk/jython/Lib/test/test_sax_jy.py trunk/jython/Lib/test/test_subclasses_jy.py trunk/jython/Lib/test/test_threading.py Modified: trunk/jython/Lib/test/test_builtin.py =================================================================== --- trunk/jython/Lib/test/test_builtin.py 2009-08-10 19:04:35 UTC (rev 6658) +++ trunk/jython/Lib/test/test_builtin.py 2009-08-10 19:05:11 UTC (rev 6659) @@ -215,7 +215,7 @@ from UserList import UserList c = UserList(); c.append(c) self.assertEqual(cmp(a, b), 0) - self.assertEqual(cmp(b, c), 0) + self.assertEqual(cmp(b, c), 0) self.assertEqual(cmp(c, a), 0) self.assertEqual(cmp(a, c), 0) # okay, now break the cycles Modified: trunk/jython/Lib/test/test_codeop.py =================================================================== --- trunk/jython/Lib/test/test_codeop.py 2009-08-10 19:04:35 UTC (rev 6658) +++ trunk/jython/Lib/test/test_codeop.py 2009-08-10 19:05:11 UTC (rev 6659) @@ -126,7 +126,7 @@ #XXX: works in CPython if not is_jython: - av("@a.b.c\ndef f():\n pass\n") + av("@a.b.c\ndef f():\n pass\n") def test_incomplete(self): ai = self.assertIncomplete Modified: trunk/jython/Lib/test/test_javalist.py =================================================================== --- trunk/jython/Lib/test/test_javalist.py 2009-08-10 19:04:35 UTC (rev 6658) +++ trunk/jython/Lib/test/test_javalist.py 2009-08-10 19:05:11 UTC (rev 6659) @@ -1,35 +1,35 @@ from javatests import ListTest class PyListTest(ListTest): - - def __init__(self): - ListTest.__init__(self) - - def newInstance(self, coll): - if coll is None: - return list() - else: - return list(coll) - - def isReadOnly(self): - return False - + def __init__(self): + ListTest.__init__(self) + + def newInstance(self, coll): + if coll is None: + return list() + else: + return list(coll) + + def isReadOnly(self): + return False + + class PyTupleTest(ListTest): - - def __init__(self): - ListTest.__init__(self) - - def newInstance(self, coll): - if coll is None: - return tuple() - else: - return tuple(coll) - - def isReadOnly(self): - return True + def __init__(self): + ListTest.__init__(self) + def newInstance(self, coll): + if coll is None: + return tuple() + else: + return tuple(coll) + + def isReadOnly(self): + return True + + # these first two tests just verify that we have a good unit test print "ListTest.java driver (test_javalist.py)" print "running test on ArrayList" @@ -45,8 +45,8 @@ print "running test on PyListTest" plt = PyListTest() -plt.testAll() +plt.testAll() print "running test on PyTupleTest" ptt = PyTupleTest() -ptt.testAll() +ptt.testAll() Modified: trunk/jython/Lib/test/test_re.py =================================================================== --- trunk/jython/Lib/test/test_re.py 2009-08-10 19:04:35 UTC (rev 6658) +++ trunk/jython/Lib/test/test_re.py 2009-08-10 19:05:11 UTC (rev 6659) @@ -515,7 +515,7 @@ # non-simple '*?' still used to hit the recursion limit, before the # non-recursive scheme was implemented. - # does not apply for Jython, since we do not implement the + # does not apply for Jython, since we do not implement the # non-recursive scheme # self.assertEqual(re.search('(a|b)*?c', 10000*'ab'+'cd').end(0), 20001) Modified: trunk/jython/Lib/test/test_sax_jy.py =================================================================== --- trunk/jython/Lib/test/test_sax_jy.py 2009-08-10 19:04:35 UTC (rev 6658) +++ trunk/jython/Lib/test/test_sax_jy.py 2009-08-10 19:05:11 UTC (rev 6659) @@ -47,4 +47,3 @@ if __name__ == "__main__": test_main() - Modified: trunk/jython/Lib/test/test_subclasses_jy.py =================================================================== --- trunk/jython/Lib/test/test_subclasses_jy.py 2009-08-10 19:04:35 UTC (rev 6658) +++ trunk/jython/Lib/test/test_subclasses_jy.py 2009-08-10 19:05:11 UTC (rev 6659) @@ -2,17 +2,17 @@ import test.test_support class SubclassInstanceTest(unittest.TestCase): - - def test_subclass_int(self): - try: - class foo(12): pass - except TypeError: - pass - else: - self.fail("expected TypeError for subclassing an int instance") + def test_subclass_int(self): + try: + class foo(12): pass + except TypeError: + pass + else: + self.fail("expected TypeError for subclassing an int instance") + def test_main(): - test.test_support.run_unittest(SubclassInstanceTest) + test.test_support.run_unittest(SubclassInstanceTest) if __name__ == "__main__": - test_main() + test_main() Modified: trunk/jython/Lib/test/test_threading.py =================================================================== --- trunk/jython/Lib/test/test_threading.py 2009-08-10 19:04:35 UTC (rev 6658) +++ trunk/jython/Lib/test/test_threading.py 2009-08-10 19:05:11 UTC (rev 6659) @@ -112,7 +112,7 @@ self.test_various_ops() threading.stack_size(0) - # this test is not applicable to jython since + # this test is not applicable to jython since # 1. Lock is equiv to RLock, so this weird sync behavior won't be seen # 2. We use a weak hash map to map these threads # 3. This behavior doesn't make sense for Jython since any foreign This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2010-04-11 19:49:33
|
Revision: 7019 http://jython.svn.sourceforge.net/jython/?rev=7019&view=rev Author: pjenvey Date: 2010-04-11 19:49:26 +0000 (Sun, 11 Apr 2010) Log Message: ----------- make this easier to find Added Paths: ----------- trunk/jython/Lib/test/test_generators_jy.py Removed Paths: ------------- trunk/jython/Lib/test/test_jy_generators.py Copied: trunk/jython/Lib/test/test_generators_jy.py (from rev 7009, trunk/jython/Lib/test/test_jy_generators.py) =================================================================== --- trunk/jython/Lib/test/test_generators_jy.py (rev 0) +++ trunk/jython/Lib/test/test_generators_jy.py 2010-04-11 19:49:26 UTC (rev 7019) @@ -0,0 +1,164 @@ +from __future__ import generators +import unittest + +#tests for deeply nested try/except/finally's + +class FinallyTests(unittest.TestCase): + def gen1(self): + try: + pass + finally: + yield 1 + def genContinue(self): + for i in range(3): + try: + continue + finally: + yield i + def genPass(self): + for i in range(3): + try: + pass + finally: + yield i + def genLocal(self): + x = 1 + try: + pass + finally: + yield x + def genConditional(self): + for i in range(3): + x = 0 + try: + if i == 2: + continue + x = 1 + finally: + for j in range(x, x + 2): + yield j + def genTryExceptAroundFinally(self): + try: + for i in range(1): + try: + for i in range(3): + try: + try: + 1//0 + finally: + yield i + except: + pass + 1//0 + except: + yield 3 + except: + pass + def genNested(self): + for i in range(2): + try: + continue + finally: + for j in range(2): + try: + pass + finally: + yield (i, j) + def genNestedReversed(self): + for i in range(2): + try: + pass + finally: + for j in range(2): + try: + continue + finally: + yield (i, j) + def genNestedDeeply(self): + for i in range(4): + try: + continue + finally: + for j in range(i): + try: + pass + finally: + for k in range(j): + try: + try: + 1//0 + finally: + yield (i, j, k) + except: + pass + def genNestedTryExcept(self): + for j in range(3): + try: + try: + 1//0 + finally: + for k in range(3): + try: + 1//0 + finally: + yield (j, k) + except: + pass + def genNestedDeeplyTryExcept(self): + for i in range(3): + try: + try: + 1//0 + finally: + for j in range(3): + try: + 1//0 + finally: + for k in range(3): + try: + 1//0 + finally: + yield (i, j, k) + except: + pass + def testFinally(self): + self.assertEquals([1], list(self.gen1())) + self.assertEquals([0, 1, 2], list(self.genContinue())) + self.assertEquals([0, 1, 2], list(self.genPass())) + self.assertEquals([1], list(self.genLocal())) + self.assertEquals( + [1, 2, 1, 2, 0, 1], + list(self.genConditional())) + self.assertEquals([0, 1, 2, 3], list(self.genTryExceptAroundFinally())) + self.assertEquals( + [(0, 0), (0, 1), (1, 0), (1, 1)], + list(self.genNested())) + self.assertEquals( + [(0, 0), (0, 1), (1, 0), (1, 1)], + list(self.genNestedReversed())) + self.assertEquals( + [(2, 1, 0), (3, 1, 0), (3, 2, 0), (3, 2, 1)], + list(self.genNestedDeeply())) + self.assertEquals( + [(0, 0), (1, 0), (2, 0)], + list(self.genNestedTryExcept())) + self.assertEquals( + [(0, 0, 0), (1, 0, 0), (2, 0, 0)], + list(self.genNestedDeeplyTryExcept())) + +class TryExceptTests(unittest.TestCase): + def genNestedExcept(self): + for j in range(3): + try: + try: + 1//0 + except ZeroDivisionError, e: + yield 1 + raise e + except ZeroDivisionError: + pass + def testExcept(self): + self.assertEquals([1, 1, 1], list(self.genNestedExcept())) + +if __name__ == "__main__": + unittest.main() Deleted: trunk/jython/Lib/test/test_jy_generators.py =================================================================== --- trunk/jython/Lib/test/test_jy_generators.py 2010-04-11 19:20:41 UTC (rev 7018) +++ trunk/jython/Lib/test/test_jy_generators.py 2010-04-11 19:49:26 UTC (rev 7019) @@ -1,164 +0,0 @@ -from __future__ import generators -import unittest - -#tests for deeply nested try/except/finally's - -class FinallyTests(unittest.TestCase): - def gen1(self): - try: - pass - finally: - yield 1 - def genContinue(self): - for i in range(3): - try: - continue - finally: - yield i - def genPass(self): - for i in range(3): - try: - pass - finally: - yield i - def genLocal(self): - x = 1 - try: - pass - finally: - yield x - def genConditional(self): - for i in range(3): - x = 0 - try: - if i == 2: - continue - x = 1 - finally: - for j in range(x, x + 2): - yield j - def genTryExceptAroundFinally(self): - try: - for i in range(1): - try: - for i in range(3): - try: - try: - 1//0 - finally: - yield i - except: - pass - 1//0 - except: - yield 3 - except: - pass - def genNested(self): - for i in range(2): - try: - continue - finally: - for j in range(2): - try: - pass - finally: - yield (i, j) - def genNestedReversed(self): - for i in range(2): - try: - pass - finally: - for j in range(2): - try: - continue - finally: - yield (i, j) - def genNestedDeeply(self): - for i in range(4): - try: - continue - finally: - for j in range(i): - try: - pass - finally: - for k in range(j): - try: - try: - 1//0 - finally: - yield (i, j, k) - except: - pass - def genNestedTryExcept(self): - for j in range(3): - try: - try: - 1//0 - finally: - for k in range(3): - try: - 1//0 - finally: - yield (j, k) - except: - pass - def genNestedDeeplyTryExcept(self): - for i in range(3): - try: - try: - 1//0 - finally: - for j in range(3): - try: - 1//0 - finally: - for k in range(3): - try: - 1//0 - finally: - yield (i, j, k) - except: - pass - def testFinally(self): - self.assertEquals([1], list(self.gen1())) - self.assertEquals([0, 1, 2], list(self.genContinue())) - self.assertEquals([0, 1, 2], list(self.genPass())) - self.assertEquals([1], list(self.genLocal())) - self.assertEquals( - [1, 2, 1, 2, 0, 1], - list(self.genConditional())) - self.assertEquals([0, 1, 2, 3], list(self.genTryExceptAroundFinally())) - self.assertEquals( - [(0, 0), (0, 1), (1, 0), (1, 1)], - list(self.genNested())) - self.assertEquals( - [(0, 0), (0, 1), (1, 0), (1, 1)], - list(self.genNestedReversed())) - self.assertEquals( - [(2, 1, 0), (3, 1, 0), (3, 2, 0), (3, 2, 1)], - list(self.genNestedDeeply())) - self.assertEquals( - [(0, 0), (1, 0), (2, 0)], - list(self.genNestedTryExcept())) - self.assertEquals( - [(0, 0, 0), (1, 0, 0), (2, 0, 0)], - list(self.genNestedDeeplyTryExcept())) - -class TryExceptTests(unittest.TestCase): - def genNestedExcept(self): - for j in range(3): - try: - try: - 1//0 - except ZeroDivisionError, e: - yield 1 - raise e - except ZeroDivisionError: - pass - def testExcept(self): - self.assertEquals([1, 1, 1], list(self.genNestedExcept())) - -if __name__ == "__main__": - unittest.main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2010-10-06 22:00:30
|
Revision: 7137 http://jython.svn.sourceforge.net/jython/?rev=7137&view=rev Author: zyasoft Date: 2010-10-06 22:00:23 +0000 (Wed, 06 Oct 2010) Log Message: ----------- Added socket server test (navie multithreaded server, thread pool using client) to verify that the memory leak for #1662 remains fixed. Modified Paths: -------------- trunk/jython/Lib/test/test_threading_jy.py Added Paths: ----------- trunk/jython/Lib/test/socketserver_test.py Added: trunk/jython/Lib/test/socketserver_test.py =================================================================== --- trunk/jython/Lib/test/socketserver_test.py (rev 0) +++ trunk/jython/Lib/test/socketserver_test.py 2010-10-06 22:00:23 UTC (rev 7137) @@ -0,0 +1,59 @@ +# Used by test_threading_jy.py to verify no memory leaks in using a +# relatively large number of threads. This is of course an absolutely +# silly way to write real code on the JVM :), use a thread pool. So +# just for testing. +# +# However, the client here does use a thread pool. +# +# TODO monitor heap consumption too from appropriate MBean. Then we +# could presumably be adaptive or something clever like that. +# +# Test for http://bugs.jython.org/issue1660 + +import socket +import threading +import SocketServer +import time +from java.lang import Runtime +from java.util.concurrent import Executors, ExecutorCompletionService + +class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): + + def handle(self): + data = self.request.recv(1024) + cur_thread = threading.currentThread() + response = "%s: %s" % (cur_thread.getName(), data) + self.request.send(response) + +class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): + "mix together" + +def client(ip, port, message): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect((ip, port)) + sock.send(message) + response = sock.recv(1024) + # print threading.currentThread().getName(), response + sock.close() + +if __name__ == "__main__": + # ephemeral ports should work on every Java system now + HOST, PORT = "localhost", 0 + + server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) + ip, port = server.server_address + + # Start a daemon thread with the server -- that thread will then start one + # more thread for each request + server_thread = threading.Thread(target=server.serve_forever) + server_thread.setDaemon(True) + server_thread.start() + + # create a client pool to run all client requests + pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1) + ecs = ExecutorCompletionService(pool) + for i in xrange(4000): # empirically, this will exhaust heap when run with 16m heap + ecs.submit(lambda: client(ip, port, "Hello World %i" % i)) + ecs.take() # wait until we have a thread available in the pool + pool.shutdown() + Modified: trunk/jython/Lib/test/test_threading_jy.py =================================================================== --- trunk/jython/Lib/test/test_threading_jy.py 2010-10-05 22:26:34 UTC (rev 7136) +++ trunk/jython/Lib/test/test_threading_jy.py 2010-10-06 22:00:23 UTC (rev 7137) @@ -4,11 +4,15 @@ """ from __future__ import with_statement +import random +import subprocess +import sys +import threading +import time import unittest + +from subprocess import PIPE, Popen from test import test_support -import threading -import time -import random from threading import Condition, Lock, Thread from java.lang import Thread as JThread, InterruptedException @@ -84,8 +88,24 @@ self.assertEqual(joined_threads, num_threads) +class MemoryLeakTestCase(unittest.TestCase): + def test_socket_server(self): + # run socketserver with a small amount of memory; verify it exits cleanly + + + rc = subprocess.call([sys.executable, + "-J-Xmx32m", + test_support.findfile("socketserver_test.py")]) + # stdout=PIPE) + self.assertEquals(rc, 0) + + def test_main(): - test_support.run_unittest(JavaIntegrationTestCase, ThreadingTestCase, TwistedTestCase) + test_support.run_unittest( + JavaIntegrationTestCase, + MemoryLeakTestCase, + ThreadingTestCase, + TwistedTestCase) if __name__ == "__main__": This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2011-03-12 20:12:01
|
Revision: 7219 http://jython.svn.sourceforge.net/jython/?rev=7219&view=rev Author: fwierzbicki Date: 2011-03-12 20:11:47 +0000 (Sat, 12 Mar 2011) Log Message: ----------- Files changed for new test_support.py Modified Paths: -------------- trunk/jython/Lib/test/test_jy_internals.py trunk/jython/Lib/test/test_optparse.py trunk/jython/Lib/test/test_pulldom.py trunk/jython/Lib/test/test_scope.py trunk/jython/Lib/test/test_select.py trunk/jython/Lib/test/test_select_new.py trunk/jython/Lib/test/test_socket.py trunk/jython/Lib/test/test_support.py Modified: trunk/jython/Lib/test/test_jy_internals.py =================================================================== --- trunk/jython/Lib/test/test_jy_internals.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_jy_internals.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -4,7 +4,7 @@ import gc import unittest import time -from test.test_support import run_suite +from test import test_support import java import jarray @@ -287,19 +287,7 @@ self.assertEquals(len(test.__dict__), 4) def test_main(): - test_suite = unittest.TestSuite() - test_loader = unittest.TestLoader() - def suite_add(case): - test_suite.addTest(test_loader.loadTestsFromTestCase(case)) - suite_add(WeakIdentityMapTests) - suite_add(LongAsScaledDoubleValueTests) - suite_add(ExtraMathTests) - suite_add(DatetimeTypeMappingTest) - suite_add(IdTest) - suite_add(FrameTest) - suite_add(ModuleTest) - suite_add(MemoryLeakTests) - run_suite(test_suite) + test_support.run_unittest(__name__) if __name__ == "__main__": test_main() Modified: trunk/jython/Lib/test/test_optparse.py =================================================================== --- trunk/jython/Lib/test/test_optparse.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_optparse.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -5,10 +5,9 @@ # (tar...@so...) -- translated from the original Optik # test suite to this PyUnit-based version. # -# $Id: test_optparse.py 50791 2006-07-23 16:05:51Z greg.ward $ +# $Id: test_optparse.py 83540 2010-08-02 18:40:55Z ezio.melotti $ # -import __builtin__ import sys import os import re @@ -17,7 +16,6 @@ import unittest from StringIO import StringIO -from pprint import pprint from test import test_support @@ -28,12 +26,6 @@ from optparse import _match_abbrev from optparse import _parse_num -# Do the right thing with boolean values for all known Python versions. -try: - True, False -except NameError: - (True, False) = (1, 0) - retype = type(re.compile('')) class InterceptedError(Exception): @@ -461,7 +453,7 @@ return int(value) else: return int(value[:-1]) * _time_units[value[-1]] - except ValueError, IndexError: + except (ValueError, IndexError): raise OptionValueError( 'option %s: invalid duration: %r' % (opt, value)) @@ -774,6 +766,11 @@ {'a': "-b3", 'boo': None, 'foo': None}, []) + def test_combined_single_invalid_option(self): + self.parser.add_option("-t", action="store_true") + self.assertParseFail(["-test"], + "no such option: -e") + class TestBool(BaseTest): def setUp(self): options = [make_option("-v", @@ -796,15 +793,13 @@ (options, args) = self.assertParseOK(["-q"], {'verbose': 0}, []) - if hasattr(__builtin__, 'False'): - self.failUnless(options.verbose is False) + self.assertTrue(options.verbose is False) def test_bool_true(self): (options, args) = self.assertParseOK(["-v"], {'verbose': 1}, []) - if hasattr(__builtin__, 'True'): - self.failUnless(options.verbose is True) + self.assertTrue(options.verbose is True) def test_bool_flicker_on_and_off(self): self.assertParseOK(["-qvq", "-q", "-v"], @@ -1466,15 +1461,9 @@ # we must restore its original value -- otherwise, this test # screws things up for other tests when it's part of the Python # test suite. - orig_columns = os.environ.get('COLUMNS') - os.environ['COLUMNS'] = str(columns) - try: + with test_support.EnvironmentVarGuard() as env: + env.set('COLUMNS', str(columns)) return InterceptingOptionParser(option_list=options) - finally: - if orig_columns is None: - del os.environ['COLUMNS'] - else: - os.environ['COLUMNS'] = orig_columns def assertHelpEquals(self, expected_output): if type(expected_output) is types.UnicodeType: @@ -1501,8 +1490,10 @@ self.assertHelpEquals(_expected_help_long_opts_first) def test_help_title_formatter(self): - self.parser.formatter = TitledHelpFormatter() - self.assertHelpEquals(_expected_help_title_formatter) + with test_support.EnvironmentVarGuard() as env: + env.set("COLUMNS", "80") + self.parser.formatter = TitledHelpFormatter() + self.assertHelpEquals(_expected_help_title_formatter) def test_wrap_columns(self): # Ensure that wrapping respects $COLUMNS environment variable. @@ -1624,21 +1615,11 @@ "option -l: invalid long integer value: '0x12x'") -def _testclasses(): - mod = sys.modules[__name__] - return [getattr(mod, name) for name in dir(mod) if name.startswith('Test')] - -def suite(): - if test_support.is_jython: - # XXX: CPython ref count specific test +def test_main(): + is_jython = sys.platform.startswith("java") + if is_jython: del TestOptionParser.test_refleak - suite = unittest.TestSuite() - for testclass in _testclasses(): - suite.addTest(unittest.makeSuite(testclass)) - return suite + test_support.run_unittest(__name__) -def test_main(): - test_support.run_suite(suite()) - if __name__ == '__main__': test_main() Modified: trunk/jython/Lib/test/test_pulldom.py =================================================================== --- trunk/jython/Lib/test/test_pulldom.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_pulldom.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -79,11 +79,7 @@ self.fail("Unexpected exception joining comment data pieces: %s" % str(x)) def test_main(): - tests = [ - UnicodeTests, - ] - suites = [unittest.makeSuite(klass, 'test') for klass in tests] - test_support.run_suite(unittest.TestSuite(suites)) + test_support.run_unittest(__name__) if __name__ == "__main__": test_main() Modified: trunk/jython/Lib/test/test_scope.py =================================================================== --- trunk/jython/Lib/test/test_scope.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_scope.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -1,4 +1,4 @@ -from test.test_support import verify, TestFailed, check_syntax, vereq, is_jython +from test.test_support import verify, TestFailed, check_syntax_error, vereq, is_jython import warnings warnings.filterwarnings("ignore", r"import \*", SyntaxWarning, "<string>") @@ -180,7 +180,13 @@ print "11. unoptimized namespaces" -check_syntax("""\ +class FakeTestCase(object): + def fail(self): + raise TestFailed + +fake = FakeTestCase() + +check_syntax_error(fake, """\ def unoptimized_clash1(strip): def f(s): from string import * @@ -188,7 +194,7 @@ return f """) -check_syntax("""\ +check_syntax_error(fake, """\ def unoptimized_clash2(): from string import * def f(s): @@ -196,7 +202,7 @@ return f """) -check_syntax("""\ +check_syntax_error(fake, """\ def unoptimized_clash2(): from string import * def g(): @@ -206,7 +212,7 @@ """) # XXX could allow this for exec with const argument, but what's the point -check_syntax("""\ +check_syntax_error(fake, """\ def error(y): exec "a = 1" def f(x): @@ -214,14 +220,14 @@ return f """) -check_syntax("""\ +check_syntax_error(fake, """\ def f(x): def g(): return x del x # can't del name """) -check_syntax("""\ +check_syntax_error(fake, """\ def f(): def g(): from string import * Modified: trunk/jython/Lib/test/test_select.py =================================================================== --- trunk/jython/Lib/test/test_select.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_select.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -222,16 +222,10 @@ p.close() def test_main(): - tests = [ - TestSelectInvalidParameters, - TestSelectClientSocket, - TestPollClientSocket, - ThreadedPollClientSocket, - ] - if sys.platform[:4] != 'java': - tests.append(TestPipes) - suites = [unittest.makeSuite(klass, 'test') for klass in tests] - test_support.run_suite(unittest.TestSuite(suites)) + if test_support.is_jython: + del TestPipes.test + test_support.run_unittest(__name__) + if __name__ == "__main__": test_main() Modified: trunk/jython/Lib/test/test_select_new.py =================================================================== --- trunk/jython/Lib/test/test_select_new.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_select_new.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -238,9 +238,7 @@ self.handler.verify_only_writable() def test_main(): - tests = [TestSelect, TestSelectOnAccept] - suites = [unittest.makeSuite(klass, 'test') for klass in tests] - test_support.run_suite(unittest.TestSuite(suites)) + test_support.run_unittest(__name__) if __name__ == "__main__": test_main() Modified: trunk/jython/Lib/test/test_socket.py =================================================================== --- trunk/jython/Lib/test/test_socket.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_socket.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -1856,7 +1856,7 @@ if False: tests.append(UDPBroadcastTest) suites = [unittest.makeSuite(klass, 'test') for klass in tests] - test_support.run_suite(unittest.TestSuite(suites)) + test_support._run_suite(unittest.TestSuite(suites)) if __name__ == "__main__": test_main() Modified: trunk/jython/Lib/test/test_support.py =================================================================== --- trunk/jython/Lib/test/test_support.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_support.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -207,10 +207,6 @@ on Windows), it will be set on the socket. This will prevent anyone else from bind()'ing to our host/port for the duration of the test. """ - - #XXX: This section is probably wrong as I (Frank Wierzbicki) don't really - # understand it, but I needed this to get the asynchat tests running - # again. if is_jython: # Find some random ports that hopefully no one is listening on. # Ideally each test would clean up after itself and not continue @@ -902,9 +898,7 @@ def threading_setup(): import threading - if is_jython: - return len(threading._active), 0 - return len(threading._active), len(threading._limbo) + return len(threading._active), 0 def threading_cleanup(num_active, num_limbo): import threading @@ -916,12 +910,6 @@ count += 1 time.sleep(0.1) - if not is_jython: - count = 0 - while len(threading._limbo) != num_limbo and count < _MAX_COUNT: - count += 1 - time.sleep(0.1) - def reap_children(): """Use this function at the end of test_main() whenever sub-processes are started. This will help ensure that no extra children (zombies) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2011-03-12 20:13:48
|
Revision: 7220 http://jython.svn.sourceforge.net/jython/?rev=7220&view=rev Author: fwierzbicki Date: 2011-03-12 20:13:35 +0000 (Sat, 12 Mar 2011) Log Message: ----------- Tests added from Python 2.6 - these should be reviewed for deletion after we switch to the 2.6 Lib. Added Paths: ----------- trunk/jython/Lib/test/exception_hierarchy.txt trunk/jython/Lib/test/output/test_global trunk/jython/Lib/test/output/test_grammar trunk/jython/Lib/test/test_asynchat.py trunk/jython/Lib/test/test_base64.py trunk/jython/Lib/test/test_contextlib.py trunk/jython/Lib/test/test_datetime.py trunk/jython/Lib/test/test_email.py trunk/jython/Lib/test/test_email_renamed.py trunk/jython/Lib/test/test_gettext.py trunk/jython/Lib/test/test_global.py trunk/jython/Lib/test/test_threading_local.py trunk/jython/Lib/test/test_wsgiref.py Added: trunk/jython/Lib/test/exception_hierarchy.txt =================================================================== --- trunk/jython/Lib/test/exception_hierarchy.txt (rev 0) +++ trunk/jython/Lib/test/exception_hierarchy.txt 2011-03-12 20:13:35 UTC (rev 7220) @@ -0,0 +1,49 @@ +BaseException + +-- SystemExit + +-- KeyboardInterrupt + +-- GeneratorExit + +-- Exception + +-- StopIteration + +-- StandardError + | +-- ArithmeticError + | | +-- FloatingPointError + | | +-- OverflowError + | | +-- ZeroDivisionError + | +-- AssertionError + | +-- AttributeError + | +-- EnvironmentError + | | +-- IOError + | | +-- OSError + | | +-- WindowsError (Windows) + | | +-- VMSError (VMS) + | +-- EOFError + | +-- ImportError + | +-- LookupError + | | +-- IndexError + | | +-- KeyError + | +-- MemoryError + | +-- NameError + | | +-- UnboundLocalError + | +-- ReferenceError + | +-- RuntimeError + | | +-- NotImplementedError + | +-- SyntaxError + | | +-- IndentationError + | | +-- TabError + | +-- SystemError + | +-- TypeError + | +-- ValueError + | +-- UnicodeError + | +-- UnicodeDecodeError + | +-- UnicodeEncodeError + | +-- UnicodeTranslateError + +-- Warning + +-- DeprecationWarning + +-- PendingDeprecationWarning + +-- RuntimeWarning + +-- SyntaxWarning + +-- UserWarning + +-- FutureWarning + +-- ImportWarning + +-- UnicodeWarning + +-- BytesWarning Added: trunk/jython/Lib/test/output/test_global =================================================================== --- trunk/jython/Lib/test/output/test_global (rev 0) +++ trunk/jython/Lib/test/output/test_global 2011-03-12 20:13:35 UTC (rev 7220) @@ -0,0 +1 @@ +test_global Added: trunk/jython/Lib/test/output/test_grammar =================================================================== --- trunk/jython/Lib/test/output/test_grammar (rev 0) +++ trunk/jython/Lib/test/output/test_grammar 2011-03-12 20:13:35 UTC (rev 7220) @@ -0,0 +1 @@ +test_grammar Added: trunk/jython/Lib/test/test_asynchat.py =================================================================== --- trunk/jython/Lib/test/test_asynchat.py (rev 0) +++ trunk/jython/Lib/test/test_asynchat.py 2011-03-12 20:13:35 UTC (rev 7220) @@ -0,0 +1,93 @@ +# test asynchat -- requires threading + +import thread # If this fails, we can't test this module +import asyncore, asynchat, socket, threading, time +import unittest +from test import test_support + +HOST = "127.0.0.1" +PORT = 54322 + +class echo_server(threading.Thread): + + def run(self): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + global PORT + PORT = test_support.bind_port(sock, HOST) + sock.listen(1) + conn, client = sock.accept() + buffer = "" + while "\n" not in buffer: + data = conn.recv(1) + if not data: + break + buffer = buffer + data + while buffer: + n = conn.send(buffer) + buffer = buffer[n:] + conn.close() + sock.close() + +class echo_client(asynchat.async_chat): + + def __init__(self, terminator): + asynchat.async_chat.__init__(self) + self.contents = None + self.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.connect((HOST, PORT)) + self.set_terminator(terminator) + self.buffer = "" + + def handle_connect(self): + pass + ##print "Connected" + + def collect_incoming_data(self, data): + self.buffer = self.buffer + data + + def found_terminator(self): + #print "Received:", repr(self.buffer) + self.contents = self.buffer + self.buffer = "" + self.close() + + +class TestAsynchat(unittest.TestCase): + def setUp (self): + pass + + def tearDown (self): + pass + + def test_line_terminator(self): + s = echo_server() + s.start() + time.sleep(1) # Give server time to initialize + c = echo_client('\n') + c.push("hello ") + c.push("world\n") + asyncore.loop() + s.join() + + self.assertEqual(c.contents, 'hello world') + + def test_numeric_terminator(self): + # Try reading a fixed number of bytes + s = echo_server() + s.start() + time.sleep(1) # Give server time to initialize + c = echo_client(6L) + c.push("hello ") + c.push("world\n") + asyncore.loop() + s.join() + + self.assertEqual(c.contents, 'hello ') + + +def test_main(verbose=None): + test_support.run_unittest(TestAsynchat) + +if __name__ == "__main__": + test_main(verbose=True) Added: trunk/jython/Lib/test/test_base64.py =================================================================== --- trunk/jython/Lib/test/test_base64.py (rev 0) +++ trunk/jython/Lib/test/test_base64.py 2011-03-12 20:13:35 UTC (rev 7220) @@ -0,0 +1,190 @@ +import unittest +from test import test_support +import base64 + + + +class LegacyBase64TestCase(unittest.TestCase): + def test_encodestring(self): + eq = self.assertEqual + eq(base64.encodestring("www.python.org"), "d3d3LnB5dGhvbi5vcmc=\n") + eq(base64.encodestring("a"), "YQ==\n") + eq(base64.encodestring("ab"), "YWI=\n") + eq(base64.encodestring("abc"), "YWJj\n") + eq(base64.encodestring(""), "") + eq(base64.encodestring("abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789!@#0^&*();:<>,. []{}"), + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" + "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" + "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n") + + def test_decodestring(self): + eq = self.assertEqual + eq(base64.decodestring("d3d3LnB5dGhvbi5vcmc=\n"), "www.python.org") + eq(base64.decodestring("YQ==\n"), "a") + eq(base64.decodestring("YWI=\n"), "ab") + eq(base64.decodestring("YWJj\n"), "abc") + eq(base64.decodestring("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" + "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" + "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n"), + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789!@#0^&*();:<>,. []{}") + eq(base64.decodestring(''), '') + + def test_encode(self): + eq = self.assertEqual + from cStringIO import StringIO + infp = StringIO('abcdefghijklmnopqrstuvwxyz' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + '0123456789!@#0^&*();:<>,. []{}') + outfp = StringIO() + base64.encode(infp, outfp) + eq(outfp.getvalue(), + 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' + 'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT' + 'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n') + + def test_decode(self): + from cStringIO import StringIO + infp = StringIO('d3d3LnB5dGhvbi5vcmc=') + outfp = StringIO() + base64.decode(infp, outfp) + self.assertEqual(outfp.getvalue(), 'www.python.org') + + + +class BaseXYTestCase(unittest.TestCase): + def test_b64encode(self): + eq = self.assertEqual + # Test default alphabet + eq(base64.b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=") + eq(base64.b64encode('\x00'), 'AA==') + eq(base64.b64encode("a"), "YQ==") + eq(base64.b64encode("ab"), "YWI=") + eq(base64.b64encode("abc"), "YWJj") + eq(base64.b64encode(""), "") + eq(base64.b64encode("abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789!@#0^&*();:<>,. []{}"), + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" + "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" + "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==") + # Test with arbitrary alternative characters + eq(base64.b64encode('\xd3V\xbeo\xf7\x1d', altchars='*$'), '01a*b$cd') + # Test standard alphabet + eq(base64.standard_b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=") + eq(base64.standard_b64encode("a"), "YQ==") + eq(base64.standard_b64encode("ab"), "YWI=") + eq(base64.standard_b64encode("abc"), "YWJj") + eq(base64.standard_b64encode(""), "") + eq(base64.standard_b64encode("abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789!@#0^&*();:<>,. []{}"), + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" + "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" + "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==") + # Test with 'URL safe' alternative characters + eq(base64.urlsafe_b64encode('\xd3V\xbeo\xf7\x1d'), '01a-b_cd') + + def test_b64decode(self): + eq = self.assertEqual + eq(base64.b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") + eq(base64.b64decode('AA=='), '\x00') + eq(base64.b64decode("YQ=="), "a") + eq(base64.b64decode("YWI="), "ab") + eq(base64.b64decode("YWJj"), "abc") + eq(base64.b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" + "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" + "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789!@#0^&*();:<>,. []{}") + eq(base64.b64decode(''), '') + # Test with arbitrary alternative characters + eq(base64.b64decode('01a*b$cd', altchars='*$'), '\xd3V\xbeo\xf7\x1d') + # Test standard alphabet + eq(base64.standard_b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") + eq(base64.standard_b64decode("YQ=="), "a") + eq(base64.standard_b64decode("YWI="), "ab") + eq(base64.standard_b64decode("YWJj"), "abc") + eq(base64.standard_b64decode(""), "") + eq(base64.standard_b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" + "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" + "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789!@#0^&*();:<>,. []{}") + # Test with 'URL safe' alternative characters + eq(base64.urlsafe_b64decode('01a-b_cd'), '\xd3V\xbeo\xf7\x1d') + + def test_b64decode_error(self): + self.assertRaises(TypeError, base64.b64decode, 'abc') + + def test_b32encode(self): + eq = self.assertEqual + eq(base64.b32encode(''), '') + eq(base64.b32encode('\x00'), 'AA======') + eq(base64.b32encode('a'), 'ME======') + eq(base64.b32encode('ab'), 'MFRA====') + eq(base64.b32encode('abc'), 'MFRGG===') + eq(base64.b32encode('abcd'), 'MFRGGZA=') + eq(base64.b32encode('abcde'), 'MFRGGZDF') + + def test_b32decode(self): + eq = self.assertEqual + eq(base64.b32decode(''), '') + eq(base64.b32decode('AA======'), '\x00') + eq(base64.b32decode('ME======'), 'a') + eq(base64.b32decode('MFRA===='), 'ab') + eq(base64.b32decode('MFRGG==='), 'abc') + eq(base64.b32decode('MFRGGZA='), 'abcd') + eq(base64.b32decode('MFRGGZDF'), 'abcde') + + def test_b32decode_casefold(self): + eq = self.assertEqual + eq(base64.b32decode('', True), '') + eq(base64.b32decode('ME======', True), 'a') + eq(base64.b32decode('MFRA====', True), 'ab') + eq(base64.b32decode('MFRGG===', True), 'abc') + eq(base64.b32decode('MFRGGZA=', True), 'abcd') + eq(base64.b32decode('MFRGGZDF', True), 'abcde') + # Lower cases + eq(base64.b32decode('me======', True), 'a') + eq(base64.b32decode('mfra====', True), 'ab') + eq(base64.b32decode('mfrgg===', True), 'abc') + eq(base64.b32decode('mfrggza=', True), 'abcd') + eq(base64.b32decode('mfrggzdf', True), 'abcde') + # Expected exceptions + self.assertRaises(TypeError, base64.b32decode, 'me======') + # Mapping zero and one + eq(base64.b32decode('MLO23456'), 'b\xdd\xad\xf3\xbe') + eq(base64.b32decode('M1023456', map01='L'), 'b\xdd\xad\xf3\xbe') + eq(base64.b32decode('M1023456', map01='I'), 'b\x1d\xad\xf3\xbe') + + def test_b32decode_error(self): + self.assertRaises(TypeError, base64.b32decode, 'abc') + self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==') + + def test_b16encode(self): + eq = self.assertEqual + eq(base64.b16encode('\x01\x02\xab\xcd\xef'), '0102ABCDEF') + eq(base64.b16encode('\x00'), '00') + + def test_b16decode(self): + eq = self.assertEqual + eq(base64.b16decode('0102ABCDEF'), '\x01\x02\xab\xcd\xef') + eq(base64.b16decode('00'), '\x00') + # Lower case is not allowed without a flag + self.assertRaises(TypeError, base64.b16decode, '0102abcdef') + # Case fold + eq(base64.b16decode('0102abcdef', True), '\x01\x02\xab\xcd\xef') + + + +def test_main(): + test_support.run_unittest(__name__) + +if __name__ == '__main__': + test_main() Added: trunk/jython/Lib/test/test_contextlib.py =================================================================== --- trunk/jython/Lib/test/test_contextlib.py (rev 0) +++ trunk/jython/Lib/test/test_contextlib.py 2011-03-12 20:13:35 UTC (rev 7220) @@ -0,0 +1,337 @@ +"""Unit tests for contextlib.py, and other context managers.""" + +import sys +import os +import decimal +import tempfile +import unittest +import threading +from contextlib import * # Tests __all__ +from test import test_support + +class ContextManagerTestCase(unittest.TestCase): + + def test_contextmanager_plain(self): + state = [] + @contextmanager + def woohoo(): + state.append(1) + yield 42 + state.append(999) + with woohoo() as x: + self.assertEqual(state, [1]) + self.assertEqual(x, 42) + state.append(x) + self.assertEqual(state, [1, 42, 999]) + + def test_contextmanager_finally(self): + state = [] + @contextmanager + def woohoo(): + state.append(1) + try: + yield 42 + finally: + state.append(999) + try: + with woohoo() as x: + self.assertEqual(state, [1]) + self.assertEqual(x, 42) + state.append(x) + raise ZeroDivisionError() + except ZeroDivisionError: + pass + else: + self.fail("Expected ZeroDivisionError") + self.assertEqual(state, [1, 42, 999]) + + def test_contextmanager_no_reraise(self): + @contextmanager + def whee(): + yield + ctx = whee() + ctx.__enter__() + # Calling __exit__ should not result in an exception + self.failIf(ctx.__exit__(TypeError, TypeError("foo"), None)) + + def test_contextmanager_trap_yield_after_throw(self): + @contextmanager + def whoo(): + try: + yield + except: + yield + ctx = whoo() + ctx.__enter__() + self.assertRaises( + RuntimeError, ctx.__exit__, TypeError, TypeError("foo"), None + ) + + def test_contextmanager_except(self): + state = [] + @contextmanager + def woohoo(): + state.append(1) + try: + yield 42 + except ZeroDivisionError, e: + state.append(e.args[0]) + self.assertEqual(state, [1, 42, 999]) + with woohoo() as x: + self.assertEqual(state, [1]) + self.assertEqual(x, 42) + state.append(x) + raise ZeroDivisionError(999) + self.assertEqual(state, [1, 42, 999]) + + def test_contextmanager_attribs(self): + def attribs(**kw): + def decorate(func): + for k,v in kw.items(): + setattr(func,k,v) + return func + return decorate + @contextmanager + @attribs(foo='bar') + def baz(spam): + """Whee!""" + self.assertEqual(baz.__name__,'baz') + self.assertEqual(baz.foo, 'bar') + self.assertEqual(baz.__doc__, "Whee!") + +class NestedTestCase(unittest.TestCase): + + # XXX This needs more work + + def test_nested(self): + @contextmanager + def a(): + yield 1 + @contextmanager + def b(): + yield 2 + @contextmanager + def c(): + yield 3 + with nested(a(), b(), c()) as (x, y, z): + self.assertEqual(x, 1) + self.assertEqual(y, 2) + self.assertEqual(z, 3) + + def test_nested_cleanup(self): + state = [] + @contextmanager + def a(): + state.append(1) + try: + yield 2 + finally: + state.append(3) + @contextmanager + def b(): + state.append(4) + try: + yield 5 + finally: + state.append(6) + try: + with nested(a(), b()) as (x, y): + state.append(x) + state.append(y) + 1 // 0 + except ZeroDivisionError: + self.assertEqual(state, [1, 4, 2, 5, 6, 3]) + else: + self.fail("Didn't raise ZeroDivisionError") + + def test_nested_right_exception(self): + state = [] + @contextmanager + def a(): + yield 1 + class b(object): + def __enter__(self): + return 2 + def __exit__(self, *exc_info): + try: + raise Exception() + except: + pass + try: + with nested(a(), b()) as (x, y): + 1 // 0 + except ZeroDivisionError: + self.assertEqual((x, y), (1, 2)) + except Exception: + self.fail("Reraised wrong exception") + else: + self.fail("Didn't raise ZeroDivisionError") + + def test_nested_b_swallows(self): + @contextmanager + def a(): + yield + @contextmanager + def b(): + try: + yield + except: + # Swallow the exception + pass + try: + with nested(a(), b()): + 1 // 0 + except ZeroDivisionError: + self.fail("Didn't swallow ZeroDivisionError") + + def test_nested_break(self): + @contextmanager + def a(): + yield + state = 0 + while True: + state += 1 + with nested(a(), a()): + break + state += 10 + self.assertEqual(state, 1) + + def test_nested_continue(self): + @contextmanager + def a(): + yield + state = 0 + while state < 3: + state += 1 + with nested(a(), a()): + continue + state += 10 + self.assertEqual(state, 3) + + def test_nested_return(self): + @contextmanager + def a(): + try: + yield + except: + pass + def foo(): + with nested(a(), a()): + return 1 + return 10 + self.assertEqual(foo(), 1) + +class ClosingTestCase(unittest.TestCase): + + # XXX This needs more work + + def test_closing(self): + state = [] + class C: + def close(self): + state.append(1) + x = C() + self.assertEqual(state, []) + with closing(x) as y: + self.assertEqual(x, y) + self.assertEqual(state, [1]) + + def test_closing_error(self): + state = [] + class C: + def close(self): + state.append(1) + x = C() + self.assertEqual(state, []) + try: + with closing(x) as y: + self.assertEqual(x, y) + 1 // 0 + except ZeroDivisionError: + self.assertEqual(state, [1]) + else: + self.fail("Didn't raise ZeroDivisionError") + +class FileContextTestCase(unittest.TestCase): + + def testWithOpen(self): + tfn = tempfile.mktemp() + try: + f = None + with open(tfn, "w") as f: + self.failIf(f.closed) + f.write("Booh\n") + self.failUnless(f.closed) + f = None + try: + with open(tfn, "r") as f: + self.failIf(f.closed) + self.assertEqual(f.read(), "Booh\n") + 1 // 0 + except ZeroDivisionError: + self.failUnless(f.closed) + else: + self.fail("Didn't raise ZeroDivisionError") + finally: + try: + os.remove(tfn) + except os.error: + pass + +class LockContextTestCase(unittest.TestCase): + + def boilerPlate(self, lock, locked): + self.failIf(locked()) + with lock: + self.failUnless(locked()) + self.failIf(locked()) + try: + with lock: + self.failUnless(locked()) + 1 // 0 + except ZeroDivisionError: + self.failIf(locked()) + else: + self.fail("Didn't raise ZeroDivisionError") + + def testWithLock(self): + lock = threading.Lock() + self.boilerPlate(lock, lock.locked) + + def testWithRLock(self): + lock = threading.RLock() + self.boilerPlate(lock, lock._is_owned) + + def testWithCondition(self): + lock = threading.Condition() + def locked(): + return lock._is_owned() + self.boilerPlate(lock, locked) + + def testWithSemaphore(self): + lock = threading.Semaphore() + def locked(): + if lock.acquire(False): + lock.release() + return False + else: + return True + self.boilerPlate(lock, locked) + + def testWithBoundedSemaphore(self): + lock = threading.BoundedSemaphore() + def locked(): + if lock.acquire(False): + lock.release() + return False + else: + return True + self.boilerPlate(lock, locked) + +# This is needed to make the test actually run under regrtest.py! +def test_main(): + test_support.run_unittest(__name__) + + +if __name__ == "__main__": + test_main() Added: trunk/jython/Lib/test/test_datetime.py =================================================================== --- trunk/jython/Lib/test/test_datetime.py (rev 0) +++ trunk/jython/Lib/test/test_datetime.py 2011-03-12 20:13:35 UTC (rev 7220) @@ -0,0 +1,3367 @@ +"""Test date/time type. + +See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases +""" + +import sys +import pickle +import cPickle +import unittest + +from test import test_support + +from datetime import MINYEAR, MAXYEAR +from datetime import timedelta +from datetime import tzinfo +from datetime import time +from datetime import date, datetime + +pickle_choices = [(pickler, unpickler, proto) + for pickler in pickle, cPickle + for unpickler in pickle, cPickle + for proto in range(3)] +assert len(pickle_choices) == 2*2*3 + +# An arbitrary collection of objects of non-datetime types, for testing +# mixed-type comparisons. +OTHERSTUFF = (10, 10L, 34.5, "abc", {}, [], ()) + + +############################################################################# +# module tests + +class TestModule(unittest.TestCase): + + def test_constants(self): + import datetime + self.assertEqual(datetime.MINYEAR, 1) + self.assertEqual(datetime.MAXYEAR, 9999) + +############################################################################# +# tzinfo tests + +class FixedOffset(tzinfo): + def __init__(self, offset, name, dstoffset=42): + if isinstance(offset, int): + offset = timedelta(minutes=offset) + if isinstance(dstoffset, int): + dstoffset = timedelta(minutes=dstoffset) + self.__offset = offset + self.__name = name + self.__dstoffset = dstoffset + def __repr__(self): + return self.__name.lower() + def utcoffset(self, dt): + return self.__offset + def tzname(self, dt): + return self.__name + def dst(self, dt): + return self.__dstoffset + +class PicklableFixedOffset(FixedOffset): + def __init__(self, offset=None, name=None, dstoffset=None): + FixedOffset.__init__(self, offset, name, dstoffset) + +class TestTZInfo(unittest.TestCase): + + def test_non_abstractness(self): + # In order to allow subclasses to get pickled, the C implementation + # wasn't able to get away with having __init__ raise + # NotImplementedError. + useless = tzinfo() + dt = datetime.max + self.assertRaises(NotImplementedError, useless.tzname, dt) + self.assertRaises(NotImplementedError, useless.utcoffset, dt) + self.assertRaises(NotImplementedError, useless.dst, dt) + + def test_subclass_must_override(self): + class NotEnough(tzinfo): + def __init__(self, offset, name): + self.__offset = offset + self.__name = name + self.failUnless(issubclass(NotEnough, tzinfo)) + ne = NotEnough(3, "NotByALongShot") + self.failUnless(isinstance(ne, tzinfo)) + + dt = datetime.now() + self.assertRaises(NotImplementedError, ne.tzname, dt) + self.assertRaises(NotImplementedError, ne.utcoffset, dt) + self.assertRaises(NotImplementedError, ne.dst, dt) + + def test_normal(self): + fo = FixedOffset(3, "Three") + self.failUnless(isinstance(fo, tzinfo)) + for dt in datetime.now(), None: + self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3)) + self.assertEqual(fo.tzname(dt), "Three") + self.assertEqual(fo.dst(dt), timedelta(minutes=42)) + + def test_pickling_base(self): + # There's no point to pickling tzinfo objects on their own (they + # carry no data), but they need to be picklable anyway else + # concrete subclasses can't be pickled. + orig = tzinfo.__new__(tzinfo) + self.failUnless(type(orig) is tzinfo) + for pickler, unpickler, proto in pickle_choices: + green = pickler.dumps(orig, proto) + derived = unpickler.loads(green) + self.failUnless(type(derived) is tzinfo) + + def test_pickling_subclass(self): + # Make sure we can pickle/unpickle an instance of a subclass. + offset = timedelta(minutes=-300) + orig = PicklableFixedOffset(offset, 'cookie') + self.failUnless(isinstance(orig, tzinfo)) + self.failUnless(type(orig) is PicklableFixedOffset) + self.assertEqual(orig.utcoffset(None), offset) + self.assertEqual(orig.tzname(None), 'cookie') + for pickler, unpickler, proto in pickle_choices: + green = pickler.dumps(orig, proto) + derived = unpickler.loads(green) + self.failUnless(isinstance(derived, tzinfo)) + self.failUnless(type(derived) is PicklableFixedOffset) + self.assertEqual(derived.utcoffset(None), offset) + self.assertEqual(derived.tzname(None), 'cookie') + +############################################################################# +# Base clase for testing a particular aspect of timedelta, time, date and +# datetime comparisons. + +class HarmlessMixedComparison: + # Test that __eq__ and __ne__ don't complain for mixed-type comparisons. + + # Subclasses must define 'theclass', and theclass(1, 1, 1) must be a + # legit constructor. + + def test_harmless_mixed_comparison(self): + me = self.theclass(1, 1, 1) + + self.failIf(me == ()) + self.failUnless(me != ()) + self.failIf(() == me) + self.failUnless(() != me) + + self.failUnless(me in [1, 20L, [], me]) + self.failIf(me not in [1, 20L, [], me]) + + self.failUnless([] in [me, 1, 20L, []]) + self.failIf([] not in [me, 1, 20L, []]) + + def test_harmful_mixed_comparison(self): + me = self.theclass(1, 1, 1) + + self.assertRaises(TypeError, lambda: me < ()) + self.assertRaises(TypeError, lambda: me <= ()) + self.assertRaises(TypeError, lambda: me > ()) + self.assertRaises(TypeError, lambda: me >= ()) + + self.assertRaises(TypeError, lambda: () < me) + self.assertRaises(TypeError, lambda: () <= me) + self.assertRaises(TypeError, lambda: () > me) + self.assertRaises(TypeError, lambda: () >= me) + + self.assertRaises(TypeError, cmp, (), me) + self.assertRaises(TypeError, cmp, me, ()) + +############################################################################# +# timedelta tests + +class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): + + theclass = timedelta + + def test_constructor(self): + eq = self.assertEqual + td = timedelta + + # Check keyword args to constructor + eq(td(), td(weeks=0, days=0, hours=0, minutes=0, seconds=0, + milliseconds=0, microseconds=0)) + eq(td(1), td(days=1)) + eq(td(0, 1), td(seconds=1)) + eq(td(0, 0, 1), td(microseconds=1)) + eq(td(weeks=1), td(days=7)) + eq(td(days=1), td(hours=24)) + eq(td(hours=1), td(minutes=60)) + eq(td(minutes=1), td(seconds=60)) + eq(td(seconds=1), td(milliseconds=1000)) + eq(td(milliseconds=1), td(microseconds=1000)) + + # Check float args to constructor + eq(td(weeks=1.0/7), td(days=1)) + eq(td(days=1.0/24), td(hours=1)) + eq(td(hours=1.0/60), td(minutes=1)) + eq(td(minutes=1.0/60), td(seconds=1)) + eq(td(seconds=0.001), td(milliseconds=1)) + eq(td(milliseconds=0.001), td(microseconds=1)) + + def test_computations(self): + eq = self.assertEqual + td = timedelta + + a = td(7) # One week + b = td(0, 60) # One minute + c = td(0, 0, 1000) # One millisecond + eq(a+b+c, td(7, 60, 1000)) + eq(a-b, td(6, 24*3600 - 60)) + eq(-a, td(-7)) + eq(+a, td(7)) + eq(-b, td(-1, 24*3600 - 60)) + eq(-c, td(-1, 24*3600 - 1, 999000)) + eq(abs(a), a) + eq(abs(-a), a) + eq(td(6, 24*3600), a) + eq(td(0, 0, 60*1000000), b) + eq(a*10, td(70)) + eq(a*10, 10*a) + eq(a*10L, 10*a) + eq(b*10, td(0, 600)) + eq(10*b, td(0, 600)) + eq(b*10L, td(0, 600)) + eq(c*10, td(0, 0, 10000)) + eq(10*c, td(0, 0, 10000)) + eq(c*10L, td(0, 0, 10000)) + eq(a*-1, -a) + eq(b*-2, -b-b) + eq(c*-2, -c+-c) + eq(b*(60*24), (b*60)*24) + eq(b*(60*24), (60*b)*24) + eq(c*1000, td(0, 1)) + eq(1000*c, td(0, 1)) + eq(a//7, td(1)) + eq(b//10, td(0, 6)) + eq(c//1000, td(0, 0, 1)) + eq(a//10, td(0, 7*24*360)) + eq(a//3600000, td(0, 0, 7*24*1000)) + + def test_disallowed_computations(self): + a = timedelta(42) + + # Add/sub ints, longs, floats should be illegal + for i in 1, 1L, 1.0: + self.assertRaises(TypeError, lambda: a+i) + self.assertRaises(TypeError, lambda: a-i) + self.assertRaises(TypeError, lambda: i+a) + self.assertRaises(TypeError, lambda: i-a) + + # Mul/div by float isn't supported. + x = 2.3 + self.assertRaises(TypeError, lambda: a*x) + self.assertRaises(TypeError, lambda: x*a) + self.assertRaises(TypeError, lambda: a/x) + self.assertRaises(TypeError, lambda: x/a) + self.assertRaises(TypeError, lambda: a // x) + self.assertRaises(TypeError, lambda: x // a) + + # Division of int by timedelta doesn't make sense. + # Division by zero doesn't make sense. + for zero in 0, 0L: + self.assertRaises(TypeError, lambda: zero // a) + self.assertRaises(ZeroDivisionError, lambda: a // zero) + + def test_basic_attributes(self): + days, seconds, us = 1, 7, 31 + td = timedelta(days, seconds, us) + self.assertEqual(td.days, days) + self.assertEqual(td.seconds, seconds) + self.assertEqual(td.microseconds, us) + + def test_carries(self): + t1 = timedelta(days=100, + weeks=-7, + hours=-24*(100-49), + minutes=-3, + seconds=12, + microseconds=(3*60 - 12) * 1e6 + 1) + t2 = timedelta(microseconds=1) + self.assertEqual(t1, t2) + + def test_hash_equality(self): + t1 = timedelta(days=100, + weeks=-7, + hours=-24*(100-49), + minutes=-3, + seconds=12, + microseconds=(3*60 - 12) * 1000000) + t2 = timedelta() + self.assertEqual(hash(t1), hash(t2)) + + t1 += timedelta(weeks=7) + t2 += timedelta(days=7*7) + self.assertEqual(t1, t2) + self.assertEqual(hash(t1), hash(t2)) + + d = {t1: 1} + d[t2] = 2 + self.assertEqual(len(d), 1) + self.assertEqual(d[t1], 2) + + def test_pickling(self): + args = 12, 34, 56 + orig = timedelta(*args) + for pickler, unpickler, proto in pickle_choices: + green = pickler.dumps(orig, proto) + derived = unpickler.loads(green) + self.assertEqual(orig, derived) + + def test_compare(self): + t1 = timedelta(2, 3, 4) + t2 = timedelta(2, 3, 4) + self.failUnless(t1 == t2) + self.failUnless(t1 <= t2) + self.failUnless(t1 >= t2) + self.failUnless(not t1 != t2) + self.failUnless(not t1 < t2) + self.failUnless(not t1 > t2) + self.assertEqual(cmp(t1, t2), 0) + self.assertEqual(cmp(t2, t1), 0) + + for args in (3, 3, 3), (2, 4, 4), (2, 3, 5): + t2 = timedelta(*args) # this is larger than t1 + self.failUnless(t1 < t2) + self.failUnless(t2 > t1) + self.failUnless(t1 <= t2) + self.failUnless(t2 >= t1) + self.failUnless(t1 != t2) + self.failUnless(t2 != t1) + self.failUnless(not t1 == t2) + self.failUnless(not t2 == t1) + self.failUnless(not t1 > t2) + self.failUnless(not t2 < t1) + self.failUnless(not t1 >= t2) + self.failUnless(not t2 <= t1) + self.assertEqual(cmp(t1, t2), -1) + self.assertEqual(cmp(t2, t1), 1) + + for badarg in OTHERSTUFF: + self.assertEqual(t1 == badarg, False) + self.assertEqual(t1 != badarg, True) + self.assertEqual(badarg == t1, False) + self.assertEqual(badarg != t1, True) + + self.assertRaises(TypeError, lambda: t1 <= badarg) + self.assertRaises(TypeError, lambda: t1 < badarg) + self.assertRaises(TypeError, lambda: t1 > badarg) + self.assertRaises(TypeError, lambda: t1 >= badarg) + self.assertRaises(TypeError, lambda: badarg <= t1) + self.assertRaises(TypeError, lambda: badarg < t1) + self.assertRaises(TypeError, lambda: badarg > t1) + self.assertRaises(TypeError, lambda: badarg >= t1) + + def test_str(self): + td = timedelta + eq = self.assertEqual + + eq(str(td(1)), "1 day, 0:00:00") + eq(str(td(-1)), "-1 day, 0:00:00") + eq(str(td(2)), "2 days, 0:00:00") + eq(str(td(-2)), "-2 days, 0:00:00") + + eq(str(td(hours=12, minutes=58, seconds=59)), "12:58:59") + eq(str(td(hours=2, minutes=3, seconds=4)), "2:03:04") + eq(str(td(weeks=-30, hours=23, minutes=12, seconds=34)), + "-210 days, 23:12:34") + + eq(str(td(milliseconds=1)), "0:00:00.001000") + eq(str(td(microseconds=3)), "0:00:00.000003") + + eq(str(td(days=999999999, hours=23, minutes=59, seconds=59, + microseconds=999999)), + "999999999 days, 23:59:59.999999") + + def test_roundtrip(self): + for td in (timedelta(days=999999999, hours=23, minutes=59, + seconds=59, microseconds=999999), + timedelta(days=-999999999), + timedelta(days=1, seconds=2, microseconds=3)): + + # Verify td -> string -> td identity. + s = repr(td) + self.failUnless(s.startswith('datetime.')) + s = s[9:] + td2 = eval(s) + self.assertEqual(td, td2) + + # Verify identity via reconstructing from pieces. + td2 = timedelta(td.days, td.seconds, td.microseconds) + self.assertEqual(td, td2) + + def test_resolution_info(self): + self.assert_(isinstance(timedelta.min, timedelta)) + self.assert_(isinstance(timedelta.max, timedelta)) + self.assert_(isinstance(timedelta.resolution, timedelta)) + self.assert_(timedelta.max > timedelta.min) + self.assertEqual(timedelta.min, timedelta(-999999999)) + self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1)) + self.assertEqual(timedelta.resolution, timedelta(0, 0, 1)) + + def test_overflow(self): + tiny = timedelta.resolution + + td = timedelta.min + tiny + td -= tiny # no problem + self.assertRaises(OverflowError, td.__sub__, tiny) + self.assertRaises(OverflowError, td.__add__, -tiny) + + td = timedelta.max - tiny + td += tiny # no problem + self.assertRaises(OverflowError, td.__add__, tiny) + self.assertRaises(OverflowError, td.__sub__, -tiny) + + self.assertRaises(OverflowError, lambda: -timedelta.max) + + def test_microsecond_rounding(self): + td = timedelta + eq = self.assertEqual + + # Single-field rounding. + eq(td(milliseconds=0.4/1000), td(0)) # rounds to 0 + eq(td(milliseconds=-0.4/1000), td(0)) # rounds to 0 + eq(td(milliseconds=0.6/1000), td(microseconds=1)) + eq(td(milliseconds=-0.6/1000), td(microseconds=-1)) + + # Rounding due to contributions from more than one field. + us_per_hour = 3600e6 + us_per_day = us_per_hour * 24 + eq(td(days=.4/us_per_day), td(0)) + eq(td(hours=.2/us_per_hour), td(0)) + eq(td(days=.4/us_per_day, hours=.2/us_per_hour), td(microseconds=1)) + + eq(td(days=-.4/us_per_day), td(0)) + eq(td(hours=-.2/us_per_hour), td(0)) + eq(td(days=-.4/us_per_day, hours=-.2/us_per_hour), td(microseconds=-1)) + + def test_massive_normalization(self): + td = timedelta(microseconds=-1) + self.assertEqual((td.days, td.seconds, td.microseconds), + (-1, 24*3600-1, 999999)) + + def test_bool(self): + self.failUnless(timedelta(1)) + self.failUnless(timedelta(0, 1)) + self.failUnless(timedelta(0, 0, 1)) + self.failUnless(timedelta(microseconds=1)) + self.failUnless(not timedelta(0)) + + def test_subclass_timedelta(self): + + class T(timedelta): + @staticmethod + def from_td(td): + return T(td.days, td.seconds, td.microseconds) + + def as_hours(self): + sum = (self.days * 24 + + self.seconds / 3600.0 + + self.microseconds / 3600e6) + return round(sum) + + t1 = T(days=1) + self.assert_(type(t1) is T) + self.assertEqual(t1.as_hours(), 24) + + t2 = T(days=-1, seconds=-3600) + self.assert_(type(t2) is T) + self.assertEqual(t2.as_hours(), -25) + + t3 = t1 + t2 + self.assert_(type(t3) is timedelta) + t4 = T.from_td(t3) + self.assert_(type(t4) is T) + self.assertEqual(t3.days, t4.days) + self.assertEqual(t3.seconds, t4.seconds) + self.assertEqual(t3.microseconds, t4.microseconds) + self.assertEqual(str(t3), str(t4)) + self.assertEqual(t4.as_hours(), -1) + +############################################################################# +# date tests + +class TestDateOnly(unittest.TestCase): + # Tests here won't pass if also run on datetime objects, so don't + # subclass this to test datetimes too. + + def test_delta_non_days_ignored(self): + dt = date(2000, 1, 2) + delta = timedelta(days=1, hours=2, minutes=3, seconds=4, + microseconds=5) + days = timedelta(delta.days) + self.assertEqual(days, timedelta(1)) + + dt2 = dt + delta + self.assertEqual(dt2, dt + days) + + dt2 = delta + dt + self.assertEqual(dt2, dt + days) + + dt2 = dt - delta + self.assertEqual(dt2, dt - days) + + delta = -delta + days = timedelta(delta.days) + self.assertEqual(days, timedelta(-2)) + + dt2 = dt + delta + self.assertEqual(dt2, dt + days) + + dt2 = delta + dt + self.assertEqual(dt2, dt + days) + + dt2 = dt - delta + self.assertEqual(dt2, dt - days) + +class SubclassDate(date): + sub_var = 1 + +class TestDate(HarmlessMixedComparison, unittest.TestCase): + # Tests here should pass for both dates and datetimes, except for a + # few tests that TestDateTime overrides. + + theclass = date + + def test_basic_attributes(self): + dt = self.theclass(2002, 3, 1) + self.assertEqual(dt.year, 2002) + self.assertEqual(dt.month, 3) + self.assertEqual(dt.day, 1) + + def test_roundtrip(self): + for dt in (self.theclass(1, 2, 3), + self.theclass.today()): + # Verify dt -> string -> date identity. + s = repr(dt) + self.failUnless(s.startswith('datetime.')) + s = s[9:] + dt2 = eval(s) + self.assertEqual(dt, dt2) + + # Verify identity via reconstructing from pieces. + dt2 = self.theclass(dt.year, dt.month, dt.day) + self.assertEqual(dt, dt2) + + def test_ordinal_conversions(self): + # Check some fixed values. + for y, m, d, n in [(1, 1, 1, 1), # calendar origin + (1, 12, 31, 365), + (2, 1, 1, 366), + # first example from "Calendrical Calculations" + (1945, 11, 12, 710347)]: + d = self.theclass(y, m, d) + self.assertEqual(n, d.toordinal()) + fromord = self.theclass.fromordinal(n) + self.assertEqual(d, fromord) + if hasattr(fromord, "hour"): + # if we're checking something fancier than a date, verify + # the extra fields have been zeroed out + self.assertEqual(fromord.hour, 0) + self.assertEqual(fromord.minute, 0) + self.assertEqual(fromord.second, 0) + self.assertEqual(fromord.microsecond, 0) + + # Check first and last days of year spottily across the whole + # range of years supported. + for year in xrange(MINYEAR, MAXYEAR+1, 7): + # Verify (year, 1, 1) -> ordinal -> y, m, d is identity. + d = self.theclass(year, 1, 1) + n = d.toordinal() + d2 = self.theclass.fromordinal(n) + self.assertEqual(d, d2) + # Verify that moving back a day gets to the end of year-1. + if year > 1: + d = self.theclass.fromordinal(n-1) + d2 = self.theclass(year-1, 12, 31) + self.assertEqual(d, d2) + self.assertEqual(d2.toordinal(), n-1) + + # Test every day in a leap-year and a non-leap year. + dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + for year, isleap in (2000, True), (2002, False): + n = self.theclass(year, 1, 1).toordinal() + for month, maxday in zip(range(1, 13), dim): + if month == 2 and isleap: + maxday += 1 + for day in range(1, maxday+1): + d = self.theclass(year, month, day) + self.assertEqual(d.toordinal(), n) + self.assertEqual(d, self.theclass.fromordinal(n)) + n += 1 + + def test_extreme_ordinals(self): + a = self.theclass.min + a = self.theclass(a.year, a.month, a.day) # get rid of time parts + aord = a.toordinal() + b = a.fromordinal(aord) + self.assertEqual(a, b) + + self.assertRaises(ValueError, lambda: a.fromordinal(aord - 1)) + + b = a + timedelta(days=1) + self.assertEqual(b.toordinal(), aord + 1) + self.assertEqual(b, self.theclass.fromordinal(aord + 1)) + + a = self.theclass.max + a = self.theclass(a.year, a.month, a.day) # get rid of time parts + aord = a.toordinal() + b = a.fromordinal(aord) + self.assertEqual(a, b) + + self.assertRaises(ValueError, lambda: a.fromordinal(aord + 1)) + + b = a - timedelta(days=1) + self.assertEqual(b.toordinal(), aord - 1) + self.assertEqual(b, self.theclass.fromordinal(aord - 1)) + + def test_bad_constructor_arguments(self): + # bad years + self.theclass(MINYEAR, 1, 1) # no exception + self.theclass(MAXYEAR, 1, 1) # no exception + self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1) + self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1) + # bad months + self.theclass(2000, 1, 1) # no exception + self.theclass(2000, 12, 1) # no exception + self.assertRaises(ValueError, self.theclass, 2000, 0, 1) + self.assertRaises(ValueError, self.theclass, 2000, 13, 1) + # bad days + self.theclass(2000, 2, 29) # no exception + self.theclass(2004, 2, 29) # no exception + self.theclass(2400, 2, 29) # no exception + self.assertRaises(ValueError, self.theclass, 2000, 2, 30) + self.assertRaises(ValueError, self.theclass, 2001, 2, 29) + self.assertRaises(ValueError, self.theclass, 2100, 2, 29) + self.assertRaises(ValueError, self.theclass, 1900, 2, 29) + self.assertRaises(ValueError, self.theclass, 2000, 1, 0) + self.assertRaises(ValueError, self.theclass, 2000, 1, 32) + + def test_hash_equality(self): + d = self.theclass(2000, 12, 31) + # same thing + e = self.theclass(2000, 12, 31) + self.assertEqual(d, e) + self.assertEqual(hash(d), hash(e)) + + dic = {d: 1} + dic[e] = 2 + self.assertEqual(len(dic), 1) + self.assertEqual(dic[d], 2) + self.assertEqual(dic[e], 2) + + d = self.theclass(2001, 1, 1) + # same thing + e = self.theclass(2001, 1, 1) + self.assertEqual(d, e) + self.assertEqual(hash(d), hash(e)) + + dic = {d: 1} + dic[e] = 2 + self.assertEqual(len(dic), 1) + self.assertEqual(dic[d], 2) + self.assertEqual(dic[e], 2) + + def test_computations(self): + a = self.theclass(2002, 1, 31) + b = self.theclass(1956, 1, 31) + + diff = a-b + self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4))) + self.assertEqual(diff.seconds, 0) + self.assertEqual(diff.microseconds, 0) + + day = timedelta(1) + week = timedelta(7) + a = self.theclass(2002, 3, 2) + self.assertEqual(a + day, self.theclass(2002, 3, 3)) + self.assertEqual(day + a, self.theclass(2002, 3, 3)) + self.assertEqual(a - day, self.theclass(2002, 3, 1)) + self.assertEqual(-day + a, self.theclass(2002, 3, 1)) + self.assertEqual(a + week, self.theclass(2002, 3, 9)) + self.assertEqual(a - week, self.theclass(2002, 2, 23)) + self.assertEqual(a + 52*week, self.theclass(2003, 3, 1)) + self.assertEqual(a - 52*week, self.theclass(2001, 3, 3)) + self.assertEqual((a + week) - a, week) + self.assertEqual((a + day) - a, day) + self.assertEqual((a - week) - a, -week) + self.assertEqual((a - day) - a, -day) + self.assertEqual(a - (a + week), -week) + self.assertEqual(a - (a + day), -day) + self.assertEqual(a - (a - week), week) + self.assertEqual(a - (a - day), day) + + # Add/sub ints, longs, floats should be illegal + for i in 1, 1L, 1.0: + self.assertRaises(TypeError, lambda: a+i) + self.assertRaises(TypeError, lambda: a-i) + self.assertRaises(TypeError, lambda: i+a) + self.assertRaises(TypeError, lambda: i-a) + + # delta - date is senseless. + self.assertRaises(TypeError, lambda: day - a) + # mixing date and (delta or date) via * or // is senseless + self.assertRaises(TypeError, lambda: day * a) + self.assertRaises(TypeError, lambda: a * day) + self.assertRaises(TypeError, lambda: day // a) + self.assertRaises(TypeError, lambda: a // day) + self.assertRaises(TypeError, lambda: a * a) + self.assertRaises(TypeError, lambda: a // a) + # date + date is senseless + self.assertRaises(TypeError, lambda: a + a) + + def test_overflow(self): + tiny = self.theclass.resolution + + for delta in [tiny, timedelta(1), timedelta(2)]: + dt = self.theclass.min + delta + dt -= delta # no problem + self.assertRaises(OverflowError, dt.__sub__, delta) + self.assertRaises(OverflowError, dt.__add__, -delta) + + dt = self.theclass.max - delta + dt += delta # no problem + self.assertRaises(OverflowError, dt.__add__, delta) + self.assertRaises(OverflowError, dt.__sub__, -delta) + + def test_fromtimestamp(self): + import time + + # Try an arbitrary fixed value. + year, month, day = 1999, 9, 19 + ts = time.mktime((year, month, day, 0, 0, 0, 0, 0, -1)) + d = self.theclass.fromtimestamp(ts) + self.assertEqual(d.year, year) + self.assertEqual(d.month, month) + self.assertEqual(d.day, day) + + def test_insane_fromtimestamp(self): + # It's possible that some platform maps time_t to double, + # and that this test will fail there. This test should + # exempt such platforms (provided they return reasonable + # results!). + for insane in -1e200, 1e200: + self.assertRaises(ValueError, self.theclass.fromtimestamp, + insane) + + def test_today(self): + import time + + # We claim that today() is like fromtimestamp(time.time()), so + # prove it. + for dummy in range(3): + today = self.theclass.today() + ts = time.time() + todayagain = self.theclass.fromtimestamp(ts) + if today == todayagain: + break + # There are several legit reasons that could fail: + # 1. It recently became midnight, between the today() and the + # time() calls. + # 2. The platform time() has such fine resolution that we'll + # never get the same value twice. + # 3. The platform time() has poor resolution, and we just + # happened to call today() right before a resolution quantum + # boundary. + # 4. The system clock got fiddled between calls. + # In any case, wait a little while and try again. + time.sleep(0.1) + + # It worked or it didn't. If it didn't, assume it's reason #2, and + # let the test pass if they're within half a second of each other. + self.failUnless(today == todayagain or + abs(todayagain - today) < timedelta(seconds=0.5)) + + def test_weekday(self): + for i in range(7): + # March 4, 2002 is a Monday + self.assertEqual(self.theclass(2002, 3, 4+i).weekday(), i) + self.assertEqual(self.theclass(2002, 3, 4+i).isoweekday(), i+1) + # January 2, 1956 is a Monday + self.assertEqual(self.theclass(1956, 1, 2+i).weekday(), i) + self.assertEqual(self.theclass(1956, 1, 2+i).isoweekday(), i+1) + + def test_isocalendar(self): + # Check examples from + # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm + for i in range(7): + d = self.theclass(2003, 12, 22+i) + self.assertEqual(d.isocalendar(), (2003, 52, i+1)) + d = self.theclass(2003, 12, 29) + timedelta(i) + self.assertEqual(d.isocalendar(), (2004, 1, i+1)) + d = self.theclass(2004, 1, 5+i) + self.assertEqual(d.isocalendar(), (2004, 2, i+1)) + d = self.theclass(2009, 12, 21+i) + self.assertEqual(d.isocalendar(), (2009, 52, i+1)) + d = self.theclass(2009, 12, 28) + timedelta(i) + self.assertEqual(d.isocalendar(), (2009, 53, i+1)) + d = self.theclass(2010, 1, 4+i) + self.assertEqual(d.isocalendar(), (2010, 1, i+1)) + + def test_iso_long_years(self): + # Calculate long ISO years and compare to table from + # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm + ISO_LONG_YEARS_TABLE = """ + 4 32 60 88 + 9 37 65 93 + 15 43 71 99 + 20 48 76 + 26 54 82 + + 105 133 161 189 + 111 139 167 195 + 116 144 172 + 122 150 178 + 128 156 184 + + 201 229 257 285 + 207 235 263 291 + 212 240 268 296 + 218 246 274 + 224 252 280 + + 303 331 359 387 + 308 336 364 392 + 314 342 370 398 + 320 348 376 + 325 353 381 + """ + iso_long_years = map(int, ISO_LONG_YEARS_TABLE.split()) + iso_long_years.sort() + L = [] + for i in range(400): + d = self.theclass(2000+i, 12, 31) + d1 = self.theclass(1600+i, 12, 31) + self.assertEqual(d.isocalendar()[1:], d1.isocalendar()[1:]) + if d.isocalendar()[1] == 53: + L.append(i) + self.assertEqual(L, iso_long_years) + + def test_isoformat(self): + t = self.theclass(2, 3, 2) + self.assertEqual(t.isoformat(), "0002-03-02") + + def test_ctime(self): + t = self.theclass(2002, 3, 2) + self.assertEqual(t.ctime(), "Sat Mar 2 00:00:00 2002") + + def test_strftime(self): + t = self.theclass(2005, 3, 2) + self.assertEqual(t.strftime("m:%m d:%d y:%y"), "m:03 d:02 y:05") + self.assertEqual(t.strftime(""), "") # SF bug #761337 + self.assertEqual(t.strftime('x'*1000), 'x'*1000) # SF bug #1556784 + + self.assertRaises(TypeError, t.strftime) # needs an arg + self.assertRaises(TypeError, t.strftime, "one", "two") # too many args + self.assertRaises(TypeError, t.strftime, 42) # arg wrong type + + # test that unicode input is allowed (issue 2782) + self.assertEqual(t.strftime(u"%m"), "03") + + # A naive object replaces %z and %Z w/ empty strings. + self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''") + + #make sure that invalid format specifiers are handled correctly + #self.assertRaises(ValueError, t.strftime, "%e") + #self.assertRaises(ValueError, t.strftime, "%") + #self.assertRaises(ValueError, t.strftime, "%#") + + #oh well, some systems just ignore those invalid ones. + #at least, excercise them to make sure that no crashes + #are generated + for f in ["%e", "%", "%#"]: + try: + t.strftime(f) + except ValueError: + pass + + #check that this standard extension works + t.strftime("%f") + + + def test_format(self): + dt = self.theclass(2007, 9, 10) + self.assertEqual(dt.__format__(''), str(dt)) + + # check that a derived class's __str__() gets called + class A(self.theclass): + def __str__(self): + return 'A' + a = A(2007, 9, 10) + self.assertEqual(a.__format__(''), 'A') + + # check that a derived class's strftime gets called + class B(self.theclass): + def strftime(self, format_spec): + return 'B' + b = B(2007, 9, 10) + self.assertEqual(b.__format__(''), str(dt)) + + for fmt in ["m:%m d:%d y:%y", + "m:%m d:%d y:%y H:%H M:%M S:%S", + "%z %Z", + ]: + self.assertEqual(dt.__format__(fmt), dt.strftime(fmt)) + self.assertEqual(a.__format__(fmt), dt.strftime(fmt)) + self.assertEqual(b.__format__(fmt), 'B') + + def test_resolution_info(self): + self.assert_(isinstance(self.theclass.min, self.theclass)) + self.assert_(isinstance(self.theclass.max, self.theclass)) + self.assert_(isinstance(self.theclass.resolution, timedelta)) + self.assert_(self.theclass.max > self.theclass.min) + + def test_extreme_timedelta(self): + big = self.theclass.max - self.theclass.min + # 3652058 days, 23 hours, 59 minutes, 59 seconds, 999999 microseconds + n = (big.days*24*3600 + big.seconds)*1000000 + big.microseconds + # n == 315537897599999999 ~= 2**58.13 + justasbig = timedelta(0, 0, n) + self.assertEqual(big, justasbig) + self.assertEqual(self.theclass.min + big, self.theclass.max) + self.assertEqual(self.theclass.max - big, self.theclass.min) + + def test_timetuple(self): + for i in range(7): + # January 2, 1956 is a Monday (0) + d = self.theclass(1956, 1, 2+i) + t = d.timetuple() + self.assertEqual(t, (1956, 1, 2+i, 0, 0, 0, i, 2+i, -1)) + # February 1, 1956 is a Wednesday (2) + d = self.theclass(1956, 2, 1+i) + t = d.timetuple() + self.assertEqual(t, (1956, 2, 1+i, 0, 0, 0, (2+i)%7, 32+i, -1)) + # March 1, 1956 is a Thursday (3), and is the 31+29+1 = 61st day + # of the year. + d = self.theclass(1956, 3, 1+i) + t = d.timetuple() + self.assert... [truncated message content] |
From: <pj...@us...> - 2011-03-14 03:06:51
|
Revision: 7231 http://jython.svn.sourceforge.net/jython/?rev=7231&view=rev Author: pjenvey Date: 2011-03-14 03:06:43 +0000 (Mon, 14 Mar 2011) Log Message: ----------- stock from CPythonLib and not needed Removed Paths: ------------- trunk/jython/Lib/test/output/test_global trunk/jython/Lib/test/test_base64.py trunk/jython/Lib/test/test_contextlib.py trunk/jython/Lib/test/test_email.py trunk/jython/Lib/test/test_email_renamed.py trunk/jython/Lib/test/test_gettext.py trunk/jython/Lib/test/test_global.py trunk/jython/Lib/test/test_wsgiref.py Deleted: trunk/jython/Lib/test/output/test_global =================================================================== --- trunk/jython/Lib/test/output/test_global 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/output/test_global 2011-03-14 03:06:43 UTC (rev 7231) @@ -1 +0,0 @@ -test_global Deleted: trunk/jython/Lib/test/test_base64.py =================================================================== --- trunk/jython/Lib/test/test_base64.py 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/test_base64.py 2011-03-14 03:06:43 UTC (rev 7231) @@ -1,190 +0,0 @@ -import unittest -from test import test_support -import base64 - - - -class LegacyBase64TestCase(unittest.TestCase): - def test_encodestring(self): - eq = self.assertEqual - eq(base64.encodestring("www.python.org"), "d3d3LnB5dGhvbi5vcmc=\n") - eq(base64.encodestring("a"), "YQ==\n") - eq(base64.encodestring("ab"), "YWI=\n") - eq(base64.encodestring("abc"), "YWJj\n") - eq(base64.encodestring(""), "") - eq(base64.encodestring("abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "0123456789!@#0^&*();:<>,. []{}"), - "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" - "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" - "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n") - - def test_decodestring(self): - eq = self.assertEqual - eq(base64.decodestring("d3d3LnB5dGhvbi5vcmc=\n"), "www.python.org") - eq(base64.decodestring("YQ==\n"), "a") - eq(base64.decodestring("YWI=\n"), "ab") - eq(base64.decodestring("YWJj\n"), "abc") - eq(base64.decodestring("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" - "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" - "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n"), - "abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "0123456789!@#0^&*();:<>,. []{}") - eq(base64.decodestring(''), '') - - def test_encode(self): - eq = self.assertEqual - from cStringIO import StringIO - infp = StringIO('abcdefghijklmnopqrstuvwxyz' - 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' - '0123456789!@#0^&*();:<>,. []{}') - outfp = StringIO() - base64.encode(infp, outfp) - eq(outfp.getvalue(), - 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' - 'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT' - 'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n') - - def test_decode(self): - from cStringIO import StringIO - infp = StringIO('d3d3LnB5dGhvbi5vcmc=') - outfp = StringIO() - base64.decode(infp, outfp) - self.assertEqual(outfp.getvalue(), 'www.python.org') - - - -class BaseXYTestCase(unittest.TestCase): - def test_b64encode(self): - eq = self.assertEqual - # Test default alphabet - eq(base64.b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=") - eq(base64.b64encode('\x00'), 'AA==') - eq(base64.b64encode("a"), "YQ==") - eq(base64.b64encode("ab"), "YWI=") - eq(base64.b64encode("abc"), "YWJj") - eq(base64.b64encode(""), "") - eq(base64.b64encode("abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "0123456789!@#0^&*();:<>,. []{}"), - "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" - "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" - "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==") - # Test with arbitrary alternative characters - eq(base64.b64encode('\xd3V\xbeo\xf7\x1d', altchars='*$'), '01a*b$cd') - # Test standard alphabet - eq(base64.standard_b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=") - eq(base64.standard_b64encode("a"), "YQ==") - eq(base64.standard_b64encode("ab"), "YWI=") - eq(base64.standard_b64encode("abc"), "YWJj") - eq(base64.standard_b64encode(""), "") - eq(base64.standard_b64encode("abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "0123456789!@#0^&*();:<>,. []{}"), - "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" - "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" - "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==") - # Test with 'URL safe' alternative characters - eq(base64.urlsafe_b64encode('\xd3V\xbeo\xf7\x1d'), '01a-b_cd') - - def test_b64decode(self): - eq = self.assertEqual - eq(base64.b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") - eq(base64.b64decode('AA=='), '\x00') - eq(base64.b64decode("YQ=="), "a") - eq(base64.b64decode("YWI="), "ab") - eq(base64.b64decode("YWJj"), "abc") - eq(base64.b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" - "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" - "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), - "abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "0123456789!@#0^&*();:<>,. []{}") - eq(base64.b64decode(''), '') - # Test with arbitrary alternative characters - eq(base64.b64decode('01a*b$cd', altchars='*$'), '\xd3V\xbeo\xf7\x1d') - # Test standard alphabet - eq(base64.standard_b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") - eq(base64.standard_b64decode("YQ=="), "a") - eq(base64.standard_b64decode("YWI="), "ab") - eq(base64.standard_b64decode("YWJj"), "abc") - eq(base64.standard_b64decode(""), "") - eq(base64.standard_b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" - "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" - "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), - "abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "0123456789!@#0^&*();:<>,. []{}") - # Test with 'URL safe' alternative characters - eq(base64.urlsafe_b64decode('01a-b_cd'), '\xd3V\xbeo\xf7\x1d') - - def test_b64decode_error(self): - self.assertRaises(TypeError, base64.b64decode, 'abc') - - def test_b32encode(self): - eq = self.assertEqual - eq(base64.b32encode(''), '') - eq(base64.b32encode('\x00'), 'AA======') - eq(base64.b32encode('a'), 'ME======') - eq(base64.b32encode('ab'), 'MFRA====') - eq(base64.b32encode('abc'), 'MFRGG===') - eq(base64.b32encode('abcd'), 'MFRGGZA=') - eq(base64.b32encode('abcde'), 'MFRGGZDF') - - def test_b32decode(self): - eq = self.assertEqual - eq(base64.b32decode(''), '') - eq(base64.b32decode('AA======'), '\x00') - eq(base64.b32decode('ME======'), 'a') - eq(base64.b32decode('MFRA===='), 'ab') - eq(base64.b32decode('MFRGG==='), 'abc') - eq(base64.b32decode('MFRGGZA='), 'abcd') - eq(base64.b32decode('MFRGGZDF'), 'abcde') - - def test_b32decode_casefold(self): - eq = self.assertEqual - eq(base64.b32decode('', True), '') - eq(base64.b32decode('ME======', True), 'a') - eq(base64.b32decode('MFRA====', True), 'ab') - eq(base64.b32decode('MFRGG===', True), 'abc') - eq(base64.b32decode('MFRGGZA=', True), 'abcd') - eq(base64.b32decode('MFRGGZDF', True), 'abcde') - # Lower cases - eq(base64.b32decode('me======', True), 'a') - eq(base64.b32decode('mfra====', True), 'ab') - eq(base64.b32decode('mfrgg===', True), 'abc') - eq(base64.b32decode('mfrggza=', True), 'abcd') - eq(base64.b32decode('mfrggzdf', True), 'abcde') - # Expected exceptions - self.assertRaises(TypeError, base64.b32decode, 'me======') - # Mapping zero and one - eq(base64.b32decode('MLO23456'), 'b\xdd\xad\xf3\xbe') - eq(base64.b32decode('M1023456', map01='L'), 'b\xdd\xad\xf3\xbe') - eq(base64.b32decode('M1023456', map01='I'), 'b\x1d\xad\xf3\xbe') - - def test_b32decode_error(self): - self.assertRaises(TypeError, base64.b32decode, 'abc') - self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==') - - def test_b16encode(self): - eq = self.assertEqual - eq(base64.b16encode('\x01\x02\xab\xcd\xef'), '0102ABCDEF') - eq(base64.b16encode('\x00'), '00') - - def test_b16decode(self): - eq = self.assertEqual - eq(base64.b16decode('0102ABCDEF'), '\x01\x02\xab\xcd\xef') - eq(base64.b16decode('00'), '\x00') - # Lower case is not allowed without a flag - self.assertRaises(TypeError, base64.b16decode, '0102abcdef') - # Case fold - eq(base64.b16decode('0102abcdef', True), '\x01\x02\xab\xcd\xef') - - - -def test_main(): - test_support.run_unittest(__name__) - -if __name__ == '__main__': - test_main() Deleted: trunk/jython/Lib/test/test_contextlib.py =================================================================== --- trunk/jython/Lib/test/test_contextlib.py 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/test_contextlib.py 2011-03-14 03:06:43 UTC (rev 7231) @@ -1,337 +0,0 @@ -"""Unit tests for contextlib.py, and other context managers.""" - -import sys -import os -import decimal -import tempfile -import unittest -import threading -from contextlib import * # Tests __all__ -from test import test_support - -class ContextManagerTestCase(unittest.TestCase): - - def test_contextmanager_plain(self): - state = [] - @contextmanager - def woohoo(): - state.append(1) - yield 42 - state.append(999) - with woohoo() as x: - self.assertEqual(state, [1]) - self.assertEqual(x, 42) - state.append(x) - self.assertEqual(state, [1, 42, 999]) - - def test_contextmanager_finally(self): - state = [] - @contextmanager - def woohoo(): - state.append(1) - try: - yield 42 - finally: - state.append(999) - try: - with woohoo() as x: - self.assertEqual(state, [1]) - self.assertEqual(x, 42) - state.append(x) - raise ZeroDivisionError() - except ZeroDivisionError: - pass - else: - self.fail("Expected ZeroDivisionError") - self.assertEqual(state, [1, 42, 999]) - - def test_contextmanager_no_reraise(self): - @contextmanager - def whee(): - yield - ctx = whee() - ctx.__enter__() - # Calling __exit__ should not result in an exception - self.failIf(ctx.__exit__(TypeError, TypeError("foo"), None)) - - def test_contextmanager_trap_yield_after_throw(self): - @contextmanager - def whoo(): - try: - yield - except: - yield - ctx = whoo() - ctx.__enter__() - self.assertRaises( - RuntimeError, ctx.__exit__, TypeError, TypeError("foo"), None - ) - - def test_contextmanager_except(self): - state = [] - @contextmanager - def woohoo(): - state.append(1) - try: - yield 42 - except ZeroDivisionError, e: - state.append(e.args[0]) - self.assertEqual(state, [1, 42, 999]) - with woohoo() as x: - self.assertEqual(state, [1]) - self.assertEqual(x, 42) - state.append(x) - raise ZeroDivisionError(999) - self.assertEqual(state, [1, 42, 999]) - - def test_contextmanager_attribs(self): - def attribs(**kw): - def decorate(func): - for k,v in kw.items(): - setattr(func,k,v) - return func - return decorate - @contextmanager - @attribs(foo='bar') - def baz(spam): - """Whee!""" - self.assertEqual(baz.__name__,'baz') - self.assertEqual(baz.foo, 'bar') - self.assertEqual(baz.__doc__, "Whee!") - -class NestedTestCase(unittest.TestCase): - - # XXX This needs more work - - def test_nested(self): - @contextmanager - def a(): - yield 1 - @contextmanager - def b(): - yield 2 - @contextmanager - def c(): - yield 3 - with nested(a(), b(), c()) as (x, y, z): - self.assertEqual(x, 1) - self.assertEqual(y, 2) - self.assertEqual(z, 3) - - def test_nested_cleanup(self): - state = [] - @contextmanager - def a(): - state.append(1) - try: - yield 2 - finally: - state.append(3) - @contextmanager - def b(): - state.append(4) - try: - yield 5 - finally: - state.append(6) - try: - with nested(a(), b()) as (x, y): - state.append(x) - state.append(y) - 1 // 0 - except ZeroDivisionError: - self.assertEqual(state, [1, 4, 2, 5, 6, 3]) - else: - self.fail("Didn't raise ZeroDivisionError") - - def test_nested_right_exception(self): - state = [] - @contextmanager - def a(): - yield 1 - class b(object): - def __enter__(self): - return 2 - def __exit__(self, *exc_info): - try: - raise Exception() - except: - pass - try: - with nested(a(), b()) as (x, y): - 1 // 0 - except ZeroDivisionError: - self.assertEqual((x, y), (1, 2)) - except Exception: - self.fail("Reraised wrong exception") - else: - self.fail("Didn't raise ZeroDivisionError") - - def test_nested_b_swallows(self): - @contextmanager - def a(): - yield - @contextmanager - def b(): - try: - yield - except: - # Swallow the exception - pass - try: - with nested(a(), b()): - 1 // 0 - except ZeroDivisionError: - self.fail("Didn't swallow ZeroDivisionError") - - def test_nested_break(self): - @contextmanager - def a(): - yield - state = 0 - while True: - state += 1 - with nested(a(), a()): - break - state += 10 - self.assertEqual(state, 1) - - def test_nested_continue(self): - @contextmanager - def a(): - yield - state = 0 - while state < 3: - state += 1 - with nested(a(), a()): - continue - state += 10 - self.assertEqual(state, 3) - - def test_nested_return(self): - @contextmanager - def a(): - try: - yield - except: - pass - def foo(): - with nested(a(), a()): - return 1 - return 10 - self.assertEqual(foo(), 1) - -class ClosingTestCase(unittest.TestCase): - - # XXX This needs more work - - def test_closing(self): - state = [] - class C: - def close(self): - state.append(1) - x = C() - self.assertEqual(state, []) - with closing(x) as y: - self.assertEqual(x, y) - self.assertEqual(state, [1]) - - def test_closing_error(self): - state = [] - class C: - def close(self): - state.append(1) - x = C() - self.assertEqual(state, []) - try: - with closing(x) as y: - self.assertEqual(x, y) - 1 // 0 - except ZeroDivisionError: - self.assertEqual(state, [1]) - else: - self.fail("Didn't raise ZeroDivisionError") - -class FileContextTestCase(unittest.TestCase): - - def testWithOpen(self): - tfn = tempfile.mktemp() - try: - f = None - with open(tfn, "w") as f: - self.failIf(f.closed) - f.write("Booh\n") - self.failUnless(f.closed) - f = None - try: - with open(tfn, "r") as f: - self.failIf(f.closed) - self.assertEqual(f.read(), "Booh\n") - 1 // 0 - except ZeroDivisionError: - self.failUnless(f.closed) - else: - self.fail("Didn't raise ZeroDivisionError") - finally: - try: - os.remove(tfn) - except os.error: - pass - -class LockContextTestCase(unittest.TestCase): - - def boilerPlate(self, lock, locked): - self.failIf(locked()) - with lock: - self.failUnless(locked()) - self.failIf(locked()) - try: - with lock: - self.failUnless(locked()) - 1 // 0 - except ZeroDivisionError: - self.failIf(locked()) - else: - self.fail("Didn't raise ZeroDivisionError") - - def testWithLock(self): - lock = threading.Lock() - self.boilerPlate(lock, lock.locked) - - def testWithRLock(self): - lock = threading.RLock() - self.boilerPlate(lock, lock._is_owned) - - def testWithCondition(self): - lock = threading.Condition() - def locked(): - return lock._is_owned() - self.boilerPlate(lock, locked) - - def testWithSemaphore(self): - lock = threading.Semaphore() - def locked(): - if lock.acquire(False): - lock.release() - return False - else: - return True - self.boilerPlate(lock, locked) - - def testWithBoundedSemaphore(self): - lock = threading.BoundedSemaphore() - def locked(): - if lock.acquire(False): - lock.release() - return False - else: - return True - self.boilerPlate(lock, locked) - -# This is needed to make the test actually run under regrtest.py! -def test_main(): - test_support.run_unittest(__name__) - - -if __name__ == "__main__": - test_main() Deleted: trunk/jython/Lib/test/test_email.py =================================================================== --- trunk/jython/Lib/test/test_email.py 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/test_email.py 2011-03-14 03:06:43 UTC (rev 7231) @@ -1,12 +0,0 @@ -# Copyright (C) 2001,2002 Python Software Foundation -# email package unit tests - -# The specific tests now live in Lib/email/test -from email.test.test_email import suite -from test import test_support - -def test_main(): - test_support.run_unittest(suite()) - -if __name__ == '__main__': - test_main() Deleted: trunk/jython/Lib/test/test_email_renamed.py =================================================================== --- trunk/jython/Lib/test/test_email_renamed.py 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/test_email_renamed.py 2011-03-14 03:06:43 UTC (rev 7231) @@ -1,12 +0,0 @@ -# Copyright (C) 2001-2006 Python Software Foundation -# email package unit tests - -# The specific tests now live in Lib/email/test -from email.test.test_email_renamed import suite -from test import test_support - -def test_main(): - test_support.run_unittest(suite()) - -if __name__ == '__main__': - test_main() Deleted: trunk/jython/Lib/test/test_gettext.py =================================================================== --- trunk/jython/Lib/test/test_gettext.py 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/test_gettext.py 2011-03-14 03:06:43 UTC (rev 7231) @@ -1,447 +0,0 @@ -import os -import base64 -import shutil -import gettext -import unittest - -from test import test_support - - -# TODO: -# - Add new tests, for example for "dgettext" -# - Remove dummy tests, for example testing for single and double quotes -# has no sense, it would have if we were testing a parser (i.e. pygettext) -# - Tests should have only one assert. - -GNU_MO_DATA = '''\ -3hIElQAAAAAGAAAAHAAAAEwAAAALAAAAfAAAAAAAAACoAAAAFQAAAKkAAAAjAAAAvwAAAKEAAADj -AAAABwAAAIUBAAALAAAAjQEAAEUBAACZAQAAFgAAAN8CAAAeAAAA9gIAAKEAAAAVAwAABQAAALcD -AAAJAAAAvQMAAAEAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABQAAAAYAAAACAAAAAFJh -eW1vbmQgTHV4dXJ5IFlhY2gtdABUaGVyZSBpcyAlcyBmaWxlAFRoZXJlIGFyZSAlcyBmaWxlcwBU -aGlzIG1vZHVsZSBwcm92aWRlcyBpbnRlcm5hdGlvbmFsaXphdGlvbiBhbmQgbG9jYWxpemF0aW9u -CnN1cHBvcnQgZm9yIHlvdXIgUHl0aG9uIHByb2dyYW1zIGJ5IHByb3ZpZGluZyBhbiBpbnRlcmZh -Y2UgdG8gdGhlIEdOVQpnZXR0ZXh0IG1lc3NhZ2UgY2F0YWxvZyBsaWJyYXJ5LgBtdWxsdXNrAG51 -ZGdlIG51ZGdlAFByb2plY3QtSWQtVmVyc2lvbjogMi4wClBPLVJldmlzaW9uLURhdGU6IDIwMDAt -MDgtMjkgMTI6MTktMDQ6MDAKTGFzdC1UcmFuc2xhdG9yOiBKLiBEYXZpZCBJYsOhw7FleiA8ai1k -YXZpZEBub29zLmZyPgpMYW5ndWFnZS1UZWFtOiBYWCA8cHl0aG9uLWRldkBweXRob24ub3JnPgpN -SU1FLVZlcnNpb246IDEuMApDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9aXNvLTg4 -NTktMQpDb250ZW50LVRyYW5zZmVyLUVuY29kaW5nOiBub25lCkdlbmVyYXRlZC1CeTogcHlnZXR0 -ZXh0LnB5IDEuMQpQbHVyYWwtRm9ybXM6IG5wbHVyYWxzPTI7IHBsdXJhbD1uIT0xOwoAVGhyb2F0 -d29iYmxlciBNYW5ncm92ZQBIYXkgJXMgZmljaGVybwBIYXkgJXMgZmljaGVyb3MAR3V2ZiB6YnFo -eXIgY2ViaXZxcmYgdmFncmVhbmd2YmFueXZtbmd2YmEgbmFxIHlicG55dm1uZ3ZiYQpmaGNjYmVn -IHNiZSBsYmhlIENsZ3ViYSBjZWJ0ZW56ZiBvbCBjZWJpdnF2YXQgbmEgdmFncmVzbnByIGdiIGd1 -ciBUQUgKdHJnZ3JrZyB6cmZmbnRyIHBuZ255YnQgeXZvZW5lbC4AYmFjb24Ad2luayB3aW5rAA== -''' - -UMO_DATA = '''\ -3hIElQAAAAACAAAAHAAAACwAAAAFAAAAPAAAAAAAAABQAAAABAAAAFEAAAAPAQAAVgAAAAQAAABm -AQAAAQAAAAIAAAAAAAAAAAAAAAAAAAAAYWLDngBQcm9qZWN0LUlkLVZlcnNpb246IDIuMApQTy1S -ZXZpc2lvbi1EYXRlOiAyMDAzLTA0LTExIDEyOjQyLTA0MDAKTGFzdC1UcmFuc2xhdG9yOiBCYXJy -eSBBLiBXQXJzYXcgPGJhcnJ5QHB5dGhvbi5vcmc+Ckxhbmd1YWdlLVRlYW06IFhYIDxweXRob24t -ZGV2QHB5dGhvbi5vcmc+Ck1JTUUtVmVyc2lvbjogMS4wCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFp -bjsgY2hhcnNldD11dGYtOApDb250ZW50LVRyYW5zZmVyLUVuY29kaW5nOiA3Yml0CkdlbmVyYXRl -ZC1CeTogbWFudWFsbHkKAMKkeXoA -''' - -MMO_DATA = '''\ -3hIElQAAAAABAAAAHAAAACQAAAADAAAALAAAAAAAAAA4AAAAeAEAADkAAAABAAAAAAAAAAAAAAAA -UHJvamVjdC1JZC1WZXJzaW9uOiBObyBQcm9qZWN0IDAuMApQT1QtQ3JlYXRpb24tRGF0ZTogV2Vk -IERlYyAxMSAwNzo0NDoxNSAyMDAyClBPLVJldmlzaW9uLURhdGU6IDIwMDItMDgtMTQgMDE6MTg6 -NTgrMDA6MDAKTGFzdC1UcmFuc2xhdG9yOiBKb2huIERvZSA8amRvZUBleGFtcGxlLmNvbT4KSmFu -ZSBGb29iYXIgPGpmb29iYXJAZXhhbXBsZS5jb20+Ckxhbmd1YWdlLVRlYW06IHh4IDx4eEBleGFt -cGxlLmNvbT4KTUlNRS1WZXJzaW9uOiAxLjAKQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFy -c2V0PWlzby04ODU5LTE1CkNvbnRlbnQtVHJhbnNmZXItRW5jb2Rpbmc6IHF1b3RlZC1wcmludGFi -bGUKR2VuZXJhdGVkLUJ5OiBweWdldHRleHQucHkgMS4zCgA= -''' - -LOCALEDIR = os.path.join('xx', 'LC_MESSAGES') -MOFILE = os.path.join(LOCALEDIR, 'gettext.mo') -UMOFILE = os.path.join(LOCALEDIR, 'ugettext.mo') -MMOFILE = os.path.join(LOCALEDIR, 'metadata.mo') -try: - LANG = os.environ['LANGUAGE'] -except: - LANG = 'en' - - -class GettextBaseTest(unittest.TestCase): - def setUp(self): - if not os.path.isdir(LOCALEDIR): - os.makedirs(LOCALEDIR) - fp = open(MOFILE, 'wb') - fp.write(base64.decodestring(GNU_MO_DATA)) - fp.close() - fp = open(UMOFILE, 'wb') - fp.write(base64.decodestring(UMO_DATA)) - fp.close() - fp = open(MMOFILE, 'wb') - fp.write(base64.decodestring(MMO_DATA)) - fp.close() - os.environ['LANGUAGE'] = 'xx' - - def tearDown(self): - os.environ['LANGUAGE'] = LANG - shutil.rmtree(os.path.split(LOCALEDIR)[0]) - - -class GettextTestCase1(GettextBaseTest): - def setUp(self): - GettextBaseTest.setUp(self) - self.localedir = os.curdir - self.mofile = MOFILE - gettext.install('gettext', self.localedir) - - def test_some_translations(self): - eq = self.assertEqual - # test some translations - eq(_('albatross'), 'albatross') - eq(_(u'mullusk'), 'bacon') - eq(_(r'Raymond Luxury Yach-t'), 'Throatwobbler Mangrove') - eq(_(ur'nudge nudge'), 'wink wink') - - def test_double_quotes(self): - eq = self.assertEqual - # double quotes - eq(_("albatross"), 'albatross') - eq(_(u"mullusk"), 'bacon') - eq(_(r"Raymond Luxury Yach-t"), 'Throatwobbler Mangrove') - eq(_(ur"nudge nudge"), 'wink wink') - - def test_triple_single_quotes(self): - eq = self.assertEqual - # triple single quotes - eq(_('''albatross'''), 'albatross') - eq(_(u'''mullusk'''), 'bacon') - eq(_(r'''Raymond Luxury Yach-t'''), 'Throatwobbler Mangrove') - eq(_(ur'''nudge nudge'''), 'wink wink') - - def test_triple_double_quotes(self): - eq = self.assertEqual - # triple double quotes - eq(_("""albatross"""), 'albatross') - eq(_(u"""mullusk"""), 'bacon') - eq(_(r"""Raymond Luxury Yach-t"""), 'Throatwobbler Mangrove') - eq(_(ur"""nudge nudge"""), 'wink wink') - - def test_multiline_strings(self): - eq = self.assertEqual - # multiline strings - eq(_('''This module provides internationalization and localization -support for your Python programs by providing an interface to the GNU -gettext message catalog library.'''), - '''Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba -fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH -trggrkg zrffntr pngnybt yvoenel.''') - - def test_the_alternative_interface(self): - eq = self.assertEqual - # test the alternative interface - fp = open(self.mofile, 'rb') - t = gettext.GNUTranslations(fp) - fp.close() - # Install the translation object - t.install() - eq(_('nudge nudge'), 'wink wink') - # Try unicode return type - t.install(unicode=True) - eq(_('mullusk'), 'bacon') - # Test installation of other methods - import __builtin__ - t.install(unicode=True, names=["gettext", "lgettext"]) - eq(_, t.ugettext) - eq(__builtin__.gettext, t.ugettext) - eq(lgettext, t.lgettext) - del __builtin__.gettext - del __builtin__.lgettext - - -class GettextTestCase2(GettextBaseTest): - def setUp(self): - GettextBaseTest.setUp(self) - self.localedir = os.curdir - # Set up the bindings - gettext.bindtextdomain('gettext', self.localedir) - gettext.textdomain('gettext') - # For convenience - self._ = gettext.gettext - - def test_bindtextdomain(self): - self.assertEqual(gettext.bindtextdomain('gettext'), self.localedir) - - def test_textdomain(self): - self.assertEqual(gettext.textdomain(), 'gettext') - - def test_some_translations(self): - eq = self.assertEqual - # test some translations - eq(self._('albatross'), 'albatross') - eq(self._(u'mullusk'), 'bacon') - eq(self._(r'Raymond Luxury Yach-t'), 'Throatwobbler Mangrove') - eq(self._(ur'nudge nudge'), 'wink wink') - - def test_double_quotes(self): - eq = self.assertEqual - # double quotes - eq(self._("albatross"), 'albatross') - eq(self._(u"mullusk"), 'bacon') - eq(self._(r"Raymond Luxury Yach-t"), 'Throatwobbler Mangrove') - eq(self._(ur"nudge nudge"), 'wink wink') - - def test_triple_single_quotes(self): - eq = self.assertEqual - # triple single quotes - eq(self._('''albatross'''), 'albatross') - eq(self._(u'''mullusk'''), 'bacon') - eq(self._(r'''Raymond Luxury Yach-t'''), 'Throatwobbler Mangrove') - eq(self._(ur'''nudge nudge'''), 'wink wink') - - def test_triple_double_quotes(self): - eq = self.assertEqual - # triple double quotes - eq(self._("""albatross"""), 'albatross') - eq(self._(u"""mullusk"""), 'bacon') - eq(self._(r"""Raymond Luxury Yach-t"""), 'Throatwobbler Mangrove') - eq(self._(ur"""nudge nudge"""), 'wink wink') - - def test_multiline_strings(self): - eq = self.assertEqual - # multiline strings - eq(self._('''This module provides internationalization and localization -support for your Python programs by providing an interface to the GNU -gettext message catalog library.'''), - '''Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba -fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH -trggrkg zrffntr pngnybt yvoenel.''') - - -class PluralFormsTestCase(GettextBaseTest): - def setUp(self): - GettextBaseTest.setUp(self) - self.mofile = MOFILE - - def test_plural_forms1(self): - eq = self.assertEqual - x = gettext.ngettext('There is %s file', 'There are %s files', 1) - eq(x, 'Hay %s fichero') - x = gettext.ngettext('There is %s file', 'There are %s files', 2) - eq(x, 'Hay %s ficheros') - - def test_plural_forms2(self): - eq = self.assertEqual - fp = open(self.mofile, 'rb') - t = gettext.GNUTranslations(fp) - fp.close() - x = t.ngettext('There is %s file', 'There are %s files', 1) - eq(x, 'Hay %s fichero') - x = t.ngettext('There is %s file', 'There are %s files', 2) - eq(x, 'Hay %s ficheros') - - def test_hu(self): - eq = self.assertEqual - f = gettext.c2py('0') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") - - def test_de(self): - eq = self.assertEqual - f = gettext.c2py('n != 1') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "10111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111") - - def test_fr(self): - eq = self.assertEqual - f = gettext.c2py('n>1') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "00111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111") - - def test_gd(self): - eq = self.assertEqual - f = gettext.c2py('n==1 ? 0 : n==2 ? 1 : 2') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "20122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222") - - def test_gd2(self): - eq = self.assertEqual - # Tests the combination of parentheses and "?:" - f = gettext.c2py('n==1 ? 0 : (n==2 ? 1 : 2)') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "20122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222") - - def test_lt(self): - eq = self.assertEqual - f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "20111111112222222222201111111120111111112011111111201111111120111111112011111111201111111120111111112011111111222222222220111111112011111111201111111120111111112011111111201111111120111111112011111111") - - def test_ru(self): - eq = self.assertEqual - f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "20111222222222222222201112222220111222222011122222201112222220111222222011122222201112222220111222222011122222222222222220111222222011122222201112222220111222222011122222201112222220111222222011122222") - - def test_pl(self): - eq = self.assertEqual - f = gettext.c2py('n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "20111222222222222222221112222222111222222211122222221112222222111222222211122222221112222222111222222211122222222222222222111222222211122222221112222222111222222211122222221112222222111222222211122222") - - def test_sl(self): - eq = self.assertEqual - f = gettext.c2py('n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "30122333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333012233333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333") - - def test_security(self): - raises = self.assertRaises - # Test for a dangerous expression - raises(ValueError, gettext.c2py, "os.chmod('/etc/passwd',0777)") - - -class UnicodeTranslationsTest(GettextBaseTest): - def setUp(self): - GettextBaseTest.setUp(self) - fp = open(UMOFILE, 'rb') - try: - self.t = gettext.GNUTranslations(fp) - finally: - fp.close() - self._ = self.t.ugettext - - def test_unicode_msgid(self): - unless = self.failUnless - unless(isinstance(self._(''), unicode)) - unless(isinstance(self._(u''), unicode)) - - def test_unicode_msgstr(self): - eq = self.assertEqual - eq(self._(u'ab\xde'), u'\xa4yz') - - -class WeirdMetadataTest(GettextBaseTest): - def setUp(self): - GettextBaseTest.setUp(self) - fp = open(MMOFILE, 'rb') - try: - try: - self.t = gettext.GNUTranslations(fp) - except: - self.tearDown() - raise - finally: - fp.close() - - def test_weird_metadata(self): - info = self.t.info() - self.assertEqual(info['last-translator'], - 'John Doe <jd...@ex...>\nJane Foobar <jf...@ex...>') - - -def test_main(): - test_support.run_unittest(__name__) - -if __name__ == '__main__': - test_main() - - -# For reference, here's the .po file used to created the GNU_MO_DATA above. -# -# The original version was automatically generated from the sources with -# pygettext. Later it was manually modified to add plural forms support. - -''' -# Dummy translation for the Python test_gettext.py module. -# Copyright (C) 2001 Python Software Foundation -# Barry Warsaw <ba...@py...>, 2000. -# -msgid "" -msgstr "" -"Project-Id-Version: 2.0\n" -"PO-Revision-Date: 2003-04-11 14:32-0400\n" -"Last-Translator: J. David Ibanez <j-...@no...>\n" -"Language-Team: XX <pyt...@py...>\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=iso-8859-1\n" -"Content-Transfer-Encoding: 8bit\n" -"Generated-By: pygettext.py 1.1\n" -"Plural-Forms: nplurals=2; plural=n!=1;\n" - -#: test_gettext.py:19 test_gettext.py:25 test_gettext.py:31 test_gettext.py:37 -#: test_gettext.py:51 test_gettext.py:80 test_gettext.py:86 test_gettext.py:92 -#: test_gettext.py:98 -msgid "nudge nudge" -msgstr "wink wink" - -#: test_gettext.py:16 test_gettext.py:22 test_gettext.py:28 test_gettext.py:34 -#: test_gettext.py:77 test_gettext.py:83 test_gettext.py:89 test_gettext.py:95 -msgid "albatross" -msgstr "" - -#: test_gettext.py:18 test_gettext.py:24 test_gettext.py:30 test_gettext.py:36 -#: test_gettext.py:79 test_gettext.py:85 test_gettext.py:91 test_gettext.py:97 -msgid "Raymond Luxury Yach-t" -msgstr "Throatwobbler Mangrove" - -#: test_gettext.py:17 test_gettext.py:23 test_gettext.py:29 test_gettext.py:35 -#: test_gettext.py:56 test_gettext.py:78 test_gettext.py:84 test_gettext.py:90 -#: test_gettext.py:96 -msgid "mullusk" -msgstr "bacon" - -#: test_gettext.py:40 test_gettext.py:101 -msgid "" -"This module provides internationalization and localization\n" -"support for your Python programs by providing an interface to the GNU\n" -"gettext message catalog library." -msgstr "" -"Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba\n" -"fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH\n" -"trggrkg zrffntr pngnybt yvoenel." - -# Manually added, as neither pygettext nor xgettext support plural forms -# in Python. -msgid "There is %s file" -msgid_plural "There are %s files" -msgstr[0] "Hay %s fichero" -msgstr[1] "Hay %s ficheros" -''' - -# Here's the second example po file example, used to generate the UMO_DATA -# containing utf-8 encoded Unicode strings - -''' -# Dummy translation for the Python test_gettext.py module. -# Copyright (C) 2001 Python Software Foundation -# Barry Warsaw <ba...@py...>, 2000. -# -msgid "" -msgstr "" -"Project-Id-Version: 2.0\n" -"PO-Revision-Date: 2003-04-11 12:42-0400\n" -"Last-Translator: Barry A. WArsaw <ba...@py...>\n" -"Language-Team: XX <pyt...@py...>\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=utf-8\n" -"Content-Transfer-Encoding: 7bit\n" -"Generated-By: manually\n" - -#: nofile:0 -msgid "ab\xc3\x9e" -msgstr "\xc2\xa4yz" -''' - -# Here's the third example po file, used to generate MMO_DATA - -''' -msgid "" -msgstr "" -"Project-Id-Version: No Project 0.0\n" -"POT-Creation-Date: Wed Dec 11 07:44:15 2002\n" -"PO-Revision-Date: 2002-08-14 01:18:58+00:00\n" -"Last-Translator: John Doe <jd...@ex...>\n" -"Jane Foobar <jf...@ex...>\n" -"Language-Team: xx <xx...@ex...>\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=iso-8859-15\n" -"Content-Transfer-Encoding: quoted-printable\n" -"Generated-By: pygettext.py 1.3\n" -''' Deleted: trunk/jython/Lib/test/test_global.py =================================================================== --- trunk/jython/Lib/test/test_global.py 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/test_global.py 2011-03-14 03:06:43 UTC (rev 7231) @@ -1,52 +0,0 @@ -"""Verify that warnings are issued for global statements following use.""" - -from test.test_support import run_unittest, check_syntax_error -import unittest -import warnings - - -class GlobalTests(unittest.TestCase): - - def test1(self): - prog_text_1 = """\ -def wrong1(): - a = 1 - b = 2 - global a - global b -""" - check_syntax_error(self, prog_text_1) - - def test2(self): - prog_text_2 = """\ -def wrong2(): - print x - global x -""" - check_syntax_error(self, prog_text_2) - - def test3(self): - prog_text_3 = """\ -def wrong3(): - print x - x = 2 - global x -""" - check_syntax_error(self, prog_text_3) - - def test4(self): - prog_text_4 = """\ -global x -x = 2 -""" - # this should work - compile(prog_text_4, "<test string>", "exec") - - -def test_main(): - with warnings.catch_warnings(): - warnings.filterwarnings("error", module="<test string>") - run_unittest(GlobalTests) - -if __name__ == "__main__": - test_main() Deleted: trunk/jython/Lib/test/test_wsgiref.py =================================================================== --- trunk/jython/Lib/test/test_wsgiref.py 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/test_wsgiref.py 2011-03-14 03:06:43 UTC (rev 7231) @@ -1,621 +0,0 @@ -from __future__ import nested_scopes # Backward compat for 2.1 -from unittest import TestCase -from wsgiref.util import setup_testing_defaults -from wsgiref.headers import Headers -from wsgiref.handlers import BaseHandler, BaseCGIHandler -from wsgiref import util -from wsgiref.validate import validator -from wsgiref.simple_server import WSGIServer, WSGIRequestHandler, demo_app -from wsgiref.simple_server import make_server -from StringIO import StringIO -from SocketServer import BaseServer -import os -import re -import sys - -from test import test_support - -class MockServer(WSGIServer): - """Non-socket HTTP server""" - - def __init__(self, server_address, RequestHandlerClass): - BaseServer.__init__(self, server_address, RequestHandlerClass) - self.server_bind() - - def server_bind(self): - host, port = self.server_address - self.server_name = host - self.server_port = port - self.setup_environ() - - -class MockHandler(WSGIRequestHandler): - """Non-socket HTTP handler""" - def setup(self): - self.connection = self.request - self.rfile, self.wfile = self.connection - - def finish(self): - pass - - - - - -def hello_app(environ,start_response): - start_response("200 OK", [ - ('Content-Type','text/plain'), - ('Date','Mon, 05 Jun 2006 18:49:54 GMT') - ]) - return ["Hello, world!"] - -def run_amock(app=hello_app, data="GET / HTTP/1.0\n\n"): - server = make_server("", 80, app, MockServer, MockHandler) - inp, out, err, olderr = StringIO(data), StringIO(), StringIO(), sys.stderr - sys.stderr = err - - try: - server.finish_request((inp,out), ("127.0.0.1",8888)) - finally: - sys.stderr = olderr - - return out.getvalue(), err.getvalue() - - - - - - - - - - - - - - - - - - - - - - - -def compare_generic_iter(make_it,match): - """Utility to compare a generic 2.1/2.2+ iterator with an iterable - - If running under Python 2.2+, this tests the iterator using iter()/next(), - as well as __getitem__. 'make_it' must be a function returning a fresh - iterator to be tested (since this may test the iterator twice).""" - - it = make_it() - n = 0 - for item in match: - if not it[n]==item: raise AssertionError - n+=1 - try: - it[n] - except IndexError: - pass - else: - raise AssertionError("Too many items from __getitem__",it) - - try: - iter, StopIteration - except NameError: - pass - else: - # Only test iter mode under 2.2+ - it = make_it() - if not iter(it) is it: raise AssertionError - for item in match: - if not it.next()==item: raise AssertionError - try: - it.next() - except StopIteration: - pass - else: - raise AssertionError("Too many items from .next()",it) - - - - - - -class IntegrationTests(TestCase): - - def check_hello(self, out, has_length=True): - self.assertEqual(out, - "HTTP/1.0 200 OK\r\n" - "Server: WSGIServer/0.1 Python/"+sys.version.split()[0]+"\r\n" - "Content-Type: text/plain\r\n" - "Date: Mon, 05 Jun 2006 18:49:54 GMT\r\n" + - (has_length and "Content-Length: 13\r\n" or "") + - "\r\n" - "Hello, world!" - ) - - def test_plain_hello(self): - out, err = run_amock() - self.check_hello(out) - - def test_validated_hello(self): - out, err = run_amock(validator(hello_app)) - # the middleware doesn't support len(), so content-length isn't there - self.check_hello(out, has_length=False) - - def test_simple_validation_error(self): - def bad_app(environ,start_response): - start_response("200 OK", ('Content-Type','text/plain')) - return ["Hello, world!"] - out, err = run_amock(validator(bad_app)) - self.failUnless(out.endswith( - "A server error occurred. Please contact the administrator." - )) - self.assertEqual( - err.splitlines()[-2], - "AssertionError: Headers (('Content-Type', 'text/plain')) must" - " be of type list: <type 'tuple'>" - ) - - - - - - -class UtilityTests(TestCase): - - def checkShift(self,sn_in,pi_in,part,sn_out,pi_out): - env = {'SCRIPT_NAME':sn_in,'PATH_INFO':pi_in} - util.setup_testing_defaults(env) - self.assertEqual(util.shift_path_info(env),part) - self.assertEqual(env['PATH_INFO'],pi_out) - self.assertEqual(env['SCRIPT_NAME'],sn_out) - return env - - def checkDefault(self, key, value, alt=None): - # Check defaulting when empty - env = {} - util.setup_testing_defaults(env) - if isinstance(value,StringIO): - self.failUnless(isinstance(env[key],StringIO)) - else: - self.assertEqual(env[key],value) - - # Check existing value - env = {key:alt} - util.setup_testing_defaults(env) - self.failUnless(env[key] is alt) - - def checkCrossDefault(self,key,value,**kw): - util.setup_testing_defaults(kw) - self.assertEqual(kw[key],value) - - def checkAppURI(self,uri,**kw): - util.setup_testing_defaults(kw) - self.assertEqual(util.application_uri(kw),uri) - - def checkReqURI(self,uri,query=1,**kw): - util.setup_testing_defaults(kw) - self.assertEqual(util.request_uri(kw,query),uri) - - - - - - - def checkFW(self,text,size,match): - - def make_it(text=text,size=size): - return util.FileWrapper(StringIO(text),size) - - compare_generic_iter(make_it,match) - - it = make_it() - self.failIf(it.filelike.closed) - - for item in it: - pass - - self.failIf(it.filelike.closed) - - it.close() - self.failUnless(it.filelike.closed) - - - def testSimpleShifts(self): - self.checkShift('','/', '', '/', '') - self.checkShift('','/x', 'x', '/x', '') - self.checkShift('/','', None, '/', '') - self.checkShift('/a','/x/y', 'x', '/a/x', '/y') - self.checkShift('/a','/x/', 'x', '/a/x', '/') - - - def testNormalizedShifts(self): - self.checkShift('/a/b', '/../y', '..', '/a', '/y') - self.checkShift('', '/../y', '..', '', '/y') - self.checkShift('/a/b', '//y', 'y', '/a/b/y', '') - self.checkShift('/a/b', '//y/', 'y', '/a/b/y', '/') - self.checkShift('/a/b', '/./y', 'y', '/a/b/y', '') - self.checkShift('/a/b', '/./y/', 'y', '/a/b/y', '/') - self.checkShift('/a/b', '///./..//y/.//', '..', '/a', '/y/') - self.checkShift('/a/b', '///', '', '/a/b/', '') - self.checkShift('/a/b', '/.//', '', '/a/b/', '') - self.checkShift('/a/b', '/x//', 'x', '/a/b/x', '/') - self.checkShift('/a/b', '/.', None, '/a/b', '') - - - def testDefaults(self): - for key, value in [ - ('SERVER_NAME','127.0.0.1'), - ('SERVER_PORT', '80'), - ('SERVER_PROTOCOL','HTTP/1.0'), - ('HTTP_HOST','127.0.0.1'), - ('REQUEST_METHOD','GET'), - ('SCRIPT_NAME',''), - ('PATH_INFO','/'), - ('wsgi.version', (1,0)), - ('wsgi.run_once', 0), - ('wsgi.multithread', 0), - ('wsgi.multiprocess', 0), - ('wsgi.input', StringIO("")), - ('wsgi.errors', StringIO()), - ('wsgi.url_scheme','http'), - ]: - self.checkDefault(key,value) - - - def testCrossDefaults(self): - self.checkCrossDefault('HTTP_HOST',"foo.bar",SERVER_NAME="foo.bar") - self.checkCrossDefault('wsgi.url_scheme',"https",HTTPS="on") - self.checkCrossDefault('wsgi.url_scheme',"https",HTTPS="1") - self.checkCrossDefault('wsgi.url_scheme',"https",HTTPS="yes") - self.checkCrossDefault('wsgi.url_scheme',"http",HTTPS="foo") - self.checkCrossDefault('SERVER_PORT',"80",HTTPS="foo") - self.checkCrossDefault('SERVER_PORT',"443",HTTPS="on") - - - def testGuessScheme(self): - self.assertEqual(util.guess_scheme({}), "http") - self.assertEqual(util.guess_scheme({'HTTPS':"foo"}), "http") - self.assertEqual(util.guess_scheme({'HTTPS':"on"}), "https") - self.assertEqual(util.guess_scheme({'HTTPS':"yes"}), "https") - self.assertEqual(util.guess_scheme({'HTTPS':"1"}), "https") - - - - - - def testAppURIs(self): - self.checkAppURI("http://127.0.0.1/") - self.checkAppURI("http://127.0.0.1/spam", SCRIPT_NAME="/spam") - self.checkAppURI("http://spam.example.com:2071/", - HTTP_HOST="spam.example.com:2071", SERVER_PORT="2071") - self.checkAppURI("http://spam.example.com/", - SERVER_NAME="spam.example.com") - self.checkAppURI("http://127.0.0.1/", - HTTP_HOST="127.0.0.1", SERVER_NAME="spam.example.com") - self.checkAppURI("https://127.0.0.1/", HTTPS="on") - self.checkAppURI("http://127.0.0.1:8000/", SERVER_PORT="8000", - HTTP_HOST=None) - - def testReqURIs(self): - self.checkReqURI("http://127.0.0.1/") - self.checkReqURI("http://127.0.0.1/spam", SCRIPT_NAME="/spam") - self.checkReqURI("http://127.0.0.1/spammity/spam", - SCRIPT_NAME="/spammity", PATH_INFO="/spam") - self.checkReqURI("http://127.0.0.1/spammity/spam?say=ni", - SCRIPT_NAME="/spammity", PATH_INFO="/spam",QUERY_STRING="say=ni") - self.checkReqURI("http://127.0.0.1/spammity/spam", 0, - SCRIPT_NAME="/spammity", PATH_INFO="/spam",QUERY_STRING="say=ni") - - def testFileWrapper(self): - self.checkFW("xyz"*50, 120, ["xyz"*40,"xyz"*10]) - - def testHopByHop(self): - for hop in ( - "Connection Keep-Alive Proxy-Authenticate Proxy-Authorization " - "TE Trailers Transfer-Encoding Upgrade" - ).split(): - for alt in hop, hop.title(), hop.upper(), hop.lower(): - self.failUnless(util.is_hop_by_hop(alt)) - - # Not comprehensive, just a few random header names - for hop in ( - "Accept Cache-Control Date Pragma Trailer Via Warning" - ).split(): - for alt in hop, hop.title(), hop.upper(), hop.lower(): - self.failIf(util.is_hop_by_hop(alt)) - -class HeaderTests(TestCase): - - def testMappingInterface(self): - test = [('x','y')] - self.assertEqual(len(Headers([])),0) - self.assertEqual(len(Headers(test[:])),1) - self.assertEqual(Headers(test[:]).keys(), ['x']) - self.assertEqual(Headers(test[:]).values(), ['y']) - self.assertEqual(Headers(test[:]).items(), test) - self.failIf(Headers(test).items() is test) # must be copy! - - h=Headers([]) - del h['foo'] # should not raise an error - - h['Foo'] = 'bar' - for m in h.has_key, h.__contains__, h.get, h.get_all, h.__getitem__: - self.failUnless(m('foo')) - self.failUnless(m('Foo')) - self.failUnless(m('FOO')) - self.failIf(m('bar')) - - self.assertEqual(h['foo'],'bar') - h['foo'] = 'baz' - self.assertEqual(h['FOO'],'baz') - self.assertEqual(h.get_all('foo'),['baz']) - - self.assertEqual(h.get("foo","whee"), "baz") - self.assertEqual(h.get("zoo","whee"), "whee") - self.assertEqual(h.setdefault("foo","whee"), "baz") - self.assertEqual(h.setdefault("zoo","whee"), "whee") - self.assertEqual(h["foo"],"baz") - self.assertEqual(h["zoo"],"whee") - - def testRequireList(self): - self.assertRaises(TypeError, Headers, "foo") - - - def testExtras(self): - h = Headers([]) - self.assertEqual(str(h),'\r\n') - - h.add_header('foo','bar',baz="spam") - self.assertEqual(h['foo'], 'bar; baz="spam"') - self.assertEqual(str(h),'foo: bar; baz="spam"\r\n\r\n') - - h.add_header('Foo','bar',cheese=None) - self.assertEqual(h.get_all('foo'), - ['bar; baz="spam"', 'bar; cheese']) - - self.assertEqual(str(h), - 'foo: bar; baz="spam"\r\n' - 'Foo: bar; cheese\r\n' - '\r\n' - ) - - -class ErrorHandler(BaseCGIHandler): - """Simple handler subclass for testing BaseHandler""" - - # BaseHandler records the OS environment at import time, but envvars - # might have been changed later by other tests, which trips up - # HandlerTests.testEnviron(). - os_environ = dict(os.environ.items()) - - def __init__(self,**kw): - setup_testing_defaults(kw) - BaseCGIHandler.__init__( - self, StringIO(''), StringIO(), StringIO(), kw, - multithread=True, multiprocess=True - ) - -class TestHandler(ErrorHandler): - """Simple handler subclass for testing BaseHandler, w/error passthru""" - - def handle_error(self): - raise # for testing, we want to see what's happening - - - - - - - - - - - -class HandlerTests(TestCase): - - def checkEnvironAttrs(self, handler): - env = handler.environ - for attr in [ - 'version','multithread','multiprocess','run_once','file_wrapper' - ]: - if attr=='file_wrapper' and handler.wsgi_file_wrapper is None: - continue - self.assertEqual(getattr(handler,'wsgi_'+attr),env['wsgi.'+attr]) - - def checkOSEnviron(self,handler): - empty = {}; setup_testing_defaults(empty) - env = handler.environ - from os import environ - for k,v in environ.items(): - if k not in empty: - self.assertEqual(env[k],v) - for k,v in empty.items(): - self.assertTrue(k in env) - - def testEnviron(self): - h = TestHandler(X="Y") - h.setup_environ() - self.checkEnvironAttrs(h) - self.checkOSEnviron(h) - self.assertEqual(h.environ["X"],"Y") - - def testCGIEnviron(self): - h = BaseCGIHandler(None,None,None,{}) - h.setup_environ() - for key in 'wsgi.url_scheme', 'wsgi.input', 'wsgi.errors': - self.assertTrue(key in h.environ) - - def testScheme(self): - h=TestHandler(HTTPS="on"); h.setup_environ() - self.assertEqual(h.environ['wsgi.url_scheme'],'https') - h=TestHandler(); h.setup_environ() - self.assertEqual(h.environ['wsgi.url_scheme'],'http') - - - def testAbstractMethods(self): - h = BaseHandler() - for name in [ - '_flush','get_stdin','get_stderr','add_cgi_vars' - ]: - self.assertRaises(NotImplementedError, getattr(h,name)) - self.assertRaises(NotImplementedError, h._write, "test") - - - def testContentLength(self): - # Demo one reason iteration is better than write()... ;) - - def trivial_app1(e,s): - s('200 OK',[]) - return [e['wsgi.url_scheme']] - - def trivial_app2(e,s): - s('200 OK',[])(e['wsgi.url_scheme']) - return [] - - h = TestHandler() - h.run(trivial_app1) - self.assertEqual(h.stdout.getvalue(), - "Status: 200 OK\r\n" - "Content-Length: 4\r\n" - "\r\n" - "http") - - h = TestHandler() - h.run(trivial_app2) - self.assertEqual(h.stdout.getvalue(), - "Status: 200 OK\r\n" - "\r\n" - "http") - - - - - - - - def testBasicErrorOutput(self): - - def non_error_app(e,s): - s('200 OK',[]) - return [] - - def error_app(e,s): - raise AssertionError("This should be caught by handler") - - h = ErrorHandler() - h.run(non_error_app) - self.assertEqual(h.stdout.getvalue(), - "Status: 200 OK\r\n" - "Content-Length: 0\r\n" - "\r\n") - self.assertEqual(h.stderr.getvalue(),"") - - h = ErrorHandler() - h.run(error_app) - self.assertEqual(h.stdout.getvalue(), - "Status: %s\r\n" - "Content-Type: text/plain\r\n" - "Content-Length: %d\r\n" - "\r\n%s" % (h.error_status,len(h.error_body),h.error_body)) - - self.assertTrue("AssertionError" in h.stderr.getvalue(), - "AssertionError not in stderr") - - def testErrorAfterOutput(self): - MSG = "Some output has been sent" - def error_app(e,s): - s("200 OK",[])(MSG) - raise AssertionError("This should be caught by handler") - - h = ErrorHandler() - h.run(error_app) - self.assertEqual(h.stdout.getvalue(), - "Status: 200 OK\r\n" - "\r\n"+MSG) - self.assertTrue("AssertionError" in h.stderr.getvalue(), - "AssertionError not in stderr") - - - def testHeaderFormats(self): - - def non_error_app(e,s): - s('200 OK',[]) - return [] - - stdpat = ( - r"HTTP/%s 200 OK\r\n" - r"Date: \w{3}, [ 0123]\d \w{3} \d{4} \d\d:\d\d:\d\d GMT\r\n" - r"%s" r"Content-Length: 0\r\n" r"\r\n" - ) - shortpat = ( - "Status: 200 OK\r\n" "Content-Length: 0\r\n" "\r\n" - ) - - for ssw in "FooBar/1.0", None: - sw = ssw and "Server: %s\r\n" % ssw or "" - - for version in "1.0", "1.1": - for proto in "HTTP/0.9", "HTTP/1.0", "HTTP/1.1": - - h = TestHandler(SERVER_PROTOCOL=proto) - h.origin_server = False - h.http_version = version - h.server_software = ssw - h.run(non_error_app) - self.assertEqual(shortpat,h.stdout.getvalue()) - - h = TestHandler(SERVER_PROTOCOL=proto) - h.origin_server = True - h.http_version = version - h.server_software = ssw - h.run(non_error_app) - if proto=="HTTP/0.9": - self.assertEqual(h.stdout.getvalue(),"") - else: - self.failUnless( - re.match(stdpat%(version,sw), h.stdout.getvalue()), - (stdpat%(version,sw), h.stdout.getvalue()) - ) - -# This epilogue is needed for compatibility with the Python 2.5 regrtest module - -def test_main(): - test_support.run_unittest(__name__) - -if __name__ == "__main__": - test_main() - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# the above lines intentionally left blank This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-14 03:14:44
|
Revision: 7232 http://jython.svn.sourceforge.net/jython/?rev=7232&view=rev Author: pjenvey Date: 2011-03-14 03:14:37 +0000 (Mon, 14 Mar 2011) Log Message: ----------- o test_grammar is stock from CPython 2.6 o old style test outputs no longer needed Removed Paths: ------------- trunk/jython/Lib/test/output/test_extcall trunk/jython/Lib/test/output/test_grammar trunk/jython/Lib/test/output/test_math trunk/jython/Lib/test/output/test_profile trunk/jython/Lib/test/output/test_signal trunk/jython/Lib/test/test_grammar.py Deleted: trunk/jython/Lib/test/output/test_extcall =================================================================== --- trunk/jython/Lib/test/output/test_extcall 2011-03-14 03:06:43 UTC (rev 7231) +++ trunk/jython/Lib/test/output/test_extcall 2011-03-14 03:14:37 UTC (rev 7232) @@ -1 +0,0 @@ -test_extcall Deleted: trunk/jython/Lib/test/output/test_grammar =================================================================== --- trunk/jython/Lib/test/output/test_grammar 2011-03-14 03:06:43 UTC (rev 7231) +++ trunk/jython/Lib/test/output/test_grammar 2011-03-14 03:14:37 UTC (rev 7232) @@ -1 +0,0 @@ -test_grammar Deleted: trunk/jython/Lib/test/output/test_math =================================================================== --- trunk/jython/Lib/test/output/test_math 2011-03-14 03:06:43 UTC (rev 7231) +++ trunk/jython/Lib/test/output/test_math 2011-03-14 03:14:37 UTC (rev 7232) @@ -1,28 +0,0 @@ -test_math -math module, testing with eps 1e-05 -constants -acos -asin -atan -atan2 -ceil -cos -cosh -degrees -exp -fabs -floor -fmod -frexp -hypot -ldexp -log -log10 -modf -pow -radians -sin -sinh -sqrt -tan -tanh Deleted: trunk/jython/Lib/test/output/test_profile =================================================================== --- trunk/jython/Lib/test/output/test_profile 2011-03-14 03:06:43 UTC (rev 7231) +++ trunk/jython/Lib/test/output/test_profile 2011-03-14 03:14:37 UTC (rev 7232) @@ -1,65 +0,0 @@ -test_profile - 98 function calls (78 primitive calls) in 1.000 CPU seconds - - Ordered by: standard name - - ncalls tottime percall cumtime percall filename:lineno(function) - 1 0.000 0.000 1.000 1.000 <string>:0(<module>) - 0 0.000 0.000 profile:0(profiler) - 1 0.000 0.000 1.000 1.000 profile:0(testfunc()) - 8 0.064 0.008 0.080 0.010 test_profile.py:103(subhelper) - 28 0.028 0.001 0.028 0.001 test_profile.py:115(__getattr__) - 1 0.270 0.270 1.000 1.000 test_profile.py:30(testfunc) - 23/3 0.150 0.007 0.170 0.057 test_profile.py:40(factorial) - 20 0.020 0.001 0.020 0.001 test_profile.py:53(mul) - 2 0.040 0.020 0.600 0.300 test_profile.py:60(helper) - 4 0.116 0.029 0.120 0.030 test_profile.py:78(helper1) - 2 0.000 0.000 0.140 0.070 test_profile.py:89(helper2_indirect) - 8 0.312 0.039 0.400 0.050 test_profile.py:93(helper2) - - - Ordered by: standard name - -Function called... -<string>:0(<module>) -> test_profile.py:30(testfunc)(1) 1.000 -profile:0(profiler) -> profile:0(testfunc())(1) 1.000 -profile:0(testfunc()) -> <string>:0(<module>)(1) 1.000 -test_profile.py:103(subhelper) -> test_profile.py:115(__getattr__)(16) 0.028 -test_profile.py:115(__getattr__) -> -test_profile.py:30(testfunc) -> test_profile.py:40(factorial)(1) 0.170 - test_profile.py:60(helper)(2) 0.600 -test_profile.py:40(factorial) -> test_profile.py:40(factorial)(20) 0.170 - test_profile.py:53(mul)(20) 0.020 -test_profile.py:53(mul) -> -test_profile.py:60(helper) -> test_profile.py:78(helper1)(4) 0.120 - test_profile.py:89(helper2_indirect)(2) 0.140 - test_profile.py:93(helper2)(6) 0.400 -test_profile.py:78(helper1) -> test_profile.py:115(__getattr__)(4) 0.028 -test_profile.py:89(helper2_indirect) -> test_profile.py:40(factorial)(2) 0.170 - test_profile.py:93(helper2)(2) 0.400 -test_profile.py:93(helper2) -> test_profile.py:103(subhelper)(8) 0.080 - test_profile.py:115(__getattr__)(8) 0.028 - - - Ordered by: standard name - -Function was called by... -<string>:0(<module>) <- profile:0(testfunc())(1) 1.000 -profile:0(profiler) <- -profile:0(testfunc()) <- profile:0(profiler)(1) 0.000 -test_profile.py:103(subhelper) <- test_profile.py:93(helper2)(8) 0.400 -test_profile.py:115(__getattr__) <- test_profile.py:78(helper1)(4) 0.120 - test_profile.py:93(helper2)(8) 0.400 - test_profile.py:103(subhelper)(16) 0.080 -test_profile.py:30(testfunc) <- <string>:0(<module>)(1) 1.000 -test_profile.py:40(factorial) <- test_profile.py:30(testfunc)(1) 1.000 - test_profile.py:40(factorial)(20) 0.170 - test_profile.py:89(helper2_indirect)(2) 0.140 -test_profile.py:53(mul) <- test_profile.py:40(factorial)(20) 0.170 -test_profile.py:60(helper) <- test_profile.py:30(testfunc)(2) 1.000 -test_profile.py:78(helper1) <- test_profile.py:60(helper)(4) 0.600 -test_profile.py:89(helper2_indirect) <- test_profile.py:60(helper)(2) 0.600 -test_profile.py:93(helper2) <- test_profile.py:60(helper)(6) 0.600 - test_profile.py:89(helper2_indirect)(2) 0.140 - - Deleted: trunk/jython/Lib/test/output/test_signal =================================================================== --- trunk/jython/Lib/test/output/test_signal 2011-03-14 03:06:43 UTC (rev 7231) +++ trunk/jython/Lib/test/output/test_signal 2011-03-14 03:14:37 UTC (rev 7232) @@ -1 +0,0 @@ -test_signal Deleted: trunk/jython/Lib/test/test_grammar.py =================================================================== --- trunk/jython/Lib/test/test_grammar.py 2011-03-14 03:06:43 UTC (rev 7231) +++ trunk/jython/Lib/test/test_grammar.py 2011-03-14 03:14:37 UTC (rev 7232) @@ -1,967 +0,0 @@ -# Python test set -- part 1, grammar. -# This just tests whether the parser accepts them all. - -# NOTE: When you run this test as a script from the command line, you -# get warnings about certain hex/oct constants. Since those are -# issued by the parser, you can't suppress them by adding a -# filterwarnings() call to this module. Therefore, to shut up the -# regression test, the filterwarnings() call has been added to -# regrtest.py. - -from test.test_support import (run_unittest, check_syntax_error, - _check_py3k_warnings) -import unittest -import sys -# testing import * -from sys import * - -class TokenTests(unittest.TestCase): - - def testBackslash(self): - # Backslash means line continuation: - x = 1 \ - + 1 - self.assertEquals(x, 2, 'backslash for line continuation') - - # Backslash does not means continuation in comments :\ - x = 0 - self.assertEquals(x, 0, 'backslash ending comment') - - def testPlainIntegers(self): - self.assertEquals(0xff, 255) - self.assertEquals(0377, 255) - self.assertEquals(2147483647, 017777777777) - # "0x" is not a valid literal - self.assertRaises(SyntaxError, eval, "0x") - from sys import maxint - if maxint == 2147483647: - self.assertEquals(-2147483647-1, -020000000000) - # XXX -2147483648 - self.assert_(037777777777 > 0) - self.assert_(0xffffffff > 0) - for s in '2147483648', '040000000000', '0x100000000': - try: - x = eval(s) - except OverflowError: - self.fail("OverflowError on huge integer literal %r" % s) - elif maxint == 9223372036854775807: - self.assertEquals(-9223372036854775807-1, -01000000000000000000000) - self.assert_(01777777777777777777777 > 0) - self.assert_(0xffffffffffffffff > 0) - for s in '9223372036854775808', '02000000000000000000000', \ - '0x10000000000000000': - try: - x = eval(s) - except OverflowError: - self.fail("OverflowError on huge integer literal %r" % s) - else: - self.fail('Weird maxint value %r' % maxint) - - def testLongIntegers(self): - x = 0L - x = 0l - x = 0xffffffffffffffffL - x = 0xffffffffffffffffl - x = 077777777777777777L - x = 077777777777777777l - x = 123456789012345678901234567890L - x = 123456789012345678901234567890l - - def testFloats(self): - x = 3.14 - x = 314. - x = 0.314 - # XXX x = 000.314 - x = .314 - x = 3e14 - x = 3E14 - x = 3e-14 - x = 3e+14 - x = 3.e14 - x = .3e14 - x = 3.1e4 - - def testStringLiterals(self): - x = ''; y = ""; self.assert_(len(x) == 0 and x == y) - x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39) - x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34) - x = "doesn't \"shrink\" does it" - y = 'doesn\'t "shrink" does it' - self.assert_(len(x) == 24 and x == y) - x = "does \"shrink\" doesn't it" - y = 'does "shrink" doesn\'t it' - self.assert_(len(x) == 24 and x == y) - x = """ -The "quick" -brown fox -jumps over -the 'lazy' dog. -""" - y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' - self.assertEquals(x, y) - y = ''' -The "quick" -brown fox -jumps over -the 'lazy' dog. -''' - self.assertEquals(x, y) - y = "\n\ -The \"quick\"\n\ -brown fox\n\ -jumps over\n\ -the 'lazy' dog.\n\ -" - self.assertEquals(x, y) - y = '\n\ -The \"quick\"\n\ -brown fox\n\ -jumps over\n\ -the \'lazy\' dog.\n\ -' - self.assertEquals(x, y) - - -class GrammarTests(unittest.TestCase): - - # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE - # XXX can't test in a script -- this rule is only used when interactive - - # file_input: (NEWLINE | stmt)* ENDMARKER - # Being tested as this very moment this very module - - # expr_input: testlist NEWLINE - # XXX Hard to test -- used only in calls to input() - - def testEvalInput(self): - # testlist ENDMARKER - x = eval('1, 0 or 1') - - def testFuncdef(self): - ### 'def' NAME parameters ':' suite - ### parameters: '(' [varargslist] ')' - ### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME] - ### | ('**'|'*' '*') NAME) - ### | fpdef ['=' test] (',' fpdef ['=' test])* [','] - ### fpdef: NAME | '(' fplist ')' - ### fplist: fpdef (',' fpdef)* [','] - ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test) - ### argument: [test '='] test # Really [keyword '='] test - def f1(): pass - f1() - f1(*()) - f1(*(), **{}) - def f2(one_argument): pass - def f3(two, arguments): pass - # Silence Py3k warning - exec('def f4(two, (compound, (argument, list))): pass') - exec('def f5((compound, first), two): pass') - self.assertEquals(f2.func_code.co_varnames, ('one_argument',)) - self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments')) - if sys.platform.startswith('java'): - self.assertEquals(f4.func_code.co_varnames, - ('two', '(compound, (argument, list))', 'compound', 'argument', - 'list',)) - self.assertEquals(f5.func_code.co_varnames, - ('(compound, first)', 'two', 'compound', 'first')) - else: - self.assertEquals(f4.func_code.co_varnames, - ('two', '.1', 'compound', 'argument', 'list')) - self.assertEquals(f5.func_code.co_varnames, - ('.0', 'two', 'compound', 'first')) - def a1(one_arg,): pass - def a2(two, args,): pass - def v0(*rest): pass - def v1(a, *rest): pass - def v2(a, b, *rest): pass - # Silence Py3k warning - exec('def v3(a, (b, c), *rest): return a, b, c, rest') - - f1() - f2(1) - f2(1,) - f3(1, 2) - f3(1, 2,) - f4(1, (2, (3, 4))) - v0() - v0(1) - v0(1,) - v0(1,2) - v0(1,2,3,4,5,6,7,8,9,0) - v1(1) - v1(1,) - v1(1,2) - v1(1,2,3) - v1(1,2,3,4,5,6,7,8,9,0) - v2(1,2) - v2(1,2,3) - v2(1,2,3,4) - v2(1,2,3,4,5,6,7,8,9,0) - v3(1,(2,3)) - v3(1,(2,3),4) - v3(1,(2,3),4,5,6,7,8,9,0) - - # ceval unpacks the formal arguments into the first argcount names; - # thus, the names nested inside tuples must appear after these names. - if sys.platform.startswith('java'): - self.assertEquals(v3.func_code.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c')) - else: - self.assertEquals(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c')) - self.assertEquals(v3(1, (2, 3), 4), (1, 2, 3, (4,))) - def d01(a=1): pass - d01() - d01(1) - d01(*(1,)) - d01(**{'a':2}) - def d11(a, b=1): pass - d11(1) - d11(1, 2) - d11(1, **{'b':2}) - def d21(a, b, c=1): pass - d21(1, 2) - d21(1, 2, 3) - d21(*(1, 2, 3)) - d21(1, *(2, 3)) - d21(1, 2, *(3,)) - d21(1, 2, **{'c':3}) - def d02(a=1, b=2): pass - d02() - d02(1) - d02(1, 2) - d02(*(1, 2)) - d02(1, *(2,)) - d02(1, **{'b':2}) - d02(**{'a': 1, 'b': 2}) - def d12(a, b=1, c=2): pass - d12(1) - d12(1, 2) - d12(1, 2, 3) - def d22(a, b, c=1, d=2): pass - d22(1, 2) - d22(1, 2, 3) - d22(1, 2, 3, 4) - def d01v(a=1, *rest): pass - d01v() - d01v(1) - d01v(1, 2) - d01v(*(1, 2, 3, 4)) - d01v(*(1,)) - d01v(**{'a':2}) - def d11v(a, b=1, *rest): pass - d11v(1) - d11v(1, 2) - d11v(1, 2, 3) - def d21v(a, b, c=1, *rest): pass - d21v(1, 2) - d21v(1, 2, 3) - d21v(1, 2, 3, 4) - d21v(*(1, 2, 3, 4)) - d21v(1, 2, **{'c': 3}) - def d02v(a=1, b=2, *rest): pass - d02v() - d02v(1) - d02v(1, 2) - d02v(1, 2, 3) - d02v(1, *(2, 3, 4)) - d02v(**{'a': 1, 'b': 2}) - def d12v(a, b=1, c=2, *rest): pass - d12v(1) - d12v(1, 2) - d12v(1, 2, 3) - d12v(1, 2, 3, 4) - d12v(*(1, 2, 3, 4)) - d12v(1, 2, *(3, 4, 5)) - d12v(1, *(2,), **{'c': 3}) - def d22v(a, b, c=1, d=2, *rest): pass - d22v(1, 2) - d22v(1, 2, 3) - d22v(1, 2, 3, 4) - d22v(1, 2, 3, 4, 5) - d22v(*(1, 2, 3, 4)) - d22v(1, 2, *(3, 4, 5)) - d22v(1, *(2, 3), **{'d': 4}) - # Silence Py3k warning - exec('def d31v((x)): pass') - exec('def d32v((x,)): pass') - d31v(1) - d32v((1,)) - - # keyword arguments after *arglist - def f(*args, **kwargs): - return args, kwargs - self.assertEquals(f(1, x=2, *[3, 4], y=5), ((1, 3, 4), - {'x':2, 'y':5})) - self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)") - self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)") - - # Check ast errors in *args and *kwargs - check_syntax_error(self, "f(*g(1=2))") - check_syntax_error(self, "f(**g(1=2))") - - def testLambdef(self): - ### lambdef: 'lambda' [varargslist] ':' test - l1 = lambda : 0 - self.assertEquals(l1(), 0) - l2 = lambda : a[d] # XXX just testing the expression - l3 = lambda : [2 < x for x in [-1, 3, 0L]] - self.assertEquals(l3(), [0, 1, 0]) - l4 = lambda x = lambda y = lambda z=1 : z : y() : x() - self.assertEquals(l4(), 1) - l5 = lambda x, y, z=2: x + y + z - self.assertEquals(l5(1, 2), 5) - self.assertEquals(l5(1, 2, 3), 6) - check_syntax_error(self, "lambda x: x = 2") - check_syntax_error(self, "lambda (None,): None") - - ### stmt: simple_stmt | compound_stmt - # Tested below - - def testSimpleStmt(self): - ### simple_stmt: small_stmt (';' small_stmt)* [';'] - x = 1; pass; del x - def foo(): - # verify statments that end with semi-colons - x = 1; pass; del x; - foo() - - ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt - # Tested below - - def testExprStmt(self): - # (exprlist '=')* exprlist - 1 - 1, 2, 3 - x = 1 - x = 1, 2, 3 - x = y = z = 1, 2, 3 - x, y, z = 1, 2, 3 - abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4) - - check_syntax_error(self, "x + 1 = 1") - check_syntax_error(self, "a + 1 = b + 2") - - def testPrintStmt(self): - # 'print' (test ',')* [test] - import StringIO - - # Can't test printing to real stdout without comparing output - # which is not available in unittest. - save_stdout = sys.stdout - sys.stdout = StringIO.StringIO() - - print 1, 2, 3 - print 1, 2, 3, - print - print 0 or 1, 0 or 1, - print 0 or 1 - - # 'print' '>>' test ',' - print >> sys.stdout, 1, 2, 3 - print >> sys.stdout, 1, 2, 3, - print >> sys.stdout - print >> sys.stdout, 0 or 1, 0 or 1, - print >> sys.stdout, 0 or 1 - - # test printing to an instance - class Gulp: - def write(self, msg): pass - - gulp = Gulp() - print >> gulp, 1, 2, 3 - print >> gulp, 1, 2, 3, - print >> gulp - print >> gulp, 0 or 1, 0 or 1, - print >> gulp, 0 or 1 - - # test print >> None - def driver(): - oldstdout = sys.stdout - sys.stdout = Gulp() - try: - tellme(Gulp()) - tellme() - finally: - sys.stdout = oldstdout - - # we should see this once - def tellme(file=sys.stdout): - print >> file, 'hello world' - - driver() - - # we should not see this at all - def tellme(file=None): - print >> file, 'goodbye universe' - - driver() - - self.assertEqual(sys.stdout.getvalue(), '''\ -1 2 3 -1 2 3 -1 1 1 -1 2 3 -1 2 3 -1 1 1 -hello world -''') - sys.stdout = save_stdout - - # syntax errors - check_syntax_error(self, 'print ,') - check_syntax_error(self, 'print >> x,') - - def testDelStmt(self): - # 'del' exprlist - abc = [1,2,3] - x, y, z = abc - xyz = x, y, z - - del abc - del x, y, (z, xyz) - - def testPassStmt(self): - # 'pass' - pass - - # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt - # Tested below - - def testBreakStmt(self): - # 'break' - while 1: break - - def testContinueStmt(self): - # 'continue' - i = 1 - while i: i = 0; continue - - msg = "" - while not msg: - msg = "ok" - try: - continue - msg = "continue failed to continue inside try" - except: - msg = "continue inside try called except block" - if msg != "ok": - self.fail(msg) - - msg = "" - while not msg: - msg = "finally block not called" - try: - continue - finally: - msg = "ok" - if msg != "ok": - self.fail(msg) - - def test_break_continue_loop(self): - # This test warrants an explanation. It is a test specifically for SF bugs - # #463359 and #462937. The bug is that a 'break' statement executed or - # exception raised inside a try/except inside a loop, *after* a continue - # statement has been executed in that loop, will cause the wrong number of - # arguments to be popped off the stack and the instruction pointer reset to - # a very small number (usually 0.) Because of this, the following test - # *must* written as a function, and the tracking vars *must* be function - # arguments with default values. Otherwise, the test will loop and loop. - - def test_inner(extra_burning_oil = 1, count=0): - big_hippo = 2 - while big_hippo: - count += 1 - try: - if extra_burning_oil and big_hippo == 1: - extra_burning_oil -= 1 - break - big_hippo -= 1 - continue - except: - raise - if count > 2 or big_hippo != 1: - self.fail("continue then break in try/except in loop broken!") - test_inner() - - def testReturn(self): - # 'return' [testlist] - def g1(): return - def g2(): return 1 - g1() - x = g2() - check_syntax_error(self, "class foo:return 1") - - def testYield(self): - check_syntax_error(self, "class foo:yield 1") - - def testRaise(self): - # 'raise' test [',' test] - try: raise RuntimeError, 'just testing' - except RuntimeError: pass - try: raise KeyboardInterrupt - except KeyboardInterrupt: pass - - def testImport(self): - # 'import' dotted_as_names - import sys - import time, sys - # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names) - from time import time - from time import (time) - # not testable inside a function, but already done at top of the module - # from sys import * - from sys import path, argv - from sys import (path, argv) - from sys import (path, argv,) - - def testGlobal(self): - # 'global' NAME (',' NAME)* - global a - global a, b - global one, two, three, four, five, six, seven, eight, nine, ten - - def testExec(self): - # 'exec' expr ['in' expr [',' expr]] - z = None - del z - exec 'z=1+1\n' - if z != 2: self.fail('exec \'z=1+1\'\\n') - del z - exec 'z=1+1' - if z != 2: self.fail('exec \'z=1+1\'') - z = None - del z - import types - if hasattr(types, "UnicodeType"): - exec r"""if 1: - exec u'z=1+1\n' - if z != 2: self.fail('exec u\'z=1+1\'\\n') - del z - exec u'z=1+1' - if z != 2: self.fail('exec u\'z=1+1\'')""" - g = {} - exec 'z = 1' in g - if '__builtins__' in g: del g['__builtins__'] - if g != {'z': 1}: self.fail('exec \'z = 1\' in g') - g = {} - l = {} - - import warnings - warnings.filterwarnings("ignore", "global statement", module="<string>") - exec 'global a; a = 1; b = 2' in g, l - if '__builtins__' in g: del g['__builtins__'] - if '__builtins__' in l: del l['__builtins__'] - if (g, l) != ({'a':1}, {'b':2}): - self.fail('exec ... in g (%s), l (%s)' %(g,l)) - - def testAssert(self): - # assert_stmt: 'assert' test [',' test] - assert 1 - assert 1, 1 - assert lambda x:x - assert 1, lambda x:x+1 - try: - assert 0, "msg" - except AssertionError, e: - self.assertEquals(e.args[0], "msg") - else: - if __debug__: - self.fail("AssertionError not raised by assert 0") - - ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef - # Tested below - - def testIf(self): - # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] - if 1: pass - if 1: pass - else: pass - if 0: pass - elif 0: pass - if 0: pass - elif 0: pass - elif 0: pass - elif 0: pass - else: pass - - def testWhile(self): - # 'while' test ':' suite ['else' ':' suite] - while 0: pass - while 0: pass - else: pass - - # Issue1920: "while 0" is optimized away, - # ensure that the "else" clause is still present. - x = 0 - while 0: - x = 1 - else: - x = 2 - self.assertEquals(x, 2) - - def testFor(self): - # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] - for i in 1, 2, 3: pass - for i, j, k in (): pass - else: pass - class Squares: - def __init__(self, max): - self.max = max - self.sofar = [] - def __len__(self): return len(self.sofar) - def __getitem__(self, i): - if not 0 <= i < self.max: raise IndexError - n = len(self.sofar) - while n <= i: - self.sofar.append(n*n) - n = n+1 - return self.sofar[i] - n = 0 - for x in Squares(10): n = n+x - if n != 285: - self.fail('for over growing sequence') - - result = [] - for x, in [(1,), (2,), (3,)]: - result.append(x) - self.assertEqual(result, [1, 2, 3]) - - def testTry(self): - ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] - ### | 'try' ':' suite 'finally' ':' suite - ### except_clause: 'except' [expr [('as' | ',') expr]] - try: - 1/0 - except ZeroDivisionError: - pass - else: - pass - try: 1/0 - except EOFError: pass - except TypeError as msg: pass - except RuntimeError, msg: pass - except: pass - else: pass - try: 1/0 - except (EOFError, TypeError, ZeroDivisionError): pass - try: 1/0 - except (EOFError, TypeError, ZeroDivisionError), msg: pass - try: pass - finally: pass - - def testSuite(self): - # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT - if 1: pass - if 1: - pass - if 1: - # - # - # - pass - pass - # - pass - # - - def testTest(self): - ### and_test ('or' and_test)* - ### and_test: not_test ('and' not_test)* - ### not_test: 'not' not_test | comparison - if not 1: pass - if 1 and 1: pass - if 1 or 1: pass - if not not not 1: pass - if not 1 and 1 and 1: pass - if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass - - def testComparison(self): - ### comparison: expr (comp_op expr)* - ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' - if 1: pass - x = (1 == 1) - if 1 == 1: pass - if 1 != 1: pass - if 1 < 1: pass - if 1 > 1: pass - if 1 <= 1: pass - if 1 >= 1: pass - if 1 is 1: pass - if 1 is not 1: pass - if 1 in (): pass - if 1 not in (): pass - if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass - # Silence Py3k warning - if eval('1 <> 1'): pass - if eval('1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1'): pass - - def testBinaryMaskOps(self): - x = 1 & 1 - x = 1 ^ 1 - x = 1 | 1 - - def testShiftOps(self): - x = 1 << 1 - x = 1 >> 1 - x = 1 << 1 >> 1 - - def testAdditiveOps(self): - x = 1 - x = 1 + 1 - x = 1 - 1 - 1 - x = 1 - 1 + 1 - 1 + 1 - - def testMultiplicativeOps(self): - x = 1 * 1 - x = 1 / 1 - x = 1 % 1 - x = 1 / 1 * 1 % 1 - - def testUnaryOps(self): - x = +1 - x = -1 - x = ~1 - x = ~1 ^ 1 & 1 | 1 & 1 ^ -1 - x = -1*1/1 + 1*1 - ---1*1 - - def testSelectors(self): - ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME - ### subscript: expr | [expr] ':' [expr] - - import sys, time - c = sys.path[0] - x = time.time() - x = sys.modules['time'].time() - a = '01234' - c = a[0] - c = a[-1] - s = a[0:5] - s = a[:5] - s = a[0:] - s = a[:] - s = a[-5:] - s = a[:-1] - s = a[-4:-3] - # A rough test of SF bug 1333982. http://python.org/sf/1333982 - # The testing here is fairly incomplete. - # Test cases should include: commas with 1 and 2 colons - d = {} - d[1] = 1 - d[1,] = 2 - d[1,2] = 3 - d[1,2,3] = 4 - L = list(d) - L.sort() - self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]') - - def testAtoms(self): - ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING - ### dictmaker: test ':' test (',' test ':' test)* [','] - - x = (1) - x = (1 or 2 or 3) - x = (1 or 2 or 3, 2, 3) - - x = [] - x = [1] - x = [1 or 2 or 3] - x = [1 or 2 or 3, 2, 3] - x = [] - - x = {} - x = {'one': 1} - x = {'one': 1,} - x = {'one' or 'two': 1 or 2} - x = {'one': 1, 'two': 2} - x = {'one': 1, 'two': 2,} - x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} - - # Silence Py3k warning - x = eval('`x`') - x = eval('`1 or 2 or 3`') - self.assertEqual(eval('`1,2`'), '(1, 2)') - - x = x - x = 'x' - x = 123 - - ### exprlist: expr (',' expr)* [','] - ### testlist: test (',' test)* [','] - # These have been exercised enough above - - def testClassdef(self): - # 'class' NAME ['(' [testlist] ')'] ':' suite - class B: pass - class B2(): pass - class C1(B): pass - class C2(B): pass - class D(C1, C2, B): pass - class C: - def meth1(self): pass - def meth2(self, arg): pass - def meth3(self, a1, a2): pass - # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE - # decorators: decorator+ - # decorated: decorators (classdef | funcdef) - def class_decorator(x): - x.decorated = True - return x - @class_decorator - class G: - pass - self.assertEqual(G.decorated, True) - - def testListcomps(self): - # list comprehension tests - nums = [1, 2, 3, 4, 5] - strs = ["Apple", "Banana", "Coconut"] - spcs = [" Apple", " Banana ", "Coco nut "] - - self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut']) - self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15]) - self.assertEqual([x for x in nums if x > 2], [3, 4, 5]) - self.assertEqual([(i, s) for i in nums for s in strs], - [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'), - (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'), - (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'), - (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'), - (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')]) - self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]], - [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'), - (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'), - (5, 'Banana'), (5, 'Coconut')]) - self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)], - [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]]) - - def test_in_func(l): - return [None < x < 3 for x in l if x > 2] - - self.assertEqual(test_in_func(nums), [False, False, False]) - - def test_nested_front(): - self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]], - [[1, 2], [3, 4], [5, 6]]) - - test_nested_front() - - check_syntax_error(self, "[i, s for i in nums for s in strs]") - check_syntax_error(self, "[x if y]") - - suppliers = [ - (1, "Boeing"), - (2, "Ford"), - (3, "Macdonalds") - ] - - parts = [ - (10, "Airliner"), - (20, "Engine"), - (30, "Cheeseburger") - ] - - suppart = [ - (1, 10), (1, 20), (2, 20), (3, 30) - ] - - x = [ - (sname, pname) - for (sno, sname) in suppliers - for (pno, pname) in parts - for (sp_sno, sp_pno) in suppart - if sno == sp_sno and pno == sp_pno - ] - - self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'), - ('Macdonalds', 'Cheeseburger')]) - - def testGenexps(self): - # generator expression tests - g = ([x for x in range(10)] for x in range(1)) - self.assertEqual(g.next(), [x for x in range(10)]) - try: - g.next() - self.fail('should produce StopIteration exception') - except StopIteration: - pass - - a = 1 - try: - g = (a for d in a) - g.next() - self.fail('should produce TypeError') - except TypeError: - pass - - self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd']) - self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy']) - - a = [x for x in range(10)] - b = (x for x in (y for y in a)) - self.assertEqual(sum(b), sum([x for x in range(10)])) - - self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)])) - self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2])) - self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)])) - self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)])) - self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)])) - self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True)) if True), sum([x for x in range(10)])) - self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0) - check_syntax_error(self, "foo(x for x in range(10), 100)") - check_syntax_error(self, "foo(100, x for x in range(10))") - - def testComprehensionSpecials(self): - # test for outmost iterable precomputation - x = 10; g = (i for i in range(x)); x = 5 - self.assertEqual(len(list(g)), 10) - - # This should hold, since we're only precomputing outmost iterable. - x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x)) - x = 5; t = True; - self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g)) - - # Grammar allows multiple adjacent 'if's in listcomps and genexps, - # even though it's silly. Make sure it works (ifelse broke this.) - self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7]) - self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7]) - - # verify unpacking single element tuples in listcomp/genexp. - self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6]) - self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9]) - - def testIfElseExpr(self): - # Test ifelse expressions in various cases - def _checkeval(msg, ret): - "helper to check that evaluation of expressions is done correctly" - print x - return ret - - self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True]) - self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True]) - self.assertEqual([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ], [True]) - self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5) - self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5) - self.assertEqual((5 and 6 if 0 else 1), 1) - self.assertEqual(((5 and 6) if 0 else 1), 1) - self.assertEqual((5 and (6 if 1 else 1)), 6) - self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3) - self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1) - self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5) - self.assertEqual((not 5 if 1 else 1), False) - self.assertEqual((not 5 if 0 else 1), 1) - self.assertEqual((6 + 1 if 1 else 2), 7) - self.assertEqual((6 - 1 if 1 else 2), 5) - self.assertEqual((6 * 2 if 1 else 4), 12) - self.assertEqual((6 / 2 if 1 else 3), 3) - self.assertEqual((6 < 4 if 0 else 2), 2) - - -def test_main(): - with _check_py3k_warnings( - ("backquote not supported", SyntaxWarning), - ("tuple parameter unpacking has been removed", SyntaxWarning), - ("parenthesized argument names are invalid", SyntaxWarning), - ("classic int division", DeprecationWarning), - (".+ not supported in 3.x", DeprecationWarning)): - run_unittest(TokenTests, GrammarTests) - -if __name__ == '__main__': - test_main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |