You can subscribe to this list here.
2000 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(1) |
Nov
(107) |
Dec
(67) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2001 |
Jan
(76) |
Feb
(125) |
Mar
(72) |
Apr
(13) |
May
(18) |
Jun
(12) |
Jul
(129) |
Aug
(47) |
Sep
(1) |
Oct
(36) |
Nov
(128) |
Dec
(124) |
2002 |
Jan
(59) |
Feb
|
Mar
(14) |
Apr
(14) |
May
(72) |
Jun
(9) |
Jul
(3) |
Aug
(5) |
Sep
(18) |
Oct
(65) |
Nov
(28) |
Dec
(12) |
2003 |
Jan
(10) |
Feb
(2) |
Mar
(4) |
Apr
(33) |
May
(21) |
Jun
(9) |
Jul
(29) |
Aug
(34) |
Sep
(4) |
Oct
(8) |
Nov
(15) |
Dec
(4) |
2004 |
Jan
(26) |
Feb
(12) |
Mar
(11) |
Apr
(9) |
May
(7) |
Jun
|
Jul
(5) |
Aug
|
Sep
(3) |
Oct
(7) |
Nov
(1) |
Dec
(10) |
2005 |
Jan
(2) |
Feb
(72) |
Mar
(16) |
Apr
(39) |
May
(48) |
Jun
(97) |
Jul
(57) |
Aug
(13) |
Sep
(16) |
Oct
(24) |
Nov
(100) |
Dec
(24) |
2006 |
Jan
(15) |
Feb
(34) |
Mar
(33) |
Apr
(31) |
May
(79) |
Jun
(64) |
Jul
(41) |
Aug
(64) |
Sep
(31) |
Oct
(46) |
Nov
(55) |
Dec
(37) |
2007 |
Jan
(32) |
Feb
(61) |
Mar
(11) |
Apr
(58) |
May
(46) |
Jun
(30) |
Jul
(94) |
Aug
(93) |
Sep
(86) |
Oct
(69) |
Nov
(125) |
Dec
(177) |
2008 |
Jan
(169) |
Feb
(97) |
Mar
(74) |
Apr
(113) |
May
(120) |
Jun
(334) |
Jul
(215) |
Aug
(237) |
Sep
(72) |
Oct
(189) |
Nov
(126) |
Dec
(160) |
2009 |
Jan
(180) |
Feb
(45) |
Mar
(98) |
Apr
(140) |
May
(151) |
Jun
(71) |
Jul
(107) |
Aug
(119) |
Sep
(73) |
Oct
(121) |
Nov
(14) |
Dec
(6) |
2010 |
Jan
(13) |
Feb
(9) |
Mar
(10) |
Apr
(64) |
May
(3) |
Jun
(16) |
Jul
(7) |
Aug
(23) |
Sep
(17) |
Oct
(37) |
Nov
(5) |
Dec
(8) |
2011 |
Jan
(10) |
Feb
(11) |
Mar
(77) |
Apr
(11) |
May
(2) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <fwi...@us...> - 2008-10-15 20:10:53
|
Revision: 5400 http://jython.svn.sourceforge.net/jython/?rev=5400&view=rev Author: fwierzbicki Date: 2008-10-15 20:10:46 +0000 (Wed, 15 Oct 2008) Log Message: ----------- ? was replaced by <module> in info. Modified Paths: -------------- trunk/jython/bugtests/test107.py Modified: trunk/jython/bugtests/test107.py =================================================================== --- trunk/jython/bugtests/test107.py 2008-10-15 17:06:58 UTC (rev 5399) +++ trunk/jython/bugtests/test107.py 2008-10-15 20:10:46 UTC (rev 5400) @@ -53,7 +53,7 @@ g = getinfo() support.compare(g[0], "(__main__|test107)") support.compare(g[1], "None") -support.compare(g[2], "\\?") +support.compare(g[2], "<module>") foo() Bar().baz() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-15 17:07:58
|
Revision: 5399 http://jython.svn.sourceforge.net/jython/?rev=5399&view=rev Author: fwierzbicki Date: 2008-10-15 17:06:58 +0000 (Wed, 15 Oct 2008) Log Message: ----------- New dotted and absolute import support. I have local tests, but have not figured out how to integrate them into the regression tests. Examining the tests in CPython does not appear to give much guidance here, the testing of these features looks pretty thin (mainly they test features around __package__ which is new in 2.6). Maybe I just haven't found the relevant tests? Modified Paths: -------------- trunk/jython/src/org/python/core/imp.java Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2008-10-15 15:56:58 UTC (rev 5398) +++ trunk/jython/src/org/python/core/imp.java 2008-10-15 17:06:58 UTC (rev 5399) @@ -529,6 +529,9 @@ * @return the parent name for a module */ private static String getParent(PyObject dict, int level) { + if (dict == null || level == 0) { + return null; + } PyObject tmp = dict.__finditem__("__name__"); if (tmp == null) { return null; @@ -538,13 +541,23 @@ tmp = dict.__finditem__("__path__"); if (tmp != null && tmp instanceof PyList) { return name.intern(); - } else { - int dot = name.lastIndexOf('.'); + } + int dot = name.lastIndexOf('.'); + if (dot == -1) { + if (level > 0) { + throw Py.ValueError("Attempted relative import in non-package"); + } + return null; + } + name = name.substring(0, dot); + while (--level > 0) { + dot = name.lastIndexOf('.'); if (dot == -1) { - return null; + throw Py.ValueError("Attempted relative import beyond toplevel package"); } - return name.substring(0, dot).intern(); + name = name.substring(0, dot); } + return name.intern(); } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2008-10-15 15:59:44
|
Revision: 5398 http://jython.svn.sourceforge.net/jython/?rev=5398&view=rev Author: otmarhumbel Date: 2008-10-15 15:56:58 +0000 (Wed, 15 Oct 2008) Log Message: ----------- applied lsoto's PyString change (revision 5390) to this handler as well Revision Links: -------------- http://jython.svn.sourceforge.net/jython/?rev=5390&view=rev Modified Paths: -------------- trunk/jython/src/com/ziclix/python/sql/handler/InformixDataHandler.java Modified: trunk/jython/src/com/ziclix/python/sql/handler/InformixDataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/handler/InformixDataHandler.java 2008-10-15 08:10:37 UTC (rev 5397) +++ trunk/jython/src/com/ziclix/python/sql/handler/InformixDataHandler.java 2008-10-15 15:56:58 UTC (rev 5398) @@ -79,7 +79,7 @@ String varchar; // Ifx driver can't handle the setCharacterStream() method so use setObject() instead if (object instanceof PyFile) { - varchar = ((PyFile) object).read(); + varchar = ((PyFile) object).read().toString(); } else { varchar = (String) object.__tojava__(String.class); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2008-10-15 08:10:49
|
Revision: 5397 http://jython.svn.sourceforge.net/jython/?rev=5397&view=rev Author: otmarhumbel Date: 2008-10-15 08:10:37 +0000 (Wed, 15 Oct 2008) Log Message: ----------- safely test if JAVA_HOME or JYTHON_HOME is set we can now handle both quoted and unquoted settings like: JAVA_HOME=C:\Program Files\Java\jdk1.6.0_07 JAVA_HOME="C:\Program Files\Java\jdk1.6.0_07" this should fix issue #1125 Modified Paths: -------------- trunk/jython/src/shell/jython.bat Modified: trunk/jython/src/shell/jython.bat =================================================================== --- trunk/jython/src/shell/jython.bat 2008-10-15 05:35:53 UTC (rev 5396) +++ trunk/jython/src/shell/jython.bat 2008-10-15 08:10:37 UTC (rev 5397) @@ -17,12 +17,18 @@ rem ----- Verify and set required environment variables ----------------------- set _JAVA_CMD=java -if not [%JAVA_HOME%] == [] ( +rem remove surrounding quotes from java home, to be able to safely empty-test it +set _TRIMMED_JAVA_HOME=%JAVA_HOME% +for /f "useback tokens=*" %%a in ('%_TRIMMED_JAVA_HOME%') do set _TRIMMED_JAVA_HOME=%%~a +if not "%_TRIMMED_JAVA_HOME%"=="" ( set _JAVA_CMD="%JAVA_HOME:"=%\bin\java" ) set _JYTHON_HOME=%JYTHON_HOME% -if not [%JYTHON_HOME%] == [] goto gotHome +rem remove surrounding quotes from jython home, to be able to safely empty-test it +set _TRIMMED_JYTHON_HOME=%JYTHON_HOME% +for /f "useback tokens=*" %%a in ('%_TRIMMED_JYTHON_HOME%') do set _TRIMMED_JYTHON_HOME=%%~a +if not "%_TRIMMED_JYTHON_HOME%"=="" goto gotHome pushd "%~dp0%\.." set _JYTHON_HOME="%CD%" popd @@ -84,7 +90,7 @@ if ["%_CMP%"] == ["--"] goto argsDone if ["%_CMP%"] == ["--jdb"] ( - if [%JAVA_HOME%] == [] ( + if "%_TRIMMED_JAVA_HOME%"=="" ( set _JAVA_CMD=jdb ) else ( set _JAVA_CMD="%JAVA_HOME:"=%\bin\jdb" @@ -145,6 +151,8 @@ set _JAVA_OPTS= set _JAVA_STACK= set _JYTHON_HOME= +set _TRIMMED_JAVA_HOME= +set _TRIMMED_JYTHON_HOME= :finish exit /b %E% This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <otm...@us...> - 2008-10-15 05:35:57
|
Revision: 5396 http://jython.svn.sourceforge.net/jython/?rev=5396&view=rev Author: otmarhumbel Date: 2008-10-15 05:35:53 +0000 (Wed, 15 Oct 2008) Log Message: ----------- fixed typo: _JAVA_HOME has to be JAVA_HOME Modified Paths: -------------- trunk/jython/src/shell/jython.bat Modified: trunk/jython/src/shell/jython.bat =================================================================== --- trunk/jython/src/shell/jython.bat 2008-10-15 04:42:15 UTC (rev 5395) +++ trunk/jython/src/shell/jython.bat 2008-10-15 05:35:53 UTC (rev 5396) @@ -87,7 +87,7 @@ if [%JAVA_HOME%] == [] ( set _JAVA_CMD=jdb ) else ( - set _JAVA_CMD="%_JAVA_HOME:"=%\bin\jdb" + set _JAVA_CMD="%JAVA_HOME:"=%\bin\jdb" ) goto :nextArg ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-15 04:42:19
|
Revision: 5395 http://jython.svn.sourceforge.net/jython/?rev=5395&view=rev Author: cgroves Date: 2008-10-15 04:42:15 +0000 (Wed, 15 Oct 2008) Log Message: ----------- Remove build/exposed from the classpath. Having it in there meant any source navigation like F3 or Open Type would go to the exposed version rather than the source version that you were really after. Not having it in there means you need to add the exposed dir to the classpath of any run configurations in Eclipse, but that felt like a lesser evil than my smiting my keyboard in frustration every time Eclipse opened the wrong file. Modified Paths: -------------- trunk/jython/.classpath Modified: trunk/jython/.classpath =================================================================== --- trunk/jython/.classpath 2008-10-15 00:46:02 UTC (rev 5394) +++ trunk/jython/.classpath 2008-10-15 04:42:15 UTC (rev 5395) @@ -1,6 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> <classpath> - <classpathentry kind="lib" path="build/exposed"/> <classpathentry excluding="com/ziclix/python/sql/handler/InformixDataHandler.java|com/ziclix/python/sql/handler/OracleDataHandler.java" kind="src" output="build/classes" path="src"/> <classpathentry kind="src" output="build/classes" path="build/gensrc"/> <classpathentry kind="src" output="build/classes" path="tests/java"/> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-15 00:46:13
|
Revision: 5394 http://jython.svn.sourceforge.net/jython/?rev=5394&view=rev Author: pjenvey Date: 2008-10-15 00:46:02 +0000 (Wed, 15 Oct 2008) Log Message: ----------- fix solid_base considering slotted objects with a __dict__ as solid Modified Paths: -------------- trunk/jython/Lib/test/test_class_jy.py trunk/jython/src/org/python/core/PyType.java Modified: trunk/jython/Lib/test/test_class_jy.py =================================================================== --- trunk/jython/Lib/test/test_class_jy.py 2008-10-14 23:08:45 UTC (rev 5393) +++ trunk/jython/Lib/test/test_class_jy.py 2008-10-15 00:46:02 UTC (rev 5394) @@ -162,6 +162,18 @@ class Bar(SlottedBase): __metaclass__ = Meta + def test_slotted_diamond_problem_bug(self): + class A(object): + __slots__ = 'foo' + class B(A): + pass + class C(A): + pass + # used to raise TypeError: multiple bases have instance lay-out + # conflict + class D(B, C): + pass + class ClassNamelessModuleTestCase(unittest.TestCase): Modified: trunk/jython/src/org/python/core/PyType.java =================================================================== --- trunk/jython/src/org/python/core/PyType.java 2008-10-14 23:08:45 UTC (rev 5393) +++ trunk/jython/src/org/python/core/PyType.java 2008-10-15 00:46:02 UTC (rev 5394) @@ -823,7 +823,8 @@ } /** - * Finds the parent of type with an underlying_class or with slots. + * Finds the parent of type with an underlying_class or with slots sans a __dict__ + * slot. */ private static PyType solid_base(PyType type) { do { @@ -836,7 +837,7 @@ } private static boolean isSolidBase(PyType type) { - return type.underlying_class != null || type.numSlots != 0; + return type.underlying_class != null || (type.numSlots != 0 && !type.needs_userdict); } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-14 23:08:57
|
Revision: 5393 http://jython.svn.sourceforge.net/jython/?rev=5393&view=rev Author: pjenvey Date: 2008-10-14 23:08:45 +0000 (Tue, 14 Oct 2008) Log Message: ----------- o fix the socket hostname functions returning unicode hostnames instead of strs. was causing test_wsgiref to fail on environments where socket.getfqdn('localhost') != 'localhost' o fix getaddrinfo default family and handling of bad familys Modified Paths: -------------- trunk/jython/Lib/socket.py trunk/jython/Lib/test/test_socket.py Modified: trunk/jython/Lib/socket.py =================================================================== --- trunk/jython/Lib/socket.py 2008-10-14 19:28:28 UTC (rev 5392) +++ trunk/jython/Lib/socket.py 2008-10-14 23:08:45 UTC (rev 5393) @@ -81,6 +81,7 @@ import org.python.core.io.DatagramSocketIO import org.python.core.io.ServerSocketIO import org.python.core.io.SocketIO +from org.python.core.util.StringUtil import asPyString class error(Exception): pass class herror(error): pass @@ -464,8 +465,8 @@ names = [] addrs = [] for addr in addresses: - names.append(addr.getHostName()) - addrs.append(addr.getHostAddress()) + names.append(asPyString(addr.getHostName())) + addrs.append(asPyString(addr.getHostAddress())) return (names, addrs) def getfqdn(name=None): @@ -487,13 +488,13 @@ def gethostname(): try: - return java.net.InetAddress.getLocalHost().getHostName() + return asPyString(java.net.InetAddress.getLocalHost().getHostName()) except java.lang.Exception, jlx: raise _map_exception(jlx) def gethostbyname(name): try: - return java.net.InetAddress.getByName(name).getHostAddress() + return asPyString(java.net.InetAddress.getByName(name).getHostAddress()) except java.lang.Exception, jlx: raise _map_exception(jlx) @@ -523,10 +524,10 @@ else: return _udpsocket() -def getaddrinfo(host, port, family=None, socktype=None, proto=0, flags=None): +def getaddrinfo(host, port, family=AF_INET, socktype=None, proto=0, flags=None): try: if not family in [AF_INET, AF_INET6, AF_UNSPEC]: - raise NotSupportedError() + raise gaierror(errno.EIO, 'ai_family not supported') filter_fns = [] filter_fns.append({ AF_INET: lambda x: isinstance(x, java.net.Inet4Address), @@ -541,7 +542,9 @@ if len([f for f in filter_fns if f(a)]): family = {java.net.Inet4Address: AF_INET, java.net.Inet6Address: AF_INET6}[a.getClass()] # TODO: Include flowinfo and scopeid in a 4-tuple for IPv6 addresses - results.append( (family, socktype, proto, a.getCanonicalHostName(), (a.getHostAddress(), port)) ) + canonname = asPyString(a.getCanonicalHostName()) + sockname = asPyString(a.getHostAddress()) + results.append((family, socktype, proto, canonname, (sockname, port))) return results except java.lang.Exception, jlx: raise _map_exception(jlx) Modified: trunk/jython/Lib/test/test_socket.py =================================================================== --- trunk/jython/Lib/test/test_socket.py 2008-10-14 19:28:28 UTC (rev 5392) +++ trunk/jython/Lib/test/test_socket.py 2008-10-14 23:08:45 UTC (rev 5393) @@ -274,8 +274,10 @@ def testHostnameRes(self): # Testing hostname resolution mechanisms hostname = socket.gethostname() + self.assert_(isinstance(hostname, str)) try: ip = socket.gethostbyname(hostname) + self.assert_(isinstance(ip, str)) except socket.error: # Probably name lookup wasn't set up right; skip this test self.fail("Probably name lookup wasn't set up right; skip testHostnameRes.gethostbyname") @@ -283,15 +285,35 @@ self.assert_(ip.find('.') >= 0, "Error resolving host to ip.") try: hname, aliases, ipaddrs = socket.gethostbyaddr(ip) + self.assert_(isinstance(hname, str)) + for hosts in aliases, ipaddrs: + self.assert_(all(isinstance(host, str) for host in hosts)) except socket.error: # Probably a similar problem as above; skip this test self.fail("Probably name lookup wasn't set up right; skip testHostnameRes.gethostbyaddr") return all_host_names = [hostname, hname] + aliases fqhn = socket.getfqdn() + self.assert_(isinstance(fqhn, str)) if not fqhn in all_host_names: self.fail("Error testing host resolution mechanisms.") + def testGetAddrInfo(self): + try: + socket.getaddrinfo(HOST, PORT, 9999) + except socket.gaierror, gaix: + self.failUnlessEqual(gaix[0], errno.EIO) + except Exception, x: + self.fail("getaddrinfo with bad family raised wrong exception: %s" % x) + else: + self.fail("getaddrinfo with bad family should have raised exception") + + addrinfos = socket.getaddrinfo(HOST, PORT) + for addrinfo in addrinfos: + family, socktype, proto, canonname, sockaddr = addrinfo + self.assert_(isinstance(canonname, str)) + self.assert_(isinstance(sockaddr[0], str)) + def testRefCountGetNameInfo(self): # Testing reference count for getnameinfo import sys This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-14 19:28:37
|
Revision: 5392 http://jython.svn.sourceforge.net/jython/?rev=5392&view=rev Author: fwierzbicki Date: 2008-10-14 19:28:28 +0000 (Tue, 14 Oct 2008) Log Message: ----------- Added inFinally parameter to suite rule, and a dynamically scoped parameter continueIllegal to support disallowing continue in a finally clause. This fixes test_syntax. Modified Paths: -------------- trunk/jython/grammar/Python.g Modified: trunk/jython/grammar/Python.g =================================================================== --- trunk/jython/grammar/Python.g 2008-10-14 16:43:46 UTC (rev 5391) +++ trunk/jython/grammar/Python.g 2008-10-14 19:28:28 UTC (rev 5392) @@ -402,7 +402,7 @@ funcdef @init { stmtType stype = null; } @after { $funcdef.tree = stype; } - : decorators? DEF NAME parameters COLON suite + : decorators? DEF NAME parameters COLON suite[false] { Token t = $DEF; if ($decorators.start != null) { @@ -663,7 +663,11 @@ //continue_stmt: 'continue' continue_stmt - : CONTINUE + : CONTINUE { + if (!$suite.isEmpty() && $suite::continueIllegal) { + errorHandler.error("'continue' not supported inside 'finally' clause", new PythonTree($continue_stmt.start)); + } + } -> ^(CONTINUE<Continue>[$CONTINUE]) ; @@ -802,7 +806,7 @@ //if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] if_stmt - : IF test[expr_contextType.Load] COLON ifsuite=suite elif_clause[$test.start]? + : IF test[expr_contextType.Load] COLON ifsuite=suite[false] elif_clause[$test.start]? -> ^(IF<If>[$IF, actions.castExpr($test.tree), actions.castStmts($ifsuite.stypes), actions.makeElse($elif_clause.stypes, $elif_clause.tree)]) ; @@ -812,7 +816,7 @@ : else_clause { $stypes = $else_clause.stypes; } - | ELIF test[expr_contextType.Load] COLON suite + | ELIF test[expr_contextType.Load] COLON suite[false] (e2=elif_clause[$iftest] -> ^(ELIF<If>[$iftest, actions.castExpr($test.tree), actions.castStmts($suite.stypes), actions.makeElse($e2.stypes, $e2.tree)]) | @@ -822,7 +826,7 @@ //not in CPython's Grammar file else_clause returns [List stypes] - : ORELSE COLON elsesuite=suite { + : ORELSE COLON elsesuite=suite[false] { $stypes = $suite.stypes; } ; @@ -835,7 +839,7 @@ @after { $while_stmt.tree = stype; } - : WHILE test[expr_contextType.Load] COLON s1=suite (ORELSE COLON s2=suite)? + : WHILE test[expr_contextType.Load] COLON s1=suite[false] (ORELSE COLON s2=suite[false])? { stype = actions.makeWhile($WHILE, actions.castExpr($test.tree), $s1.stypes, $s2.stypes); } @@ -849,8 +853,8 @@ @after { $for_stmt.tree = stype; } - : FOR exprlist[expr_contextType.Store] IN testlist[expr_contextType.Load] COLON s1=suite - (ORELSE COLON s2=suite)? + : FOR exprlist[expr_contextType.Store] IN testlist[expr_contextType.Load] COLON s1=suite[false] + (ORELSE COLON s2=suite[false])? { stype = actions.makeFor($FOR, $exprlist.etype, actions.castExpr($testlist.tree), $s1.stypes, $s2.stypes); } @@ -868,12 +872,12 @@ @after { $try_stmt.tree = stype; } - : TRY COLON trysuite=suite - ( e+=except_clause+ (ORELSE COLON elsesuite=suite)? (FINALLY COLON finalsuite=suite)? + : TRY COLON trysuite=suite[!$suite.isEmpty() && $suite::continueIllegal] + ( e+=except_clause+ (ORELSE COLON elsesuite=suite[!$suite.isEmpty() && $suite::continueIllegal])? (FINALLY COLON finalsuite=suite[true])? { stype = actions.makeTryExcept($TRY, $trysuite.stypes, $e, $elsesuite.stypes, $finalsuite.stypes); } - | FINALLY COLON finalsuite=suite + | FINALLY COLON finalsuite=suite[true] { stype = actions.makeTryFinally($TRY, $trysuite.stypes, $finalsuite.stypes); } @@ -888,7 +892,7 @@ @after { $with_stmt.tree = stype; } - : WITH test[expr_contextType.Load] (with_var)? COLON suite + : WITH test[expr_contextType.Load] (with_var)? COLON suite[false] { stype = new With($WITH, actions.castExpr($test.tree), $with_var.etype, actions.castStmts($suite.stypes)); @@ -905,14 +909,22 @@ //except_clause: 'except' [test [',' test]] except_clause - : EXCEPT (t1=test[expr_contextType.Load] (COMMA t2=test[expr_contextType.Store])?)? COLON suite + : EXCEPT (t1=test[expr_contextType.Load] (COMMA t2=test[expr_contextType.Store])?)? COLON suite[!$suite.isEmpty() && $suite::continueIllegal] -> ^(EXCEPT<excepthandlerType>[$EXCEPT, actions.castExpr($t1.tree), actions.castExpr($t2.tree), actions.castStmts($suite.stypes), $EXCEPT.getLine(), $EXCEPT.getCharPositionInLine()]) ; //suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT -suite returns [List stypes] +suite[boolean fromFinally] returns [List stypes] +scope { + boolean continueIllegal; +} @init { + if ($suite::continueIllegal || fromFinally) { + $suite::continueIllegal = true; + } else { + $suite::continueIllegal = false; + } $stypes = new ArrayList(); } : simple_stmt @@ -1409,7 +1421,7 @@ @after { $classdef.tree = stype; } - : CLASS NAME (LPAREN testlist[expr_contextType.Load]? RPAREN)? COLON suite + : CLASS NAME (LPAREN testlist[expr_contextType.Load]? RPAREN)? COLON suite[false] { stype = new ClassDef($CLASS, actions.cantBeNone($NAME), actions.makeBases(actions.castExpr($testlist.tree)), actions.castStmts($suite.stypes)); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-14 16:43:57
|
Revision: 5391 http://jython.svn.sourceforge.net/jython/?rev=5391&view=rev Author: fwierzbicki Date: 2008-10-14 16:43:46 +0000 (Tue, 14 Oct 2008) Log Message: ----------- Fix or skips for most remaining problems in test_syntax.py. All remaining problems are due to the lack of enforcement on continuations not being permitted in finally. Modified Paths: -------------- trunk/jython/Lib/test/test_syntax.py trunk/jython/grammar/Python.g trunk/jython/src/org/python/antlr/GrammarActions.java Modified: trunk/jython/Lib/test/test_syntax.py =================================================================== --- trunk/jython/Lib/test/test_syntax.py 2008-10-14 03:20:10 UTC (rev 5390) +++ trunk/jython/Lib/test/test_syntax.py 2008-10-14 16:43:46 UTC (rev 5391) @@ -61,7 +61,7 @@ Traceback (most recent call last): SyntaxError: can't assign to operator (<doctest test.test_syntax[6]>, line 1) ->>> (x for x in x) = 1 +>>> (x for x in x) = 1 #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): SyntaxError: can't assign to generator expression (<doctest test.test_syntax[7]>, line 1) @@ -146,69 +146,71 @@ >>> f((x for x in L), 1) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ->>> f(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, -... i12, i13, i14, i15, i16, i17, i18, i19, i20, i21, i22, -... i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33, -... i34, i35, i36, i37, i38, i39, i40, i41, i42, i43, i44, -... i45, i46, i47, i48, i49, i50, i51, i52, i53, i54, i55, -... i56, i57, i58, i59, i60, i61, i62, i63, i64, i65, i66, -... i67, i68, i69, i70, i71, i72, i73, i74, i75, i76, i77, -... i78, i79, i80, i81, i82, i83, i84, i85, i86, i87, i88, -... i89, i90, i91, i92, i93, i94, i95, i96, i97, i98, i99, -... i100, i101, i102, i103, i104, i105, i106, i107, i108, -... i109, i110, i111, i112, i113, i114, i115, i116, i117, -... i118, i119, i120, i121, i122, i123, i124, i125, i126, -... i127, i128, i129, i130, i131, i132, i133, i134, i135, -... i136, i137, i138, i139, i140, i141, i142, i143, i144, -... i145, i146, i147, i148, i149, i150, i151, i152, i153, -... i154, i155, i156, i157, i158, i159, i160, i161, i162, -... i163, i164, i165, i166, i167, i168, i169, i170, i171, -... i172, i173, i174, i175, i176, i177, i178, i179, i180, -... i181, i182, i183, i184, i185, i186, i187, i188, i189, -... i190, i191, i192, i193, i194, i195, i196, i197, i198, -... i199, i200, i201, i202, i203, i204, i205, i206, i207, -... i208, i209, i210, i211, i212, i213, i214, i215, i216, -... i217, i218, i219, i220, i221, i222, i223, i224, i225, -... i226, i227, i228, i229, i230, i231, i232, i233, i234, -... i235, i236, i237, i238, i239, i240, i241, i242, i243, -... i244, i245, i246, i247, i248, i249, i250, i251, i252, -... i253, i254, i255) -Traceback (most recent call last): #doctest: +IGNORE_EXCEPTION_DETAIL -SyntaxError: more than 255 arguments (<doctest test.test_syntax[25]>, line 1) +### XXX: commented out -- jython lacks this limit -- should it have it? +#>>> f(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, +#... i12, i13, i14, i15, i16, i17, i18, i19, i20, i21, i22, +#... i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33, +#... i34, i35, i36, i37, i38, i39, i40, i41, i42, i43, i44, +#... i45, i46, i47, i48, i49, i50, i51, i52, i53, i54, i55, +#... i56, i57, i58, i59, i60, i61, i62, i63, i64, i65, i66, +#... i67, i68, i69, i70, i71, i72, i73, i74, i75, i76, i77, +#... i78, i79, i80, i81, i82, i83, i84, i85, i86, i87, i88, +#... i89, i90, i91, i92, i93, i94, i95, i96, i97, i98, i99, +#... i100, i101, i102, i103, i104, i105, i106, i107, i108, +#... i109, i110, i111, i112, i113, i114, i115, i116, i117, +#... i118, i119, i120, i121, i122, i123, i124, i125, i126, +#... i127, i128, i129, i130, i131, i132, i133, i134, i135, +#... i136, i137, i138, i139, i140, i141, i142, i143, i144, +#... i145, i146, i147, i148, i149, i150, i151, i152, i153, +#... i154, i155, i156, i157, i158, i159, i160, i161, i162, +#... i163, i164, i165, i166, i167, i168, i169, i170, i171, +#... i172, i173, i174, i175, i176, i177, i178, i179, i180, +#... i181, i182, i183, i184, i185, i186, i187, i188, i189, +#... i190, i191, i192, i193, i194, i195, i196, i197, i198, +#... i199, i200, i201, i202, i203, i204, i205, i206, i207, +#... i208, i209, i210, i211, i212, i213, i214, i215, i216, +#... i217, i218, i219, i220, i221, i222, i223, i224, i225, +#... i226, i227, i228, i229, i230, i231, i232, i233, i234, +#... i235, i236, i237, i238, i239, i240, i241, i242, i243, +#... i244, i245, i246, i247, i248, i249, i250, i251, i252, +#... i253, i254, i255) +#Traceback (most recent call last): +#SyntaxError: more than 255 arguments (<doctest test.test_syntax[25]>, line 1) The actual error cases counts positional arguments, keyword arguments, and generator expression arguments separately. This test combines the three. ->>> f(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, -... i12, i13, i14, i15, i16, i17, i18, i19, i20, i21, i22, -... i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33, -... i34, i35, i36, i37, i38, i39, i40, i41, i42, i43, i44, -... i45, i46, i47, i48, i49, i50, i51, i52, i53, i54, i55, -... i56, i57, i58, i59, i60, i61, i62, i63, i64, i65, i66, -... i67, i68, i69, i70, i71, i72, i73, i74, i75, i76, i77, -... i78, i79, i80, i81, i82, i83, i84, i85, i86, i87, i88, -... i89, i90, i91, i92, i93, i94, i95, i96, i97, i98, i99, -... i100, i101, i102, i103, i104, i105, i106, i107, i108, -... i109, i110, i111, i112, i113, i114, i115, i116, i117, -... i118, i119, i120, i121, i122, i123, i124, i125, i126, -... i127, i128, i129, i130, i131, i132, i133, i134, i135, -... i136, i137, i138, i139, i140, i141, i142, i143, i144, -... i145, i146, i147, i148, i149, i150, i151, i152, i153, -... i154, i155, i156, i157, i158, i159, i160, i161, i162, -... i163, i164, i165, i166, i167, i168, i169, i170, i171, -... i172, i173, i174, i175, i176, i177, i178, i179, i180, -... i181, i182, i183, i184, i185, i186, i187, i188, i189, -... i190, i191, i192, i193, i194, i195, i196, i197, i198, -... i199, i200, i201, i202, i203, i204, i205, i206, i207, -... i208, i209, i210, i211, i212, i213, i214, i215, i216, -... i217, i218, i219, i220, i221, i222, i223, i224, i225, -... i226, i227, i228, i229, i230, i231, i232, i233, i234, -... i235, i236, i237, i238, i239, i240, i241, i242, i243, -... (x for x in i244), i245, i246, i247, i248, i249, i250, i251, -... i252=1, i253=1, i254=1, i255=1) -Traceback (most recent call last): #doctest: +IGNORE_EXCEPTION_DETAIL -SyntaxError: more than 255 arguments (<doctest test.test_syntax[26]>, line 1) +### XXX: commented out -- jython lacks this limit -- should it have it? +#>>> f(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, +#... i12, i13, i14, i15, i16, i17, i18, i19, i20, i21, i22, +#... i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33, +#... i34, i35, i36, i37, i38, i39, i40, i41, i42, i43, i44, +#... i45, i46, i47, i48, i49, i50, i51, i52, i53, i54, i55, +#... i56, i57, i58, i59, i60, i61, i62, i63, i64, i65, i66, +#... i67, i68, i69, i70, i71, i72, i73, i74, i75, i76, i77, +#... i78, i79, i80, i81, i82, i83, i84, i85, i86, i87, i88, +#... i89, i90, i91, i92, i93, i94, i95, i96, i97, i98, i99, +#... i100, i101, i102, i103, i104, i105, i106, i107, i108, +#... i109, i110, i111, i112, i113, i114, i115, i116, i117, +#... i118, i119, i120, i121, i122, i123, i124, i125, i126, +#... i127, i128, i129, i130, i131, i132, i133, i134, i135, +#... i136, i137, i138, i139, i140, i141, i142, i143, i144, +#... i145, i146, i147, i148, i149, i150, i151, i152, i153, +#... i154, i155, i156, i157, i158, i159, i160, i161, i162, +#... i163, i164, i165, i166, i167, i168, i169, i170, i171, +#... i172, i173, i174, i175, i176, i177, i178, i179, i180, +#... i181, i182, i183, i184, i185, i186, i187, i188, i189, +#... i190, i191, i192, i193, i194, i195, i196, i197, i198, +#... i199, i200, i201, i202, i203, i204, i205, i206, i207, +#... i208, i209, i210, i211, i212, i213, i214, i215, i216, +#... i217, i218, i219, i220, i221, i222, i223, i224, i225, +#... i226, i227, i228, i229, i230, i231, i232, i233, i234, +#... i235, i236, i237, i238, i239, i240, i241, i242, i243, +#... (x for x in i244), i245, i246, i247, i248, i249, i250, i251, +#... i252=1, i253=1, i254=1, i255=1) +#Traceback (most recent call last): +#SyntaxError: more than 255 arguments (<doctest test.test_syntax[26]>, line 1) >>> f(lambda x: x[0] = 3) #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): @@ -453,10 +455,7 @@ self.fail("compile() did not raise SyntaxError") def test_assign_call(self): - if test_support.is_jython: - self._check_error("f() = 1") - else: - self._check_error("f() = 1", "assign") + self._check_error("f() = 1", "assign") def test_assign_del(self): self._check_error("del f()", "delete") Modified: trunk/jython/grammar/Python.g =================================================================== --- trunk/jython/grammar/Python.g 2008-10-14 03:20:10 UTC (rev 5390) +++ trunk/jython/grammar/Python.g 2008-10-14 16:43:46 UTC (rev 5391) @@ -110,7 +110,6 @@ import org.python.antlr.ast.expr_contextType; import org.python.antlr.ast.ExtSlice; import org.python.antlr.ast.For; -import org.python.antlr.ast.FunctionDef; import org.python.antlr.ast.GeneratorExp; import org.python.antlr.ast.Global; import org.python.antlr.ast.If; @@ -638,7 +637,7 @@ //del_stmt: 'del' exprlist del_stmt : DELETE del_list - -> ^(DELETE<Delete>[$DELETE, actions.castExprs($del_list.etypes)]) + -> ^(DELETE<Delete>[$DELETE, $del_list.etypes]) ; //pass_stmt: 'pass' @@ -1376,10 +1375,10 @@ //not in CPython's Grammar file //Needed as an exprlist that does not produce tuples for del_stmt. -del_list returns [List etypes] +del_list returns [exprType[\] etypes] : e+=expr[expr_contextType.Del] (options {k=2;}: COMMA e+=expr[expr_contextType.Del])* (COMMA)? { - $etypes = $e; + $etypes = actions.makeDeleteList($e); } ; Modified: trunk/jython/src/org/python/antlr/GrammarActions.java =================================================================== --- trunk/jython/src/org/python/antlr/GrammarActions.java 2008-10-14 03:20:10 UTC (rev 5390) +++ trunk/jython/src/org/python/antlr/GrammarActions.java 2008-10-14 16:43:46 UTC (rev 5391) @@ -327,12 +327,12 @@ if (snameToken == null) { s = null; } else { - s = snameToken.getText(); + s = cantBeNone(snameToken); } if (knameToken == null) { k = null; } else { - k = knameToken.getText(); + k = cantBeNone(knameToken); } return new argumentsType(t, p, s, k, d); } @@ -347,8 +347,12 @@ for(int i=0;i<args.size();i++) { exprType[] e = (exprType[])args.get(i); checkAssign(e[0]); - Name arg = (Name)e[0]; - k.add(new keywordType(arg, arg.id, e[1])); + if (e[0] instanceof Name) { + Name arg = (Name)e[0]; + k.add(new keywordType(arg, arg.id, e[1])); + } else { + errorHandler.error("keyword must be a name", e[0]); + } } return k.toArray(new keywordType[k.size()]); } @@ -495,26 +499,6 @@ return new ClassDef(t, nameToken.getText(), b, s); } - argumentsType makeArgumentsType(PythonTree t, List params, PythonTree snameToken, - PythonTree knameToken, List defaults) { - - exprType[] p = castExprs(params); - exprType[] d = castExprs(defaults); - String s; - String k; - if (snameToken == null) { - s = null; - } else { - s = snameToken.getText(); - } - if (knameToken == null) { - k = null; - } else { - k = knameToken.getText(); - } - return new argumentsType(t, p, s, k, d); - } - stmtType makeTryExcept(PythonTree t, List body, List handlers, List orelse, List finBody) { stmtType[] b = castStmts(body); excepthandlerType[] e = (excepthandlerType[])handlers.toArray(new excepthandlerType[handlers.size()]); @@ -632,27 +616,46 @@ errorHandler.error("can't assign to generator expression", e); } else if (e instanceof Num) { errorHandler.error("can't assign to number", e); + } else if (e instanceof Str) { + errorHandler.error("can't assign to string", e); } else if (e instanceof Yield) { errorHandler.error("can't assign to yield expression", e); } else if (e instanceof BinOp) { errorHandler.error("can't assign to operator", e); } else if (e instanceof Lambda) { errorHandler.error("can't assign to lambda", e); + } else if (e instanceof Call) { + errorHandler.error("can't assign to function call", e); + } else if (e instanceof Repr) { + errorHandler.error("can't assign to repr", e); + } else if (e instanceof IfExp) { + errorHandler.error("can't assign to conditional expression", e); } else if (e instanceof Tuple) { //XXX: performance problem? Any way to do this better? exprType[] elts = ((Tuple)e).elts; + if (elts.length == 0) { + errorHandler.error("can't assign to ()", e); + } for (int i=0;i<elts.length;i++) { checkAssign(elts[i]); } + } else if (e instanceof org.python.antlr.ast.List) { + //XXX: performance problem? Any way to do this better? + exprType[] elts = ((org.python.antlr.ast.List)e).elts; + for (int i=0;i<elts.length;i++) { + checkAssign(elts[i]); + } } } - void checkDelete(exprType[] exprs) { + exprType[] makeDeleteList(List e) { + exprType[] exprs = castExprs(e); for(int i=0;i<exprs.length;i++) { if (exprs[i] instanceof Call) { errorHandler.error("can't delete function call", exprs[i]); } } + return exprs; } sliceType makeSubscript(PythonTree lower, Token colon, PythonTree upper, PythonTree sliceop) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2008-10-14 03:20:21
|
Revision: 5390 http://jython.svn.sourceforge.net/jython/?rev=5390&view=rev Author: leosoto Date: 2008-10-14 03:20:10 +0000 (Tue, 14 Oct 2008) Log Message: ----------- Now String is mapped to PyUnicode on ClassicPyObjectAdapter (instead of mapping it to PyString). Thus, for APIs which really need to return bytestrings (such as PyFile) we now have to explicitely declare the return type as PyString (and on code written in Python, use StringUtil.asPyString(String)). Fixes #1128 Modified Paths: -------------- trunk/jython/Lib/javapath.py trunk/jython/Lib/os.py trunk/jython/Lib/zlib.py trunk/jython/src/com/ziclix/python/sql/DataHandler.java trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java trunk/jython/src/com/ziclix/python/sql/handler/MySQLDataHandler.java trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java trunk/jython/src/org/python/core/PyFile.java trunk/jython/src/org/python/core/PyFunction.java trunk/jython/src/org/python/core/PyStringMap.java trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/PyTraceback.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java trunk/jython/src/org/python/core/util/StringUtil.java trunk/jython/src/org/python/modules/binascii.java trunk/jython/src/org/python/modules/cPickle.java trunk/jython/src/org/python/modules/cStringIO.java trunk/jython/src/org/python/modules/struct.java trunk/jython/src/org/python/modules/time/Time.java Modified: trunk/jython/Lib/javapath.py =================================================================== --- trunk/jython/Lib/javapath.py 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/Lib/javapath.py 2008-10-14 03:20:10 UTC (rev 5390) @@ -20,7 +20,9 @@ from java.lang import System import os +from org.python.core.util.StringUtil import asPyString + def _tostr(s, method): if isinstance(s, basestring): return s @@ -40,7 +42,7 @@ def dirname(path): """Return the directory component of a pathname""" path = _tostr(path, "dirname") - result = File(path).getParent() + result = asPyString(File(path).getParent()) if not result: if isabs(path): result = path # Must be root @@ -51,7 +53,7 @@ def basename(path): """Return the final component of a pathname""" path = _tostr(path, "basename") - return File(path).getName() + return asPyString(File(path).getName()) def split(path): """Split a pathname. @@ -128,7 +130,7 @@ if a == "": a = os.sep f = File(f, a) - return f.getPath() + return asPyString(f.getPath()) def normcase(path): """Normalize case of pathname. @@ -137,7 +139,7 @@ """ path = _tostr(path, "normcase") - return File(path).getPath() + return asPyString(File(path).getPath()) def commonprefix(m): "Given a list of pathnames, return the longest common leading component" @@ -197,7 +199,7 @@ if not c: return gethome() if c == os.sep: - return File(gethome(), path[2:]).getPath() + return asPyString(File(gethome(), path[2:]).getPath()) return path def getuser(): @@ -252,7 +254,7 @@ def _abspath(path): # Must use normpath separately because getAbsolutePath doesn't normalize # and getCanonicalPath would eliminate symlinks. - return normpath(File(sys.getPath(path)).getAbsolutePath()) + return normpath(asPyString(File(sys.getPath(path)).getAbsolutePath())) def realpath(path): """Return an absolute path normalized and symbolic links eliminated""" @@ -261,7 +263,7 @@ def _realpath(path): try: - return File(sys.getPath(path)).getCanonicalPath() + return asPyString(File(sys.getPath(path)).getCanonicalPath()) except java.io.IOException: return _abspath(path) Modified: trunk/jython/Lib/os.py =================================================================== --- trunk/jython/Lib/os.py 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/Lib/os.py 2008-10-14 03:20:10 UTC (rev 5390) @@ -48,6 +48,7 @@ from java.io import File from org.python.core import PyFile from org.python.core.io import FileDescriptors, FileIO, IOBase +from org.python.core.util.StringUtil import asPyString # Mapping of: os._name: [name list, shell command list] _os_map = dict(nt=[ @@ -264,7 +265,7 @@ l = File(sys.getPath(path)).list() if l is None: raise OSError(0, 'No such directory', path) - return list(l) + return [asPyString(entry) for entry in l] def chmod(path, mode): """chmod(path, mode) @@ -629,7 +630,7 @@ from org.python.core.util import StringUtil rawio = FileDescriptors.get(fd) buf = _handle_oserror(rawio.read, buffersize) - return str(StringUtil.fromBytes(buf)) + return asPyString(StringUtil.fromBytes(buf)) def write(fd, string): """write(fd, string) -> byteswritten Modified: trunk/jython/Lib/zlib.py =================================================================== --- trunk/jython/Lib/zlib.py 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/Lib/zlib.py 2008-10-14 03:20:10 UTC (rev 5390) @@ -1,8 +1,10 @@ import jarray, binascii from java.util.zip import Adler32, Deflater, Inflater -from java.lang import Long, String, StringBuffer +from java.lang import Long, String +from cStringIO import StringIO + class error(Exception): pass @@ -132,18 +134,19 @@ def _get_deflate_data(deflater): buf = jarray.zeros(1024, 'b') - sb = StringBuffer() + s = StringIO() while not deflater.finished(): l = deflater.deflate(buf) if l == 0: break - sb.append(String(buf, 0, 0, l)) - return sb.toString() + s.write(String(buf, 0, 0, l)) + s.seek(0) + return s.read() def _get_inflate_data(inflater, max_length=0): buf = jarray.zeros(1024, 'b') - sb = StringBuffer() + s = StringIO() total = 0 while not inflater.finished(): if max_length: @@ -154,7 +157,8 @@ break total += l - sb.append(String(buf, 0, 0, l)) + s.write(String(buf, 0, 0, l)) if max_length and total == max_length: break - return sb.toString() + s.seek(0) + return s.read() Modified: trunk/jython/src/com/ziclix/python/sql/DataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/DataHandler.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/com/ziclix/python/sql/DataHandler.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -177,7 +177,7 @@ case Types.LONGVARCHAR: if (object instanceof PyFile) { - object = new PyString(((PyFile) object).read()); + object = ((PyFile) object).read(); } String varchar = (String) object.__tojava__(String.class); @@ -192,7 +192,7 @@ default : if (object instanceof PyFile) { - object = new PyString(((PyFile) object).read()); + object = ((PyFile) object).read(); } stmt.setObject(index, object.__tojava__(Object.class), type); Modified: trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/com/ziclix/python/sql/JDBC20DataHandler.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -62,7 +62,7 @@ case Types.CLOB: if (object instanceof PyFile) { - object = new PyString(((PyFile) object).read()); + object = ((PyFile) object).read(); } String clob = (String) object.__tojava__(String.class); Modified: trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/com/ziclix/python/sql/Jython22DataHandler.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -163,7 +163,7 @@ case Types.LONGVARCHAR: if (object instanceof PyFile) { - object = new PyString(((PyFile) object).read()); + object = ((PyFile) object).read(); } String varchar = (String) object.__tojava__(String.class); @@ -178,7 +178,7 @@ default : if (object instanceof PyFile) { - object = new PyString(((PyFile) object).read()); + object = ((PyFile) object).read(); } stmt.setObject(index, object.__tojava__(Object.class), type); Modified: trunk/jython/src/com/ziclix/python/sql/handler/MySQLDataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/handler/MySQLDataHandler.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/com/ziclix/python/sql/handler/MySQLDataHandler.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -54,17 +54,19 @@ switch (type) { case Types.LONGVARCHAR: - String varchar; + // XXX: Only works with ASCII data! + byte[] bytes; if (object instanceof PyFile) { - varchar = ((PyFile) object).read(); + bytes = ((PyFile) object).read().toBytes(); } else { - varchar = (String) object.__tojava__(String.class); + String varchar = (String) object.__tojava__(String.class); + bytes = StringUtil.toBytes(varchar); } - InputStream stream = new ByteArrayInputStream(StringUtil.toBytes(varchar)); + InputStream stream = new ByteArrayInputStream(bytes); stream = new BufferedInputStream(stream); - stmt.setAsciiStream(index, stream, varchar.length()); + stmt.setAsciiStream(index, stream, bytes.length); break; default : Modified: trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java =================================================================== --- trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -111,7 +111,7 @@ String varchar; // Postgresql driver can't handle the setCharacterStream() method so use setObject() instead if (object instanceof PyFile) { - varchar = ((PyFile) object).read(); + varchar = ((PyFile) object).read().asString(); } else { varchar = (String) object.__tojava__(String.class); } Modified: trunk/jython/src/org/python/core/PyFile.java =================================================================== --- trunk/jython/src/org/python/core/PyFile.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/PyFile.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -286,16 +286,16 @@ } @ExposedMethod(defaults = {"-1"}) - final synchronized String file_read(int n) { + final synchronized PyString file_read(int n) { checkClosed(); - return file.read(n); + return new PyString(file.read(n)); } - public String read(int n) { + public PyString read(int n) { return file_read(n); } - public String read() { + public PyString read() { return file_read(-1); } @@ -310,16 +310,16 @@ } @ExposedMethod(defaults = {"-1"}) - final synchronized String file_readline(int max) { + final synchronized PyString file_readline(int max) { checkClosed(); - return file.readline(max); + return new PyString(file.readline(max)); } - public String readline(int max) { + public PyString readline(int max) { return file_readline(max); } - public String readline() { + public PyString readline() { return file_readline(-1); } Modified: trunk/jython/src/org/python/core/PyFunction.java =================================================================== --- trunk/jython/src/org/python/core/PyFunction.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/PyFunction.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -143,13 +143,13 @@ } @ExposedGet(name = "func_name") - public String getFuncName() { - return __name__; + public PyString getFuncName() { + return new PyString(__name__); } @ExposedSet(name = "func_name") - public void setFuncName(String func_name) { - __name__ = func_name; + public void setFuncName(PyString func_name) { + __name__ = func_name.asString(); } @ExposedGet(name = "func_doc") Modified: trunk/jython/src/org/python/core/PyStringMap.java =================================================================== --- trunk/jython/src/org/python/core/PyStringMap.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/PyStringMap.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -141,7 +141,9 @@ for (Entry<Object, PyObject> entry : table.entrySet()) { Object key = entry.getKey(); if (key instanceof String) { - buf.append(Py.java2py(key).__repr__().toString()); + // This is a bit complicated, but prevents us to duplicate + // PyString#__repr__ logic here. + buf.append(new PyString((String)key).__repr__().toString()); } else { buf.append(((PyObject)key).__repr__().toString()); } Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/PySystemState.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -41,7 +41,7 @@ private static final String JAR_URL_PREFIX = "jar:file:"; private static final String JAR_SEPARATOR = "!"; - public static String version = Version.getVersion(); + public static PyString version = new PyString(Version.getVersion()); public static int hexversion = ((Version.PY_MAJOR_VERSION << 24) | (Version.PY_MINOR_VERSION << 16) | (Version.PY_MICRO_VERSION << 8) | @@ -101,8 +101,8 @@ public PyList path_hooks; public PyObject path_importer_cache; - public static String platform = "java"; - public static String byteorder = "big"; + public static PyString platform = new PyString("java"); + public static PyString byteorder = new PyString("big"); public PyObject ps1 = new PyString(">>> "); public PyObject ps2 = new PyString("... "); @@ -288,8 +288,8 @@ } } - public String getdefaultencoding() { - return codecs.getDefaultEncoding(); + public PyString getdefaultencoding() { + return new PyString(codecs.getDefaultEncoding()); } public void setdefaultencoding(String encoding) { @@ -431,7 +431,7 @@ if (version.equals("12")) { version = "1.2"; } - platform = "java" + version; + platform = new PyString("java" + version); } private static void initRegistry(Properties preProperties, Properties postProperties, Modified: trunk/jython/src/org/python/core/PyTraceback.java =================================================================== --- trunk/jython/src/org/python/core/PyTraceback.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/PyTraceback.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -62,11 +62,12 @@ return null; } + String line = null; int i = 0; try { for (i = 0; i < tb_lineno; i++) { - line = pyFile.readline(); + line = pyFile.readline().asString(); if (line.equals("")) { break; } Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -1028,7 +1028,7 @@ private static PyString readline(PyObject file) { if (file instanceof PyFile) { - return new PyString(((PyFile) file).readline()); + return ((PyFile) file).readline(); } else { PyObject ret = file.invoke("readline"); if (!(ret instanceof PyString)) { Modified: trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java =================================================================== --- trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/adapter/ClassicPyObjectAdapter.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -9,8 +9,8 @@ import org.python.core.PyLong; import org.python.core.PyObject; import org.python.core.PyProxy; -import org.python.core.PyString; import org.python.core.PyType; +import org.python.core.PyUnicode; /** * Implements the algorithm originally used in {@link Py#java2py} to adapt objects. @@ -60,7 +60,7 @@ add(new ClassAdapter(String.class) { public PyObject adapt(Object o) { - return new PyString((String) o); + return new PyUnicode((String) o); } }); Modified: trunk/jython/src/org/python/core/util/StringUtil.java =================================================================== --- trunk/jython/src/org/python/core/util/StringUtil.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/core/util/StringUtil.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -5,6 +5,7 @@ import java.nio.ByteBuffer; import org.python.core.Py; +import org.python.core.PyString; /** * String Utility methods. @@ -83,4 +84,8 @@ chars[0] = Character.toLowerCase(c0); return new String(chars); } + + public static PyString asPyString(String string) { + return new PyString(string); } +} Modified: trunk/jython/src/org/python/modules/binascii.java =================================================================== --- trunk/jython/src/org/python/modules/binascii.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/modules/binascii.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -272,12 +272,12 @@ * binary data. Lines normally contain 45 (binary) bytes, except for the * last line. Line data may be followed by whitespace. */ - public static String a2b_uu(String ascii_data) { + public static PyString a2b_uu(String ascii_data) { int leftbits = 0; int leftchar = 0; if (ascii_data.length() == 0) - return ""; + return new PyString(""); StringBuffer bin_data = new StringBuffer(); @@ -331,7 +331,7 @@ for (; i<bin_len; i++) bin_data.append((char)0); - return bin_data.toString(); + return new PyString(bin_data.toString()); } @@ -346,7 +346,7 @@ * is the converted line, including a newline char. The length of * <i>data</i> should be at most 45. */ - public static String b2a_uu(String bin_data) { + public static PyString b2a_uu(String bin_data) { int leftbits = 0; char this_ch; int leftchar = 0; @@ -379,7 +379,7 @@ } ascii_data.append('\n'); // Append a courtesy newline - return ascii_data.toString(); + return new PyString(ascii_data.toString()); } @@ -417,7 +417,7 @@ * Convert a block of base64 data back to binary and return the * binary data. More than one line may be passed at a time. */ - public static String a2b_base64(String ascii_data) { + public static PyString a2b_base64(String ascii_data) { int leftbits = 0; char this_ch; int leftchar = 0; @@ -468,7 +468,7 @@ if (leftbits != 0) { throw new PyException(Error, "Incorrect padding"); } - return bin_data.toString(); + return new PyString(bin_data.toString()); } @@ -482,7 +482,7 @@ * Convert binary data to a line of ASCII characters in base64 coding. * The return value is the converted line, including a newline char. */ - public static String b2a_base64(String bin_data) { + public static PyString b2a_base64(String bin_data) { int leftbits = 0; char this_ch; int leftchar = 0; @@ -516,7 +516,7 @@ } ascii_data.append('\n'); // Append a courtesy newline - return ascii_data.toString(); + return new PyString(ascii_data.toString()); } @@ -625,7 +625,7 @@ * resulting string. The argument should already be RLE-coded, and have a * length divisible by 3 (except possibly the last fragment). */ - public static String b2a_hqx(String bin_data) { + public static PyString b2a_hqx(String bin_data) { int leftbits = 0; char this_ch; int leftchar = 0; @@ -649,7 +649,7 @@ leftchar <<= (6-leftbits); ascii_data.append((char) table_b2a_hqx[leftchar & 0x3f]); } - return ascii_data.toString(); + return new PyString(ascii_data.toString()); } @@ -834,7 +834,7 @@ "This function is also available as \"hexlify()\"." ); - public static String b2a_hex(String argbuf) { + public static PyString b2a_hex(String argbuf) { int arglen = argbuf.length(); StringBuffer retbuf = new StringBuffer(arglen*2); @@ -845,12 +845,12 @@ retbuf.append(hexdigit[(ch >>> 4) & 0xF]); retbuf.append(hexdigit[ch & 0xF]); } - return retbuf.toString(); + return new PyString(retbuf.toString()); } - public static String hexlify(String argbuf) { + public static PyString hexlify(String argbuf) { return b2a_hex(argbuf); } @@ -864,7 +864,7 @@ ); - public static String a2b_hex(String argbuf) { + public static PyString a2b_hex(String argbuf) { int arglen = argbuf.length(); /* XXX What should we do about strings with an odd length? Should @@ -883,11 +883,11 @@ throw Py.TypeError("Non-hexadecimal digit found"); retbuf.append((char) ((top << 4) + bot)); } - return retbuf.toString(); + return new PyString(retbuf.toString()); } - public static String unhexlify(String argbuf) { + public static PyString unhexlify(String argbuf) { return a2b_hex(argbuf); } @@ -917,7 +917,7 @@ return val; } - public static String a2b_qp(PyObject[] arg, String[] kws) + public static PyString a2b_qp(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("a2b_qp", arg, kws, new String[] {"s", "header"}); String s = ap.getString(0); @@ -951,8 +951,7 @@ sb.append(c); } } - - return sb.toString(); + return new PyString(sb.toString()); } final private static Pattern RN_TO_N = Pattern.compile("\r\n"); @@ -964,7 +963,7 @@ + "space at end of lines is. When istext is not set, \r and \n (CR/LF) are\n" + "both encoded. When quotetabs is set, space and tabs are encoded."); - public static String b2a_qp(PyObject[] arg, String[] kws) { + public static PyString b2a_qp(PyObject[] arg, String[] kws) { ArgParser ap = new ArgParser("b2a_qp", arg, kws, new String[] {"s", "quotetabs", "istext", "header"}); String s = ap.getString(0); boolean quotetabs = getIntFlagAsBool(ap, 1, 0, "an integer is required"); @@ -1034,7 +1033,7 @@ qpEscape(sb, c); } } - return sb.toString(); + return new PyString(sb.toString()); } private static boolean endOfLine(String s, String lineEnd, int i) { Modified: trunk/jython/src/org/python/modules/cPickle.java =================================================================== --- trunk/jython/src/org/python/modules/cPickle.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/modules/cPickle.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -614,7 +614,7 @@ * @param object a data object which should be pickled. * @returns a string representing the pickled object. */ - public static String dumps(PyObject object) { + public static PyString dumps(PyObject object) { return dumps(object, 0); } @@ -625,7 +625,7 @@ * @param protocol pickle protocol version (0 - text, 1 - pre-2.3 binary, 2 - 2.3) * @returns a string representing the pickled object. */ - public static String dumps(PyObject object, int protocol) { + public static PyString dumps(PyObject object, int protocol) { cStringIO.StringIO file = cStringIO.StringIO(); dump(object, file, protocol); return file.getvalue(); @@ -705,11 +705,11 @@ public void flush() {} public String read(int len) { - return file.read(len); + return file.read(len).asString(); } public String readlineNoNl() { - return file.readlineNoNl(); + return file.readlineNoNl().asString(); } } Modified: trunk/jython/src/org/python/modules/cStringIO.java =================================================================== --- trunk/jython/src/org/python/modules/cStringIO.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/modules/cStringIO.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -99,10 +99,10 @@ public PyObject __iternext__() { _complain_ifclosed(); - String r = readline(); - if(r.equals("")) + PyString r = readline(); + if (r.__len__() == 0) return null; - return new PyString(r); + return r; } /** @@ -176,7 +176,7 @@ * An empty string is returned when EOF is encountered immediately. * @returns A string containing the data. */ - public String read() { + public PyString read() { return read(-1); } @@ -190,7 +190,7 @@ * @returns A string containing the data read. */ - public synchronized String read(long size) { + public synchronized PyString read(long size) { _complain_ifclosed(); int size_int = _convert_to_int(size); int len = buf.length(); @@ -204,10 +204,9 @@ substr = buf.substring(pos, newpos); pos = newpos; } - return substr; + return new PyString(substr); } - /** * Read one entire line from the file. A trailing newline character * is kept in the string (but may be absent when a file ends with @@ -215,7 +214,7 @@ * An empty string is returned when EOF is hit immediately. * @returns data from the file up to and including the newline. */ - public String readline() { + public PyString readline() { return readline(-1); } @@ -229,12 +228,12 @@ * returned. * @returns data from the file up to and including the newline. */ - public synchronized String readline(long size) { + public synchronized PyString readline(long size) { _complain_ifclosed(); int size_int = _convert_to_int(size); int len = buf.length(); if (pos == len) { - return ""; + return new PyString(""); } int i = buf.indexOf("\n", pos); int newpos = (i < 0) ? len : i + 1; @@ -243,7 +242,7 @@ } String r = buf.substring(pos, newpos); pos = newpos; - return r; + return new PyString(r); } @@ -251,7 +250,7 @@ * Read and return a line without the trailing newline. * Usind by cPickle as an optimization. */ - public synchronized String readlineNoNl() { + public synchronized PyString readlineNoNl() { _complain_ifclosed(); int len = buf.length(); int i = buf.indexOf("\n", pos); @@ -260,7 +259,7 @@ pos = newpos; if (pos < len) // Skip the newline pos++; - return r; + return new PyString(r); } @@ -286,10 +285,10 @@ int sizehint_int = (int)sizehint; int total = 0; PyList lines = new PyList(); - String line = readline(); - while (line.length() > 0) { - lines.append(new PyString(line)); - total += line.length(); + PyString line = readline(); + while (line.__len__() > 0) { + lines.append(line); + total += line.__len__(); if (0 < sizehint_int && sizehint_int <= total) break; line = readline(); @@ -367,8 +366,8 @@ * before the StringIO object's close() method is called. * @return the contents of the StringIO. */ - public synchronized String getvalue() { - return buf.toString(); + public synchronized PyString getvalue() { + return new PyString(buf.toString()); } } Modified: trunk/jython/src/org/python/modules/struct.java =================================================================== --- trunk/jython/src/org/python/modules/struct.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/modules/struct.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -978,7 +978,7 @@ * to the given format. The arguments must match the * values required by the format exactly. */ - static public String pack(PyObject[] args) { + static public PyString pack(PyObject[] args) { if (args.length < 1) Py.TypeError("illegal argument type for built-in operation"); @@ -987,7 +987,7 @@ FormatDef[] f = whichtable(format); int size = calcsize(format, f); - return pack(format, f, size, 1, args).toString(); + return new PyString(pack(format, f, size, 1, args).toString()); } // xxx - may need to consider doing a generic arg parser here Modified: trunk/jython/src/org/python/modules/time/Time.java =================================================================== --- trunk/jython/src/org/python/modules/time/Time.java 2008-10-14 01:47:30 UTC (rev 5389) +++ trunk/jython/src/org/python/modules/time/Time.java 2008-10-14 03:20:10 UTC (rev 5390) @@ -308,11 +308,11 @@ return _timefields(parseTimeDoubleArg(arg), TimeZone.getTimeZone("GMT")); } - public static String ctime() { + public static PyString ctime() { return ctime(Py.None); } - public static String ctime(PyObject secs) { + public static PyString ctime(PyObject secs) { return asctime(localtime(secs)); } @@ -405,11 +405,11 @@ return yearstr.substring(yearstr.length()-2, yearstr.length()); } - public static String asctime() { + public static PyString asctime() { return asctime(localtime()); } - public static String asctime(PyTuple tup) { + public static PyString asctime(PyTuple tup) { StringBuffer buf = new StringBuffer(25); buf.append(enshortdays[item(tup, 6)]).append(' '); buf.append(enshortmonths[item(tup, 1)]).append(' '); @@ -421,7 +421,7 @@ buf.append(_twodigit(item(tup, 3))).append(':'); buf.append(_twodigit(item(tup, 4))).append(':'); buf.append(_twodigit(item(tup, 5))).append(' '); - return buf.append(item(tup, 0)).toString(); + return new PyString(buf.append(item(tup, 0)).toString()); } public static String locale_asctime(PyTuple tup) { @@ -454,11 +454,11 @@ // writable but ignore its value? public static final int accept2dyear = 0; - public static String strftime(String format) { + public static PyString strftime(String format) { return strftime(format, localtime()); } - public static String strftime(String format, PyTuple tup) { + public static PyString strftime(String format, PyTuple tup) { checkLocale(); // Immediately validate the tuple @@ -651,7 +651,18 @@ lastc = i+1; i++; } - return s; + // FIXME: This have problems with localized data: + // $ LANG=es_ES.UTF-8 jythont -c "import time; print time.strftime('%A')" + // s?bado + // + // On the other hand, returning unicode would break some doctests + // and will give problems when the return value of strftime is + // mixed with other strings and then the final result is stored + // on places which only support str and not unicode (such as + // os.environ) + // + // TODO: Check how CPython deals with this problem. + return new PyString(s); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cg...@us...> - 2008-10-14 01:47:36
|
Revision: 5389 http://jython.svn.sourceforge.net/jython/?rev=5389&view=rev Author: cgroves Date: 2008-10-14 01:47:30 +0000 (Tue, 14 Oct 2008) Log Message: ----------- Jarjar if antlr changed more recently than the jarjar'd jar. Jar. Modified Paths: -------------- trunk/jython/build.xml Modified: trunk/jython/build.xml =================================================================== --- trunk/jython/build.xml 2008-10-13 20:38:36 UTC (rev 5388) +++ trunk/jython/build.xml 2008-10-14 01:47:30 UTC (rev 5389) @@ -111,6 +111,7 @@ <target name="needed-check" unless="full-build"> <uptodate property="jarjar.notneeded" targetfile="${output.dir}/jarjar.jar"> <srcfiles dir="extlibs" includes="*" /> + <srcfiles dir="grammar" includes="*.g" /> </uptodate> <uptodate property="antlr.notneeded" targetfile="${dist.dir}/jython.jar"> <srcfiles dir="grammar" includes="*.g" /> @@ -316,14 +317,10 @@ want to comment this out, as a clean is really only needed if you change the tokens defined in Python.g (and cleans make the build slow) --> <antcall target="clean"/> - <!-- force jarjar build --> - <property name="jarjar.needed" value="true" /> </target> - - <target name ="prepare-output" depends="init,needed-check,clean-if-antlr-needed,make-output-dirs"/> - + <!-- create output directories --> - <target name ="make-output-dirs" depends="init"> + <target name ="prepare-output" depends="init,needed-check,clean-if-antlr-needed"> <mkdir dir="${compile.dir}" /> <mkdir dir="${jarjar.dir}" /> <mkdir dir="${gensrc.dir}/org/python/antlr" /> @@ -506,10 +503,7 @@ includesfile="${jython.base.dir}/CoreExposed.includes"/> </target> - <!-- XXX: this should be conditional if="jarjar.needed" or unless="jarjar.notneeded" - but I haven't been able to get this to work. For now always do jarjar - --> - <target name="jarjar" depends="init,needed-check"> + <target name="jarjar" depends="init,needed-check" unless="jarjar.notneeded"> <taskdef name="jarjar" classname="com.tonicsystems.jarjar.JarJarTask" classpath="extlibs/jarjar-0.7.jar"/> <jarjar destfile="${output.dir}/jarjar.jar"> <zipfileset src="extlibs/antlr-runtime-3.1.jar"/> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-13 20:38:42
|
Revision: 5388 http://jython.svn.sourceforge.net/jython/?rev=5388&view=rev Author: fwierzbicki Date: 2008-10-13 20:38:36 +0000 (Mon, 13 Oct 2008) Log Message: ----------- Disabling tests of "as" and "with" semi-keyword status, for now it's too hard to get antlr to treat them as almost-keywords. I want to revisit, but this is a low priority compared to other problems. Modified Paths: -------------- trunk/jython/Lib/test/test_with.py Modified: trunk/jython/Lib/test/test_with.py =================================================================== --- trunk/jython/Lib/test/test_with.py 2008-10-13 19:41:45 UTC (rev 5387) +++ trunk/jython/Lib/test/test_with.py 2008-10-13 20:38:36 UTC (rev 5388) @@ -663,7 +663,15 @@ NonLocalFlowControlTestCase, AssignmentTargetTestCase, ExitSwallowsExceptionTestCase, - NewKeywordsWarningTestCase) + ) + #XXX: punting NewKeywordsWarningTestCase at least for the + # short term making "with" and "as" anything but true + # keywords is not easy with the antlr parser though it is + # probably doable. Just not a high priority compared to + # other problems and in 2.6+ it is a non-problem since + # these become true keywords in CPython. + # + #NewKeywordsWarningTestCase) if __name__ == '__main__': This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-13 19:41:52
|
Revision: 5387 http://jython.svn.sourceforge.net/jython/?rev=5387&view=rev Author: fwierzbicki Date: 2008-10-13 19:41:45 +0000 (Mon, 13 Oct 2008) Log Message: ----------- from http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_with.py@66619 Added Paths: ----------- trunk/jython/Lib/test/test_with.py Added: trunk/jython/Lib/test/test_with.py =================================================================== --- trunk/jython/Lib/test/test_with.py (rev 0) +++ trunk/jython/Lib/test/test_with.py 2008-10-13 19:41:45 UTC (rev 5387) @@ -0,0 +1,670 @@ +#!/usr/bin/env python + +"""Unit tests for the with statement specified in PEP 343.""" + +from __future__ import with_statement + +__author__ = "Mike Bland" +__email__ = "mbland at acm dot org" + +import sys +import unittest +import StringIO +from collections import deque +from contextlib import GeneratorContextManager, contextmanager +from test.test_support import run_unittest + + +class MockContextManager(GeneratorContextManager): + def __init__(self, gen): + GeneratorContextManager.__init__(self, gen) + self.enter_called = False + self.exit_called = False + self.exit_args = None + + def __enter__(self): + self.enter_called = True + return GeneratorContextManager.__enter__(self) + + def __exit__(self, type, value, traceback): + self.exit_called = True + self.exit_args = (type, value, traceback) + return GeneratorContextManager.__exit__(self, type, + value, traceback) + + +def mock_contextmanager(func): + def helper(*args, **kwds): + return MockContextManager(func(*args, **kwds)) + return helper + + +class MockResource(object): + def __init__(self): + self.yielded = False + self.stopped = False + + +@mock_contextmanager +def mock_contextmanager_generator(): + mock = MockResource() + try: + mock.yielded = True + yield mock + finally: + mock.stopped = True + + +class Nested(object): + + def __init__(self, *managers): + self.managers = managers + self.entered = None + + def __enter__(self): + if self.entered is not None: + raise RuntimeError("Context is not reentrant") + self.entered = deque() + vars = [] + try: + for mgr in self.managers: + vars.append(mgr.__enter__()) + self.entered.appendleft(mgr) + except: + if not self.__exit__(*sys.exc_info()): + raise + return vars + + def __exit__(self, *exc_info): + # Behave like nested with statements + # first in, last out + # New exceptions override old ones + ex = exc_info + for mgr in self.entered: + try: + if mgr.__exit__(*ex): + ex = (None, None, None) + except: + ex = sys.exc_info() + self.entered = None + if ex is not exc_info: + raise ex[0], ex[1], ex[2] + + +class MockNested(Nested): + def __init__(self, *managers): + Nested.__init__(self, *managers) + self.enter_called = False + self.exit_called = False + self.exit_args = None + + def __enter__(self): + self.enter_called = True + return Nested.__enter__(self) + + def __exit__(self, *exc_info): + self.exit_called = True + self.exit_args = exc_info + return Nested.__exit__(self, *exc_info) + + +class FailureTestCase(unittest.TestCase): + def testNameError(self): + def fooNotDeclared(): + with foo: pass + self.assertRaises(NameError, fooNotDeclared) + + def testEnterAttributeError(self): + class LacksEnter(object): + def __exit__(self, type, value, traceback): + pass + + def fooLacksEnter(): + foo = LacksEnter() + with foo: pass + self.assertRaises(AttributeError, fooLacksEnter) + + def testExitAttributeError(self): + class LacksExit(object): + def __enter__(self): + pass + + def fooLacksExit(): + foo = LacksExit() + with foo: pass + self.assertRaises(AttributeError, fooLacksExit) + + def assertRaisesSyntaxError(self, codestr): + def shouldRaiseSyntaxError(s): + compile(s, '', 'single') + self.assertRaises(SyntaxError, shouldRaiseSyntaxError, codestr) + + def testAssignmentToNoneError(self): + self.assertRaisesSyntaxError('with mock as None:\n pass') + self.assertRaisesSyntaxError( + 'with mock as (None):\n' + ' pass') + + def testAssignmentToEmptyTupleError(self): + self.assertRaisesSyntaxError( + 'with mock as ():\n' + ' pass') + + def testAssignmentToTupleOnlyContainingNoneError(self): + self.assertRaisesSyntaxError('with mock as None,:\n pass') + self.assertRaisesSyntaxError( + 'with mock as (None,):\n' + ' pass') + + def testAssignmentToTupleContainingNoneError(self): + self.assertRaisesSyntaxError( + 'with mock as (foo, None, bar):\n' + ' pass') + + def testEnterThrows(self): + class EnterThrows(object): + def __enter__(self): + raise RuntimeError("Enter threw") + def __exit__(self, *args): + pass + + def shouldThrow(): + ct = EnterThrows() + self.foo = None + with ct as self.foo: + pass + self.assertRaises(RuntimeError, shouldThrow) + self.assertEqual(self.foo, None) + + def testExitThrows(self): + class ExitThrows(object): + def __enter__(self): + return + def __exit__(self, *args): + raise RuntimeError(42) + def shouldThrow(): + with ExitThrows(): + pass + self.assertRaises(RuntimeError, shouldThrow) + +class ContextmanagerAssertionMixin(object): + TEST_EXCEPTION = RuntimeError("test exception") + + def assertInWithManagerInvariants(self, mock_manager): + self.assertTrue(mock_manager.enter_called) + self.assertFalse(mock_manager.exit_called) + self.assertEqual(mock_manager.exit_args, None) + + def assertAfterWithManagerInvariants(self, mock_manager, exit_args): + self.assertTrue(mock_manager.enter_called) + self.assertTrue(mock_manager.exit_called) + self.assertEqual(mock_manager.exit_args, exit_args) + + def assertAfterWithManagerInvariantsNoError(self, mock_manager): + self.assertAfterWithManagerInvariants(mock_manager, + (None, None, None)) + + def assertInWithGeneratorInvariants(self, mock_generator): + self.assertTrue(mock_generator.yielded) + self.assertFalse(mock_generator.stopped) + + def assertAfterWithGeneratorInvariantsNoError(self, mock_generator): + self.assertTrue(mock_generator.yielded) + self.assertTrue(mock_generator.stopped) + + def raiseTestException(self): + raise self.TEST_EXCEPTION + + def assertAfterWithManagerInvariantsWithError(self, mock_manager): + self.assertTrue(mock_manager.enter_called) + self.assertTrue(mock_manager.exit_called) + self.assertEqual(mock_manager.exit_args[0], RuntimeError) + self.assertEqual(mock_manager.exit_args[1], self.TEST_EXCEPTION) + + def assertAfterWithGeneratorInvariantsWithError(self, mock_generator): + self.assertTrue(mock_generator.yielded) + self.assertTrue(mock_generator.stopped) + + +class NonexceptionalTestCase(unittest.TestCase, ContextmanagerAssertionMixin): + def testInlineGeneratorSyntax(self): + with mock_contextmanager_generator(): + pass + + def testUnboundGenerator(self): + mock = mock_contextmanager_generator() + with mock: + pass + self.assertAfterWithManagerInvariantsNoError(mock) + + def testInlineGeneratorBoundSyntax(self): + with mock_contextmanager_generator() as foo: + self.assertInWithGeneratorInvariants(foo) + # FIXME: In the future, we'll try to keep the bound names from leaking + self.assertAfterWithGeneratorInvariantsNoError(foo) + + def testInlineGeneratorBoundToExistingVariable(self): + foo = None + with mock_contextmanager_generator() as foo: + self.assertInWithGeneratorInvariants(foo) + self.assertAfterWithGeneratorInvariantsNoError(foo) + + def testInlineGeneratorBoundToDottedVariable(self): + with mock_contextmanager_generator() as self.foo: + self.assertInWithGeneratorInvariants(self.foo) + self.assertAfterWithGeneratorInvariantsNoError(self.foo) + + def testBoundGenerator(self): + mock = mock_contextmanager_generator() + with mock as foo: + self.assertInWithGeneratorInvariants(foo) + self.assertInWithManagerInvariants(mock) + self.assertAfterWithGeneratorInvariantsNoError(foo) + self.assertAfterWithManagerInvariantsNoError(mock) + + def testNestedSingleStatements(self): + mock_a = mock_contextmanager_generator() + with mock_a as foo: + mock_b = mock_contextmanager_generator() + with mock_b as bar: + self.assertInWithManagerInvariants(mock_a) + self.assertInWithManagerInvariants(mock_b) + self.assertInWithGeneratorInvariants(foo) + self.assertInWithGeneratorInvariants(bar) + self.assertAfterWithManagerInvariantsNoError(mock_b) + self.assertAfterWithGeneratorInvariantsNoError(bar) + self.assertInWithManagerInvariants(mock_a) + self.assertInWithGeneratorInvariants(foo) + self.assertAfterWithManagerInvariantsNoError(mock_a) + self.assertAfterWithGeneratorInvariantsNoError(foo) + + +class NestedNonexceptionalTestCase(unittest.TestCase, + ContextmanagerAssertionMixin): + def testSingleArgInlineGeneratorSyntax(self): + with Nested(mock_contextmanager_generator()): + pass + + def testSingleArgUnbound(self): + mock_contextmanager = mock_contextmanager_generator() + mock_nested = MockNested(mock_contextmanager) + with mock_nested: + self.assertInWithManagerInvariants(mock_contextmanager) + self.assertInWithManagerInvariants(mock_nested) + self.assertAfterWithManagerInvariantsNoError(mock_contextmanager) + self.assertAfterWithManagerInvariantsNoError(mock_nested) + + def testSingleArgBoundToNonTuple(self): + m = mock_contextmanager_generator() + # This will bind all the arguments to nested() into a single list + # assigned to foo. + with Nested(m) as foo: + self.assertInWithManagerInvariants(m) + self.assertAfterWithManagerInvariantsNoError(m) + + def testSingleArgBoundToSingleElementParenthesizedList(self): + m = mock_contextmanager_generator() + # This will bind all the arguments to nested() into a single list + # assigned to foo. + with Nested(m) as (foo): + self.assertInWithManagerInvariants(m) + self.assertAfterWithManagerInvariantsNoError(m) + + def testSingleArgBoundToMultipleElementTupleError(self): + def shouldThrowValueError(): + with Nested(mock_contextmanager_generator()) as (foo, bar): + pass + self.assertRaises(ValueError, shouldThrowValueError) + + def testSingleArgUnbound(self): + mock_contextmanager = mock_contextmanager_generator() + mock_nested = MockNested(mock_contextmanager) + with mock_nested: + self.assertInWithManagerInvariants(mock_contextmanager) + self.assertInWithManagerInvariants(mock_nested) + self.assertAfterWithManagerInvariantsNoError(mock_contextmanager) + self.assertAfterWithManagerInvariantsNoError(mock_nested) + + def testMultipleArgUnbound(self): + m = mock_contextmanager_generator() + n = mock_contextmanager_generator() + o = mock_contextmanager_generator() + mock_nested = MockNested(m, n, o) + with mock_nested: + self.assertInWithManagerInvariants(m) + self.assertInWithManagerInvariants(n) + self.assertInWithManagerInvariants(o) + self.assertInWithManagerInvariants(mock_nested) + self.assertAfterWithManagerInvariantsNoError(m) + self.assertAfterWithManagerInvariantsNoError(n) + self.assertAfterWithManagerInvariantsNoError(o) + self.assertAfterWithManagerInvariantsNoError(mock_nested) + + def testMultipleArgBound(self): + mock_nested = MockNested(mock_contextmanager_generator(), + mock_contextmanager_generator(), mock_contextmanager_generator()) + with mock_nested as (m, n, o): + self.assertInWithGeneratorInvariants(m) + self.assertInWithGeneratorInvariants(n) + self.assertInWithGeneratorInvariants(o) + self.assertInWithManagerInvariants(mock_nested) + self.assertAfterWithGeneratorInvariantsNoError(m) + self.assertAfterWithGeneratorInvariantsNoError(n) + self.assertAfterWithGeneratorInvariantsNoError(o) + self.assertAfterWithManagerInvariantsNoError(mock_nested) + + +class ExceptionalTestCase(unittest.TestCase, ContextmanagerAssertionMixin): + def testSingleResource(self): + cm = mock_contextmanager_generator() + def shouldThrow(): + with cm as self.resource: + self.assertInWithManagerInvariants(cm) + self.assertInWithGeneratorInvariants(self.resource) + self.raiseTestException() + self.assertRaises(RuntimeError, shouldThrow) + self.assertAfterWithManagerInvariantsWithError(cm) + self.assertAfterWithGeneratorInvariantsWithError(self.resource) + + def testNestedSingleStatements(self): + mock_a = mock_contextmanager_generator() + mock_b = mock_contextmanager_generator() + def shouldThrow(): + with mock_a as self.foo: + with mock_b as self.bar: + self.assertInWithManagerInvariants(mock_a) + self.assertInWithManagerInvariants(mock_b) + self.assertInWithGeneratorInvariants(self.foo) + self.assertInWithGeneratorInvariants(self.bar) + self.raiseTestException() + self.assertRaises(RuntimeError, shouldThrow) + self.assertAfterWithManagerInvariantsWithError(mock_a) + self.assertAfterWithManagerInvariantsWithError(mock_b) + self.assertAfterWithGeneratorInvariantsWithError(self.foo) + self.assertAfterWithGeneratorInvariantsWithError(self.bar) + + def testMultipleResourcesInSingleStatement(self): + cm_a = mock_contextmanager_generator() + cm_b = mock_contextmanager_generator() + mock_nested = MockNested(cm_a, cm_b) + def shouldThrow(): + with mock_nested as (self.resource_a, self.resource_b): + self.assertInWithManagerInvariants(cm_a) + self.assertInWithManagerInvariants(cm_b) + self.assertInWithManagerInvariants(mock_nested) + self.assertInWithGeneratorInvariants(self.resource_a) + self.assertInWithGeneratorInvariants(self.resource_b) + self.raiseTestException() + self.assertRaises(RuntimeError, shouldThrow) + self.assertAfterWithManagerInvariantsWithError(cm_a) + self.assertAfterWithManagerInvariantsWithError(cm_b) + self.assertAfterWithManagerInvariantsWithError(mock_nested) + self.assertAfterWithGeneratorInvariantsWithError(self.resource_a) + self.assertAfterWithGeneratorInvariantsWithError(self.resource_b) + + def testNestedExceptionBeforeInnerStatement(self): + mock_a = mock_contextmanager_generator() + mock_b = mock_contextmanager_generator() + self.bar = None + def shouldThrow(): + with mock_a as self.foo: + self.assertInWithManagerInvariants(mock_a) + self.assertInWithGeneratorInvariants(self.foo) + self.raiseTestException() + with mock_b as self.bar: + pass + self.assertRaises(RuntimeError, shouldThrow) + self.assertAfterWithManagerInvariantsWithError(mock_a) + self.assertAfterWithGeneratorInvariantsWithError(self.foo) + + # The inner statement stuff should never have been touched + self.assertEqual(self.bar, None) + self.assertFalse(mock_b.enter_called) + self.assertFalse(mock_b.exit_called) + self.assertEqual(mock_b.exit_args, None) + + def testNestedExceptionAfterInnerStatement(self): + mock_a = mock_contextmanager_generator() + mock_b = mock_contextmanager_generator() + def shouldThrow(): + with mock_a as self.foo: + with mock_b as self.bar: + self.assertInWithManagerInvariants(mock_a) + self.assertInWithManagerInvariants(mock_b) + self.assertInWithGeneratorInvariants(self.foo) + self.assertInWithGeneratorInvariants(self.bar) + self.raiseTestException() + self.assertRaises(RuntimeError, shouldThrow) + self.assertAfterWithManagerInvariantsWithError(mock_a) + self.assertAfterWithManagerInvariantsNoError(mock_b) + self.assertAfterWithGeneratorInvariantsWithError(self.foo) + self.assertAfterWithGeneratorInvariantsNoError(self.bar) + + def testRaisedStopIteration1(self): + # From bug 1462485 + @contextmanager + def cm(): + yield + + def shouldThrow(): + with cm(): + raise StopIteration("from with") + + self.assertRaises(StopIteration, shouldThrow) + + def testRaisedStopIteration2(self): + # From bug 1462485 + class cm(object): + def __enter__(self): + pass + def __exit__(self, type, value, traceback): + pass + + def shouldThrow(): + with cm(): + raise StopIteration("from with") + + self.assertRaises(StopIteration, shouldThrow) + + def testRaisedStopIteration3(self): + # Another variant where the exception hasn't been instantiated + # From bug 1705170 + @contextmanager + def cm(): + yield + + def shouldThrow(): + with cm(): + raise iter([]).next() + + self.assertRaises(StopIteration, shouldThrow) + + def testRaisedGeneratorExit1(self): + # From bug 1462485 + @contextmanager + def cm(): + yield + + def shouldThrow(): + with cm(): + raise GeneratorExit("from with") + + self.assertRaises(GeneratorExit, shouldThrow) + + def testRaisedGeneratorExit2(self): + # From bug 1462485 + class cm (object): + def __enter__(self): + pass + def __exit__(self, type, value, traceback): + pass + + def shouldThrow(): + with cm(): + raise GeneratorExit("from with") + + self.assertRaises(GeneratorExit, shouldThrow) + + +class NonLocalFlowControlTestCase(unittest.TestCase): + + def testWithBreak(self): + counter = 0 + while True: + counter += 1 + with mock_contextmanager_generator(): + counter += 10 + break + counter += 100 # Not reached + self.assertEqual(counter, 11) + + def testWithContinue(self): + counter = 0 + while True: + counter += 1 + if counter > 2: + break + with mock_contextmanager_generator(): + counter += 10 + continue + counter += 100 # Not reached + self.assertEqual(counter, 12) + + def testWithReturn(self): + def foo(): + counter = 0 + while True: + counter += 1 + with mock_contextmanager_generator(): + counter += 10 + return counter + counter += 100 # Not reached + self.assertEqual(foo(), 11) + + def testWithYield(self): + def gen(): + with mock_contextmanager_generator(): + yield 12 + yield 13 + x = list(gen()) + self.assertEqual(x, [12, 13]) + + def testWithRaise(self): + counter = 0 + try: + counter += 1 + with mock_contextmanager_generator(): + counter += 10 + raise RuntimeError + counter += 100 # Not reached + except RuntimeError: + self.assertEqual(counter, 11) + else: + self.fail("Didn't raise RuntimeError") + + +class AssignmentTargetTestCase(unittest.TestCase): + + def testSingleComplexTarget(self): + targets = {1: [0, 1, 2]} + with mock_contextmanager_generator() as targets[1][0]: + self.assertEqual(targets.keys(), [1]) + self.assertEqual(targets[1][0].__class__, MockResource) + with mock_contextmanager_generator() as targets.values()[0][1]: + self.assertEqual(targets.keys(), [1]) + self.assertEqual(targets[1][1].__class__, MockResource) + with mock_contextmanager_generator() as targets[2]: + keys = targets.keys() + keys.sort() + self.assertEqual(keys, [1, 2]) + class C: pass + blah = C() + with mock_contextmanager_generator() as blah.foo: + self.assertEqual(hasattr(blah, "foo"), True) + + def testMultipleComplexTargets(self): + class C: + def __enter__(self): return 1, 2, 3 + def __exit__(self, t, v, tb): pass + targets = {1: [0, 1, 2]} + with C() as (targets[1][0], targets[1][1], targets[1][2]): + self.assertEqual(targets, {1: [1, 2, 3]}) + with C() as (targets.values()[0][2], targets.values()[0][1], targets.values()[0][0]): + self.assertEqual(targets, {1: [3, 2, 1]}) + with C() as (targets[1], targets[2], targets[3]): + self.assertEqual(targets, {1: 1, 2: 2, 3: 3}) + class B: pass + blah = B() + with C() as (blah.one, blah.two, blah.three): + self.assertEqual(blah.one, 1) + self.assertEqual(blah.two, 2) + self.assertEqual(blah.three, 3) + + +class ExitSwallowsExceptionTestCase(unittest.TestCase): + + def testExitTrueSwallowsException(self): + class AfricanSwallow: + def __enter__(self): pass + def __exit__(self, t, v, tb): return True + try: + with AfricanSwallow(): + 1/0 + except ZeroDivisionError: + self.fail("ZeroDivisionError should have been swallowed") + + def testExitFalseDoesntSwallowException(self): + class EuropeanSwallow: + def __enter__(self): pass + def __exit__(self, t, v, tb): return False + try: + with EuropeanSwallow(): + 1/0 + except ZeroDivisionError: + pass + else: + self.fail("ZeroDivisionError should have been raised") + + +class NewKeywordsWarningTestCase(unittest.TestCase): + + def check(self, code, word=None): + save = sys.stderr + sys.stderr = stream = StringIO.StringIO() + try: + compile(code, "<string>", "exec", 0, True) + finally: + sys.stderr = save + if word: + self.assert_("Warning: %r will become a reserved keyword in Python 2.6" % word + in stream.getvalue()) + else: + self.assertEqual(stream.getvalue(), "") + + def test_basic(self): + self.check("as = 4", "as") + self.check("with = 4", "with") + self.check("class as: pass", "as") + self.check("class with: pass", "with") + self.check("obj.as = 4", "as") + self.check("with.obj = 4", "with") + self.check("def with(): pass", "with") + self.check("do(); with = 23", "with") + + def test_after_import(self): + # issue 3936 + self.check("import sys\nas = 4", "as") + self.check("import sys\nwith = 4", "with") + + +def test_main(): + run_unittest(FailureTestCase, NonexceptionalTestCase, + NestedNonexceptionalTestCase, ExceptionalTestCase, + NonLocalFlowControlTestCase, + AssignmentTargetTestCase, + ExitSwallowsExceptionTestCase, + NewKeywordsWarningTestCase) + + +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...> - 2008-10-13 18:50:22
|
Revision: 5386 http://jython.svn.sourceforge.net/jython/?rev=5386&view=rev Author: fwierzbicki Date: 2008-10-13 18:50:06 +0000 (Mon, 13 Oct 2008) Log Message: ----------- Fixed "expected skips" that wheren't actually being skipped. Also added test_peepholer and test_profile to expected failures since these are platform specific tests. This is a work around, we should (most likely) go back and force these expected failures to skip in Jython, but I want to do that in one future sweep. Modified Paths: -------------- trunk/jython/Lib/test/regrtest.py Modified: trunk/jython/Lib/test/regrtest.py =================================================================== --- trunk/jython/Lib/test/regrtest.py 2008-10-13 17:31:05 UTC (rev 5385) +++ trunk/jython/Lib/test/regrtest.py 2008-10-13 18:50:06 UTC (rev 5386) @@ -1388,9 +1388,6 @@ test_capi test_cd test_cl - test_code - test_codeccallbacks - test_codeop test_commands test_crypt test_ctypes @@ -1417,28 +1414,23 @@ test_macfs test_macostools test_mmap - test_mpz test_nis test_normalization test_openpty test_ossaudiodev test_parser - test_peepholer test_plistlib test_poll - test_profile test_pty test_pyexpat test_resource test_rgbimg - test_rotor test_scriptpackages test_signal test_socket_ssl test_socketserver test_sqlite test_startfile - test_stringprep test_strop test_structmembers test_sunaudiodev @@ -1447,8 +1439,6 @@ test_tcl test_threadsignals test_timeout - test_timing - test_transformer test_unicode_file test_wait3 test_wait4 @@ -1482,6 +1472,8 @@ test_gc test_iterlen test_marshal + test_peepholer + test_profile test_pyclbr test_transformer test_ucn This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-13 17:31:17
|
Revision: 5385 http://jython.svn.sourceforge.net/jython/?rev=5385&view=rev Author: fwierzbicki Date: 2008-10-13 17:31:05 +0000 (Mon, 13 Oct 2008) Log Message: ----------- disable test_transformer for the same reason we disabled test_compiler: we don't intend to support the parser module compiler relies on, with _ast being the way forward. transformer.py is in the same area of code. Modified Paths: -------------- trunk/jython/Lib/test/regrtest.py Modified: trunk/jython/Lib/test/regrtest.py =================================================================== --- trunk/jython/Lib/test/regrtest.py 2008-10-13 17:19:47 UTC (rev 5384) +++ trunk/jython/Lib/test/regrtest.py 2008-10-13 17:31:05 UTC (rev 5385) @@ -1483,6 +1483,7 @@ test_iterlen test_marshal test_pyclbr + test_transformer test_ucn test_xml_etree test_zipimport This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-13 17:19:51
|
Revision: 5384 http://jython.svn.sourceforge.net/jython/?rev=5384&view=rev Author: fwierzbicki Date: 2008-10-13 17:19:47 +0000 (Mon, 13 Oct 2008) Log Message: ----------- Fixed issue http://bugs.jython.org/issue1111: keyword arguments not supported on __import__ Modified Paths: -------------- trunk/jython/NEWS trunk/jython/src/org/python/core/__builtin__.java Modified: trunk/jython/NEWS =================================================================== --- trunk/jython/NEWS 2008-10-12 23:00:34 UTC (rev 5383) +++ trunk/jython/NEWS 2008-10-13 17:19:47 UTC (rev 5384) @@ -1,6 +1,9 @@ Jython NEWS Jython 2.5 + Bugs fixed (new numbering due to move to Roundup) + - [ 1111 ] keyword arguments not supported on __import__ + Incompatible Changes - The python.prepath property has been removed; use python.path instead. - To implement the Java Map interface, PyDictionary.values now returns a Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-12 23:00:34 UTC (rev 5383) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-10-13 17:19:47 UTC (rev 5384) @@ -1268,24 +1268,14 @@ "is the number of parent directories to search relative to the current module."); } -// public ImportFunction() { -// } - public PyObject __call__(PyObject args[], String keywords[]) { - if (!(args.length < 1 || args[0] instanceof PyString)) { - throw Py.TypeError("first argument must be a string"); - } - if (keywords.length > 0) { - throw Py.TypeError("__import__() takes no keyword arguments"); - } + ArgParser ap = new ArgParser("__import__", args, keywords, new String[]{"name", "globals", "locals", "fromlist", "level"}, 1); - int argc = args.length; - String module = args[0].__str__().toString(); + String module = ap.getString(0); + PyObject globals = ap.getPyObject(1, null); + PyObject fromlist = ap.getPyObject(3, Py.EmptyTuple); + int level = ap.getInt(4, imp.DEFAULT_LEVEL); - PyObject globals = (argc > 1 && args[1] != null) ? args[1] : null; - PyObject fromlist = (argc > 3 && args[3] != null) ? args[3] : Py.EmptyTuple; - int level = (argc > 4 && args[4] != null) ? Py.py2int(args[4]) : imp.DEFAULT_LEVEL; - return load(module, globals, fromlist, level); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-12 23:00:38
|
Revision: 5383 http://jython.svn.sourceforge.net/jython/?rev=5383&view=rev Author: pjenvey Date: 2008-10-12 23:00:34 +0000 (Sun, 12 Oct 2008) Log Message: ----------- fix the renamed _collections Modified Paths: -------------- trunk/jython/src/templates/mappings Modified: trunk/jython/src/templates/mappings =================================================================== --- trunk/jython/src/templates/mappings 2008-10-12 22:37:53 UTC (rev 5382) +++ trunk/jython/src/templates/mappings 2008-10-12 23:00:34 UTC (rev 5383) @@ -11,8 +11,8 @@ bool.derived:org.python.core.PyBooleanDerived classmethod.derived:org.python.core.PyClassMethodDerived complex.derived:org.python.core.PyComplexDerived -defaultdict.derived:org.python.modules.collections.PyDefaultDictDerived -deque.derived:org.python.modules.collections.PyDequeDerived +defaultdict.derived:org.python.modules._collections.PyDefaultDictDerived +deque.derived:org.python.modules._collections.PyDequeDerived dialect.derived:org.python.modules._csv.PyDialectDerived dict.derived:org.python.core.PyDictionaryDerived enumerate.derived:org.python.core.PyEnumerateDerived This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-12 22:38:07
|
Revision: 5382 http://jython.svn.sourceforge.net/jython/?rev=5382&view=rev Author: pjenvey Date: 2008-10-12 22:37:53 +0000 (Sun, 12 Oct 2008) Log Message: ----------- update the deriveds for better unhashable TypeError messages Modified Paths: -------------- trunk/jython/src/org/python/core/PyArrayDerived.java trunk/jython/src/org/python/core/PyBaseExceptionDerived.java trunk/jython/src/org/python/core/PyBooleanDerived.java trunk/jython/src/org/python/core/PyClassMethodDerived.java trunk/jython/src/org/python/core/PyComplexDerived.java trunk/jython/src/org/python/core/PyDictionaryDerived.java trunk/jython/src/org/python/core/PyEnumerateDerived.java trunk/jython/src/org/python/core/PyFileDerived.java trunk/jython/src/org/python/core/PyFloatDerived.java trunk/jython/src/org/python/core/PyFrozenSetDerived.java trunk/jython/src/org/python/core/PyIntegerDerived.java trunk/jython/src/org/python/core/PyListDerived.java trunk/jython/src/org/python/core/PyLongDerived.java trunk/jython/src/org/python/core/PyModuleDerived.java trunk/jython/src/org/python/core/PyObjectDerived.java trunk/jython/src/org/python/core/PyPropertyDerived.java trunk/jython/src/org/python/core/PySetDerived.java trunk/jython/src/org/python/core/PySliceDerived.java trunk/jython/src/org/python/core/PyStringDerived.java trunk/jython/src/org/python/core/PySuperDerived.java trunk/jython/src/org/python/core/PyTupleDerived.java trunk/jython/src/org/python/core/PyTypeDerived.java trunk/jython/src/org/python/core/PyUnicodeDerived.java trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java trunk/jython/src/org/python/modules/random/PyRandomDerived.java trunk/jython/src/org/python/modules/thread/PyLocalDerived.java trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java Modified: trunk/jython/src/org/python/core/PyArrayDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyArrayDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyArrayDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyBaseExceptionDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyBaseExceptionDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyBaseExceptionDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -720,7 +720,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyBooleanDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyBooleanDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyBooleanDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyClassMethodDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyClassMethodDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyClassMethodDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyComplexDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyComplexDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyComplexDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyDictionaryDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionaryDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyDictionaryDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyEnumerateDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyEnumerateDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyEnumerateDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyFileDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFileDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyFileDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyFloatDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFloatDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyFloatDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyFrozenSetDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyFrozenSetDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyFrozenSetDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyIntegerDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyIntegerDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyIntegerDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyListDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyListDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyListDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyLongDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyLongDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyLongDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyModuleDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyModuleDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyModuleDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -720,7 +720,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyObjectDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyObjectDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyObjectDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyPropertyDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyPropertyDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyPropertyDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PySetDerived.java =================================================================== --- trunk/jython/src/org/python/core/PySetDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PySetDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PySliceDerived.java =================================================================== --- trunk/jython/src/org/python/core/PySliceDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PySliceDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyStringDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyStringDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyStringDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PySuperDerived.java =================================================================== --- trunk/jython/src/org/python/core/PySuperDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PySuperDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyTupleDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyTupleDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyTupleDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyTypeDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyTypeDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyTypeDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -720,7 +720,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/core/PyUnicodeDerived.java =================================================================== --- trunk/jython/src/org/python/core/PyUnicodeDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/core/PyUnicodeDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -744,7 +744,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/_collections/PyDefaultDictDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -746,7 +746,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/_collections/PyDequeDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -746,7 +746,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/_csv/PyDialectDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -722,7 +722,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/_functools/PyPartialDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -722,7 +722,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java =================================================================== --- trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/_weakref/ReferenceTypeDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -746,7 +746,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/random/PyRandomDerived.java =================================================================== --- trunk/jython/src/org/python/modules/random/PyRandomDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/random/PyRandomDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -746,7 +746,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/thread/PyLocalDerived.java =================================================================== --- trunk/jython/src/org/python/modules/thread/PyLocalDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/thread/PyLocalDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -722,7 +722,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } Modified: trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java =================================================================== --- trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java 2008-10-12 22:18:06 UTC (rev 5381) +++ trunk/jython/src/org/python/modules/zipimport/zipimporterDerived.java 2008-10-12 22:37:53 UTC (rev 5382) @@ -722,7 +722,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'",getType().fastGetName())); } return super.hashCode(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-12 22:18:20
|
Revision: 5381 http://jython.svn.sourceforge.net/jython/?rev=5381&view=rev Author: pjenvey Date: 2008-10-12 22:18:06 +0000 (Sun, 12 Oct 2008) Log Message: ----------- better unhashable TypeError messages Modified Paths: -------------- trunk/jython/src/org/python/core/PyDictionary.java trunk/jython/src/org/python/core/PyList.java trunk/jython/src/org/python/core/PySlice.java trunk/jython/src/templates/object.derived Modified: trunk/jython/src/org/python/core/PyDictionary.java =================================================================== --- trunk/jython/src/org/python/core/PyDictionary.java 2008-10-12 20:10:04 UTC (rev 5380) +++ trunk/jython/src/org/python/core/PyDictionary.java 2008-10-12 22:18:06 UTC (rev 5381) @@ -661,7 +661,7 @@ @ExposedMethod final int dict___hash__() { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'", getType().fastGetName())); } public boolean isSequenceType() { Modified: trunk/jython/src/org/python/core/PyList.java =================================================================== --- trunk/jython/src/org/python/core/PyList.java 2008-10-12 20:10:04 UTC (rev 5380) +++ trunk/jython/src/org/python/core/PyList.java 2008-10-12 22:18:06 UTC (rev 5381) @@ -730,7 +730,7 @@ @ExposedMethod final int list___hash__() { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'", getType().fastGetName())); } public PyTuple __getnewargs__() { Modified: trunk/jython/src/org/python/core/PySlice.java =================================================================== --- trunk/jython/src/org/python/core/PySlice.java 2008-10-12 20:10:04 UTC (rev 5380) +++ trunk/jython/src/org/python/core/PySlice.java 2008-10-12 22:18:06 UTC (rev 5381) @@ -71,7 +71,7 @@ @ExposedMethod final int slice___hash__() { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'", getType().fastGetName())); } public PyString __str__() { Modified: trunk/jython/src/templates/object.derived =================================================================== --- trunk/jython/src/templates/object.derived 2008-10-12 20:10:04 UTC (rev 5380) +++ trunk/jython/src/templates/object.derived 2008-10-12 22:18:06 UTC (rev 5381) @@ -78,7 +78,7 @@ throw Py.TypeError("__hash__ should return a int"); } if (self_type.lookup("__eq__") != null || self_type.lookup("__cmp__") != null) { - throw Py.TypeError("unhashable type"); + throw Py.TypeError(String.format("unhashable type: '%.200s'", getType().fastGetName())); } return super.hashCode(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2008-10-12 20:10:17
|
Revision: 5380 http://jython.svn.sourceforge.net/jython/?rev=5380&view=rev Author: pjenvey Date: 2008-10-12 20:10:04 +0000 (Sun, 12 Oct 2008) Log Message: ----------- fix bad bytecode generated for: a[[b for b, c in d]] = e the store was losing track of the value (e) here because the list comp/tuple unpack combo overwrote where e's location was held Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-12 16:28:15 UTC (rev 5379) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-12 20:10:04 UTC (rev 5380) @@ -1604,6 +1604,7 @@ return Slice(node, (Slice) node.slice); } + int value = temporary; expr_contextType ctx = node.ctx; if (node.ctx == expr_contextType.AugStore && augmode == expr_contextType.Store) { restoreAugTmps(node, 2); @@ -1627,7 +1628,7 @@ return null; case Param: case Store: - code.aload(temporary); + code.aload(value); code.invokevirtual("org/python/core/PyObject", "__setitem__", "(" + $pyObj + $pyObj + ")V"); return null; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-10-12 16:28:25
|
Revision: 5379 http://jython.svn.sourceforge.net/jython/?rev=5379&view=rev Author: fwierzbicki Date: 2008-10-12 16:28:15 +0000 (Sun, 12 Oct 2008) Log Message: ----------- More groundwork for absolute_import. Passing level info into most of the places it needs to go, also now sending the correct level information when "from __future__ import absolute_import" is issued. Added a constant in imp.java DEFAULT_LEVEL, so that it can be changed in one place when absolute import becomes the default behavior. Modified Paths: -------------- trunk/jython/src/org/python/compiler/CodeCompiler.java trunk/jython/src/org/python/compiler/Future.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/core/imp.java Modified: trunk/jython/src/org/python/compiler/CodeCompiler.java =================================================================== --- trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-12 00:25:07 UTC (rev 5378) +++ trunk/jython/src/org/python/compiler/CodeCompiler.java 2008-10-12 16:28:15 UTC (rev 5379) @@ -802,7 +802,16 @@ makeStrings(code, fromNames, fromNames.length); loadFrame(); - code.iconst(node.level); + + if (node.level == 0) { + if (module.getFutures().isAbsoluteImportOn()) { + code.iconst_0(); + } else { + code.iconst_m1(); + } + } else { + code.iconst(node.level); + } code.invokestatic("org/python/core/imp", "importFrom", "(" + $str + $strArr + $pyFrame + "I" + ")" + $pyObjArr); int tmp = storeTop(); for (int i = 0; i < node.names.length; i++) { Modified: trunk/jython/src/org/python/compiler/Future.java =================================================================== --- trunk/jython/src/org/python/compiler/Future.java 2008-10-12 00:25:07 UTC (rev 5378) +++ trunk/jython/src/org/python/compiler/Future.java 2008-10-12 16:28:15 UTC (rev 5379) @@ -115,4 +115,8 @@ return with_statement; } + public boolean isAbsoluteImportOn() { + return absolute_import; + } + } Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-12 00:25:07 UTC (rev 5378) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-10-12 16:28:15 UTC (rev 5379) @@ -1198,18 +1198,22 @@ } public static PyObject __import__(String name) { - return __import__(name, null, null, null); + return __import__(name, null, null, null, imp.DEFAULT_LEVEL); } public static PyObject __import__(String name, PyObject globals) { - return __import__(name, globals, null, null); + return __import__(name, globals, null, null, imp.DEFAULT_LEVEL); } public static PyObject __import__(String name, PyObject globals, PyObject locals) { - return __import__(name, globals, locals, null); + return __import__(name, globals, locals, null, imp.DEFAULT_LEVEL); } public static PyObject __import__(String name, PyObject globals, PyObject locals, PyObject fromlist) { + return __import__(name, globals, locals, fromlist, imp.DEFAULT_LEVEL); + } + + public static PyObject __import__(String name, PyObject globals, PyObject locals, PyObject fromlist, int level) { PyFrame frame = Py.getFrame(); if (frame == null) { return null; @@ -1224,7 +1228,7 @@ return null; } - PyObject module = __import__.__call__(new PyObject[]{Py.newString(name), globals, locals, fromlist}); + PyObject module = __import__.__call__(new PyObject[]{Py.newString(name), globals, locals, fromlist, Py.newInteger(level)}); return module; } } @@ -1280,12 +1284,13 @@ PyObject globals = (argc > 1 && args[1] != null) ? args[1] : null; PyObject fromlist = (argc > 3 && args[3] != null) ? args[3] : Py.EmptyTuple; + int level = (argc > 4 && args[4] != null) ? Py.py2int(args[4]) : imp.DEFAULT_LEVEL; - return load(module, globals, fromlist); + return load(module, globals, fromlist, level); } - private PyObject load(String module, PyObject globals, PyObject fromlist) { - PyObject mod = imp.importName(module.intern(), fromlist.__len__() == 0, globals, fromlist); + private PyObject load(String module, PyObject globals, PyObject fromlist, int level) { + PyObject mod = imp.importName(module.intern(), fromlist.__len__() == 0, globals, fromlist, level); return mod; } Modified: trunk/jython/src/org/python/core/imp.java =================================================================== --- trunk/jython/src/org/python/core/imp.java 2008-10-12 00:25:07 UTC (rev 5378) +++ trunk/jython/src/org/python/core/imp.java 2008-10-12 16:28:15 UTC (rev 5379) @@ -24,6 +24,9 @@ public static final int APIVersion = 15; + //This should change to 0 for Python 2.7 and 3.0 see PEP 328 + public static final int DEFAULT_LEVEL = -1; + /** A non-empty fromlist for __import__'ing sub-modules. */ private static final PyObject nonEmptyFromlist = new PyTuple(Py.newString("__doc__")); @@ -518,9 +521,14 @@ * 'a.b.c' would return 'a.b'. * * @param dict the __dict__ of a loaded module + * @param level used for relative and absolute imports. -1 means try both, + * 0 means absolute only, positive ints represent the level to + * look upward for a relative path. See PEP 328 at + * http://www.python.org/dev/peps/pep-0328/ + * * @return the parent name for a module */ - private static String getParent(PyObject dict) { + private static String getParent(PyObject dict, int level) { PyObject tmp = dict.__finditem__("__name__"); if (tmp == null) { return null; @@ -639,7 +647,7 @@ * @return a module */ private static PyObject import_name(String name, boolean top, - PyObject modDict, PyObject fromlist) { + PyObject modDict, PyObject fromlist, int level) { if (name.length() == 0) { throw Py.ValueError("Empty module name"); } @@ -647,7 +655,7 @@ PyObject pkgMod = null; String pkgName = null; if (modDict != null && !(modDict instanceof PyNone)) { - pkgName = getParent(modDict); + pkgName = getParent(modDict, level); pkgMod = modules.__finditem__(pkgName); if (pkgMod != null && !(pkgMod instanceof PyModule)) { pkgMod = null; @@ -705,7 +713,7 @@ * @return an imported module (Java or Python) */ public static PyObject importName(String name, boolean top) { - return import_name(name, top, null, null); + return import_name(name, top, null, null, DEFAULT_LEVEL); } /** @@ -718,10 +726,10 @@ * @return an imported module (Java or Python) */ public static PyObject importName(String name, boolean top, - PyObject modDict, PyObject fromlist) { + PyObject modDict, PyObject fromlist, int level) { importLock.lock(); try { - return import_name(name, top, modDict, fromlist); + return import_name(name, top, modDict, fromlist, level); } finally { importLock.unlock(); } @@ -758,7 +766,7 @@ */ public static PyObject[] importFrom(String mod, String[] names, PyFrame frame) { - return importFromAs(mod, names, null, frame, 0); + return importFromAs(mod, names, null, frame, DEFAULT_LEVEL); } /** @@ -776,7 +784,7 @@ */ public static PyObject[] importFromAs(String mod, String[] names, PyFrame frame) { - return importFromAs(mod, names, null, frame, 0); + return importFromAs(mod, names, null, frame, DEFAULT_LEVEL); } /** @@ -791,7 +799,7 @@ } PyObject module = __builtin__.__import__(mod, frame.f_globals, frame.getLocals(), - new PyTuple(pyNames)); + new PyTuple(pyNames), level); PyObject[] submods = new PyObject[names.length]; for (int i = 0; i < names.length; i++) { PyObject submod = module.__findattr__(names[i]); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-10-12 00:25:12
|
Revision: 5378 http://jython.svn.sourceforge.net/jython/?rev=5378&view=rev Author: zyasoft Date: 2008-10-12 00:25:07 +0000 (Sun, 12 Oct 2008) Log Message: ----------- Missing module for previous commit! Added Paths: ----------- trunk/jython/src/org/python/modules/PyStruct.java Added: trunk/jython/src/org/python/modules/PyStruct.java =================================================================== --- trunk/jython/src/org/python/modules/PyStruct.java (rev 0) +++ trunk/jython/src/org/python/modules/PyStruct.java 2008-10-12 00:25:07 UTC (rev 5378) @@ -0,0 +1,88 @@ +package org.python.modules; + +import org.python.core.Py; +import org.python.core.PyArray; +import org.python.core.PyNewWrapper; +import org.python.core.PyObject; +import org.python.core.PyString; +import org.python.core.PyTuple; +import org.python.core.PyType; +import org.python.expose.ExposedGet; +import org.python.expose.ExposedMethod; +import org.python.expose.ExposedNew; +import org.python.expose.ExposedType; + +@ExposedType(name = "Struct", base = PyObject.class) +public class PyStruct extends PyObject { + public static final PyType TYPE = PyType.fromClass(PyStruct.class); + + @ExposedGet + public final String format; + + @ExposedGet + public final int size; + + private final struct.FormatDef[] format_def; + + @ExposedGet(name = "__class__") + @Override + public PyType getType() { + return TYPE; + } + + public PyStruct(PyObject[] args, String[] keywords) { + final int nargs = args.length; + if (keywords.length > 0 ) { + for (String keyword : keywords) { + if (!keyword.equals("format")) { + throw Py.TypeError("'" + keyword + "' is an invalid keyword argument for this function"); + } + } + } + else if (nargs < 1 || nargs > 1) { + throw Py.TypeError("Struct() takes exactly 1 argument (" + nargs + " given)"); + } + format = args[0].toString(); + format_def = struct.whichtable(format); + size = struct.calcsize(format, format_def); + } + + @ExposedNew + final static PyObject Struct___new__ (PyNewWrapper new_, boolean init, + PyType subtype, PyObject[] args, String[] keywords) { + return new PyStruct(args, keywords); + } + + @ExposedMethod + public String pack(PyObject[] args, String[] kwds) { + return struct.pack(format, format_def, size, 0, args).toString(); + } + + @ExposedMethod + final void pack_into(PyObject[] args, String[] kwds) { + struct.pack_into(format, format_def, size, 0, args); + } + + @ExposedMethod + public PyTuple unpack(PyObject source) { + String s; + if (source instanceof PyString) + s = source.toString(); + else if (source instanceof PyArray) + s = ((PyArray)source).tostring(); + else + throw Py.TypeError("unpack of a str or array"); + if (size != s.length()) + throw struct.StructError("unpack str size does not match format"); + return struct.unpack(format_def, size, format, new struct.ByteStream(s)); + } + + // xxx - also support byte[], java.nio.(Byte)Buffer at some point? + @ExposedMethod(defaults = {"0"}) + public PyTuple unpack_from(PyObject string, int offset) { + String s = string.toString(); + if (size >= (s.length() - offset + 1)) + throw struct.StructError("unpack_from str size does not match format"); + return struct.unpack(format_def, size, format, new struct.ByteStream(s, offset)); + } +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-10-12 00:24:36
|
Revision: 5377 http://jython.svn.sourceforge.net/jython/?rev=5377&view=rev Author: zyasoft Date: 2008-10-12 00:24:30 +0000 (Sun, 12 Oct 2008) Log Message: ----------- Implemented struct.Struct as well as other updates in the struct module for 2.5 Modified Paths: -------------- trunk/jython/CoreExposed.includes trunk/jython/Lib/test/test_struct.py trunk/jython/src/org/python/core/PyArray.java trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/modules/struct.java Modified: trunk/jython/CoreExposed.includes =================================================================== --- trunk/jython/CoreExposed.includes 2008-10-12 00:18:38 UTC (rev 5376) +++ trunk/jython/CoreExposed.includes 2008-10-12 00:24:30 UTC (rev 5377) @@ -52,4 +52,5 @@ org/python/modules/thread/PyLocal.class org/python/modules/time/PyTimeTuple.class org/python/modules/zipimport/zipimporter.class +org/python/modules/PyStruct.class org/python/modules/PyTeeIterator.class Modified: trunk/jython/Lib/test/test_struct.py =================================================================== --- trunk/jython/Lib/test/test_struct.py 2008-10-12 00:18:38 UTC (rev 5376) +++ trunk/jython/Lib/test/test_struct.py 2008-10-12 00:24:30 UTC (rev 5377) @@ -1,9 +1,15 @@ -from test.test_support import TestFailed, verbose, verify, vereq +from test.test_support import TestFailed, verbose, verify, vereq, is_jython import test.test_support import struct import array import warnings +if is_jython: + # currently no buffer type, but this will work fine for this testing + def buffer(s): + return str(s) + + import sys ISBIGENDIAN = sys.byteorder == "big" del sys Modified: trunk/jython/src/org/python/core/PyArray.java =================================================================== --- trunk/jython/src/org/python/core/PyArray.java 2008-10-12 00:18:38 UTC (rev 5376) +++ trunk/jython/src/org/python/core/PyArray.java 2008-10-12 00:24:30 UTC (rev 5377) @@ -1393,6 +1393,23 @@ Array.set(data, i, o); } + // xxx - add more efficient comparable typecode lookup via an enumset, and expand + public void set(int i, int value) { + if ("u".equals(typecode) || type == Integer.TYPE || type == Long.TYPE) { + Array.setInt(data, i, value); + } else { + throw Py.TypeError("Type not compatible with array type"); + } + } + + public void set(int i, char value) { + if ("c".equals(typecode) || type == Integer.TYPE || type == Long.TYPE) { + Array.setChar(data, i, value); + } else { + throw Py.TypeError("Type not compatible with array type"); + } + } + private boolean isSigned() { return typecode.length() == 1 && typecode.equals(typecode.toUpperCase()); } Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2008-10-12 00:18:38 UTC (rev 5376) +++ trunk/jython/src/org/python/core/__builtin__.java 2008-10-12 00:24:30 UTC (rev 5377) @@ -1233,6 +1233,7 @@ abstract class ExtendedBuiltinFunction extends PyObject { public static final PyType TYPE = PyType.fromClass(PyBuiltinFunction.class); @ExposedGet(name = "__class__") + @Override public PyType getType() { return TYPE; } Modified: trunk/jython/src/org/python/modules/struct.java =================================================================== --- trunk/jython/src/org/python/modules/struct.java 2008-10-12 00:18:38 UTC (rev 5376) +++ trunk/jython/src/org/python/modules/struct.java 2008-10-12 00:24:30 UTC (rev 5377) @@ -20,6 +20,13 @@ import org.python.core.PyTuple; import java.math.BigInteger; +import java.util.Arrays; +import org.python.core.ClassDictInit; +import org.python.core.PyArray; +import org.python.core.PyType; +import org.python.expose.ExposedGet; +import org.python.expose.ExposedNew; +import org.python.expose.ExposedType; /** * This module performs conversions between Python values and C @@ -399,11 +406,17 @@ } ByteStream(String s) { - int l = s.length(); + this(s, 0); + } + + ByteStream(String s, int offset) { + int l = s.length() - offset; data = new char[l]; - s.getChars(0, l, data, 0); + s.getChars(offset, s.length(), data, 0); len = l; pos = 0; + +// System.out.println("s.length()=" + s.length() + ",offset=" + offset + ",l=" + l + ",data=" + Arrays.toString(data)); } int readByte() { @@ -874,7 +887,7 @@ - private static FormatDef[] whichtable(String pfmt) { + static FormatDef[] whichtable(String pfmt) { char c = pfmt.charAt(0); switch (c) { case '<' : @@ -913,7 +926,7 @@ - private static int calcsize(String format, FormatDef[] f) { + static int calcsize(String format, FormatDef[] f) { int size = 0; int len = format.length(); @@ -973,10 +986,43 @@ FormatDef[] f = whichtable(format); int size = calcsize(format, f); + + return pack(format, f, size, 1, args).toString(); + } + + // xxx - may need to consider doing a generic arg parser here + static public void pack_into(PyObject[] args) { + if (args.length < 3) + Py.TypeError("illegal argument type for built-in operation"); + String format = args[0].toString(); + FormatDef[] f = whichtable(format); + int size = calcsize(format, f); + pack_into(format, f, size, 1, args); + } + + static void pack_into(String format, FormatDef[] f, int size, int argstart, PyObject[] args) { + if (args.length - argstart < 2) + Py.TypeError("illegal argument type for built-in operation"); + if (!(args[argstart] instanceof PyArray)) { + throw Py.TypeError("pack_into takes an array arg"); // as well as a buffer, what else? + } + PyArray buffer = (PyArray)args[argstart]; + int offset = args[argstart + 1].__int__().asInt(); + ByteStream res = pack(format, f, size, argstart + 2, args); + if (res.pos > buffer.__len__()) { + throw StructError("pack_into requires a buffer of at least " + res.pos + " bytes, got " + buffer.__len__()); + } + for (int i = 0; i < res.pos; i++, offset++) { + char val = res.data[i]; + buffer.set(offset, val); + } + } + + static ByteStream pack(String format, FormatDef[] f, int size, int start, PyObject[] args) { ByteStream res = new ByteStream(); - int i = 1; + int i = start; int len = format.length(); for (int j = 0; j < len; j++) { char c = format.charAt(j); @@ -995,7 +1041,7 @@ FormatDef e = getentry(c, f); - // Fill padd bytes with zeros + // Fill pad bytes with zeros int nres = align(res.size(), e) - res.size(); while (nres-- > 0) res.writeByte(0); @@ -1005,7 +1051,7 @@ if (i < args.length) throw StructError("too many arguments for pack format"); - return res.toString(); + return res; } @@ -1017,19 +1063,41 @@ * The string must contain exactly the amount of data required by * the format (i.e. len(string) must equal calcsize(fmt)). */ + public static PyTuple unpack(String format, String string) { + FormatDef[] f = whichtable(format); + int size = calcsize(format, f); int len = string.length(); - + if (size != len) + throw StructError("unpack str size does not match format"); + return unpack(f, size, format, new ByteStream(string)); + } + + public static PyTuple unpack(String format, PyArray buffer) { + String string = buffer.tostring(); FormatDef[] f = whichtable(format); int size = calcsize(format, f); - - if (size != len) + int len = string.length(); + if (size != len) throw StructError("unpack str size does not match format"); - + return unpack(f, size, format, new ByteStream(string)); + } + + public static PyTuple unpack_from(String format, String string) { + return unpack_from(format, string, 0); + } + + public static PyTuple unpack_from(String format, String string, int offset) { + FormatDef[] f = whichtable(format); + int size = calcsize(format, f); + int len = string.length(); + if (size >= (len - offset + 1)) + throw StructError("unpack_from str size does not match format"); + return unpack(f, size, format, new ByteStream(string, offset)); + } + + static PyTuple unpack(FormatDef[] f, int size, String format, ByteStream str) { PyList res = new PyList(); - - ByteStream str = new ByteStream(string); - int flen = format.length(); for (int j = 0; j < flen; j++) { char c = format.charAt(j); @@ -1057,8 +1125,7 @@ } - - private static PyException StructError(String explanation) { + static PyException StructError(String explanation) { return new PyException(error, explanation); } @@ -1067,4 +1134,9 @@ dict.__setitem__("__module__", new PyString("struct")); return dict; } + + public static PyStruct Struct(PyObject[] args, String[] keywords) { + return new PyStruct(args, keywords); + } } + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-10-12 00:18:44
|
Revision: 5376 http://jython.svn.sourceforge.net/jython/?rev=5376&view=rev Author: zyasoft Date: 2008-10-12 00:18:38 +0000 (Sun, 12 Oct 2008) Log Message: ----------- From http://svn.python.org/projects/python/branches/release25-maint/Lib/test/test_struct.py@60892 Added Paths: ----------- trunk/jython/Lib/test/test_struct.py Added: trunk/jython/Lib/test/test_struct.py =================================================================== --- trunk/jython/Lib/test/test_struct.py (rev 0) +++ trunk/jython/Lib/test/test_struct.py 2008-10-12 00:18:38 UTC (rev 5376) @@ -0,0 +1,625 @@ +from test.test_support import TestFailed, verbose, verify, vereq +import test.test_support +import struct +import array +import warnings + +import sys +ISBIGENDIAN = sys.byteorder == "big" +del sys +verify((struct.pack('=i', 1)[0] == chr(0)) == ISBIGENDIAN, + "bigendian determination appears wrong") + +try: + import _struct +except ImportError: + PY_STRUCT_RANGE_CHECKING = 0 + PY_STRUCT_OVERFLOW_MASKING = 1 + PY_STRUCT_FLOAT_COERCE = 2 +else: + PY_STRUCT_RANGE_CHECKING = getattr(_struct, '_PY_STRUCT_RANGE_CHECKING', 0) + PY_STRUCT_OVERFLOW_MASKING = getattr(_struct, '_PY_STRUCT_OVERFLOW_MASKING', 0) + PY_STRUCT_FLOAT_COERCE = getattr(_struct, '_PY_STRUCT_FLOAT_COERCE', 0) + +def string_reverse(s): + return "".join(reversed(s)) + +def bigendian_to_native(value): + if ISBIGENDIAN: + return value + else: + return string_reverse(value) + +def simple_err(func, *args): + try: + func(*args) + except struct.error: + pass + else: + raise TestFailed, "%s%s did not raise struct.error" % ( + func.__name__, args) + +def any_err(func, *args): + try: + func(*args) + except (struct.error, TypeError): + pass + else: + raise TestFailed, "%s%s did not raise error" % ( + func.__name__, args) + +def with_warning_restore(func): + def _with_warning_restore(*args, **kw): + # The `warnings` module doesn't have an advertised way to restore + # its filter list. Cheat. + save_warnings_filters = warnings.filters[:] + # Grrr, we need this function to warn every time. Without removing + # the warningregistry, running test_tarfile then test_struct would fail + # on 64-bit platforms. + globals = func.func_globals + if '__warningregistry__' in globals: + del globals['__warningregistry__'] + warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning) + warnings.filterwarnings("error", r""".*format requires.*""", + DeprecationWarning) + try: + return func(*args, **kw) + finally: + warnings.filters[:] = save_warnings_filters[:] + return _with_warning_restore + +def deprecated_err(func, *args): + try: + func(*args) + except (struct.error, TypeError): + pass + except DeprecationWarning: + if not PY_STRUCT_OVERFLOW_MASKING: + raise TestFailed, "%s%s expected to raise struct.error" % ( + func.__name__, args) + else: + raise TestFailed, "%s%s did not raise error" % ( + func.__name__, args) +deprecated_err = with_warning_restore(deprecated_err) + + +simple_err(struct.calcsize, 'Z') + +sz = struct.calcsize('i') +if sz * 3 != struct.calcsize('iii'): + raise TestFailed, 'inconsistent sizes' + +fmt = 'cbxxxxxxhhhhiillffd' +fmt3 = '3c3b18x12h6i6l6f3d' +sz = struct.calcsize(fmt) +sz3 = struct.calcsize(fmt3) +if sz * 3 != sz3: + raise TestFailed, 'inconsistent sizes (3*%r -> 3*%d = %d, %r -> %d)' % ( + fmt, sz, 3*sz, fmt3, sz3) + +simple_err(struct.pack, 'iii', 3) +simple_err(struct.pack, 'i', 3, 3, 3) +simple_err(struct.pack, 'i', 'foo') +simple_err(struct.pack, 'P', 'foo') +simple_err(struct.unpack, 'd', 'flap') +s = struct.pack('ii', 1, 2) +simple_err(struct.unpack, 'iii', s) +simple_err(struct.unpack, 'i', s) + +c = 'a' +b = 1 +h = 255 +i = 65535 +l = 65536 +f = 3.1415 +d = 3.1415 + +for prefix in ('', '@', '<', '>', '=', '!'): + for format in ('xcbhilfd', 'xcBHILfd'): + format = prefix + format + if verbose: + print "trying:", format + s = struct.pack(format, c, b, h, i, l, f, d) + cp, bp, hp, ip, lp, fp, dp = struct.unpack(format, s) + if (cp != c or bp != b or hp != h or ip != i or lp != l or + int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d)): + # ^^^ calculate only to two decimal places + raise TestFailed, "unpack/pack not transitive (%s, %s)" % ( + str(format), str((cp, bp, hp, ip, lp, fp, dp))) + +# Test some of the new features in detail + +# (format, argument, big-endian result, little-endian result, asymmetric) +tests = [ + ('c', 'a', 'a', 'a', 0), + ('xc', 'a', '\0a', '\0a', 0), + ('cx', 'a', 'a\0', 'a\0', 0), + ('s', 'a', 'a', 'a', 0), + ('0s', 'helloworld', '', '', 1), + ('1s', 'helloworld', 'h', 'h', 1), + ('9s', 'helloworld', 'helloworl', 'helloworl', 1), + ('10s', 'helloworld', 'helloworld', 'helloworld', 0), + ('11s', 'helloworld', 'helloworld\0', 'helloworld\0', 1), + ('20s', 'helloworld', 'helloworld'+10*'\0', 'helloworld'+10*'\0', 1), + ('b', 7, '\7', '\7', 0), + ('b', -7, '\371', '\371', 0), + ('B', 7, '\7', '\7', 0), + ('B', 249, '\371', '\371', 0), + ('h', 700, '\002\274', '\274\002', 0), + ('h', -700, '\375D', 'D\375', 0), + ('H', 700, '\002\274', '\274\002', 0), + ('H', 0x10000-700, '\375D', 'D\375', 0), + ('i', 70000000, '\004,\035\200', '\200\035,\004', 0), + ('i', -70000000, '\373\323\342\200', '\200\342\323\373', 0), + ('I', 70000000L, '\004,\035\200', '\200\035,\004', 0), + ('I', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0), + ('l', 70000000, '\004,\035\200', '\200\035,\004', 0), + ('l', -70000000, '\373\323\342\200', '\200\342\323\373', 0), + ('L', 70000000L, '\004,\035\200', '\200\035,\004', 0), + ('L', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0), + ('f', 2.0, '@\000\000\000', '\000\000\000@', 0), + ('d', 2.0, '@\000\000\000\000\000\000\000', + '\000\000\000\000\000\000\000@', 0), + ('f', -2.0, '\300\000\000\000', '\000\000\000\300', 0), + ('d', -2.0, '\300\000\000\000\000\000\000\000', + '\000\000\000\000\000\000\000\300', 0), +] + +for fmt, arg, big, lil, asy in tests: + if verbose: + print "%r %r %r %r" % (fmt, arg, big, lil) + for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil), + ('='+fmt, ISBIGENDIAN and big or lil)]: + res = struct.pack(xfmt, arg) + if res != exp: + raise TestFailed, "pack(%r, %r) -> %r # expected %r" % ( + fmt, arg, res, exp) + n = struct.calcsize(xfmt) + if n != len(res): + raise TestFailed, "calcsize(%r) -> %d # expected %d" % ( + xfmt, n, len(res)) + rev = struct.unpack(xfmt, res)[0] + if rev != arg and not asy: + raise TestFailed, "unpack(%r, %r) -> (%r,) # expected (%r,)" % ( + fmt, res, rev, arg) + +########################################################################### +# Simple native q/Q tests. + +has_native_qQ = 1 +try: + struct.pack("q", 5) +except struct.error: + has_native_qQ = 0 + +if verbose: + print "Platform has native q/Q?", has_native_qQ and "Yes." or "No." + +any_err(struct.pack, "Q", -1) # can't pack -1 as unsigned regardless +simple_err(struct.pack, "q", "a") # can't pack string as 'q' regardless +simple_err(struct.pack, "Q", "a") # ditto, but 'Q' + +def test_native_qQ(): + bytes = struct.calcsize('q') + # The expected values here are in big-endian format, primarily because + # I'm on a little-endian machine and so this is the clearest way (for + # me) to force the code to get exercised. + for format, input, expected in ( + ('q', -1, '\xff' * bytes), + ('q', 0, '\x00' * bytes), + ('Q', 0, '\x00' * bytes), + ('q', 1L, '\x00' * (bytes-1) + '\x01'), + ('Q', (1L << (8*bytes))-1, '\xff' * bytes), + ('q', (1L << (8*bytes-1))-1, '\x7f' + '\xff' * (bytes - 1))): + got = struct.pack(format, input) + native_expected = bigendian_to_native(expected) + verify(got == native_expected, + "%r-pack of %r gave %r, not %r" % + (format, input, got, native_expected)) + retrieved = struct.unpack(format, got)[0] + verify(retrieved == input, + "%r-unpack of %r gave %r, not %r" % + (format, got, retrieved, input)) + +if has_native_qQ: + test_native_qQ() + +########################################################################### +# Standard integer tests (bBhHiIlLqQ). + +import binascii + +class IntTester: + + # XXX Most std integer modes fail to test for out-of-range. + # The "i" and "l" codes appear to range-check OK on 32-bit boxes, but + # fail to check correctly on some 64-bit ones (Tru64 Unix + Compaq C + # reported by Mark Favas). + BUGGY_RANGE_CHECK = "bBhHiIlL" + + def __init__(self, formatpair, bytesize): + assert len(formatpair) == 2 + self.formatpair = formatpair + for direction in "<>!=": + for code in formatpair: + format = direction + code + verify(struct.calcsize(format) == bytesize) + self.bytesize = bytesize + self.bitsize = bytesize * 8 + self.signed_code, self.unsigned_code = formatpair + self.unsigned_min = 0 + self.unsigned_max = 2L**self.bitsize - 1 + self.signed_min = -(2L**(self.bitsize-1)) + self.signed_max = 2L**(self.bitsize-1) - 1 + + def test_one(self, x, pack=struct.pack, + unpack=struct.unpack, + unhexlify=binascii.unhexlify): + if verbose: + print "trying std", self.formatpair, "on", x, "==", hex(x) + + # Try signed. + code = self.signed_code + if self.signed_min <= x <= self.signed_max: + # Try big-endian. + expected = long(x) + if x < 0: + expected += 1L << self.bitsize + assert expected > 0 + expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' + if len(expected) & 1: + expected = "0" + expected + expected = unhexlify(expected) + expected = "\x00" * (self.bytesize - len(expected)) + expected + + # Pack work? + format = ">" + code + got = pack(format, x) + verify(got == expected, + "'%s'-pack of %r gave %r, not %r" % + (format, x, got, expected)) + + # Unpack work? + retrieved = unpack(format, got)[0] + verify(x == retrieved, + "'%s'-unpack of %r gave %r, not %r" % + (format, got, retrieved, x)) + + # Adding any byte should cause a "too big" error. + any_err(unpack, format, '\x01' + got) + + # Try little-endian. + format = "<" + code + expected = string_reverse(expected) + + # Pack work? + got = pack(format, x) + verify(got == expected, + "'%s'-pack of %r gave %r, not %r" % + (format, x, got, expected)) + + # Unpack work? + retrieved = unpack(format, got)[0] + verify(x == retrieved, + "'%s'-unpack of %r gave %r, not %r" % + (format, got, retrieved, x)) + + # Adding any byte should cause a "too big" error. + any_err(unpack, format, '\x01' + got) + + else: + # x is out of range -- verify pack realizes that. + if not PY_STRUCT_RANGE_CHECKING and code in self.BUGGY_RANGE_CHECK: + if verbose: + print "Skipping buggy range check for code", code + else: + deprecated_err(pack, ">" + code, x) + deprecated_err(pack, "<" + code, x) + + # Much the same for unsigned. + code = self.unsigned_code + if self.unsigned_min <= x <= self.unsigned_max: + # Try big-endian. + format = ">" + code + expected = long(x) + expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' + if len(expected) & 1: + expected = "0" + expected + expected = unhexlify(expected) + expected = "\x00" * (self.bytesize - len(expected)) + expected + + # Pack work? + got = pack(format, x) + verify(got == expected, + "'%s'-pack of %r gave %r, not %r" % + (format, x, got, expected)) + + # Unpack work? + retrieved = unpack(format, got)[0] + verify(x == retrieved, + "'%s'-unpack of %r gave %r, not %r" % + (format, got, retrieved, x)) + + # Adding any byte should cause a "too big" error. + any_err(unpack, format, '\x01' + got) + + # Try little-endian. + format = "<" + code + expected = string_reverse(expected) + + # Pack work? + got = pack(format, x) + verify(got == expected, + "'%s'-pack of %r gave %r, not %r" % + (format, x, got, expected)) + + # Unpack work? + retrieved = unpack(format, got)[0] + verify(x == retrieved, + "'%s'-unpack of %r gave %r, not %r" % + (format, got, retrieved, x)) + + # Adding any byte should cause a "too big" error. + any_err(unpack, format, '\x01' + got) + + else: + # x is out of range -- verify pack realizes that. + if not PY_STRUCT_RANGE_CHECKING and code in self.BUGGY_RANGE_CHECK: + if verbose: + print "Skipping buggy range check for code", code + else: + deprecated_err(pack, ">" + code, x) + deprecated_err(pack, "<" + code, x) + + def run(self): + from random import randrange + + # Create all interesting powers of 2. + values = [] + for exp in range(self.bitsize + 3): + values.append(1L << exp) + + # Add some random values. + for i in range(self.bitsize): + val = 0L + for j in range(self.bytesize): + val = (val << 8) | randrange(256) + values.append(val) + + # Try all those, and their negations, and +-1 from them. Note + # that this tests all power-of-2 boundaries in range, and a few out + # of range, plus +-(2**n +- 1). + for base in values: + for val in -base, base: + for incr in -1, 0, 1: + x = val + incr + try: + x = int(x) + except OverflowError: + pass + self.test_one(x) + + # Some error cases. + for direction in "<>": + for code in self.formatpair: + for badobject in "a string", 3+42j, randrange: + any_err(struct.pack, direction + code, badobject) + +for args in [("bB", 1), + ("hH", 2), + ("iI", 4), + ("lL", 4), + ("qQ", 8)]: + t = IntTester(*args) + t.run() + + +########################################################################### +# The p ("Pascal string") code. + +def test_p_code(): + for code, input, expected, expectedback in [ + ('p','abc', '\x00', ''), + ('1p', 'abc', '\x00', ''), + ('2p', 'abc', '\x01a', 'a'), + ('3p', 'abc', '\x02ab', 'ab'), + ('4p', 'abc', '\x03abc', 'abc'), + ('5p', 'abc', '\x03abc\x00', 'abc'), + ('6p', 'abc', '\x03abc\x00\x00', 'abc'), + ('1000p', 'x'*1000, '\xff' + 'x'*999, 'x'*255)]: + got = struct.pack(code, input) + if got != expected: + raise TestFailed("pack(%r, %r) == %r but expected %r" % + (code, input, got, expected)) + (got,) = struct.unpack(code, got) + if got != expectedback: + raise TestFailed("unpack(%r, %r) == %r but expected %r" % + (code, input, got, expectedback)) + +test_p_code() + + +########################################################################### +# SF bug 705836. "<f" and ">f" had a severe rounding bug, where a carry +# from the low-order discarded bits could propagate into the exponent +# field, causing the result to be wrong by a factor of 2. + +def test_705836(): + import math + + for base in range(1, 33): + # smaller <- largest representable float less than base. + delta = 0.5 + while base - delta / 2.0 != base: + delta /= 2.0 + smaller = base - delta + # Packing this rounds away a solid string of trailing 1 bits. + packed = struct.pack("<f", smaller) + unpacked = struct.unpack("<f", packed)[0] + # This failed at base = 2, 4, and 32, with unpacked = 1, 2, and + # 16, respectively. + verify(base == unpacked) + bigpacked = struct.pack(">f", smaller) + verify(bigpacked == string_reverse(packed), + ">f pack should be byte-reversal of <f pack") + unpacked = struct.unpack(">f", bigpacked)[0] + verify(base == unpacked) + + # Largest finite IEEE single. + big = (1 << 24) - 1 + big = math.ldexp(big, 127 - 23) + packed = struct.pack(">f", big) + unpacked = struct.unpack(">f", packed)[0] + verify(big == unpacked) + + # The same, but tack on a 1 bit so it rounds up to infinity. + big = (1 << 25) - 1 + big = math.ldexp(big, 127 - 24) + try: + packed = struct.pack(">f", big) + except OverflowError: + pass + else: + TestFailed("expected OverflowError") + +test_705836() + +########################################################################### +# SF bug 1229380. No struct.pack exception for some out of range integers + +def test_1229380(): + import sys + for endian in ('', '>', '<'): + for cls in (int, long): + for fmt in ('B', 'H', 'I', 'L'): + deprecated_err(struct.pack, endian + fmt, cls(-1)) + + deprecated_err(struct.pack, endian + 'B', cls(300)) + deprecated_err(struct.pack, endian + 'H', cls(70000)) + + deprecated_err(struct.pack, endian + 'I', sys.maxint * 4L) + deprecated_err(struct.pack, endian + 'L', sys.maxint * 4L) + +if PY_STRUCT_RANGE_CHECKING: + test_1229380() + +########################################################################### +# SF bug 1530559. struct.pack raises TypeError where it used to convert. + +def check_float_coerce(format, number): + if PY_STRUCT_FLOAT_COERCE == 2: + # Test for pre-2.5 struct module + packed = struct.pack(format, number) + floored = struct.unpack(format, packed)[0] + if floored != int(number): + raise TestFailed("did not correcly coerce float to int") + return + try: + func(*args) + except (struct.error, TypeError): + if PY_STRUCT_FLOAT_COERCE: + raise TestFailed("expected DeprecationWarning for float coerce") + except DeprecationWarning: + if not PY_STRUCT_FLOAT_COERCE: + raise TestFailed("expected to raise struct.error for float coerce") + else: + raise TestFailed("did not raise error for float coerce") + +check_float_coerce = with_warning_restore(deprecated_err) + +def test_1530559(): + for endian in ('', '>', '<'): + for fmt in ('B', 'H', 'I', 'L', 'b', 'h', 'i', 'l'): + check_float_coerce(endian + fmt, 1.0) + check_float_coerce(endian + fmt, 1.5) + +test_1530559() + +########################################################################### +# Packing and unpacking to/from buffers. + +# Copied and modified from unittest. +def assertRaises(excClass, callableObj, *args, **kwargs): + try: + callableObj(*args, **kwargs) + except excClass: + return + else: + raise TestFailed("%s not raised." % excClass) + +def test_unpack_from(): + test_string = 'abcd01234' + fmt = '4s' + s = struct.Struct(fmt) + for cls in (str, buffer): + data = cls(test_string) + vereq(s.unpack_from(data), ('abcd',)) + vereq(s.unpack_from(data, 2), ('cd01',)) + vereq(s.unpack_from(data, 4), ('0123',)) + for i in xrange(6): + vereq(s.unpack_from(data, i), (data[i:i+4],)) + for i in xrange(6, len(test_string) + 1): + simple_err(s.unpack_from, data, i) + for cls in (str, buffer): + data = cls(test_string) + vereq(struct.unpack_from(fmt, data), ('abcd',)) + vereq(struct.unpack_from(fmt, data, 2), ('cd01',)) + vereq(struct.unpack_from(fmt, data, 4), ('0123',)) + for i in xrange(6): + vereq(struct.unpack_from(fmt, data, i), (data[i:i+4],)) + for i in xrange(6, len(test_string) + 1): + simple_err(struct.unpack_from, fmt, data, i) + +def test_pack_into(): + test_string = 'Reykjavik rocks, eow!' + writable_buf = array.array('c', ' '*100) + fmt = '21s' + s = struct.Struct(fmt) + + # Test without offset + s.pack_into(writable_buf, 0, test_string) + from_buf = writable_buf.tostring()[:len(test_string)] + vereq(from_buf, test_string) + + # Test with offset. + s.pack_into(writable_buf, 10, test_string) + from_buf = writable_buf.tostring()[:len(test_string)+10] + vereq(from_buf, test_string[:10] + test_string) + + # Go beyond boundaries. + small_buf = array.array('c', ' '*10) + assertRaises(struct.error, s.pack_into, small_buf, 0, test_string) + assertRaises(struct.error, s.pack_into, small_buf, 2, test_string) + +def test_pack_into_fn(): + test_string = 'Reykjavik rocks, eow!' + writable_buf = array.array('c', ' '*100) + fmt = '21s' + pack_into = lambda *args: struct.pack_into(fmt, *args) + + # Test without offset. + pack_into(writable_buf, 0, test_string) + from_buf = writable_buf.tostring()[:len(test_string)] + vereq(from_buf, test_string) + + # Test with offset. + pack_into(writable_buf, 10, test_string) + from_buf = writable_buf.tostring()[:len(test_string)+10] + vereq(from_buf, test_string[:10] + test_string) + + # Go beyond boundaries. + small_buf = array.array('c', ' '*10) + assertRaises(struct.error, pack_into, small_buf, 0, test_string) + assertRaises(struct.error, pack_into, small_buf, 2, test_string) + +def test_unpack_with_buffer(): + # SF bug 1563759: struct.unpack doens't support buffer protocol objects + data = array.array('B', '\x12\x34\x56\x78') + value, = struct.unpack('>I', data) + vereq(value, 0x12345678) + +# Test methods to pack and unpack from buffers rather than strings. +test_unpack_from() +test_pack_into() +test_pack_into_fn() +test_unpack_with_buffer() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |