From: <pj...@us...> - 2008-10-05 00:04:46
|
Revision: 5357 http://jython.svn.sourceforge.net/jython/?rev=5357&view=rev Author: pjenvey Date: 2008-10-05 00:00:24 +0000 (Sun, 05 Oct 2008) Log Message: ----------- avoid test_asynchat on BSD where it deadlocks refs #1064 Modified Paths: -------------- trunk/jython/Lib/test/regrtest.py trunk/jython/Lib/test/test_asynchat.py Modified: trunk/jython/Lib/test/regrtest.py =================================================================== --- trunk/jython/Lib/test/regrtest.py 2008-10-02 02:31:03 UTC (rev 5356) +++ trunk/jython/Lib/test/regrtest.py 2008-10-05 00:00:24 UTC (rev 5357) @@ -1379,7 +1379,6 @@ test_aepack test_al test_applesingle - test_asynchat test_audioop test_bsddb test_bsddb185 @@ -1529,8 +1528,13 @@ for skip in WIN_ONLY: self.expected.add(skip) - if test_support.is_jython and os._name != 'posix': - self.expected.add('test_mhlib') + if test_support.is_jython: + if os._name != 'posix': + self.expected.add('test_mhlib') + import platform + os_name = platform.java_ver()[3][0] + if os_name == 'Mac OS X' or 'BSD' in os_name: + self.expected.add('test_asynchat') self.valid = True Modified: trunk/jython/Lib/test/test_asynchat.py =================================================================== --- trunk/jython/Lib/test/test_asynchat.py 2008-10-02 02:31:03 UTC (rev 5356) +++ trunk/jython/Lib/test/test_asynchat.py 2008-10-05 00:00:24 UTC (rev 5357) @@ -5,6 +5,12 @@ import unittest from test import test_support +import platform +os_name = platform.java_ver()[3][0] +if os_name == 'Mac OS X' or 'BSD' in os_name: + raise test_support.TestSkipped('test_asynchat deadlocks on Jython/BSD: ' + 'http://bugs.jython.org/issue1064') + HOST = "127.0.0.1" PORT = 54322 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-11-17 20:06:01
|
Revision: 5583 http://jython.svn.sourceforge.net/jython/?rev=5583&view=rev Author: pjenvey Date: 2008-11-17 20:05:55 +0000 (Mon, 17 Nov 2008) Log Message: ----------- o allow Socket{TCP,UDP}Test HOST/PORT to be overriden per class o use a different port than test_socket for test_select as test_socket sockopt tests don't REUSEADDR Modified Paths: -------------- trunk/jython/Lib/test/test_select.py trunk/jython/Lib/test/test_socket.py Modified: trunk/jython/Lib/test/test_select.py =================================================================== --- trunk/jython/Lib/test/test_select.py 2008-11-16 22:52:56 UTC (rev 5582) +++ trunk/jython/Lib/test/test_select.py 2008-11-17 20:05:55 UTC (rev 5583) @@ -1,21 +1,18 @@ """ AMAK: 20050515: This module is the test_select.py from cpython 2.4, ported to jython + unittest """ - -try: - object -except NameError: - class object: pass - import errno +import os import select import socket - -import os import sys -from test import test_support +import test_socket import unittest +from test import test_support +HOST = test_socket.HOST +PORT = test_socket.PORT + 100 + class SelectWrapper: def __init__(self): @@ -140,11 +137,11 @@ # # using the test_socket thread based server/client management, for convenience. # - -import test_socket - class ThreadedPollClientSocket(test_socket.ThreadedTCPSocketTest): + HOST = HOST + PORT = PORT + def testSocketRegisteredBeforeConnected(self): self.cli_conn = self.serv.accept() @@ -158,7 +155,7 @@ self.failIf(self.cli in result_sockets, "Unconnected client socket should not have been selectable") # Now connect the socket, but DO NOT register it again self.cli.setblocking(0) - self.cli.connect( (test_socket.HOST, test_socket.PORT) ) + self.cli.connect( (self.HOST, self.PORT) ) # Now poll again, to check that the poll object has recognised that the socket is now connected result_list = poll_object.poll(timeout) result_sockets = [r[0] for r in result_list] @@ -169,7 +166,7 @@ def _testSocketMustBeNonBlocking(self): self.cli.setblocking(1) - self.cli.connect( (test_socket.HOST, test_socket.PORT) ) + self.cli.connect( (self.HOST, self.PORT) ) timeout = 1000 # milliseconds poll_object = select.poll() try: Modified: trunk/jython/Lib/test/test_socket.py =================================================================== --- trunk/jython/Lib/test/test_socket.py 2008-11-16 22:52:56 UTC (rev 5582) +++ trunk/jython/Lib/test/test_socket.py 2008-11-17 20:05:55 UTC (rev 5583) @@ -28,10 +28,13 @@ class SocketTCPTest(unittest.TestCase): + HOST = HOST + PORT = PORT + def setUp(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - self.serv.bind((HOST, PORT)) + self.serv.bind((self.HOST, self.PORT)) self.serv.listen(1) def tearDown(self): @@ -40,10 +43,13 @@ class SocketUDPTest(unittest.TestCase): + HOST = HOST + PORT = PORT + def setUp(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - self.serv.bind((HOST, PORT)) + self.serv.bind((self.HOST, self.PORT)) def tearDown(self): self.serv.close() @@ -196,7 +202,7 @@ def clientSetUp(self): ThreadedTCPSocketTest.clientSetUp(self) - self.cli.connect((HOST, PORT)) + self.cli.connect((self.HOST, self.PORT)) self.serv_conn = self.cli def clientTearDown(self): @@ -796,7 +802,7 @@ self.assertEqual(msg, MSG) def _testSendtoAndRecv(self): - self.cli.sendto(MSG, 0, (HOST, PORT)) + self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) def testSendtoAndRecvTimeoutMode(self): # Need to test again in timeout mode, which follows @@ -807,7 +813,7 @@ def _testSendtoAndRecvTimeoutMode(self): self.cli.settimeout(10) - self.cli.sendto(MSG, 0, (HOST, PORT)) + self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) def testRecvFrom(self): # Testing recvfrom() over UDP @@ -815,7 +821,7 @@ self.assertEqual(msg, MSG) def _testRecvFrom(self): - self.cli.sendto(MSG, 0, (HOST, PORT)) + self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) def testRecvFromTimeoutMode(self): # Need to test again in timeout mode, which follows @@ -826,7 +832,7 @@ def _testRecvFromTimeoutMode(self): self.cli.settimeout(10) - self.cli.sendto(MSG, 0, (HOST, PORT)) + self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) def testSendtoEightBitSafe(self): # This test is necessary because java only supports signed bytes @@ -834,7 +840,7 @@ self.assertEqual(msg, EIGHT_BIT_MSG) def _testSendtoEightBitSafe(self): - self.cli.sendto(EIGHT_BIT_MSG, 0, (HOST, PORT)) + self.cli.sendto(EIGHT_BIT_MSG, 0, (self.HOST, self.PORT)) def testSendtoEightBitSafeTimeoutMode(self): # Need to test again in timeout mode, which follows @@ -845,7 +851,7 @@ def _testSendtoEightBitSafeTimeoutMode(self): self.cli.settimeout(10) - self.cli.sendto(EIGHT_BIT_MSG, 0, (HOST, PORT)) + self.cli.sendto(EIGHT_BIT_MSG, 0, (self.HOST, self.PORT)) class UDPBroadcastTest(ThreadedUDPSocketTest): @@ -854,13 +860,13 @@ self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) def testBroadcast(self): - self.serv.bind( ("<broadcast>", PORT) ) + self.serv.bind( ("<broadcast>", self.PORT) ) msg = self.serv.recv(len(EIGHT_BIT_MSG)) self.assertEqual(msg, EIGHT_BIT_MSG) def _testBroadcast(self): self.cli.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) - self.cli.sendto(EIGHT_BIT_MSG, ("<broadcast>", PORT) ) + self.cli.sendto(EIGHT_BIT_MSG, ("<broadcast>", self.PORT) ) class BasicSocketPairTest(SocketPairTest): @@ -927,7 +933,7 @@ def _testAcceptConnection(self): # Make a connection to the server - self.cli.connect((HOST, PORT)) + self.cli.connect((self.HOST, self.PORT)) # # AMAK: 20070311 @@ -942,7 +948,7 @@ def _testBlockingConnect(self): # Testing blocking connect self.cli.settimeout(10) - self.cli.connect((HOST, PORT)) + self.cli.connect((self.HOST, self.PORT)) def testNonBlockingConnect(self): # Testing non-blocking connect @@ -951,7 +957,7 @@ def _testNonBlockingConnect(self): # Testing non-blocking connect self.cli.setblocking(0) - result = self.cli.connect_ex((HOST, PORT)) + result = self.cli.connect_ex((self.HOST, self.PORT)) rfds, wfds, xfds = select.select([], [self.cli], []) self.failUnless(self.cli in wfds) try: @@ -970,13 +976,13 @@ def _testConnectWithLocalBind(self): # Testing blocking connect with local bind - cli_port = PORT - 1 + cli_port = self.PORT - 1 while True: # Keep trying until a local port is available self.cli.settimeout(1) - self.cli.bind( (HOST, cli_port) ) + self.cli.bind( (self.HOST, cli_port) ) try: - self.cli.connect((HOST, PORT)) + self.cli.connect((self.HOST, self.PORT)) break except socket.error, se: # cli_port is in use (maybe in TIME_WAIT state from a @@ -1004,7 +1010,7 @@ self.fail("Non-blocking socket with data should been in read list.") def _testRecvData(self): - self.cli.connect((HOST, PORT)) + self.cli.connect((self.HOST, self.PORT)) self.cli.send(MSG) def testRecvNoData(self): @@ -1019,7 +1025,7 @@ self.fail("Non-blocking recv of no data should have raised socket.error.") def _testRecvNoData(self): - self.cli.connect((HOST, PORT)) + self.cli.connect((self.HOST, self.PORT)) time.sleep(0.1) class NonBlockingUDPTests(ThreadedUDPSocketTest): pass @@ -1067,7 +1073,7 @@ self.cli_file = self.cli.makefile('wb') self.cli_file.close() try: - self.cli.sendto(MSG, 0, (HOST, PORT)) + self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) except Exception, x: self.fail("Closing file wrapper appears to have closed underlying socket: %s" % str(x)) @@ -1079,7 +1085,7 @@ def _testCloseSocketDoesNotCloseFile(self): try: - self.cli.sendto(MSG, 0, (HOST, PORT)) + self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) except Exception, x: self.fail("Closing file wrapper appears to have closed underlying socket: %s" % str(x)) @@ -1488,7 +1494,7 @@ pass def _testUnicodeHostname(self): - self.cli.connect((unicode(HOST), PORT)) + self.cli.connect((unicode(self.HOST), self.PORT)) class TestInvalidUsage(unittest.TestCase): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-12-17 03:57:00
|
Revision: 5771 http://jython.svn.sourceforge.net/jython/?rev=5771&view=rev Author: fwierzbicki Date: 2008-12-17 03:56:56 +0000 (Wed, 17 Dec 2008) Log Message: ----------- On the advice of the original poster of http://bugs.jython.org/issue1205 known to us only as pb, switching the test cases to the more poetic computation of the Hardy-Ramanujan number http://en.wikipedia.org/wiki/1729_(number). Modified Paths: -------------- trunk/jython/Lib/test/test_genexps_jy.py trunk/jython/Lib/test/test_listcomp_jy.py Modified: trunk/jython/Lib/test/test_genexps_jy.py =================================================================== --- trunk/jython/Lib/test/test_genexps_jy.py 2008-12-16 19:24:41 UTC (rev 5770) +++ trunk/jython/Lib/test/test_genexps_jy.py 2008-12-17 03:56:56 UTC (rev 5771) @@ -17,11 +17,15 @@ #http://bugs.jython.org/issue1205 applied to genexps. def test_long_genexp(self): - r = 2 - g = ((x1**3+x2**3,(x1,x2),(y1,y2)) for x1 in range(4) for x2 in range(4) - if x1 < x2 for y1 in range(r) for y2 in range(r) if y1 < y2 - if x1**3+x2**3 == y1**3+y2**3 ) - self.assertEquals(g.next(), (1, (0, 1), (0, 1))) + #for a long genexp, we compute the Hardy-Ramanujan number + #http://en.wikipedia.org/wiki/1729_(number) + res = ((x1**3+x2**3,(x1,x2),(y1,y2)) + for x1 in range(20) for x2 in range(20) if x1 < x2 # x-Paare + for y1 in range(20) for y2 in range(20) if y1 < y2 # y-Paare + if x1**3+x2**3 == y1**3+y2**3 # gleiche Summe + if (x1,x2) < (y1,y2) + ) + self.assertEquals(1729, res.next()[0]) def test_main(): test_support.run_unittest(GeneratorExpressionsTestCase) Modified: trunk/jython/Lib/test/test_listcomp_jy.py =================================================================== --- trunk/jython/Lib/test/test_listcomp_jy.py 2008-12-16 19:24:41 UTC (rev 5770) +++ trunk/jython/Lib/test/test_listcomp_jy.py 2008-12-17 03:56:56 UTC (rev 5771) @@ -5,12 +5,16 @@ #http://bugs.jython.org/issue1205 def test_long_listcomp(self): - r = 2 - lc = [(x1**3+x2**3,(x1,x2),(y1,y2)) for x1 in range(4) for x2 in range(4) - if x1 < x2 for y1 in range(r) for y2 in range(r) if y1 < y2 - if x1**3+x2**3 == y1**3+y2**3 ] - self.assertEquals(len(lc), 1) - self.assertEquals(lc, [(1, (0, 1), (0, 1))]) + #for a long list comp, we compute the Hardy-Ramanujan number + #http://en.wikipedia.org/wiki/1729_(number) + res = [(x1**3+x2**3,(x1,x2),(y1,y2)) + for x1 in range(20) for x2 in range(20) if x1 < x2 # x-Paare + for y1 in range(20) for y2 in range(20) if y1 < y2 # y-Paare + if x1**3+x2**3 == y1**3+y2**3 # gleiche Summe + if (x1,x2) < (y1,y2) + ] + self.assertEquals(1729, min(res)[0]) + self.assertEquals(len(res), 2) def test_main(): test_support.run_unittest(ListCompTestCase) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-12-29 17:26:50
|
Revision: 5809 http://jython.svn.sourceforge.net/jython/?rev=5809&view=rev Author: fwierzbicki Date: 2008-12-29 17:26:45 +0000 (Mon, 29 Dec 2008) Log Message: ----------- rename test to fit convention of _jy at the end and to match the CPython Lib test on which it is based. Added Paths: ----------- trunk/jython/Lib/test/test_codeop_jy.py Removed Paths: ------------- trunk/jython/Lib/test/test_jy_compile.py Copied: trunk/jython/Lib/test/test_codeop_jy.py (from rev 5808, trunk/jython/Lib/test/test_jy_compile.py) =================================================================== --- trunk/jython/Lib/test/test_codeop_jy.py (rev 0) +++ trunk/jython/Lib/test/test_codeop_jy.py 2008-12-29 17:26:45 UTC (rev 5809) @@ -0,0 +1,176 @@ +""" + test compile. derived from test_codeop +""" +import unittest +from test import test_support +from test.test_support import run_unittest + + +def compile_(source,name="<input>",symbol="single"): + return compile(source,name,symbol) + +class CompileTests(unittest.TestCase): + + def assertValid(self, str, symbol='single',values=None,value=None): + '''succeed iff str is a valid piece of code''' + code = compile_(str, "<input>", symbol) + if values: + 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: + compile_(str,symbol=symbol) + self.fail("No exception thrown for invalid code") + except SyntaxError: + self.assert_(is_syntax) + except OverflowError: + self.assert_(not is_syntax) + + assertIncomplete = assertInvalid + + def test_valid(self): + av = self.assertValid + + av("") + av("\n") + av("\n\n") + av("# a\n") + + av("a = 1") + av("\na = 1") + av("a = 1\n") + av("a = 1\n\n") + av("\n\na = 1\n\n",values={'a':1}) + + av("def x():\n pass\n") + av("if 1:\n pass\n") + + av("\n\nif 1: pass\n") + av("\n\nif 1: a=1\n\n",values={'a':1}) + + av("def x():\n pass") + av("def x():\n pass\n ") + av("def x():\n pass\n ") + av("\n\ndef x():\n pass") + + av("def x():\n\n pass\n") # failed under 2.1 + av("def x():\n pass\n \n") + av("def x():\n pass\n \n") + + av("pass\n") + av("3**3\n") + + av("if 9==3:\n pass\nelse:\n pass") + av("if 9==3:\n pass\nelse:\n pass\n") + av("if 1:\n pass\n if 1:\n pass\n else:\n pass") + av("if 1:\n pass\n if 1:\n pass\n else:\n pass\n") + + av("#a\n#b\na = 3\n") + av("#a\n\n \na=3\n",values={'a':3}) + av("a=3\n\n") + av("a = 9+ \\\n3") + + av("3**3","eval") + av("(lambda z: \n z**3)","eval") + + av("9+ \\\n3","eval") + av("9+ \\\n3\n","eval") + + # these failed under 2.1 + self.eval_d = {'a': 2} + av("\n\na**3","eval",value=8) + av("\n \na**3","eval",value=8) + av("#a\n#b\na**3","eval",value=8) + + # this failed under 2.2.1 + av("def f():\n try: pass\n finally: [x for x in (1,2)]") + + # Failed for Jython 2.5a2. See http://bugs.jython.org/issue1116. + av("@a.b.c\ndef f():\n pass") + + def test_incomplete(self): + ai = self.assertIncomplete + + ai("(a **") + ai("(a,b,") + ai("(a,b,(") + ai("(a,b,(") + ai("a = (") + ai("a = {") + ai("b + {") + + ai("if 9==3:\n pass\nelse:") + ai("if 9==3:\n pass\nelse:\n") + + ai("if 1:") + ai("if 1:\n") + ai("if 1:\n pass\n if 1:\n pass\n else:") + ai("if 1:\n pass\n if 1:\n pass\n else:\n") + + ai("def x():") + ai("def x():\n") + ai("def x():\n\n") + + ai("a = 9+ \\") + ai("a = 'a\\") + ai("a = '''xy") + + ai("","eval") + ai("\n","eval") + ai("(","eval") + ai("(\n\n\n","eval") + ai("(9+","eval") + ai("9+ \\","eval") + ai("lambda z: \\","eval") + + def test_invalid(self): + ai = self.assertInvalid + + ai("a b") + + ai("a @") + ai("a b @") + ai("a ** @") + + ai("a = ") + ai("a = 9 +") + + ai("def x():\n\npass\n") + + ai("\n\n if 1: pass\n\npass") # valid for 2.1 ?! + + ai("a = 9+ \\\n") + ai("a = 'a\\ ") + ai("a = 'a\\\n") + + ai("a = 1","eval") + ai("a = (","eval") + ai("]","eval") + ai("())","eval") + ai("[}","eval") + ai("9+","eval") + ai("lambda z:","eval") + ai("a b","eval") + ai("return 2.3") + + def test_filename(self): + self.assertEquals(compile_("a = 1\n", "abc").co_filename, + compile("a = 1\n", "abc", 'single').co_filename) + self.assertNotEquals(compile_("a = 1\n", "abc").co_filename, + compile("a = 1\n", "def", 'single').co_filename) + + +def test_main(): + run_unittest(CompileTests) + + +if __name__ == "__main__": + test_main() Deleted: trunk/jython/Lib/test/test_jy_compile.py =================================================================== --- trunk/jython/Lib/test/test_jy_compile.py 2008-12-29 09:00:09 UTC (rev 5808) +++ trunk/jython/Lib/test/test_jy_compile.py 2008-12-29 17:26:45 UTC (rev 5809) @@ -1,176 +0,0 @@ -""" - test compile. derived from test_codeop -""" -import unittest -from test import test_support -from test.test_support import run_unittest - - -def compile_(source,name="<input>",symbol="single"): - return compile(source,name,symbol) - -class CompileTests(unittest.TestCase): - - def assertValid(self, str, symbol='single',values=None,value=None): - '''succeed iff str is a valid piece of code''' - code = compile_(str, "<input>", symbol) - if values: - 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: - compile_(str,symbol=symbol) - self.fail("No exception thrown for invalid code") - except SyntaxError: - self.assert_(is_syntax) - except OverflowError: - self.assert_(not is_syntax) - - assertIncomplete = assertInvalid - - def test_valid(self): - av = self.assertValid - - av("") - av("\n") - av("\n\n") - av("# a\n") - - av("a = 1") - av("\na = 1") - av("a = 1\n") - av("a = 1\n\n") - av("\n\na = 1\n\n",values={'a':1}) - - av("def x():\n pass\n") - av("if 1:\n pass\n") - - av("\n\nif 1: pass\n") - av("\n\nif 1: a=1\n\n",values={'a':1}) - - av("def x():\n pass") - av("def x():\n pass\n ") - av("def x():\n pass\n ") - av("\n\ndef x():\n pass") - - av("def x():\n\n pass\n") # failed under 2.1 - av("def x():\n pass\n \n") - av("def x():\n pass\n \n") - - av("pass\n") - av("3**3\n") - - av("if 9==3:\n pass\nelse:\n pass") - av("if 9==3:\n pass\nelse:\n pass\n") - av("if 1:\n pass\n if 1:\n pass\n else:\n pass") - av("if 1:\n pass\n if 1:\n pass\n else:\n pass\n") - - av("#a\n#b\na = 3\n") - av("#a\n\n \na=3\n",values={'a':3}) - av("a=3\n\n") - av("a = 9+ \\\n3") - - av("3**3","eval") - av("(lambda z: \n z**3)","eval") - - av("9+ \\\n3","eval") - av("9+ \\\n3\n","eval") - - # these failed under 2.1 - self.eval_d = {'a': 2} - av("\n\na**3","eval",value=8) - av("\n \na**3","eval",value=8) - av("#a\n#b\na**3","eval",value=8) - - # this failed under 2.2.1 - av("def f():\n try: pass\n finally: [x for x in (1,2)]") - - # Failed for Jython 2.5a2. See http://bugs.jython.org/issue1116. - av("@a.b.c\ndef f():\n pass") - - def test_incomplete(self): - ai = self.assertIncomplete - - ai("(a **") - ai("(a,b,") - ai("(a,b,(") - ai("(a,b,(") - ai("a = (") - ai("a = {") - ai("b + {") - - ai("if 9==3:\n pass\nelse:") - ai("if 9==3:\n pass\nelse:\n") - - ai("if 1:") - ai("if 1:\n") - ai("if 1:\n pass\n if 1:\n pass\n else:") - ai("if 1:\n pass\n if 1:\n pass\n else:\n") - - ai("def x():") - ai("def x():\n") - ai("def x():\n\n") - - ai("a = 9+ \\") - ai("a = 'a\\") - ai("a = '''xy") - - ai("","eval") - ai("\n","eval") - ai("(","eval") - ai("(\n\n\n","eval") - ai("(9+","eval") - ai("9+ \\","eval") - ai("lambda z: \\","eval") - - def test_invalid(self): - ai = self.assertInvalid - - ai("a b") - - ai("a @") - ai("a b @") - ai("a ** @") - - ai("a = ") - ai("a = 9 +") - - ai("def x():\n\npass\n") - - ai("\n\n if 1: pass\n\npass") # valid for 2.1 ?! - - ai("a = 9+ \\\n") - ai("a = 'a\\ ") - ai("a = 'a\\\n") - - ai("a = 1","eval") - ai("a = (","eval") - ai("]","eval") - ai("())","eval") - ai("[}","eval") - ai("9+","eval") - ai("lambda z:","eval") - ai("a b","eval") - ai("return 2.3") - - def test_filename(self): - self.assertEquals(compile_("a = 1\n", "abc").co_filename, - compile("a = 1\n", "abc", 'single').co_filename) - self.assertNotEquals(compile_("a = 1\n", "abc").co_filename, - compile("a = 1\n", "def", 'single').co_filename) - - -def test_main(): - run_unittest(CompileTests) - - -if __name__ == "__main__": - test_main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-01-08 07:40:06
|
Revision: 5877 http://jython.svn.sourceforge.net/jython/?rev=5877&view=rev Author: pjenvey Date: 2009-01-08 07:40:01 +0000 (Thu, 08 Jan 2009) Log Message: ----------- from: http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_xml_etree.py@50943 http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_xml_etree_c.py@51322 Added Paths: ----------- trunk/jython/Lib/test/test_xml_etree.py trunk/jython/Lib/test/test_xml_etree_c.py Added: trunk/jython/Lib/test/test_xml_etree.py =================================================================== --- trunk/jython/Lib/test/test_xml_etree.py (rev 0) +++ trunk/jython/Lib/test/test_xml_etree.py 2009-01-08 07:40:01 UTC (rev 5877) @@ -0,0 +1,354 @@ +# xml.etree test. This file contains enough tests to make sure that +# all included components work as they should. For a more extensive +# test suite, see the selftest script in the ElementTree distribution. + +import doctest, sys + +from test import test_support + +SAMPLE_XML = """ +<body> + <tag>text</tag> + <tag /> + <section> + <tag>subtext</tag> + </section> +</body> +""" + +SAMPLE_XML_NS = """ +<body xmlns="http://effbot.org/ns"> + <tag>text</tag> + <tag /> + <section> + <tag>subtext</tag> + </section> +</body> +""" + +def sanity(): + """ + Import sanity. + + >>> from xml.etree import ElementTree + >>> from xml.etree import ElementInclude + >>> from xml.etree import ElementPath + """ + +def check_method(method): + if not callable(method): + print method, "not callable" + +def serialize(ET, elem, encoding=None): + import StringIO + file = StringIO.StringIO() + tree = ET.ElementTree(elem) + if encoding: + tree.write(file, encoding) + else: + tree.write(file) + return file.getvalue() + +def summarize(elem): + return elem.tag + +def summarize_list(seq): + return map(summarize, seq) + +def interface(): + """ + Test element tree interface. + + >>> from xml.etree import ElementTree as ET + + >>> element = ET.Element("tag", key="value") + >>> tree = ET.ElementTree(element) + + Make sure all standard element methods exist. + + >>> check_method(element.append) + >>> check_method(element.insert) + >>> check_method(element.remove) + >>> check_method(element.getchildren) + >>> check_method(element.find) + >>> check_method(element.findall) + >>> check_method(element.findtext) + >>> check_method(element.clear) + >>> check_method(element.get) + >>> check_method(element.set) + >>> check_method(element.keys) + >>> check_method(element.items) + >>> check_method(element.getiterator) + + Basic method sanity checks. + + >>> serialize(ET, element) # 1 + '<tag key="value" />' + >>> subelement = ET.Element("subtag") + >>> element.append(subelement) + >>> serialize(ET, element) # 2 + '<tag key="value"><subtag /></tag>' + >>> element.insert(0, subelement) + >>> serialize(ET, element) # 3 + '<tag key="value"><subtag /><subtag /></tag>' + >>> element.remove(subelement) + >>> serialize(ET, element) # 4 + '<tag key="value"><subtag /></tag>' + >>> element.remove(subelement) + >>> serialize(ET, element) # 5 + '<tag key="value" />' + >>> element.remove(subelement) + Traceback (most recent call last): + ValueError: list.remove(x): x not in list + >>> serialize(ET, element) # 6 + '<tag key="value" />' + """ + +def find(): + """ + Test find methods (including xpath syntax). + + >>> from xml.etree import ElementTree as ET + + >>> elem = ET.XML(SAMPLE_XML) + >>> elem.find("tag").tag + 'tag' + >>> ET.ElementTree(elem).find("tag").tag + 'tag' + >>> elem.find("section/tag").tag + 'tag' + >>> ET.ElementTree(elem).find("section/tag").tag + 'tag' + >>> elem.findtext("tag") + 'text' + >>> elem.findtext("tog") + >>> elem.findtext("tog", "default") + 'default' + >>> ET.ElementTree(elem).findtext("tag") + 'text' + >>> elem.findtext("section/tag") + 'subtext' + >>> ET.ElementTree(elem).findtext("section/tag") + 'subtext' + >>> summarize_list(elem.findall("tag")) + ['tag', 'tag'] + >>> summarize_list(elem.findall("*")) + ['tag', 'tag', 'section'] + >>> summarize_list(elem.findall(".//tag")) + ['tag', 'tag', 'tag'] + >>> summarize_list(elem.findall("section/tag")) + ['tag'] + >>> summarize_list(elem.findall("section//tag")) + ['tag'] + >>> summarize_list(elem.findall("section/*")) + ['tag'] + >>> summarize_list(elem.findall("section//*")) + ['tag'] + >>> summarize_list(elem.findall("section/.//*")) + ['tag'] + >>> summarize_list(elem.findall("*/*")) + ['tag'] + >>> summarize_list(elem.findall("*//*")) + ['tag'] + >>> summarize_list(elem.findall("*/tag")) + ['tag'] + >>> summarize_list(elem.findall("*/./tag")) + ['tag'] + >>> summarize_list(elem.findall("./tag")) + ['tag', 'tag'] + >>> summarize_list(elem.findall(".//tag")) + ['tag', 'tag', 'tag'] + >>> summarize_list(elem.findall("././tag")) + ['tag', 'tag'] + >>> summarize_list(ET.ElementTree(elem).findall("/tag")) + ['tag', 'tag'] + >>> summarize_list(ET.ElementTree(elem).findall("./tag")) + ['tag', 'tag'] + >>> elem = ET.XML(SAMPLE_XML_NS) + >>> summarize_list(elem.findall("tag")) + [] + >>> summarize_list(elem.findall("{http://effbot.org/ns}tag")) + ['{http://effbot.org/ns}tag', '{http://effbot.org/ns}tag'] + >>> summarize_list(elem.findall(".//{http://effbot.org/ns}tag")) + ['{http://effbot.org/ns}tag', '{http://effbot.org/ns}tag', '{http://effbot.org/ns}tag'] + """ + +def parseliteral(): + r""" + + >>> from xml.etree import ElementTree as ET + + >>> element = ET.XML("<html><body>text</body></html>") + >>> ET.ElementTree(element).write(sys.stdout) + <html><body>text</body></html> + >>> element = ET.fromstring("<html><body>text</body></html>") + >>> ET.ElementTree(element).write(sys.stdout) + <html><body>text</body></html> + >>> print ET.tostring(element) + <html><body>text</body></html> + >>> print ET.tostring(element, "ascii") + <?xml version='1.0' encoding='ascii'?> + <html><body>text</body></html> + >>> _, ids = ET.XMLID("<html><body>text</body></html>") + >>> len(ids) + 0 + >>> _, ids = ET.XMLID("<html><body id='body'>text</body></html>") + >>> len(ids) + 1 + >>> ids["body"].tag + 'body' + """ + + +def check_encoding(ET, encoding): + """ + >>> from xml.etree import ElementTree as ET + + >>> check_encoding(ET, "ascii") + >>> check_encoding(ET, "us-ascii") + >>> check_encoding(ET, "iso-8859-1") + >>> check_encoding(ET, "iso-8859-15") + >>> check_encoding(ET, "cp437") + >>> check_encoding(ET, "mac-roman") + """ + ET.XML("<?xml version='1.0' encoding='%s'?><xml />" % encoding) + + +# +# xinclude tests (samples from appendix C of the xinclude specification) + +XINCLUDE = {} + +XINCLUDE["C1.xml"] = """\ +<?xml version='1.0'?> +<document xmlns:xi="http://www.w3.org/2001/XInclude"> + <p>120 Mz is adequate for an average home user.</p> + <xi:include href="disclaimer.xml"/> +</document> +""" + +XINCLUDE["disclaimer.xml"] = """\ +<?xml version='1.0'?> +<disclaimer> + <p>The opinions represented herein represent those of the individual + and should not be interpreted as official policy endorsed by this + organization.</p> +</disclaimer> +""" + +XINCLUDE["C2.xml"] = """\ +<?xml version='1.0'?> +<document xmlns:xi="http://www.w3.org/2001/XInclude"> + <p>This document has been accessed + <xi:include href="count.txt" parse="text"/> times.</p> +</document> +""" + +XINCLUDE["count.txt"] = "324387" + +XINCLUDE["C3.xml"] = """\ +<?xml version='1.0'?> +<document xmlns:xi="http://www.w3.org/2001/XInclude"> + <p>The following is the source of the "data.xml" resource:</p> + <example><xi:include href="data.xml" parse="text"/></example> +</document> +""" + +XINCLUDE["data.xml"] = """\ +<?xml version='1.0'?> +<data> + <item><![CDATA[Brooks & Shields]]></item> +</data> +""" + +XINCLUDE["C5.xml"] = """\ +<?xml version='1.0'?> +<div xmlns:xi="http://www.w3.org/2001/XInclude"> + <xi:include href="example.txt" parse="text"> + <xi:fallback> + <xi:include href="fallback-example.txt" parse="text"> + <xi:fallback><a href="mailto:bo...@ex...">Report error</a></xi:fallback> + </xi:include> + </xi:fallback> + </xi:include> +</div> +""" + +XINCLUDE["default.xml"] = """\ +<?xml version='1.0'?> +<document xmlns:xi="http://www.w3.org/2001/XInclude"> + <p>Example.</p> + <xi:include href="samples/simple.xml"/> +</document> +""" + +def xinclude_loader(href, parse="xml", encoding=None): + try: + data = XINCLUDE[href] + except KeyError: + raise IOError("resource not found") + if parse == "xml": + from xml.etree.ElementTree import XML + return XML(data) + return data + +def xinclude(): + r""" + Basic inclusion example (XInclude C.1) + + >>> from xml.etree import ElementTree as ET + >>> from xml.etree import ElementInclude + + >>> document = xinclude_loader("C1.xml") + >>> ElementInclude.include(document, xinclude_loader) + >>> print serialize(ET, document) # C1 + <document> + <p>120 Mz is adequate for an average home user.</p> + <disclaimer> + <p>The opinions represented herein represent those of the individual + and should not be interpreted as official policy endorsed by this + organization.</p> + </disclaimer> + </document> + + Textual inclusion example (XInclude C.2) + + >>> document = xinclude_loader("C2.xml") + >>> ElementInclude.include(document, xinclude_loader) + >>> print serialize(ET, document) # C2 + <document> + <p>This document has been accessed + 324387 times.</p> + </document> + + Textual inclusion of XML example (XInclude C.3) + + >>> document = xinclude_loader("C3.xml") + >>> ElementInclude.include(document, xinclude_loader) + >>> print serialize(ET, document) # C3 + <document> + <p>The following is the source of the "data.xml" resource:</p> + <example><?xml version='1.0'?> + <data> + <item><![CDATA[Brooks & Shields]]></item> + </data> + </example> + </document> + + Fallback example (XInclude C.5) + Note! Fallback support is not yet implemented + + >>> document = xinclude_loader("C5.xml") + >>> ElementInclude.include(document, xinclude_loader) + Traceback (most recent call last): + IOError: resource not found + >>> # print serialize(ET, document) # C5 + + """ + +def test_main(): + from test import test_xml_etree + test_support.run_doctest(test_xml_etree, verbosity=True) + +if __name__ == '__main__': + test_main() Added: trunk/jython/Lib/test/test_xml_etree_c.py =================================================================== --- trunk/jython/Lib/test/test_xml_etree_c.py (rev 0) +++ trunk/jython/Lib/test/test_xml_etree_c.py 2009-01-08 07:40:01 UTC (rev 5877) @@ -0,0 +1,223 @@ +# xml.etree test for cElementTree + +import doctest, sys + +from test import test_support + +from xml.etree import cElementTree as ET + +SAMPLE_XML = """ +<body> + <tag>text</tag> + <tag /> + <section> + <tag>subtext</tag> + </section> +</body> +""" + +SAMPLE_XML_NS = """ +<body xmlns="http://effbot.org/ns"> + <tag>text</tag> + <tag /> + <section> + <tag>subtext</tag> + </section> +</body> +""" + +def sanity(): + """ + Import sanity. + + >>> from xml.etree import cElementTree + """ + +def check_method(method): + if not callable(method): + print method, "not callable" + +def serialize(ET, elem, encoding=None): + import StringIO + file = StringIO.StringIO() + tree = ET.ElementTree(elem) + if encoding: + tree.write(file, encoding) + else: + tree.write(file) + return file.getvalue() + +def summarize(elem): + return elem.tag + +def summarize_list(seq): + return map(summarize, seq) + +def interface(): + """ + Test element tree interface. + + >>> element = ET.Element("tag", key="value") + >>> tree = ET.ElementTree(element) + + Make sure all standard element methods exist. + + >>> check_method(element.append) + >>> check_method(element.insert) + >>> check_method(element.remove) + >>> check_method(element.getchildren) + >>> check_method(element.find) + >>> check_method(element.findall) + >>> check_method(element.findtext) + >>> check_method(element.clear) + >>> check_method(element.get) + >>> check_method(element.set) + >>> check_method(element.keys) + >>> check_method(element.items) + >>> check_method(element.getiterator) + + Basic method sanity checks. + + >>> serialize(ET, element) # 1 + '<tag key="value" />' + >>> subelement = ET.Element("subtag") + >>> element.append(subelement) + >>> serialize(ET, element) # 2 + '<tag key="value"><subtag /></tag>' + >>> element.insert(0, subelement) + >>> serialize(ET, element) # 3 + '<tag key="value"><subtag /><subtag /></tag>' + >>> element.remove(subelement) + >>> serialize(ET, element) # 4 + '<tag key="value"><subtag /></tag>' + >>> element.remove(subelement) + >>> serialize(ET, element) # 5 + '<tag key="value" />' + >>> element.remove(subelement) + Traceback (most recent call last): + ValueError: list.remove(x): x not in list + >>> serialize(ET, element) # 6 + '<tag key="value" />' + """ + +def find(): + """ + Test find methods (including xpath syntax). + + >>> elem = ET.XML(SAMPLE_XML) + >>> elem.find("tag").tag + 'tag' + >>> ET.ElementTree(elem).find("tag").tag + 'tag' + >>> elem.find("section/tag").tag + 'tag' + >>> ET.ElementTree(elem).find("section/tag").tag + 'tag' + >>> elem.findtext("tag") + 'text' + >>> elem.findtext("tog") + >>> elem.findtext("tog", "default") + 'default' + >>> ET.ElementTree(elem).findtext("tag") + 'text' + >>> elem.findtext("section/tag") + 'subtext' + >>> ET.ElementTree(elem).findtext("section/tag") + 'subtext' + >>> summarize_list(elem.findall("tag")) + ['tag', 'tag'] + >>> summarize_list(elem.findall("*")) + ['tag', 'tag', 'section'] + >>> summarize_list(elem.findall(".//tag")) + ['tag', 'tag', 'tag'] + >>> summarize_list(elem.findall("section/tag")) + ['tag'] + >>> summarize_list(elem.findall("section//tag")) + ['tag'] + >>> summarize_list(elem.findall("section/*")) + ['tag'] + >>> summarize_list(elem.findall("section//*")) + ['tag'] + >>> summarize_list(elem.findall("section/.//*")) + ['tag'] + >>> summarize_list(elem.findall("*/*")) + ['tag'] + >>> summarize_list(elem.findall("*//*")) + ['tag'] + >>> summarize_list(elem.findall("*/tag")) + ['tag'] + >>> summarize_list(elem.findall("*/./tag")) + ['tag'] + >>> summarize_list(elem.findall("./tag")) + ['tag', 'tag'] + >>> summarize_list(elem.findall(".//tag")) + ['tag', 'tag', 'tag'] + >>> summarize_list(elem.findall("././tag")) + ['tag', 'tag'] + >>> summarize_list(ET.ElementTree(elem).findall("/tag")) + ['tag', 'tag'] + >>> summarize_list(ET.ElementTree(elem).findall("./tag")) + ['tag', 'tag'] + >>> elem = ET.XML(SAMPLE_XML_NS) + >>> summarize_list(elem.findall("tag")) + [] + >>> summarize_list(elem.findall("{http://effbot.org/ns}tag")) + ['{http://effbot.org/ns}tag', '{http://effbot.org/ns}tag'] + >>> summarize_list(elem.findall(".//{http://effbot.org/ns}tag")) + ['{http://effbot.org/ns}tag', '{http://effbot.org/ns}tag', '{http://effbot.org/ns}tag'] + """ + +def parseliteral(): + r""" + + >>> element = ET.XML("<html><body>text</body></html>") + >>> ET.ElementTree(element).write(sys.stdout) + <html><body>text</body></html> + >>> element = ET.fromstring("<html><body>text</body></html>") + >>> ET.ElementTree(element).write(sys.stdout) + <html><body>text</body></html> + >>> print ET.tostring(element) + <html><body>text</body></html> + >>> print ET.tostring(element, "ascii") + <?xml version='1.0' encoding='ascii'?> + <html><body>text</body></html> + >>> _, ids = ET.XMLID("<html><body>text</body></html>") + >>> len(ids) + 0 + >>> _, ids = ET.XMLID("<html><body id='body'>text</body></html>") + >>> len(ids) + 1 + >>> ids["body"].tag + 'body' + """ + +def check_encoding(encoding): + """ + >>> check_encoding("ascii") + >>> check_encoding("us-ascii") + >>> check_encoding("iso-8859-1") + >>> check_encoding("iso-8859-15") + >>> check_encoding("cp437") + >>> check_encoding("mac-roman") + """ + ET.XML( + "<?xml version='1.0' encoding='%s'?><xml />" % encoding + ) + +def bug_1534630(): + """ + >>> bob = ET.TreeBuilder() + >>> e = bob.data("data") + >>> e = bob.start("tag", {}) + >>> e = bob.end("tag") + >>> e = bob.close() + >>> serialize(ET, e) + '<tag />' + """ + +def test_main(): + from test import test_xml_etree_c + test_support.run_doctest(test_xml_etree_c, verbosity=True) + +if __name__ == '__main__': + test_main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2009-01-24 20:11:04
|
Revision: 5971 http://jython.svn.sourceforge.net/jython/?rev=5971&view=rev Author: cgroves Date: 2009-01-24 20:10:59 +0000 (Sat, 24 Jan 2009) Log Message: ----------- Run the java import * test from a sub-interpreter to allow regrtest to be run with python.cachedir.skip=true Modified Paths: -------------- trunk/jython/Lib/test/test_java_integration.py Added Paths: ----------- trunk/jython/Lib/test/import_star_from_java.py Added: trunk/jython/Lib/test/import_star_from_java.py =================================================================== --- trunk/jython/Lib/test/import_star_from_java.py (rev 0) +++ trunk/jython/Lib/test/import_star_from_java.py 2009-01-24 20:10:59 UTC (rev 5971) @@ -0,0 +1,4 @@ +from java.util.regex import * + +p = Pattern.compile("foo") +assert p.flags() == 0 Modified: trunk/jython/Lib/test/test_java_integration.py =================================================================== --- trunk/jython/Lib/test/test_java_integration.py 2009-01-24 18:02:37 UTC (rev 5970) +++ trunk/jython/Lib/test/test_java_integration.py 2009-01-24 20:10:59 UTC (rev 5971) @@ -21,10 +21,6 @@ from org.python.core.util import FileUtil from org.python.tests import BeanImplementation, Child, Listenable, CustomizableMapHolder -#Just for test_import_star -#java.util.regex was chosen for its small number of classes to reduce the pollution. -from java.util.regex import * - class InstantiationTest(unittest.TestCase): def test_cant_instantiate_abstract(self): self.assertRaises(TypeError, Component) @@ -417,9 +413,8 @@ self.assertEquals(None, m.nonexistent, "Nonexistent fields should be passed on to the Map") def test_import_star(self): - #Depends on "from java.util.regex import *" at the top. - x = Pattern.compile("foo") - self.assertEquals(x.flags(), 0) + self.assertEquals(subprocess.call([sys.executable, + test_support.findfile("import_star_from_java.py")]), 0) def test_main(): test_support.run_unittest(InstantiationTest, This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2009-03-08 04:11:01
|
Revision: 6084 http://jython.svn.sourceforge.net/jython/?rev=6084&view=rev Author: zyasoft Date: 2009-03-08 04:10:37 +0000 (Sun, 08 Mar 2009) Log Message: ----------- Re-enabled test_asynchat for all platforms Modified Paths: -------------- trunk/jython/Lib/test/regrtest.py Removed Paths: ------------- trunk/jython/Lib/test/test_asynchat.py Modified: trunk/jython/Lib/test/regrtest.py =================================================================== --- trunk/jython/Lib/test/regrtest.py 2009-03-07 17:57:57 UTC (rev 6083) +++ trunk/jython/Lib/test/regrtest.py 2009-03-08 04:10:37 UTC (rev 6084) @@ -1535,8 +1535,6 @@ self.expected.add('test_mhlib') import platform os_name = platform.java_ver()[3][0] - if os_name == 'Mac OS X' or 'BSD' in os_name: - self.expected.add('test_asynchat') self.valid = True Deleted: trunk/jython/Lib/test/test_asynchat.py =================================================================== --- trunk/jython/Lib/test/test_asynchat.py 2009-03-07 17:57:57 UTC (rev 6083) +++ trunk/jython/Lib/test/test_asynchat.py 2009-03-08 04:10:37 UTC (rev 6084) @@ -1,100 +0,0 @@ -# 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 - -import platform -os_name = platform.java_ver()[3][0] -if os_name == 'Mac OS X' or os_name == 'SunOS' or 'BSD' in os_name \ - or 'Windows' in os_name: - raise test_support.TestSkipped('test_asynchat deadlocks on Jython: ' - 'http://bugs.jython.org/issue1064') - -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, PORT) - 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) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-03-16 23:26:39
|
Revision: 6097 http://jython.svn.sourceforge.net/jython/?rev=6097&view=rev Author: pjenvey Date: 2009-03-16 23:26:18 +0000 (Mon, 16 Mar 2009) Log Message: ----------- o re-enable test_unicode w/out the idna test o test_marshal now passes Modified Paths: -------------- trunk/jython/Lib/test/regrtest.py trunk/jython/Lib/test/test_unicode.py Modified: trunk/jython/Lib/test/regrtest.py =================================================================== --- trunk/jython/Lib/test/regrtest.py 2009-03-14 23:23:10 UTC (rev 6096) +++ trunk/jython/Lib/test/regrtest.py 2009-03-16 23:26:18 UTC (rev 6097) @@ -1475,7 +1475,6 @@ test_frozen test_gc test_iterlen - test_marshal test_multibytecodec test_multibytecodec_support test_peepholer @@ -1484,7 +1483,6 @@ test_stringprep test_transformer test_ucn - test_unicode test_unicodedata test_zipimport """, Modified: trunk/jython/Lib/test/test_unicode.py =================================================================== --- trunk/jython/Lib/test/test_unicode.py 2009-03-14 23:23:10 UTC (rev 6096) +++ trunk/jython/Lib/test/test_unicode.py 2009-03-16 23:26:18 UTC (rev 6097) @@ -712,6 +712,9 @@ self.assertEqual(x, y) def test_main(): + if test_support.is_jython: + # http://bugs.jython.org/issue1153 + del UnicodeTest.test_codecs_idna test_support.run_unittest(UnicodeTest) if __name__ == "__main__": This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-03-21 22:29:35
|
Revision: 6105 http://jython.svn.sourceforge.net/jython/?rev=6105&view=rev Author: pjenvey Date: 2009-03-21 22:29:19 +0000 (Sat, 21 Mar 2009) Log Message: ----------- o reenable test_profile, tweak the output to: - <string>:0 -> <string>:1 - don't test for profiling of Java (builtin) functions: http://bugs.jython.org/issue1281 Modified Paths: -------------- trunk/jython/Lib/test/output/test_profile trunk/jython/Lib/test/regrtest.py Modified: trunk/jython/Lib/test/output/test_profile =================================================================== --- trunk/jython/Lib/test/output/test_profile 2009-03-21 22:27:42 UTC (rev 6104) +++ trunk/jython/Lib/test/output/test_profile 2009-03-21 22:29:19 UTC (rev 6105) @@ -1,15 +1,10 @@ test_profile - 127 function calls (107 primitive calls) in 1.000 CPU seconds + 98 function calls (78 primitive calls) in 1.000 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) - 4 0.000 0.000 0.000 0.000 :0(append) - 4 0.000 0.000 0.000 0.000 :0(exc_info) - 12 0.000 0.000 0.012 0.001 :0(hasattr) - 8 0.000 0.000 0.000 0.000 :0(range) - 1 0.000 0.000 0.000 0.000 :0(setprofile) - 1 0.000 0.000 1.000 1.000 <string>:1(<module>) + 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) @@ -26,17 +21,10 @@ Ordered by: standard name Function called... -:0(append) -> -:0(exc_info) -> -:0(hasattr) -> test_profile.py:115(__getattr__)(12) 0.028 -:0(range) -> -:0(setprofile) -> -<string>:1(<module>) -> test_profile.py:30(testfunc)(1) 1.000 +<string>:0(<module>) -> test_profile.py:30(testfunc)(1) 1.000 profile:0(profiler) -> profile:0(testfunc())(1) 1.000 -profile:0(testfunc()) -> :0(setprofile)(1) 0.000 - <string>:1(<module>)(1) 1.000 -test_profile.py:103(subhelper) -> :0(range)(8) 0.000 - test_profile.py:115(__getattr__)(16) 0.028 +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 @@ -46,31 +34,24 @@ 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) -> :0(append)(4) 0.000 - :0(exc_info)(4) 0.000 - :0(hasattr)(4) 0.012 +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) -> :0(hasattr)(8) 0.012 - test_profile.py:103(subhelper)(8) 0.080 +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... -:0(append) <- test_profile.py:78(helper1)(4) 0.120 -:0(exc_info) <- test_profile.py:78(helper1)(4) 0.120 -:0(hasattr) <- test_profile.py:78(helper1)(4) 0.120 - test_profile.py:93(helper2)(8) 0.400 -:0(range) <- test_profile.py:103(subhelper)(8) 0.080 -:0(setprofile) <- profile:0(testfunc())(1) 1.000 -<string>:1(<module>) <- profile:0(testfunc())(1) 1.000 +<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__) <- :0(hasattr)(12) 0.012 +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>:1(<module>)(1) 1.000 +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 Modified: trunk/jython/Lib/test/regrtest.py =================================================================== --- trunk/jython/Lib/test/regrtest.py 2009-03-21 22:27:42 UTC (rev 6104) +++ trunk/jython/Lib/test/regrtest.py 2009-03-21 22:29:19 UTC (rev 6105) @@ -1476,7 +1476,6 @@ test_multibytecodec test_multibytecodec_support test_peepholer - test_profile test_pyclbr test_stringprep test_threadsignals This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-03-29 23:21:16
|
Revision: 6117 http://jython.svn.sourceforge.net/jython/?rev=6117&view=rev Author: pjenvey Date: 2009-03-29 23:21:00 +0000 (Sun, 29 Mar 2009) Log Message: ----------- fix failing tests: always compile the compiled version, incase the bytecode magic changes Modified Paths: -------------- trunk/jython/Lib/test/classimport.jar trunk/jython/Lib/test/classimport_Lib.jar trunk/jython/Lib/test/test_classpathimporter.py Modified: trunk/jython/Lib/test/classimport.jar =================================================================== (Binary files differ) Modified: trunk/jython/Lib/test/classimport_Lib.jar =================================================================== (Binary files differ) Modified: trunk/jython/Lib/test/test_classpathimporter.py =================================================================== --- trunk/jython/Lib/test/test_classpathimporter.py 2009-03-29 22:13:47 UTC (rev 6116) +++ trunk/jython/Lib/test/test_classpathimporter.py 2009-03-29 23:21:00 UTC (rev 6117) @@ -1,9 +1,15 @@ +import os +import py_compile +import shutil +import sys +import tempfile import unittest -import sys +import zipfile from test import test_support from java.lang import Thread class ClasspathImporterTestCase(unittest.TestCase): + def setUp(self): self.orig_context = Thread.currentThread().contextClassLoader self.orig_path = sys.path @@ -11,32 +17,7 @@ def tearDown(self): Thread.currentThread().contextClassLoader = self.orig_context sys.path = self.orig_path - try: - del sys.modules['flat_in_jar'] - del sys.modules['jar_pkg'] - del sys.modules['jar_pkg.prefer_compiled'] - except KeyError: - pass - def setClassLoaderAndCheck(self, jar, prefix): - Thread.currentThread().contextClassLoader = test_support.make_jar_classloader(jar) - import flat_in_jar - self.assertEquals(flat_in_jar.value, 7) - import jar_pkg - self.assertEquals(prefix + '/jar_pkg/__init__$py.class', jar_pkg.__file__) - from jar_pkg import prefer_compiled - self.assertEquals(prefix + '/jar_pkg/prefer_compiled$py.class', prefer_compiled.__file__) - self.assert_(prefer_compiled.compiled) - self.assertRaises(NameError, __import__, 'flat_bad') - self.assertRaises(NameError, __import__, 'jar_pkg.bad') - - def test_default_pyclasspath(self): - self.setClassLoaderAndCheck("classimport.jar", "__pyclasspath__") - - def test_path_in_pyclasspath(self): - sys.path = ['__pyclasspath__/Lib'] - self.setClassLoaderAndCheck("classimport_Lib.jar", "__pyclasspath__/Lib") - # I don't like the checked in jar file bug1239.jar. The *one* thing I # liked about the tests in bugtests/ is that you could create a java file, # compile it, jar it and destroy the jar when done. Maybe when we move to @@ -54,8 +35,65 @@ sys.path.append("Lib/test/bug1126/bug1126.jar") import org.subpackage + +class PyclasspathImporterTestCase(unittest.TestCase): + + def setUp(self): + self.orig_context = Thread.currentThread().contextClassLoader + self.orig_path = sys.path + self.temp_dir = tempfile.mkdtemp() + self.modules = sys.modules.keys() + + def tearDown(self): + Thread.currentThread().contextClassLoader = self.orig_context + sys.path = self.orig_path + shutil.rmtree(self.temp_dir) + for module in sys.modules.keys(): + if module not in self.modules: + del sys.modules[module] + + def setClassLoaderAndCheck(self, orig_jar, prefix, compile_path=''): + # Create a new jar and compile prefer_compiled into it + orig_jar = test_support.findfile(orig_jar) + jar = os.path.join(self.temp_dir, os.path.basename(orig_jar)) + shutil.copy(orig_jar, jar) + + code = os.path.join(self.temp_dir, 'prefer_compiled.py') + fp = open(code, 'w') + fp.write('compiled = True') + fp.close() + py_compile.compile(code) + zip = zipfile.ZipFile(jar, 'a') + zip.write(os.path.join(self.temp_dir, 'prefer_compiled$py.class'), + os.path.join(compile_path, 'jar_pkg', + 'prefer_compiled$py.class')) + zip.close() + zip = zipfile.ZipFile(jar) + + Thread.currentThread().contextClassLoader = test_support.make_jar_classloader(jar) + import flat_in_jar + self.assertEquals(flat_in_jar.value, 7) + import jar_pkg + self.assertEquals(prefix + '/jar_pkg/__init__.py', jar_pkg.__file__) + from jar_pkg import prefer_compiled + self.assertEquals(prefix + '/jar_pkg/prefer_compiled$py.class', prefer_compiled.__file__) + self.assert_(prefer_compiled.compiled) + self.assertRaises(NameError, __import__, 'flat_bad') + self.assertRaises(NameError, __import__, 'jar_pkg.bad') + + def test_default_pyclasspath(self): + self.setClassLoaderAndCheck('classimport.jar', '__pyclasspath__') + + def test_path_in_pyclasspath(self): + sys.path = ['__pyclasspath__/Lib'] + self.setClassLoaderAndCheck('classimport_Lib.jar', + '__pyclasspath__/Lib', 'Lib') + + def test_main(): - test_support.run_unittest(ClasspathImporterTestCase) + test_support.run_unittest(ClasspathImporterTestCase, + PyclasspathImporterTestCase) + if __name__ == '__main__': test_main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-04-04 04:12:01
|
Revision: 6158 http://jython.svn.sourceforge.net/jython/?rev=6158&view=rev Author: pjenvey Date: 2009-04-04 04:11:53 +0000 (Sat, 04 Apr 2009) Log Message: ----------- move to unicode tests Modified Paths: -------------- trunk/jython/Lib/test/test_str_jy.py trunk/jython/Lib/test/test_unicode_jy.py Modified: trunk/jython/Lib/test/test_str_jy.py =================================================================== --- trunk/jython/Lib/test/test_str_jy.py 2009-04-04 04:11:13 UTC (rev 6157) +++ trunk/jython/Lib/test/test_str_jy.py 2009-04-04 04:11:53 UTC (rev 6158) @@ -92,14 +92,7 @@ # But, args found before the first unicode should not be __unicode__'d self.assertEquals("%s %s %s" % (S(), u"bar", S()), u"str bar unicode") - def test_non_ascii_unicode_mod_str(self): - # Regression test for a problem on the formatting logic: when no unicode - # args were found, Jython stored the resulting buffer on a PyString, - # decoding it later to make a PyUnicode. That crashed when the left side - # of % was a unicode containing non-ascii chars - self.assertEquals(u"\u00e7%s" % "foo", u"\u00e7foo") - class DisplayTest(unittest.TestCase): def test_str_and_repr(self): Modified: trunk/jython/Lib/test/test_unicode_jy.py =================================================================== --- trunk/jython/Lib/test/test_unicode_jy.py 2009-04-04 04:11:13 UTC (rev 6157) +++ trunk/jython/Lib/test/test_unicode_jy.py 2009-04-04 04:11:53 UTC (rev 6158) @@ -120,7 +120,14 @@ return key u'%(foo)s' % EnsureUnicode() + def test_non_ascii_unicode_mod_str(self): + # Regression test for a problem on the formatting logic: when no unicode + # args were found, Jython stored the resulting buffer on a PyString, + # decoding it later to make a PyUnicode. That crashed when the left side + # of % was a unicode containing non-ascii chars + self.assertEquals(u"\u00e7%s" % "foo", u"\u00e7foo") + def test_main(): test_support.run_unittest(UnicodeTestCase, UnicodeFormatTestCase) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-04-07 00:37:55
|
Revision: 6179 http://jython.svn.sourceforge.net/jython/?rev=6179&view=rev Author: pjenvey Date: 2009-04-07 00:37:45 +0000 (Tue, 07 Apr 2009) Log Message: ----------- these now match CPythonLib's Removed Paths: ------------- trunk/jython/Lib/test/cfgparser.1 trunk/jython/Lib/test/test_doctest.py Deleted: trunk/jython/Lib/test/cfgparser.1 =================================================================== --- trunk/jython/Lib/test/cfgparser.1 2009-04-07 00:33:46 UTC (rev 6178) +++ trunk/jython/Lib/test/cfgparser.1 2009-04-07 00:37:45 UTC (rev 6179) @@ -1,2 +0,0 @@ -[Foo Bar] -foo=newbar Deleted: trunk/jython/Lib/test/test_doctest.py =================================================================== --- trunk/jython/Lib/test/test_doctest.py 2009-04-07 00:33:46 UTC (rev 6178) +++ trunk/jython/Lib/test/test_doctest.py 2009-04-07 00:37:45 UTC (rev 6179) @@ -1,2437 +0,0 @@ -""" -Test script for doctest. -""" - -from test import test_support -import doctest -import warnings - -###################################################################### -## Sample Objects (used by test cases) -###################################################################### - -def sample_func(v): - """ - Blah blah - - >>> print sample_func(22) - 44 - - Yee ha! - """ - return v+v - -class SampleClass: - """ - >>> print 1 - 1 - - >>> # comments get ignored. so are empty PS1 and PS2 prompts: - >>> - ... - - Multiline example: - >>> sc = SampleClass(3) - >>> for i in range(10): - ... sc = sc.double() - ... print sc.get(), - 6 12 24 48 96 192 384 768 1536 3072 - """ - def __init__(self, val): - """ - >>> print SampleClass(12).get() - 12 - """ - self.val = val - - def double(self): - """ - >>> print SampleClass(12).double().get() - 24 - """ - return SampleClass(self.val + self.val) - - def get(self): - """ - >>> print SampleClass(-5).get() - -5 - """ - return self.val - - def a_staticmethod(v): - """ - >>> print SampleClass.a_staticmethod(10) - 11 - """ - return v+1 - a_staticmethod = staticmethod(a_staticmethod) - - def a_classmethod(cls, v): - """ - >>> print SampleClass.a_classmethod(10) - 12 - >>> print SampleClass(0).a_classmethod(10) - 12 - """ - return v+2 - a_classmethod = classmethod(a_classmethod) - - a_property = property(get, doc=""" - >>> print SampleClass(22).a_property - 22 - """) - - class NestedClass: - """ - >>> x = SampleClass.NestedClass(5) - >>> y = x.square() - >>> print y.get() - 25 - """ - def __init__(self, val=0): - """ - >>> print SampleClass.NestedClass().get() - 0 - """ - self.val = val - def square(self): - return SampleClass.NestedClass(self.val*self.val) - def get(self): - return self.val - -class SampleNewStyleClass(object): - r""" - >>> print '1\n2\n3' - 1 - 2 - 3 - """ - def __init__(self, val): - """ - >>> print SampleNewStyleClass(12).get() - 12 - """ - self.val = val - - def double(self): - """ - >>> print SampleNewStyleClass(12).double().get() - 24 - """ - return SampleNewStyleClass(self.val + self.val) - - def get(self): - """ - >>> print SampleNewStyleClass(-5).get() - -5 - """ - return self.val - -###################################################################### -## Fake stdin (for testing interactive debugging) -###################################################################### - -class _FakeInput: - """ - A fake input stream for pdb's interactive debugger. Whenever a - line is read, print it (to simulate the user typing it), and then - return it. The set of lines to return is specified in the - constructor; they should not have trailing newlines. - """ - def __init__(self, lines): - self.lines = lines - - def readline(self): - line = self.lines.pop(0) - print line - return line+'\n' - -###################################################################### -## Test Cases -###################################################################### - -def test_Example(): r""" -Unit tests for the `Example` class. - -Example is a simple container class that holds: - - `source`: A source string. - - `want`: An expected output string. - - `exc_msg`: An expected exception message string (or None if no - exception is expected). - - `lineno`: A line number (within the docstring). - - `indent`: The example's indentation in the input string. - - `options`: An option dictionary, mapping option flags to True or - False. - -These attributes are set by the constructor. `source` and `want` are -required; the other attributes all have default values: - - >>> example = doctest.Example('print 1', '1\n') - >>> (example.source, example.want, example.exc_msg, - ... example.lineno, example.indent, example.options) - ('print 1\n', '1\n', None, 0, 0, {}) - -The first three attributes (`source`, `want`, and `exc_msg`) may be -specified positionally; the remaining arguments should be specified as -keyword arguments: - - >>> exc_msg = 'IndexError: pop from an empty list' - >>> example = doctest.Example('[].pop()', '', exc_msg, - ... lineno=5, indent=4, - ... options={doctest.ELLIPSIS: True}) - >>> (example.source, example.want, example.exc_msg, - ... example.lineno, example.indent, example.options) - ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True}) - -The constructor normalizes the `source` string to end in a newline: - - Source spans a single line: no terminating newline. - >>> e = doctest.Example('print 1', '1\n') - >>> e.source, e.want - ('print 1\n', '1\n') - - >>> e = doctest.Example('print 1\n', '1\n') - >>> e.source, e.want - ('print 1\n', '1\n') - - Source spans multiple lines: require terminating newline. - >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n') - >>> e.source, e.want - ('print 1;\nprint 2\n', '1\n2\n') - - >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n') - >>> e.source, e.want - ('print 1;\nprint 2\n', '1\n2\n') - - Empty source string (which should never appear in real examples) - >>> e = doctest.Example('', '') - >>> e.source, e.want - ('\n', '') - -The constructor normalizes the `want` string to end in a newline, -unless it's the empty string: - - >>> e = doctest.Example('print 1', '1\n') - >>> e.source, e.want - ('print 1\n', '1\n') - - >>> e = doctest.Example('print 1', '1') - >>> e.source, e.want - ('print 1\n', '1\n') - - >>> e = doctest.Example('print', '') - >>> e.source, e.want - ('print\n', '') - -The constructor normalizes the `exc_msg` string to end in a newline, -unless it's `None`: - - Message spans one line - >>> exc_msg = 'IndexError: pop from an empty list' - >>> e = doctest.Example('[].pop()', '', exc_msg) - >>> e.exc_msg - 'IndexError: pop from an empty list\n' - - >>> exc_msg = 'IndexError: pop from an empty list\n' - >>> e = doctest.Example('[].pop()', '', exc_msg) - >>> e.exc_msg - 'IndexError: pop from an empty list\n' - - Message spans multiple lines - >>> exc_msg = 'ValueError: 1\n 2' - >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg) - >>> e.exc_msg - 'ValueError: 1\n 2\n' - - >>> exc_msg = 'ValueError: 1\n 2\n' - >>> e = doctest.Example('raise ValueError("1\n 2")', '', exc_msg) - >>> e.exc_msg - 'ValueError: 1\n 2\n' - - Empty (but non-None) exception message (which should never appear - in real examples) - >>> exc_msg = '' - >>> e = doctest.Example('raise X()', '', exc_msg) - >>> e.exc_msg - '\n' -""" - -def test_DocTest(): r""" -Unit tests for the `DocTest` class. - -DocTest is a collection of examples, extracted from a docstring, along -with information about where the docstring comes from (a name, -filename, and line number). The docstring is parsed by the `DocTest` -constructor: - - >>> docstring = ''' - ... >>> print 12 - ... 12 - ... - ... Non-example text. - ... - ... >>> print 'another\example' - ... another - ... example - ... ''' - >>> globs = {} # globals to run the test in. - >>> parser = doctest.DocTestParser() - >>> test = parser.get_doctest(docstring, globs, 'some_test', - ... 'some_file', 20) - >>> print test - <DocTest some_test from some_file:20 (2 examples)> - >>> len(test.examples) - 2 - >>> e1, e2 = test.examples - >>> (e1.source, e1.want, e1.lineno) - ('print 12\n', '12\n', 1) - >>> (e2.source, e2.want, e2.lineno) - ("print 'another\\example'\n", 'another\nexample\n', 6) - -Source information (name, filename, and line number) is available as -attributes on the doctest object: - - >>> (test.name, test.filename, test.lineno) - ('some_test', 'some_file', 20) - -The line number of an example within its containing file is found by -adding the line number of the example and the line number of its -containing test: - - >>> test.lineno + e1.lineno - 21 - >>> test.lineno + e2.lineno - 26 - -If the docstring contains inconsistant leading whitespace in the -expected output of an example, then `DocTest` will raise a ValueError: - - >>> docstring = r''' - ... >>> print 'bad\nindentation' - ... bad - ... indentation - ... ''' - >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) - Traceback (most recent call last): - ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation' - -If the docstring contains inconsistent leading whitespace on -continuation lines, then `DocTest` will raise a ValueError: - - >>> docstring = r''' - ... >>> print ('bad indentation', - ... ... 2) - ... ('bad', 'indentation') - ... ''' - >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) - Traceback (most recent call last): - ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)' - -If there's no blank space after a PS1 prompt ('>>>'), then `DocTest` -will raise a ValueError: - - >>> docstring = '>>>print 1\n1' - >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) - Traceback (most recent call last): - ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1' - -If there's no blank space after a PS2 prompt ('...'), then `DocTest` -will raise a ValueError: - - >>> docstring = '>>> if 1:\n...print 1\n1' - >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0) - Traceback (most recent call last): - ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1' - -""" - -def test_DocTestFinder(): r""" -Unit tests for the `DocTestFinder` class. - -DocTestFinder is used to extract DocTests from an object's docstring -and the docstrings of its contained objects. It can be used with -modules, functions, classes, methods, staticmethods, classmethods, and -properties. - -Finding Tests in Functions -~~~~~~~~~~~~~~~~~~~~~~~~~~ -For a function whose docstring contains examples, DocTestFinder.find() -will return a single test (for that function's docstring): - - >>> finder = doctest.DocTestFinder() - -We'll simulate a __file__ attr that ends in pyc: - - >>> import test.test_doctest - >>> old = test.test_doctest.__file__ - >>> test.test_doctest.__file__ = 'test_doctest.pyc' - - >>> tests = finder.find(sample_func) - - >>> print tests # doctest: +ELLIPSIS - [<DocTest sample_func from ...:13 (1 example)>] - -The exact name depends on how test_doctest was invoked, so allow for -leading path components. - - >>> tests[0].filename # doctest: +ELLIPSIS - '...test_doctest.py' - - >>> test.test_doctest.__file__ = old - - - >>> e = tests[0].examples[0] - >>> (e.source, e.want, e.lineno) - ('print sample_func(22)\n', '44\n', 3) - -By default, tests are created for objects with no docstring: - - >>> def no_docstring(v): - ... pass - >>> finder.find(no_docstring) - [] - -However, the optional argument `exclude_empty` to the DocTestFinder -constructor can be used to exclude tests for objects with empty -docstrings: - - >>> def no_docstring(v): - ... pass - >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True) - >>> excl_empty_finder.find(no_docstring) - [] - -If the function has a docstring with no examples, then a test with no -examples is returned. (This lets `DocTestRunner` collect statistics -about which functions have no tests -- but is that useful? And should -an empty test also be created when there's no docstring?) - - >>> def no_examples(v): - ... ''' no doctest examples ''' - >>> finder.find(no_examples) # doctest: +ELLIPSIS - [<DocTest no_examples from ...:1 (no examples)>] - -Finding Tests in Classes -~~~~~~~~~~~~~~~~~~~~~~~~ -For a class, DocTestFinder will create a test for the class's -docstring, and will recursively explore its contents, including -methods, classmethods, staticmethods, properties, and nested classes. - - >>> finder = doctest.DocTestFinder() - >>> tests = finder.find(SampleClass) - >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) - 3 SampleClass - 3 SampleClass.NestedClass - 1 SampleClass.NestedClass.__init__ - 1 SampleClass.__init__ - 2 SampleClass.a_classmethod - 1 SampleClass.a_property - 1 SampleClass.a_staticmethod - 1 SampleClass.double - 1 SampleClass.get - -New-style classes are also supported: - - >>> tests = finder.find(SampleNewStyleClass) - >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) - 1 SampleNewStyleClass - 1 SampleNewStyleClass.__init__ - 1 SampleNewStyleClass.double - 1 SampleNewStyleClass.get - -Finding Tests in Modules -~~~~~~~~~~~~~~~~~~~~~~~~ -For a module, DocTestFinder will create a test for the class's -docstring, and will recursively explore its contents, including -functions, classes, and the `__test__` dictionary, if it exists: - - >>> # A module - >>> import new - >>> m = new.module('some_module') - >>> def triple(val): - ... ''' - ... >>> print triple(11) - ... 33 - ... ''' - ... return val*3 - >>> m.__dict__.update({ - ... 'sample_func': sample_func, - ... 'SampleClass': SampleClass, - ... '__doc__': ''' - ... Module docstring. - ... >>> print 'module' - ... module - ... ''', - ... '__test__': { - ... 'd': '>>> print 6\n6\n>>> print 7\n7\n', - ... 'c': triple}}) - - >>> finder = doctest.DocTestFinder() - >>> # Use module=test.test_doctest, to prevent doctest from - >>> # ignoring the objects since they weren't defined in m. - >>> import test.test_doctest - >>> tests = finder.find(m, module=test.test_doctest) - >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) - 1 some_module - 3 some_module.SampleClass - 3 some_module.SampleClass.NestedClass - 1 some_module.SampleClass.NestedClass.__init__ - 1 some_module.SampleClass.__init__ - 2 some_module.SampleClass.a_classmethod - 1 some_module.SampleClass.a_property - 1 some_module.SampleClass.a_staticmethod - 1 some_module.SampleClass.double - 1 some_module.SampleClass.get - 1 some_module.__test__.c - 2 some_module.__test__.d - 1 some_module.sample_func - -Duplicate Removal -~~~~~~~~~~~~~~~~~ -If a single object is listed twice (under different names), then tests -will only be generated for it once: - - >>> from test import doctest_aliases - >>> tests = excl_empty_finder.find(doctest_aliases) - >>> print len(tests) - 2 - >>> print tests[0].name - test.doctest_aliases.TwoNames - - TwoNames.f and TwoNames.g are bound to the same object. - We can't guess which will be found in doctest's traversal of - TwoNames.__dict__ first, so we have to allow for either. - - >>> tests[1].name.split('.')[-1] in ['f', 'g'] - True - -Empty Tests -~~~~~~~~~~~ -By default, an object with no doctests doesn't create any tests: - - >>> tests = doctest.DocTestFinder().find(SampleClass) - >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) - 3 SampleClass - 3 SampleClass.NestedClass - 1 SampleClass.NestedClass.__init__ - 1 SampleClass.__init__ - 2 SampleClass.a_classmethod - 1 SampleClass.a_property - 1 SampleClass.a_staticmethod - 1 SampleClass.double - 1 SampleClass.get - -By default, that excluded objects with no doctests. exclude_empty=False -tells it to include (empty) tests for objects with no doctests. This feature -is really to support backward compatibility in what doctest.master.summarize() -displays. - - >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass) - >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) - 3 SampleClass - 3 SampleClass.NestedClass - 1 SampleClass.NestedClass.__init__ - 0 SampleClass.NestedClass.get - 0 SampleClass.NestedClass.square - 1 SampleClass.__init__ - 2 SampleClass.a_classmethod - 1 SampleClass.a_property - 1 SampleClass.a_staticmethod - 1 SampleClass.double - 1 SampleClass.get - -Turning off Recursion -~~~~~~~~~~~~~~~~~~~~~ -DocTestFinder can be told not to look for tests in contained objects -using the `recurse` flag: - - >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass) - >>> for t in tests: - ... print '%2s %s' % (len(t.examples), t.name) - 3 SampleClass - -Line numbers -~~~~~~~~~~~~ -DocTestFinder finds the line number of each example: - - >>> def f(x): - ... ''' - ... >>> x = 12 - ... - ... some text - ... - ... >>> # examples are not created for comments & bare prompts. - ... >>> - ... ... - ... - ... >>> for x in range(10): - ... ... print x, - ... 0 1 2 3 4 5 6 7 8 9 - ... >>> x//2 - ... 6 - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> [e.lineno for e in test.examples] - [1, 9, 12] -""" - -def test_DocTestParser(): r""" -Unit tests for the `DocTestParser` class. - -DocTestParser is used to parse docstrings containing doctest examples. - -The `parse` method divides a docstring into examples and intervening -text: - - >>> s = ''' - ... >>> x, y = 2, 3 # no output expected - ... >>> if 1: - ... ... print x - ... ... print y - ... 2 - ... 3 - ... - ... Some text. - ... >>> x+y - ... 5 - ... ''' - >>> parser = doctest.DocTestParser() - >>> for piece in parser.parse(s): - ... if isinstance(piece, doctest.Example): - ... print 'Example:', (piece.source, piece.want, piece.lineno) - ... else: - ... print ' Text:', `piece` - Text: '\n' - Example: ('x, y = 2, 3 # no output expected\n', '', 1) - Text: '' - Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2) - Text: '\nSome text.\n' - Example: ('x+y\n', '5\n', 9) - Text: '' - -The `get_examples` method returns just the examples: - - >>> for piece in parser.get_examples(s): - ... print (piece.source, piece.want, piece.lineno) - ('x, y = 2, 3 # no output expected\n', '', 1) - ('if 1:\n print x\n print y\n', '2\n3\n', 2) - ('x+y\n', '5\n', 9) - -The `get_doctest` method creates a Test from the examples, along with the -given arguments: - - >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5) - >>> (test.name, test.filename, test.lineno) - ('name', 'filename', 5) - >>> for piece in test.examples: - ... print (piece.source, piece.want, piece.lineno) - ('x, y = 2, 3 # no output expected\n', '', 1) - ('if 1:\n print x\n print y\n', '2\n3\n', 2) - ('x+y\n', '5\n', 9) -""" - -class test_DocTestRunner: - def basics(): r""" -Unit tests for the `DocTestRunner` class. - -DocTestRunner is used to run DocTest test cases, and to accumulate -statistics. Here's a simple DocTest case we can use: - - >>> def f(x): - ... ''' - ... >>> x = 12 - ... >>> print x - ... 12 - ... >>> x//2 - ... 6 - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - -The main DocTestRunner interface is the `run` method, which runs a -given DocTest case in a given namespace (globs). It returns a tuple -`(f,t)`, where `f` is the number of failed tests and `t` is the number -of tried tests. - - >>> doctest.DocTestRunner(verbose=False).run(test) - (0, 3) - -If any example produces incorrect output, then the test runner reports -the failure and proceeds to the next example: - - >>> def f(x): - ... ''' - ... >>> x = 12 - ... >>> print x - ... 14 - ... >>> x//2 - ... 6 - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=True).run(test) - ... # doctest: +ELLIPSIS - Trying: - x = 12 - Expecting nothing - ok - Trying: - print x - Expecting: - 14 - ********************************************************************** - File ..., line 4, in f - Failed example: - print x - Expected: - 14 - Got: - 12 - Trying: - x//2 - Expecting: - 6 - ok - (1, 3) -""" - def verbose_flag(): r""" -The `verbose` flag makes the test runner generate more detailed -output: - - >>> def f(x): - ... ''' - ... >>> x = 12 - ... >>> print x - ... 12 - ... >>> x//2 - ... 6 - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - - >>> doctest.DocTestRunner(verbose=True).run(test) - Trying: - x = 12 - Expecting nothing - ok - Trying: - print x - Expecting: - 12 - ok - Trying: - x//2 - Expecting: - 6 - ok - (0, 3) - -If the `verbose` flag is unspecified, then the output will be verbose -iff `-v` appears in sys.argv: - - >>> # Save the real sys.argv list. - >>> old_argv = sys.argv - - >>> # If -v does not appear in sys.argv, then output isn't verbose. - >>> sys.argv = ['test'] - >>> doctest.DocTestRunner().run(test) - (0, 3) - - >>> # If -v does appear in sys.argv, then output is verbose. - >>> sys.argv = ['test', '-v'] - >>> doctest.DocTestRunner().run(test) - Trying: - x = 12 - Expecting nothing - ok - Trying: - print x - Expecting: - 12 - ok - Trying: - x//2 - Expecting: - 6 - ok - (0, 3) - - >>> # Restore sys.argv - >>> sys.argv = old_argv - -In the remaining examples, the test runner's verbosity will be -explicitly set, to ensure that the test behavior is consistent. - """ - def exceptions(): r""" -Tests of `DocTestRunner`'s exception handling. - -An expected exception is specified with a traceback message. The -lines between the first line and the type/value may be omitted or -replaced with any other string: - - >>> def f(x): - ... ''' - ... >>> x = 12 - ... >>> print x//0 - ... Traceback (most recent call last): - ... ZeroDivisionError: integer division or modulo by zero - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - (0, 2) - -An example may not generate output before it raises an exception; if -it does, then the traceback message will not be recognized as -signaling an expected exception, so the example will be reported as an -unexpected exception: - - >>> def f(x): - ... ''' - ... >>> x = 12 - ... >>> print 'pre-exception output', x//0 - ... pre-exception output - ... Traceback (most recent call last): - ... ZeroDivisionError: integer division or modulo by zero - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 4, in f - Failed example: - print 'pre-exception output', x//0 - Exception raised: - ... - ZeroDivisionError: integer division or modulo by zero - (1, 2) - -Exception messages may contain newlines: - - >>> def f(x): - ... r''' - ... >>> raise ValueError, 'multi\nline\nmessage' - ... Traceback (most recent call last): - ... ValueError: multi - ... line - ... message - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - (0, 1) - -If an exception is expected, but an exception with the wrong type or -message is raised, then it is reported as a failure: - - >>> def f(x): - ... r''' - ... >>> raise ValueError, 'message' - ... Traceback (most recent call last): - ... ValueError: wrong message - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 3, in f - Failed example: - raise ValueError, 'message' - Expected: - Traceback (most recent call last): - ValueError: wrong message - Got: - Traceback (most recent call last): - ... - ValueError: message - (1, 1) - -However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the -detail: - - >>> def f(x): - ... r''' - ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL - ... Traceback (most recent call last): - ... ValueError: wrong message - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - (0, 1) - -But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type: - - >>> def f(x): - ... r''' - ... >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL - ... Traceback (most recent call last): - ... TypeError: wrong type - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 3, in f - Failed example: - raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL - Expected: - Traceback (most recent call last): - TypeError: wrong type - Got: - Traceback (most recent call last): - ... - ValueError: message - (1, 1) - -If an exception is raised but not expected, then it is reported as an -unexpected exception: - - >>> def f(x): - ... r''' - ... >>> 1//0 - ... 0 - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 3, in f - Failed example: - 1//0 - Exception raised: - Traceback (most recent call last): - ... - ZeroDivisionError: integer division or modulo by zero - (1, 1) -""" - def optionflags(): r""" -Tests of `DocTestRunner`'s option flag handling. - -Several option flags can be used to customize the behavior of the test -runner. These are defined as module constants in doctest, and passed -to the DocTestRunner constructor (multiple constants should be or-ed -together). - -The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False -and 1/0: - - >>> def f(x): - ... '>>> True\n1\n' - - >>> # Without the flag: - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - (0, 1) - - >>> # With the flag: - >>> test = doctest.DocTestFinder().find(f)[0] - >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1 - >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 2, in f - Failed example: - True - Expected: - 1 - Got: - True - (1, 1) - -The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines -and the '<BLANKLINE>' marker: - - >>> def f(x): - ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n' - - >>> # Without the flag: - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - (0, 1) - - >>> # With the flag: - >>> test = doctest.DocTestFinder().find(f)[0] - >>> flags = doctest.DONT_ACCEPT_BLANKLINE - >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 2, in f - Failed example: - print "a\n\nb" - Expected: - a - <BLANKLINE> - b - Got: - a - <BLANKLINE> - b - (1, 1) - -The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be -treated as equal: - - >>> def f(x): - ... '>>> print 1, 2, 3\n 1 2\n 3' - - >>> # Without the flag: - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 2, in f - Failed example: - print 1, 2, 3 - Expected: - 1 2 - 3 - Got: - 1 2 3 - (1, 1) - - >>> # With the flag: - >>> test = doctest.DocTestFinder().find(f)[0] - >>> flags = doctest.NORMALIZE_WHITESPACE - >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test) - (0, 1) - - An example from the docs: - >>> print range(20) #doctest: +NORMALIZE_WHITESPACE - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, - 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] - -The ELLIPSIS flag causes ellipsis marker ("...") in the expected -output to match any substring in the actual output: - - >>> def f(x): - ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n' - - >>> # Without the flag: - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 2, in f - Failed example: - print range(15) - Expected: - [0, 1, 2, ..., 14] - Got: - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] - (1, 1) - - >>> # With the flag: - >>> test = doctest.DocTestFinder().find(f)[0] - >>> flags = doctest.ELLIPSIS - >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test) - (0, 1) - - ... also matches nothing: - - >>> for i in range(100): - ... print i**2, #doctest: +ELLIPSIS - 0 1...4...9 16 ... 36 49 64 ... 9801 - - ... can be surprising; e.g., this test passes: - - >>> for i in range(21): #doctest: +ELLIPSIS - ... print i, - 0 1 2 ...1...2...0 - - Examples from the docs: - - >>> print range(20) # doctest:+ELLIPSIS - [0, 1, ..., 18, 19] - - >>> print range(20) # doctest: +ELLIPSIS - ... # doctest: +NORMALIZE_WHITESPACE - [0, 1, ..., 18, 19] - -The SKIP flag causes an example to be skipped entirely. I.e., the -example is not run. It can be useful in contexts where doctest -examples serve as both documentation and test cases, and an example -should be included for documentation purposes, but should not be -checked (e.g., because its output is random, or depends on resources -which would be unavailable.) The SKIP flag can also be used for -'commenting out' broken examples. - - >>> import unavailable_resource # doctest: +SKIP - >>> unavailable_resource.do_something() # doctest: +SKIP - >>> unavailable_resource.blow_up() # doctest: +SKIP - Traceback (most recent call last): - ... - UncheckedBlowUpError: Nobody checks me. - - >>> import random - >>> print random.random() # doctest: +SKIP - 0.721216923889 - -The REPORT_UDIFF flag causes failures that involve multi-line expected -and actual outputs to be displayed using a unified diff: - - >>> def f(x): - ... r''' - ... >>> print '\n'.join('abcdefg') - ... a - ... B - ... c - ... d - ... f - ... g - ... h - ... ''' - - >>> # Without the flag: - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 3, in f - Failed example: - print '\n'.join('abcdefg') - Expected: - a - B - c - d - f - g - h - Got: - a - b - c - d - e - f - g - (1, 1) - - >>> # With the flag: - >>> test = doctest.DocTestFinder().find(f)[0] - >>> flags = doctest.REPORT_UDIFF - >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 3, in f - Failed example: - print '\n'.join('abcdefg') - Differences (unified diff with -expected +actual): - @@ -1,7 +1,7 @@ - a - -B - +b - c - d - +e - f - g - -h - (1, 1) - -The REPORT_CDIFF flag causes failures that involve multi-line expected -and actual outputs to be displayed using a context diff: - - >>> # Reuse f() from the REPORT_UDIFF example, above. - >>> test = doctest.DocTestFinder().find(f)[0] - >>> flags = doctest.REPORT_CDIFF - >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 3, in f - Failed example: - print '\n'.join('abcdefg') - Differences (context diff with expected followed by actual): - *************** - *** 1,7 **** - a - ! B - c - d - f - g - - h - --- 1,7 ---- - a - ! b - c - d - + e - f - g - (1, 1) - - -The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm -used by the popular ndiff.py utility. This does intraline difference -marking, as well as interline differences. - - >>> def f(x): - ... r''' - ... >>> print "a b c d e f g h i j k l m" - ... a b c d e f g h i j k 1 m - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> flags = doctest.REPORT_NDIFF - >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 3, in f - Failed example: - print "a b c d e f g h i j k l m" - Differences (ndiff with -expected +actual): - - a b c d e f g h i j k 1 m - ? ^ - + a b c d e f g h i j k l m - ? + ++ ^ - (1, 1) - -The REPORT_ONLY_FIRST_FAILURE supresses result output after the first -failing example: - - >>> def f(x): - ... r''' - ... >>> print 1 # first success - ... 1 - ... >>> print 2 # first failure - ... 200 - ... >>> print 3 # second failure - ... 300 - ... >>> print 4 # second success - ... 4 - ... >>> print 5 # third failure - ... 500 - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE - >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 5, in f - Failed example: - print 2 # first failure - Expected: - 200 - Got: - 2 - (3, 5) - -However, output from `report_start` is not supressed: - - >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test) - ... # doctest: +ELLIPSIS - Trying: - print 1 # first success - Expecting: - 1 - ok - Trying: - print 2 # first failure - Expecting: - 200 - ********************************************************************** - File ..., line 5, in f - Failed example: - print 2 # first failure - Expected: - 200 - Got: - 2 - (3, 5) - -For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions -count as failures: - - >>> def f(x): - ... r''' - ... >>> print 1 # first success - ... 1 - ... >>> raise ValueError(2) # first failure - ... 200 - ... >>> print 3 # second failure - ... 300 - ... >>> print 4 # second success - ... 4 - ... >>> print 5 # third failure - ... 500 - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE - >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 5, in f - Failed example: - raise ValueError(2) # first failure - Exception raised: - ... - ValueError: 2 - (3, 5) - -New option flags can also be registered, via register_optionflag(). Here -we reach into doctest's internals a bit. - - >>> unlikely = "UNLIKELY_OPTION_NAME" - >>> unlikely in doctest.OPTIONFLAGS_BY_NAME - False - >>> new_flag_value = doctest.register_optionflag(unlikely) - >>> unlikely in doctest.OPTIONFLAGS_BY_NAME - True - -Before 2.4.4/2.5, registering a name more than once erroneously created -more than one flag value. Here we verify that's fixed: - - >>> redundant_flag_value = doctest.register_optionflag(unlikely) - >>> redundant_flag_value == new_flag_value - True - -Clean up. - >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely] - - """ - - def option_directives(): r""" -Tests of `DocTestRunner`'s option directive mechanism. - -Option directives can be used to turn option flags on or off for a -single example. To turn an option on for an example, follow that -example with a comment of the form ``# doctest: +OPTION``: - - >>> def f(x): r''' - ... >>> print range(10) # should fail: no ellipsis - ... [0, 1, ..., 9] - ... - ... >>> print range(10) # doctest: +ELLIPSIS - ... [0, 1, ..., 9] - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 2, in f - Failed example: - print range(10) # should fail: no ellipsis - Expected: - [0, 1, ..., 9] - Got: - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - (1, 2) - -To turn an option off for an example, follow that example with a -comment of the form ``# doctest: -OPTION``: - - >>> def f(x): r''' - ... >>> print range(10) - ... [0, 1, ..., 9] - ... - ... >>> # should fail: no ellipsis - ... >>> print range(10) # doctest: -ELLIPSIS - ... [0, 1, ..., 9] - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False, - ... optionflags=doctest.ELLIPSIS).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 6, in f - Failed example: - print range(10) # doctest: -ELLIPSIS - Expected: - [0, 1, ..., 9] - Got: - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - (1, 2) - -Option directives affect only the example that they appear with; they -do not change the options for surrounding examples: - - >>> def f(x): r''' - ... >>> print range(10) # Should fail: no ellipsis - ... [0, 1, ..., 9] - ... - ... >>> print range(10) # doctest: +ELLIPSIS - ... [0, 1, ..., 9] - ... - ... >>> print range(10) # Should fail: no ellipsis - ... [0, 1, ..., 9] - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 2, in f - Failed example: - print range(10) # Should fail: no ellipsis - Expected: - [0, 1, ..., 9] - Got: - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - ********************************************************************** - File ..., line 8, in f - Failed example: - print range(10) # Should fail: no ellipsis - Expected: - [0, 1, ..., 9] - Got: - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - (2, 3) - -Multiple options may be modified by a single option directive. They -may be separated by whitespace, commas, or both: - - >>> def f(x): r''' - ... >>> print range(10) # Should fail - ... [0, 1, ..., 9] - ... >>> print range(10) # Should succeed - ... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE - ... [0, 1, ..., 9] - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 2, in f - Failed example: - print range(10) # Should fail - Expected: - [0, 1, ..., 9] - Got: - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - (1, 2) - - >>> def f(x): r''' - ... >>> print range(10) # Should fail - ... [0, 1, ..., 9] - ... >>> print range(10) # Should succeed - ... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE - ... [0, 1, ..., 9] - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 2, in f - Failed example: - print range(10) # Should fail - Expected: - [0, 1, ..., 9] - Got: - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - (1, 2) - - >>> def f(x): r''' - ... >>> print range(10) # Should fail - ... [0, 1, ..., 9] - ... >>> print range(10) # Should succeed - ... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE - ... [0, 1, ..., 9] - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - ... # doctest: +ELLIPSIS - ********************************************************************** - File ..., line 2, in f - Failed example: - print range(10) # Should fail - Expected: - [0, 1, ..., 9] - Got: - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - (1, 2) - -The option directive may be put on the line following the source, as -long as a continuation prompt is used: - - >>> def f(x): r''' - ... >>> print range(10) - ... ... # doctest: +ELLIPSIS - ... [0, 1, ..., 9] - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - (0, 1) - -For examples with multi-line source, the option directive may appear -at the end of any line: - - >>> def f(x): r''' - ... >>> for x in range(10): # doctest: +ELLIPSIS - ... ... print x, - ... 0 1 2 ... 9 - ... - ... >>> for x in range(10): - ... ... print x, # doctest: +ELLIPSIS - ... 0 1 2 ... 9 - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - (0, 2) - -If more than one line of an example with multi-line source has an -option directive, then they are combined: - - >>> def f(x): r''' - ... Should fail (option directive not on the last line): - ... >>> for x in range(10): # doctest: +ELLIPSIS - ... ... print x, # doctest: +NORMALIZE_WHITESPACE - ... 0 1 2...9 - ... ''' - >>> test = doctest.DocTestFinder().find(f)[0] - >>> doctest.DocTestRunner(verbose=False).run(test) - (0, 1) - -It is an error to have a comment of the form ``# doctest:`` that is -*not* followed by words of the form ``+OPTION`` or ``-OPTION``, where -``OPTION`` is an option that has been registered with -`register_option`: - - >>> # Error: Option not registered - >>> s = '>>> print 12 #doctest: +BADOPTION' - >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0) - Traceback (most recent call last): - ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION' - - >>> # Error: No + or - prefix - >>> s = '>>> print 12 #doctest: ELLIPSIS' - >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0) - Traceback (most recent call last): - ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS' - -It is an error to use an option directive on a line that contains no -source: - - >>> s = '>>> # doctest: +ELLIPSIS' - >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0) - Traceback (most recent call last): - ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS' -""" - -def test_testsource(): r""" -Unit tests for `testsource()`. - -The testsource() function takes a module and a name, finds the (first) -test with that name in that module, and converts it to a script. The -example code is converted to regular Python code. The surrounding -words and expected output are converted to comments: - - >>> import test.test_doctest - >>> name = 'test.test_doctest.sample_func' - >>> print doctest.testsource(test.test_doctest, name) - # Blah blah - # - print sample_func(22) - # Expected: - ## 44 - # - # Yee ha! - <BLANKLINE> - - >>> name = 'test.test_doctest.SampleNewStyleClass' - >>> print doctest.testsource(test.test_doctest, name) - print '1\n2\n3' - # Expected: - ## 1 - ## 2 - ## 3 - <BLANKLINE> - - >>> name = 'test.test_doctest.SampleClass.a_classmethod' - >>> print doctest.testsource(test.test_doctest, name) - print SampleClass.a_classmethod(10) - # Expected: - ## 12 - print SampleClass(0).a_classmethod(10) - # Expected: - ## 12 - <BLANKLINE> -""" - -def test_debug(): r""" - -Create a docstring that we want to debug: - - >>> s = ''' - ... >>> x = 12 - ... >>> print x - ... 12 - ... ''' - -Create some fake stdin input, to feed to the debugger: - - >>> import tempfile - >>> real_stdin = sys.stdin - >>> sys.stdin = _FakeInput(['next', 'print x', 'continue']) - -Run the debugger on the docstring, and then restore sys.stdin. - - >>> try: doctest.debug_src(s) - ... finally: sys.stdin = real_stdin - > <string>(1)<module>() - (Pdb) next - 12 - --Return-- - > <string>(1)<module>()->None - (Pdb) print x - 12 - (Pdb) continue - -""" - -def test_pdb_set_trace(): - """Using pdb.set_trace from a doctest. - - You can use pdb.set_trace from a doctest. To do so, you must - retrieve the set_trace function from the pdb module at the time - you use it. The doctest module changes sys.stdout so that it can - capture program output. It also temporarily replaces pdb.set_trace - with a version that restores stdout. This is necessary for you to - see debugger output. - - >>> doc = ''' - ... >>> x = 42 - ... >>> import pdb; pdb.set_trace() - ... ''' - >>> parser = doctest.DocTestParser() - >>> test = parser.get_doctest(doc, {}, "foo", "foo.py", 0) - >>> runner = doctest.DocTestRunner(verbose=False) - - To demonstrate this, we'll create a fake standard input that - captures our debugger input: - - >>> import tempfile - >>> real_stdin = sys.stdin - >>> sys.stdin = _FakeInput([ - ... 'print x', # print data defined by the example - ... 'continue', # stop debugging - ... '']) - - >>> try: runner.run(test) - ... finally: sys.stdin = real_stdin - --Return-- - > <doctest foo[1]>(1)<module>()->None - -> import pdb; pdb.set_trace() - (Pdb) print x - 42 - (Pdb) continue - (0, 2) - - You can also put pdb.set_trace in a function called from a test: - - >>> def calls_set_trace(): - ... y=2 - ... import pdb; pdb.set_trace() - - >>> doc = ''' - ... >>> x=1 - ... >>> calls_set_trace() - ... ''' - >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0) - >>> real_stdin = sys.stdin - >>> sys.stdin = _FakeInput([ - ... 'print y', # print data defined in the function - ... 'up', # out of function - ... 'print x', # print data defined by the example - ... 'continue', # stop debugging - ... '']) - - >>> try: - ... runner.run(test) - ... finally: - ... sys.stdin = real_stdin - --Return-- - > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None - -> import pdb; pdb.set_trace() - (Pdb) print y - 2 - (Pdb) up - > <doctest foo[1]>(1)<module>() - -> calls_set_trace() - (Pdb) print x - 1 - (Pdb) continue - (0, 2) - - During interactive debugging, source code is shown, even for - doctest examples: - - >>> doc = ''' - ... >>> def f(x): - ... ... g(x*2) - ... >>> def g(x): - ... ... print x+3 - ... ... import pdb; pdb.set_trace() - ... >>> f(3) - ... ''' - >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0) - >>> real_stdin = sys.stdin - >>> sys.stdin = _FakeInput([ - ... 'list', # list source from example 2 - ... 'next', # return from g() - ... 'list', # list source from example 1 - ... 'next', # return from f() - ... 'list', # list source from example 3 - ... 'continue', # stop debugging - ... '']) - >>> try: runner.run(test) - ... finally: sys.stdin = real_stdin - ... # doctest: +NORMALIZE_WHITESPACE - --Return-- - > <doctest foo[1]>(3)g()->None - -> import pdb; pdb.set_trace() - (Pdb) list - 1 def g(x): - 2 print x+3 - 3 -> import pdb; pdb.set_trace() - [EOF] - (Pdb) next - --Return-- - > <doctest foo[0]>(2)f()->None - -> g(x*2) - (Pdb) list - 1 def f(x): - 2 -> g(x*2) - [EOF] - (Pdb) next - --Return-- - > <doctest foo[2]>(1)<module>()->None - -> f(3) - (Pdb) list - 1 -> f(3) - [EOF] - (Pdb) continue - ********************************************************************** - File "foo.py", line 7, in foo - Failed example: - f(3) - Expected nothing - Got: - 9 - (1, 3) - """ - -def test_pdb_set_trace_nested(): - """This illustrates more-demanding use of set_trace with nested functions. - - >>> class C(object): - ... def calls_set_trace(self): - ... y = 1 - ... import pdb; pdb.set_trace() - ... self.f1() - ... y = 2 - ... def f1(self): - ... x = 1 - ... self.f2() - ... x = 2 - ... def f2(self): - ... z = 1 - ... z = 2 - - >>> calls_set_trace = C().calls_set_trace - - >>> doc = ''' - ... >>> a = 1 - ... >>> calls_set_trace() - ... ''' - >>> parser = doctest.DocTestParser() - >>> runner = doctest.DocTestRunner(verbose=False) - >>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0) - >>> real_stdin = sys.stdin - >>> sys.stdin = _FakeInput([ - ... 'print y', # print data defined in the function - ... 'step', 'step', 'step', 'step', 'step', 'step', 'print z', - ... 'up', 'print x', - ... 'up', 'print y', - ... 'up', 'print foo', - ... 'continue', # stop debugging - ... '']) - - >>> try: - ... runner.run(test) - ... finally: - ... sys.stdin = real_stdin - > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace() - -> self.f1() - (Pdb) print y - 1 - (Pdb) step - --Call-- - > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1() - -> def f1(self): - (Pdb) step - > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1() - -> x = 1 - (Pdb) step - > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1() - -> self.f2() - (Pdb) step - --Call-- - > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2() - -> def f2(self): - (Pdb) step - > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2() - -> z = 1 - (Pdb) step - > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2() - -> z = 2 - (Pdb) print z - 1 - (Pdb) up - > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1() - -> self.f2() - (Pdb) print x - 1 - (Pdb) up - > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace() - -> self.f1() - (Pdb) print y - 1 - (Pdb) up - > <doctest foo[1]>(1)<module>() - -> calls_set_trace() - (Pdb) print foo - *** NameError: name 'foo' is not defined - (Pdb) continue - (0, 2) -""" - -def test_DocTestSuite(): - """DocTestSuite creates a unittest test suite from a doctest. - - We create a Suite by providing a module. A module can be provided - by passing a module object: - - >>> import unittest - >>> import test.sample_doctest - >>> suite = doctest.DocTestSuite(test.sample_doctest) - >>> suite.run(unittest.TestResult()) - <unittest.TestResult run=9 errors=0 failures=4> - - We can also supply the module by name: - - >>> suite = doctest.DocTestSuite('test.sample_doctest') - >>> suite.run(unittest.TestResult()) - <unittest.TestResult run=9 errors=0 failures=4> - - We can use the current module: - - >>> suite = test.sample_doctest.test_suite() - >>> suite.run(unittest.TestResult()) - <unittest.TestResult run=9 errors=0 failures=4> - - We can supply global variables. If we pass globs, they will be - used instead of the module globals. Here we'll pass an empty - globals, triggering an extra error: - - >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={}) - >>> suite.run(unittest.TestResult()) - <unittest.TestResult run=9 errors=0 failures=5> - - Alternatively, we can provide extra globals. Here we'll make an - error go away by providing an extra global variable: - - >>> suite = doctest.DocTestSuite('test.sample_doctest', - ... extraglobs={'y': 1}) - >>> suite.run(unittest.TestResult()) - <unittest.TestResult run=9 errors=0 failures=3> - - You can pass option flags. Here we'll cause an extra error - by disabling the blank-line feature: - - >>> suite = doctest.DocTestSuite('test.sample_doctest', - ... optionflags=doctest.DONT_ACCEPT_BLANKLINE) - >>> suite.run(unittest.TestResult()) - <unittest.TestResult run=9 errors=0 failures=5> - - You can supply setUp and tearDown functions: - - >>> def setUp(t): - ... import test.test_doctest - ... test.test_doctest.sillySetup = True - - >>> def tearDown(t): - ... import test.test_doctest - ... del test.test_doctest.sillySetup - - Here, we installed a silly variable that the test expects: - - >>> suite = doctest.DocTestSuite('test.sample_doctest', - ... setUp=setUp, tearDown=tearDown) - >>> suite.run(unittest.TestResult()) - <unittest.TestResult run=9 errors=0 failures=3> - - But the tearDown restores sanity: - - >>> import test.test_doctest - >>> test.test_doctest.sillySetup - Traceback (most recent call last): - ... - AttributeError: 'module' object has no attribute 'sillySetup' - - The setUp and tearDown funtions are passed test objects. Here - we'll use the setUp function to supply the missing variable y: - - >>> def setUp(test): - ... test.globs['y'] = 1 - - >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp) - >>> suite.run(unittest.TestResult()) - <unittest.TestResult run=9 errors=0 failures=3> - - Here, we didn't need to use a tearDown function because we - modified the test globals, which are a copy of the - sample_doctest module dictionary. The test globals are - automatically cleared for us after a test. - """ - -def test_DocFileSuite(): - """We can test tests found in text files using a DocFileSuite. - - We create a suite by providing the names of one or more text - files that include examples: - - >>> import unittest - >>> suite = doctest.DocFileSuite('test_doctest.txt', - ... 'test_doctest2.txt', - ... 'test_doctest4.txt') - >>> suite.run(unittest.TestResult()) - <unittest.TestResult run=3 errors=0 failures=3> - - The test files are looked for in the directory containing the - calling module. A package keyword argument can be provided to - specify a different relative location. - - >>> import unittest - >>> suite = doctest.DocFileSuite('test_doctest.txt', - ... 'test_doctest2.txt', - ... 'test_doctest4.txt', - ... package='test') - >>> suite.run(unittest.TestResult()) - <unittest.TestResult run=3 errors=0 failures=3> - - Support for using a package's __loader__.get_data() is also - provided. - - >>> import unittest, pkgutil, test - >>> added_loader = False - >>> if not hasattr(test, '__loader__'): - ... test.__loader__ = pkgutil.get_loader(test) - ... added_loader = True - >>> try: - ... suite = doctest.DocFileSuite('test_doctest.txt', - ... 'test_doctest2.txt', - ... 'test_doctest4.txt', - ... package='test') - ... suite.run(unittest.TestResult()) - ... [truncated message content] |
From: <pj...@us...> - 2009-04-10 23:09:53
|
Revision: 6211 http://jython.svn.sourceforge.net/jython/?rev=6211&view=rev Author: pjenvey Date: 2009-04-10 23:09:34 +0000 (Fri, 10 Apr 2009) Log Message: ----------- feeble attempt of debugging why these fail on hudson's all job Modified Paths: -------------- trunk/jython/Lib/test/test_cmd_line.py trunk/jython/Lib/test/test_sax.py Modified: trunk/jython/Lib/test/test_cmd_line.py =================================================================== --- trunk/jython/Lib/test/test_cmd_line.py 2009-04-10 21:12:28 UTC (rev 6210) +++ trunk/jython/Lib/test/test_cmd_line.py 2009-04-10 23:09:34 UTC (rev 6211) @@ -42,11 +42,13 @@ self.verify_valid_flag('-S') def test_usage(self): - self.assertTrue('usage' in self.start_python('-h')) + result = self.start_python('-h') + self.assertTrue('usage' in result, repr(result)) def test_version(self): version = 'Jython %d.%d' % sys.version_info[:2] - self.assertTrue(self.start_python('-V').startswith(version)) + result = self.start_python('-V') + self.assertTrue(result.startswith(version), repr(result)) def test_main(): test.test_support.run_unittest(CmdLineTest) Modified: trunk/jython/Lib/test/test_sax.py =================================================================== --- trunk/jython/Lib/test/test_sax.py 2009-04-10 21:12:28 UTC (rev 6210) +++ trunk/jython/Lib/test/test_sax.py 2009-04-10 23:09:34 UTC (rev 6211) @@ -479,8 +479,21 @@ if os.name == 'java': testfile = testfile.replace('\\', '/') - return xmlgen.location.getSystemId().endswith(testfile) and \ + t = xmlgen.location.getSystemId().endswith(testfile) and \ xmlgen.location.getPublicId() is None + if not t: + print 'os.name: %s' % os.name + print 'systemId (%s): %s publicId (%s): %s' % \ + (type(xmlgen.location.getSystemId()), xmlgen.location.getSystemId(), + type(xmlgen.location.getPublicId()), xmlgen.location.getPublicId()) + content = open(testfile).read() + print '------- contents of %s ---------' % testfile + print content + print '------- end contents of %s ---------' % testfile + print '------- repr ---------' + print repr(content) + print '------- end repr ---------' + return t # =========================================================================== This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-04-17 02:22:35
|
Revision: 6234 http://jython.svn.sourceforge.net/jython/?rev=6234&view=rev Author: pjenvey Date: 2009-04-17 01:38:24 +0000 (Fri, 17 Apr 2009) Log Message: ----------- rename eof_fodder7 to match other SyntaxError'ing tests. avoids test_compiler from randomly importing it Modified Paths: -------------- trunk/jython/Lib/test/test_eof_jy.py Added Paths: ----------- trunk/jython/Lib/test/badsyntax_eof1.py Removed Paths: ------------- trunk/jython/Lib/test/eof_fodder7.py Copied: trunk/jython/Lib/test/badsyntax_eof1.py (from rev 6223, trunk/jython/Lib/test/eof_fodder7.py) =================================================================== --- trunk/jython/Lib/test/badsyntax_eof1.py (rev 0) +++ trunk/jython/Lib/test/badsyntax_eof1.py 2009-04-17 01:38:24 UTC (rev 6234) @@ -0,0 +1,5 @@ +def hi(): + pass + +def bye(): + hi( Deleted: trunk/jython/Lib/test/eof_fodder7.py =================================================================== --- trunk/jython/Lib/test/eof_fodder7.py 2009-04-17 01:35:16 UTC (rev 6233) +++ trunk/jython/Lib/test/eof_fodder7.py 2009-04-17 01:38:24 UTC (rev 6234) @@ -1,5 +0,0 @@ -def hi(): - pass - -def bye(): - hi( Modified: trunk/jython/Lib/test/test_eof_jy.py =================================================================== --- trunk/jython/Lib/test/test_eof_jy.py 2009-04-17 01:35:16 UTC (rev 6233) +++ trunk/jython/Lib/test/test_eof_jy.py 2009-04-17 01:38:24 UTC (rev 6234) @@ -47,7 +47,7 @@ def test_trailing_paren(self): try: - import eof_fodder7 + import badsyntax_eof1 except SyntaxError, cause: self.assertEquals(cause.lineno, 5) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2009-05-08 05:51:45
|
Revision: 6317 http://jython.svn.sourceforge.net/jython/?rev=6317&view=rev Author: zyasoft Date: 2009-05-08 05:51:42 +0000 (Fri, 08 May 2009) Log Message: ----------- Added limited testing of org.python.core.PyBytecode (PBC-VM) Added Paths: ----------- trunk/jython/Lib/test/output/test_types_pyc trunk/jython/Lib/test/pbcvm/ trunk/jython/Lib/test/pbcvm/test/ trunk/jython/Lib/test/pbcvm/test/README trunk/jython/Lib/test/pbcvm/test/__init__.py trunk/jython/Lib/test/pbcvm/test/test_builtin_pyc.pyc trunk/jython/Lib/test/pbcvm/test/test_exceptions_pyc.pyc trunk/jython/Lib/test/pbcvm/test/test_types_pyc.pyc trunk/jython/Lib/test/test_pbcvm.py Added: trunk/jython/Lib/test/output/test_types_pyc =================================================================== --- trunk/jython/Lib/test/output/test_types_pyc (rev 0) +++ trunk/jython/Lib/test/output/test_types_pyc 2009-05-08 05:51:42 UTC (rev 6317) @@ -0,0 +1,15 @@ +test_types_pyc +6. Built-in types +6.1 Truth value testing +6.2 Boolean operations +6.3 Comparisons +6.4 Numeric types (mostly conversions) +6.4.1 32-bit integers +6.4.2 Long integers +6.4.3 Floating point numbers +6.5 Sequence types +6.5.1 Strings +6.5.2 Tuples [see test_tuple.py] +6.5.3 Lists [see test_list.py] +6.6 Mappings == Dictionaries [see test_dict.py] +Buffers Added: trunk/jython/Lib/test/pbcvm/test/README =================================================================== --- trunk/jython/Lib/test/pbcvm/test/README (rev 0) +++ trunk/jython/Lib/test/pbcvm/test/README 2009-05-08 05:51:42 UTC (rev 6317) @@ -0,0 +1 @@ +Contains precompiled pyc files for testing org.python.core.PyBytecode by test_pbcvm - don't delete! Added: trunk/jython/Lib/test/pbcvm/test/__init__.py =================================================================== --- trunk/jython/Lib/test/pbcvm/test/__init__.py (rev 0) +++ trunk/jython/Lib/test/pbcvm/test/__init__.py 2009-05-08 05:51:42 UTC (rev 6317) @@ -0,0 +1 @@ +# mock test directory Added: trunk/jython/Lib/test/pbcvm/test/test_builtin_pyc.pyc =================================================================== (Binary files differ) Property changes on: trunk/jython/Lib/test/pbcvm/test/test_builtin_pyc.pyc ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/jython/Lib/test/pbcvm/test/test_exceptions_pyc.pyc =================================================================== (Binary files differ) Property changes on: trunk/jython/Lib/test/pbcvm/test/test_exceptions_pyc.pyc ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/jython/Lib/test/pbcvm/test/test_types_pyc.pyc =================================================================== (Binary files differ) Property changes on: trunk/jython/Lib/test/pbcvm/test/test_types_pyc.pyc ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: trunk/jython/Lib/test/test_pbcvm.py =================================================================== --- trunk/jython/Lib/test/test_pbcvm.py (rev 0) +++ trunk/jython/Lib/test/test_pbcvm.py 2009-05-08 05:51:42 UTC (rev 6317) @@ -0,0 +1,71 @@ +import inspect +import os.path +import sys +import unittest +from test import test_support +from regrtest import runtest + +def make_fib_function(): + from org.python.core import PyBytecode, PyFunction + co_argcount = 1 + co_nlocals = 1 + co_stacksize = 4 + co_flags = 67 + co_code = '|\x00\x00d\x01\x00j\x02\x00p\r\x00\x01|\x00\x00d\x02\x00j\x02\x00o\x08\x00\x01d\x02\x00Sn\x1d\x00\x01t\x00\x00|\x00\x00d\x03\x00\x18\x83\x01\x00t\x00\x00|\x00\x00d\x02\x00\x18\x83\x01\x00\x17Sd\x00\x00S' + co_consts = (None, 0, 1, 2) + co_names = ('fib',) + co_varnames = ('x',) + co_filename = '<fib test code>' + co_name = 'fib' + co_firstlineno = 1 + co_lnotab = '\x00\x01\x1a\x01\x08\x02' + co_freevars = () + co_cellvars = () + + c = PyBytecode( + co_argcount, co_nlocals, co_stacksize, co_flags, + co_code, co_consts, co_names, co_varnames, + co_filename, co_name, co_firstlineno, co_lnotab, co_freevars, co_cellvars) + + return PyFunction(c, globals()) + +fib = make_fib_function() + +class PyBytecodeTest(unittest.TestCase): + + def test_fib(self): + expected_fib = [1,1,2,3,5,8,13,21,34,55] + for i in range(10): + self.assertEquals(fib(i), expected_fib[i]) + +class AdhocRegrtest(unittest.TestCase): + + def setUp(self): + self.old_verbosity = test_support.verbose + test_support.verbose = 0 + import pycimport + sys.path.insert(0, os.path.join(os.path.split(inspect.getfile(self.__class__))[0], 'pbcvm')) + + 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 + # use subprocess asap + 'test_types_pyc', + 'test_exceptions_pyc'): + ok = runtest(test, generate=False, verbose=False, quiet=True, testdir=None, + huntrleaks=False, junit_xml=None) + self.assertTrue(ok > 0) + + def tearDown(self): + # typical unsafe ops we have to do in testing... + test_support.verbose = self.old_verbosity + sys.path.pop(0) + sys.meta_path.pop(0) + + +def test_main(): + test_support.run_unittest(PyBytecodeTest, AdhocRegrtest) + +if __name__ == "__main__": + test_main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-26 06:49:59
|
Revision: 6380 http://jython.svn.sourceforge.net/jython/?rev=6380&view=rev Author: pjenvey Date: 2009-05-26 06:49:37 +0000 (Tue, 26 May 2009) Log Message: ----------- add windows skips, close files in test_traceback Modified Paths: -------------- trunk/jython/Lib/test/regrtest.py trunk/jython/Lib/test/test_dircache.py trunk/jython/Lib/test/test_signal.py trunk/jython/Lib/test/test_traceback.py Modified: trunk/jython/Lib/test/regrtest.py =================================================================== --- trunk/jython/Lib/test/regrtest.py 2009-05-26 06:40:28 UTC (rev 6379) +++ trunk/jython/Lib/test/regrtest.py 2009-05-26 06:49:37 UTC (rev 6380) @@ -1532,9 +1532,7 @@ if test_support.is_jython: if os._name != 'posix': - self.expected.add('test_mhlib') - import platform - os_name = platform.java_ver()[3][0] + self.expected.update(['test_mhlib', 'test_signal']) self.valid = True Modified: trunk/jython/Lib/test/test_dircache.py =================================================================== --- trunk/jython/Lib/test/test_dircache.py 2009-05-26 06:40:28 UTC (rev 6379) +++ trunk/jython/Lib/test/test_dircache.py 2009-05-26 06:49:37 UTC (rev 6380) @@ -4,7 +4,7 @@ """ import unittest -from test.test_support import run_unittest, TESTFN +from test.test_support import is_jython, run_unittest, TESTFN import dircache, os, time, sys, tempfile @@ -44,7 +44,8 @@ # That is, this test can't possibly work under Windows -- dircache # is only good for capturing a one-shot snapshot there. - if sys.platform[:3] not in ('win', 'os2'): + if (sys.platform[:3] not in ('win', 'os2') or + (is_jython and os._name != 'nt')): # Sadly, dircache has the same granularity as stat.mtime, and so # can't notice any changes that occurred within 1 sec of the last # time it examined a directory. Modified: trunk/jython/Lib/test/test_signal.py =================================================================== --- trunk/jython/Lib/test/test_signal.py 2009-05-26 06:40:28 UTC (rev 6379) +++ trunk/jython/Lib/test/test_signal.py 2009-05-26 06:49:37 UTC (rev 6380) @@ -20,7 +20,8 @@ import traceback import sys, os, time, errno -if sys.platform[:3] in ('win', 'os2') or sys.platform == 'riscos': +if (sys.platform[:3] in ('win', 'os2') or sys.platform == 'riscos' or + (test_support.is_jython and os._name == 'nt')): raise test_support.TestSkipped("Can't test signal on %s" % \ sys.platform) Modified: trunk/jython/Lib/test/test_traceback.py =================================================================== --- trunk/jython/Lib/test/test_traceback.py 2009-05-26 06:40:28 UTC (rev 6379) +++ trunk/jython/Lib/test/test_traceback.py 2009-05-26 06:49:37 UTC (rev 6380) @@ -1,5 +1,6 @@ """Test cases for traceback module""" +from __future__ import with_statement import unittest from test.test_support import run_unittest, is_jython @@ -62,7 +63,8 @@ try: sys.path.insert(0, testdir) testfile = os.path.join(testdir, 'test_bug737473.py') - print >> open(testfile, 'w'), """ + with open(testfile, 'w') as fp: + print >> fp, """ def test(): raise ValueError""" @@ -84,7 +86,8 @@ # three seconds are needed for this test to pass reliably :-( time.sleep(4) - print >> open(testfile, 'w'), """ + with open(testfile, 'w') as fp: + print >> fp, """ def test(): raise NotImplementedError""" reload(test_bug737473) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-26 07:46:49
|
Revision: 6383 http://jython.svn.sourceforge.net/jython/?rev=6383&view=rev Author: pjenvey Date: 2009-05-26 07:46:39 +0000 (Tue, 26 May 2009) Log Message: ----------- more testing on Windows fixes Modified Paths: -------------- trunk/jython/Lib/test/check_for_initializer_in_syspath.py trunk/jython/Lib/test/test_marshal.py trunk/jython/Lib/test/test_tarfile.py Modified: trunk/jython/Lib/test/check_for_initializer_in_syspath.py =================================================================== --- trunk/jython/Lib/test/check_for_initializer_in_syspath.py 2009-05-26 07:00:22 UTC (rev 6382) +++ trunk/jython/Lib/test/check_for_initializer_in_syspath.py 2009-05-26 07:46:39 UTC (rev 6383) @@ -1,2 +1,4 @@ +import os import sys -assert "/from_SyspathAppendingInitializer_with_love" in sys.path +path = os.path.abspath("/from_SyspathAppendingInitializer_with_love") +assert path in sys.path Modified: trunk/jython/Lib/test/test_marshal.py =================================================================== --- trunk/jython/Lib/test/test_marshal.py 2009-05-26 07:00:22 UTC (rev 6382) +++ trunk/jython/Lib/test/test_marshal.py 2009-05-26 07:46:39 UTC (rev 6383) @@ -16,7 +16,7 @@ with open(test_support.TESTFN, "wb") as test_file: marshal.dump(item, test_file) with open(test_support.TESTFN, "rb") as test_file: - got = marshal.load(file(test_support.TESTFN, "rb")) #, debug=True) + got = marshal.load(test_file) return got Modified: trunk/jython/Lib/test/test_tarfile.py =================================================================== --- trunk/jython/Lib/test/test_tarfile.py 2009-05-26 07:00:22 UTC (rev 6382) +++ trunk/jython/Lib/test/test_tarfile.py 2009-05-26 07:46:39 UTC (rev 6383) @@ -200,7 +200,8 @@ def test_extractall(self): # Test if extractall() correctly restores directory permissions # and times (see issue1735). - if sys.platform == "win32": + if (sys.platform == "win32" or + test_support.is_jython and os._name == 'nt'): # Win32 has no support for utime() on directories or # fine grained permissions. return @@ -275,6 +276,9 @@ def setUp(self): self.tar = tarfile.open(tarname(self.comp), self.mode) + def tearDown(self): + self.tar.close() + class ReadDetectFileobjTest(ReadTest): def setUp(self): @@ -322,6 +326,7 @@ fobj.seek(offset) # Test if the tarfile starts with the second member. + self.tar.close() self.tar = tarfile.open(tarname(self.comp), "r:", fileobj=fobj) t = self.tar.next() self.assertEqual(t.name, name) @@ -330,6 +335,8 @@ self.tar.getmembers() self.assertEqual(self.tar.extractfile(t).read(), data, "seek back did not work") + self.tar.close() + fobj.close() class WriteTest(BaseTest): mode = 'w' @@ -460,9 +467,11 @@ s = f.read() f.close() elif self.comp == "bz2": - f = bz2.BZ2Decompressor() - s = file(self.dstname).read() - s = f.decompress(s) + b = bz2.BZ2Decompressor() + f = file(self.dstname) + s = f.read() + f.close() + s = b.decompress(s) self.assertEqual(len(f.unused_data), 0, "trailing data") else: f = file(self.dstname) @@ -718,22 +727,27 @@ def test_no_name_argument(self): fobj = open(testtar, "rb") - tar = tarfile.open(fileobj=fobj, mode="r") - self.assertEqual(tar.name, os.path.abspath(fobj.name)) + self.tar = tarfile.open(fileobj=fobj, mode="r") + self.assertEqual(self.tar.name, os.path.abspath(fobj.name)) + fobj.close() def test_no_name_attribute(self): - data = open(testtar, "rb").read() + fp = open(testtar, "rb") + data = fp.read() + fp.close() fobj = StringIO.StringIO(data) self.assertRaises(AttributeError, getattr, fobj, "name") - tar = tarfile.open(fileobj=fobj, mode="r") - self.assertEqual(tar.name, None) + self.tar = tarfile.open(fileobj=fobj, mode="r") + self.assertEqual(self.tar.name, None) def test_empty_name_attribute(self): - data = open(testtar, "rb").read() + fp = open(testtar, "rb") + data = fp.read() + fp.close() fobj = StringIO.StringIO(data) fobj.name = "" - tar = tarfile.open(fileobj=fobj, mode="r") - self.assertEqual(tar.name, None) + self.tar = tarfile.open(fileobj=fobj, mode="r") + self.assertEqual(self.tar.name, None) if bz2: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-27 02:22:26
|
Revision: 6389 http://jython.svn.sourceforge.net/jython/?rev=6389&view=rev Author: pjenvey Date: 2009-05-27 01:47:54 +0000 (Wed, 27 May 2009) Log Message: ----------- test_dircache thinko, add more windows regrtest skips Modified Paths: -------------- trunk/jython/Lib/test/regrtest.py trunk/jython/Lib/test/test_dircache.py Modified: trunk/jython/Lib/test/regrtest.py =================================================================== --- trunk/jython/Lib/test/regrtest.py 2009-05-27 01:46:25 UTC (rev 6388) +++ trunk/jython/Lib/test/regrtest.py 2009-05-27 01:47:54 UTC (rev 6389) @@ -1532,7 +1532,9 @@ if test_support.is_jython: if os._name != 'posix': - self.expected.update(['test_mhlib', 'test_signal']) + self.expected.update([ + 'test_grb', 'test_mhlib', 'test_posix', 'test_pwd', + 'test_signal']) self.valid = True Modified: trunk/jython/Lib/test/test_dircache.py =================================================================== --- trunk/jython/Lib/test/test_dircache.py 2009-05-27 01:46:25 UTC (rev 6388) +++ trunk/jython/Lib/test/test_dircache.py 2009-05-27 01:47:54 UTC (rev 6389) @@ -44,8 +44,8 @@ # That is, this test can't possibly work under Windows -- dircache # is only good for capturing a one-shot snapshot there. - if (sys.platform[:3] not in ('win', 'os2') or - (is_jython and os._name != 'nt')): + if (sys.platform[:3] not in ('win', 'os2') and + (not is_jython or os._name != 'nt')): # Sadly, dircache has the same granularity as stat.mtime, and so # can't notice any changes that occurred within 1 sec of the last # time it examined a directory. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-27 02:22:31
|
Revision: 6388 http://jython.svn.sourceforge.net/jython/?rev=6388&view=rev Author: pjenvey Date: 2009-05-27 01:46:25 +0000 (Wed, 27 May 2009) Log Message: ----------- solaris test fixes: o apply test_socket bsd setsockopt workaround and then some o extra_collect the particularly garbagey test_scope test twice Modified Paths: -------------- trunk/jython/Lib/test/test_scope.py trunk/jython/Lib/test/test_socket.py Modified: trunk/jython/Lib/test/test_scope.py =================================================================== --- trunk/jython/Lib/test/test_scope.py 2009-05-26 21:57:38 UTC (rev 6387) +++ trunk/jython/Lib/test/test_scope.py 2009-05-27 01:46:25 UTC (rev 6388) @@ -438,6 +438,8 @@ if is_jython: from test_weakref import extra_collect extra_collect() + # A lot of garbage + extra_collect() vereq(Foo.count, 0) print "17. class and global" Modified: trunk/jython/Lib/test/test_socket.py =================================================================== --- trunk/jython/Lib/test/test_socket.py 2009-05-26 21:57:38 UTC (rev 6387) +++ trunk/jython/Lib/test/test_socket.py 2009-05-27 01:46:25 UTC (rev 6388) @@ -23,6 +23,7 @@ EIGHT_BIT_MSG = 'Bh\xed Al\xe1in \xd3 Cinn\xe9ide anseo\n' os_name = platform.java_ver()[3][0] is_bsd = os_name == 'Mac OS X' or 'BSD' in os_name +is_solaris = os_name == 'SunOS' try: True @@ -535,8 +536,11 @@ for expected_value in values: sock.setsockopt(level, option, expected_value) retrieved_value = sock.getsockopt(level, option) - self.failUnlessEqual(retrieved_value, expected_value, \ - "Retrieved option(%s, %s) value %s != %s(value set)" % (level, option, retrieved_value, expected_value)) + msg = "Retrieved option(%s, %s) value %s != %s(value set)" % (level, option, retrieved_value, expected_value) + if is_solaris and option == socket.SO_RCVBUF: + self.assert_(retrieved_value >= expected_value, msg) + else: + self.failUnlessEqual(retrieved_value, expected_value, msg) def _testUDPOption(self, level, option, values): try: @@ -565,8 +569,8 @@ sock.bind( (HOST, PORT+1) ) sock.connect( (HOST, PORT) ) msg = "Option value '%s'='%s' did not propagate to implementation socket" % (option, values[-1]) - if is_bsd and option in (socket.SO_RCVBUF, socket.SO_SNDBUF): - # XXX: there's no guarantee that bufsize will be the + if ((is_bsd or is_solaris) and option in (socket.SO_RCVBUF, socket.SO_SNDBUF)): + # NOTE: there's no guarantee that bufsize will be the # exact setsockopt value, particularly after # establishing a connection. seems it will be *at least* # the values we test (which are rather small) on @@ -587,8 +591,12 @@ # now bind and listen on the socket i.e. cause the implementation socket to be created sock.bind( (HOST, PORT) ) sock.listen(50) - self.failUnlessEqual(sock.getsockopt(level, option), values[-1], \ - "Option value '(%s,%s)'='%s' did not propagate to implementation socket" % (level, option, values[-1])) + msg = "Option value '(%s,%s)'='%s' did not propagate to implementation socket" % (level, option, values[-1]) + if is_solaris and option == socket.SO_RCVBUF: + # NOTE: see similar bsd/solaris workaround above + self.assert_(sock.getsockopt(level, option) >= values[-1], msg) + else: + self.failUnlessEqual(sock.getsockopt(level, option), values[-1], msg) self._testSetAndGetOption(sock, level, option, values) finally: sock.close() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-05-27 02:43:23
|
Revision: 6391 http://jython.svn.sourceforge.net/jython/?rev=6391&view=rev Author: pjenvey Date: 2009-05-27 02:43:21 +0000 (Wed, 27 May 2009) Log Message: ----------- windows test fixes: o help test_ftruncate w/ an extra fsync o handle ':' in the test_sax.test_expat_locator_withinfo url o recompile test_java_subclasses' class files and write them in binary mode in hopes this satisifies the buildbot env o regrtest typo Modified Paths: -------------- trunk/jython/Lib/test/regrtest.py trunk/jython/Lib/test/test_fileno.py trunk/jython/Lib/test/test_java_subclasses.py trunk/jython/Lib/test/test_sax.py Modified: trunk/jython/Lib/test/regrtest.py =================================================================== --- trunk/jython/Lib/test/regrtest.py 2009-05-27 02:42:18 UTC (rev 6390) +++ trunk/jython/Lib/test/regrtest.py 2009-05-27 02:43:21 UTC (rev 6391) @@ -1533,7 +1533,7 @@ if test_support.is_jython: if os._name != 'posix': self.expected.update([ - 'test_grb', 'test_mhlib', 'test_posix', 'test_pwd', + 'test_grp', 'test_mhlib', 'test_posix', 'test_pwd', 'test_signal']) self.valid = True Modified: trunk/jython/Lib/test/test_fileno.py =================================================================== --- trunk/jython/Lib/test/test_fileno.py 2009-05-27 02:42:18 UTC (rev 6390) +++ trunk/jython/Lib/test/test_fileno.py 2009-05-27 02:43:21 UTC (rev 6391) @@ -24,6 +24,7 @@ def test_ftruncate(self): self.fp.write('jython filenos') self.fp.flush() + os.fsync(self.fd) self.assertEqual(os.path.getsize(self.filename), 14) os.ftruncate(self.fd, 8) self.assertEqual(os.path.getsize(self.filename), 8) Modified: trunk/jython/Lib/test/test_java_subclasses.py =================================================================== --- trunk/jython/Lib/test/test_java_subclasses.py 2009-05-27 02:42:18 UTC (rev 6390) +++ trunk/jython/Lib/test/test_java_subclasses.py 2009-05-27 02:43:21 UTC (rev 6391) @@ -248,7 +248,7 @@ Checks for http://jython.org/bugs/1861985 ''' def setUp(self): - out = open('Abstract.class', 'w') + out = open('Abstract.class', 'wb') out.write(ABSTRACT_CLASS) out.close() self.orig_syspath = sys.path[:] @@ -277,13 +277,12 @@ """ # The following is the correspoding bytecode for ContextAbstract compiled with javac 1.5 # Needs to be named differently than Abstract above so the class loader won't just use it -CONTEXT_ABSTRACT = '''\ -eJxdjr1uwjAUhc8lbgIh/AVegA0YQJ1BlRBSp6gdWrE7wQKjEEvBVH0tFip14AF4KMQ17YSHc3yu -vuPry/X3DOAZ3RACrRAe2gE6AWKCP9OFti8EbzBcEsTCrBShlehCvR12qSo/ZZrzJE5MJvOlLLXL -/0NhN3pP6CQLU1j1befp3pYys1N+d6fsxqwI4Yc5lJl61a7QewDHW/klIzzBjxDB58UPAKHtkEku -i/XkPd2qzIo+/1/AnQrIdVkDTlN2Yq+NfkCjEyrHO1JlbXLF3QV7lbXGKfqDEaIOCHL7ORMad7J5 -A7yvPDQ= -'''.decode('base64').decode('zlib') +CONTEXT_ABSTRACT = """\ +eJxdTsEOwVAQnK2n1aq2Bz/ghgNxF4lInIQDcX9tX6jQJvWI33IhcfABPkrs69EedjKzM7v7+b7e +AEaIPAj4HmpoOQgchAR7nOWZnhBq3d6WIGZFqgjhIsvV8nKKVbmR8ZEV+6T0vkgJ3rq4lImaZ0Zt +z4pcq5uexmddykQPDvIqfdRh+3Bh86I/AyEyluFR5rvhKj6oRIsO/yNgygKZLHeHWY+RGN3+E9R/ +wLozITS4BxwxdsHYgBBkrlVTr9KbP6qaLFc= +""".decode('base64').decode('zlib') class ContextClassloaderTest(unittest.TestCase): '''Classes on the context classloader should be importable and subclassable. Modified: trunk/jython/Lib/test/test_sax.py =================================================================== --- trunk/jython/Lib/test/test_sax.py 2009-05-27 02:42:18 UTC (rev 6390) +++ trunk/jython/Lib/test/test_sax.py 2009-05-27 02:43:21 UTC (rev 6391) @@ -479,9 +479,8 @@ # replace the backslashes with forward testfile = testfile.replace('\\', '/') - # XXX: may not match getSystemId when the filename contains funky - # characters (like ':') - expected = urllib.quote(testfile) + # urllib.quote isn't the exact encoder (e.g. ':' isn't escaped) + expected = urllib.quote(testfile).replace('%3A', ':') return xmlgen.location.getSystemId().endswith(expected) and \ xmlgen.location.getPublicId() is None This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-06-01 04:38:00
|
Revision: 6436 http://jython.svn.sourceforge.net/jython/?rev=6436&view=rev Author: pjenvey Date: 2009-06-01 04:37:42 +0000 (Mon, 01 Jun 2009) Log Message: ----------- change our extra_collect into the 2.7/3.1 style test_support.gc_collect Modified Paths: -------------- trunk/jython/Lib/test/test_array.py trunk/jython/Lib/test/test_class.py trunk/jython/Lib/test/test_deque.py trunk/jython/Lib/test/test_descr.py trunk/jython/Lib/test/test_file.py trunk/jython/Lib/test/test_functools.py trunk/jython/Lib/test/test_generators.py trunk/jython/Lib/test/test_iter.py trunk/jython/Lib/test/test_scope.py trunk/jython/Lib/test/test_set.py trunk/jython/Lib/test/test_support.py trunk/jython/Lib/test/test_weakref.py Modified: trunk/jython/Lib/test/test_array.py =================================================================== --- trunk/jython/Lib/test/test_array.py 2009-05-31 21:42:09 UTC (rev 6435) +++ trunk/jython/Lib/test/test_array.py 2009-06-01 04:37:42 UTC (rev 6436) @@ -11,7 +11,6 @@ if test_support.is_jython: import operator - from test_weakref import extra_collect class ArraySubclass(array.array): pass @@ -704,8 +703,7 @@ p = proxy(s) self.assertEqual(p.tostring(), s.tostring()) s = None - if test_support.is_jython: - extra_collect() + test_support.gc_collect() self.assertRaises(ReferenceError, len, p) def test_bug_782369(self): Modified: trunk/jython/Lib/test/test_class.py =================================================================== --- trunk/jython/Lib/test/test_class.py 2009-05-31 21:42:09 UTC (rev 6435) +++ trunk/jython/Lib/test/test_class.py 2009-06-01 04:37:42 UTC (rev 6436) @@ -1,6 +1,6 @@ "Test the functionality of Python classes implementing operators." -from test.test_support import TestFailed +from test.test_support import TestFailed, gc_collect testmeths = [ @@ -249,9 +249,7 @@ # This test has to be last (duh.) del testme -if sys.platform[:4] == 'java': - from test_weakref import extra_collect - extra_collect() +gc_collect() # Interfering tests Modified: trunk/jython/Lib/test/test_deque.py =================================================================== --- trunk/jython/Lib/test/test_deque.py 2009-05-31 21:42:09 UTC (rev 6435) +++ trunk/jython/Lib/test/test_deque.py 2009-06-01 04:37:42 UTC (rev 6436) @@ -475,9 +475,7 @@ p = proxy(d) self.assertEqual(str(p), str(d)) d = None - if test_support.is_jython: - from test_weakref import extra_collect - extra_collect() + test_support.gc_collect() self.assertRaises(ReferenceError, str, p) def test_strange_subclass(self): Modified: trunk/jython/Lib/test/test_descr.py =================================================================== --- trunk/jython/Lib/test/test_descr.py 2009-05-31 21:42:09 UTC (rev 6435) +++ trunk/jython/Lib/test/test_descr.py 2009-06-01 04:37:42 UTC (rev 6436) @@ -1,14 +1,9 @@ # Test enhancements related to descriptors and new-style classes -from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout, is_jython +from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout, gc_collect, is_jython from copy import deepcopy import warnings import types -if is_jython: - from test_weakref import extra_collect -else: - def extra_collect(): - pass warnings.filterwarnings("ignore", r'complex divmod\(\), // and % are deprecated$', @@ -1266,7 +1261,7 @@ x.c = Counted() vereq(Counted.counter, 3) del x - extra_collect() + gc_collect() vereq(Counted.counter, 0) class D(C): pass @@ -1275,7 +1270,7 @@ x.z = Counted() vereq(Counted.counter, 2) del x - extra_collect() + gc_collect() vereq(Counted.counter, 0) class E(D): __slots__ = ['e'] @@ -1285,7 +1280,7 @@ x.e = Counted() vereq(Counted.counter, 3) del x - extra_collect() + gc_collect() vereq(Counted.counter, 0) # Test cyclical leaks [SF bug 519621] @@ -1298,7 +1293,7 @@ s = None import gc gc.collect() - extra_collect() + gc_collect() vereq(Counted.counter, 0) # XXX: This tests a CPython GC reference count bug and Jython lacks @@ -1331,7 +1326,7 @@ h = H() try: del h - extra_collect() + gc_collect() finally: sys.stderr = save_stderr @@ -1982,7 +1977,7 @@ r = weakref.ref(c) verify(r() is c) del c - extra_collect() + gc_collect() verify(r() is None) del r class NoWeak(object): @@ -2002,7 +1997,7 @@ r = weakref.ref(yes) verify(r() is yes) del yes - extra_collect() + gc_collect() verify(r() is None) del r @@ -3332,7 +3327,7 @@ c = C() vereq(log, []) del c - extra_collect() + gc_collect() vereq(log, [1]) class D(object): pass Modified: trunk/jython/Lib/test/test_file.py =================================================================== --- trunk/jython/Lib/test/test_file.py 2009-05-31 21:42:09 UTC (rev 6435) +++ trunk/jython/Lib/test/test_file.py 2009-06-01 04:37:42 UTC (rev 6436) @@ -5,7 +5,7 @@ from array import array from weakref import proxy -from test.test_support import TESTFN, findfile, is_jython, run_unittest +from test.test_support import TESTFN, findfile, gc_collect, is_jython, run_unittest from UserList import UserList class AutoFileTests(unittest.TestCase): @@ -26,9 +26,7 @@ self.assertEquals(self.f.tell(), p.tell()) self.f.close() self.f = None - if is_jython: - from test_weakref import extra_collect - extra_collect() + gc_collect() self.assertRaises(ReferenceError, getattr, p, 'tell') def testAttributes(self): Modified: trunk/jython/Lib/test/test_functools.py =================================================================== --- trunk/jython/Lib/test/test_functools.py 2009-05-31 21:42:09 UTC (rev 6435) +++ trunk/jython/Lib/test/test_functools.py 2009-06-01 04:37:42 UTC (rev 6436) @@ -131,9 +131,7 @@ p = proxy(f) self.assertEqual(f.func, p.func) f = None - if test_support.is_jython: - from test_weakref import extra_collect - extra_collect() + test_support.gc_collect() self.assertRaises(ReferenceError, getattr, p, 'func') def test_with_bound_and_unbound_methods(self): Modified: trunk/jython/Lib/test/test_generators.py =================================================================== --- trunk/jython/Lib/test/test_generators.py 2009-05-31 21:42:09 UTC (rev 6435) +++ trunk/jython/Lib/test/test_generators.py 2009-06-01 04:37:42 UTC (rev 6436) @@ -1653,7 +1653,7 @@ >>> g = f() >>> g.next() ->>> del g; extra_collect() +>>> del g; gc_collect() exiting @@ -1678,7 +1678,7 @@ >>> old, sys.stderr = sys.stderr, StringIO.StringIO() >>> g = f() >>> g.next() ->>> del g; extra_collect() +>>> del g; gc_collect() >>> sys.stderr.getvalue().startswith( ... "Exception RuntimeError" ... ) @@ -1795,7 +1795,7 @@ ... raise RuntimeError ... ... l = Leaker() -... del l; extra_collect() +... del l; gc_collect() ... err = sys.stderr.getvalue().strip() ... err.startswith( ... "Exception RuntimeError in <" @@ -1834,13 +1834,8 @@ from test import test_support, test_generators test_support.run_doctest(test_generators, verbose) -def extra_collect(): - import gc - from time import sleep +from test.test_support import gc_collect - gc.collect(); sleep(1); gc.collect(); sleep(0.1); gc.collect() - - # This part isn't needed for regrtest, but for running the test directly. if __name__ == "__main__": test_main(1) Modified: trunk/jython/Lib/test/test_iter.py =================================================================== --- trunk/jython/Lib/test/test_iter.py 2009-05-31 21:42:09 UTC (rev 6435) +++ trunk/jython/Lib/test/test_iter.py 2009-06-01 04:37:42 UTC (rev 6436) @@ -1,7 +1,7 @@ # Test iterators. import unittest -from test.test_support import run_unittest, TESTFN, unlink, have_unicode +from test.test_support import gc_collect, run_unittest, TESTFN, unlink, have_unicode # Test result of triple loop (too big to inline) TRIPLETS = [(0, 0, 0), (0, 0, 1), (0, 0, 2), @@ -781,7 +781,6 @@ # Test reference count behavior # XXX: Jython new style objects don't support __del__ yet - from test_weakref import extra_collect #class C(object): class C: count = 0 @@ -797,7 +796,7 @@ x = C() self.assertEqual(C.count, 1) del x - extra_collect() + gc_collect() self.assertEqual(C.count, 0) l = [C(), C(), C()] self.assertEqual(C.count, 3) @@ -806,7 +805,7 @@ except ValueError: pass del l - extra_collect() + gc_collect() self.assertEqual(C.count, 0) Modified: trunk/jython/Lib/test/test_scope.py =================================================================== --- trunk/jython/Lib/test/test_scope.py 2009-05-31 21:42:09 UTC (rev 6435) +++ trunk/jython/Lib/test/test_scope.py 2009-06-01 04:37:42 UTC (rev 6436) @@ -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, vereq, gc_collect import warnings warnings.filterwarnings("ignore", r"import \*", SyntaxWarning, "<string>") @@ -435,11 +435,9 @@ for i in range(100): f1() -if is_jython: - from test_weakref import extra_collect - extra_collect() - # A lot of garbage - extra_collect() +gc_collect() +# A lot of garbage +gc_collect() vereq(Foo.count, 0) print "17. class and global" Modified: trunk/jython/Lib/test/test_set.py =================================================================== --- trunk/jython/Lib/test/test_set.py 2009-05-31 21:42:09 UTC (rev 6435) +++ trunk/jython/Lib/test/test_set.py 2009-06-01 04:37:42 UTC (rev 6436) @@ -1,6 +1,5 @@ import unittest from test import test_support -from test_weakref import extra_collect from weakref import proxy import operator import copy @@ -484,7 +483,7 @@ p = proxy(s) self.assertEqual(str(p), str(s)) s = None - extra_collect() + test_support.gc_collect() self.assertRaises(ReferenceError, str, p) # C API test only available in a debug build Modified: trunk/jython/Lib/test/test_support.py =================================================================== --- trunk/jython/Lib/test/test_support.py 2009-05-31 21:42:09 UTC (rev 6435) +++ trunk/jython/Lib/test/test_support.py 2009-06-01 04:37:42 UTC (rev 6436) @@ -299,6 +299,22 @@ fn, _ = urllib.urlretrieve(url, filename) return open(fn) +def gc_collect(): + """Force as many objects as possible to be collected. + + In non-CPython implementations of Python, this is needed because timely + deallocation is not guaranteed by the garbage collector. (Even in CPython + this can be the case in case of reference cycles.) This means that __del__ + methods may be called later than expected and weakrefs may remain alive for + longer than expected. This function tries its best to force all garbage + objects to disappear. + """ + import gc + gc.collect() + time.sleep(0.1) + gc.collect() + gc.collect() + #======================================================================= # Decorator for running a function in a different locale, correctly resetting # it afterwards. Modified: trunk/jython/Lib/test/test_weakref.py =================================================================== --- trunk/jython/Lib/test/test_weakref.py 2009-05-31 21:42:09 UTC (rev 6435) +++ trunk/jython/Lib/test/test_weakref.py 2009-06-01 04:37:42 UTC (rev 6436) @@ -6,19 +6,6 @@ from test import test_support -if test_support.is_jython: - import time - - def extra_collect(): - """Kick Java's GC into gear""" - gc.collect() - time.sleep(0.1) - gc.collect() - gc.collect() -else: - def extra_collect(): - pass - # Used in ReferencesTestCase.test_ref_created_during_del() . ref_from_del = None @@ -82,7 +69,7 @@ ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del o - extra_collect() + test_support.gc_collect() self.assert_(ref1() is None, "expected reference to be invalidated") self.assert_(ref2() is None, @@ -118,7 +105,7 @@ def check(proxy): proxy.bar - extra_collect() + test_support.gc_collect() self.assertRaises(weakref.ReferenceError, check, ref1) self.assertRaises(weakref.ReferenceError, check, ref2) # XXX: CPython GC collects C() immediately. use ref1 instead on @@ -143,7 +130,7 @@ o = factory() ref = weakref.ref(o, self.callback) del o - extra_collect() + test_support.gc_collect() self.assert_(self.cbcalled == 1, "callback did not properly set 'cbcalled'") self.assert_(ref() is None, @@ -168,7 +155,7 @@ self.assert_(weakref.getweakrefcount(o) == 2, "wrong weak ref count for object") del proxy - extra_collect() + test_support.gc_collect() self.assert_(weakref.getweakrefcount(o) == 1, "wrong weak ref count for object after deleting proxy") @@ -314,7 +301,7 @@ "got wrong number of weak reference objects") del ref1, ref2, proxy1, proxy2 - extra_collect() + test_support.gc_collect() self.assert_(weakref.getweakrefcount(o) == 0, "weak reference objects not unlinked from" " referent when discarded.") @@ -328,7 +315,7 @@ ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref1 - extra_collect() + test_support.gc_collect() self.assert_(weakref.getweakrefs(o) == [ref2], "list of refs does not match") @@ -336,7 +323,7 @@ ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref2 - extra_collect() + test_support.gc_collect() if test_support.is_jython: # XXX: Likely a Jython bug: the following inline declared # [ref1] list isn't garbage collected no matter how many @@ -353,7 +340,7 @@ "list of refs does not match") del ref1 - extra_collect() + test_support.gc_collect() self.assert_(weakref.getweakrefs(o) == [], "list of refs not cleared") @@ -632,7 +619,7 @@ del callback, c, d, C self.assertEqual(alist, []) # del isn't enough to clean up cycles gc.collect() - extra_collect() + test_support.gc_collect() self.assertEqual(alist, ["safe_callback called"]) self.assertEqual(external_wr(), None) @@ -783,18 +770,18 @@ del items1, items2 self.assert_(len(dict) == self.COUNT) del objects[0] - extra_collect() + test_support.gc_collect() self.assert_(len(dict) == (self.COUNT - 1), "deleting object did not cause dictionary update") del objects, o - extra_collect() + test_support.gc_collect() self.assert_(len(dict) == 0, "deleting the values did not clear the dictionary") # regression on SF bug #447152: dict = weakref.WeakValueDictionary() self.assertRaises(KeyError, dict.__getitem__, 1) dict[2] = C() - extra_collect() + test_support.gc_collect() self.assertRaises(KeyError, dict.__getitem__, 2) def test_weak_keys(self): @@ -815,11 +802,11 @@ del items1, items2 self.assert_(len(dict) == self.COUNT) del objects[0] - extra_collect() + test_support.gc_collect() self.assert_(len(dict) == (self.COUNT - 1), "deleting object did not cause dictionary update") del objects, o - extra_collect() + test_support.gc_collect() self.assert_(len(dict) == 0, "deleting the keys did not clear the dictionary") o = Object(42) @@ -1128,7 +1115,7 @@ >>> o is o2 True >>> del o, o2 ->>> extra_collect() +>>> test_support.gc_collect() >>> print r() None @@ -1181,7 +1168,7 @@ >>> id2obj(a_id) is a True >>> del a ->>> extra_collect() +>>> test_support.gc_collect() >>> try: ... id2obj(a_id) ... except KeyError: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-06-01 04:47:02
|
Revision: 6437 http://jython.svn.sourceforge.net/jython/?rev=6437&view=rev Author: pjenvey Date: 2009-06-01 04:46:45 +0000 (Mon, 01 Jun 2009) Log Message: ----------- blah, revert r6435 for now as it breaks running the tests on CPython, which is too useful Modified Paths: -------------- trunk/jython/Lib/test/test_array.py trunk/jython/Lib/test/test_class.py trunk/jython/Lib/test/test_deque.py trunk/jython/Lib/test/test_descr.py trunk/jython/Lib/test/test_file.py trunk/jython/Lib/test/test_functools.py trunk/jython/Lib/test/test_generators.py trunk/jython/Lib/test/test_iter.py trunk/jython/Lib/test/test_scope.py trunk/jython/Lib/test/test_set.py trunk/jython/Lib/test/test_support.py trunk/jython/Lib/test/test_weakref.py Modified: trunk/jython/Lib/test/test_array.py =================================================================== --- trunk/jython/Lib/test/test_array.py 2009-06-01 04:37:42 UTC (rev 6436) +++ trunk/jython/Lib/test/test_array.py 2009-06-01 04:46:45 UTC (rev 6437) @@ -11,6 +11,7 @@ if test_support.is_jython: import operator + from test_weakref import extra_collect class ArraySubclass(array.array): pass @@ -703,7 +704,8 @@ p = proxy(s) self.assertEqual(p.tostring(), s.tostring()) s = None - test_support.gc_collect() + if test_support.is_jython: + extra_collect() self.assertRaises(ReferenceError, len, p) def test_bug_782369(self): Modified: trunk/jython/Lib/test/test_class.py =================================================================== --- trunk/jython/Lib/test/test_class.py 2009-06-01 04:37:42 UTC (rev 6436) +++ trunk/jython/Lib/test/test_class.py 2009-06-01 04:46:45 UTC (rev 6437) @@ -1,6 +1,6 @@ "Test the functionality of Python classes implementing operators." -from test.test_support import TestFailed, gc_collect +from test.test_support import TestFailed testmeths = [ @@ -249,7 +249,9 @@ # This test has to be last (duh.) del testme -gc_collect() +if sys.platform[:4] == 'java': + from test_weakref import extra_collect + extra_collect() # Interfering tests Modified: trunk/jython/Lib/test/test_deque.py =================================================================== --- trunk/jython/Lib/test/test_deque.py 2009-06-01 04:37:42 UTC (rev 6436) +++ trunk/jython/Lib/test/test_deque.py 2009-06-01 04:46:45 UTC (rev 6437) @@ -475,7 +475,9 @@ p = proxy(d) self.assertEqual(str(p), str(d)) d = None - test_support.gc_collect() + if test_support.is_jython: + from test_weakref import extra_collect + extra_collect() self.assertRaises(ReferenceError, str, p) def test_strange_subclass(self): Modified: trunk/jython/Lib/test/test_descr.py =================================================================== --- trunk/jython/Lib/test/test_descr.py 2009-06-01 04:37:42 UTC (rev 6436) +++ trunk/jython/Lib/test/test_descr.py 2009-06-01 04:46:45 UTC (rev 6437) @@ -1,9 +1,14 @@ # Test enhancements related to descriptors and new-style classes -from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout, gc_collect, is_jython +from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout, is_jython from copy import deepcopy import warnings import types +if is_jython: + from test_weakref import extra_collect +else: + def extra_collect(): + pass warnings.filterwarnings("ignore", r'complex divmod\(\), // and % are deprecated$', @@ -1261,7 +1266,7 @@ x.c = Counted() vereq(Counted.counter, 3) del x - gc_collect() + extra_collect() vereq(Counted.counter, 0) class D(C): pass @@ -1270,7 +1275,7 @@ x.z = Counted() vereq(Counted.counter, 2) del x - gc_collect() + extra_collect() vereq(Counted.counter, 0) class E(D): __slots__ = ['e'] @@ -1280,7 +1285,7 @@ x.e = Counted() vereq(Counted.counter, 3) del x - gc_collect() + extra_collect() vereq(Counted.counter, 0) # Test cyclical leaks [SF bug 519621] @@ -1293,7 +1298,7 @@ s = None import gc gc.collect() - gc_collect() + extra_collect() vereq(Counted.counter, 0) # XXX: This tests a CPython GC reference count bug and Jython lacks @@ -1326,7 +1331,7 @@ h = H() try: del h - gc_collect() + extra_collect() finally: sys.stderr = save_stderr @@ -1977,7 +1982,7 @@ r = weakref.ref(c) verify(r() is c) del c - gc_collect() + extra_collect() verify(r() is None) del r class NoWeak(object): @@ -1997,7 +2002,7 @@ r = weakref.ref(yes) verify(r() is yes) del yes - gc_collect() + extra_collect() verify(r() is None) del r @@ -3327,7 +3332,7 @@ c = C() vereq(log, []) del c - gc_collect() + extra_collect() vereq(log, [1]) class D(object): pass Modified: trunk/jython/Lib/test/test_file.py =================================================================== --- trunk/jython/Lib/test/test_file.py 2009-06-01 04:37:42 UTC (rev 6436) +++ trunk/jython/Lib/test/test_file.py 2009-06-01 04:46:45 UTC (rev 6437) @@ -5,7 +5,7 @@ from array import array from weakref import proxy -from test.test_support import TESTFN, findfile, gc_collect, is_jython, run_unittest +from test.test_support import TESTFN, findfile, is_jython, run_unittest from UserList import UserList class AutoFileTests(unittest.TestCase): @@ -26,7 +26,9 @@ self.assertEquals(self.f.tell(), p.tell()) self.f.close() self.f = None - gc_collect() + if is_jython: + from test_weakref import extra_collect + extra_collect() self.assertRaises(ReferenceError, getattr, p, 'tell') def testAttributes(self): Modified: trunk/jython/Lib/test/test_functools.py =================================================================== --- trunk/jython/Lib/test/test_functools.py 2009-06-01 04:37:42 UTC (rev 6436) +++ trunk/jython/Lib/test/test_functools.py 2009-06-01 04:46:45 UTC (rev 6437) @@ -131,7 +131,9 @@ p = proxy(f) self.assertEqual(f.func, p.func) f = None - test_support.gc_collect() + if test_support.is_jython: + from test_weakref import extra_collect + extra_collect() self.assertRaises(ReferenceError, getattr, p, 'func') def test_with_bound_and_unbound_methods(self): Modified: trunk/jython/Lib/test/test_generators.py =================================================================== --- trunk/jython/Lib/test/test_generators.py 2009-06-01 04:37:42 UTC (rev 6436) +++ trunk/jython/Lib/test/test_generators.py 2009-06-01 04:46:45 UTC (rev 6437) @@ -1653,7 +1653,7 @@ >>> g = f() >>> g.next() ->>> del g; gc_collect() +>>> del g; extra_collect() exiting @@ -1678,7 +1678,7 @@ >>> old, sys.stderr = sys.stderr, StringIO.StringIO() >>> g = f() >>> g.next() ->>> del g; gc_collect() +>>> del g; extra_collect() >>> sys.stderr.getvalue().startswith( ... "Exception RuntimeError" ... ) @@ -1795,7 +1795,7 @@ ... raise RuntimeError ... ... l = Leaker() -... del l; gc_collect() +... del l; extra_collect() ... err = sys.stderr.getvalue().strip() ... err.startswith( ... "Exception RuntimeError in <" @@ -1834,8 +1834,13 @@ from test import test_support, test_generators test_support.run_doctest(test_generators, verbose) -from test.test_support import gc_collect +def extra_collect(): + import gc + from time import sleep + gc.collect(); sleep(1); gc.collect(); sleep(0.1); gc.collect() + + # This part isn't needed for regrtest, but for running the test directly. if __name__ == "__main__": test_main(1) Modified: trunk/jython/Lib/test/test_iter.py =================================================================== --- trunk/jython/Lib/test/test_iter.py 2009-06-01 04:37:42 UTC (rev 6436) +++ trunk/jython/Lib/test/test_iter.py 2009-06-01 04:46:45 UTC (rev 6437) @@ -1,7 +1,7 @@ # Test iterators. import unittest -from test.test_support import gc_collect, run_unittest, TESTFN, unlink, have_unicode +from test.test_support import run_unittest, TESTFN, unlink, have_unicode # Test result of triple loop (too big to inline) TRIPLETS = [(0, 0, 0), (0, 0, 1), (0, 0, 2), @@ -781,6 +781,7 @@ # Test reference count behavior # XXX: Jython new style objects don't support __del__ yet + from test_weakref import extra_collect #class C(object): class C: count = 0 @@ -796,7 +797,7 @@ x = C() self.assertEqual(C.count, 1) del x - gc_collect() + extra_collect() self.assertEqual(C.count, 0) l = [C(), C(), C()] self.assertEqual(C.count, 3) @@ -805,7 +806,7 @@ except ValueError: pass del l - gc_collect() + extra_collect() self.assertEqual(C.count, 0) Modified: trunk/jython/Lib/test/test_scope.py =================================================================== --- trunk/jython/Lib/test/test_scope.py 2009-06-01 04:37:42 UTC (rev 6436) +++ trunk/jython/Lib/test/test_scope.py 2009-06-01 04:46:45 UTC (rev 6437) @@ -1,4 +1,4 @@ -from test.test_support import verify, TestFailed, check_syntax, vereq, gc_collect +from test.test_support import verify, TestFailed, check_syntax, vereq, is_jython import warnings warnings.filterwarnings("ignore", r"import \*", SyntaxWarning, "<string>") @@ -435,9 +435,11 @@ for i in range(100): f1() -gc_collect() -# A lot of garbage -gc_collect() +if is_jython: + from test_weakref import extra_collect + extra_collect() + # A lot of garbage + extra_collect() vereq(Foo.count, 0) print "17. class and global" Modified: trunk/jython/Lib/test/test_set.py =================================================================== --- trunk/jython/Lib/test/test_set.py 2009-06-01 04:37:42 UTC (rev 6436) +++ trunk/jython/Lib/test/test_set.py 2009-06-01 04:46:45 UTC (rev 6437) @@ -1,5 +1,6 @@ import unittest from test import test_support +from test_weakref import extra_collect from weakref import proxy import operator import copy @@ -483,7 +484,7 @@ p = proxy(s) self.assertEqual(str(p), str(s)) s = None - test_support.gc_collect() + extra_collect() self.assertRaises(ReferenceError, str, p) # C API test only available in a debug build Modified: trunk/jython/Lib/test/test_support.py =================================================================== --- trunk/jython/Lib/test/test_support.py 2009-06-01 04:37:42 UTC (rev 6436) +++ trunk/jython/Lib/test/test_support.py 2009-06-01 04:46:45 UTC (rev 6437) @@ -299,22 +299,6 @@ fn, _ = urllib.urlretrieve(url, filename) return open(fn) -def gc_collect(): - """Force as many objects as possible to be collected. - - In non-CPython implementations of Python, this is needed because timely - deallocation is not guaranteed by the garbage collector. (Even in CPython - this can be the case in case of reference cycles.) This means that __del__ - methods may be called later than expected and weakrefs may remain alive for - longer than expected. This function tries its best to force all garbage - objects to disappear. - """ - import gc - gc.collect() - time.sleep(0.1) - gc.collect() - gc.collect() - #======================================================================= # Decorator for running a function in a different locale, correctly resetting # it afterwards. Modified: trunk/jython/Lib/test/test_weakref.py =================================================================== --- trunk/jython/Lib/test/test_weakref.py 2009-06-01 04:37:42 UTC (rev 6436) +++ trunk/jython/Lib/test/test_weakref.py 2009-06-01 04:46:45 UTC (rev 6437) @@ -6,6 +6,19 @@ from test import test_support +if test_support.is_jython: + import time + + def extra_collect(): + """Kick Java's GC into gear""" + gc.collect() + time.sleep(0.1) + gc.collect() + gc.collect() +else: + def extra_collect(): + pass + # Used in ReferencesTestCase.test_ref_created_during_del() . ref_from_del = None @@ -69,7 +82,7 @@ ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del o - test_support.gc_collect() + extra_collect() self.assert_(ref1() is None, "expected reference to be invalidated") self.assert_(ref2() is None, @@ -105,7 +118,7 @@ def check(proxy): proxy.bar - test_support.gc_collect() + extra_collect() self.assertRaises(weakref.ReferenceError, check, ref1) self.assertRaises(weakref.ReferenceError, check, ref2) # XXX: CPython GC collects C() immediately. use ref1 instead on @@ -130,7 +143,7 @@ o = factory() ref = weakref.ref(o, self.callback) del o - test_support.gc_collect() + extra_collect() self.assert_(self.cbcalled == 1, "callback did not properly set 'cbcalled'") self.assert_(ref() is None, @@ -155,7 +168,7 @@ self.assert_(weakref.getweakrefcount(o) == 2, "wrong weak ref count for object") del proxy - test_support.gc_collect() + extra_collect() self.assert_(weakref.getweakrefcount(o) == 1, "wrong weak ref count for object after deleting proxy") @@ -301,7 +314,7 @@ "got wrong number of weak reference objects") del ref1, ref2, proxy1, proxy2 - test_support.gc_collect() + extra_collect() self.assert_(weakref.getweakrefcount(o) == 0, "weak reference objects not unlinked from" " referent when discarded.") @@ -315,7 +328,7 @@ ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref1 - test_support.gc_collect() + extra_collect() self.assert_(weakref.getweakrefs(o) == [ref2], "list of refs does not match") @@ -323,7 +336,7 @@ ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref2 - test_support.gc_collect() + extra_collect() if test_support.is_jython: # XXX: Likely a Jython bug: the following inline declared # [ref1] list isn't garbage collected no matter how many @@ -340,7 +353,7 @@ "list of refs does not match") del ref1 - test_support.gc_collect() + extra_collect() self.assert_(weakref.getweakrefs(o) == [], "list of refs not cleared") @@ -619,7 +632,7 @@ del callback, c, d, C self.assertEqual(alist, []) # del isn't enough to clean up cycles gc.collect() - test_support.gc_collect() + extra_collect() self.assertEqual(alist, ["safe_callback called"]) self.assertEqual(external_wr(), None) @@ -770,18 +783,18 @@ del items1, items2 self.assert_(len(dict) == self.COUNT) del objects[0] - test_support.gc_collect() + extra_collect() self.assert_(len(dict) == (self.COUNT - 1), "deleting object did not cause dictionary update") del objects, o - test_support.gc_collect() + extra_collect() self.assert_(len(dict) == 0, "deleting the values did not clear the dictionary") # regression on SF bug #447152: dict = weakref.WeakValueDictionary() self.assertRaises(KeyError, dict.__getitem__, 1) dict[2] = C() - test_support.gc_collect() + extra_collect() self.assertRaises(KeyError, dict.__getitem__, 2) def test_weak_keys(self): @@ -802,11 +815,11 @@ del items1, items2 self.assert_(len(dict) == self.COUNT) del objects[0] - test_support.gc_collect() + extra_collect() self.assert_(len(dict) == (self.COUNT - 1), "deleting object did not cause dictionary update") del objects, o - test_support.gc_collect() + extra_collect() self.assert_(len(dict) == 0, "deleting the keys did not clear the dictionary") o = Object(42) @@ -1115,7 +1128,7 @@ >>> o is o2 True >>> del o, o2 ->>> test_support.gc_collect() +>>> extra_collect() >>> print r() None @@ -1168,7 +1181,7 @@ >>> id2obj(a_id) is a True >>> del a ->>> test_support.gc_collect() +>>> extra_collect() >>> try: ... id2obj(a_id) ... except KeyError: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2009-06-08 07:06:09
|
Revision: 6469 http://jython.svn.sourceforge.net/jython/?rev=6469&view=rev Author: pjenvey Date: 2009-06-08 07:06:07 +0000 (Mon, 08 Jun 2009) Log Message: ----------- rename to test_nt_paths_jy and add to skips Modified Paths: -------------- trunk/jython/Lib/test/regrtest.py Added Paths: ----------- trunk/jython/Lib/test/test_nt_paths_jy.py Removed Paths: ------------- trunk/jython/Lib/test/test_nt_paths.py Modified: trunk/jython/Lib/test/regrtest.py =================================================================== --- trunk/jython/Lib/test/regrtest.py 2009-06-08 06:41:36 UTC (rev 6468) +++ trunk/jython/Lib/test/regrtest.py 2009-06-08 07:06:07 UTC (rev 6469) @@ -1538,6 +1538,8 @@ self.expected.update([ 'test_grp', 'test_mhlib', 'test_posix', 'test_pwd', 'test_signal']) + if os._name != 'nt': + self.expected.add('test_nt_paths_jy') self.valid = True Deleted: trunk/jython/Lib/test/test_nt_paths.py =================================================================== --- trunk/jython/Lib/test/test_nt_paths.py 2009-06-08 06:41:36 UTC (rev 6468) +++ trunk/jython/Lib/test/test_nt_paths.py 2009-06-08 07:06:07 UTC (rev 6469) @@ -1,40 +0,0 @@ -"""Test path handling on Windows - -Made for Jython. -""" -from __future__ import with_statement -import os -import unittest -from test import test_support - -class NTAbspathTestCase(unittest.TestCase): - - def setUp(self): - with open(test_support.TESTFN, 'w') as fp: - fp.write('foo') - - # Move to the same drive as TESTFN - drive, self.path = os.path.splitdrive(os.path.abspath( - test_support.TESTFN)) - self.orig_cwd = os.getcwd() - os.chdir(os.path.join(drive, os.sep)) - - def tearDown(self): - os.chdir(self.orig_cwd) - os.remove(test_support.TESTFN) - - def test_abspaths(self): - # Ensure r'\TESTFN' and '/TESTFN' are handled as absolute - for path in self.path, self.path.replace('\\', '/'): - with open(path) as fp: - self.assertEqual(fp.read(), 'foo') - - -def test_main(): - if (os._name if test_support.is_jython else os.name) != 'nt': - raise test_support.TestSkipped('NT specific test') - test_support.run_unittest(NTAbspathTestCase) - - -if __name__ == '__main__': - test_main() Copied: trunk/jython/Lib/test/test_nt_paths_jy.py (from rev 6468, trunk/jython/Lib/test/test_nt_paths.py) =================================================================== --- trunk/jython/Lib/test/test_nt_paths_jy.py (rev 0) +++ trunk/jython/Lib/test/test_nt_paths_jy.py 2009-06-08 07:06:07 UTC (rev 6469) @@ -0,0 +1,40 @@ +"""Test path handling on Windows + +Made for Jython. +""" +from __future__ import with_statement +import os +import unittest +from test import test_support + +class NTAbspathTestCase(unittest.TestCase): + + def setUp(self): + with open(test_support.TESTFN, 'w') as fp: + fp.write('foo') + + # Move to the same drive as TESTFN + drive, self.path = os.path.splitdrive(os.path.abspath( + test_support.TESTFN)) + self.orig_cwd = os.getcwd() + os.chdir(os.path.join(drive, os.sep)) + + def tearDown(self): + os.chdir(self.orig_cwd) + os.remove(test_support.TESTFN) + + def test_abspaths(self): + # Ensure r'\TESTFN' and '/TESTFN' are handled as absolute + for path in self.path, self.path.replace('\\', '/'): + with open(path) as fp: + self.assertEqual(fp.read(), 'foo') + + +def test_main(): + if (os._name if test_support.is_jython else os.name) != 'nt': + raise test_support.TestSkipped('NT specific test') + test_support.run_unittest(NTAbspathTestCase) + + +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-07-30 14:31:18
|
Revision: 6605 http://jython.svn.sourceforge.net/jython/?rev=6605&view=rev Author: fwierzbicki Date: 2009-07-30 14:31:06 +0000 (Thu, 30 Jul 2009) Log Message: ----------- Moved a few tests from test_codeop_jy to test_codeop as they are valid for both CPython and Jython. Prepping to push these and a few more upstream to CPython. Modified Paths: -------------- trunk/jython/Lib/test/test_codeop.py trunk/jython/Lib/test/test_codeop_jy.py Modified: trunk/jython/Lib/test/test_codeop.py =================================================================== --- trunk/jython/Lib/test/test_codeop.py 2009-07-30 12:09:14 UTC (rev 6604) +++ trunk/jython/Lib/test/test_codeop.py 2009-07-30 14:31:06 UTC (rev 6605) @@ -108,6 +108,12 @@ av("\n \na**3","eval") av("#a\n#b\na**3","eval") + # From Jython project, not Jython specific + + # this failed under Jython 2.2.1 + av("def x():\n try: pass\n finally: [a for a in (1,2)]\n") + + def test_incomplete(self): ai = self.assertIncomplete @@ -149,6 +155,8 @@ ai("9+ \\","eval") ai("lambda z: \\","eval") + # From Jython project, not Jython specific + #Did not work in Jython 2.5rc2 see first issue in # http://bugs.jython.org/issue1354 ai("if True:\n if True:\n if True: \n") @@ -184,6 +192,10 @@ ai("lambda z:","eval") ai("a b","eval") + # From Jython project, not Jython specific + ai("return 2.3") + ai("if (a == 1 and b = 2): pass") + def test_filename(self): self.assertEquals(compile_command("a = 1\n", "abc").co_filename, compile("a = 1\n", "abc", 'single').co_filename) Modified: trunk/jython/Lib/test/test_codeop_jy.py =================================================================== --- trunk/jython/Lib/test/test_codeop_jy.py 2009-07-30 12:09:14 UTC (rev 6604) +++ trunk/jython/Lib/test/test_codeop_jy.py 2009-07-30 14:31:06 UTC (rev 6605) @@ -49,9 +49,6 @@ av("def x():\n pass\n ") av("\n\ndef x():\n pass") - # this failed under 2.2.1 - av("def x():\n try: pass\n finally: [a for a in (1,2)]\n") - av("if 9==3:\n pass\nelse:\n pass") av("if 1:\n pass\n if 1:\n pass\n else:\n pass") @@ -75,13 +72,11 @@ def test_invalid(self): ai = self.assertInvalid - ai("return 2.3") ai("del 1") ai("del ()") ai("del (1,)") ai("del [1]") ai("del '1'") - ai("if (a == 1 and b = 2): pass") ai("[i for i in range(10)] = (1, 2, 3)") This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2009-08-02 17:13:24
|
Revision: 6623 http://jython.svn.sourceforge.net/jython/?rev=6623&view=rev Author: fwierzbicki Date: 2009-08-02 17:13:16 +0000 (Sun, 02 Aug 2009) Log Message: ----------- Moved the rest of the tests that could be moved from test_codeop_jy to test_codeop.py. Modified Paths: -------------- trunk/jython/Lib/test/test_codeop.py trunk/jython/Lib/test/test_codeop_jy.py Modified: trunk/jython/Lib/test/test_codeop.py =================================================================== --- trunk/jython/Lib/test/test_codeop.py 2009-08-02 00:09:03 UTC (rev 6622) +++ trunk/jython/Lib/test/test_codeop.py 2009-08-02 17:13:16 UTC (rev 6623) @@ -108,12 +108,26 @@ av("\n \na**3","eval") av("#a\n#b\na**3","eval") - # From Jython project, not Jython specific + av("\n\na = 1\n\n") + av("\n\nif 1: a=1\n\n") + + av("if 1:\n pass\n if 1:\n pass\n else:\n pass\n") + av("#a\n\n \na=3\n\n") + + av("\n\na**3","eval") + av("\n \na**3","eval") + av("#a\n#b\na**3","eval") + # this failed under Jython 2.2.1 - av("def x():\n try: pass\n finally: [a for a in (1,2)]\n") + av("def f():\n try: pass\n finally: [x for x in (1,2)]\n") + av("def f():\n pass\n#foo\n") + #XXX: works in CPython + if not is_jython: + av("@a.b.c\ndef f():\n pass\n") + def test_incomplete(self): ai = self.assertIncomplete @@ -155,8 +169,6 @@ ai("9+ \\","eval") ai("lambda z: \\","eval") - # From Jython project, not Jython specific - #Did not work in Jython 2.5rc2 see first issue in # http://bugs.jython.org/issue1354 ai("if True:\n if True:\n if True: \n") @@ -266,10 +278,11 @@ ai("a = 'a\\\n") ai("a = 1","eval") - #XXX: Current limitation in PythonPartial.g prevents this from properly - # erroring on Jython. + + # XXX: PythonPartial.g needs to reject this. if not is_jython: ai("a = (","eval") + ai("]","eval") ai("())","eval") ai("[}","eval") @@ -277,17 +290,30 @@ ai("lambda z:","eval") ai("a b","eval") - # From Jython project, not Jython specific ai("return 2.3") ai("if (a == 1 and b = 2): pass") + # XXX: PythonPartial.g needs to reject these. + if not is_jython: + ai("del 1") + ai("del ()") + ai("del (1,)") + ai("del [1]") + ai("del '1'") + ai("[i for i in range(10)] = (1, 2, 3)") + def test_filename(self): self.assertEquals(compile_command("a = 1\n", "abc").co_filename, compile("a = 1\n", "abc", 'single').co_filename) self.assertNotEquals(compile_command("a = 1\n", "abc").co_filename, compile("a = 1\n", "def", 'single').co_filename) + def test_no_universal_newlines(self): + # previously \r was translated due to universal newlines + code = compile_command("'\rfoo\r'", symbol='eval') + self.assertEqual(eval(code), '\rfoo\r') + def test_main(): run_unittest(CodeopTests) Modified: trunk/jython/Lib/test/test_codeop_jy.py =================================================================== --- trunk/jython/Lib/test/test_codeop_jy.py 2009-08-02 00:09:03 UTC (rev 6622) +++ trunk/jython/Lib/test/test_codeop_jy.py 2009-08-02 17:13:16 UTC (rev 6623) @@ -37,38 +37,25 @@ def test_valid(self): av = self.assertValid + # Failed for Jython 2.5a2. See http://bugs.jython.org/issue1116. + # For some reason this tests fails when run from test_codeops#test_valid + # when run from Jython (works in CPython). + av("@a.b.c\ndef f():\n pass") + + # These tests pass on Jython, but fail on CPython. Will need to investigate + # to decide if we need to match CPython. av("\n\n") av("# a\n") - av("\n\na = 1\n\n",values={'a':1}) - av("\n\nif 1: a=1\n\n",values={'a':1}) - - av("def x():\n pass") av("def x():\n pass\n ") av("def x():\n pass\n ") - av("\n\ndef x():\n pass") - - av("if 9==3:\n pass\nelse:\n pass") - av("if 1:\n pass\n if 1:\n pass\n else:\n pass") - av("#a\n\n \na=3\n",values={'a':3}) - - - # these failed under 2.1 - self.eval_d = {'a': 2} - av("\n\na**3","eval",value=8) - av("\n \na**3","eval",value=8) - av("#a\n#b\na**3","eval",value=8) - - # this failed under 2.2.1 - av("def f():\n try: pass\n finally: [x for x in (1,2)]") - - # Failed for Jython 2.5a2. See http://bugs.jython.org/issue1116. - av("@a.b.c\ndef f():\n pass") - av("def f():\n pass\n#foo") + # these tests fail in Jython in test_codeop.py because PythonPartial.g + # erroneously allows them through. Once that is fixed, these tests + # can be deleted. def test_invalid(self): ai = self.assertInvalid @@ -80,17 +67,8 @@ ai("[i for i in range(10)] = (1, 2, 3)") -class CodeopTests(unittest.TestCase): - - def test_no_universal_newlines(self): - # previously \r was translated due to universal newlines - code = codeop.compile_command("'\rfoo\r'", symbol='eval') - self.assertEqual(eval(code), '\rfoo\r') - - def test_main(): - run_unittest(CompileTests, - CodeopTests) + run_unittest(CompileTests) if __name__ == "__main__": This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |