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: <pj...@us...> - 2011-03-17 22:18:44
|
Revision: 7242 http://jython.svn.sourceforge.net/jython/?rev=7242&view=rev Author: pjenvey Date: 2011-03-17 22:18:37 +0000 (Thu, 17 Mar 2011) Log Message: ----------- update inspect/test_inspect to 2.6 we now pass test_inspect's test_getargspec_method and all of its test_excluding_predicates Modified Paths: -------------- trunk/jython/Lib/inspect.py trunk/jython/Lib/test/test_inspect.py Modified: trunk/jython/Lib/inspect.py =================================================================== --- trunk/jython/Lib/inspect.py 2011-03-16 05:44:13 UTC (rev 7241) +++ trunk/jython/Lib/inspect.py 2011-03-17 22:18:37 UTC (rev 7242) @@ -7,8 +7,9 @@ Here are some of the useful functions provided by this module: - ismodule(), isclass(), ismethod(), isfunction(), istraceback(), - isframe(), iscode(), isbuiltin(), isroutine() - check object types + ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(), + isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(), + isroutine() - check object types getmembers() - get members of an object that satisfy a given condition getfile(), getsourcefile(), getsource() - find an object's source code @@ -28,12 +29,27 @@ __author__ = 'Ka-Ping Yee <pi...@lf...>' __date__ = '1 Jan 2001' -import sys, os, types, string, re, dis, imp, tokenize, linecache +import sys +import os +import types +import string +import re +import dis +import imp +import tokenize +import linecache from operator import attrgetter +from collections import namedtuple _jython = sys.platform.startswith('java') if _jython: _ReflectedFunctionType = type(os.listdir) +# These constants are from Include/code.h. +CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 0x1, 0x2, 0x4, 0x8 +CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40 +# See Include/object.h +TPFLAGS_IS_ABSTRACT = 1 << 20 + # ----------------------------------------------------------- type-checking def ismodule(object): """Return true if the object is a module. @@ -139,6 +155,32 @@ func_name (same as __name__)""" return isinstance(object, types.FunctionType) +def isgeneratorfunction(object): + """Return true if the object is a user-defined generator function. + + Generator function objects provides same attributes as functions. + + See isfunction.__doc__ for attributes listing.""" + return bool((isfunction(object) or ismethod(object)) and + object.func_code.co_flags & CO_GENERATOR) + +def isgenerator(object): + """Return true if the object is a generator. + + Generator objects provide these attributes: + __iter__ defined to support interation over container + close raises a new GeneratorExit exception inside the + generator to terminate the iteration + gi_code code object + gi_frame frame object or possibly None once the generator has + been exhausted + gi_running set to 1 when generator is executing, 0 otherwise + next return the next item from the container + send resumes the generator and "sends" a value that becomes + the result of the current yield-expression + throw used to raise an exception inside the generator""" + return isinstance(object, types.GeneratorType) + def istraceback(object): """Return true if the object is a traceback. @@ -202,6 +244,10 @@ or ismethoddescriptor(object) or (_jython and isinstance(object, _ReflectedFunctionType))) +def isabstract(object): + """Return true if the object is an abstract base class (ABC).""" + return isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT + def getmembers(object, predicate=None): """Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.""" @@ -213,6 +259,8 @@ results.sort() return results +Attribute = namedtuple('Attribute', 'name kind defining_class object') + def classify_class_attrs(cls): """Return list of attribute-descriptor tuples. @@ -279,7 +327,7 @@ else: kind = "data" - result.append((name, kind, homecls, obj)) + result.append(Attribute(name, kind, homecls, obj)) return result @@ -374,15 +422,18 @@ raise TypeError('arg is not a module, class, method, ' 'function, traceback, frame, or code object') +ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type') + def getmoduleinfo(path): """Get the module name, suffix, mode, and module type for a given file.""" filename = os.path.basename(path) - suffixes = map(lambda (suffix, mode, mtype): - (-len(suffix), suffix, mode, mtype), imp.get_suffixes()) + suffixes = map(lambda info: + (-len(info[0]), info[0], info[1], info[2]), + imp.get_suffixes()) suffixes.sort() # try longest suffixes first, in case they overlap for neglen, suffix, mode, mtype in suffixes: if filename[neglen:] == suffix: - return filename[:neglen], suffix, mode, mtype + return ModuleInfo(filename[:neglen], suffix, mode, mtype) def getmodulename(path): """Return the module name for a given file, or None.""" @@ -581,7 +632,9 @@ self.passline = False self.last = 1 - def tokeneater(self, type, token, (srow, scol), (erow, ecol), line): + def tokeneater(self, type, token, srow_scol, erow_ecol, line): + srow, scol = srow_scol + erow, ecol = erow_ecol if not self.started: # look for the first "def", "class" or "lambda" if token in ("def", "class", "lambda"): @@ -679,8 +732,7 @@ return walktree(roots, children, None) # ------------------------------------------------ argument list extraction -# These constants are from Python's compile.h. -CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8 +Arguments = namedtuple('Arguments', 'args varargs keywords') def getargs(co): """Get information about the arguments accepted by a code object. @@ -742,8 +794,10 @@ varkw = None if co.co_flags & CO_VARKEYWORDS: varkw = co.co_varnames[nargs] - return args, varargs, varkw + return Arguments(args, varargs, varkw) +ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults') + def getargspec(func): """Get the names and default values of a function's arguments. @@ -758,8 +812,10 @@ if not isfunction(func): raise TypeError('arg is not a Python function') args, varargs, varkw = getargs(func.func_code) - return args, varargs, varkw, func.func_defaults + return ArgSpec(args, varargs, varkw, func.func_defaults) +ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals') + def getargvalues(frame): """Get information about arguments passed into a particular frame. @@ -768,7 +824,7 @@ 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'locals' is the locals dictionary of the given frame.""" args, varargs, varkw = getargs(frame.f_code) - return args, varargs, varkw, frame.f_locals + return ArgInfo(args, varargs, varkw, frame.f_locals) def joinseq(seq): if len(seq) == 1: @@ -834,6 +890,9 @@ return '(' + string.join(specs, ', ') + ')' # -------------------------------------------------- stack frame extraction + +Traceback = namedtuple('Traceback', 'filename lineno function code_context index') + def getframeinfo(frame, context=1): """Get information about a frame or traceback object. @@ -865,7 +924,7 @@ else: lines = index = None - return (filename, lineno, frame.f_code.co_name, lines, index) + return Traceback(filename, lineno, frame.f_code.co_name, lines, index) def getlineno(frame): """Get the line number from a frame object, allowing for optimization.""" @@ -894,7 +953,10 @@ tb = tb.tb_next return framelist -currentframe = sys._getframe +if hasattr(sys, '_getframe'): + currentframe = sys._getframe +else: + currentframe = lambda _=None: None def stack(context=1): """Return a list of records for the stack above the caller's frame.""" Modified: trunk/jython/Lib/test/test_inspect.py =================================================================== --- trunk/jython/Lib/test/test_inspect.py 2011-03-16 05:44:13 UTC (rev 7241) +++ trunk/jython/Lib/test/test_inspect.py 2011-03-17 22:18:37 UTC (rev 7242) @@ -4,19 +4,24 @@ import inspect import datetime -from test.test_support import TESTFN, run_unittest, is_jython +from test.test_support import is_jython, run_unittest, _check_py3k_warnings -from test import inspect_fodder as mod -from test import inspect_fodder2 as mod2 -from test import test_support +with _check_py3k_warnings( + ("tuple parameter unpacking has been removed", SyntaxWarning), + quiet=True): + from test import inspect_fodder as mod + from test import inspect_fodder2 as mod2 # Functions tested in this suite: # ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode, -# isbuiltin, isroutine, getmembers, getdoc, getfile, getmodule, -# getsourcefile, getcomments, getsource, getclasstree, getargspec, -# getargvalues, formatargspec, formatargvalues, currentframe, stack, trace -# isdatadescriptor +# isbuiltin, isroutine, isgenerator, isgeneratorfunction, getmembers, +# getdoc, getfile, getmodule, getsourcefile, getcomments, getsource, +# getclasstree, getargspec, getargvalues, formatargspec, formatargvalues, +# currentframe, stack, trace, isdatadescriptor +# NOTE: There are some additional tests relating to interaction with +# zipimport in the test_zipimport_support test module. + modfile = mod.__file__ if modfile.endswith(('c', 'o')): modfile = modfile[:-1] @@ -26,7 +31,7 @@ import __builtin__ try: - 1/0 + 1 // 0 except: tb = sys.exc_traceback @@ -44,27 +49,37 @@ class IsTestBase(unittest.TestCase): predicates = set([inspect.isbuiltin, inspect.isclass, inspect.iscode, inspect.isframe, inspect.isfunction, inspect.ismethod, - inspect.ismodule, inspect.istraceback]) + inspect.ismodule, inspect.istraceback, + inspect.isgenerator, inspect.isgeneratorfunction]) def istest(self, predicate, exp): obj = eval(exp) self.failUnless(predicate(obj), '%s(%s)' % (predicate.__name__, exp)) for other in self.predicates - set([predicate]): + if predicate == inspect.isgeneratorfunction and\ + other == inspect.isfunction: + continue self.failIf(other(obj), 'not %s(%s)' % (other.__name__, exp)) +def generator_function_example(self): + for i in xrange(2): + yield i + class TestPredicates(IsTestBase): - def test_thirteen(self): + def test_sixteen(self): count = len(filter(lambda x:x.startswith('is'), dir(inspect))) - # Doc/lib/libinspect.tex claims there are 13 such functions - expected = 13 + # This test is here for remember you to update Doc/library/inspect.rst + # which claims there are 16 such functions + expected = 16 err_msg = "There are %d (not %d) is* functions" % (count, expected) self.assertEqual(count, expected, err_msg) + def test_excluding_predicates(self): - #XXX: Jython's PySystemState needs more work before this - #will be doable. - if not test_support.is_jython: + # XXX: Jython's PySystemState needs more work before this will + # be doable. + if not is_jython: self.istest(inspect.isbuiltin, 'sys.exit') self.istest(inspect.isbuiltin, '[].append') self.istest(inspect.isclass, 'mod.StupidGit') @@ -77,11 +92,12 @@ self.istest(inspect.istraceback, 'tb') self.istest(inspect.isdatadescriptor, '__builtin__.file.closed') self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace') + self.istest(inspect.isgenerator, '(x for x in xrange(2))') + self.istest(inspect.isgeneratorfunction, 'generator_function_example') if hasattr(types, 'GetSetDescriptorType'): self.istest(inspect.isgetsetdescriptor, 'type(tb.tb_frame).f_locals') - #XXX: This detail of PyFrames is not yet supported in Jython - elif not test_support.is_jython: + else: self.failIf(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals)) if hasattr(types, 'MemberDescriptorType'): self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days') @@ -120,7 +136,7 @@ self.assertEqual(git.tr[1][1:], (modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0)) self.assertEqual(git.tr[2][1:], (modfile, 18, 'eggs', - [' q = y / 0\n'], 0)) + [' q = y // 0\n'], 0)) def test_frame(self): args, varargs, varkw, locals = inspect.getargvalues(mod.fr) @@ -194,6 +210,10 @@ self.assertEqual(inspect.getdoc(git.abuse), 'Another\n\ndocstring\n\ncontaining\n\ntabs') + def test_cleandoc(self): + self.assertEqual(inspect.cleandoc('An\n indented\n docstring.'), + 'An\nindented\ndocstring.') + def test_getcomments(self): self.assertEqual(inspect.getcomments(mod), '# line 1\n') self.assertEqual(inspect.getcomments(mod.StupidGit), '# line 20\n') @@ -224,9 +244,9 @@ self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__) def test_getmodule_recursion(self): - from new import module + from types import ModuleType name = '__inspect_dummy' - m = sys.modules[name] = module(name) + m = sys.modules[name] = ModuleType(name) m.__file__ = "<string>" # hopefully not a real filename... m.__loader__ = "dummy" # pretend the filename is understood by a loader exec "def x(): pass" in m.__dict__ @@ -357,7 +377,6 @@ 'g', 'h', (3, (4, (5,))), '(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h)') - @na_for_jython def test_getargspec_method(self): class A(object): def m(self): @@ -366,11 +385,14 @@ @na_for_jython def test_getargspec_sublistofone(self): - def sublistOfOne((foo,)): return 1 - self.assertArgSpecEquals(sublistOfOne, [['foo']]) + with _check_py3k_warnings( + ("tuple parameter unpacking has been removed", SyntaxWarning), + ("parenthesized argument names are invalid", SyntaxWarning)): + exec 'def sublistOfOne((foo,)): return 1' + self.assertArgSpecEquals(sublistOfOne, [['foo']]) - def fakeSublistOfOne((foo)): return 1 - self.assertArgSpecEquals(fakeSublistOfOne, ['foo']) + exec 'def fakeSublistOfOne((foo)): return 1' + self.assertArgSpecEquals(fakeSublistOfOne, ['foo']) def test_classify_oldstyle(self): class A: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2011-03-16 05:44:19
|
Revision: 7241 http://jython.svn.sourceforge.net/jython/?rev=7241&view=rev Author: fwierzbicki Date: 2011-03-16 05:44:13 +0000 (Wed, 16 Mar 2011) Log Message: ----------- Fixes various calls to int() with new numerical literals. Modified Paths: -------------- trunk/jython/src/org/python/core/PyString.java Modified: trunk/jython/src/org/python/core/PyString.java =================================================================== --- trunk/jython/src/org/python/core/PyString.java 2011-03-14 23:09:29 UTC (rev 7240) +++ trunk/jython/src/org/python/core/PyString.java 2011-03-16 05:44:13 UTC (rev 7241) @@ -1587,17 +1587,37 @@ while (b < e && Character.isWhitespace(getString().charAt(b))) b++; } - if (base == 0 || base == 16) { + if (base == 16) { if (getString().charAt(b) == '0') { if (b < e-1 && Character.toUpperCase(getString().charAt(b+1)) == 'X') { + b += 2; + } + } + } else if (base == 0) { + if (getString().charAt(b) == '0') { + if (b < e-1 && Character.toUpperCase(getString().charAt(b+1)) == 'X') { base = 16; b += 2; + } else if (b < e-1 && Character.toUpperCase(getString().charAt(b+1)) == 'O') { + base = 8; + b += 2; + } else if (b < e-1 && Character.toUpperCase(getString().charAt(b+1)) == 'B') { + base = 2; + b += 2; } else { - if (base == 0) - base = 8; + base = 8; } } + } else if (base == 8) { + if (b < e-1 && Character.toUpperCase(getString().charAt(b+1)) == 'O') { + b += 2; + } + } else if (base == 2) { + if (b < e-1 && + Character.toUpperCase(getString().charAt(b+1)) == 'B') { + b += 2; + } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-14 23:09:35
|
Revision: 7240 http://jython.svn.sourceforge.net/jython/?rev=7240&view=rev Author: pjenvey Date: 2011-03-14 23:09:29 +0000 (Mon, 14 Mar 2011) Log Message: ----------- add tuple.index Modified Paths: -------------- trunk/jython/src/org/python/core/PyTuple.java Modified: trunk/jython/src/org/python/core/PyTuple.java =================================================================== --- trunk/jython/src/org/python/core/PyTuple.java 2011-03-14 22:47:30 UTC (rev 7239) +++ trunk/jython/src/org/python/core/PyTuple.java 2011-03-14 23:09:29 UTC (rev 7240) @@ -471,21 +471,51 @@ } } - public int count(PyObject obj) { - return tuple_count(obj); + public int count(PyObject value) { + return tuple_count(value); } @ExposedMethod(doc = BuiltinDocs.tuple_count_doc) - final int tuple_count(PyObject obj) { + final int tuple_count(PyObject value) { int count = 0; for (PyObject item : array) { - if (item.equals(obj)) { + if (item.equals(value)) { count++; } } return count; } + public int index(PyObject value) { + return index(value, 0); + } + + public int index(PyObject value, int start) { + return index(value, start, size()); + } + + public int index(PyObject value, int start, int stop) { + return tuple_index(value, start, stop); + } + + @ExposedMethod(defaults = {"null", "null"}, doc = BuiltinDocs.tuple_index_doc) + final int tuple_index(PyObject value, PyObject start, PyObject stop) { + int startInt = start == null ? 0 : PySlice.calculateSliceIndex(start); + int stopInt = stop == null ? size() : PySlice.calculateSliceIndex(stop); + return tuple_index(value, startInt, stopInt); + } + + final int tuple_index(PyObject value, int start, int stop) { + int validStart = boundToSequence(start); + int validStop = boundToSequence(stop); + for (int i = validStart; i < validStop; i++) { + if (array[i].equals(value)) { + return i; + } + } + throw Py.ValueError("tuple.index(x): x not in list"); + } + @Override public boolean equals(Object other) { if (this == other) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-14 22:47:36
|
Revision: 7239 http://jython.svn.sourceforge.net/jython/?rev=7239&view=rev Author: pjenvey Date: 2011-03-14 22:47:30 +0000 (Mon, 14 Mar 2011) Log Message: ----------- mistakenly didn't reincorporate this line Modified Paths: -------------- trunk/jython/Lib/test/test_support.py Modified: trunk/jython/Lib/test/test_support.py =================================================================== --- trunk/jython/Lib/test/test_support.py 2011-03-14 16:54:14 UTC (rev 7238) +++ trunk/jython/Lib/test/test_support.py 2011-03-14 22:47:30 UTC (rev 7239) @@ -66,6 +66,7 @@ verbose = 1 # Flag set to 0 by regrtest.py use_resources = None # Flag set to [] by regrtest.py +junit_xml_dir = None # Option set by regrtest.py max_memuse = 0 # Disable bigmem tests (they will still be run with # small sizes, to make sure they work.) real_max_memuse = 0 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-14 16:54:21
|
Revision: 7238 http://jython.svn.sourceforge.net/jython/?rev=7238&view=rev Author: pjenvey Date: 2011-03-14 16:54:14 +0000 (Mon, 14 Mar 2011) Log Message: ----------- more includes for 2.6. I think this is all of them except abc/_abcoll/io/ssl Modified Paths: -------------- trunk/jython/CPythonLib.includes Removed Paths: ------------- trunk/jython/Lib/ast.py Modified: trunk/jython/CPythonLib.includes =================================================================== --- trunk/jython/CPythonLib.includes 2011-03-14 16:30:18 UTC (rev 7237) +++ trunk/jython/CPythonLib.includes 2011-03-14 16:54:14 UTC (rev 7238) @@ -18,6 +18,7 @@ _threading_local.py aifc.py anydbm.py +ast.py atexit.py asynchat.py BaseHTTPServer.py @@ -59,8 +60,10 @@ fnmatch.py formatter.py fpformat.py +fractions.py ftplib.py functools.py +genericpath.py getopt.py glob.py gopherlib.py @@ -91,6 +94,7 @@ multifile.py mutex.py nntplib.py +numbers.py nturl2path.py opcode.py optparse.py @@ -98,12 +102,14 @@ pickle.py pickletools.py pipes.py +plistlib.py poplib.py posixfile.py pprint.py profile.py pstats.py pyclbr.py +pydoc_topics.py Queue.py quopri.py random.py Deleted: trunk/jython/Lib/ast.py =================================================================== --- trunk/jython/Lib/ast.py 2011-03-14 16:30:18 UTC (rev 7237) +++ trunk/jython/Lib/ast.py 2011-03-14 16:54:14 UTC (rev 7238) @@ -1,301 +0,0 @@ -# -*- coding: utf-8 -*- -""" - ast - ~~~ - - The `ast` module helps Python applications to process trees of the Python - abstract syntax grammar. The abstract syntax itself might change with - each Python release; this module helps to find out programmatically what - the current grammar looks like and allows modifications of it. - - An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as - a flag to the `compile()` builtin function or by using the `parse()` - function from this module. The result will be a tree of objects whose - classes all inherit from `ast.AST`. - - A modified abstract syntax tree can be compiled into a Python code object - using the built-in `compile()` function. - - Additionally various helper functions are provided that make working with - the trees simpler. The main intention of the helper functions and this - module in general is to provide an easy to use interface for libraries - that work tightly with the python syntax (template engines for example). - - - :copyright: Copyright 2008 by Armin Ronacher. - :license: Python License. -""" -from _ast import * -from _ast import __version__ - - -def parse(expr, filename='<unknown>', mode='exec'): - """ - Parse an expression into an AST node. - Equivalent to compile(expr, filename, mode, PyCF_ONLY_AST). - """ - return compile(expr, filename, mode, PyCF_ONLY_AST) - - -def literal_eval(node_or_string): - """ - Safely evaluate an expression node or a string containing a Python - expression. The string or node provided may only consist of the following - Python literal structures: strings, numbers, tuples, lists, dicts, booleans, - and None. - """ - _safe_names = {'None': None, 'True': True, 'False': False} - if isinstance(node_or_string, basestring): - node_or_string = parse(node_or_string, mode='eval') - if isinstance(node_or_string, Expression): - node_or_string = node_or_string.body - def _convert(node): - if isinstance(node, Str): - return node.s - elif isinstance(node, Num): - return node.n - elif isinstance(node, Tuple): - return tuple(map(_convert, node.elts)) - elif isinstance(node, List): - return list(map(_convert, node.elts)) - elif isinstance(node, Dict): - return dict((_convert(k), _convert(v)) for k, v - in zip(node.keys, node.values)) - elif isinstance(node, Name): - if node.id in _safe_names: - return _safe_names[node.id] - raise ValueError('malformed string') - return _convert(node_or_string) - - -def dump(node, annotate_fields=True, include_attributes=False): - """ - Return a formatted dump of the tree in *node*. This is mainly useful for - debugging purposes. The returned string will show the names and the values - for fields. This makes the code impossible to evaluate, so if evaluation is - wanted *annotate_fields* must be set to False. Attributes such as line - numbers and column offsets are not dumped by default. If this is wanted, - *include_attributes* can be set to True. - """ - def _format(node): - if isinstance(node, AST): - fields = [(a, _format(b)) for a, b in iter_fields(node)] - rv = '%s(%s' % (node.__class__.__name__, ', '.join( - ('%s=%s' % field for field in fields) - if annotate_fields else - (b for a, b in fields) - )) - if include_attributes and node._attributes: - rv += fields and ', ' or ' ' - rv += ', '.join('%s=%s' % (a, _format(getattr(node, a))) - for a in node._attributes) - return rv + ')' - elif isinstance(node, list): - return '[%s]' % ', '.join(_format(x) for x in node) - return repr(node) - if not isinstance(node, AST): - raise TypeError('expected AST, got %r' % node.__class__.__name__) - return _format(node) - - -def copy_location(new_node, old_node): - """ - Copy source location (`lineno` and `col_offset` attributes) from - *old_node* to *new_node* if possible, and return *new_node*. - """ - for attr in 'lineno', 'col_offset': - if attr in old_node._attributes and attr in new_node._attributes \ - and hasattr(old_node, attr): - setattr(new_node, attr, getattr(old_node, attr)) - return new_node - - -def fix_missing_locations(node): - """ - When you compile a node tree with compile(), the compiler expects lineno and - col_offset attributes for every node that supports them. This is rather - tedious to fill in for generated nodes, so this helper adds these attributes - recursively where not already set, by setting them to the values of the - parent node. It works recursively starting at *node*. - """ - def _fix(node, lineno, col_offset): - if 'lineno' in node._attributes: - if not hasattr(node, 'lineno'): - node.lineno = lineno - else: - lineno = node.lineno - if 'col_offset' in node._attributes: - if not hasattr(node, 'col_offset'): - node.col_offset = col_offset - else: - col_offset = node.col_offset - for child in iter_child_nodes(node): - _fix(child, lineno, col_offset) - _fix(node, 1, 0) - return node - - -def increment_lineno(node, n=1): - """ - Increment the line number of each node in the tree starting at *node* by *n*. - This is useful to "move code" to a different location in a file. - """ - if 'lineno' in node._attributes: - node.lineno = getattr(node, 'lineno', 0) + n - for child in walk(node): - if 'lineno' in child._attributes: - child.lineno = getattr(child, 'lineno', 0) + n - return node - - -def iter_fields(node): - """ - Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` - that is present on *node*. - """ - for field in node._fields: - try: - yield field, getattr(node, field) - except AttributeError: - pass - - -def iter_child_nodes(node): - """ - Yield all direct child nodes of *node*, that is, all fields that are nodes - and all items of fields that are lists of nodes. - """ - for name, field in iter_fields(node): - if isinstance(field, AST): - yield field - elif isinstance(field, list): - for item in field: - if isinstance(item, AST): - yield item - - -def get_docstring(node, clean=True): - """ - Return the docstring for the given node or None if no docstring can - be found. If the node provided does not have docstrings a TypeError - will be raised. - """ - if not isinstance(node, (FunctionDef, ClassDef, Module)): - raise TypeError("%r can't have docstrings" % node.__class__.__name__) - if node.body and isinstance(node.body[0], Expr) and \ - isinstance(node.body[0].value, Str): - if clean: - import inspect - return inspect.cleandoc(node.body[0].value.s) - return node.body[0].value.s - - -def walk(node): - """ - Recursively yield all child nodes of *node*, in no specified order. This is - useful if you only want to modify nodes in place and don't care about the - context. - """ - from collections import deque - todo = deque([node]) - while todo: - node = todo.popleft() - todo.extend(iter_child_nodes(node)) - yield node - - -class NodeVisitor(object): - """ - A node visitor base class that walks the abstract syntax tree and calls a - visitor function for every node found. This function may return a value - which is forwarded by the `visit` method. - - This class is meant to be subclassed, with the subclass adding visitor - methods. - - Per default the visitor functions for the nodes are ``'visit_'`` + - class name of the node. So a `TryFinally` node visit function would - be `visit_TryFinally`. This behavior can be changed by overriding - the `visit` method. If no visitor function exists for a node - (return value `None`) the `generic_visit` visitor is used instead. - - Don't use the `NodeVisitor` if you want to apply changes to nodes during - traversing. For this a special visitor exists (`NodeTransformer`) that - allows modifications. - """ - - def visit(self, node): - """Visit a node.""" - method = 'visit_' + node.__class__.__name__ - visitor = getattr(self, method, self.generic_visit) - return visitor(node) - - def generic_visit(self, node): - """Called if no explicit visitor function exists for a node.""" - for field, value in iter_fields(node): - if isinstance(value, list): - for item in value: - if isinstance(item, AST): - self.visit(item) - elif isinstance(value, AST): - self.visit(value) - - -class NodeTransformer(NodeVisitor): - """ - A :class:`NodeVisitor` subclass that walks the abstract syntax tree and - allows modification of nodes. - - The `NodeTransformer` will walk the AST and use the return value of the - visitor methods to replace or remove the old node. If the return value of - the visitor method is ``None``, the node will be removed from its location, - otherwise it is replaced with the return value. The return value may be the - original node in which case no replacement takes place. - - Here is an example transformer that rewrites all occurrences of name lookups - (``foo``) to ``data['foo']``:: - - class RewriteName(NodeTransformer): - - def visit_Name(self, node): - return copy_location(Subscript( - value=Name(id='data', ctx=Load()), - slice=Index(value=Str(s=node.id)), - ctx=node.ctx - ), node) - - Keep in mind that if the node you're operating on has child nodes you must - either transform the child nodes yourself or call the :meth:`generic_visit` - method for the node first. - - For nodes that were part of a collection of statements (that applies to all - statement nodes), the visitor may also return a list of nodes rather than - just a single node. - - Usually you use the transformer like this:: - - node = YourTransformer().visit(node) - """ - - def generic_visit(self, node): - for field, old_value in iter_fields(node): - old_value = getattr(node, field, None) - if isinstance(old_value, list): - new_values = [] - for value in old_value: - if isinstance(value, AST): - value = self.visit(value) - if value is None: - continue - elif not isinstance(value, AST): - new_values.extend(value) - continue - new_values.append(value) - old_value[:] = new_values - elif isinstance(old_value, AST): - new_node = self.visit(old_value) - if new_node is None: - delattr(node, field) - else: - setattr(node, field, new_node) - return node This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-14 16:30:25
|
Revision: 7237 http://jython.svn.sourceforge.net/jython/?rev=7237&view=rev Author: pjenvey Date: 2011-03-14 16:30:18 +0000 (Mon, 14 Mar 2011) Log Message: ----------- add property.getter/setter/deleter Modified Paths: -------------- trunk/jython/src/org/python/core/PyProperty.java Modified: trunk/jython/src/org/python/core/PyProperty.java =================================================================== --- trunk/jython/src/org/python/core/PyProperty.java 2011-03-14 04:31:54 UTC (rev 7236) +++ trunk/jython/src/org/python/core/PyProperty.java 2011-03-14 16:30:18 UTC (rev 7237) @@ -1,3 +1,4 @@ +/* Copyright (c) Jython Developers */ package org.python.core; import org.python.expose.ExposedGet; @@ -19,6 +20,9 @@ @ExposedGet(doc = BuiltinDocs.property_fdel_doc) protected PyObject fdel; + /** Whether this property's __doc__ was copied from its getter. */ + protected boolean docFromGetter; + @ExposedGet(name = "__doc__") protected PyObject doc; @@ -30,9 +34,8 @@ super(subType); } - //XXX: needs __doc__ @ExposedNew - @ExposedMethod + @ExposedMethod(doc = BuiltinDocs.property___init___doc) public void property___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("property", args, keywords, new String[] {"fget", "fset", "fdel", "doc"}, 0); @@ -46,14 +49,24 @@ // if no docstring given and the getter has one, use fget's if ((doc == null || doc == Py.None) && fget != null) { - doc = fget.__findattr__("__doc__"); + PyObject getDoc = fget.__findattr__("__doc__"); + if (getType() == TYPE) { + doc = getDoc; + } else { + // Put __doc__ in dict of the subclass instance instead, otherwise it gets + // shadowed by class's __doc__ + __setattr__("__doc__", getDoc); + } + docFromGetter = true; } } + @Override public PyObject __call__(PyObject arg1, PyObject args[], String keywords[]) { return fget.__call__(arg1); } + @Override public PyObject __get__(PyObject obj, PyObject type) { return property___get__(obj,type); } @@ -69,6 +82,7 @@ return fget.__call__(obj); } + @Override public void __set__(PyObject obj, PyObject value) { property___set__(obj, value); } @@ -81,6 +95,7 @@ fset.__call__(obj, value); } + @Override public void __delete__(PyObject obj) { property___delete__(obj); } @@ -92,4 +107,57 @@ } fdel.__call__(obj); } + + public PyObject getter(PyObject getter) { + return property_getter(getter); + } + + @ExposedMethod(doc = BuiltinDocs.property_getter_doc) + final PyObject property_getter(PyObject getter) { + return propertyCopy(getter, null, null); + } + + public PyObject setter(PyObject setter) { + return property_setter(setter); + } + + @ExposedMethod(doc = BuiltinDocs.property_setter_doc) + final PyObject property_setter(PyObject setter) { + return propertyCopy(null, setter, null); + } + + public PyObject deleter(PyObject deleter) { + return property_deleter(deleter); + } + + @ExposedMethod(doc = BuiltinDocs.property_deleter_doc) + final PyObject property_deleter(PyObject deleter) { + return propertyCopy(null, null, deleter); + } + + /** + * Return a copy of this property with the optional addition of a get/set/del. Helper + * method for the getter/setter/deleter methods. + */ + private PyObject propertyCopy(PyObject get, PyObject set, PyObject del) { + if (get == null) { + get = fget != null ? fget : Py.None; + } + if (set == null) { + set = fset != null ? fset : Py.None; + } + if (del == null) { + del = fdel != null ? fdel : Py.None; + } + + PyObject doc; + if (docFromGetter) { + // make _init use __doc__ from getter + doc = Py.None; + } else { + doc = this.doc != null ? this.doc : Py.None; + } + + return getType().__call__(get, set, del, doc); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-14 04:32:00
|
Revision: 7236 http://jython.svn.sourceforge.net/jython/?rev=7236&view=rev Author: pjenvey Date: 2011-03-14 04:31:54 +0000 (Mon, 14 Mar 2011) Log Message: ----------- reapply our extra_collect fix Modified Paths: -------------- trunk/jython/Lib/test/test_scope.py Modified: trunk/jython/Lib/test/test_scope.py =================================================================== --- trunk/jython/Lib/test/test_scope.py 2011-03-14 04:29:34 UTC (rev 7235) +++ trunk/jython/Lib/test/test_scope.py 2011-03-14 04:31:54 UTC (rev 7236) @@ -1,6 +1,6 @@ import unittest from test.test_support import (check_syntax_error, _check_py3k_warnings, - check_warnings, run_unittest) + check_warnings, is_jython, run_unittest) class ScopeTests(unittest.TestCase): @@ -444,6 +444,11 @@ for i in range(100): f1() + if is_jython: + from test_weakref import extra_collect + # A lot of garbage + for i in range(3): + extra_collect() self.assertEqual(Foo.count, 0) def testClassAndGlobal(self): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-14 04:29:41
|
Revision: 7235 http://jython.svn.sourceforge.net/jython/?rev=7235&view=rev Author: pjenvey Date: 2011-03-14 04:29:34 +0000 (Mon, 14 Mar 2011) Log Message: ----------- from: https://svn.python.org/projects/python/branches/release26-maint/Lib/test/test_scope.py@83635 Modified Paths: -------------- trunk/jython/Lib/test/test_scope.py Modified: trunk/jython/Lib/test/test_scope.py =================================================================== --- trunk/jython/Lib/test/test_scope.py 2011-03-14 03:34:15 UTC (rev 7234) +++ trunk/jython/Lib/test/test_scope.py 2011-03-14 04:29:34 UTC (rev 7235) @@ -1,192 +1,188 @@ -from test.test_support import verify, TestFailed, check_syntax_error, vereq, is_jython +import unittest +from test.test_support import (check_syntax_error, _check_py3k_warnings, + check_warnings, run_unittest) -import warnings -warnings.filterwarnings("ignore", r"import \*", SyntaxWarning, "<string>") -print "1. simple nesting" +class ScopeTests(unittest.TestCase): -def make_adder(x): - def adder(y): - return x + y - return adder + def testSimpleNesting(self): -inc = make_adder(1) -plus10 = make_adder(10) + def make_adder(x): + def adder(y): + return x + y + return adder -vereq(inc(1), 2) -vereq(plus10(-2), 8) + inc = make_adder(1) + plus10 = make_adder(10) -print "2. extra nesting" + self.assertEqual(inc(1), 2) + self.assertEqual(plus10(-2), 8) -def make_adder2(x): - def extra(): # check freevars passing through non-use scopes - def adder(y): - return x + y - return adder - return extra() + def testExtraNesting(self): -inc = make_adder2(1) -plus10 = make_adder2(10) + def make_adder2(x): + def extra(): # check freevars passing through non-use scopes + def adder(y): + return x + y + return adder + return extra() -vereq(inc(1), 2) -vereq(plus10(-2), 8) + inc = make_adder2(1) + plus10 = make_adder2(10) -print "3. simple nesting + rebinding" + self.assertEqual(inc(1), 2) + self.assertEqual(plus10(-2), 8) -def make_adder3(x): - def adder(y): - return x + y - x = x + 1 # check tracking of assignment to x in defining scope - return adder + def testSimpleAndRebinding(self): -inc = make_adder3(0) -plus10 = make_adder3(9) + def make_adder3(x): + def adder(y): + return x + y + x = x + 1 # check tracking of assignment to x in defining scope + return adder -vereq(inc(1), 2) -vereq(plus10(-2), 8) + inc = make_adder3(0) + plus10 = make_adder3(9) -print "4. nesting with global but no free" + self.assertEqual(inc(1), 2) + self.assertEqual(plus10(-2), 8) -def make_adder4(): # XXX add exta level of indirection - def nest(): - def nest(): - def adder(y): - return global_x + y # check that plain old globals work - return adder - return nest() - return nest() + def testNestingGlobalNoFree(self): -global_x = 1 -adder = make_adder4() -vereq(adder(1), 2) + def make_adder4(): # XXX add exta level of indirection + def nest(): + def nest(): + def adder(y): + return global_x + y # check that plain old globals work + return adder + return nest() + return nest() -global_x = 10 -vereq(adder(-2), 8) + global_x = 1 + adder = make_adder4() + self.assertEqual(adder(1), 2) -print "5. nesting through class" + global_x = 10 + self.assertEqual(adder(-2), 8) -def make_adder5(x): - class Adder: - def __call__(self, y): - return x + y - return Adder() + def testNestingThroughClass(self): -inc = make_adder5(1) -plus10 = make_adder5(10) + def make_adder5(x): + class Adder: + def __call__(self, y): + return x + y + return Adder() -vereq(inc(1), 2) -vereq(plus10(-2), 8) + inc = make_adder5(1) + plus10 = make_adder5(10) -print "6. nesting plus free ref to global" + self.assertEqual(inc(1), 2) + self.assertEqual(plus10(-2), 8) -def make_adder6(x): - global global_nest_x - def adder(y): - return global_nest_x + y - global_nest_x = x - return adder + def testNestingPlusFreeRefToGlobal(self): -inc = make_adder6(1) -plus10 = make_adder6(10) + def make_adder6(x): + global global_nest_x + def adder(y): + return global_nest_x + y + global_nest_x = x + return adder -vereq(inc(1), 11) # there's only one global -vereq(plus10(-2), 8) + inc = make_adder6(1) + plus10 = make_adder6(10) -print "7. nearest enclosing scope" + self.assertEqual(inc(1), 11) # there's only one global + self.assertEqual(plus10(-2), 8) -def f(x): - def g(y): - x = 42 # check that this masks binding in f() - def h(z): - return x + z - return h - return g(2) + def testNearestEnclosingScope(self): -test_func = f(10) -vereq(test_func(5), 47) + def f(x): + def g(y): + x = 42 # check that this masks binding in f() + def h(z): + return x + z + return h + return g(2) -print "8. mixed freevars and cellvars" + test_func = f(10) + self.assertEqual(test_func(5), 47) -def identity(x): - return x + def testMixedFreevarsAndCellvars(self): -def f(x, y, z): - def g(a, b, c): - a = a + x # 3 - def h(): - # z * (4 + 9) - # 3 * 13 - return identity(z * (b + y)) - y = c + z # 9 - return h - return g + def identity(x): + return x -g = f(1, 2, 3) -h = g(2, 4, 6) -vereq(h(), 39) + def f(x, y, z): + def g(a, b, c): + a = a + x # 3 + def h(): + # z * (4 + 9) + # 3 * 13 + return identity(z * (b + y)) + y = c + z # 9 + return h + return g -print "9. free variable in method" + g = f(1, 2, 3) + h = g(2, 4, 6) + self.assertEqual(h(), 39) -def test(): - method_and_var = "var" - class Test: - def method_and_var(self): - return "method" - def test(self): - return method_and_var - def actual_global(self): - return str("global") - def str(self): - return str(self) - return Test() + def testFreeVarInMethod(self): -t = test() -vereq(t.test(), "var") -vereq(t.method_and_var(), "method") -vereq(t.actual_global(), "global") + def test(): + method_and_var = "var" + class Test: + def method_and_var(self): + return "method" + def test(self): + return method_and_var + def actual_global(self): + return str("global") + def str(self): + return str(self) + return Test() -method_and_var = "var" -class Test: - # this class is not nested, so the rules are different - def method_and_var(self): - return "method" - def test(self): - return method_and_var - def actual_global(self): - return str("global") - def str(self): - return str(self) + t = test() + self.assertEqual(t.test(), "var") + self.assertEqual(t.method_and_var(), "method") + self.assertEqual(t.actual_global(), "global") -t = Test() -vereq(t.test(), "var") -vereq(t.method_and_var(), "method") -vereq(t.actual_global(), "global") + method_and_var = "var" + class Test: + # this class is not nested, so the rules are different + def method_and_var(self): + return "method" + def test(self): + return method_and_var + def actual_global(self): + return str("global") + def str(self): + return str(self) -print "10. recursion" + t = Test() + self.assertEqual(t.test(), "var") + self.assertEqual(t.method_and_var(), "method") + self.assertEqual(t.actual_global(), "global") -def f(x): - def fact(n): - if n == 0: - return 1 - else: - return n * fact(n - 1) - if x >= 0: - return fact(x) - else: - raise ValueError, "x must be >= 0" + def testRecursion(self): -vereq(f(6), 720) + def f(x): + def fact(n): + if n == 0: + return 1 + else: + return n * fact(n - 1) + if x >= 0: + return fact(x) + else: + raise ValueError, "x must be >= 0" + self.assertEqual(f(6), 720) -print "11. unoptimized namespaces" -class FakeTestCase(object): - def fail(self): - raise TestFailed + def testUnoptimizedNamespaces(self): -fake = FakeTestCase() - -check_syntax_error(fake, """\ + check_syntax_error(self, """\ def unoptimized_clash1(strip): def f(s): from string import * @@ -194,7 +190,7 @@ return f """) -check_syntax_error(fake, """\ + check_syntax_error(self, """\ def unoptimized_clash2(): from string import * def f(s): @@ -202,7 +198,7 @@ return f """) -check_syntax_error(fake, """\ + check_syntax_error(self, """\ def unoptimized_clash2(): from string import * def g(): @@ -211,8 +207,8 @@ return f """) -# XXX could allow this for exec with const argument, but what's the point -check_syntax_error(fake, """\ + # XXX could allow this for exec with const argument, but what's the point + check_syntax_error(self, """\ def error(y): exec "a = 1" def f(x): @@ -220,23 +216,23 @@ return f """) -check_syntax_error(fake, """\ + check_syntax_error(self, """\ def f(x): def g(): return x del x # can't del name """) -check_syntax_error(fake, """\ + check_syntax_error(self, """\ def f(): def g(): - from string import * - return strip # global or local? + from string import * + return strip # global or local? """) -# and verify a few cases that should work + # and verify a few cases that should work -exec """ + exec """ def noproblem1(): from string import * f = lambda x:x @@ -253,59 +249,60 @@ y = x """ -print "12. lambdas" + def testLambdas(self): -f1 = lambda x: lambda y: x + y -inc = f1(1) -plus10 = f1(10) -vereq(inc(1), 2) -vereq(plus10(5), 15) + f1 = lambda x: lambda y: x + y + inc = f1(1) + plus10 = f1(10) + self.assertEqual(inc(1), 2) + self.assertEqual(plus10(5), 15) -f2 = lambda x: (lambda : lambda y: x + y)() -inc = f2(1) -plus10 = f2(10) -vereq(inc(1), 2) -vereq(plus10(5), 15) + f2 = lambda x: (lambda : lambda y: x + y)() + inc = f2(1) + plus10 = f2(10) + self.assertEqual(inc(1), 2) + self.assertEqual(plus10(5), 15) -f3 = lambda x: lambda y: global_x + y -global_x = 1 -inc = f3(None) -vereq(inc(2), 3) + f3 = lambda x: lambda y: global_x + y + global_x = 1 + inc = f3(None) + self.assertEqual(inc(2), 3) -f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y) -g = f8(1, 2, 3) -h = g(2, 4, 6) -vereq(h(), 18) + f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y) + g = f8(1, 2, 3) + h = g(2, 4, 6) + self.assertEqual(h(), 18) -print "13. UnboundLocal" + def testUnboundLocal(self): -def errorInOuter(): - print y - def inner(): - return y - y = 1 + def errorInOuter(): + print y + def inner(): + return y + y = 1 -def errorInInner(): - def inner(): - return y - inner() - y = 1 + def errorInInner(): + def inner(): + return y + inner() + y = 1 -try: - errorInOuter() -except UnboundLocalError: - pass -else: - raise TestFailed + try: + errorInOuter() + except UnboundLocalError: + pass + else: + self.fail() -try: - errorInInner() -except NameError: - pass -else: - raise TestFailed + try: + errorInInner() + except NameError: + pass + else: + self.fail() -# test for bug #1501934: incorrect LOAD/STORE_GLOBAL generation + # test for bug #1501934: incorrect LOAD/STORE_GLOBAL generation + exec """ global_x = 1 def f(): global_x += 1 @@ -314,34 +311,39 @@ except UnboundLocalError: pass else: - raise TestFailed, 'scope of global_x not correctly determined' + fail('scope of global_x not correctly determined') +""" in {'fail': self.fail} -print "14. complex definitions" + def testComplexDefinitions(self): -def makeReturner(*lst): - def returner(): - return lst - return returner + def makeReturner(*lst): + def returner(): + return lst + return returner -vereq(makeReturner(1,2,3)(), (1,2,3)) + self.assertEqual(makeReturner(1,2,3)(), (1,2,3)) -def makeReturner2(**kwargs): - def returner(): - return kwargs - return returner + def makeReturner2(**kwargs): + def returner(): + return kwargs + return returner -vereq(makeReturner2(a=11)()['a'], 11) + self.assertEqual(makeReturner2(a=11)()['a'], 11) + with _check_py3k_warnings(("tuple parameter unpacking has been removed", + SyntaxWarning)): + exec """\ def makeAddPair((a, b)): def addPair((c, d)): return (a + c, b + d) return addPair +""" in locals() + self.assertEqual(makeAddPair((1, 2))((100, 200)), (101,202)) -vereq(makeAddPair((1, 2))((100, 200)), (101,202)) - -print "15. scope of global statements" + def testScopeOfGlobalStmt(self): # Examples posted by Samuele Pedroni to python-dev on 3/1/2001 + exec """\ # I x = 7 def f(): @@ -354,8 +356,8 @@ return h() return i() return g() -vereq(f(), 7) -vereq(x, 7) +self.assertEqual(f(), 7) +self.assertEqual(x, 7) # II x = 7 @@ -369,8 +371,8 @@ return h() return i() return g() -vereq(f(), 2) -vereq(x, 7) +self.assertEqual(f(), 2) +self.assertEqual(x, 7) # III x = 7 @@ -385,8 +387,8 @@ return h() return i() return g() -vereq(f(), 2) -vereq(x, 2) +self.assertEqual(f(), 2) +self.assertEqual(x, 2) # IV x = 7 @@ -401,8 +403,8 @@ return h() return i() return g() -vereq(f(), 2) -vereq(x, 2) +self.assertEqual(f(), 2) +self.assertEqual(x, 2) # XXX what about global statements in class blocks? # do they affect methods? @@ -417,39 +419,36 @@ return x g = Global() -vereq(g.get(), 13) +self.assertEqual(g.get(), 13) g.set(15) -vereq(g.get(), 13) +self.assertEqual(g.get(), 13) +""" -print "16. check leaks" + def testLeaks(self): -class Foo: - count = 0 + class Foo: + count = 0 - def __init__(self): - Foo.count += 1 + def __init__(self): + Foo.count += 1 - def __del__(self): - Foo.count -= 1 + def __del__(self): + Foo.count -= 1 -def f1(): - x = Foo() - def f2(): - return x - f2() + def f1(): + x = Foo() + def f2(): + return x + f2() -for i in range(100): - f1() + for i in range(100): + f1() -if is_jython: - from test_weakref import extra_collect - # A lot of garbage - for i in range(3): - extra_collect() -vereq(Foo.count, 0) + self.assertEqual(Foo.count, 0) -print "17. class and global" + def testClassAndGlobal(self): + exec """\ def test(x): class Foo: global x @@ -458,9 +457,9 @@ return Foo() x = 0 -vereq(test(6)(2), 8) +self.assertEqual(test(6)(2), 8) x = -1 -vereq(test(3)(2), 5) +self.assertEqual(test(3)(2), 5) looked_up_by_load_name = False class X: @@ -469,104 +468,201 @@ locals()['looked_up_by_load_name'] = True passed = looked_up_by_load_name -verify(X.passed) +self.assert_(X.passed) +""" -print "18. verify that locals() works" + def testLocalsFunction(self): -def f(x): - def g(y): - def h(z): - return y + z - w = x + y - y += 3 - return locals() - return g + def f(x): + def g(y): + def h(z): + return y + z + w = x + y + y += 3 + return locals() + return g -d = f(2)(4) -verify(d.has_key('h')) -del d['h'] -vereq(d, {'x': 2, 'y': 7, 'w': 6}) + d = f(2)(4) + self.assertTrue('h' in d) + del d['h'] + self.assertEqual(d, {'x': 2, 'y': 7, 'w': 6}) -print "19. var is bound and free in class" + def testLocalsClass(self): + # This test verifies that calling locals() does not pollute + # the local namespace of the class with free variables. Old + # versions of Python had a bug, where a free variable being + # passed through a class namespace would be inserted into + # locals() by locals() or exec or a trace function. + # + # The real bug lies in frame code that copies variables + # between fast locals and the locals dict, e.g. when executing + # a trace function. -def f(x): - class C: - def m(self): - return x - a = x - return C + def f(x): + class C: + x = 12 + def m(self): + return x + locals() + return C -inst = f(3)() -vereq(inst.a, inst.m()) + self.assertEqual(f(1).x, 12) -print "20. interaction with trace function" + def f(x): + class C: + y = x + def m(self): + return x + z = list(locals()) + return C -import sys -def tracer(a,b,c): - return tracer + varnames = f(1).z + self.assert_("x" not in varnames) + self.assert_("y" in varnames) -def adaptgetter(name, klass, getter): - kind, des = getter - if kind == 1: # AV happens when stepping from this line to next - if des == "": - des = "_%s__%s" % (klass.__name__, name) - return lambda obj: getattr(obj, des) + def testLocalsClass_WithTrace(self): + # Issue23728: after the trace function returns, the locals() + # dictionary is used to update all variables, this used to + # include free variables. But in class statements, free + # variables are not inserted... + import sys + sys.settrace(lambda a,b,c:None) + try: + x = 12 -class TestClass: - pass + class C: + def f(self): + return x -sys.settrace(tracer) -adaptgetter("foo", TestClass, (1, "")) -sys.settrace(None) + self.assertEquals(x, 12) # Used to raise UnboundLocalError + finally: + sys.settrace(None) -try: sys.settrace() -except TypeError: pass -else: raise TestFailed, 'sys.settrace() did not raise TypeError' + def testBoundAndFree(self): + # var is bound and free in class -print "20. eval and exec with free variables" + def f(x): + class C: + def m(self): + return x + a = x + return C -def f(x): - return lambda: x + 1 + inst = f(3)() + self.assertEqual(inst.a, inst.m()) -g = f(3) -try: - eval(g.func_code) -except TypeError: - pass -else: - print "eval() should have failed, because code contained free vars" + def testInteractionWithTraceFunc(self): -try: - exec g.func_code -except TypeError: - pass -else: - print "exec should have failed, because code contained free vars" + import sys + def tracer(a,b,c): + return tracer -print "21. list comprehension with local variables" + def adaptgetter(name, klass, getter): + kind, des = getter + if kind == 1: # AV happens when stepping from this line to next + if des == "": + des = "_%s__%s" % (klass.__name__, name) + return lambda obj: getattr(obj, des) -try: - print bad -except NameError: - pass -else: - print "bad should not be defined" + class TestClass: + pass -def x(): - [bad for s in 'a b' for bad in s.split()] + sys.settrace(tracer) + adaptgetter("foo", TestClass, (1, "")) + sys.settrace(None) -x() -try: - print bad -except NameError: - pass + self.assertRaises(TypeError, sys.settrace) -print "22. eval with free variables" + def testEvalExecFreeVars(self): -def f(x): + def f(x): + return lambda: x + 1 + + g = f(3) + self.assertRaises(TypeError, eval, g.func_code) + + try: + exec g.func_code in {} + except TypeError: + pass + else: + self.fail("exec should have failed, because code contained free vars") + + def testListCompLocalVars(self): + + try: + print bad + except NameError: + pass + else: + print "bad should not be defined" + + def x(): + [bad for s in 'a b' for bad in s.split()] + + x() + try: + print bad + except NameError: + pass + + def testEvalFreeVars(self): + + def f(x): + def g(): + x + eval("x + 1") + return g + + f(4)() + + def testFreeingCell(self): + # Test what happens when a finalizer accesses + # the cell where the object was stored. + class Special: + def __del__(self): + nestedcell_get() + + def f(): + global nestedcell_get + def nestedcell_get(): + return c + + c = (Special(),) + c = 2 + + f() # used to crash the interpreter... + + def testGlobalInParallelNestedFunctions(self): + # A symbol table bug leaked the global statement from one + # function to other nested functions in the same block. + # This test verifies that a global statement in the first + # function does not affect the second function. + CODE = """def f(): + y = 1 def g(): - x - eval("x + 1") - return g + global y + return y + def h(): + return y + 1 + return g, h -f(4)() +y = 9 +g, h = f() +result9 = g() +result2 = h() +""" + local_ns = {} + global_ns = {} + exec CODE in local_ns, global_ns + self.assertEqual(2, global_ns["result2"]) + self.assertEqual(9, global_ns["result9"]) + + +def test_main(): + with check_warnings(("import \* only allowed at module level", + SyntaxWarning)): + run_unittest(ScopeTests) + +if __name__ == '__main__': + test_main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-14 03:34:21
|
Revision: 7234 http://jython.svn.sourceforge.net/jython/?rev=7234&view=rev Author: pjenvey Date: 2011-03-14 03:34:15 +0000 (Mon, 14 Mar 2011) Log Message: ----------- add tuple.count Modified Paths: -------------- trunk/jython/src/org/python/core/PyTuple.java Modified: trunk/jython/src/org/python/core/PyTuple.java =================================================================== --- trunk/jython/src/org/python/core/PyTuple.java 2011-03-14 03:32:44 UTC (rev 7233) +++ trunk/jython/src/org/python/core/PyTuple.java 2011-03-14 03:34:15 UTC (rev 7234) @@ -471,6 +471,21 @@ } } + public int count(PyObject obj) { + return tuple_count(obj); + } + + @ExposedMethod(doc = BuiltinDocs.tuple_count_doc) + final int tuple_count(PyObject obj) { + int count = 0; + for (PyObject item : array) { + if (item.equals(obj)) { + count++; + } + } + return count; + } + @Override public boolean equals(Object other) { if (this == other) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-14 03:32:52
|
Revision: 7233 http://jython.svn.sourceforge.net/jython/?rev=7233&view=rev Author: pjenvey Date: 2011-03-14 03:32:44 +0000 (Mon, 14 Mar 2011) Log Message: ----------- initial rebuild of docs from python 2.6.4 Modified Paths: -------------- trunk/jython/src/org/python/core/BuiltinDocs.java Modified: trunk/jython/src/org/python/core/BuiltinDocs.java =================================================================== --- trunk/jython/src/org/python/core/BuiltinDocs.java 2011-03-14 03:14:37 UTC (rev 7232) +++ trunk/jython/src/org/python/core/BuiltinDocs.java 2011-03-14 03:32:44 UTC (rev 7233) @@ -15,6 +15,9 @@ public final static String object_doc = "The most base type"; + public final static String object___format___doc = + "default object formatter"; + public final static String object___getattribute___doc = "x.__getattribute__('name') <==> x.name"; @@ -39,10 +42,25 @@ public final static String object___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String object___sizeof___doc = + "__sizeof__() -> size of object in memory, in bytes"; + public final static String object___str___doc = "x.__str__() <==> str(x)"; + public final static String object___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + // Docs for <type 'type'> + public final static String type___abstractmethods___doc = + ""; + public final static String type___base___doc = "The most base type"; @@ -59,8 +77,9 @@ "argument will be truncated towards zero (this does not include a string\n" + "representation of a floating point number!) When converting a string, use\n" + "the optional base. It is an error to supply a base when converting a\n" + - "non-string. If the argument is outside the integer range a long object\n" + - "will be returned instead."; + "non-string. If base is zero, the proper base is guessed based on the\n" + + "string content. If the argument is outside the integer range a\n" + + "long object will be returned instead."; public final static String type___call___doc = "x.__call__(...) <==> x(...)"; @@ -85,13 +104,17 @@ "argument will be truncated towards zero (this does not include a string\n" + "representation of a floating point number!) When converting a string, use\n" + "the optional base. It is an error to supply a base when converting a\n" + - "non-string. If the argument is outside the integer range a long object\n" + - "will be returned instead."; + "non-string. If base is zero, the proper base is guessed based on the\n" + + "string content. If the argument is outside the integer range a\n" + + "long object will be returned instead."; public final static String type_doc = "type(object) -> the object's type\n" + "type(name, bases, dict) -> a new type"; + public final static String type___eq___doc = + "x.__eq__(y) <==> x==y"; + public final static String type___flags___doc = "int(x[, base]) -> integer\n" + "\n" + @@ -99,18 +122,31 @@ "argument will be truncated towards zero (this does not include a string\n" + "representation of a floating point number!) When converting a string, use\n" + "the optional base. It is an error to supply a base when converting a\n" + - "non-string. If the argument is outside the integer range a long object\n" + - "will be returned instead."; + "non-string. If base is zero, the proper base is guessed based on the\n" + + "string content. If the argument is outside the integer range a\n" + + "long object will be returned instead."; + public final static String type___format___doc = + "default object formatter"; + + public final static String type___ge___doc = + "x.__ge__(y) <==> x>=y"; + public final static String type___getattribute___doc = "x.__getattribute__('name') <==> x.name"; + public final static String type___gt___doc = + "x.__gt__(y) <==> x>y"; + public final static String type___hash___doc = "x.__hash__() <==> hash(x)"; public final static String type___init___doc = "x.__init__(...) initializes x; see x.__class__.__doc__ for signature"; + public final static String type___instancecheck___doc = + ""; + public final static String type___itemsize___doc = "int(x[, base]) -> integer\n" + "\n" + @@ -118,9 +154,16 @@ "argument will be truncated towards zero (this does not include a string\n" + "representation of a floating point number!) When converting a string, use\n" + "the optional base. It is an error to supply a base when converting a\n" + - "non-string. If the argument is outside the integer range a long object\n" + - "will be returned instead."; + "non-string. If base is zero, the proper base is guessed based on the\n" + + "string content. If the argument is outside the integer range a\n" + + "long object will be returned instead."; + public final static String type___le___doc = + "x.__le__(y) <==> x<=y"; + + public final static String type___lt___doc = + "x.__lt__(y) <==> x<y"; + public final static String type___module___doc = "str(object) -> string\n" + "\n" + @@ -139,6 +182,9 @@ "Return a nice string representation of the object.\n" + "If the argument is a string, the return value is the same object."; + public final static String type___ne___doc = + "x.__ne__(y) <==> x!=y"; + public final static String type___new___doc = "T.__new__(S, ...) -> a new object with type S, a subtype of T"; @@ -154,12 +200,27 @@ public final static String type___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String type___sizeof___doc = + "__sizeof__() -> size of object in memory, in bytes"; + public final static String type___str___doc = "x.__str__() <==> str(x)"; + public final static String type___subclasscheck___doc = + ""; + public final static String type___subclasses___doc = "__subclasses__() -> list of immediate subclasses"; + public final static String type___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + public final static String type___weakrefoffset___doc = "int(x[, base]) -> integer\n" + "\n" + @@ -167,8 +228,9 @@ "argument will be truncated towards zero (this does not include a string\n" + "representation of a floating point number!) When converting a string, use\n" + "the optional base. It is an error to supply a base when converting a\n" + - "non-string. If the argument is outside the integer range a long object\n" + - "will be returned instead."; + "non-string. If base is zero, the proper base is guessed based on the\n" + + "string content. If the argument is outside the integer range a\n" + + "long object will be returned instead."; public final static String type_mro_doc = "mro() -> list\n" + @@ -198,6 +260,11 @@ public final static String unicode___eq___doc = "x.__eq__(y) <==> x==y"; + public final static String unicode___format___doc = + "S.__format__(format_spec) -> unicode\n" + + "\n" + + ""; + public final static String unicode___ge___doc = "x.__ge__(y) <==> x>=y"; @@ -212,8 +279,8 @@ public final static String unicode___getslice___doc = "x.__getslice__(i, j) <==> x[i:j]\n" + - " \n" + - " Use of negative indices is not supported."; + " \n" + + " Use of negative indices is not supported."; public final static String unicode___gt___doc = "x.__gt__(y) <==> x>y"; @@ -263,9 +330,29 @@ public final static String unicode___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String unicode___sizeof___doc = + "S.__sizeof__() -> size of S in memory, in bytes\n" + + "\n" + + ""; + public final static String unicode___str___doc = "x.__str__() <==> str(x)"; + public final static String unicode___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + + public final static String unicode__formatter_field_name_split_doc = + ""; + + public final static String unicode__formatter_parser_doc = + ""; + public final static String unicode_capitalize_doc = "S.capitalize() -> unicode\n" + "\n" + @@ -323,11 +410,16 @@ "S.find(sub [,start [,end]]) -> int\n" + "\n" + "Return the lowest index in S where substring sub is found,\n" + - "such that sub is contained within s[start,end]. Optional\n" + + "such that sub is contained within s[start:end]. Optional\n" + "arguments start and end are interpreted as in slice notation.\n" + "\n" + "Return -1 on failure."; + public final static String unicode_format_doc = + "S.format(*args, **kwargs) -> unicode\n" + + "\n" + + ""; + public final static String unicode_index_doc = "S.index(sub [,start [,end]]) -> int\n" + "\n" + @@ -398,7 +490,7 @@ public final static String unicode_ljust_doc = "S.ljust(width[, fillchar]) -> int\n" + "\n" + - "Return S left justified in a Unicode string of length width. Padding is\n" + + "Return S left-justified in a Unicode string of length width. Padding is\n" + "done using the specified fill character (default is a space)."; public final static String unicode_lower_doc = @@ -416,22 +508,22 @@ public final static String unicode_partition_doc = "S.partition(sep) -> (head, sep, tail)\n" + "\n" + - "Searches for the separator sep in S, and returns the part before it,\n" + + "Search for the separator sep in S, and return the part before it,\n" + "the separator itself, and the part after it. If the separator is not\n" + - "found, returns S and two empty strings."; + "found, return S and two empty strings."; public final static String unicode_replace_doc = - "S.replace (old, new[, maxsplit]) -> unicode\n" + + "S.replace (old, new[, count]) -> unicode\n" + "\n" + "Return a copy of S with all occurrences of substring\n" + - "old replaced by new. If the optional argument maxsplit is\n" + - "given, only the first maxsplit occurrences are replaced."; + "old replaced by new. If the optional argument count is\n" + + "given, only the first count occurrences are replaced."; public final static String unicode_rfind_doc = "S.rfind(sub [,start [,end]]) -> int\n" + "\n" + "Return the highest index in S where substring sub is found,\n" + - "such that sub is contained within s[start,end]. Optional\n" + + "such that sub is contained within s[start:end]. Optional\n" + "arguments start and end are interpreted as in slice notation.\n" + "\n" + "Return -1 on failure."; @@ -444,15 +536,15 @@ public final static String unicode_rjust_doc = "S.rjust(width[, fillchar]) -> unicode\n" + "\n" + - "Return S right justified in a Unicode string of length width. Padding is\n" + + "Return S right-justified in a Unicode string of length width. Padding is\n" + "done using the specified fill character (default is a space)."; public final static String unicode_rpartition_doc = "S.rpartition(sep) -> (tail, sep, head)\n" + "\n" + - "Searches for the separator sep in S, starting at the end of S, and returns\n" + + "Search for the separator sep in S, starting at the end of S, and return\n" + "the part before it, the separator itself, and the part after it. If the\n" + - "separator is not found, returns two empty strings and S."; + "separator is not found, return two empty strings and S."; public final static String unicode_rsplit_doc = "S.rsplit([sep [,maxsplit]]) -> list of strings\n" + @@ -475,11 +567,12 @@ "\n" + "Return a list of the words in S, using sep as the\n" + "delimiter string. If maxsplit is given, at most maxsplit\n" + - "splits are done. If sep is not specified or is None,\n" + - "any whitespace string is a separator."; + "splits are done. If sep is not specified or is None, any\n" + + "whitespace string is a separator and empty strings are\n" + + "removed from the result."; public final static String unicode_splitlines_doc = - "S.splitlines([keepends]]) -> list of strings\n" + + "S.splitlines([keepends]) -> list of strings\n" + "\n" + "Return a list of the lines in S, breaking at line boundaries.\n" + "Line breaks are not included in the resulting list unless keepends\n" + @@ -530,8 +623,8 @@ public final static String unicode_zfill_doc = "S.zfill(width) -> unicode\n" + "\n" + - "Pad a numeric string x with zeros on the left, to fill a field\n" + - "of the specified width. The string x is never truncated."; + "Pad a numeric string S with zeros on the left, to fill a field\n" + + "of the specified width. The string S is never truncated."; // Docs for <type 'dict'> public final static String dict___class___doc = @@ -564,6 +657,9 @@ public final static String dict___eq___doc = "x.__eq__(y) <==> x==y"; + public final static String dict___format___doc = + "default object formatter"; + public final static String dict___ge___doc = "x.__ge__(y) <==> x>=y"; @@ -577,7 +673,7 @@ "x.__gt__(y) <==> x>y"; public final static String dict___hash___doc = - "x.__hash__() <==> hash(x)"; + ""; public final static String dict___init___doc = "x.__init__(...) initializes x; see x.__class__.__doc__ for signature"; @@ -615,9 +711,21 @@ public final static String dict___setitem___doc = "x.__setitem__(i, y) <==> x[i]=y"; + public final static String dict___sizeof___doc = + "D.__sizeof__() -> size of D in memory, in bytes"; + public final static String dict___str___doc = "x.__str__() <==> str(x)"; + public final static String dict___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + public final static String dict_clear_doc = "D.clear() -> None. Remove all items from D."; @@ -650,19 +758,21 @@ "D.keys() -> list of D's keys"; public final static String dict_pop_doc = - "D.pop(k[,d]) -> v, remove specified key and return the corresponding value\n" + + "D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n" + "If key is not found, d is returned if given, otherwise KeyError is raised"; public final static String dict_popitem_doc = "D.popitem() -> (k, v), remove and return some (key, value) pair as a\n" + - "2-tuple; but raise KeyError if D is empty"; + "2-tuple; but raise KeyError if D is empty."; public final static String dict_setdefault_doc = "D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D"; public final static String dict_update_doc = - "D.update(E, **F) -> None. Update D from E and F: for k in E: D[k] = E[k]\n" + - "(if E has keys else: for (k, v) in E: D[k] = v) then: for k in F: D[k] = F[k]"; + "D.update(E, **F) -> None. Update D from dict/iterable E and F.\n" + + "If E has a .keys() method, does: for k in E: D[k] = E[k]\n" + + "If E lacks .keys() method, does: for (k, v) in E: D[k] = v\n" + + "In either case, this is followed by: for k in F: D[k] = F[k]"; public final static String dict_values_doc = "D.values() -> list of D's values"; @@ -686,8 +796,8 @@ public final static String list___delslice___doc = "x.__delslice__(i, j) <==> del x[i:j]\n" + - " \n" + - " Use of negative indices is not supported."; + " \n" + + " Use of negative indices is not supported."; public final static String list_doc = "list() -> new list\n" + @@ -696,6 +806,9 @@ public final static String list___eq___doc = "x.__eq__(y) <==> x==y"; + public final static String list___format___doc = + "default object formatter"; + public final static String list___ge___doc = "x.__ge__(y) <==> x>=y"; @@ -707,14 +820,14 @@ public final static String list___getslice___doc = "x.__getslice__(i, j) <==> x[i:j]\n" + - " \n" + - " Use of negative indices is not supported."; + " \n" + + " Use of negative indices is not supported."; public final static String list___gt___doc = "x.__gt__(y) <==> x>y"; public final static String list___hash___doc = - "x.__hash__() <==> hash(x)"; + ""; public final static String list___iadd___doc = "x.__iadd__(y) <==> x+=y"; @@ -769,12 +882,24 @@ public final static String list___setslice___doc = "x.__setslice__(i, j, y) <==> x[i:j]=y\n" + - " \n" + - " Use of negative indices is not supported."; + " \n" + + " Use of negative indices is not supported."; + public final static String list___sizeof___doc = + "L.__sizeof__() -- size of L in memory, in bytes"; + public final static String list___str___doc = "x.__str__() <==> str(x)"; + public final static String list___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + public final static String list_append_doc = "L.append(object) -- append object to end"; @@ -785,16 +910,19 @@ "L.extend(iterable) -- extend list by appending elements from the iterable"; public final static String list_index_doc = - "L.index(value, [start, [stop]]) -> integer -- return first index of value"; + "L.index(value, [start, [stop]]) -> integer -- return first index of value.\n" + + "Raises ValueError if the value is not present."; public final static String list_insert_doc = "L.insert(index, object) -- insert object before index"; public final static String list_pop_doc = - "L.pop([index]) -> item -- remove and return item at index (default last)"; + "L.pop([index]) -> item -- remove and return item at index (default last).\n" + + "Raises IndexError if list is empty or index is out of range."; public final static String list_remove_doc = - "L.remove(value) -- remove first occurrence of value"; + "L.remove(value) -- remove first occurrence of value.\n" + + "Raises ValueError if the value is not present."; public final static String list_reverse_doc = "L.reverse() -- reverse *IN PLACE*"; @@ -819,6 +947,9 @@ "\n" + "Create a slice object. This is used for extended slicing (e.g. a[0:10:2])."; + public final static String slice___format___doc = + "default object formatter"; + public final static String slice___getattribute___doc = "x.__getattribute__('name') <==> x.name"; @@ -832,7 +963,7 @@ "T.__new__(S, ...) -> a new object with type S, a subtype of T"; public final static String slice___reduce___doc = - "helper for pickle"; + "Return state information for pickling."; public final static String slice___reduce_ex___doc = "helper for pickle"; @@ -843,9 +974,21 @@ public final static String slice___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String slice___sizeof___doc = + "__sizeof__() -> size of object in memory, in bytes"; + public final static String slice___str___doc = "x.__str__() <==> str(x)"; + public final static String slice___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + public final static String slice_indices_doc = "S.indices(len) -> (start, stop, stride)\n" + "\n" + @@ -878,8 +1021,11 @@ "Typical use to call a cooperative superclass method:\n" + "class C(B):\n" + " def meth(self, arg):\n" + - " super(C, self).meth(arg)"; + " super(C, self).meth(arg)"; + public final static String super___format___doc = + "default object formatter"; + public final static String super___get___doc = "descr.__get__(obj[, type]) -> value"; @@ -913,9 +1059,21 @@ public final static String super___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String super___sizeof___doc = + "__sizeof__() -> size of object in memory, in bytes"; + public final static String super___str___doc = "x.__str__() <==> str(x)"; + public final static String super___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + public final static String super___thisclass___doc = "the class invoking super()"; @@ -945,6 +1103,9 @@ "Static methods in Python are similar to those found in Java or C++.\n" + "For a more advanced concept, see the classmethod builtin."; + public final static String staticmethod___format___doc = + "default object formatter"; + public final static String staticmethod___get___doc = "descr.__get__(obj[, type]) -> value"; @@ -972,9 +1133,21 @@ public final static String staticmethod___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String staticmethod___sizeof___doc = + "__sizeof__() -> size of object in memory, in bytes"; + public final static String staticmethod___str___doc = "x.__str__() <==> str(x)"; + public final static String staticmethod___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + // Docs for <type 'float'> public final static String float___abs___doc = "x.__abs__() <==> abs(x)"; @@ -1012,6 +1185,11 @@ public final static String float___floordiv___doc = "x.__floordiv__(y) <==> x//y"; + public final static String float___format___doc = + "float.__format__(format_spec) -> string\n" + + "\n" + + "Formats the float according to format_spec."; + public final static String float___ge___doc = "x.__ge__(y) <==> x>=y"; @@ -1128,15 +1306,74 @@ "Overrides the automatic determination of C-level floating point type.\n" + "This affects how floats are converted to and from binary strings."; + public final static String float___sizeof___doc = + "__sizeof__() -> size of object in memory, in bytes"; + public final static String float___str___doc = "x.__str__() <==> str(x)"; public final static String float___sub___doc = "x.__sub__(y) <==> x-y"; + public final static String float___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + public final static String float___truediv___doc = "x.__truediv__(y) <==> x/y"; + public final static String float___trunc___doc = + "Returns the Integral closest to x between 0 and x."; + + public final static String float_as_integer_ratio_doc = + "float.as_integer_ratio() -> (int, int)\n" + + "\n" + + "Returns a pair of integers, whose ratio is exactly equal to the original\n" + + "float and with a positive denominator.\n" + + "Raises OverflowError on infinities and a ValueError on NaNs.\n" + + "\n" + + ">>> (10.0).as_integer_ratio()\n" + + "(10, 1)\n" + + ">>> (0.0).as_integer_ratio()\n" + + "(0, 1)\n" + + ">>> (-.25).as_integer_ratio()\n" + + "(-1, 4)"; + + public final static String float_conjugate_doc = + "Returns self, the complex conjugate of any float."; + + public final static String float_fromhex_doc = + "float.fromhex(string) -> float\n" + + "\n" + + "Create a floating-point number from a hexadecimal string.\n" + + ">>> float.fromhex('0x1.ffffp10')\n" + + "2047.984375\n" + + ">>> float.fromhex('-0x1p-1074')\n" + + "-4.9406564584124654e-324"; + + public final static String float_hex_doc = + "float.hex() -> string\n" + + "\n" + + "Return a hexadecimal representation of a floating-point number.\n" + + ">>> (-0.1).hex()\n" + + "'-0x1.999999999999ap-4'\n" + + ">>> 3.14159.hex()\n" + + "'0x1.921f9f01b866ep+1'"; + + public final static String float_imag_doc = + "the imaginary part of a complex number"; + + public final static String float_is_integer_doc = + "Returns True if the float is an integer."; + + public final static String float_real_doc = + "the real part of a complex number"; + // Docs for <type 'enumerate'> public final static String enumerate___class___doc = "type(object) -> the object's type\n" + @@ -1148,11 +1385,14 @@ public final static String enumerate_doc = "enumerate(iterable) -> iterator for index, value of iterable\n" + "\n" + - "Return an enumerate object. iterable must be an other object that supports\n" + + "Return an enumerate object. iterable must be another object that supports\n" + "iteration. The enumerate object yields pairs containing a count (from\n" + "zero) and a value yielded by the iterable argument. enumerate is useful\n" + "for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ..."; + public final static String enumerate___format___doc = + "default object formatter"; + public final static String enumerate___getattribute___doc = "x.__getattribute__('name') <==> x.name"; @@ -1180,9 +1420,21 @@ public final static String enumerate___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String enumerate___sizeof___doc = + "__sizeof__() -> size of object in memory, in bytes"; + public final static String enumerate___str___doc = "x.__str__() <==> str(x)"; + public final static String enumerate___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + public final static String enumerate_next_doc = "x.next() -> the next value, or raise StopIteration"; @@ -1197,6 +1449,9 @@ public final static String basestring_doc = "Type basestring cannot be instantiated; it is the base for str and unicode."; + public final static String basestring___format___doc = + "default object formatter"; + public final static String basestring___getattribute___doc = "x.__getattribute__('name') <==> x.name"; @@ -1221,9 +1476,21 @@ public final static String basestring___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String basestring___sizeof___doc = + "__sizeof__() -> size of object in memory, in bytes"; + public final static String basestring___str___doc = "x.__str__() <==> str(x)"; + public final static String basestring___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + // Docs for <type 'long'> public final static String long___abs___doc = "x.__abs__() <==> abs(x)"; @@ -1268,6 +1535,9 @@ public final static String long___floordiv___doc = "x.__floordiv__(y) <==> x//y"; + public final static String long___format___doc = + ""; + public final static String long___getattribute___doc = "x.__getattribute__('name') <==> x.name"; @@ -1382,18 +1652,48 @@ public final static String long___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String long___sizeof___doc = + "Returns size in memory, in bytes"; + public final static String long___str___doc = "x.__str__() <==> str(x)"; public final static String long___sub___doc = "x.__sub__(y) <==> x-y"; + public final static String long___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + public final static String long___truediv___doc = "x.__truediv__(y) <==> x/y"; + public final static String long___trunc___doc = + "Truncating an Integral returns itself."; + public final static String long___xor___doc = "x.__xor__(y) <==> x^y"; + public final static String long_conjugate_doc = + "Returns self, the complex conjugate of any long."; + + public final static String long_denominator_doc = + "the denominator of a rational number in lowest terms"; + + public final static String long_imag_doc = + "the imaginary part of a complex number"; + + public final static String long_numerator_doc = + "the numerator of a rational number in lowest terms"; + + public final static String long_real_doc = + "the real part of a complex number"; + // Docs for <type 'tuple'> public final static String tuple___add___doc = "x.__add__(y) <==> x+y"; @@ -1417,6 +1717,9 @@ public final static String tuple___eq___doc = "x.__eq__(y) <==> x==y"; + public final static String tuple___format___doc = + "default object formatter"; + public final static String tuple___ge___doc = "x.__ge__(y) <==> x>=y"; @@ -1431,8 +1734,8 @@ public final static String tuple___getslice___doc = "x.__getslice__(i, j) <==> x[i:j]\n" + - " \n" + - " Use of negative indices is not supported."; + " \n" + + " Use of negative indices is not supported."; public final static String tuple___gt___doc = "x.__gt__(y) <==> x>y"; @@ -1479,9 +1782,28 @@ public final static String tuple___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String tuple___sizeof___doc = + "T.__sizeof__() -- size of T in memory, in bytes"; + public final static String tuple___str___doc = "x.__str__() <==> str(x)"; + public final static String tuple___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + + public final static String tuple_count_doc = + "T.count(value) -> integer -- return number of occurrences of value"; + + public final static String tuple_index_doc = + "T.index(value, [start, [stop]]) -> integer -- return first index of value.\n" + + "Raises ValueError if the value is not present."; + // Docs for <type 'str'> public final static String str___add___doc = "x.__add__(y) <==> x+y"; @@ -1505,6 +1827,11 @@ public final static String str___eq___doc = "x.__eq__(y) <==> x==y"; + public final static String str___format___doc = + "S.__format__(format_spec) -> unicode\n" + + "\n" + + ""; + public final static String str___ge___doc = "x.__ge__(y) <==> x>=y"; @@ -1519,8 +1846,8 @@ public final static String str___getslice___doc = "x.__getslice__(i, j) <==> x[i:j]\n" + - " \n" + - " Use of negative indices is not supported."; + " \n" + + " Use of negative indices is not supported."; public final static String str___gt___doc = "x.__gt__(y) <==> x>y"; @@ -1570,9 +1897,27 @@ public final static String str___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String str___sizeof___doc = + "S.__sizeof__() -> size of S in memory, in bytes"; + public final static String str___str___doc = "x.__str__() <==> str(x)"; + public final static String str___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + + public final static String str__formatter_field_name_split_doc = + ""; + + public final static String str__formatter_parser_doc = + ""; + public final static String str_capitalize_doc = "S.capitalize() -> string\n" + "\n" + @@ -1599,7 +1944,7 @@ "to the default encoding. errors may be given to set a different error\n" + "handling scheme. Default is 'strict' meaning that encoding errors raise\n" + "a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n" + - "as well as any other name registerd with codecs.register_error that is\n" + + "as well as any other name registered with codecs.register_error that is\n" + "able to handle UnicodeDecodeErrors."; public final static String str_encode_doc = @@ -1630,11 +1975,16 @@ "S.find(sub [,start [,end]]) -> int\n" + "\n" + "Return the lowest index in S where substring sub is found,\n" + - "such that sub is contained within s[start,end]. Optional\n" + + "such that sub is contained within s[start:end]. Optional\n" + "arguments start and end are interpreted as in slice notation.\n" + "\n" + "Return -1 on failure."; + public final static String str_format_doc = + "S.format(*args, **kwargs) -> unicode\n" + + "\n" + + ""; + public final static String str_index_doc = "S.index(sub [,start [,end]]) -> int\n" + "\n" + @@ -1693,7 +2043,7 @@ public final static String str_ljust_doc = "S.ljust(width[, fillchar]) -> string\n" + "\n" + - "Return S left justified in a string of length width. Padding is\n" + + "Return S left-justified in a string of length width. Padding is\n" + "done using the specified fill character (default is a space)."; public final static String str_lower_doc = @@ -1711,9 +2061,9 @@ public final static String str_partition_doc = "S.partition(sep) -> (head, sep, tail)\n" + "\n" + - "Searches for the separator sep in S, and returns the part before it,\n" + + "Search for the separator sep in S, and return the part before it,\n" + "the separator itself, and the part after it. If the separator is not\n" + - "found, returns S and two empty strings."; + "found, return S and two empty strings."; public final static String str_replace_doc = "S.replace (old, new[, count]) -> string\n" + @@ -1726,7 +2076,7 @@ "S.rfind(sub [,start [,end]]) -> int\n" + "\n" + "Return the highest index in S where substring sub is found,\n" + - "such that sub is contained within s[start,end]. Optional\n" + + "such that sub is contained within s[start:end]. Optional\n" + "arguments start and end are interpreted as in slice notation.\n" + "\n" + "Return -1 on failure."; @@ -1739,15 +2089,15 @@ public final static String str_rjust_doc = "S.rjust(width[, fillchar]) -> string\n" + "\n" + - "Return S right justified in a string of length width. Padding is\n" + + "Return S right-justified in a string of length width. Padding is\n" + "done using the specified fill character (default is a space)"; public final static String str_rpartition_doc = "S.rpartition(sep) -> (tail, sep, head)\n" + "\n" + - "Searches for the separator sep in S, starting at the end of S, and returns\n" + + "Search for the separator sep in S, starting at the end of S, and return\n" + "the part before it, the separator itself, and the part after it. If the\n" + - "separator is not found, returns two empty strings and S."; + "separator is not found, return two empty strings and S."; public final static String str_rsplit_doc = "S.rsplit([sep [,maxsplit]]) -> list of strings\n" + @@ -1771,7 +2121,8 @@ "Return a list of the words in the string S, using sep as the\n" + "delimiter string. If maxsplit is given, at most maxsplit\n" + "splits are done. If sep is not specified or is None, any\n" + - "whitespace string is a separator."; + "whitespace string is a separator and empty strings are removed\n" + + "from the result."; public final static String str_splitlines_doc = "S.splitlines([keepends]) -> list of strings\n" + @@ -1845,11 +2196,24 @@ "fset is a function for setting, and fdel a function for del'ing, an\n" + "attribute. Typical use is to define a managed attribute x:\n" + "class C(object):\n" + - " def getx(self): return self.__x\n" + - " def setx(self, value): self.__x = value\n" + - " def delx(self): del self.__x\n" + - " x = property(getx, setx, delx, \"I'm the 'x' property.\")"; + " def getx(self): return self._x\n" + + " def setx(self, value): self._x = value\n" + + " def delx(self): del self._x\n" + + " x = property(getx, setx, delx, \"I'm the 'x' property.\")\n" + + "\n" + + "Decorators make defining new properties or modifying existing ones easy:\n" + + "class C(object):\n" + + " @property\n" + + " def x(self): return self._x\n" + + " @x.setter\n" + + " def x(self, value): self._x = value\n" + + " @x.deleter\n" + + " def x(self): del self._x\n" + + ""; + public final static String property___format___doc = + "default object formatter"; + public final static String property___get___doc = "descr.__get__(obj[, type]) -> value"; @@ -1880,9 +2244,24 @@ public final static String property___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String property___sizeof___doc = + "__sizeof__() -> size of object in memory, in bytes"; + public final static String property___str___doc = "x.__str__() <==> str(x)"; + public final static String property___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + + public final static String property_deleter_doc = + "Descriptor to change the deleter on a property."; + public final static String property_fdel_doc = ""; @@ -1892,6 +2271,12 @@ public final static String property_fset_doc = ""; + public final static String property_getter_doc = + "Descriptor to change the getter on a property."; + + public final static String property_setter_doc = + "Descriptor to change the setter on a property."; + // Docs for <type 'int'> public final static String int___abs___doc = "x.__abs__() <==> abs(x)"; @@ -1928,8 +2313,9 @@ "argument will be truncated towards zero (this does not include a string\n" + "representation of a floating point number!) When converting a string, use\n" + "the optional base. It is an error to supply a base when converting a\n" + - "non-string. If the argument is outside the integer range a long object\n" + - "will be returned instead."; + "non-string. If base is zero, the proper base is guessed based on the\n" + + "string content. If the argument is outside the integer range a\n" + + "long object will be returned instead."; public final static String int___float___doc = "x.__float__() <==> float(x)"; @@ -1937,6 +2323,9 @@ public final static String int___floordiv___doc = "x.__floordiv__(y) <==> x//y"; + public final static String int___format___doc = + ""; + public final static String int___getattribute___doc = "x.__getattribute__('name') <==> x.name"; @@ -2051,18 +2440,48 @@ public final static String int___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String int___sizeof___doc = + "__sizeof__() -> size of object in memory, in bytes"; + public final static String int___str___doc = "x.__str__() <==> str(x)"; public final static String int___sub___doc = "x.__sub__(y) <==> x-y"; + public final static String int___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + public final static String int___truediv___doc = "x.__truediv__(y) <==> x/y"; + public final static String int___trunc___doc = + "Truncating an Integral returns itself."; + public final static String int___xor___doc = "x.__xor__(y) <==> x^y"; + public final static String int_conjugate_doc = + "Returns self, the complex conjugate of any int."; + + public final static String int_denominator_doc = + "the denominator of a rational number in lowest terms"; + + public final static String int_imag_doc = + "the imaginary part of a complex number"; + + public final static String int_numerator_doc = + "the numerator of a rational number in lowest terms"; + + public final static String int_real_doc = + "the real part of a complex number"; + // Docs for <type 'xrange'> public final static String xrange___class___doc = "type(object) -> the object's type\n" + @@ -2078,6 +2497,9 @@ "generates the numbers in the range on demand. For looping, this is \n" + "slightly faster than range() and more memory efficient."; + public final static String xrange___format___doc = + "default object formatter"; + public final static String xrange___getattribute___doc = "x.__getattribute__('name') <==> x.name"; @@ -2100,7 +2522,7 @@ "T.__new__(S, ...) -> a new object with type S, a subtype of T"; public final static String xrange___reduce___doc = - "helper for pickle"; + ""; public final static String xrange___reduce_ex___doc = "helper for pickle"; @@ -2114,9 +2536,21 @@ public final static String xrange___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String xrange___sizeof___doc = + "__sizeof__() -> size of object in memory, in bytes"; + public final static String xrange___str___doc = "x.__str__() <==> str(x)"; + public final static String xrange___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + // Docs for <type 'file'> public final static String file___class___doc = "type(object) -> the object's type\n" + @@ -2134,7 +2568,8 @@ "opened for writing. Add a 'b' to the mode for binary files.\n" + "Add a '+' to the mode to allow simultaneous reading and writing.\n" + "If the buffering argument is given, 0 means unbuffered, 1 means line\n" + - "buffered, and larger numbers specify the buffer size.\n" + + "buffered, and larger numbers specify the buffer size. The preferred way\n" + + "to open a file is with the builtin open() function.\n" + "Add a 'U' to mode to open the file for input with universal newline\n" + "support. Any line ending in the input file will be seen as a '\\n'\n" + "in Python. Also, a file so opened gains the attribute 'newlines';\n" + @@ -2150,6 +2585,9 @@ public final static String file___exit___doc = "__exit__(*excinfo) -> None. Closes the file."; + public final static String file___format___doc = + "default object formatter"; + public final static String file___getattribute___doc = "x.__getattribute__('name') <==> x.name"; @@ -2177,9 +2615,21 @@ public final static String file___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String file___sizeof___doc = + "__sizeof__() -> size of object in memory, in bytes"; + public final static String file___str___doc = "x.__str__() <==> str(x)"; + public final static String file___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + public final static String file_close_doc = "close() -> None or (perhaps) an integer. Close the file.\n" + "\n" + @@ -2194,6 +2644,9 @@ public final static String file_encoding_doc = "file encoding"; + public final static String file_errors_doc = + "Unicode error handler"; + public final static String file_fileno_doc = "fileno() -> integer \"file descriptor\".\n" + "\n" + @@ -2320,6 +2773,9 @@ public final static String complex___floordiv___doc = "x.__floordiv__(y) <==> x//y"; + public final static String complex___format___doc = + "default object formatter"; + public final static String complex___ge___doc = "x.__ge__(y) <==> x>=y"; @@ -2413,17 +2869,31 @@ public final static String complex___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String complex___sizeof___doc = + "__sizeof__() -> size of object in memory, in bytes"; + public final static String complex___str___doc = "x.__str__() <==> str(x)"; public final static String complex___sub___doc = "x.__sub__(y) <==> x-y"; + public final static String complex___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + public final static String complex___truediv___doc = "x.__truediv__(y) <==> x/y"; public final static String complex_conjugate_doc = - ""; + "complex.conjugate() -> complex\n" + + "\n" + + "Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j."; public final static String complex_imag_doc = "the imaginary part of a complex number"; @@ -2473,6 +2943,9 @@ public final static String bool___floordiv___doc = "x.__floordiv__(y) <==> x//y"; + public final static String bool___format___doc = + ""; + public final static String bool___getattribute___doc = "x.__getattribute__('name') <==> x.name"; @@ -2587,18 +3060,48 @@ public final static String bool___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String bool___sizeof___doc = + "__sizeof__() -> size of object in memory, in bytes"; + public final static String bool___str___doc = "x.__str__() <==> str(x)"; public final static String bool___sub___doc = "x.__sub__(y) <==> x-y"; + public final static String bool___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + public final static String bool___truediv___doc = "x.__truediv__(y) <==> x/y"; + public final static String bool___trunc___doc = + "Truncating an Integral returns itself."; + public final static String bool___xor___doc = "x.__xor__(y) <==> x^y"; + public final static String bool_conjugate_doc = + "Returns self, the complex conjugate of any int."; + + public final static String bool_denominator_doc = + "the denominator of a rational number in lowest terms"; + + public final static String bool_imag_doc = + "the imaginary part of a complex number"; + + public final static String bool_numerator_doc = + "the numerator of a rational number in lowest terms"; + + public final static String bool_real_doc = + "the real part of a complex number"; + // Docs for <type 'classmethod'> public final static String classmethod___class___doc = "type(object) -> the object's type\n" + @@ -2628,6 +3131,9 @@ "Class methods are different than C++ or Java static methods.\n" + "If you want those, see the staticmethod builtin."; + public final static String classmethod___format___doc = + "default object formatter"; + public final static String classmethod___get___doc = "descr.__get__(obj[, type]) -> value"; @@ -2655,9 +3161,21 @@ public final static String classmethod___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String classmethod___sizeof___doc = + "__sizeof__() -> size of object in memory, in bytes"; + public final static String classmethod___str___doc = "x.__str__() <==> str(x)"; + public final static String classmethod___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + // Docs for <type 'set'> public final static String set___and___doc = "x.__and__(y) <==> x&y"; @@ -2683,6 +3201,9 @@ public final static String set___eq___doc = "x.__eq__(y) <==> x==y"; + public final static String set___format___doc = + "default object formatter"; + public final static String set___ge___doc = "x.__ge__(y) <==> x>=y"; @@ -2693,7 +3214,7 @@ "x.__gt__(y) <==> x>y"; public final static String set___hash___doc = - "x.__hash__() <==> hash(x)"; + ""; public final static String set___iand___doc = "x.__iand__(y) <==> x&y"; @@ -2755,12 +3276,24 @@ public final static String set___setattr___doc = "x.__setattr__('name', value) <==> x.name = value"; + public final static String set___sizeof___doc = + "S.__sizeof__() -> size of S in memory, in bytes"; + public final static String set___str___doc = "x.__str__() <==> str(x)"; public final static String set___sub___doc = "x.__sub__(y) <==> x-y"; + public final static String set___subclasshook___doc = + "Abstract classes can override this to customize issubclass().\n" + + "\n" + + "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" + + "It should return True, False or NotImplemented. If it returns\n" + + "NotImplemented, the normal algorithm is used. Otherwise, it\n" + + "overrides the normal algorithm (and the outcome is cached).\n" + + ""; + public final static String set___xor___doc = "x.__xor__(y) <==> x^y"; @@ -2776,9 +3309,9 @@ "Return a shallow copy of a set."; public final static String set_difference_doc = - "Return the difference of two sets as a new set.\n" + + "Return the difference of two or more sets as a new set.\n" + "\n" + - "(i.e. all elements that are in this set but not the other.)"; + "(i.e. all elements that are in this set but not the others.)"; public final static String set_difference_update_doc = "Remove all elements of another set from this set."; @@ -2796,6 +3329,9 @@ public final static String set_intersection_update_doc = "Update a set with the intersection of itself and another."; + public final static String set_isdisjoint_doc = + "Return True if two sets have a null intersection."; + public final static String set_issubset_doc = "Report whether another set contains this set."; @@ -2803,7 +3339,8 @@ "Report whether this set contains another set."; public final static String set_pop_doc = - "Remove and return an arbitrary set element."; + "Remove and return an arbitrary set element.\n" + + "Raises KeyError if the set is empty."; public final static String set_remove_doc = "Remove an ... [truncated message content] |
From: <pj...@us...> - 2011-03-14 03:14:44
|
Revision: 7232 http://jython.svn.sourceforge.net/jython/?rev=7232&view=rev Author: pjenvey Date: 2011-03-14 03:14:37 +0000 (Mon, 14 Mar 2011) Log Message: ----------- o test_grammar is stock from CPython 2.6 o old style test outputs no longer needed Removed Paths: ------------- trunk/jython/Lib/test/output/test_extcall trunk/jython/Lib/test/output/test_grammar trunk/jython/Lib/test/output/test_math trunk/jython/Lib/test/output/test_profile trunk/jython/Lib/test/output/test_signal trunk/jython/Lib/test/test_grammar.py Deleted: trunk/jython/Lib/test/output/test_extcall =================================================================== --- trunk/jython/Lib/test/output/test_extcall 2011-03-14 03:06:43 UTC (rev 7231) +++ trunk/jython/Lib/test/output/test_extcall 2011-03-14 03:14:37 UTC (rev 7232) @@ -1 +0,0 @@ -test_extcall Deleted: trunk/jython/Lib/test/output/test_grammar =================================================================== --- trunk/jython/Lib/test/output/test_grammar 2011-03-14 03:06:43 UTC (rev 7231) +++ trunk/jython/Lib/test/output/test_grammar 2011-03-14 03:14:37 UTC (rev 7232) @@ -1 +0,0 @@ -test_grammar Deleted: trunk/jython/Lib/test/output/test_math =================================================================== --- trunk/jython/Lib/test/output/test_math 2011-03-14 03:06:43 UTC (rev 7231) +++ trunk/jython/Lib/test/output/test_math 2011-03-14 03:14:37 UTC (rev 7232) @@ -1,28 +0,0 @@ -test_math -math module, testing with eps 1e-05 -constants -acos -asin -atan -atan2 -ceil -cos -cosh -degrees -exp -fabs -floor -fmod -frexp -hypot -ldexp -log -log10 -modf -pow -radians -sin -sinh -sqrt -tan -tanh Deleted: trunk/jython/Lib/test/output/test_profile =================================================================== --- trunk/jython/Lib/test/output/test_profile 2011-03-14 03:06:43 UTC (rev 7231) +++ trunk/jython/Lib/test/output/test_profile 2011-03-14 03:14:37 UTC (rev 7232) @@ -1,65 +0,0 @@ -test_profile - 98 function calls (78 primitive calls) in 1.000 CPU seconds - - Ordered by: standard name - - ncalls tottime percall cumtime percall filename:lineno(function) - 1 0.000 0.000 1.000 1.000 <string>:0(<module>) - 0 0.000 0.000 profile:0(profiler) - 1 0.000 0.000 1.000 1.000 profile:0(testfunc()) - 8 0.064 0.008 0.080 0.010 test_profile.py:103(subhelper) - 28 0.028 0.001 0.028 0.001 test_profile.py:115(__getattr__) - 1 0.270 0.270 1.000 1.000 test_profile.py:30(testfunc) - 23/3 0.150 0.007 0.170 0.057 test_profile.py:40(factorial) - 20 0.020 0.001 0.020 0.001 test_profile.py:53(mul) - 2 0.040 0.020 0.600 0.300 test_profile.py:60(helper) - 4 0.116 0.029 0.120 0.030 test_profile.py:78(helper1) - 2 0.000 0.000 0.140 0.070 test_profile.py:89(helper2_indirect) - 8 0.312 0.039 0.400 0.050 test_profile.py:93(helper2) - - - Ordered by: standard name - -Function called... -<string>:0(<module>) -> test_profile.py:30(testfunc)(1) 1.000 -profile:0(profiler) -> profile:0(testfunc())(1) 1.000 -profile:0(testfunc()) -> <string>:0(<module>)(1) 1.000 -test_profile.py:103(subhelper) -> test_profile.py:115(__getattr__)(16) 0.028 -test_profile.py:115(__getattr__) -> -test_profile.py:30(testfunc) -> test_profile.py:40(factorial)(1) 0.170 - test_profile.py:60(helper)(2) 0.600 -test_profile.py:40(factorial) -> test_profile.py:40(factorial)(20) 0.170 - test_profile.py:53(mul)(20) 0.020 -test_profile.py:53(mul) -> -test_profile.py:60(helper) -> test_profile.py:78(helper1)(4) 0.120 - test_profile.py:89(helper2_indirect)(2) 0.140 - test_profile.py:93(helper2)(6) 0.400 -test_profile.py:78(helper1) -> test_profile.py:115(__getattr__)(4) 0.028 -test_profile.py:89(helper2_indirect) -> test_profile.py:40(factorial)(2) 0.170 - test_profile.py:93(helper2)(2) 0.400 -test_profile.py:93(helper2) -> test_profile.py:103(subhelper)(8) 0.080 - test_profile.py:115(__getattr__)(8) 0.028 - - - Ordered by: standard name - -Function was called by... -<string>:0(<module>) <- profile:0(testfunc())(1) 1.000 -profile:0(profiler) <- -profile:0(testfunc()) <- profile:0(profiler)(1) 0.000 -test_profile.py:103(subhelper) <- test_profile.py:93(helper2)(8) 0.400 -test_profile.py:115(__getattr__) <- test_profile.py:78(helper1)(4) 0.120 - test_profile.py:93(helper2)(8) 0.400 - test_profile.py:103(subhelper)(16) 0.080 -test_profile.py:30(testfunc) <- <string>:0(<module>)(1) 1.000 -test_profile.py:40(factorial) <- test_profile.py:30(testfunc)(1) 1.000 - test_profile.py:40(factorial)(20) 0.170 - test_profile.py:89(helper2_indirect)(2) 0.140 -test_profile.py:53(mul) <- test_profile.py:40(factorial)(20) 0.170 -test_profile.py:60(helper) <- test_profile.py:30(testfunc)(2) 1.000 -test_profile.py:78(helper1) <- test_profile.py:60(helper)(4) 0.600 -test_profile.py:89(helper2_indirect) <- test_profile.py:60(helper)(2) 0.600 -test_profile.py:93(helper2) <- test_profile.py:60(helper)(6) 0.600 - test_profile.py:89(helper2_indirect)(2) 0.140 - - Deleted: trunk/jython/Lib/test/output/test_signal =================================================================== --- trunk/jython/Lib/test/output/test_signal 2011-03-14 03:06:43 UTC (rev 7231) +++ trunk/jython/Lib/test/output/test_signal 2011-03-14 03:14:37 UTC (rev 7232) @@ -1 +0,0 @@ -test_signal Deleted: trunk/jython/Lib/test/test_grammar.py =================================================================== --- trunk/jython/Lib/test/test_grammar.py 2011-03-14 03:06:43 UTC (rev 7231) +++ trunk/jython/Lib/test/test_grammar.py 2011-03-14 03:14:37 UTC (rev 7232) @@ -1,967 +0,0 @@ -# Python test set -- part 1, grammar. -# This just tests whether the parser accepts them all. - -# NOTE: When you run this test as a script from the command line, you -# get warnings about certain hex/oct constants. Since those are -# issued by the parser, you can't suppress them by adding a -# filterwarnings() call to this module. Therefore, to shut up the -# regression test, the filterwarnings() call has been added to -# regrtest.py. - -from test.test_support import (run_unittest, check_syntax_error, - _check_py3k_warnings) -import unittest -import sys -# testing import * -from sys import * - -class TokenTests(unittest.TestCase): - - def testBackslash(self): - # Backslash means line continuation: - x = 1 \ - + 1 - self.assertEquals(x, 2, 'backslash for line continuation') - - # Backslash does not means continuation in comments :\ - x = 0 - self.assertEquals(x, 0, 'backslash ending comment') - - def testPlainIntegers(self): - self.assertEquals(0xff, 255) - self.assertEquals(0377, 255) - self.assertEquals(2147483647, 017777777777) - # "0x" is not a valid literal - self.assertRaises(SyntaxError, eval, "0x") - from sys import maxint - if maxint == 2147483647: - self.assertEquals(-2147483647-1, -020000000000) - # XXX -2147483648 - self.assert_(037777777777 > 0) - self.assert_(0xffffffff > 0) - for s in '2147483648', '040000000000', '0x100000000': - try: - x = eval(s) - except OverflowError: - self.fail("OverflowError on huge integer literal %r" % s) - elif maxint == 9223372036854775807: - self.assertEquals(-9223372036854775807-1, -01000000000000000000000) - self.assert_(01777777777777777777777 > 0) - self.assert_(0xffffffffffffffff > 0) - for s in '9223372036854775808', '02000000000000000000000', \ - '0x10000000000000000': - try: - x = eval(s) - except OverflowError: - self.fail("OverflowError on huge integer literal %r" % s) - else: - self.fail('Weird maxint value %r' % maxint) - - def testLongIntegers(self): - x = 0L - x = 0l - x = 0xffffffffffffffffL - x = 0xffffffffffffffffl - x = 077777777777777777L - x = 077777777777777777l - x = 123456789012345678901234567890L - x = 123456789012345678901234567890l - - def testFloats(self): - x = 3.14 - x = 314. - x = 0.314 - # XXX x = 000.314 - x = .314 - x = 3e14 - x = 3E14 - x = 3e-14 - x = 3e+14 - x = 3.e14 - x = .3e14 - x = 3.1e4 - - def testStringLiterals(self): - x = ''; y = ""; self.assert_(len(x) == 0 and x == y) - x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39) - x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34) - x = "doesn't \"shrink\" does it" - y = 'doesn\'t "shrink" does it' - self.assert_(len(x) == 24 and x == y) - x = "does \"shrink\" doesn't it" - y = 'does "shrink" doesn\'t it' - self.assert_(len(x) == 24 and x == y) - x = """ -The "quick" -brown fox -jumps over -the 'lazy' dog. -""" - y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' - self.assertEquals(x, y) - y = ''' -The "quick" -brown fox -jumps over -the 'lazy' dog. -''' - self.assertEquals(x, y) - y = "\n\ -The \"quick\"\n\ -brown fox\n\ -jumps over\n\ -the 'lazy' dog.\n\ -" - self.assertEquals(x, y) - y = '\n\ -The \"quick\"\n\ -brown fox\n\ -jumps over\n\ -the \'lazy\' dog.\n\ -' - self.assertEquals(x, y) - - -class GrammarTests(unittest.TestCase): - - # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE - # XXX can't test in a script -- this rule is only used when interactive - - # file_input: (NEWLINE | stmt)* ENDMARKER - # Being tested as this very moment this very module - - # expr_input: testlist NEWLINE - # XXX Hard to test -- used only in calls to input() - - def testEvalInput(self): - # testlist ENDMARKER - x = eval('1, 0 or 1') - - def testFuncdef(self): - ### 'def' NAME parameters ':' suite - ### parameters: '(' [varargslist] ')' - ### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME] - ### | ('**'|'*' '*') NAME) - ### | fpdef ['=' test] (',' fpdef ['=' test])* [','] - ### fpdef: NAME | '(' fplist ')' - ### fplist: fpdef (',' fpdef)* [','] - ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test) - ### argument: [test '='] test # Really [keyword '='] test - def f1(): pass - f1() - f1(*()) - f1(*(), **{}) - def f2(one_argument): pass - def f3(two, arguments): pass - # Silence Py3k warning - exec('def f4(two, (compound, (argument, list))): pass') - exec('def f5((compound, first), two): pass') - self.assertEquals(f2.func_code.co_varnames, ('one_argument',)) - self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments')) - if sys.platform.startswith('java'): - self.assertEquals(f4.func_code.co_varnames, - ('two', '(compound, (argument, list))', 'compound', 'argument', - 'list',)) - self.assertEquals(f5.func_code.co_varnames, - ('(compound, first)', 'two', 'compound', 'first')) - else: - self.assertEquals(f4.func_code.co_varnames, - ('two', '.1', 'compound', 'argument', 'list')) - self.assertEquals(f5.func_code.co_varnames, - ('.0', 'two', 'compound', 'first')) - def a1(one_arg,): pass - def a2(two, args,): pass - def v0(*rest): pass - def v1(a, *rest): pass - def v2(a, b, *rest): pass - # Silence Py3k warning - exec('def v3(a, (b, c), *rest): return a, b, c, rest') - - f1() - f2(1) - f2(1,) - f3(1, 2) - f3(1, 2,) - f4(1, (2, (3, 4))) - v0() - v0(1) - v0(1,) - v0(1,2) - v0(1,2,3,4,5,6,7,8,9,0) - v1(1) - v1(1,) - v1(1,2) - v1(1,2,3) - v1(1,2,3,4,5,6,7,8,9,0) - v2(1,2) - v2(1,2,3) - v2(1,2,3,4) - v2(1,2,3,4,5,6,7,8,9,0) - v3(1,(2,3)) - v3(1,(2,3),4) - v3(1,(2,3),4,5,6,7,8,9,0) - - # ceval unpacks the formal arguments into the first argcount names; - # thus, the names nested inside tuples must appear after these names. - if sys.platform.startswith('java'): - self.assertEquals(v3.func_code.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c')) - else: - self.assertEquals(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c')) - self.assertEquals(v3(1, (2, 3), 4), (1, 2, 3, (4,))) - def d01(a=1): pass - d01() - d01(1) - d01(*(1,)) - d01(**{'a':2}) - def d11(a, b=1): pass - d11(1) - d11(1, 2) - d11(1, **{'b':2}) - def d21(a, b, c=1): pass - d21(1, 2) - d21(1, 2, 3) - d21(*(1, 2, 3)) - d21(1, *(2, 3)) - d21(1, 2, *(3,)) - d21(1, 2, **{'c':3}) - def d02(a=1, b=2): pass - d02() - d02(1) - d02(1, 2) - d02(*(1, 2)) - d02(1, *(2,)) - d02(1, **{'b':2}) - d02(**{'a': 1, 'b': 2}) - def d12(a, b=1, c=2): pass - d12(1) - d12(1, 2) - d12(1, 2, 3) - def d22(a, b, c=1, d=2): pass - d22(1, 2) - d22(1, 2, 3) - d22(1, 2, 3, 4) - def d01v(a=1, *rest): pass - d01v() - d01v(1) - d01v(1, 2) - d01v(*(1, 2, 3, 4)) - d01v(*(1,)) - d01v(**{'a':2}) - def d11v(a, b=1, *rest): pass - d11v(1) - d11v(1, 2) - d11v(1, 2, 3) - def d21v(a, b, c=1, *rest): pass - d21v(1, 2) - d21v(1, 2, 3) - d21v(1, 2, 3, 4) - d21v(*(1, 2, 3, 4)) - d21v(1, 2, **{'c': 3}) - def d02v(a=1, b=2, *rest): pass - d02v() - d02v(1) - d02v(1, 2) - d02v(1, 2, 3) - d02v(1, *(2, 3, 4)) - d02v(**{'a': 1, 'b': 2}) - def d12v(a, b=1, c=2, *rest): pass - d12v(1) - d12v(1, 2) - d12v(1, 2, 3) - d12v(1, 2, 3, 4) - d12v(*(1, 2, 3, 4)) - d12v(1, 2, *(3, 4, 5)) - d12v(1, *(2,), **{'c': 3}) - def d22v(a, b, c=1, d=2, *rest): pass - d22v(1, 2) - d22v(1, 2, 3) - d22v(1, 2, 3, 4) - d22v(1, 2, 3, 4, 5) - d22v(*(1, 2, 3, 4)) - d22v(1, 2, *(3, 4, 5)) - d22v(1, *(2, 3), **{'d': 4}) - # Silence Py3k warning - exec('def d31v((x)): pass') - exec('def d32v((x,)): pass') - d31v(1) - d32v((1,)) - - # keyword arguments after *arglist - def f(*args, **kwargs): - return args, kwargs - self.assertEquals(f(1, x=2, *[3, 4], y=5), ((1, 3, 4), - {'x':2, 'y':5})) - self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)") - self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)") - - # Check ast errors in *args and *kwargs - check_syntax_error(self, "f(*g(1=2))") - check_syntax_error(self, "f(**g(1=2))") - - def testLambdef(self): - ### lambdef: 'lambda' [varargslist] ':' test - l1 = lambda : 0 - self.assertEquals(l1(), 0) - l2 = lambda : a[d] # XXX just testing the expression - l3 = lambda : [2 < x for x in [-1, 3, 0L]] - self.assertEquals(l3(), [0, 1, 0]) - l4 = lambda x = lambda y = lambda z=1 : z : y() : x() - self.assertEquals(l4(), 1) - l5 = lambda x, y, z=2: x + y + z - self.assertEquals(l5(1, 2), 5) - self.assertEquals(l5(1, 2, 3), 6) - check_syntax_error(self, "lambda x: x = 2") - check_syntax_error(self, "lambda (None,): None") - - ### stmt: simple_stmt | compound_stmt - # Tested below - - def testSimpleStmt(self): - ### simple_stmt: small_stmt (';' small_stmt)* [';'] - x = 1; pass; del x - def foo(): - # verify statments that end with semi-colons - x = 1; pass; del x; - foo() - - ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt - # Tested below - - def testExprStmt(self): - # (exprlist '=')* exprlist - 1 - 1, 2, 3 - x = 1 - x = 1, 2, 3 - x = y = z = 1, 2, 3 - x, y, z = 1, 2, 3 - abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4) - - check_syntax_error(self, "x + 1 = 1") - check_syntax_error(self, "a + 1 = b + 2") - - def testPrintStmt(self): - # 'print' (test ',')* [test] - import StringIO - - # Can't test printing to real stdout without comparing output - # which is not available in unittest. - save_stdout = sys.stdout - sys.stdout = StringIO.StringIO() - - print 1, 2, 3 - print 1, 2, 3, - print - print 0 or 1, 0 or 1, - print 0 or 1 - - # 'print' '>>' test ',' - print >> sys.stdout, 1, 2, 3 - print >> sys.stdout, 1, 2, 3, - print >> sys.stdout - print >> sys.stdout, 0 or 1, 0 or 1, - print >> sys.stdout, 0 or 1 - - # test printing to an instance - class Gulp: - def write(self, msg): pass - - gulp = Gulp() - print >> gulp, 1, 2, 3 - print >> gulp, 1, 2, 3, - print >> gulp - print >> gulp, 0 or 1, 0 or 1, - print >> gulp, 0 or 1 - - # test print >> None - def driver(): - oldstdout = sys.stdout - sys.stdout = Gulp() - try: - tellme(Gulp()) - tellme() - finally: - sys.stdout = oldstdout - - # we should see this once - def tellme(file=sys.stdout): - print >> file, 'hello world' - - driver() - - # we should not see this at all - def tellme(file=None): - print >> file, 'goodbye universe' - - driver() - - self.assertEqual(sys.stdout.getvalue(), '''\ -1 2 3 -1 2 3 -1 1 1 -1 2 3 -1 2 3 -1 1 1 -hello world -''') - sys.stdout = save_stdout - - # syntax errors - check_syntax_error(self, 'print ,') - check_syntax_error(self, 'print >> x,') - - def testDelStmt(self): - # 'del' exprlist - abc = [1,2,3] - x, y, z = abc - xyz = x, y, z - - del abc - del x, y, (z, xyz) - - def testPassStmt(self): - # 'pass' - pass - - # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt - # Tested below - - def testBreakStmt(self): - # 'break' - while 1: break - - def testContinueStmt(self): - # 'continue' - i = 1 - while i: i = 0; continue - - msg = "" - while not msg: - msg = "ok" - try: - continue - msg = "continue failed to continue inside try" - except: - msg = "continue inside try called except block" - if msg != "ok": - self.fail(msg) - - msg = "" - while not msg: - msg = "finally block not called" - try: - continue - finally: - msg = "ok" - if msg != "ok": - self.fail(msg) - - def test_break_continue_loop(self): - # This test warrants an explanation. It is a test specifically for SF bugs - # #463359 and #462937. The bug is that a 'break' statement executed or - # exception raised inside a try/except inside a loop, *after* a continue - # statement has been executed in that loop, will cause the wrong number of - # arguments to be popped off the stack and the instruction pointer reset to - # a very small number (usually 0.) Because of this, the following test - # *must* written as a function, and the tracking vars *must* be function - # arguments with default values. Otherwise, the test will loop and loop. - - def test_inner(extra_burning_oil = 1, count=0): - big_hippo = 2 - while big_hippo: - count += 1 - try: - if extra_burning_oil and big_hippo == 1: - extra_burning_oil -= 1 - break - big_hippo -= 1 - continue - except: - raise - if count > 2 or big_hippo != 1: - self.fail("continue then break in try/except in loop broken!") - test_inner() - - def testReturn(self): - # 'return' [testlist] - def g1(): return - def g2(): return 1 - g1() - x = g2() - check_syntax_error(self, "class foo:return 1") - - def testYield(self): - check_syntax_error(self, "class foo:yield 1") - - def testRaise(self): - # 'raise' test [',' test] - try: raise RuntimeError, 'just testing' - except RuntimeError: pass - try: raise KeyboardInterrupt - except KeyboardInterrupt: pass - - def testImport(self): - # 'import' dotted_as_names - import sys - import time, sys - # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names) - from time import time - from time import (time) - # not testable inside a function, but already done at top of the module - # from sys import * - from sys import path, argv - from sys import (path, argv) - from sys import (path, argv,) - - def testGlobal(self): - # 'global' NAME (',' NAME)* - global a - global a, b - global one, two, three, four, five, six, seven, eight, nine, ten - - def testExec(self): - # 'exec' expr ['in' expr [',' expr]] - z = None - del z - exec 'z=1+1\n' - if z != 2: self.fail('exec \'z=1+1\'\\n') - del z - exec 'z=1+1' - if z != 2: self.fail('exec \'z=1+1\'') - z = None - del z - import types - if hasattr(types, "UnicodeType"): - exec r"""if 1: - exec u'z=1+1\n' - if z != 2: self.fail('exec u\'z=1+1\'\\n') - del z - exec u'z=1+1' - if z != 2: self.fail('exec u\'z=1+1\'')""" - g = {} - exec 'z = 1' in g - if '__builtins__' in g: del g['__builtins__'] - if g != {'z': 1}: self.fail('exec \'z = 1\' in g') - g = {} - l = {} - - import warnings - warnings.filterwarnings("ignore", "global statement", module="<string>") - exec 'global a; a = 1; b = 2' in g, l - if '__builtins__' in g: del g['__builtins__'] - if '__builtins__' in l: del l['__builtins__'] - if (g, l) != ({'a':1}, {'b':2}): - self.fail('exec ... in g (%s), l (%s)' %(g,l)) - - def testAssert(self): - # assert_stmt: 'assert' test [',' test] - assert 1 - assert 1, 1 - assert lambda x:x - assert 1, lambda x:x+1 - try: - assert 0, "msg" - except AssertionError, e: - self.assertEquals(e.args[0], "msg") - else: - if __debug__: - self.fail("AssertionError not raised by assert 0") - - ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef - # Tested below - - def testIf(self): - # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] - if 1: pass - if 1: pass - else: pass - if 0: pass - elif 0: pass - if 0: pass - elif 0: pass - elif 0: pass - elif 0: pass - else: pass - - def testWhile(self): - # 'while' test ':' suite ['else' ':' suite] - while 0: pass - while 0: pass - else: pass - - # Issue1920: "while 0" is optimized away, - # ensure that the "else" clause is still present. - x = 0 - while 0: - x = 1 - else: - x = 2 - self.assertEquals(x, 2) - - def testFor(self): - # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] - for i in 1, 2, 3: pass - for i, j, k in (): pass - else: pass - class Squares: - def __init__(self, max): - self.max = max - self.sofar = [] - def __len__(self): return len(self.sofar) - def __getitem__(self, i): - if not 0 <= i < self.max: raise IndexError - n = len(self.sofar) - while n <= i: - self.sofar.append(n*n) - n = n+1 - return self.sofar[i] - n = 0 - for x in Squares(10): n = n+x - if n != 285: - self.fail('for over growing sequence') - - result = [] - for x, in [(1,), (2,), (3,)]: - result.append(x) - self.assertEqual(result, [1, 2, 3]) - - def testTry(self): - ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] - ### | 'try' ':' suite 'finally' ':' suite - ### except_clause: 'except' [expr [('as' | ',') expr]] - try: - 1/0 - except ZeroDivisionError: - pass - else: - pass - try: 1/0 - except EOFError: pass - except TypeError as msg: pass - except RuntimeError, msg: pass - except: pass - else: pass - try: 1/0 - except (EOFError, TypeError, ZeroDivisionError): pass - try: 1/0 - except (EOFError, TypeError, ZeroDivisionError), msg: pass - try: pass - finally: pass - - def testSuite(self): - # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT - if 1: pass - if 1: - pass - if 1: - # - # - # - pass - pass - # - pass - # - - def testTest(self): - ### and_test ('or' and_test)* - ### and_test: not_test ('and' not_test)* - ### not_test: 'not' not_test | comparison - if not 1: pass - if 1 and 1: pass - if 1 or 1: pass - if not not not 1: pass - if not 1 and 1 and 1: pass - if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass - - def testComparison(self): - ### comparison: expr (comp_op expr)* - ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' - if 1: pass - x = (1 == 1) - if 1 == 1: pass - if 1 != 1: pass - if 1 < 1: pass - if 1 > 1: pass - if 1 <= 1: pass - if 1 >= 1: pass - if 1 is 1: pass - if 1 is not 1: pass - if 1 in (): pass - if 1 not in (): pass - if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass - # Silence Py3k warning - if eval('1 <> 1'): pass - if eval('1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1'): pass - - def testBinaryMaskOps(self): - x = 1 & 1 - x = 1 ^ 1 - x = 1 | 1 - - def testShiftOps(self): - x = 1 << 1 - x = 1 >> 1 - x = 1 << 1 >> 1 - - def testAdditiveOps(self): - x = 1 - x = 1 + 1 - x = 1 - 1 - 1 - x = 1 - 1 + 1 - 1 + 1 - - def testMultiplicativeOps(self): - x = 1 * 1 - x = 1 / 1 - x = 1 % 1 - x = 1 / 1 * 1 % 1 - - def testUnaryOps(self): - x = +1 - x = -1 - x = ~1 - x = ~1 ^ 1 & 1 | 1 & 1 ^ -1 - x = -1*1/1 + 1*1 - ---1*1 - - def testSelectors(self): - ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME - ### subscript: expr | [expr] ':' [expr] - - import sys, time - c = sys.path[0] - x = time.time() - x = sys.modules['time'].time() - a = '01234' - c = a[0] - c = a[-1] - s = a[0:5] - s = a[:5] - s = a[0:] - s = a[:] - s = a[-5:] - s = a[:-1] - s = a[-4:-3] - # A rough test of SF bug 1333982. http://python.org/sf/1333982 - # The testing here is fairly incomplete. - # Test cases should include: commas with 1 and 2 colons - d = {} - d[1] = 1 - d[1,] = 2 - d[1,2] = 3 - d[1,2,3] = 4 - L = list(d) - L.sort() - self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]') - - def testAtoms(self): - ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING - ### dictmaker: test ':' test (',' test ':' test)* [','] - - x = (1) - x = (1 or 2 or 3) - x = (1 or 2 or 3, 2, 3) - - x = [] - x = [1] - x = [1 or 2 or 3] - x = [1 or 2 or 3, 2, 3] - x = [] - - x = {} - x = {'one': 1} - x = {'one': 1,} - x = {'one' or 'two': 1 or 2} - x = {'one': 1, 'two': 2} - x = {'one': 1, 'two': 2,} - x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} - - # Silence Py3k warning - x = eval('`x`') - x = eval('`1 or 2 or 3`') - self.assertEqual(eval('`1,2`'), '(1, 2)') - - x = x - x = 'x' - x = 123 - - ### exprlist: expr (',' expr)* [','] - ### testlist: test (',' test)* [','] - # These have been exercised enough above - - def testClassdef(self): - # 'class' NAME ['(' [testlist] ')'] ':' suite - class B: pass - class B2(): pass - class C1(B): pass - class C2(B): pass - class D(C1, C2, B): pass - class C: - def meth1(self): pass - def meth2(self, arg): pass - def meth3(self, a1, a2): pass - # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE - # decorators: decorator+ - # decorated: decorators (classdef | funcdef) - def class_decorator(x): - x.decorated = True - return x - @class_decorator - class G: - pass - self.assertEqual(G.decorated, True) - - def testListcomps(self): - # list comprehension tests - nums = [1, 2, 3, 4, 5] - strs = ["Apple", "Banana", "Coconut"] - spcs = [" Apple", " Banana ", "Coco nut "] - - self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut']) - self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15]) - self.assertEqual([x for x in nums if x > 2], [3, 4, 5]) - self.assertEqual([(i, s) for i in nums for s in strs], - [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'), - (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'), - (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'), - (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'), - (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')]) - self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]], - [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'), - (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'), - (5, 'Banana'), (5, 'Coconut')]) - self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)], - [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]]) - - def test_in_func(l): - return [None < x < 3 for x in l if x > 2] - - self.assertEqual(test_in_func(nums), [False, False, False]) - - def test_nested_front(): - self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]], - [[1, 2], [3, 4], [5, 6]]) - - test_nested_front() - - check_syntax_error(self, "[i, s for i in nums for s in strs]") - check_syntax_error(self, "[x if y]") - - suppliers = [ - (1, "Boeing"), - (2, "Ford"), - (3, "Macdonalds") - ] - - parts = [ - (10, "Airliner"), - (20, "Engine"), - (30, "Cheeseburger") - ] - - suppart = [ - (1, 10), (1, 20), (2, 20), (3, 30) - ] - - x = [ - (sname, pname) - for (sno, sname) in suppliers - for (pno, pname) in parts - for (sp_sno, sp_pno) in suppart - if sno == sp_sno and pno == sp_pno - ] - - self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'), - ('Macdonalds', 'Cheeseburger')]) - - def testGenexps(self): - # generator expression tests - g = ([x for x in range(10)] for x in range(1)) - self.assertEqual(g.next(), [x for x in range(10)]) - try: - g.next() - self.fail('should produce StopIteration exception') - except StopIteration: - pass - - a = 1 - try: - g = (a for d in a) - g.next() - self.fail('should produce TypeError') - except TypeError: - pass - - self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd']) - self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy']) - - a = [x for x in range(10)] - b = (x for x in (y for y in a)) - self.assertEqual(sum(b), sum([x for x in range(10)])) - - self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)])) - self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2])) - self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)])) - self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)])) - self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)])) - self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True)) if True), sum([x for x in range(10)])) - self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0) - check_syntax_error(self, "foo(x for x in range(10), 100)") - check_syntax_error(self, "foo(100, x for x in range(10))") - - def testComprehensionSpecials(self): - # test for outmost iterable precomputation - x = 10; g = (i for i in range(x)); x = 5 - self.assertEqual(len(list(g)), 10) - - # This should hold, since we're only precomputing outmost iterable. - x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x)) - x = 5; t = True; - self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g)) - - # Grammar allows multiple adjacent 'if's in listcomps and genexps, - # even though it's silly. Make sure it works (ifelse broke this.) - self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7]) - self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7]) - - # verify unpacking single element tuples in listcomp/genexp. - self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6]) - self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9]) - - def testIfElseExpr(self): - # Test ifelse expressions in various cases - def _checkeval(msg, ret): - "helper to check that evaluation of expressions is done correctly" - print x - return ret - - self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True]) - self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True]) - self.assertEqual([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ], [True]) - self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5) - self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5) - self.assertEqual((5 and 6 if 0 else 1), 1) - self.assertEqual(((5 and 6) if 0 else 1), 1) - self.assertEqual((5 and (6 if 1 else 1)), 6) - self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3) - self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1) - self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5) - self.assertEqual((not 5 if 1 else 1), False) - self.assertEqual((not 5 if 0 else 1), 1) - self.assertEqual((6 + 1 if 1 else 2), 7) - self.assertEqual((6 - 1 if 1 else 2), 5) - self.assertEqual((6 * 2 if 1 else 4), 12) - self.assertEqual((6 / 2 if 1 else 3), 3) - self.assertEqual((6 < 4 if 0 else 2), 2) - - -def test_main(): - with _check_py3k_warnings( - ("backquote not supported", SyntaxWarning), - ("tuple parameter unpacking has been removed", SyntaxWarning), - ("parenthesized argument names are invalid", SyntaxWarning), - ("classic int division", DeprecationWarning), - (".+ not supported in 3.x", DeprecationWarning)): - run_unittest(TokenTests, GrammarTests) - -if __name__ == '__main__': - test_main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-14 03:06:51
|
Revision: 7231 http://jython.svn.sourceforge.net/jython/?rev=7231&view=rev Author: pjenvey Date: 2011-03-14 03:06:43 +0000 (Mon, 14 Mar 2011) Log Message: ----------- stock from CPythonLib and not needed Removed Paths: ------------- trunk/jython/Lib/test/output/test_global trunk/jython/Lib/test/test_base64.py trunk/jython/Lib/test/test_contextlib.py trunk/jython/Lib/test/test_email.py trunk/jython/Lib/test/test_email_renamed.py trunk/jython/Lib/test/test_gettext.py trunk/jython/Lib/test/test_global.py trunk/jython/Lib/test/test_wsgiref.py Deleted: trunk/jython/Lib/test/output/test_global =================================================================== --- trunk/jython/Lib/test/output/test_global 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/output/test_global 2011-03-14 03:06:43 UTC (rev 7231) @@ -1 +0,0 @@ -test_global Deleted: trunk/jython/Lib/test/test_base64.py =================================================================== --- trunk/jython/Lib/test/test_base64.py 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/test_base64.py 2011-03-14 03:06:43 UTC (rev 7231) @@ -1,190 +0,0 @@ -import unittest -from test import test_support -import base64 - - - -class LegacyBase64TestCase(unittest.TestCase): - def test_encodestring(self): - eq = self.assertEqual - eq(base64.encodestring("www.python.org"), "d3d3LnB5dGhvbi5vcmc=\n") - eq(base64.encodestring("a"), "YQ==\n") - eq(base64.encodestring("ab"), "YWI=\n") - eq(base64.encodestring("abc"), "YWJj\n") - eq(base64.encodestring(""), "") - eq(base64.encodestring("abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "0123456789!@#0^&*();:<>,. []{}"), - "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" - "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" - "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n") - - def test_decodestring(self): - eq = self.assertEqual - eq(base64.decodestring("d3d3LnB5dGhvbi5vcmc=\n"), "www.python.org") - eq(base64.decodestring("YQ==\n"), "a") - eq(base64.decodestring("YWI=\n"), "ab") - eq(base64.decodestring("YWJj\n"), "abc") - eq(base64.decodestring("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" - "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" - "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n"), - "abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "0123456789!@#0^&*();:<>,. []{}") - eq(base64.decodestring(''), '') - - def test_encode(self): - eq = self.assertEqual - from cStringIO import StringIO - infp = StringIO('abcdefghijklmnopqrstuvwxyz' - 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' - '0123456789!@#0^&*();:<>,. []{}') - outfp = StringIO() - base64.encode(infp, outfp) - eq(outfp.getvalue(), - 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' - 'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT' - 'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n') - - def test_decode(self): - from cStringIO import StringIO - infp = StringIO('d3d3LnB5dGhvbi5vcmc=') - outfp = StringIO() - base64.decode(infp, outfp) - self.assertEqual(outfp.getvalue(), 'www.python.org') - - - -class BaseXYTestCase(unittest.TestCase): - def test_b64encode(self): - eq = self.assertEqual - # Test default alphabet - eq(base64.b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=") - eq(base64.b64encode('\x00'), 'AA==') - eq(base64.b64encode("a"), "YQ==") - eq(base64.b64encode("ab"), "YWI=") - eq(base64.b64encode("abc"), "YWJj") - eq(base64.b64encode(""), "") - eq(base64.b64encode("abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "0123456789!@#0^&*();:<>,. []{}"), - "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" - "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" - "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==") - # Test with arbitrary alternative characters - eq(base64.b64encode('\xd3V\xbeo\xf7\x1d', altchars='*$'), '01a*b$cd') - # Test standard alphabet - eq(base64.standard_b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=") - eq(base64.standard_b64encode("a"), "YQ==") - eq(base64.standard_b64encode("ab"), "YWI=") - eq(base64.standard_b64encode("abc"), "YWJj") - eq(base64.standard_b64encode(""), "") - eq(base64.standard_b64encode("abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "0123456789!@#0^&*();:<>,. []{}"), - "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" - "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" - "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==") - # Test with 'URL safe' alternative characters - eq(base64.urlsafe_b64encode('\xd3V\xbeo\xf7\x1d'), '01a-b_cd') - - def test_b64decode(self): - eq = self.assertEqual - eq(base64.b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") - eq(base64.b64decode('AA=='), '\x00') - eq(base64.b64decode("YQ=="), "a") - eq(base64.b64decode("YWI="), "ab") - eq(base64.b64decode("YWJj"), "abc") - eq(base64.b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" - "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" - "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), - "abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "0123456789!@#0^&*();:<>,. []{}") - eq(base64.b64decode(''), '') - # Test with arbitrary alternative characters - eq(base64.b64decode('01a*b$cd', altchars='*$'), '\xd3V\xbeo\xf7\x1d') - # Test standard alphabet - eq(base64.standard_b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") - eq(base64.standard_b64decode("YQ=="), "a") - eq(base64.standard_b64decode("YWI="), "ab") - eq(base64.standard_b64decode("YWJj"), "abc") - eq(base64.standard_b64decode(""), "") - eq(base64.standard_b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" - "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" - "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), - "abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "0123456789!@#0^&*();:<>,. []{}") - # Test with 'URL safe' alternative characters - eq(base64.urlsafe_b64decode('01a-b_cd'), '\xd3V\xbeo\xf7\x1d') - - def test_b64decode_error(self): - self.assertRaises(TypeError, base64.b64decode, 'abc') - - def test_b32encode(self): - eq = self.assertEqual - eq(base64.b32encode(''), '') - eq(base64.b32encode('\x00'), 'AA======') - eq(base64.b32encode('a'), 'ME======') - eq(base64.b32encode('ab'), 'MFRA====') - eq(base64.b32encode('abc'), 'MFRGG===') - eq(base64.b32encode('abcd'), 'MFRGGZA=') - eq(base64.b32encode('abcde'), 'MFRGGZDF') - - def test_b32decode(self): - eq = self.assertEqual - eq(base64.b32decode(''), '') - eq(base64.b32decode('AA======'), '\x00') - eq(base64.b32decode('ME======'), 'a') - eq(base64.b32decode('MFRA===='), 'ab') - eq(base64.b32decode('MFRGG==='), 'abc') - eq(base64.b32decode('MFRGGZA='), 'abcd') - eq(base64.b32decode('MFRGGZDF'), 'abcde') - - def test_b32decode_casefold(self): - eq = self.assertEqual - eq(base64.b32decode('', True), '') - eq(base64.b32decode('ME======', True), 'a') - eq(base64.b32decode('MFRA====', True), 'ab') - eq(base64.b32decode('MFRGG===', True), 'abc') - eq(base64.b32decode('MFRGGZA=', True), 'abcd') - eq(base64.b32decode('MFRGGZDF', True), 'abcde') - # Lower cases - eq(base64.b32decode('me======', True), 'a') - eq(base64.b32decode('mfra====', True), 'ab') - eq(base64.b32decode('mfrgg===', True), 'abc') - eq(base64.b32decode('mfrggza=', True), 'abcd') - eq(base64.b32decode('mfrggzdf', True), 'abcde') - # Expected exceptions - self.assertRaises(TypeError, base64.b32decode, 'me======') - # Mapping zero and one - eq(base64.b32decode('MLO23456'), 'b\xdd\xad\xf3\xbe') - eq(base64.b32decode('M1023456', map01='L'), 'b\xdd\xad\xf3\xbe') - eq(base64.b32decode('M1023456', map01='I'), 'b\x1d\xad\xf3\xbe') - - def test_b32decode_error(self): - self.assertRaises(TypeError, base64.b32decode, 'abc') - self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==') - - def test_b16encode(self): - eq = self.assertEqual - eq(base64.b16encode('\x01\x02\xab\xcd\xef'), '0102ABCDEF') - eq(base64.b16encode('\x00'), '00') - - def test_b16decode(self): - eq = self.assertEqual - eq(base64.b16decode('0102ABCDEF'), '\x01\x02\xab\xcd\xef') - eq(base64.b16decode('00'), '\x00') - # Lower case is not allowed without a flag - self.assertRaises(TypeError, base64.b16decode, '0102abcdef') - # Case fold - eq(base64.b16decode('0102abcdef', True), '\x01\x02\xab\xcd\xef') - - - -def test_main(): - test_support.run_unittest(__name__) - -if __name__ == '__main__': - test_main() Deleted: trunk/jython/Lib/test/test_contextlib.py =================================================================== --- trunk/jython/Lib/test/test_contextlib.py 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/test_contextlib.py 2011-03-14 03:06:43 UTC (rev 7231) @@ -1,337 +0,0 @@ -"""Unit tests for contextlib.py, and other context managers.""" - -import sys -import os -import decimal -import tempfile -import unittest -import threading -from contextlib import * # Tests __all__ -from test import test_support - -class ContextManagerTestCase(unittest.TestCase): - - def test_contextmanager_plain(self): - state = [] - @contextmanager - def woohoo(): - state.append(1) - yield 42 - state.append(999) - with woohoo() as x: - self.assertEqual(state, [1]) - self.assertEqual(x, 42) - state.append(x) - self.assertEqual(state, [1, 42, 999]) - - def test_contextmanager_finally(self): - state = [] - @contextmanager - def woohoo(): - state.append(1) - try: - yield 42 - finally: - state.append(999) - try: - with woohoo() as x: - self.assertEqual(state, [1]) - self.assertEqual(x, 42) - state.append(x) - raise ZeroDivisionError() - except ZeroDivisionError: - pass - else: - self.fail("Expected ZeroDivisionError") - self.assertEqual(state, [1, 42, 999]) - - def test_contextmanager_no_reraise(self): - @contextmanager - def whee(): - yield - ctx = whee() - ctx.__enter__() - # Calling __exit__ should not result in an exception - self.failIf(ctx.__exit__(TypeError, TypeError("foo"), None)) - - def test_contextmanager_trap_yield_after_throw(self): - @contextmanager - def whoo(): - try: - yield - except: - yield - ctx = whoo() - ctx.__enter__() - self.assertRaises( - RuntimeError, ctx.__exit__, TypeError, TypeError("foo"), None - ) - - def test_contextmanager_except(self): - state = [] - @contextmanager - def woohoo(): - state.append(1) - try: - yield 42 - except ZeroDivisionError, e: - state.append(e.args[0]) - self.assertEqual(state, [1, 42, 999]) - with woohoo() as x: - self.assertEqual(state, [1]) - self.assertEqual(x, 42) - state.append(x) - raise ZeroDivisionError(999) - self.assertEqual(state, [1, 42, 999]) - - def test_contextmanager_attribs(self): - def attribs(**kw): - def decorate(func): - for k,v in kw.items(): - setattr(func,k,v) - return func - return decorate - @contextmanager - @attribs(foo='bar') - def baz(spam): - """Whee!""" - self.assertEqual(baz.__name__,'baz') - self.assertEqual(baz.foo, 'bar') - self.assertEqual(baz.__doc__, "Whee!") - -class NestedTestCase(unittest.TestCase): - - # XXX This needs more work - - def test_nested(self): - @contextmanager - def a(): - yield 1 - @contextmanager - def b(): - yield 2 - @contextmanager - def c(): - yield 3 - with nested(a(), b(), c()) as (x, y, z): - self.assertEqual(x, 1) - self.assertEqual(y, 2) - self.assertEqual(z, 3) - - def test_nested_cleanup(self): - state = [] - @contextmanager - def a(): - state.append(1) - try: - yield 2 - finally: - state.append(3) - @contextmanager - def b(): - state.append(4) - try: - yield 5 - finally: - state.append(6) - try: - with nested(a(), b()) as (x, y): - state.append(x) - state.append(y) - 1 // 0 - except ZeroDivisionError: - self.assertEqual(state, [1, 4, 2, 5, 6, 3]) - else: - self.fail("Didn't raise ZeroDivisionError") - - def test_nested_right_exception(self): - state = [] - @contextmanager - def a(): - yield 1 - class b(object): - def __enter__(self): - return 2 - def __exit__(self, *exc_info): - try: - raise Exception() - except: - pass - try: - with nested(a(), b()) as (x, y): - 1 // 0 - except ZeroDivisionError: - self.assertEqual((x, y), (1, 2)) - except Exception: - self.fail("Reraised wrong exception") - else: - self.fail("Didn't raise ZeroDivisionError") - - def test_nested_b_swallows(self): - @contextmanager - def a(): - yield - @contextmanager - def b(): - try: - yield - except: - # Swallow the exception - pass - try: - with nested(a(), b()): - 1 // 0 - except ZeroDivisionError: - self.fail("Didn't swallow ZeroDivisionError") - - def test_nested_break(self): - @contextmanager - def a(): - yield - state = 0 - while True: - state += 1 - with nested(a(), a()): - break - state += 10 - self.assertEqual(state, 1) - - def test_nested_continue(self): - @contextmanager - def a(): - yield - state = 0 - while state < 3: - state += 1 - with nested(a(), a()): - continue - state += 10 - self.assertEqual(state, 3) - - def test_nested_return(self): - @contextmanager - def a(): - try: - yield - except: - pass - def foo(): - with nested(a(), a()): - return 1 - return 10 - self.assertEqual(foo(), 1) - -class ClosingTestCase(unittest.TestCase): - - # XXX This needs more work - - def test_closing(self): - state = [] - class C: - def close(self): - state.append(1) - x = C() - self.assertEqual(state, []) - with closing(x) as y: - self.assertEqual(x, y) - self.assertEqual(state, [1]) - - def test_closing_error(self): - state = [] - class C: - def close(self): - state.append(1) - x = C() - self.assertEqual(state, []) - try: - with closing(x) as y: - self.assertEqual(x, y) - 1 // 0 - except ZeroDivisionError: - self.assertEqual(state, [1]) - else: - self.fail("Didn't raise ZeroDivisionError") - -class FileContextTestCase(unittest.TestCase): - - def testWithOpen(self): - tfn = tempfile.mktemp() - try: - f = None - with open(tfn, "w") as f: - self.failIf(f.closed) - f.write("Booh\n") - self.failUnless(f.closed) - f = None - try: - with open(tfn, "r") as f: - self.failIf(f.closed) - self.assertEqual(f.read(), "Booh\n") - 1 // 0 - except ZeroDivisionError: - self.failUnless(f.closed) - else: - self.fail("Didn't raise ZeroDivisionError") - finally: - try: - os.remove(tfn) - except os.error: - pass - -class LockContextTestCase(unittest.TestCase): - - def boilerPlate(self, lock, locked): - self.failIf(locked()) - with lock: - self.failUnless(locked()) - self.failIf(locked()) - try: - with lock: - self.failUnless(locked()) - 1 // 0 - except ZeroDivisionError: - self.failIf(locked()) - else: - self.fail("Didn't raise ZeroDivisionError") - - def testWithLock(self): - lock = threading.Lock() - self.boilerPlate(lock, lock.locked) - - def testWithRLock(self): - lock = threading.RLock() - self.boilerPlate(lock, lock._is_owned) - - def testWithCondition(self): - lock = threading.Condition() - def locked(): - return lock._is_owned() - self.boilerPlate(lock, locked) - - def testWithSemaphore(self): - lock = threading.Semaphore() - def locked(): - if lock.acquire(False): - lock.release() - return False - else: - return True - self.boilerPlate(lock, locked) - - def testWithBoundedSemaphore(self): - lock = threading.BoundedSemaphore() - def locked(): - if lock.acquire(False): - lock.release() - return False - else: - return True - self.boilerPlate(lock, locked) - -# This is needed to make the test actually run under regrtest.py! -def test_main(): - test_support.run_unittest(__name__) - - -if __name__ == "__main__": - test_main() Deleted: trunk/jython/Lib/test/test_email.py =================================================================== --- trunk/jython/Lib/test/test_email.py 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/test_email.py 2011-03-14 03:06:43 UTC (rev 7231) @@ -1,12 +0,0 @@ -# Copyright (C) 2001,2002 Python Software Foundation -# email package unit tests - -# The specific tests now live in Lib/email/test -from email.test.test_email import suite -from test import test_support - -def test_main(): - test_support.run_unittest(suite()) - -if __name__ == '__main__': - test_main() Deleted: trunk/jython/Lib/test/test_email_renamed.py =================================================================== --- trunk/jython/Lib/test/test_email_renamed.py 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/test_email_renamed.py 2011-03-14 03:06:43 UTC (rev 7231) @@ -1,12 +0,0 @@ -# Copyright (C) 2001-2006 Python Software Foundation -# email package unit tests - -# The specific tests now live in Lib/email/test -from email.test.test_email_renamed import suite -from test import test_support - -def test_main(): - test_support.run_unittest(suite()) - -if __name__ == '__main__': - test_main() Deleted: trunk/jython/Lib/test/test_gettext.py =================================================================== --- trunk/jython/Lib/test/test_gettext.py 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/test_gettext.py 2011-03-14 03:06:43 UTC (rev 7231) @@ -1,447 +0,0 @@ -import os -import base64 -import shutil -import gettext -import unittest - -from test import test_support - - -# TODO: -# - Add new tests, for example for "dgettext" -# - Remove dummy tests, for example testing for single and double quotes -# has no sense, it would have if we were testing a parser (i.e. pygettext) -# - Tests should have only one assert. - -GNU_MO_DATA = '''\ -3hIElQAAAAAGAAAAHAAAAEwAAAALAAAAfAAAAAAAAACoAAAAFQAAAKkAAAAjAAAAvwAAAKEAAADj -AAAABwAAAIUBAAALAAAAjQEAAEUBAACZAQAAFgAAAN8CAAAeAAAA9gIAAKEAAAAVAwAABQAAALcD -AAAJAAAAvQMAAAEAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABQAAAAYAAAACAAAAAFJh -eW1vbmQgTHV4dXJ5IFlhY2gtdABUaGVyZSBpcyAlcyBmaWxlAFRoZXJlIGFyZSAlcyBmaWxlcwBU -aGlzIG1vZHVsZSBwcm92aWRlcyBpbnRlcm5hdGlvbmFsaXphdGlvbiBhbmQgbG9jYWxpemF0aW9u -CnN1cHBvcnQgZm9yIHlvdXIgUHl0aG9uIHByb2dyYW1zIGJ5IHByb3ZpZGluZyBhbiBpbnRlcmZh -Y2UgdG8gdGhlIEdOVQpnZXR0ZXh0IG1lc3NhZ2UgY2F0YWxvZyBsaWJyYXJ5LgBtdWxsdXNrAG51 -ZGdlIG51ZGdlAFByb2plY3QtSWQtVmVyc2lvbjogMi4wClBPLVJldmlzaW9uLURhdGU6IDIwMDAt -MDgtMjkgMTI6MTktMDQ6MDAKTGFzdC1UcmFuc2xhdG9yOiBKLiBEYXZpZCBJYsOhw7FleiA8ai1k -YXZpZEBub29zLmZyPgpMYW5ndWFnZS1UZWFtOiBYWCA8cHl0aG9uLWRldkBweXRob24ub3JnPgpN -SU1FLVZlcnNpb246IDEuMApDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9aXNvLTg4 -NTktMQpDb250ZW50LVRyYW5zZmVyLUVuY29kaW5nOiBub25lCkdlbmVyYXRlZC1CeTogcHlnZXR0 -ZXh0LnB5IDEuMQpQbHVyYWwtRm9ybXM6IG5wbHVyYWxzPTI7IHBsdXJhbD1uIT0xOwoAVGhyb2F0 -d29iYmxlciBNYW5ncm92ZQBIYXkgJXMgZmljaGVybwBIYXkgJXMgZmljaGVyb3MAR3V2ZiB6YnFo -eXIgY2ViaXZxcmYgdmFncmVhbmd2YmFueXZtbmd2YmEgbmFxIHlicG55dm1uZ3ZiYQpmaGNjYmVn -IHNiZSBsYmhlIENsZ3ViYSBjZWJ0ZW56ZiBvbCBjZWJpdnF2YXQgbmEgdmFncmVzbnByIGdiIGd1 -ciBUQUgKdHJnZ3JrZyB6cmZmbnRyIHBuZ255YnQgeXZvZW5lbC4AYmFjb24Ad2luayB3aW5rAA== -''' - -UMO_DATA = '''\ -3hIElQAAAAACAAAAHAAAACwAAAAFAAAAPAAAAAAAAABQAAAABAAAAFEAAAAPAQAAVgAAAAQAAABm -AQAAAQAAAAIAAAAAAAAAAAAAAAAAAAAAYWLDngBQcm9qZWN0LUlkLVZlcnNpb246IDIuMApQTy1S -ZXZpc2lvbi1EYXRlOiAyMDAzLTA0LTExIDEyOjQyLTA0MDAKTGFzdC1UcmFuc2xhdG9yOiBCYXJy -eSBBLiBXQXJzYXcgPGJhcnJ5QHB5dGhvbi5vcmc+Ckxhbmd1YWdlLVRlYW06IFhYIDxweXRob24t -ZGV2QHB5dGhvbi5vcmc+Ck1JTUUtVmVyc2lvbjogMS4wCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFp -bjsgY2hhcnNldD11dGYtOApDb250ZW50LVRyYW5zZmVyLUVuY29kaW5nOiA3Yml0CkdlbmVyYXRl -ZC1CeTogbWFudWFsbHkKAMKkeXoA -''' - -MMO_DATA = '''\ -3hIElQAAAAABAAAAHAAAACQAAAADAAAALAAAAAAAAAA4AAAAeAEAADkAAAABAAAAAAAAAAAAAAAA -UHJvamVjdC1JZC1WZXJzaW9uOiBObyBQcm9qZWN0IDAuMApQT1QtQ3JlYXRpb24tRGF0ZTogV2Vk -IERlYyAxMSAwNzo0NDoxNSAyMDAyClBPLVJldmlzaW9uLURhdGU6IDIwMDItMDgtMTQgMDE6MTg6 -NTgrMDA6MDAKTGFzdC1UcmFuc2xhdG9yOiBKb2huIERvZSA8amRvZUBleGFtcGxlLmNvbT4KSmFu -ZSBGb29iYXIgPGpmb29iYXJAZXhhbXBsZS5jb20+Ckxhbmd1YWdlLVRlYW06IHh4IDx4eEBleGFt -cGxlLmNvbT4KTUlNRS1WZXJzaW9uOiAxLjAKQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFy -c2V0PWlzby04ODU5LTE1CkNvbnRlbnQtVHJhbnNmZXItRW5jb2Rpbmc6IHF1b3RlZC1wcmludGFi -bGUKR2VuZXJhdGVkLUJ5OiBweWdldHRleHQucHkgMS4zCgA= -''' - -LOCALEDIR = os.path.join('xx', 'LC_MESSAGES') -MOFILE = os.path.join(LOCALEDIR, 'gettext.mo') -UMOFILE = os.path.join(LOCALEDIR, 'ugettext.mo') -MMOFILE = os.path.join(LOCALEDIR, 'metadata.mo') -try: - LANG = os.environ['LANGUAGE'] -except: - LANG = 'en' - - -class GettextBaseTest(unittest.TestCase): - def setUp(self): - if not os.path.isdir(LOCALEDIR): - os.makedirs(LOCALEDIR) - fp = open(MOFILE, 'wb') - fp.write(base64.decodestring(GNU_MO_DATA)) - fp.close() - fp = open(UMOFILE, 'wb') - fp.write(base64.decodestring(UMO_DATA)) - fp.close() - fp = open(MMOFILE, 'wb') - fp.write(base64.decodestring(MMO_DATA)) - fp.close() - os.environ['LANGUAGE'] = 'xx' - - def tearDown(self): - os.environ['LANGUAGE'] = LANG - shutil.rmtree(os.path.split(LOCALEDIR)[0]) - - -class GettextTestCase1(GettextBaseTest): - def setUp(self): - GettextBaseTest.setUp(self) - self.localedir = os.curdir - self.mofile = MOFILE - gettext.install('gettext', self.localedir) - - def test_some_translations(self): - eq = self.assertEqual - # test some translations - eq(_('albatross'), 'albatross') - eq(_(u'mullusk'), 'bacon') - eq(_(r'Raymond Luxury Yach-t'), 'Throatwobbler Mangrove') - eq(_(ur'nudge nudge'), 'wink wink') - - def test_double_quotes(self): - eq = self.assertEqual - # double quotes - eq(_("albatross"), 'albatross') - eq(_(u"mullusk"), 'bacon') - eq(_(r"Raymond Luxury Yach-t"), 'Throatwobbler Mangrove') - eq(_(ur"nudge nudge"), 'wink wink') - - def test_triple_single_quotes(self): - eq = self.assertEqual - # triple single quotes - eq(_('''albatross'''), 'albatross') - eq(_(u'''mullusk'''), 'bacon') - eq(_(r'''Raymond Luxury Yach-t'''), 'Throatwobbler Mangrove') - eq(_(ur'''nudge nudge'''), 'wink wink') - - def test_triple_double_quotes(self): - eq = self.assertEqual - # triple double quotes - eq(_("""albatross"""), 'albatross') - eq(_(u"""mullusk"""), 'bacon') - eq(_(r"""Raymond Luxury Yach-t"""), 'Throatwobbler Mangrove') - eq(_(ur"""nudge nudge"""), 'wink wink') - - def test_multiline_strings(self): - eq = self.assertEqual - # multiline strings - eq(_('''This module provides internationalization and localization -support for your Python programs by providing an interface to the GNU -gettext message catalog library.'''), - '''Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba -fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH -trggrkg zrffntr pngnybt yvoenel.''') - - def test_the_alternative_interface(self): - eq = self.assertEqual - # test the alternative interface - fp = open(self.mofile, 'rb') - t = gettext.GNUTranslations(fp) - fp.close() - # Install the translation object - t.install() - eq(_('nudge nudge'), 'wink wink') - # Try unicode return type - t.install(unicode=True) - eq(_('mullusk'), 'bacon') - # Test installation of other methods - import __builtin__ - t.install(unicode=True, names=["gettext", "lgettext"]) - eq(_, t.ugettext) - eq(__builtin__.gettext, t.ugettext) - eq(lgettext, t.lgettext) - del __builtin__.gettext - del __builtin__.lgettext - - -class GettextTestCase2(GettextBaseTest): - def setUp(self): - GettextBaseTest.setUp(self) - self.localedir = os.curdir - # Set up the bindings - gettext.bindtextdomain('gettext', self.localedir) - gettext.textdomain('gettext') - # For convenience - self._ = gettext.gettext - - def test_bindtextdomain(self): - self.assertEqual(gettext.bindtextdomain('gettext'), self.localedir) - - def test_textdomain(self): - self.assertEqual(gettext.textdomain(), 'gettext') - - def test_some_translations(self): - eq = self.assertEqual - # test some translations - eq(self._('albatross'), 'albatross') - eq(self._(u'mullusk'), 'bacon') - eq(self._(r'Raymond Luxury Yach-t'), 'Throatwobbler Mangrove') - eq(self._(ur'nudge nudge'), 'wink wink') - - def test_double_quotes(self): - eq = self.assertEqual - # double quotes - eq(self._("albatross"), 'albatross') - eq(self._(u"mullusk"), 'bacon') - eq(self._(r"Raymond Luxury Yach-t"), 'Throatwobbler Mangrove') - eq(self._(ur"nudge nudge"), 'wink wink') - - def test_triple_single_quotes(self): - eq = self.assertEqual - # triple single quotes - eq(self._('''albatross'''), 'albatross') - eq(self._(u'''mullusk'''), 'bacon') - eq(self._(r'''Raymond Luxury Yach-t'''), 'Throatwobbler Mangrove') - eq(self._(ur'''nudge nudge'''), 'wink wink') - - def test_triple_double_quotes(self): - eq = self.assertEqual - # triple double quotes - eq(self._("""albatross"""), 'albatross') - eq(self._(u"""mullusk"""), 'bacon') - eq(self._(r"""Raymond Luxury Yach-t"""), 'Throatwobbler Mangrove') - eq(self._(ur"""nudge nudge"""), 'wink wink') - - def test_multiline_strings(self): - eq = self.assertEqual - # multiline strings - eq(self._('''This module provides internationalization and localization -support for your Python programs by providing an interface to the GNU -gettext message catalog library.'''), - '''Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba -fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH -trggrkg zrffntr pngnybt yvoenel.''') - - -class PluralFormsTestCase(GettextBaseTest): - def setUp(self): - GettextBaseTest.setUp(self) - self.mofile = MOFILE - - def test_plural_forms1(self): - eq = self.assertEqual - x = gettext.ngettext('There is %s file', 'There are %s files', 1) - eq(x, 'Hay %s fichero') - x = gettext.ngettext('There is %s file', 'There are %s files', 2) - eq(x, 'Hay %s ficheros') - - def test_plural_forms2(self): - eq = self.assertEqual - fp = open(self.mofile, 'rb') - t = gettext.GNUTranslations(fp) - fp.close() - x = t.ngettext('There is %s file', 'There are %s files', 1) - eq(x, 'Hay %s fichero') - x = t.ngettext('There is %s file', 'There are %s files', 2) - eq(x, 'Hay %s ficheros') - - def test_hu(self): - eq = self.assertEqual - f = gettext.c2py('0') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") - - def test_de(self): - eq = self.assertEqual - f = gettext.c2py('n != 1') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "10111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111") - - def test_fr(self): - eq = self.assertEqual - f = gettext.c2py('n>1') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "00111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111") - - def test_gd(self): - eq = self.assertEqual - f = gettext.c2py('n==1 ? 0 : n==2 ? 1 : 2') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "20122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222") - - def test_gd2(self): - eq = self.assertEqual - # Tests the combination of parentheses and "?:" - f = gettext.c2py('n==1 ? 0 : (n==2 ? 1 : 2)') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "20122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222") - - def test_lt(self): - eq = self.assertEqual - f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "20111111112222222222201111111120111111112011111111201111111120111111112011111111201111111120111111112011111111222222222220111111112011111111201111111120111111112011111111201111111120111111112011111111") - - def test_ru(self): - eq = self.assertEqual - f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "20111222222222222222201112222220111222222011122222201112222220111222222011122222201112222220111222222011122222222222222220111222222011122222201112222220111222222011122222201112222220111222222011122222") - - def test_pl(self): - eq = self.assertEqual - f = gettext.c2py('n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "20111222222222222222221112222222111222222211122222221112222222111222222211122222221112222222111222222211122222222222222222111222222211122222221112222222111222222211122222221112222222111222222211122222") - - def test_sl(self): - eq = self.assertEqual - f = gettext.c2py('n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3') - s = ''.join([ str(f(x)) for x in range(200) ]) - eq(s, "30122333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333012233333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333") - - def test_security(self): - raises = self.assertRaises - # Test for a dangerous expression - raises(ValueError, gettext.c2py, "os.chmod('/etc/passwd',0777)") - - -class UnicodeTranslationsTest(GettextBaseTest): - def setUp(self): - GettextBaseTest.setUp(self) - fp = open(UMOFILE, 'rb') - try: - self.t = gettext.GNUTranslations(fp) - finally: - fp.close() - self._ = self.t.ugettext - - def test_unicode_msgid(self): - unless = self.failUnless - unless(isinstance(self._(''), unicode)) - unless(isinstance(self._(u''), unicode)) - - def test_unicode_msgstr(self): - eq = self.assertEqual - eq(self._(u'ab\xde'), u'\xa4yz') - - -class WeirdMetadataTest(GettextBaseTest): - def setUp(self): - GettextBaseTest.setUp(self) - fp = open(MMOFILE, 'rb') - try: - try: - self.t = gettext.GNUTranslations(fp) - except: - self.tearDown() - raise - finally: - fp.close() - - def test_weird_metadata(self): - info = self.t.info() - self.assertEqual(info['last-translator'], - 'John Doe <jd...@ex...>\nJane Foobar <jf...@ex...>') - - -def test_main(): - test_support.run_unittest(__name__) - -if __name__ == '__main__': - test_main() - - -# For reference, here's the .po file used to created the GNU_MO_DATA above. -# -# The original version was automatically generated from the sources with -# pygettext. Later it was manually modified to add plural forms support. - -''' -# Dummy translation for the Python test_gettext.py module. -# Copyright (C) 2001 Python Software Foundation -# Barry Warsaw <ba...@py...>, 2000. -# -msgid "" -msgstr "" -"Project-Id-Version: 2.0\n" -"PO-Revision-Date: 2003-04-11 14:32-0400\n" -"Last-Translator: J. David Ibanez <j-...@no...>\n" -"Language-Team: XX <pyt...@py...>\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=iso-8859-1\n" -"Content-Transfer-Encoding: 8bit\n" -"Generated-By: pygettext.py 1.1\n" -"Plural-Forms: nplurals=2; plural=n!=1;\n" - -#: test_gettext.py:19 test_gettext.py:25 test_gettext.py:31 test_gettext.py:37 -#: test_gettext.py:51 test_gettext.py:80 test_gettext.py:86 test_gettext.py:92 -#: test_gettext.py:98 -msgid "nudge nudge" -msgstr "wink wink" - -#: test_gettext.py:16 test_gettext.py:22 test_gettext.py:28 test_gettext.py:34 -#: test_gettext.py:77 test_gettext.py:83 test_gettext.py:89 test_gettext.py:95 -msgid "albatross" -msgstr "" - -#: test_gettext.py:18 test_gettext.py:24 test_gettext.py:30 test_gettext.py:36 -#: test_gettext.py:79 test_gettext.py:85 test_gettext.py:91 test_gettext.py:97 -msgid "Raymond Luxury Yach-t" -msgstr "Throatwobbler Mangrove" - -#: test_gettext.py:17 test_gettext.py:23 test_gettext.py:29 test_gettext.py:35 -#: test_gettext.py:56 test_gettext.py:78 test_gettext.py:84 test_gettext.py:90 -#: test_gettext.py:96 -msgid "mullusk" -msgstr "bacon" - -#: test_gettext.py:40 test_gettext.py:101 -msgid "" -"This module provides internationalization and localization\n" -"support for your Python programs by providing an interface to the GNU\n" -"gettext message catalog library." -msgstr "" -"Guvf zbqhyr cebivqrf vagreangvbanyvmngvba naq ybpnyvmngvba\n" -"fhccbeg sbe lbhe Clguba cebtenzf ol cebivqvat na vagresnpr gb gur TAH\n" -"trggrkg zrffntr pngnybt yvoenel." - -# Manually added, as neither pygettext nor xgettext support plural forms -# in Python. -msgid "There is %s file" -msgid_plural "There are %s files" -msgstr[0] "Hay %s fichero" -msgstr[1] "Hay %s ficheros" -''' - -# Here's the second example po file example, used to generate the UMO_DATA -# containing utf-8 encoded Unicode strings - -''' -# Dummy translation for the Python test_gettext.py module. -# Copyright (C) 2001 Python Software Foundation -# Barry Warsaw <ba...@py...>, 2000. -# -msgid "" -msgstr "" -"Project-Id-Version: 2.0\n" -"PO-Revision-Date: 2003-04-11 12:42-0400\n" -"Last-Translator: Barry A. WArsaw <ba...@py...>\n" -"Language-Team: XX <pyt...@py...>\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=utf-8\n" -"Content-Transfer-Encoding: 7bit\n" -"Generated-By: manually\n" - -#: nofile:0 -msgid "ab\xc3\x9e" -msgstr "\xc2\xa4yz" -''' - -# Here's the third example po file, used to generate MMO_DATA - -''' -msgid "" -msgstr "" -"Project-Id-Version: No Project 0.0\n" -"POT-Creation-Date: Wed Dec 11 07:44:15 2002\n" -"PO-Revision-Date: 2002-08-14 01:18:58+00:00\n" -"Last-Translator: John Doe <jd...@ex...>\n" -"Jane Foobar <jf...@ex...>\n" -"Language-Team: xx <xx...@ex...>\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=iso-8859-15\n" -"Content-Transfer-Encoding: quoted-printable\n" -"Generated-By: pygettext.py 1.3\n" -''' Deleted: trunk/jython/Lib/test/test_global.py =================================================================== --- trunk/jython/Lib/test/test_global.py 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/test_global.py 2011-03-14 03:06:43 UTC (rev 7231) @@ -1,52 +0,0 @@ -"""Verify that warnings are issued for global statements following use.""" - -from test.test_support import run_unittest, check_syntax_error -import unittest -import warnings - - -class GlobalTests(unittest.TestCase): - - def test1(self): - prog_text_1 = """\ -def wrong1(): - a = 1 - b = 2 - global a - global b -""" - check_syntax_error(self, prog_text_1) - - def test2(self): - prog_text_2 = """\ -def wrong2(): - print x - global x -""" - check_syntax_error(self, prog_text_2) - - def test3(self): - prog_text_3 = """\ -def wrong3(): - print x - x = 2 - global x -""" - check_syntax_error(self, prog_text_3) - - def test4(self): - prog_text_4 = """\ -global x -x = 2 -""" - # this should work - compile(prog_text_4, "<test string>", "exec") - - -def test_main(): - with warnings.catch_warnings(): - warnings.filterwarnings("error", module="<test string>") - run_unittest(GlobalTests) - -if __name__ == "__main__": - test_main() Deleted: trunk/jython/Lib/test/test_wsgiref.py =================================================================== --- trunk/jython/Lib/test/test_wsgiref.py 2011-03-14 02:04:08 UTC (rev 7230) +++ trunk/jython/Lib/test/test_wsgiref.py 2011-03-14 03:06:43 UTC (rev 7231) @@ -1,621 +0,0 @@ -from __future__ import nested_scopes # Backward compat for 2.1 -from unittest import TestCase -from wsgiref.util import setup_testing_defaults -from wsgiref.headers import Headers -from wsgiref.handlers import BaseHandler, BaseCGIHandler -from wsgiref import util -from wsgiref.validate import validator -from wsgiref.simple_server import WSGIServer, WSGIRequestHandler, demo_app -from wsgiref.simple_server import make_server -from StringIO import StringIO -from SocketServer import BaseServer -import os -import re -import sys - -from test import test_support - -class MockServer(WSGIServer): - """Non-socket HTTP server""" - - def __init__(self, server_address, RequestHandlerClass): - BaseServer.__init__(self, server_address, RequestHandlerClass) - self.server_bind() - - def server_bind(self): - host, port = self.server_address - self.server_name = host - self.server_port = port - self.setup_environ() - - -class MockHandler(WSGIRequestHandler): - """Non-socket HTTP handler""" - def setup(self): - self.connection = self.request - self.rfile, self.wfile = self.connection - - def finish(self): - pass - - - - - -def hello_app(environ,start_response): - start_response("200 OK", [ - ('Content-Type','text/plain'), - ('Date','Mon, 05 Jun 2006 18:49:54 GMT') - ]) - return ["Hello, world!"] - -def run_amock(app=hello_app, data="GET / HTTP/1.0\n\n"): - server = make_server("", 80, app, MockServer, MockHandler) - inp, out, err, olderr = StringIO(data), StringIO(), StringIO(), sys.stderr - sys.stderr = err - - try: - server.finish_request((inp,out), ("127.0.0.1",8888)) - finally: - sys.stderr = olderr - - return out.getvalue(), err.getvalue() - - - - - - - - - - - - - - - - - - - - - - - -def compare_generic_iter(make_it,match): - """Utility to compare a generic 2.1/2.2+ iterator with an iterable - - If running under Python 2.2+, this tests the iterator using iter()/next(), - as well as __getitem__. 'make_it' must be a function returning a fresh - iterator to be tested (since this may test the iterator twice).""" - - it = make_it() - n = 0 - for item in match: - if not it[n]==item: raise AssertionError - n+=1 - try: - it[n] - except IndexError: - pass - else: - raise AssertionError("Too many items from __getitem__",it) - - try: - iter, StopIteration - except NameError: - pass - else: - # Only test iter mode under 2.2+ - it = make_it() - if not iter(it) is it: raise AssertionError - for item in match: - if not it.next()==item: raise AssertionError - try: - it.next() - except StopIteration: - pass - else: - raise AssertionError("Too many items from .next()",it) - - - - - - -class IntegrationTests(TestCase): - - def check_hello(self, out, has_length=True): - self.assertEqual(out, - "HTTP/1.0 200 OK\r\n" - "Server: WSGIServer/0.1 Python/"+sys.version.split()[0]+"\r\n" - "Content-Type: text/plain\r\n" - "Date: Mon, 05 Jun 2006 18:49:54 GMT\r\n" + - (has_length and "Content-Length: 13\r\n" or "") + - "\r\n" - "Hello, world!" - ) - - def test_plain_hello(self): - out, err = run_amock() - self.check_hello(out) - - def test_validated_hello(self): - out, err = run_amock(validator(hello_app)) - # the middleware doesn't support len(), so content-length isn't there - self.check_hello(out, has_length=False) - - def test_simple_validation_error(self): - def bad_app(environ,start_response): - start_response("200 OK", ('Content-Type','text/plain')) - return ["Hello, world!"] - out, err = run_amock(validator(bad_app)) - self.failUnless(out.endswith( - "A server error occurred. Please contact the administrator." - )) - self.assertEqual( - err.splitlines()[-2], - "AssertionError: Headers (('Content-Type', 'text/plain')) must" - " be of type list: <type 'tuple'>" - ) - - - - - - -class UtilityTests(TestCase): - - def checkShift(self,sn_in,pi_in,part,sn_out,pi_out): - env = {'SCRIPT_NAME':sn_in,'PATH_INFO':pi_in} - util.setup_testing_defaults(env) - self.assertEqual(util.shift_path_info(env),part) - self.assertEqual(env['PATH_INFO'],pi_out) - self.assertEqual(env['SCRIPT_NAME'],sn_out) - return env - - def checkDefault(self, key, value, alt=None): - # Check defaulting when empty - env = {} - util.setup_testing_defaults(env) - if isinstance(value,StringIO): - self.failUnless(isinstance(env[key],StringIO)) - else: - self.assertEqual(env[key],value) - - # Check existing value - env = {key:alt} - util.setup_testing_defaults(env) - self.failUnless(env[key] is alt) - - def checkCrossDefault(self,key,value,**kw): - util.setup_testing_defaults(kw) - self.assertEqual(kw[key],value) - - def checkAppURI(self,uri,**kw): - util.setup_testing_defaults(kw) - self.assertEqual(util.application_uri(kw),uri) - - def checkReqURI(self,uri,query=1,**kw): - util.setup_testing_defaults(kw) - self.assertEqual(util.request_uri(kw,query),uri) - - - - - - - def checkFW(self,text,size,match): - - def make_it(text=text,size=size): - return util.FileWrapper(StringIO(text),size) - - compare_generic_iter(make_it,match) - - it = make_it() - self.failIf(it.filelike.closed) - - for item in it: - pass - - self.failIf(it.filelike.closed) - - it.close() - self.failUnless(it.filelike.closed) - - - def testSimpleShifts(self): - self.checkShift('','/', '', '/', '') - self.checkShift('','/x', 'x', '/x', '') - self.checkShift('/','', None, '/', '') - self.checkShift('/a','/x/y', 'x', '/a/x', '/y') - self.checkShift('/a','/x/', 'x', '/a/x', '/') - - - def testNormalizedShifts(self): - self.checkShift('/a/b', '/../y', '..', '/a', '/y') - self.checkShift('', '/../y', '..', '', '/y') - self.checkShift('/a/b', '//y', 'y', '/a/b/y', '') - self.checkShift('/a/b', '//y/', 'y', '/a/b/y', '/') - self.checkShift('/a/b', '/./y', 'y', '/a/b/y', '') - self.checkShift('/a/b', '/./y/', 'y', '/a/b/y', '/') - self.checkShift('/a/b', '///./..//y/.//', '..', '/a', '/y/') - self.checkShift('/a/b', '///', '', '/a/b/', '') - self.checkShift('/a/b', '/.//', '', '/a/b/', '') - self.checkShift('/a/b', '/x//', 'x', '/a/b/x', '/') - self.checkShift('/a/b', '/.', None, '/a/b', '') - - - def testDefaults(self): - for key, value in [ - ('SERVER_NAME','127.0.0.1'), - ('SERVER_PORT', '80'), - ('SERVER_PROTOCOL','HTTP/1.0'), - ('HTTP_HOST','127.0.0.1'), - ('REQUEST_METHOD','GET'), - ('SCRIPT_NAME',''), - ('PATH_INFO','/'), - ('wsgi.version', (1,0)), - ('wsgi.run_once', 0), - ('wsgi.multithread', 0), - ('wsgi.multiprocess', 0), - ('wsgi.input', StringIO("")), - ('wsgi.errors', StringIO()), - ('wsgi.url_scheme','http'), - ]: - self.checkDefault(key,value) - - - def testCrossDefaults(self): - self.checkCrossDefault('HTTP_HOST',"foo.bar",SERVER_NAME="foo.bar") - self.checkCrossDefault('wsgi.url_scheme',"https",HTTPS="on") - self.checkCrossDefault('wsgi.url_scheme',"https",HTTPS="1") - self.checkCrossDefault('wsgi.url_scheme',"https",HTTPS="yes") - self.checkCrossDefault('wsgi.url_scheme',"http",HTTPS="foo") - self.checkCrossDefault('SERVER_PORT',"80",HTTPS="foo") - self.checkCrossDefault('SERVER_PORT',"443",HTTPS="on") - - - def testGuessScheme(self): - self.assertEqual(util.guess_scheme({}), "http") - self.assertEqual(util.guess_scheme({'HTTPS':"foo"}), "http") - self.assertEqual(util.guess_scheme({'HTTPS':"on"}), "https") - self.assertEqual(util.guess_scheme({'HTTPS':"yes"}), "https") - self.assertEqual(util.guess_scheme({'HTTPS':"1"}), "https") - - - - - - def testAppURIs(self): - self.checkAppURI("http://127.0.0.1/") - self.checkAppURI("http://127.0.0.1/spam", SCRIPT_NAME="/spam") - self.checkAppURI("http://spam.example.com:2071/", - HTTP_HOST="spam.example.com:2071", SERVER_PORT="2071") - self.checkAppURI("http://spam.example.com/", - SERVER_NAME="spam.example.com") - self.checkAppURI("http://127.0.0.1/", - HTTP_HOST="127.0.0.1", SERVER_NAME="spam.example.com") - self.checkAppURI("https://127.0.0.1/", HTTPS="on") - self.checkAppURI("http://127.0.0.1:8000/", SERVER_PORT="8000", - HTTP_HOST=None) - - def testReqURIs(self): - self.checkReqURI("http://127.0.0.1/") - self.checkReqURI("http://127.0.0.1/spam", SCRIPT_NAME="/spam") - self.checkReqURI("http://127.0.0.1/spammity/spam", - SCRIPT_NAME="/spammity", PATH_INFO="/spam") - self.checkReqURI("http://127.0.0.1/spammity/spam?say=ni", - SCRIPT_NAME="/spammity", PATH_INFO="/spam",QUERY_STRING="say=ni") - self.checkReqURI("http://127.0.0.1/spammity/spam", 0, - SCRIPT_NAME="/spammity", PATH_INFO="/spam",QUERY_STRING="say=ni") - - def testFileWrapper(self): - self.checkFW("xyz"*50, 120, ["xyz"*40,"xyz"*10]) - - def testHopByHop(self): - for hop in ( - "Connection Keep-Alive Proxy-Authenticate Proxy-Authorization " - "TE Trailers Transfer-Encoding Upgrade" - ).split(): - for alt in hop, hop.title(), hop.upper(), hop.lower(): - self.failUnless(util.is_hop_by_hop(alt)) - - # Not comprehensive, just a few random header names - for hop in ( - "Accept Cache-Control Date Pragma Trailer Via Warning" - ).split(): - for alt in hop, hop.title(), hop.upper(), hop.lower(): - self.failIf(util.is_hop_by_hop(alt)) - -class HeaderTests(TestCase): - - def testMappingInterface(self): - test = [('x','y')] - self.assertEqual(len(Headers([])),0) - self.assertEqual(len(Headers(test[:])),1) - self.assertEqual(Headers(test[:]).keys(), ['x']) - self.assertEqual(Headers(test[:]).values(), ['y']) - self.assertEqual(Headers(test[:]).items(), test) - self.failIf(Headers(test).items() is test) # must be copy! - - h=Headers([]) - del h['foo'] # should not raise an error - - h['Foo'] = 'bar' - for m in h.has_key, h.__contains__, h.get, h.get_all, h.__getitem__: - self.failUnless(m('foo')) - self.failUnless(m('Foo')) - self.failUnless(m('FOO')) - self.failIf(m('bar')) - - self.assertEqual(h['foo'],'bar') - h['foo'] = 'baz' - self.assertEqual(h['FOO'],'baz') - self.assertEqual(h.get_all('foo'),['baz']) - - self.assertEqual(h.get("foo","whee"), "baz") - self.assertEqual(h.get("zoo","whee"), "whee") - self.assertEqual(h.setdefault("foo","whee"), "baz") - self.assertEqual(h.setdefault("zoo","whee"), "whee") - self.assertEqual(h["foo"],"baz") - self.assertEqual(h["zoo"],"whee") - - def testRequireList(self): - self.assertRaises(TypeError, Headers, "foo") - - - def testExtras(self): - h = Headers([]) - self.assertEqual(str(h),'\r\n') - - h.add_header('foo','bar',baz="spam") - self.assertEqual(h['foo'], 'bar; baz="spam"') - self.assertEqual(str(h),'foo: bar; baz="spam"\r\n\r\n') - - h.add_header('Foo','bar',cheese=None) - self.assertEqual(h.get_all('foo'), - ['bar; baz="spam"', 'bar; cheese']) - - self.assertEqual(str(h), - 'foo: bar; baz="spam"\r\n' - 'Foo: bar; cheese\r\n' - '\r\n' - ) - - -class ErrorHandler(BaseCGIHandler): - """Simple handler subclass for testing BaseHandler""" - - # BaseHandler records the OS environment at import time, but envvars - # might have been changed later by other tests, which trips up - # HandlerTests.testEnviron(). - os_environ = dict(os.environ.items()) - - def __init__(self,**kw): - setup_testing_defaults(kw) - BaseCGIHandler.__init__( - self, StringIO(''), StringIO(), StringIO(), kw, - multithread=True, multiprocess=True - ) - -class TestHandler(ErrorHandler): - """Simple handler subclass for testing BaseHandler, w/error passthru""" - - def handle_error(self): - raise # for testing, we want to see what's happening - - - - - - - - - - - -class HandlerTests(TestCase): - - def checkEnvironAttrs(self, handler): - env = handler.environ - for attr in [ - 'version','multithread','multiprocess','run_once','file_wrapper' - ]: - if attr=='file_wrapper' and handler.wsgi_file_wrapper is None: - continue - self.assertEqual(getattr(handler,'wsgi_'+attr),env['wsgi.'+attr]) - - def checkOSEnviron(self,handler): - empty = {}; setup_testing_defaults(empty) - env = handler.environ - from os import environ - for k,v in environ.items(): - if k not in empty: - self.assertEqual(env[k],v) - for k,v in empty.items(): - self.assertTrue(k in env) - - def testEnviron(self): - h = TestHandler(X="Y") - h.setup_environ() - self.checkEnvironAttrs(h) - self.checkOSEnviron(h) - self.assertEqual(h.environ["X"],"Y") - - def testCGIEnviron(self): - h = BaseCGIHandler(None,None,None,{}) - h.setup_environ() - for key in 'wsgi.url_scheme', 'wsgi.input', 'wsgi.errors': - self.assertTrue(key in h.environ) - - def testScheme(self): - h=TestHandler(HTTPS="on"); h.setup_environ() - self.assertEqual(h.environ['wsgi.url_scheme'],'https') - h=TestHandler(); h.setup_environ() - self.assertEqual(h.environ['wsgi.url_scheme'],'http') - - - def testAbstractMethods(self): - h = BaseHandler() - for name in [ - '_flush','get_stdin','get_stderr','add_cgi_vars' - ]: - self.assertRaises(NotImplementedError, getattr(h,name)) - self.assertRaises(NotImplementedError, h._write, "test") - - - def testContentLength(self): - # Demo one reason iteration is better than write()... ;) - - def trivial_app1(e,s): - s('200 OK',[]) - return [e['wsgi.url_scheme']] - - def trivial_app2(e,s): - s('200 OK',[])(e['wsgi.url_scheme']) - return [] - - h = TestHandler() - h.run(trivial_app1) - self.assertEqual(h.stdout.getvalue(), - "Status: 200 OK\r\n" - "Content-Length: 4\r\n" - "\r\n" - "http") - - h = TestHandler() - h.run(trivial_app2) - self.assertEqual(h.stdout.getvalue(), - "Status: 200 OK\r\n" - "\r\n" - "http") - - - - - - - - def testBasicErrorOutput(self): - - def non_error_app(e,s): - s('200 OK',[]) - return [] - - def error_app(e,s): - raise AssertionError("This should be caught by handler") - - h = ErrorHandler() - h.run(non_error_app) - self.assertEqual(h.stdout.getvalue(), - "Status: 200 OK\r\n" - "Content-Length: 0\r\n" - "\r\n") - self.assertEqual(h.stderr.getvalue(),"") - - h = ErrorHandler() - h.run(error_app) - self.assertEqual(h.stdout.getvalue(), - "Status: %s\r\n" - "Content-Type: text/plain\r\n" - "Content-Length: %d\r\n" - "\r\n%s" % (h.error_status,len(h.error_body),h.error_body)) - - self.assertTrue("AssertionError" in h.stderr.getvalue(), - "AssertionError not in stderr") - - def testErrorAfterOutput(self): - MSG = "Some output has been sent" - def error_app(e,s): - s("200 OK",[])(MSG) - raise AssertionError("This should be caught by handler") - - h = ErrorHandler() - h.run(error_app) - self.assertEqual(h.stdout.getvalue(), - "Status: 200 OK\r\n" - "\r\n"+MSG) - self.assertTrue("AssertionError" in h.stderr.getvalue(), - "AssertionError not in stderr") - - - def testHeaderFormats(self): - - def non_error_app(e,s): - s('200 OK',[]) - return [] - - stdpat = ( - r"HTTP/%s 200 OK\r\n" - r"Date: \w{3}, [ 0123]\d \w{3} \d{4} \d\d:\d\d:\d\d GMT\r\n" - r"%s" r"Content-Length: 0\r\n" r"\r\n" - ) - shortpat = ( - "Status: 200 OK\r\n" "Content-Length: 0\r\n" "\r\n" - ) - - for ssw in "FooBar/1.0", None: - sw = ssw and "Server: %s\r\n" % ssw or "" - - for version in "1.0", "1.1": - for proto in "HTTP/0.9", "HTTP/1.0", "HTTP/1.1": - - h = TestHandler(SERVER_PROTOCOL=proto) - h.origin_server = False - h.http_version = version - h.server_software = ssw - h.run(non_error_app) - self.assertEqual(shortpat,h.stdout.getvalue()) - - h = TestHandler(SERVER_PROTOCOL=proto) - h.origin_server = True - h.http_version = version - h.server_software = ssw - h.run(non_error_app) - if proto=="HTTP/0.9": - self.assertEqual(h.stdout.getvalue(),"") - else: - self.failUnless( - re.match(stdpat%(version,sw), h.stdout.getvalue()), - (stdpat%(version,sw), h.stdout.getvalue()) - ) - -# This epilogue is needed for compatibility with the Python 2.5 regrtest module - -def test_main(): - test_support.run_unittest(__name__) - -if __name__ == "__main__": - test_main() - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# the above lines intentionally left blank This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-14 02:04:16
|
Revision: 7230 http://jython.svn.sourceforge.net/jython/?rev=7230&view=rev Author: pjenvey Date: 2011-03-14 02:04:08 +0000 (Mon, 14 Mar 2011) Log Message: ----------- reapply our junit_xml hooks Modified Paths: -------------- trunk/jython/Lib/test/test_support.py Modified: trunk/jython/Lib/test/test_support.py =================================================================== --- trunk/jython/Lib/test/test_support.py 2011-03-14 01:52:02 UTC (rev 7229) +++ trunk/jython/Lib/test/test_support.py 2011-03-14 02:04:08 UTC (rev 7230) @@ -826,7 +826,28 @@ def _run_suite(suite): """Run tests from a unittest.TestSuite-derived class.""" - if verbose: + if not junit_xml_dir: + # Splitting tests apart slightly changes the handling of the + # TestFailed message + return _run_suite(suite, testclass) + + failed = False + for test in suite: + suite = unittest.TestSuite() + suite.addTest(test) + try: + _run_suite(suite, testclass) + except TestFailed, e: + if not failed: + failed = e + if failed: + raise failed + +def _run_suite(suite, testclass=None): + if junit_xml_dir: + from junit_xml import JUnitXMLTestRunner + runner = JUnitXMLTestRunner(junit_xml_dir) + elif verbose: runner = unittest.TextTestRunner(sys.stdout, verbosity=2) else: runner = BasicTestRunner() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-14 01:52:08
|
Revision: 7229 http://jython.svn.sourceforge.net/jython/?rev=7229&view=rev Author: pjenvey Date: 2011-03-14 01:52:02 +0000 (Mon, 14 Mar 2011) Log Message: ----------- reapply all our changes Modified Paths: -------------- trunk/jython/Lib/test/regrtest.py Modified: trunk/jython/Lib/test/regrtest.py =================================================================== --- trunk/jython/Lib/test/regrtest.py 2011-03-14 01:51:34 UTC (rev 7228) +++ trunk/jython/Lib/test/regrtest.py 2011-03-14 01:52:02 UTC (rev 7229) @@ -15,6 +15,8 @@ -s: single -- run only a single test (see below) -S: slow -- print the slowest 10 tests -r: random -- randomize test execution order +-m: memo -- save results to file +-j: junit-xml -- save results as JUnit XML to files in directory -f: fromfile -- read names of tests to run from a file (see below) -l: findleaks -- if GC is available detect tests that leak memory -u: use -- specify which special resource intensive tests to run @@ -26,6 +28,7 @@ -L: runleaks -- run the leaks(1) command just before exit -R: huntrleaks -- search for reference leaks (needs debug build, v. slow) -M: memlimit -- run very large memory-consuming tests +-e: expected -- run only tests that are expected to run and pass If non-option arguments are present, they are names for tests to run, unless -x is given, in which case they are names for tests not to run. @@ -169,6 +172,7 @@ newsoft = min(hard, max(soft, 1024*2048)) resource.setrlimit(resource.RLIMIT_STACK, (newsoft, hard)) +import test as _test from test import test_support RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network', 'bsddb', @@ -184,7 +188,8 @@ def main(tests=None, testdir=None, verbose=0, quiet=False, exclude=False, single=False, randomize=False, fromfile=None, findleaks=False, use_resources=None, trace=False, coverdir='coverage', - runleaks=False, huntrleaks=False, verbose2=False, print_slow=False): + runleaks=False, huntrleaks=False, verbose2=False, print_slow=False, + expected=False, memo=None, junit_xml=None): """Execute a test suite. This also parses command-line options and modifies its behavior @@ -209,17 +214,19 @@ test_support.record_original_stdout(sys.stdout) try: - opts, args = getopt.getopt(sys.argv[1:], 'hvqxsSrf:lu:t:TD:NLR:wM:', + opts, args = getopt.getopt(sys.argv[1:], 'hvqxsSrf:lu:t:TD:NLR:wM:em:j:', ['help', 'verbose', 'quiet', 'exclude', 'single', 'slow', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=', 'trace', 'coverdir=', 'nocoverdir', 'runleaks', 'huntrleaks=', 'verbose2', 'memlimit=', + 'expected', 'memo' ]) except getopt.error, msg: usage(2, msg) # Defaults + allran = True if use_resources is None: use_resources = [] for o, a in opts: @@ -234,6 +241,10 @@ verbose = 0 elif o in ('-x', '--exclude'): exclude = True + allran = False + elif o in ('-e', '--expected'): + expected = True + allran = False elif o in ('-s', '--single'): single = True elif o in ('-S', '--slow'): @@ -246,6 +257,10 @@ findleaks = True elif o in ('-L', '--runleaks'): runleaks = True + elif o in ('-m', '--memo'): + memo = a + elif o in ('-j', '--junit-xml'): + junit_xml = a elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) @@ -303,6 +318,8 @@ if findleaks: try: + if test_support.is_jython: + raise ImportError() import gc except ImportError: print 'No GC available, disabling findleaks.' @@ -337,6 +354,7 @@ # Strip .py extensions. if args: args = map(removepy, args) + allran = False if tests: tests = map(removepy, tests) @@ -360,8 +378,13 @@ test_times = [] test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources + test_support.junit_xml_dir = junit_xml save_modules = sys.modules.keys() + skips = _ExpectedSkips() + failures = _ExpectedFailures() for test in tests: + if expected and (test in skips or test in failures): + continue if not quiet: print test sys.stdout.flush() @@ -374,7 +397,7 @@ else: try: ok = runtest(test, verbose, quiet, test_times, - testdir, huntrleaks) + testdir, huntrleaks, junit_xml) except KeyboardInterrupt: # print a newline separate from the ^C print @@ -402,6 +425,9 @@ for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) + module = module[5:] + if hasattr(_test, module): + delattr(_test, module) if good and not quiet: if not bad and not skipped and len(good) > 1: @@ -412,27 +438,14 @@ print "10 slowest tests:" for time, test in test_times[:10]: print "%s: %.1fs" % (test, time) - if bad: - print count(len(bad), "test"), "failed:" - printlist(bad) + surprises = 0 if skipped and not quiet: print count(len(skipped), "test"), "skipped:" - printlist(skipped) + surprises += countsurprises(skips, skipped, 'skip', 'ran', allran, resource_denieds) + if bad: + print count(len(bad), "test"), "failed:" + surprises += countsurprises(failures, bad, 'fail', 'passed', allran, resource_denieds) - e = _ExpectedSkips() - plat = sys.platform - if e.isvalid(): - surprise = set(skipped) - e.getexpected() - set(resource_denieds) - if surprise: - print count(len(surprise), "skip"), \ - "unexpected on", plat + ":" - printlist(surprise) - else: - print "Those skips are all expected on", plat + "." - else: - print "Ask someone to teach regrtest.py about which tests are" - print "expected to get skipped on", plat + "." - if verbose2 and bad: print "Re-running failed tests in verbose mode" for test in bad: @@ -470,9 +483,12 @@ if runleaks: os.system("leaks %d" % os.getpid()) - sys.exit(len(bad) > 0) + if memo: + savememo(memo,good,bad,skipped) + sys.exit(surprises > 0) + STDTESTS = [ 'test_grammar', 'test_opcodes', @@ -512,7 +528,7 @@ return stdtests + tests def runtest(test, verbose, quiet, test_times, - testdir=None, huntrleaks=False): + testdir=None, huntrleaks=False, junit_xml=None): """Run a single test. test -- the name of the test @@ -531,12 +547,12 @@ try: return runtest_inner(test, verbose, quiet, test_times, - testdir, huntrleaks) + testdir, huntrleaks, junit_xml) finally: cleanup_test_droppings(test, verbose) def runtest_inner(test, verbose, quiet, test_times, - testdir=None, huntrleaks=False): + testdir=None, huntrleaks=False, junit_xml_dir=None): test_support.unload(test) if not testdir: testdir = findtestdir() @@ -545,8 +561,15 @@ else: capture_stdout = cStringIO.StringIO() + from test.junit_xml import Tee, write_direct_test try: save_stdout = sys.stdout + + indirect_test = None + if junit_xml_dir: + save_stderr = sys.stderr + sys.stdout = stdout = Tee(sys.stdout) + sys.stderr = stderr = Tee(sys.stderr) try: if capture_stdout: sys.stdout = capture_stdout @@ -562,29 +585,54 @@ # being imported. For tests based on unittest or doctest, # explicitly invoke their test_main() function (if it exists). indirect_test = getattr(the_module, "test_main", None) + test_time = None if indirect_test is not None: indirect_test() + elif junit_xml_dir: + test_time = time.time() - start_time + write_direct_test(junit_xml_dir, abstest, test_time, + stdout=stdout.getvalue(), + stderr=stderr.getvalue()) if huntrleaks: dash_R(the_module, test, indirect_test, huntrleaks) - test_time = time.time() - start_time + if test_time is None: + test_time = time.time() - start_time test_times.append((test_time, test)) finally: sys.stdout = save_stdout + if junit_xml_dir: + sys.stderr = save_stderr + test_time = time.time() - start_time except test_support.ResourceDenied, msg: if not quiet: print test, "skipped --", msg sys.stdout.flush() + if junit_xml_dir: + write_direct_test(junit_xml_dir, abstest, test_time, + 'skipped', sys.exc_info(), + stdout=stdout.getvalue(), + stderr=stderr.getvalue()) return -2 except (ImportError, test_support.TestSkipped), msg: if not quiet: print test, "skipped --", msg sys.stdout.flush() + if junit_xml_dir: + write_direct_test(junit_xml_dir, abstest, test_time, + 'skipped', sys.exc_info(), + stdout=stdout.getvalue(), + stderr=stderr.getvalue()) return -1 except KeyboardInterrupt: raise except test_support.TestFailed, msg: print "test", test, "failed --", msg sys.stdout.flush() + if junit_xml_dir and indirect_test is None: + write_direct_test(junit_xml_dir, abstest, test_time, + 'failure', sys.exc_info(), + stdout=stdout.getvalue(), + stderr=stderr.getvalue()) return 0 except: type, value = sys.exc_info()[:2] @@ -593,6 +641,11 @@ if verbose: traceback.print_exc(file=sys.stdout) sys.stdout.flush() + if junit_xml_dir and indirect_test is None: + write_direct_test(junit_xml_dir, abstest, test_time, + 'error', sys.exc_info(), + stdout=stdout.getvalue(), + stderr=stderr.getvalue()) return 0 else: # Except in verbose mode, tests should not print anything @@ -767,6 +820,23 @@ print fill(' '.join(str(elt) for elt in sorted(x)), width, initial_indent=blanks, subsequent_indent=blanks) +def countsurprises(expected, actual, action, antiaction, allran, resource_denieds): + """returns the number of items in actual that aren't in expected.""" + printlist(actual) + if not expected.isvalid(): + print "Ask someone to teach regrtest.py about which tests are" + print "expected to %s on %s." % (action, sys.platform) + return 1#Surprising not to know what to expect.... + good_surprise = expected.getexpected() - set(actual) + if allran and good_surprise: + print count(len(good_surprise), 'test'), antiaction, 'unexpectedly:' + printlist(good_surprise) + bad_surprise = set(actual) - expected.getexpected() - set(resource_denieds) + if bad_surprise: + print count(len(bad_surprise), action), "unexpected:" + printlist(bad_surprise) + return len(bad_surprise) + # Map sys.platform to a string containing the basenames of tests # expected to be skipped on that platform. # @@ -1107,20 +1177,144 @@ test_tcl test_multiprocessing """, + 'java': + """ + test__locale + test__rawffi + test_aepack + test_al + test_applesingle + test_audioop + test_bsddb + test_bsddb185 + test_bsddb3 + test_bz2 + test_cProfile + test_capi + test_cd + test_cl + test_commands + test_crypt + test_ctypes + test_curses + test_dbm + test_dl + test_email_codecs + test_fcntl + test_fork1 + test_gdbm + test_getargs2 + test_gl + test_hotshot + test_imageop + test_imgfile + test_ioctl + test_largefile + test_linuxaudiodev + test_locale + test_longexp + test_macfs + test_macostools + test_mmap + test_nis + test_normalization + test_openpty + test_ossaudiodev + test_parser + test_plistlib + test_poll + test_pty + test_resource + test_rgbimg + test_scriptpackages + test_socket_ssl + test_socketserver + test_sqlite + test_startfile + test_strop + test_structmembers + test_sunaudiodev + test_sundry + test_symtable + test_tcl + test_timeout + test_unicode_file + test_wait3 + test_wait4 + test_wave + test_winreg + test_winsound + test_zipfile64 + + test_gzip + test_ftplib + test_logging + test_poplib + test_pydoc + test_queue + test_smtplib + test_telnetlib + """ } _expectations['freebsd5'] = _expectations['freebsd4'] _expectations['freebsd6'] = _expectations['freebsd4'] _expectations['freebsd7'] = _expectations['freebsd4'] _expectations['freebsd8'] = _expectations['freebsd4'] +_failures = { + 'java': + """ + test_codecencodings_cn + test_codecencodings_hk + test_codecencodings_jp + test_codecencodings_kr + test_codecencodings_tw + test_codecmaps_cn + test_codecmaps_hk + test_codecmaps_jp + test_codecmaps_kr + test_codecmaps_tw + test_compiler + test_dis + test_dummy_threading + test_eof + test_frozen + test_gc + test_import + test_iterlen + test_multibytecodec + test_multibytecodec_support + test_peepholer + test_pyclbr + test_pyexpat + test_stringprep + test_threadsignals + test_transformer + test_ucn + test_unicodedata + test_zipimport + """, +} + +_platform = sys.platform +if _platform[:4] == 'java': + _platform = 'java' + if os._name == 'nt': + # XXX: Omitted for now because it fails so miserably and ruins + # other tests + _failures['java'] += '\ntest_mailbox' + if ' ' in sys.executable: + # http://bugs.python.org/issue1559298 + _failures['java'] += '\ntest_popen' + class _ExpectedSkips: def __init__(self): import os.path from test import test_timeout self.valid = False - if sys.platform in _expectations: - s = _expectations[sys.platform] + if _platform in _expectations: + s = _expectations[_platform] self.expected = set(s.split()) # expected to be skipped on every platform, even Linux @@ -1175,6 +1369,14 @@ if not sys.py3kwarning: self.expected.add('test_py3kwarn') + if test_support.is_jython: + if os._name != 'posix': + self.expected.update([ + 'test_grp', 'test_mhlib', 'test_posix', 'test_pwd', + 'test_signal']) + if os._name != 'nt': + self.expected.add('test_nt_paths_jy') + self.valid = True def isvalid(self): @@ -1190,6 +1392,28 @@ assert self.isvalid() return self.expected + def __contains__(self, key): + return key in self.expected + +class _ExpectedFailures(_ExpectedSkips): + def __init__(self): + self.valid = False + if _platform in _failures: + s = _failures[_platform] + self.expected = set(s.split()) + self.valid = True + +def savememo(memo,good,bad,skipped): + f = open(memo,'w') + try: + for n,l in [('good',good),('bad',bad),('skipped',skipped)]: + print >>f,"%s = [" % n + for x in l: + print >>f," %r," % x + print >>f," ]" + finally: + f.close() + if __name__ == '__main__': # Remove regrtest.py's own directory from the module search path. This # prevents relative imports from working, and relative imports will screw This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-14 01:51:41
|
Revision: 7228 http://jython.svn.sourceforge.net/jython/?rev=7228&view=rev Author: pjenvey Date: 2011-03-14 01:51:34 +0000 (Mon, 14 Mar 2011) Log Message: ----------- from: https://svn.python.org/projects/python/branches/release26-maint/Lib/test/regrtest.py@83687 Modified Paths: -------------- trunk/jython/Lib/test/regrtest.py Modified: trunk/jython/Lib/test/regrtest.py =================================================================== --- trunk/jython/Lib/test/regrtest.py 2011-03-13 18:54:43 UTC (rev 7227) +++ trunk/jython/Lib/test/regrtest.py 2011-03-14 01:51:34 UTC (rev 7228) @@ -11,12 +11,10 @@ -v: verbose -- run tests in verbose mode with output to stdout -w: verbose2 -- re-run failed tests in verbose mode -q: quiet -- don't print anything except if a test fails --g: generate -- write the output file for a test instead of comparing it -x: exclude -- arguments are tests to *exclude* -s: single -- run only a single test (see below) +-S: slow -- print the slowest 10 tests -r: random -- randomize test execution order --m: memo -- save results to file --j: junit-xml -- save results as JUnit XML to files in directory -f: fromfile -- read names of tests to run from a file (see below) -l: findleaks -- if GC is available detect tests that leak memory -u: use -- specify which special resource intensive tests to run @@ -28,14 +26,11 @@ -L: runleaks -- run the leaks(1) command just before exit -R: huntrleaks -- search for reference leaks (needs debug build, v. slow) -M: memlimit -- run very large memory-consuming tests --e: expected -- run only tests that are expected to run and pass If non-option arguments are present, they are names for tests to run, unless -x is given, in which case they are names for tests not to run. If no test names are given, all tests are run. --v is incompatible with -g and does not compare test output files. - -T turns on code coverage tracing with the trace module. -D specifies the directory where coverage files are put. @@ -96,6 +91,8 @@ curses - Tests that use curses and will modify the terminal's state and output modes. + lib2to3 - Run the tests for 2to3 (They take a while.) + largefile - It is okay to run some test that may create huge files. These tests can take a long time and may consume >2GB of disk space temporarily. @@ -124,15 +121,19 @@ option '-uall,-bsddb'. """ -import os -import sys +import cStringIO import getopt +import os import random -import warnings import re -import cStringIO -import traceback +import sys import time +import traceback +import warnings +# keep a reference to the ascii module to workaround #7140 bug +# (see issue #7027) +import encodings.ascii +import imp # I see no other way to suppress these warnings; # putting them in test_grammar.py has no effect: @@ -168,7 +169,6 @@ newsoft = min(hard, max(soft, 1024*2048)) resource.setrlimit(resource.RLIMIT_STACK, (newsoft, hard)) -import test as _test from test import test_support RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network', 'bsddb', @@ -181,11 +181,10 @@ sys.exit(code) -def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False, +def main(tests=None, testdir=None, verbose=0, quiet=False, exclude=False, single=False, randomize=False, fromfile=None, findleaks=False, use_resources=None, trace=False, coverdir='coverage', - runleaks=False, huntrleaks=False, verbose2=False, expected=False, - memo=None, junit_xml=None): + runleaks=False, huntrleaks=False, verbose2=False, print_slow=False): """Execute a test suite. This also parses command-line options and modifies its behavior @@ -202,27 +201,25 @@ command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. - The other default arguments (verbose, quiet, generate, exclude, single, - randomize, findleaks, use_resources, trace and coverdir) allow programmers - calling main() directly to set the values that would normally be set by - flags on the command line. + The other default arguments (verbose, quiet, exclude, + single, randomize, findleaks, use_resources, trace, coverdir, and + print_slow) allow programmers calling main() directly to set the + values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: - opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:TD:NLR:wM:em:j:', - ['help', 'verbose', 'quiet', 'generate', - 'exclude', 'single', 'random', 'fromfile', + opts, args = getopt.getopt(sys.argv[1:], 'hvqxsSrf:lu:t:TD:NLR:wM:', + ['help', 'verbose', 'quiet', 'exclude', + 'single', 'slow', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=', 'trace', 'coverdir=', 'nocoverdir', 'runleaks', 'huntrleaks=', 'verbose2', 'memlimit=', - 'expected', 'memo' ]) except getopt.error, msg: usage(2, msg) # Defaults - allran = True if use_resources is None: use_resources = [] for o, a in opts: @@ -235,16 +232,12 @@ elif o in ('-q', '--quiet'): quiet = True; verbose = 0 - elif o in ('-g', '--generate'): - generate = True elif o in ('-x', '--exclude'): exclude = True - allran = False - elif o in ('-e', '--expected'): - expected = True - allran = False elif o in ('-s', '--single'): single = True + elif o in ('-S', '--slow'): + print_slow = True elif o in ('-r', '--randomize'): randomize = True elif o in ('-f', '--fromfile'): @@ -253,10 +246,6 @@ findleaks = True elif o in ('-L', '--runleaks'): runleaks = True - elif o in ('-m', '--memo'): - memo = a - elif o in ('-j', '--junit-xml'): - junit_xml = a elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) @@ -300,8 +289,10 @@ use_resources.remove(r) elif r not in use_resources: use_resources.append(r) - if generate and verbose: - usage(2, "-g and -v don't go together!") + else: + print >>sys.stderr, ("No handler for option {0}. Please " + "report this as a bug at http://bugs.python.org.").format(o) + sys.exit(1) if single and fromfile: usage(2, "-s and -f don't go together!") @@ -312,8 +303,6 @@ if findleaks: try: - if test_support.is_jython: - raise ImportError() import gc except ImportError: print 'No GC available, disabling findleaks.' @@ -348,7 +337,6 @@ # Strip .py extensions. if args: args = map(removepy, args) - allran = False if tests: tests = map(removepy, tests) @@ -369,27 +357,24 @@ import trace tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix], trace=False, count=True) + test_times = [] test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources - test_support.junit_xml_dir = junit_xml save_modules = sys.modules.keys() - skips = _ExpectedSkips() - failures = _ExpectedFailures() for test in tests: - if expected and (test in skips or test in failures): - continue if not quiet: print test sys.stdout.flush() if trace: # If we're tracing code coverage, then we don't exit with status # if on a false return value from main. - tracer.runctx('runtest(test, generate, verbose, quiet, testdir)', + tracer.runctx('runtest(test, verbose, quiet,' + ' test_times, testdir)', globals=globals(), locals=vars()) else: try: - ok = runtest(test, generate, verbose, quiet, testdir, - huntrleaks, junit_xml) + ok = runtest(test, verbose, quiet, test_times, + testdir, huntrleaks) except KeyboardInterrupt: # print a newline separate from the ^C print @@ -417,38 +402,45 @@ for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) - module = module[5:] - if hasattr(_test, module): - delattr(_test, module) - # The lists won't be sorted if running with -r - good.sort() - bad.sort() - skipped.sort() - if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." - if verbose: - print "CAUTION: stdout isn't compared in verbose mode:" - print "a test that passes in verbose mode may fail without it." - surprises = 0 - if skipped and not quiet: - print count(len(skipped), "test"), "skipped:" - surprises += countsurprises(skips, skipped, 'skip', 'ran', allran, resource_denieds) + if print_slow: + test_times.sort(reverse=True) + print "10 slowest tests:" + for time, test in test_times[:10]: + print "%s: %.1fs" % (test, time) if bad: print count(len(bad), "test"), "failed:" - surprises += countsurprises(failures, bad, 'fail', 'passed', allran, resource_denieds) + printlist(bad) + if skipped and not quiet: + print count(len(skipped), "test"), "skipped:" + printlist(skipped) + e = _ExpectedSkips() + plat = sys.platform + if e.isvalid(): + surprise = set(skipped) - e.getexpected() - set(resource_denieds) + if surprise: + print count(len(surprise), "skip"), \ + "unexpected on", plat + ":" + printlist(surprise) + else: + print "Those skips are all expected on", plat + "." + else: + print "Ask someone to teach regrtest.py about which tests are" + print "expected to get skipped on", plat + "." + if verbose2 and bad: print "Re-running failed tests in verbose mode" for test in bad: print "Re-running test %r in verbose mode" % test sys.stdout.flush() try: - test_support.verbose = 1 - ok = runtest(test, generate, 1, quiet, testdir, + test_support.verbose = True + ok = runtest(test, True, quiet, test_times, testdir, huntrleaks) except KeyboardInterrupt: # print a newline separate from the ^C @@ -478,29 +470,32 @@ if runleaks: os.system("leaks %d" % os.getpid()) - if memo: - savememo(memo,good,bad,skipped) + sys.exit(len(bad) > 0) - sys.exit(surprises > 0) - STDTESTS = [ 'test_grammar', 'test_opcodes', - 'test_operations', + 'test_dict', 'test_builtin', 'test_exceptions', 'test_types', 'test_unittest', 'test_doctest', 'test_doctest2', + # On 2.6, when a C module like dl or linuxaudiodev is imported by some + # test, a DeprecationWarning is raised, but test_py3kwarn can not find + # it in the __warningregistry__ of the modules in sys.modules. + # C modules raise the warning only once, and since there's no way to + # find these warnings, test_py3kwarn is executed first to catch them + # before the other modules. This shouldn't affect 2.7+ + 'test_py3kwarn', ] NOTTESTS = [ 'test_support', 'test_future1', 'test_future2', - 'test_future3', ] def findtests(testdir=None, stdtests=STDTESTS, nottests=NOTTESTS): @@ -516,15 +511,14 @@ tests.sort() return stdtests + tests -def runtest(test, generate, verbose, quiet, testdir=None, huntrleaks=False, - junit_xml=None): +def runtest(test, verbose, quiet, test_times, + testdir=None, huntrleaks=False): """Run a single test. test -- the name of the test - generate -- if true, generate output, instead of running the test - and comparing it to a previously created output file verbose -- if true, print more messages quiet -- if true, don't print 'skipped' messages (probably redundant) + test_times -- a list of (time, test_name) pairs testdir -- test directory huntrleaks -- run multiple times to test for leaks; requires a debug build; a triple corresponding to -R's three arguments @@ -536,91 +530,61 @@ """ try: - return runtest_inner(test, generate, verbose, quiet, testdir, - huntrleaks, junit_xml) + return runtest_inner(test, verbose, quiet, test_times, + testdir, huntrleaks) finally: cleanup_test_droppings(test, verbose) -def runtest_inner(test, generate, verbose, quiet, - testdir=None, huntrleaks=False, junit_xml_dir=None): +def runtest_inner(test, verbose, quiet, test_times, + testdir=None, huntrleaks=False): test_support.unload(test) if not testdir: testdir = findtestdir() - outputdir = os.path.join(testdir, "output") - outputfile = os.path.join(outputdir, test) if verbose: - cfp = None + capture_stdout = None else: - cfp = cStringIO.StringIO() + capture_stdout = cStringIO.StringIO() - from test.junit_xml import Tee, write_direct_test try: save_stdout = sys.stdout - - indirect_test = None - if junit_xml_dir: - save_stderr = sys.stderr - sys.stdout = stdout = Tee(sys.stdout) - sys.stderr = stderr = Tee(sys.stderr) try: - if cfp: - sys.stdout = cfp - print test # Output file starts with test name + if capture_stdout: + sys.stdout = capture_stdout if test.startswith('test.'): abstest = test else: # Always import it from the test package abstest = 'test.' + test - start = time.time() + start_time = time.time() the_package = __import__(abstest, globals(), locals(), []) the_module = getattr(the_package, test) - # Most tests run to completion simply as a side-effect of - # being imported. For the benefit of tests that can't run - # that way (like test_threaded_import), explicitly invoke - # their test_main() function (if it exists). + # Old tests run to completion simply as a side-effect of + # being imported. For tests based on unittest or doctest, + # explicitly invoke their test_main() function (if it exists). indirect_test = getattr(the_module, "test_main", None) if indirect_test is not None: indirect_test() - elif junit_xml_dir: - write_direct_test(junit_xml_dir, abstest, time.time() - start, - stdout=stdout.getvalue(), - stderr=stderr.getvalue()) if huntrleaks: dash_R(the_module, test, indirect_test, huntrleaks) + test_time = time.time() - start_time + test_times.append((test_time, test)) finally: sys.stdout = save_stdout - if junit_xml_dir: - sys.stderr = save_stderr except test_support.ResourceDenied, msg: if not quiet: print test, "skipped --", msg sys.stdout.flush() - if junit_xml_dir: - write_direct_test(junit_xml_dir, abstest, time.time() - start, - 'skipped', sys.exc_info(), - stdout=stdout.getvalue(), - stderr=stderr.getvalue()) return -2 except (ImportError, test_support.TestSkipped), msg: if not quiet: print test, "skipped --", msg sys.stdout.flush() - if junit_xml_dir: - write_direct_test(junit_xml_dir, abstest, time.time() - start, - 'skipped', sys.exc_info(), - stdout=stdout.getvalue(), - stderr=stderr.getvalue()) return -1 except KeyboardInterrupt: raise except test_support.TestFailed, msg: print "test", test, "failed --", msg sys.stdout.flush() - if junit_xml_dir and indirect_test is None: - write_direct_test(junit_xml_dir, abstest, time.time() - start, - 'failure', sys.exc_info(), - stdout=stdout.getvalue(), - stderr=stderr.getvalue()) return 0 except: type, value = sys.exc_info()[:2] @@ -629,42 +593,19 @@ if verbose: traceback.print_exc(file=sys.stdout) sys.stdout.flush() - if junit_xml_dir and indirect_test is None: - write_direct_test(junit_xml_dir, abstest, time.time() - start, - 'error', sys.exc_info(), - stdout=stdout.getvalue(), - stderr=stderr.getvalue()) return 0 else: - if not cfp: + # Except in verbose mode, tests should not print anything + if verbose or huntrleaks: return 1 - output = cfp.getvalue() - if generate: - if output == test + "\n": - if os.path.exists(outputfile): - # Write it since it already exists (and the contents - # may have changed), but let the user know it isn't - # needed: - print "output file", outputfile, \ - "is no longer needed; consider removing it" - else: - # We don't need it, so don't create it. - return 1 - fp = open(outputfile, "w") - fp.write(output) - fp.close() + output = capture_stdout.getvalue() + if not output: return 1 - if os.path.exists(outputfile): - fp = open(outputfile, "r") - expected = fp.read() - fp.close() - else: - expected = test + "\n" - if output == expected or huntrleaks: - return 1 + print "test", test, "produced unexpected output:" + print "*" * 70 + print output + print "*" * 70 sys.stdout.flush() - reportdiff(expected, output) - sys.stdout.flush() return 0 def cleanup_test_droppings(testname, verbose): @@ -700,7 +641,7 @@ def dash_R(the_module, test, indirect_test, huntrleaks): # This code is hackish and inelegant, but it seems to do the job. - import copy_reg + import copy_reg, _abcoll, io if not hasattr(sys, 'gettotalrefcount'): raise Exception("Tracking reference leaks requires a debug build " @@ -710,41 +651,56 @@ fs = warnings.filters[:] ps = copy_reg.dispatch_table.copy() pic = sys.path_importer_cache.copy() + abcs = {} + modules = _abcoll, io + for abc in [getattr(mod, a) for mod in modules for a in mod.__all__]: + # XXX isinstance(abc, ABCMeta) leads to infinite recursion + if not hasattr(abc, '_abc_registry'): + continue + for obj in abc.__subclasses__() + [abc]: + abcs[obj] = obj._abc_registry.copy() if indirect_test: def run_the_test(): indirect_test() else: def run_the_test(): - reload(the_module) + imp.reload(the_module) deltas = [] nwarmup, ntracked, fname = huntrleaks repcount = nwarmup + ntracked print >> sys.stderr, "beginning", repcount, "repetitions" print >> sys.stderr, ("1234567890"*(repcount//10 + 1))[:repcount] - dash_R_cleanup(fs, ps, pic) + dash_R_cleanup(fs, ps, pic, abcs) for i in range(repcount): rc = sys.gettotalrefcount() run_the_test() sys.stderr.write('.') - dash_R_cleanup(fs, ps, pic) + dash_R_cleanup(fs, ps, pic, abcs) if i >= nwarmup: deltas.append(sys.gettotalrefcount() - rc - 2) print >> sys.stderr if any(deltas): - print >> sys.stderr, test, 'leaked', deltas, 'references' + msg = '%s leaked %s references, sum=%s' % (test, deltas, sum(deltas)) + print >> sys.stderr, msg refrep = open(fname, "a") - print >> refrep, test, 'leaked', deltas, 'references' + print >> refrep, msg refrep.close() -def dash_R_cleanup(fs, ps, pic): +def dash_R_cleanup(fs, ps, pic, abcs): import gc, copy_reg - import _strptime, linecache, dircache + import _strptime, linecache + dircache = test_support.import_module('dircache', deprecated=True) import urlparse, urllib, urllib2, mimetypes, doctest import struct, filecmp from distutils.dir_util import _path_created + # Clear the warnings registry, so they can be displayed again + for mod in sys.modules.values(): + if hasattr(mod, '__warningregistry__'): + del mod.__warningregistry__ + # Restore some original values. warnings.filters[:] = fs copy_reg.dispatch_table.clear() @@ -752,6 +708,15 @@ sys.path_importer_cache.clear() sys.path_importer_cache.update(pic) + # clear type cache + sys._clear_type_cache() + + # Clear ABC registries, restoring previously saved ABC registries. + for abc, registry in abcs.items(): + abc._abc_registry = registry.copy() + abc._abc_cache.clear() + abc._abc_negative_cache.clear() + # Clear assorted module caches. _path_created.clear() re.purge() @@ -762,55 +727,13 @@ dircache.reset() linecache.clearcache() mimetypes._default_mime_types() - struct._cache.clear() filecmp._cache.clear() + struct._clearcache() doctest.master = None # Collect cyclic trash. gc.collect() -def reportdiff(expected, output): - import difflib - print "*" * 70 - a = expected.splitlines(1) - b = output.splitlines(1) - sm = difflib.SequenceMatcher(a=a, b=b) - tuples = sm.get_opcodes() - - def pair(x0, x1): - # x0:x1 are 0-based slice indices; convert to 1-based line indices. - x0 += 1 - if x0 >= x1: - return "line " + str(x0) - else: - return "lines %d-%d" % (x0, x1) - - for op, a0, a1, b0, b1 in tuples: - if op == 'equal': - pass - - elif op == 'delete': - print "***", pair(a0, a1), "of expected output missing:" - for line in a[a0:a1]: - print "-", line, - - elif op == 'replace': - print "*** mismatch between", pair(a0, a1), "of expected", \ - "output and", pair(b0, b1), "of actual output:" - for line in difflib.ndiff(a[a0:a1], b[b0:b1]): - print line, - - elif op == 'insert': - print "***", pair(b0, b1), "of actual output doesn't appear", \ - "in expected output after line", str(a1)+":" - for line in b[b0:b1]: - print "+", line, - - else: - print "get_opcodes() returned bad tuple?!?!", (op, a0, a1, b0, b1) - - print "*" * 70 - def findtestdir(): if __name__ == '__main__': file = sys.argv[0] @@ -840,26 +763,10 @@ from textwrap import fill blanks = ' ' * indent - print fill(' '.join(map(str, sorted(x))), width, + # Print the sorted list: 'x' may be a '--random' list or a set() + print fill(' '.join(str(elt) for elt in sorted(x)), width, initial_indent=blanks, subsequent_indent=blanks) -def countsurprises(expected, actual, action, antiaction, allran, resource_denieds): - """returns the number of items in actual that aren't in expected.""" - printlist(actual) - if not expected.isvalid(): - print "Ask someone to teach regrtest.py about which tests are" - print "expected to %s on %s." % (action, sys.platform) - return 1#Surprising not to know what to expect.... - good_surprise = expected.getexpected() - set(actual) - if allran and good_surprise: - print count(len(good_surprise), 'test'), antiaction, 'unexpectedly:' - printlist(good_surprise) - bad_surprise = set(actual) - expected.getexpected() - set(resource_denieds) - if bad_surprise: - print count(len(bad_surprise), action), "unexpected:" - printlist(bad_surprise) - return len(bad_surprise) - # Map sys.platform to a string containing the basenames of tests # expected to be skipped on that platform. # @@ -873,17 +780,16 @@ # test_timeout # Controlled by test_timeout.skip_expected. Requires the network # resource and a socket module. +# +# Tests that are expected to be skipped everywhere except on one platform +# are also handled separately. _expectations = { 'win32': """ test__locale - test_applesingle - test_al test_bsddb185 test_bsddb3 - test_cd - test_cl test_commands test_crypt test_curses @@ -891,24 +797,22 @@ test_dl test_fcntl test_fork1 + test_epoll test_gdbm - test_gl test_grp - test_imgfile test_ioctl test_largefile - test_linuxaudiodev + test_kqueue test_mhlib - test_nis test_openpty test_ossaudiodev + test_pipes test_poll test_posix test_pty test_pwd test_resource test_signal - test_sunaudiodev test_threadsignals test_timing test_wait3 @@ -916,34 +820,20 @@ """, 'linux2': """ - test_al - test_applesingle test_bsddb185 - test_cd - test_cl test_curses test_dl - test_gl - test_imgfile test_largefile - test_linuxaudiodev - test_nis - test_ntpath + test_kqueue test_ossaudiodev - test_sqlite - test_startfile - test_sunaudiodev """, 'mac': """ - test_al test_atexit test_bsddb test_bsddb185 test_bsddb3 test_bz2 - test_cd - test_cl test_commands test_crypt test_curses @@ -951,16 +841,13 @@ test_dl test_fcntl test_fork1 - test_gl + test_epoll test_grp test_ioctl - test_imgfile test_largefile - test_linuxaudiodev test_locale + test_kqueue test_mmap - test_nis - test_ntpath test_openpty test_ossaudiodev test_poll @@ -971,88 +858,55 @@ test_pwd test_resource test_signal - test_sqlite - test_startfile - test_sunaudiodev test_sundry test_tarfile test_timing """, 'unixware7': """ - test_al - test_applesingle test_bsddb test_bsddb185 - test_cd - test_cl test_dl - test_gl - test_imgfile + test_epoll test_largefile - test_linuxaudiodev + test_kqueue test_minidom - test_nis - test_ntpath test_openpty test_pyexpat test_sax - test_startfile - test_sqlite - test_sunaudiodev test_sundry """, 'openunix8': """ - test_al - test_applesingle test_bsddb test_bsddb185 - test_cd - test_cl test_dl - test_gl - test_imgfile + test_epoll test_largefile - test_linuxaudiodev + test_kqueue test_minidom - test_nis - test_ntpath test_openpty test_pyexpat test_sax - test_sqlite - test_startfile - test_sunaudiodev test_sundry """, 'sco_sv3': """ - test_al - test_applesingle test_asynchat test_bsddb test_bsddb185 - test_cd - test_cl test_dl test_fork1 + test_epoll test_gettext - test_gl - test_imgfile test_largefile - test_linuxaudiodev test_locale + test_kqueue test_minidom - test_nis - test_ntpath test_openpty test_pyexpat test_queue test_sax - test_sqlite - test_startfile - test_sunaudiodev test_sundry test_thread test_threaded_import @@ -1061,40 +915,30 @@ """, 'riscos': """ - test_al - test_applesingle test_asynchat test_atexit test_bsddb test_bsddb185 test_bsddb3 - test_cd - test_cl test_commands test_crypt test_dbm test_dl test_fcntl test_fork1 + test_epoll test_gdbm - test_gl test_grp - test_imgfile test_largefile - test_linuxaudiodev test_locale + test_kqueue test_mmap - test_nis - test_ntpath test_openpty test_poll test_popen2 test_pty test_pwd test_strop - test_sqlite - test_startfile - test_sunaudiodev test_sundry test_thread test_threaded_import @@ -1105,452 +949,232 @@ 'darwin': """ test__locale - test_al test_bsddb test_bsddb3 - test_cd - test_cl test_curses + test_epoll test_gdbm - test_gl - test_imgfile test_largefile - test_linuxaudiodev test_locale + test_kqueue test_minidom - test_nis - test_ntpath test_ossaudiodev test_poll - test_sqlite - test_startfile - test_sunaudiodev """, 'sunos5': """ - test_al - test_applesingle test_bsddb test_bsddb185 - test_cd - test_cl test_curses test_dbm + test_epoll + test_kqueue test_gdbm - test_gl test_gzip - test_imgfile - test_linuxaudiodev test_openpty - test_sqlite - test_startfile test_zipfile test_zlib """, 'hp-ux11': """ - test_al - test_applesingle test_bsddb test_bsddb185 - test_cd - test_cl test_curses test_dl + test_epoll test_gdbm - test_gl test_gzip - test_imgfile test_largefile - test_linuxaudiodev test_locale + test_kqueue test_minidom - test_nis - test_ntpath test_openpty test_pyexpat test_sax - test_sqlite - test_startfile - test_sunaudiodev test_zipfile test_zlib """, 'atheos': """ - test_al - test_applesingle test_bsddb185 - test_cd - test_cl test_curses test_dl test_gdbm - test_gl - test_imgfile + test_epoll test_largefile - test_linuxaudiodev test_locale + test_kqueue test_mhlib test_mmap - test_nis test_poll test_popen2 test_resource - test_sqlite - test_startfile - test_sunaudiodev """, 'cygwin': """ - test_al - test_applesingle test_bsddb185 test_bsddb3 - test_cd - test_cl test_curses test_dbm - test_gl - test_imgfile + test_epoll test_ioctl + test_kqueue test_largefile - test_linuxaudiodev test_locale - test_nis test_ossaudiodev test_socketserver - test_sqlite - test_sunaudiodev """, 'os2emx': """ - test_al - test_applesingle test_audioop test_bsddb185 test_bsddb3 - test_cd - test_cl test_commands test_curses test_dl - test_gl - test_imgfile + test_epoll + test_kqueue test_largefile - test_linuxaudiodev test_mhlib test_mmap - test_nis test_openpty test_ossaudiodev test_pty test_resource test_signal - test_sqlite - test_startfile - test_sunaudiodev """, 'freebsd4': """ - test_aepack - test_al - test_applesingle test_bsddb test_bsddb3 - test_cd - test_cl + test_epoll test_gdbm - test_gl - test_imgfile - test_linuxaudiodev test_locale - test_macfs - test_macostools - test_nis test_ossaudiodev test_pep277 - test_plistlib test_pty - test_scriptpackages test_socket_ssl test_socketserver - test_sqlite - test_startfile - test_sunaudiodev test_tcl test_timeout - test_unicode_file test_urllibnet - test_winreg - test_winsound + test_multiprocessing """, 'aix5': """ - test_aepack - test_al - test_applesingle test_bsddb test_bsddb185 test_bsddb3 test_bz2 - test_cd - test_cl test_dl + test_epoll test_gdbm - test_gl test_gzip - test_imgfile - test_linuxaudiodev - test_macfs - test_macostools - test_nis + test_kqueue test_ossaudiodev - test_sqlite - test_startfile - test_sunaudiodev test_tcl - test_winreg - test_winsound test_zipimport test_zlib """, 'openbsd3': """ - test_aepack - test_al - test_applesingle test_bsddb test_bsddb3 - test_cd - test_cl test_ctypes test_dl + test_epoll test_gdbm - test_gl - test_imgfile - test_linuxaudiodev test_locale - test_macfs - test_macostools - test_nis test_normalization test_ossaudiodev test_pep277 - test_plistlib - test_scriptpackages test_tcl - test_sqlite - test_startfile - test_sunaudiodev - test_unicode_file - test_winreg - test_winsound + test_multiprocessing """, 'netbsd3': """ - test_aepack - test_al - test_applesingle test_bsddb test_bsddb185 test_bsddb3 - test_cd - test_cl test_ctypes test_curses test_dl + test_epoll test_gdbm - test_gl - test_imgfile - test_linuxaudiodev test_locale - test_macfs - test_macostools - test_nis test_ossaudiodev test_pep277 - test_sqlite - test_startfile - test_sunaudiodev test_tcl - test_unicode_file - test_winreg - test_winsound + test_multiprocessing """, - 'java': - """ - test__locale - test__rawffi - test_aepack - test_al - test_applesingle - test_audioop - test_bsddb - test_bsddb185 - test_bsddb3 - test_bz2 - test_cProfile - test_capi - test_cd - test_cl - test_commands - test_crypt - test_ctypes - test_curses - test_dbm - test_dl - test_email_codecs - test_fcntl - test_fork1 - test_gdbm - test_getargs2 - test_gl - test_hotshot - test_imageop - test_imgfile - test_ioctl - test_largefile - test_linuxaudiodev - test_locale - test_longexp - test_macfs - test_macostools - test_mmap - test_nis - test_normalization - test_openpty - test_ossaudiodev - test_parser - test_plistlib - test_poll - test_pty - test_resource - test_rgbimg - test_scriptpackages - test_socket_ssl - test_socketserver - test_sqlite - test_startfile - test_strop - test_structmembers - test_sunaudiodev - test_sundry - test_symtable - test_tcl - test_timeout - test_unicode_file - test_wait3 - test_wait4 - test_wave - test_winreg - test_winsound - test_zipfile64 - - test_gzip - test_ftplib - test_logging - test_poplib - test_pydoc - test_queue - test_smtplib - test_telnetlib - """ } _expectations['freebsd5'] = _expectations['freebsd4'] _expectations['freebsd6'] = _expectations['freebsd4'] _expectations['freebsd7'] = _expectations['freebsd4'] +_expectations['freebsd8'] = _expectations['freebsd4'] -_failures = { - 'java': - """ - test_codecencodings_cn - test_codecencodings_hk - test_codecencodings_jp - test_codecencodings_kr - test_codecencodings_tw - test_codecmaps_cn - test_codecmaps_hk - test_codecmaps_jp - test_codecmaps_kr - test_codecmaps_tw - test_compiler - test_dis - test_dummy_threading - test_eof - test_frozen - test_gc - test_import - test_iterlen - test_multibytecodec - test_multibytecodec_support - test_peepholer - test_pyclbr - test_pyexpat - test_stringprep - test_threadsignals - test_transformer - test_ucn - test_unicodedata - test_zipimport - """, -} - -_platform = sys.platform -if _platform[:4] == 'java': - _platform = 'java' - if os._name == 'nt': - # XXX: Omitted for now because it fails so miserably and ruins - # other tests - _failures['java'] += '\ntest_mailbox' - if ' ' in sys.executable: - # http://bugs.python.org/issue1559298 - _failures['java'] += '\ntest_popen' - class _ExpectedSkips: def __init__(self): import os.path - from test import test_socket_ssl from test import test_timeout self.valid = False - if _platform in _expectations: - s = _expectations[_platform] + if sys.platform in _expectations: + s = _expectations[sys.platform] self.expected = set(s.split()) + # expected to be skipped on every platform, even Linux + self.expected.add('test_linuxaudiodev') + if not os.path.supports_unicode_filenames: self.expected.add('test_pep277') - if test_socket_ssl.skip_expected: - self.expected.add('test_socket_ssl') + try: + from test import test_socket_ssl + except ImportError: + pass + else: + if test_socket_ssl.skip_expected: + self.expected.add('test_socket_ssl') if test_timeout.skip_expected: self.expected.add('test_timeout') if sys.maxint == 9223372036854775807L: - self.expected.add('test_rgbimg') self.expected.add('test_imageop') if not sys.platform in ("mac", "darwin"): - MAC_ONLY = ["test_macostools", "test_macfs", "test_aepack", - "test_plistlib", "test_scriptpackages"] + MAC_ONLY = ["test_macos", "test_macostools", "test_aepack", + "test_plistlib", "test_scriptpackages", + "test_applesingle"] for skip in MAC_ONLY: self.expected.add(skip) + elif len(u'\0'.encode('unicode-internal')) == 4: + self.expected.add("test_macostools") + if sys.platform != "win32": + # test_sqlite is only reliable on Windows where the library + # is distributed with Python WIN_ONLY = ["test_unicode_file", "test_winreg", - "test_winsound"] + "test_winsound", "test_startfile", + "test_sqlite"] for skip in WIN_ONLY: self.expected.add(skip) - if test_support.is_jython: - if os._name != 'posix': - self.expected.update([ - 'test_grp', 'test_mhlib', 'test_posix', 'test_pwd', - 'test_signal']) - if os._name != 'nt': - self.expected.add('test_nt_paths_jy') + if sys.platform != 'irix': + IRIX_ONLY = ["test_imageop", "test_al", "test_cd", "test_cl", + "test_gl", "test_imgfile"] + for skip in IRIX_ONLY: + self.expected.add(skip) + if sys.platform != 'sunos5': + self.expected.add('test_sunaudiodev') + self.expected.add('test_nis') + + if not sys.py3kwarning: + self.expected.add('test_py3kwarn') + self.valid = True def isvalid(self): @@ -1566,28 +1190,6 @@ assert self.isvalid() return self.expected - def __contains__(self, key): - return key in self.expected - -class _ExpectedFailures(_ExpectedSkips): - def __init__(self): - self.valid = False - if _platform in _failures: - s = _failures[_platform] - self.expected = set(s.split()) - self.valid = True - -def savememo(memo,good,bad,skipped): - f = open(memo,'w') - try: - for n,l in [('good',good),('bad',bad),('skipped',skipped)]: - print >>f,"%s = [" % n - for x in l: - print >>f," %r," % x - print >>f," ]" - finally: - f.close() - if __name__ == '__main__': # Remove regrtest.py's own directory from the module search path. This # prevents relative imports from working, and relative imports will screw @@ -1596,11 +1198,9 @@ # much of the testing framework relies on the globals in the # test.test_support module. mydir = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0]))) - i = pathlen = len(sys.path) + i = len(sys.path) while i >= 0: i -= 1 if os.path.abspath(os.path.normpath(sys.path[i])) == mydir: del sys.path[i] - if len(sys.path) == pathlen: - print 'Could not find %r in sys.path to remove it' % mydir main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pj...@us...> - 2011-03-13 18:54:49
|
Revision: 7227 http://jython.svn.sourceforge.net/jython/?rev=7227&view=rev Author: pjenvey Date: 2011-03-13 18:54:43 +0000 (Sun, 13 Mar 2011) Log Message: ----------- include CPython collections, thanks fwierzbicki Modified Paths: -------------- trunk/jython/CPythonLib.includes Modified: trunk/jython/CPythonLib.includes =================================================================== --- trunk/jython/CPythonLib.includes 2011-03-13 16:09:41 UTC (rev 7226) +++ trunk/jython/CPythonLib.includes 2011-03-13 18:54:43 UTC (rev 7227) @@ -35,6 +35,7 @@ cmpcache.py code.py codecs.py +collections.py colorsys.py commands.py compileall.py This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2011-03-13 16:09:47
|
Revision: 7226 http://jython.svn.sourceforge.net/jython/?rev=7226&view=rev Author: fwierzbicki Date: 2011-03-13 16:09:41 +0000 (Sun, 13 Mar 2011) Log Message: ----------- Removing these collections as they are supperceded by collections.py. Removed Paths: ------------- trunk/jython/Lib/collections/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2011-03-13 04:28:53
|
Revision: 7225 http://jython.svn.sourceforge.net/jython/?rev=7225&view=rev Author: fwierzbicki Date: 2011-03-13 04:28:47 +0000 (Sun, 13 Mar 2011) Log Message: ----------- Jython does not have buffer. Modified Paths: -------------- trunk/jython/Lib/_abcoll.py Modified: trunk/jython/Lib/_abcoll.py =================================================================== --- trunk/jython/Lib/_abcoll.py 2011-03-13 04:17:29 UTC (rev 7224) +++ trunk/jython/Lib/_abcoll.py 2011-03-13 04:28:47 UTC (rev 7225) @@ -556,7 +556,8 @@ Sequence.register(tuple) Sequence.register(basestring) -Sequence.register(buffer) +if sys.platform[:4] != "java": + Sequence.register(buffer) Sequence.register(xrange) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2011-03-13 04:17:36
|
Revision: 7224 http://jython.svn.sourceforge.net/jython/?rev=7224&view=rev Author: fwierzbicki Date: 2011-03-13 04:17:29 +0000 (Sun, 13 Mar 2011) Log Message: ----------- from: https://bitbucket.org/pypy/pypy/lib-python/2.7.0/_abcoll.py@42546:f93911d7479c https://bitbucket.org/pypy/pypy/lib-python/2.7.0/_weakrefset.py@42546:f93911d7479c https://bitbucket.org/pypy/pypy/lib-python/2.7.0/abc.py@42546:f93911d7479c Added Paths: ----------- trunk/jython/Lib/_abcoll.py trunk/jython/Lib/_weakrefset.py trunk/jython/Lib/abc.py Added: trunk/jython/Lib/_abcoll.py =================================================================== --- trunk/jython/Lib/_abcoll.py (rev 0) +++ trunk/jython/Lib/_abcoll.py 2011-03-13 04:17:29 UTC (rev 7224) @@ -0,0 +1,601 @@ +# Copyright 2007 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Abstract Base Classes (ABCs) for collections, according to PEP 3119. + +DON'T USE THIS MODULE DIRECTLY! The classes here should be imported +via collections; they are defined here only to alleviate certain +bootstrapping issues. Unit tests are in test_collections. +""" + +from abc import ABCMeta, abstractmethod +import sys + +__all__ = ["Hashable", "Iterable", "Iterator", + "Sized", "Container", "Callable", + "Set", "MutableSet", + "Mapping", "MutableMapping", + "MappingView", "KeysView", "ItemsView", "ValuesView", + "Sequence", "MutableSequence", + ] + +### ONE-TRICK PONIES ### + +def _hasattr(C, attr): + try: + return any(attr in B.__dict__ for B in C.__mro__) + except AttributeError: + # Old-style class + return hasattr(C, attr) + + +class Hashable: + __metaclass__ = ABCMeta + + @abstractmethod + def __hash__(self): + return 0 + + @classmethod + def __subclasshook__(cls, C): + if cls is Hashable: + try: + for B in C.__mro__: + if "__hash__" in B.__dict__: + if B.__dict__["__hash__"]: + return True + break + except AttributeError: + # Old-style class + if getattr(C, "__hash__", None): + return True + return NotImplemented + + +class Iterable: + __metaclass__ = ABCMeta + + @abstractmethod + def __iter__(self): + while False: + yield None + + @classmethod + def __subclasshook__(cls, C): + if cls is Iterable: + if _hasattr(C, "__iter__"): + return True + return NotImplemented + +Iterable.register(str) + + +class Iterator(Iterable): + + @abstractmethod + def next(self): + raise StopIteration + + def __iter__(self): + return self + + @classmethod + def __subclasshook__(cls, C): + if cls is Iterator: + if _hasattr(C, "next"): + return True + return NotImplemented + + +class Sized: + __metaclass__ = ABCMeta + + @abstractmethod + def __len__(self): + return 0 + + @classmethod + def __subclasshook__(cls, C): + if cls is Sized: + if _hasattr(C, "__len__"): + return True + return NotImplemented + + +class Container: + __metaclass__ = ABCMeta + + @abstractmethod + def __contains__(self, x): + return False + + @classmethod + def __subclasshook__(cls, C): + if cls is Container: + if _hasattr(C, "__contains__"): + return True + return NotImplemented + + +class Callable: + __metaclass__ = ABCMeta + + @abstractmethod + def __call__(self, *args, **kwds): + return False + + @classmethod + def __subclasshook__(cls, C): + if cls is Callable: + if _hasattr(C, "__call__"): + return True + return NotImplemented + + +### SETS ### + + +class Set(Sized, Iterable, Container): + """A set is a finite, iterable container. + + This class provides concrete generic implementations of all + methods except for __contains__, __iter__ and __len__. + + To override the comparisons (presumably for speed, as the + semantics are fixed), all you have to do is redefine __le__ and + then the other operations will automatically follow suit. + """ + + def __le__(self, other): + if not isinstance(other, Set): + return NotImplemented + if len(self) > len(other): + return False + for elem in self: + if elem not in other: + return False + return True + + def __lt__(self, other): + if not isinstance(other, Set): + return NotImplemented + return len(self) < len(other) and self.__le__(other) + + def __gt__(self, other): + if not isinstance(other, Set): + return NotImplemented + return other < self + + def __ge__(self, other): + if not isinstance(other, Set): + return NotImplemented + return other <= self + + def __eq__(self, other): + if not isinstance(other, Set): + return NotImplemented + return len(self) == len(other) and self.__le__(other) + + def __ne__(self, other): + return not (self == other) + + @classmethod + def _from_iterable(cls, it): + '''Construct an instance of the class from any iterable input. + + Must override this method if the class constructor signature + does not accept an iterable for an input. + ''' + return cls(it) + + def __and__(self, other): + if not isinstance(other, Iterable): + return NotImplemented + return self._from_iterable(value for value in other if value in self) + + def isdisjoint(self, other): + for value in other: + if value in self: + return False + return True + + def __or__(self, other): + if not isinstance(other, Iterable): + return NotImplemented + chain = (e for s in (self, other) for e in s) + return self._from_iterable(chain) + + def __sub__(self, other): + if not isinstance(other, Set): + if not isinstance(other, Iterable): + return NotImplemented + other = self._from_iterable(other) + return self._from_iterable(value for value in self + if value not in other) + + def __xor__(self, other): + if not isinstance(other, Set): + if not isinstance(other, Iterable): + return NotImplemented + other = self._from_iterable(other) + return (self - other) | (other - self) + + # Sets are not hashable by default, but subclasses can change this + __hash__ = None + + def _hash(self): + """Compute the hash value of a set. + + Note that we don't define __hash__: not all sets are hashable. + But if you define a hashable set type, its __hash__ should + call this function. + + This must be compatible __eq__. + + All sets ought to compare equal if they contain the same + elements, regardless of how they are implemented, and + regardless of the order of the elements; so there's not much + freedom for __eq__ or __hash__. We match the algorithm used + by the built-in frozenset type. + """ + MAX = sys.maxint + MASK = 2 * MAX + 1 + n = len(self) + h = 1927868237 * (n + 1) + h &= MASK + for x in self: + hx = hash(x) + h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167 + h &= MASK + h = h * 69069 + 907133923 + h &= MASK + if h > MAX: + h -= MASK + 1 + if h == -1: + h = 590923713 + return h + +Set.register(frozenset) + + +class MutableSet(Set): + + @abstractmethod + def add(self, value): + """Add an element.""" + raise NotImplementedError + + @abstractmethod + def discard(self, value): + """Remove an element. Do not raise an exception if absent.""" + raise NotImplementedError + + def remove(self, value): + """Remove an element. If not a member, raise a KeyError.""" + if value not in self: + raise KeyError(value) + self.discard(value) + + def pop(self): + """Return the popped value. Raise KeyError if empty.""" + it = iter(self) + try: + value = next(it) + except StopIteration: + raise KeyError + self.discard(value) + return value + + def clear(self): + """This is slow (creates N new iterators!) but effective.""" + try: + while True: + self.pop() + except KeyError: + pass + + def __ior__(self, it): + for value in it: + self.add(value) + return self + + def __iand__(self, it): + for value in (self - it): + self.discard(value) + return self + + def __ixor__(self, it): + if it is self: + self.clear() + else: + if not isinstance(it, Set): + it = self._from_iterable(it) + for value in it: + if value in self: + self.discard(value) + else: + self.add(value) + return self + + def __isub__(self, it): + if it is self: + self.clear() + else: + for value in it: + self.discard(value) + return self + +MutableSet.register(set) + + +### MAPPINGS ### + + +class Mapping(Sized, Iterable, Container): + + @abstractmethod + def __getitem__(self, key): + raise KeyError + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + return default + + def __contains__(self, key): + try: + self[key] + except KeyError: + return False + else: + return True + + def iterkeys(self): + return iter(self) + + def itervalues(self): + for key in self: + yield self[key] + + def iteritems(self): + for key in self: + yield (key, self[key]) + + def keys(self): + return list(self) + + def items(self): + return [(key, self[key]) for key in self] + + def values(self): + return [self[key] for key in self] + + # Mappings are not hashable by default, but subclasses can change this + __hash__ = None + + def __eq__(self, other): + if not isinstance(other, Mapping): + return NotImplemented + return dict(self.items()) == dict(other.items()) + + def __ne__(self, other): + return not (self == other) + +class MappingView(Sized): + + def __init__(self, mapping): + self._mapping = mapping + + def __len__(self): + return len(self._mapping) + + def __repr__(self): + return '{0.__class__.__name__}({0._mapping!r})'.format(self) + + +class KeysView(MappingView, Set): + + @classmethod + def _from_iterable(self, it): + return set(it) + + def __contains__(self, key): + return key in self._mapping + + def __iter__(self): + for key in self._mapping: + yield key + + +class ItemsView(MappingView, Set): + + @classmethod + def _from_iterable(self, it): + return set(it) + + def __contains__(self, item): + key, value = item + try: + v = self._mapping[key] + except KeyError: + return False + else: + return v == value + + def __iter__(self): + for key in self._mapping: + yield (key, self._mapping[key]) + + +class ValuesView(MappingView): + + def __contains__(self, value): + for key in self._mapping: + if value == self._mapping[key]: + return True + return False + + def __iter__(self): + for key in self._mapping: + yield self._mapping[key] + + +class MutableMapping(Mapping): + + @abstractmethod + def __setitem__(self, key, value): + raise KeyError + + @abstractmethod + def __delitem__(self, key): + raise KeyError + + __marker = object() + + def pop(self, key, default=__marker): + try: + value = self[key] + except KeyError: + if default is self.__marker: + raise + return default + else: + del self[key] + return value + + def popitem(self): + try: + key = next(iter(self)) + except StopIteration: + raise KeyError + value = self[key] + del self[key] + return key, value + + def clear(self): + try: + while True: + self.popitem() + except KeyError: + pass + + def update(*args, **kwds): + if len(args) > 2: + raise TypeError("update() takes at most 2 positional " + "arguments ({} given)".format(len(args))) + elif not args: + raise TypeError("update() takes at least 1 argument (0 given)") + self = args[0] + other = args[1] if len(args) >= 2 else () + + if isinstance(other, Mapping): + for key in other: + self[key] = other[key] + elif hasattr(other, "keys"): + for key in other.keys(): + self[key] = other[key] + else: + for key, value in other: + self[key] = value + for key, value in kwds.items(): + self[key] = value + + def setdefault(self, key, default=None): + try: + return self[key] + except KeyError: + self[key] = default + return default + +MutableMapping.register(dict) + + +### SEQUENCES ### + + +class Sequence(Sized, Iterable, Container): + """All the operations on a read-only sequence. + + Concrete subclasses must override __new__ or __init__, + __getitem__, and __len__. + """ + + @abstractmethod + def __getitem__(self, index): + raise IndexError + + def __iter__(self): + i = 0 + try: + while True: + v = self[i] + yield v + i += 1 + except IndexError: + return + + def __contains__(self, value): + for v in self: + if v == value: + return True + return False + + def __reversed__(self): + for i in reversed(range(len(self))): + yield self[i] + + def index(self, value): + for i, v in enumerate(self): + if v == value: + return i + raise ValueError + + def count(self, value): + return sum(1 for v in self if v == value) + +Sequence.register(tuple) +Sequence.register(basestring) +Sequence.register(buffer) +Sequence.register(xrange) + + +class MutableSequence(Sequence): + + @abstractmethod + def __setitem__(self, index, value): + raise IndexError + + @abstractmethod + def __delitem__(self, index): + raise IndexError + + @abstractmethod + def insert(self, index, value): + raise IndexError + + def append(self, value): + self.insert(len(self), value) + + def reverse(self): + n = len(self) + for i in range(n//2): + self[i], self[n-i-1] = self[n-i-1], self[i] + + def extend(self, values): + for v in values: + self.append(v) + + def pop(self, index=-1): + v = self[index] + del self[index] + return v + + def remove(self, value): + del self[self.index(value)] + + def __iadd__(self, values): + self.extend(values) + return self + +MutableSequence.register(list) Added: trunk/jython/Lib/_weakrefset.py =================================================================== --- trunk/jython/Lib/_weakrefset.py (rev 0) +++ trunk/jython/Lib/_weakrefset.py 2011-03-13 04:17:29 UTC (rev 7224) @@ -0,0 +1,212 @@ +# Access WeakSet through the weakref module. +# This code is separated-out because it is needed +# by abc.py to load everything else at startup. + +from _weakref import ref + +__all__ = ['WeakSet'] + + +class _IterationGuard(object): + # This context manager registers itself in the current iterators of the + # weak container, such as to delay all removals until the context manager + # exits. + # This technique should be relatively thread-safe (since sets are). + + def __init__(self, weakcontainer): + # Don't create cycles + self.weakcontainer = ref(weakcontainer) + + def __enter__(self): + w = self.weakcontainer() + if w is not None: + w._iterating.add(self) + return self + + def __exit__(self, e, t, b): + w = self.weakcontainer() + if w is not None: + s = w._iterating + s.remove(self) + if not s: + w._commit_removals() + + +class WeakSet(object): + def __init__(self, data=None): + self.data = set() + def _remove(item, selfref=ref(self)): + self = selfref() + if self is not None: + if self._iterating: + self._pending_removals.append(item) + else: + self.data.discard(item) + self._remove = _remove + # A list of keys to be removed + self._pending_removals = [] + self._iterating = set() + if data is not None: + self.update(data) + + def _commit_removals(self): + l = self._pending_removals + discard = self.data.discard + while l: + discard(l.pop()) + + def __iter__(self): + with _IterationGuard(self): + for itemref in self.data: + item = itemref() + if item is not None: + yield item + + def __len__(self): + return sum(x() is not None for x in self.data) + + def __contains__(self, item): + return ref(item) in self.data + + def __reduce__(self): + return (self.__class__, (list(self),), + getattr(self, '__dict__', None)) + + __hash__ = None + + def add(self, item): + if self._pending_removals: + self._commit_removals() + self.data.add(ref(item, self._remove)) + + def clear(self): + if self._pending_removals: + self._commit_removals() + self.data.clear() + + def copy(self): + return self.__class__(self) + + def pop(self): + if self._pending_removals: + self._commit_removals() + while True: + try: + itemref = self.data.pop() + except KeyError: + raise KeyError('pop from empty WeakSet') + item = itemref() + if item is not None: + return item + + def remove(self, item): + if self._pending_removals: + self._commit_removals() + self.data.remove(ref(item)) + + def discard(self, item): + if self._pending_removals: + self._commit_removals() + self.data.discard(ref(item)) + + def update(self, other): + if self._pending_removals: + self._commit_removals() + if isinstance(other, self.__class__): + self.data.update(other.data) + else: + for element in other: + self.add(element) + + def __ior__(self, other): + self.update(other) + return self + + # Helper functions for simple delegating methods. + def _apply(self, other, method): + if not isinstance(other, self.__class__): + other = self.__class__(other) + newdata = method(other.data) + newset = self.__class__() + newset.data = newdata + return newset + + def difference(self, other): + return self._apply(other, self.data.difference) + __sub__ = difference + + def difference_update(self, other): + if self._pending_removals: + self._commit_removals() + if self is other: + self.data.clear() + else: + self.data.difference_update(ref(item) for item in other) + def __isub__(self, other): + if self._pending_removals: + self._commit_removals() + if self is other: + self.data.clear() + else: + self.data.difference_update(ref(item) for item in other) + return self + + def intersection(self, other): + return self._apply(other, self.data.intersection) + __and__ = intersection + + def intersection_update(self, other): + if self._pending_removals: + self._commit_removals() + self.data.intersection_update(ref(item) for item in other) + def __iand__(self, other): + if self._pending_removals: + self._commit_removals() + self.data.intersection_update(ref(item) for item in other) + return self + + def issubset(self, other): + return self.data.issubset(ref(item) for item in other) + __lt__ = issubset + + def __le__(self, other): + return self.data <= set(ref(item) for item in other) + + def issuperset(self, other): + return self.data.issuperset(ref(item) for item in other) + __gt__ = issuperset + + def __ge__(self, other): + return self.data >= set(ref(item) for item in other) + + def __eq__(self, other): + if not isinstance(other, self.__class__): + return NotImplemented + return self.data == set(ref(item) for item in other) + + def symmetric_difference(self, other): + return self._apply(other, self.data.symmetric_difference) + __xor__ = symmetric_difference + + def symmetric_difference_update(self, other): + if self._pending_removals: + self._commit_removals() + if self is other: + self.data.clear() + else: + self.data.symmetric_difference_update(ref(item) for item in other) + def __ixor__(self, other): + if self._pending_removals: + self._commit_removals() + if self is other: + self.data.clear() + else: + self.data.symmetric_difference_update(ref(item) for item in other) + return self + + def union(self, other): + return self._apply(other, self.data.union) + __or__ = union + + def isdisjoint(self, other): + return len(self.intersection(other)) == 0 Added: trunk/jython/Lib/abc.py =================================================================== --- trunk/jython/Lib/abc.py (rev 0) +++ trunk/jython/Lib/abc.py 2011-03-13 04:17:29 UTC (rev 7224) @@ -0,0 +1,185 @@ +# Copyright 2007 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Abstract Base Classes (ABCs) according to PEP 3119.""" + +import types + +from _weakrefset import WeakSet + +# Instance of old-style class +class _C: pass +_InstanceType = type(_C()) + + +def abstractmethod(funcobj): + """A decorator indicating abstract methods. + + Requires that the metaclass is ABCMeta or derived from it. A + class that has a metaclass derived from ABCMeta cannot be + instantiated unless all of its abstract methods are overridden. + The abstract methods can be called using any of the normal + 'super' call mechanisms. + + Usage: + + class C: + __metaclass__ = ABCMeta + @abstractmethod + def my_abstract_method(self, ...): + ... + """ + funcobj.__isabstractmethod__ = True + return funcobj + + +class abstractproperty(property): + """A decorator indicating abstract properties. + + Requires that the metaclass is ABCMeta or derived from it. A + class that has a metaclass derived from ABCMeta cannot be + instantiated unless all of its abstract properties are overridden. + The abstract properties can be called using any of the normal + 'super' call mechanisms. + + Usage: + + class C: + __metaclass__ = ABCMeta + @abstractproperty + def my_abstract_property(self): + ... + + This defines a read-only property; you can also define a read-write + abstract property using the 'long' form of property declaration: + + class C: + __metaclass__ = ABCMeta + def getx(self): ... + def setx(self, value): ... + x = abstractproperty(getx, setx) + """ + __isabstractmethod__ = True + + +class ABCMeta(type): + + """Metaclass for defining Abstract Base Classes (ABCs). + + Use this metaclass to create an ABC. An ABC can be subclassed + directly, and then acts as a mix-in class. You can also register + unrelated concrete classes (even built-in classes) and unrelated + ABCs as 'virtual subclasses' -- these and their descendants will + be considered subclasses of the registering ABC by the built-in + issubclass() function, but the registering ABC won't show up in + their MRO (Method Resolution Order) nor will method + implementations defined by the registering ABC be callable (not + even via super()). + + """ + + # A global counter that is incremented each time a class is + # registered as a virtual subclass of anything. It forces the + # negative cache to be cleared before its next use. + _abc_invalidation_counter = 0 + + def __new__(mcls, name, bases, namespace): + cls = super(ABCMeta, mcls).__new__(mcls, name, bases, namespace) + # Compute set of abstract method names + abstracts = set(name + for name, value in namespace.items() + if getattr(value, "__isabstractmethod__", False)) + for base in bases: + for name in getattr(base, "__abstractmethods__", set()): + value = getattr(cls, name, None) + if getattr(value, "__isabstractmethod__", False): + abstracts.add(name) + cls.__abstractmethods__ = frozenset(abstracts) + # Set up inheritance registry + cls._abc_registry = WeakSet() + cls._abc_cache = WeakSet() + cls._abc_negative_cache = WeakSet() + cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter + return cls + + def register(cls, subclass): + """Register a virtual subclass of an ABC.""" + if not isinstance(subclass, (type, types.ClassType)): + raise TypeError("Can only register classes") + if issubclass(subclass, cls): + return # Already a subclass + # Subtle: test for cycles *after* testing for "already a subclass"; + # this means we allow X.register(X) and interpret it as a no-op. + if issubclass(cls, subclass): + # This would create a cycle, which is bad for the algorithm below + raise RuntimeError("Refusing to create an inheritance cycle") + cls._abc_registry.add(subclass) + ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache + + def _dump_registry(cls, file=None): + """Debug helper to print the ABC registry.""" + print >> file, "Class: %s.%s" % (cls.__module__, cls.__name__) + print >> file, "Inv.counter: %s" % ABCMeta._abc_invalidation_counter + for name in sorted(cls.__dict__.keys()): + if name.startswith("_abc_"): + value = getattr(cls, name) + print >> file, "%s: %r" % (name, value) + + def __instancecheck__(cls, instance): + """Override for isinstance(instance, cls).""" + # Inline the cache checking when it's simple. + subclass = getattr(instance, '__class__', None) + if subclass is not None and subclass in cls._abc_cache: + return True + subtype = type(instance) + # Old-style instances + if subtype is _InstanceType: + subtype = subclass + if subtype is subclass or subclass is None: + if (cls._abc_negative_cache_version == + ABCMeta._abc_invalidation_counter and + subtype in cls._abc_negative_cache): + return False + # Fall back to the subclass check. + return cls.__subclasscheck__(subtype) + return (cls.__subclasscheck__(subclass) or + cls.__subclasscheck__(subtype)) + + def __subclasscheck__(cls, subclass): + """Override for issubclass(subclass, cls).""" + # Check cache + if subclass in cls._abc_cache: + return True + # Check negative cache; may have to invalidate + if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter: + # Invalidate the negative cache + cls._abc_negative_cache = WeakSet() + cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter + elif subclass in cls._abc_negative_cache: + return False + # Check the subclass hook + ok = cls.__subclasshook__(subclass) + if ok is not NotImplemented: + assert isinstance(ok, bool) + if ok: + cls._abc_cache.add(subclass) + else: + cls._abc_negative_cache.add(subclass) + return ok + # Check if it's a direct subclass + if cls in getattr(subclass, '__mro__', ()): + cls._abc_cache.add(subclass) + return True + # Check if it's a subclass of a registered class (recursive) + for rcls in cls._abc_registry: + if issubclass(subclass, rcls): + cls._abc_cache.add(subclass) + return True + # Check if it's a subclass of a subclass (recursive) + for scls in cls.__subclasses__(): + if issubclass(subclass, scls): + cls._abc_cache.add(subclass) + return True + # No dice; update negative cache + cls._abc_negative_cache.add(subclass) + return False This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2011-03-13 03:56:21
|
Revision: 7223 http://jython.svn.sourceforge.net/jython/?rev=7223&view=rev Author: fwierzbicki Date: 2011-03-13 03:56:15 +0000 (Sun, 13 Mar 2011) Log Message: ----------- Delete tests that import audioop. I just deleted them because these tests are not present in CPython 2.7. Modified Paths: -------------- trunk/jython/Lib/test/test_unittest.py Modified: trunk/jython/Lib/test/test_unittest.py =================================================================== --- trunk/jython/Lib/test/test_unittest.py 2011-03-13 03:54:20 UTC (rev 7222) +++ trunk/jython/Lib/test/test_unittest.py 2011-03-13 03:56:15 UTC (rev 7223) @@ -507,33 +507,6 @@ else: self.fail("TestLoader.loadTestsFromName failed to raise TypeError") - # "The specifier can refer to modules and packages which have not been - # imported; they will be imported as a side-effect" - def test_loadTestsFromName__module_not_loaded(self): - # We're going to try to load this module as a side-effect, so it - # better not be loaded before we try. - # - # Why pick audioop? Google shows it isn't used very often, so there's - # a good chance that it won't be imported when this test is run - module_name = 'audioop' - - import sys - if module_name in sys.modules: - del sys.modules[module_name] - - loader = unittest.TestLoader() - try: - suite = loader.loadTestsFromName(module_name) - - self.failUnless(isinstance(suite, loader.suiteClass)) - self.assertEqual(list(suite), []) - - # audioop should now be loaded, thanks to loadTestsFromName() - self.failUnless(module_name in sys.modules) - finally: - if module_name in sys.modules: - del sys.modules[module_name] - ################################################################ ### Tests for TestLoader.loadTestsFromName() @@ -895,33 +868,6 @@ else: self.fail("TestLoader.loadTestsFromNames failed to raise TypeError") - # "The specifier can refer to modules and packages which have not been - # imported; they will be imported as a side-effect" - def test_loadTestsFromNames__module_not_loaded(self): - # We're going to try to load this module as a side-effect, so it - # better not be loaded before we try. - # - # Why pick audioop? Google shows it isn't used very often, so there's - # a good chance that it won't be imported when this test is run - module_name = 'audioop' - - import sys - if module_name in sys.modules: - del sys.modules[module_name] - - loader = unittest.TestLoader() - try: - suite = loader.loadTestsFromNames([module_name]) - - self.failUnless(isinstance(suite, loader.suiteClass)) - self.assertEqual(list(suite), [unittest.TestSuite()]) - - # audioop should now be loaded, thanks to loadTestsFromName() - self.failUnless(module_name in sys.modules) - finally: - if module_name in sys.modules: - del sys.modules[module_name] - ################################################################ ### /Tests for TestLoader.loadTestsFromNames() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2011-03-13 03:54:28
|
Revision: 7222 http://jython.svn.sourceforge.net/jython/?rev=7222&view=rev Author: fwierzbicki Date: 2011-03-13 03:54:20 +0000 (Sun, 13 Mar 2011) Log Message: ----------- from: http://svn.python.org/projects/python/branches/release26-maint/Lib/test/test_unittest@88766 Added Paths: ----------- trunk/jython/Lib/test/test_unittest.py Added: trunk/jython/Lib/test/test_unittest.py =================================================================== --- trunk/jython/Lib/test/test_unittest.py (rev 0) +++ trunk/jython/Lib/test/test_unittest.py 2011-03-13 03:54:20 UTC (rev 7222) @@ -0,0 +1,2300 @@ +"""Test script for unittest. + +By Collin Winter <collinw at gmail.com> + +Still need testing: + TestCase.{assert,fail}* methods (some are tested implicitly) +""" + +import sys +from test import test_support +import unittest +from unittest import TestCase +import types + +### Support code +################################################################ + +class LoggingResult(unittest.TestResult): + def __init__(self, log): + self._events = log + super(LoggingResult, self).__init__() + + def startTest(self, test): + self._events.append('startTest') + super(LoggingResult, self).startTest(test) + + def stopTest(self, test): + self._events.append('stopTest') + super(LoggingResult, self).stopTest(test) + + def addFailure(self, *args): + self._events.append('addFailure') + super(LoggingResult, self).addFailure(*args) + + def addError(self, *args): + self._events.append('addError') + super(LoggingResult, self).addError(*args) + +class TestEquality(object): + # Check for a valid __eq__ implementation + def test_eq(self): + for obj_1, obj_2 in self.eq_pairs: + self.assertEqual(obj_1, obj_2) + self.assertEqual(obj_2, obj_1) + + # Check for a valid __ne__ implementation + def test_ne(self): + for obj_1, obj_2 in self.ne_pairs: + self.failIfEqual(obj_1, obj_2) + self.failIfEqual(obj_2, obj_1) + +class TestHashing(object): + # Check for a valid __hash__ implementation + def test_hash(self): + for obj_1, obj_2 in self.eq_pairs: + try: + assert hash(obj_1) == hash(obj_2) + except KeyboardInterrupt: + raise + except AssertionError: + self.fail("%s and %s do not hash equal" % (obj_1, obj_2)) + except Exception, e: + self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e)) + + for obj_1, obj_2 in self.ne_pairs: + try: + assert hash(obj_1) != hash(obj_2) + except KeyboardInterrupt: + raise + except AssertionError: + self.fail("%s and %s hash equal, but shouldn't" % (obj_1, obj_2)) + except Exception, e: + self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e)) + + +################################################################ +### /Support code + +class Test_TestLoader(TestCase): + + ### Tests for TestLoader.loadTestsFromTestCase + ################################################################ + + # "Return a suite of all tests cases contained in the TestCase-derived + # class testCaseClass" + def test_loadTestsFromTestCase(self): + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + def foo_bar(self): pass + + tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) + + loader = unittest.TestLoader() + self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) + + # "Return a suite of all tests cases contained in the TestCase-derived + # class testCaseClass" + # + # Make sure it does the right thing even if no tests were found + def test_loadTestsFromTestCase__no_matches(self): + class Foo(unittest.TestCase): + def foo_bar(self): pass + + empty_suite = unittest.TestSuite() + + loader = unittest.TestLoader() + self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite) + + # "Return a suite of all tests cases contained in the TestCase-derived + # class testCaseClass" + # + # What happens if loadTestsFromTestCase() is given an object + # that isn't a subclass of TestCase? Specifically, what happens + # if testCaseClass is a subclass of TestSuite? + # + # This is checked for specifically in the code, so we better add a + # test for it. + def test_loadTestsFromTestCase__TestSuite_subclass(self): + class NotATestCase(unittest.TestSuite): + pass + + loader = unittest.TestLoader() + try: + loader.loadTestsFromTestCase(NotATestCase) + except TypeError: + pass + else: + self.fail('Should raise TypeError') + + # "Return a suite of all tests cases contained in the TestCase-derived + # class testCaseClass" + # + # Make sure loadTestsFromTestCase() picks up the default test method + # name (as specified by TestCase), even though the method name does + # not match the default TestLoader.testMethodPrefix string + def test_loadTestsFromTestCase__default_method_name(self): + class Foo(unittest.TestCase): + def runTest(self): + pass + + loader = unittest.TestLoader() + # This has to be false for the test to succeed + self.failIf('runTest'.startswith(loader.testMethodPrefix)) + + suite = loader.loadTestsFromTestCase(Foo) + self.failUnless(isinstance(suite, loader.suiteClass)) + self.assertEqual(list(suite), [Foo('runTest')]) + + ################################################################ + ### /Tests for TestLoader.loadTestsFromTestCase + + ### Tests for TestLoader.loadTestsFromModule + ################################################################ + + # "This method searches `module` for classes derived from TestCase" + def test_loadTestsFromModule__TestCase_subclass(self): + m = types.ModuleType('m') + class MyTestCase(unittest.TestCase): + def test(self): + pass + m.testcase_1 = MyTestCase + + loader = unittest.TestLoader() + suite = loader.loadTestsFromModule(m) + self.failUnless(isinstance(suite, loader.suiteClass)) + + expected = [loader.suiteClass([MyTestCase('test')])] + self.assertEqual(list(suite), expected) + + # "This method searches `module` for classes derived from TestCase" + # + # What happens if no tests are found (no TestCase instances)? + def test_loadTestsFromModule__no_TestCase_instances(self): + m = types.ModuleType('m') + + loader = unittest.TestLoader() + suite = loader.loadTestsFromModule(m) + self.failUnless(isinstance(suite, loader.suiteClass)) + self.assertEqual(list(suite), []) + + # "This method searches `module` for classes derived from TestCase" + # + # What happens if no tests are found (TestCases instances, but no tests)? + def test_loadTestsFromModule__no_TestCase_tests(self): + m = types.ModuleType('m') + class MyTestCase(unittest.TestCase): + pass + m.testcase_1 = MyTestCase + + loader = unittest.TestLoader() + suite = loader.loadTestsFromModule(m) + self.failUnless(isinstance(suite, loader.suiteClass)) + + self.assertEqual(list(suite), [loader.suiteClass()]) + + # "This method searches `module` for classes derived from TestCase"s + # + # What happens if loadTestsFromModule() is given something other + # than a module? + # + # XXX Currently, it succeeds anyway. This flexibility + # should either be documented or loadTestsFromModule() should + # raise a TypeError + # + # XXX Certain people are using this behaviour. We'll add a test for it + def test_loadTestsFromModule__not_a_module(self): + class MyTestCase(unittest.TestCase): + def test(self): + pass + + class NotAModule(object): + test_2 = MyTestCase + + loader = unittest.TestLoader() + suite = loader.loadTestsFromModule(NotAModule) + + reference = [unittest.TestSuite([MyTestCase('test')])] + self.assertEqual(list(suite), reference) + + ################################################################ + ### /Tests for TestLoader.loadTestsFromModule() + + ### Tests for TestLoader.loadTestsFromName() + ################################################################ + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # + # Is ValueError raised in response to an empty name? + def test_loadTestsFromName__empty_name(self): + loader = unittest.TestLoader() + + try: + loader.loadTestsFromName('') + except ValueError, e: + self.assertEqual(str(e), "Empty module name") + else: + self.fail("TestLoader.loadTestsFromName failed to raise ValueError") + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # + # What happens when the name contains invalid characters? + def test_loadTestsFromName__malformed_name(self): + loader = unittest.TestLoader() + + # XXX Should this raise ValueError or ImportError? + try: + loader.loadTestsFromName('abc () //') + except ValueError: + pass + except ImportError: + pass + else: + self.fail("TestLoader.loadTestsFromName failed to raise ValueError") + + # "The specifier name is a ``dotted name'' that may resolve ... to a + # module" + # + # What happens when a module by that name can't be found? + def test_loadTestsFromName__unknown_module_name(self): + loader = unittest.TestLoader() + + try: + loader.loadTestsFromName('sdasfasfasdf') + except ImportError, e: + self.assertEqual(str(e), "No module named sdasfasfasdf") + else: + self.fail("TestLoader.loadTestsFromName failed to raise ImportError") + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # + # What happens when the module is found, but the attribute can't? + def test_loadTestsFromName__unknown_attr_name(self): + loader = unittest.TestLoader() + + try: + loader.loadTestsFromName('unittest.sdasfasfasdf') + except AttributeError, e: + self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") + else: + self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # + # What happens when we provide the module, but the attribute can't be + # found? + def test_loadTestsFromName__relative_unknown_name(self): + loader = unittest.TestLoader() + + try: + loader.loadTestsFromName('sdasfasfasdf', unittest) + except AttributeError, e: + self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") + else: + self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # ... + # "The method optionally resolves name relative to the given module" + # + # Does loadTestsFromName raise ValueError when passed an empty + # name relative to a provided module? + # + # XXX Should probably raise a ValueError instead of an AttributeError + def test_loadTestsFromName__relative_empty_name(self): + loader = unittest.TestLoader() + + try: + loader.loadTestsFromName('', unittest) + except AttributeError, e: + pass + else: + self.fail("Failed to raise AttributeError") + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # ... + # "The method optionally resolves name relative to the given module" + # + # What happens when an impossible name is given, relative to the provided + # `module`? + def test_loadTestsFromName__relative_malformed_name(self): + loader = unittest.TestLoader() + + # XXX Should this raise AttributeError or ValueError? + try: + loader.loadTestsFromName('abc () //', unittest) + except ValueError: + pass + except AttributeError: + pass + else: + self.fail("TestLoader.loadTestsFromName failed to raise ValueError") + + # "The method optionally resolves name relative to the given module" + # + # Does loadTestsFromName raise TypeError when the `module` argument + # isn't a module object? + # + # XXX Accepts the not-a-module object, ignorning the object's type + # This should raise an exception or the method name should be changed + # + # XXX Some people are relying on this, so keep it for now + def test_loadTestsFromName__relative_not_a_module(self): + class MyTestCase(unittest.TestCase): + def test(self): + pass + + class NotAModule(object): + test_2 = MyTestCase + + loader = unittest.TestLoader() + suite = loader.loadTestsFromName('test_2', NotAModule) + + reference = [MyTestCase('test')] + self.assertEqual(list(suite), reference) + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # + # Does it raise an exception if the name resolves to an invalid + # object? + def test_loadTestsFromName__relative_bad_object(self): + m = types.ModuleType('m') + m.testcase_1 = object() + + loader = unittest.TestLoader() + try: + loader.loadTestsFromName('testcase_1', m) + except TypeError: + pass + else: + self.fail("Should have raised TypeError") + + # "The specifier name is a ``dotted name'' that may + # resolve either to ... a test case class" + def test_loadTestsFromName__relative_TestCase_subclass(self): + m = types.ModuleType('m') + class MyTestCase(unittest.TestCase): + def test(self): + pass + m.testcase_1 = MyTestCase + + loader = unittest.TestLoader() + suite = loader.loadTestsFromName('testcase_1', m) + self.failUnless(isinstance(suite, loader.suiteClass)) + self.assertEqual(list(suite), [MyTestCase('test')]) + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + def test_loadTestsFromName__relative_TestSuite(self): + m = types.ModuleType('m') + class MyTestCase(unittest.TestCase): + def test(self): + pass + m.testsuite = unittest.TestSuite([MyTestCase('test')]) + + loader = unittest.TestLoader() + suite = loader.loadTestsFromName('testsuite', m) + self.failUnless(isinstance(suite, loader.suiteClass)) + + self.assertEqual(list(suite), [MyTestCase('test')]) + + # "The specifier name is a ``dotted name'' that may resolve ... to + # ... a test method within a test case class" + def test_loadTestsFromName__relative_testmethod(self): + m = types.ModuleType('m') + class MyTestCase(unittest.TestCase): + def test(self): + pass + m.testcase_1 = MyTestCase + + loader = unittest.TestLoader() + suite = loader.loadTestsFromName('testcase_1.test', m) + self.failUnless(isinstance(suite, loader.suiteClass)) + + self.assertEqual(list(suite), [MyTestCase('test')]) + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # + # Does loadTestsFromName() raise the proper exception when trying to + # resolve "a test method within a test case class" that doesn't exist + # for the given name (relative to a provided module)? + def test_loadTestsFromName__relative_invalid_testmethod(self): + m = types.ModuleType('m') + class MyTestCase(unittest.TestCase): + def test(self): + pass + m.testcase_1 = MyTestCase + + loader = unittest.TestLoader() + try: + loader.loadTestsFromName('testcase_1.testfoo', m) + except AttributeError, e: + self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'") + else: + self.fail("Failed to raise AttributeError") + + # "The specifier name is a ``dotted name'' that may resolve ... to + # ... a callable object which returns a ... TestSuite instance" + def test_loadTestsFromName__callable__TestSuite(self): + m = types.ModuleType('m') + testcase_1 = unittest.FunctionTestCase(lambda: None) + testcase_2 = unittest.FunctionTestCase(lambda: None) + def return_TestSuite(): + return unittest.TestSuite([testcase_1, testcase_2]) + m.return_TestSuite = return_TestSuite + + loader = unittest.TestLoader() + suite = loader.loadTestsFromName('return_TestSuite', m) + self.failUnless(isinstance(suite, loader.suiteClass)) + self.assertEqual(list(suite), [testcase_1, testcase_2]) + + # "The specifier name is a ``dotted name'' that may resolve ... to + # ... a callable object which returns a TestCase ... instance" + def test_loadTestsFromName__callable__TestCase_instance(self): + m = types.ModuleType('m') + testcase_1 = unittest.FunctionTestCase(lambda: None) + def return_TestCase(): + return testcase_1 + m.return_TestCase = return_TestCase + + loader = unittest.TestLoader() + suite = loader.loadTestsFromName('return_TestCase', m) + self.failUnless(isinstance(suite, loader.suiteClass)) + self.assertEqual(list(suite), [testcase_1]) + + # "The specifier name is a ``dotted name'' that may resolve ... to + # ... a callable object which returns a TestCase or TestSuite instance" + # + # What happens if the callable returns something else? + def test_loadTestsFromName__callable__wrong_type(self): + m = types.ModuleType('m') + def return_wrong(): + return 6 + m.return_wrong = return_wrong + + loader = unittest.TestLoader() + try: + suite = loader.loadTestsFromName('return_wrong', m) + except TypeError: + pass + else: + self.fail("TestLoader.loadTestsFromName failed to raise TypeError") + + # "The specifier can refer to modules and packages which have not been + # imported; they will be imported as a side-effect" + def test_loadTestsFromName__module_not_loaded(self): + # We're going to try to load this module as a side-effect, so it + # better not be loaded before we try. + # + # Why pick audioop? Google shows it isn't used very often, so there's + # a good chance that it won't be imported when this test is run + module_name = 'audioop' + + import sys + if module_name in sys.modules: + del sys.modules[module_name] + + loader = unittest.TestLoader() + try: + suite = loader.loadTestsFromName(module_name) + + self.failUnless(isinstance(suite, loader.suiteClass)) + self.assertEqual(list(suite), []) + + # audioop should now be loaded, thanks to loadTestsFromName() + self.failUnless(module_name in sys.modules) + finally: + if module_name in sys.modules: + del sys.modules[module_name] + + ################################################################ + ### Tests for TestLoader.loadTestsFromName() + + ### Tests for TestLoader.loadTestsFromNames() + ################################################################ + + # "Similar to loadTestsFromName(), but takes a sequence of names rather + # than a single name." + # + # What happens if that sequence of names is empty? + def test_loadTestsFromNames__empty_name_list(self): + loader = unittest.TestLoader() + + suite = loader.loadTestsFromNames([]) + self.failUnless(isinstance(suite, loader.suiteClass)) + self.assertEqual(list(suite), []) + + # "Similar to loadTestsFromName(), but takes a sequence of names rather + # than a single name." + # ... + # "The method optionally resolves name relative to the given module" + # + # What happens if that sequence of names is empty? + # + # XXX Should this raise a ValueError or just return an empty TestSuite? + def test_loadTestsFromNames__relative_empty_name_list(self): + loader = unittest.TestLoader() + + suite = loader.loadTestsFromNames([], unittest) + self.failUnless(isinstance(suite, loader.suiteClass)) + self.assertEqual(list(suite), []) + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # + # Is ValueError raised in response to an empty name? + def test_loadTestsFromNames__empty_name(self): + loader = unittest.TestLoader() + + try: + loader.loadTestsFromNames(['']) + except ValueError, e: + self.assertEqual(str(e), "Empty module name") + else: + self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # + # What happens when presented with an impossible module name? + def test_loadTestsFromNames__malformed_name(self): + loader = unittest.TestLoader() + + # XXX Should this raise ValueError or ImportError? + try: + loader.loadTestsFromNames(['abc () //']) + except ValueError: + pass + except ImportError: + pass + else: + self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # + # What happens when no module can be found for the given name? + def test_loadTestsFromNames__unknown_module_name(self): + loader = unittest.TestLoader() + + try: + loader.loadTestsFromNames(['sdasfasfasdf']) + except ImportError, e: + self.assertEqual(str(e), "No module named sdasfasfasdf") + else: + self.fail("TestLoader.loadTestsFromNames failed to raise ImportError") + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # + # What happens when the module can be found, but not the attribute? + def test_loadTestsFromNames__unknown_attr_name(self): + loader = unittest.TestLoader() + + try: + loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest']) + except AttributeError, e: + self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") + else: + self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError") + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # ... + # "The method optionally resolves name relative to the given module" + # + # What happens when given an unknown attribute on a specified `module` + # argument? + def test_loadTestsFromNames__unknown_name_relative_1(self): + loader = unittest.TestLoader() + + try: + loader.loadTestsFromNames(['sdasfasfasdf'], unittest) + except AttributeError, e: + self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") + else: + self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # ... + # "The method optionally resolves name relative to the given module" + # + # Do unknown attributes (relative to a provided module) still raise an + # exception even in the presence of valid attribute names? + def test_loadTestsFromNames__unknown_name_relative_2(self): + loader = unittest.TestLoader() + + try: + loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest) + except AttributeError, e: + self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") + else: + self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # ... + # "The method optionally resolves name relative to the given module" + # + # What happens when faced with the empty string? + # + # XXX This currently raises AttributeError, though ValueError is probably + # more appropriate + def test_loadTestsFromNames__relative_empty_name(self): + loader = unittest.TestLoader() + + try: + loader.loadTestsFromNames([''], unittest) + except AttributeError: + pass + else: + self.fail("Failed to raise ValueError") + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # ... + # "The method optionally resolves name relative to the given module" + # + # What happens when presented with an impossible attribute name? + def test_loadTestsFromNames__relative_malformed_name(self): + loader = unittest.TestLoader() + + # XXX Should this raise AttributeError or ValueError? + try: + loader.loadTestsFromNames(['abc () //'], unittest) + except AttributeError: + pass + except ValueError: + pass + else: + self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") + + # "The method optionally resolves name relative to the given module" + # + # Does loadTestsFromNames() make sure the provided `module` is in fact + # a module? + # + # XXX This validation is currently not done. This flexibility should + # either be documented or a TypeError should be raised. + def test_loadTestsFromNames__relative_not_a_module(self): + class MyTestCase(unittest.TestCase): + def test(self): + pass + + class NotAModule(object): + test_2 = MyTestCase + + loader = unittest.TestLoader() + suite = loader.loadTestsFromNames(['test_2'], NotAModule) + + reference = [unittest.TestSuite([MyTestCase('test')])] + self.assertEqual(list(suite), reference) + + # "The specifier name is a ``dotted name'' that may resolve either to + # a module, a test case class, a TestSuite instance, a test method + # within a test case class, or a callable object which returns a + # TestCase or TestSuite instance." + # + # Does it raise an exception if the name resolves to an invalid + # object? + def test_loadTestsFromNames__relative_bad_object(self): + m = types.ModuleType('m') + m.testcase_1 = object() + + loader = unittest.TestLoader() + try: + loader.loadTestsFromNames(['testcase_1'], m) + except TypeError: + pass + else: + self.fail("Should have raised TypeError") + + # "The specifier name is a ``dotted name'' that may resolve ... to + # ... a test case class" + def test_loadTestsFromNames__relative_TestCase_subclass(self): + m = types.ModuleType('m') + class MyTestCase(unittest.TestCase): + def test(self): + pass + m.testcase_1 = MyTestCase + + loader = unittest.TestLoader() + suite = loader.loadTestsFromNames(['testcase_1'], m) + self.failUnless(isinstance(suite, loader.suiteClass)) + + expected = loader.suiteClass([MyTestCase('test')]) + self.assertEqual(list(suite), [expected]) + + # "The specifier name is a ``dotted name'' that may resolve ... to + # ... a TestSuite instance" + def test_loadTestsFromNames__relative_TestSuite(self): + m = types.ModuleType('m') + class MyTestCase(unittest.TestCase): + def test(self): + pass + m.testsuite = unittest.TestSuite([MyTestCase('test')]) + + loader = unittest.TestLoader() + suite = loader.loadTestsFromNames(['testsuite'], m) + self.failUnless(isinstance(suite, loader.suiteClass)) + + self.assertEqual(list(suite), [m.testsuite]) + + # "The specifier name is a ``dotted name'' that may resolve ... to ... a + # test method within a test case class" + def test_loadTestsFromNames__relative_testmethod(self): + m = types.ModuleType('m') + class MyTestCase(unittest.TestCase): + def test(self): + pass + m.testcase_1 = MyTestCase + + loader = unittest.TestLoader() + suite = loader.loadTestsFromNames(['testcase_1.test'], m) + self.failUnless(isinstance(suite, loader.suiteClass)) + + ref_suite = unittest.TestSuite([MyTestCase('test')]) + self.assertEqual(list(suite), [ref_suite]) + + # "The specifier name is a ``dotted name'' that may resolve ... to ... a + # test method within a test case class" + # + # Does the method gracefully handle names that initially look like they + # resolve to "a test method within a test case class" but don't? + def test_loadTestsFromNames__relative_invalid_testmethod(self): + m = types.ModuleType('m') + class MyTestCase(unittest.TestCase): + def test(self): + pass + m.testcase_1 = MyTestCase + + loader = unittest.TestLoader() + try: + loader.loadTestsFromNames(['testcase_1.testfoo'], m) + except AttributeError, e: + self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'") + else: + self.fail("Failed to raise AttributeError") + + # "The specifier name is a ``dotted name'' that may resolve ... to + # ... a callable object which returns a ... TestSuite instance" + def test_loadTestsFromNames__callable__TestSuite(self): + m = types.ModuleType('m') + testcase_1 = unittest.FunctionTestCase(lambda: None) + testcase_2 = unittest.FunctionTestCase(lambda: None) + def return_TestSuite(): + return unittest.TestSuite([testcase_1, testcase_2]) + m.return_TestSuite = return_TestSuite + + loader = unittest.TestLoader() + suite = loader.loadTestsFromNames(['return_TestSuite'], m) + self.failUnless(isinstance(suite, loader.suiteClass)) + + expected = unittest.TestSuite([testcase_1, testcase_2]) + self.assertEqual(list(suite), [expected]) + + # "The specifier name is a ``dotted name'' that may resolve ... to + # ... a callable object which returns a TestCase ... instance" + def test_loadTestsFromNames__callable__TestCase_instance(self): + m = types.ModuleType('m') + testcase_1 = unittest.FunctionTestCase(lambda: None) + def return_TestCase(): + return testcase_1 + m.return_TestCase = return_TestCase + + loader = unittest.TestLoader() + suite = loader.loadTestsFromNames(['return_TestCase'], m) + self.failUnless(isinstance(suite, loader.suiteClass)) + + ref_suite = unittest.TestSuite([testcase_1]) + self.assertEqual(list(suite), [ref_suite]) + + # "The specifier name is a ``dotted name'' that may resolve ... to + # ... a callable object which returns a TestCase or TestSuite instance" + # + # Are staticmethods handled correctly? + def test_loadTestsFromNames__callable__call_staticmethod(self): + m = types.ModuleType('m') + class Test1(unittest.TestCase): + def test(self): + pass + + testcase_1 = Test1('test') + class Foo(unittest.TestCase): + @staticmethod + def foo(): + return testcase_1 + m.Foo = Foo + + loader = unittest.TestLoader() + suite = loader.loadTestsFromNames(['Foo.foo'], m) + self.failUnless(isinstance(suite, loader.suiteClass)) + + ref_suite = unittest.TestSuite([testcase_1]) + self.assertEqual(list(suite), [ref_suite]) + + # "The specifier name is a ``dotted name'' that may resolve ... to + # ... a callable object which returns a TestCase or TestSuite instance" + # + # What happens when the callable returns something else? + def test_loadTestsFromNames__callable__wrong_type(self): + m = types.ModuleType('m') + def return_wrong(): + return 6 + m.return_wrong = return_wrong + + loader = unittest.TestLoader() + try: + suite = loader.loadTestsFromNames(['return_wrong'], m) + except TypeError: + pass + else: + self.fail("TestLoader.loadTestsFromNames failed to raise TypeError") + + # "The specifier can refer to modules and packages which have not been + # imported; they will be imported as a side-effect" + def test_loadTestsFromNames__module_not_loaded(self): + # We're going to try to load this module as a side-effect, so it + # better not be loaded before we try. + # + # Why pick audioop? Google shows it isn't used very often, so there's + # a good chance that it won't be imported when this test is run + module_name = 'audioop' + + import sys + if module_name in sys.modules: + del sys.modules[module_name] + + loader = unittest.TestLoader() + try: + suite = loader.loadTestsFromNames([module_name]) + + self.failUnless(isinstance(suite, loader.suiteClass)) + self.assertEqual(list(suite), [unittest.TestSuite()]) + + # audioop should now be loaded, thanks to loadTestsFromName() + self.failUnless(module_name in sys.modules) + finally: + if module_name in sys.modules: + del sys.modules[module_name] + + ################################################################ + ### /Tests for TestLoader.loadTestsFromNames() + + ### Tests for TestLoader.getTestCaseNames() + ################################################################ + + # "Return a sorted sequence of method names found within testCaseClass" + # + # Test.foobar is defined to make sure getTestCaseNames() respects + # loader.testMethodPrefix + def test_getTestCaseNames(self): + class Test(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + def foobar(self): pass + + loader = unittest.TestLoader() + + self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2']) + + # "Return a sorted sequence of method names found within testCaseClass" + # + # Does getTestCaseNames() behave appropriately if no tests are found? + def test_getTestCaseNames__no_tests(self): + class Test(unittest.TestCase): + def foobar(self): pass + + loader = unittest.TestLoader() + + self.assertEqual(loader.getTestCaseNames(Test), []) + + # "Return a sorted sequence of method names found within testCaseClass" + # + # Are not-TestCases handled gracefully? + # + # XXX This should raise a TypeError, not return a list + # + # XXX It's too late in the 2.5 release cycle to fix this, but it should + # probably be revisited for 2.6 + def test_getTestCaseNames__not_a_TestCase(self): + class BadCase(int): + def test_foo(self): + pass + + loader = unittest.TestLoader() + names = loader.getTestCaseNames(BadCase) + + self.assertEqual(names, ['test_foo']) + + # "Return a sorted sequence of method names found within testCaseClass" + # + # Make sure inherited names are handled. + # + # TestP.foobar is defined to make sure getTestCaseNames() respects + # loader.testMethodPrefix + def test_getTestCaseNames__inheritance(self): + class TestP(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + def foobar(self): pass + + class TestC(TestP): + def test_1(self): pass + def test_3(self): pass + + loader = unittest.TestLoader() + + names = ['test_1', 'test_2', 'test_3'] + self.assertEqual(loader.getTestCaseNames(TestC), names) + + ################################################################ + ### /Tests for TestLoader.getTestCaseNames() + + ### Tests for TestLoader.testMethodPrefix + ################################################################ + + # "String giving the prefix of method names which will be interpreted as + # test methods" + # + # Implicit in the documentation is that testMethodPrefix is respected by + # all loadTestsFrom* methods. + def test_testMethodPrefix__loadTestsFromTestCase(self): + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + def foo_bar(self): pass + + tests_1 = unittest.TestSuite([Foo('foo_bar')]) + tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) + + loader = unittest.TestLoader() + loader.testMethodPrefix = 'foo' + self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1) + + loader.testMethodPrefix = 'test' + self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2) + + # "String giving the prefix of method names which will be interpreted as + # test methods" + # + # Implicit in the documentation is that testMethodPrefix is respected by + # all loadTestsFrom* methods. + def test_testMethodPrefix__loadTestsFromModule(self): + m = types.ModuleType('m') + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + def foo_bar(self): pass + m.Foo = Foo + + tests_1 = [unittest.TestSuite([Foo('foo_bar')])] + tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])] + + loader = unittest.TestLoader() + loader.testMethodPrefix = 'foo' + self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1) + + loader.testMethodPrefix = 'test' + self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2) + + # "String giving the prefix of method names which will be interpreted as + # test methods" + # + # Implicit in the documentation is that testMethodPrefix is respected by + # all loadTestsFrom* methods. + def test_testMethodPrefix__loadTestsFromName(self): + m = types.ModuleType('m') + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + def foo_bar(self): pass + m.Foo = Foo + + tests_1 = unittest.TestSuite([Foo('foo_bar')]) + tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) + + loader = unittest.TestLoader() + loader.testMethodPrefix = 'foo' + self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1) + + loader.testMethodPrefix = 'test' + self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2) + + # "String giving the prefix of method names which will be interpreted as + # test methods" + # + # Implicit in the documentation is that testMethodPrefix is respected by + # all loadTestsFrom* methods. + def test_testMethodPrefix__loadTestsFromNames(self): + m = types.ModuleType('m') + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + def foo_bar(self): pass + m.Foo = Foo + + tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])]) + tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) + tests_2 = unittest.TestSuite([tests_2]) + + loader = unittest.TestLoader() + loader.testMethodPrefix = 'foo' + self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1) + + loader.testMethodPrefix = 'test' + self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2) + + # "The default value is 'test'" + def test_testMethodPrefix__default_value(self): + loader = unittest.TestLoader() + self.failUnless(loader.testMethodPrefix == 'test') + + ################################################################ + ### /Tests for TestLoader.testMethodPrefix + + ### Tests for TestLoader.sortTestMethodsUsing + ################################################################ + + # "Function to be used to compare method names when sorting them in + # getTestCaseNames() and all the loadTestsFromX() methods" + def test_sortTestMethodsUsing__loadTestsFromTestCase(self): + def reversed_cmp(x, y): + return -cmp(x, y) + + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + + loader = unittest.TestLoader() + loader.sortTestMethodsUsing = reversed_cmp + + tests = loader.suiteClass([Foo('test_2'), Foo('test_1')]) + self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) + + # "Function to be used to compare method names when sorting them in + # getTestCaseNames() and all the loadTestsFromX() methods" + def test_sortTestMethodsUsing__loadTestsFromModule(self): + def reversed_cmp(x, y): + return -cmp(x, y) + + m = types.ModuleType('m') + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + m.Foo = Foo + + loader = unittest.TestLoader() + loader.sortTestMethodsUsing = reversed_cmp + + tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])] + self.assertEqual(list(loader.loadTestsFromModule(m)), tests) + + # "Function to be used to compare method names when sorting them in + # getTestCaseNames() and all the loadTestsFromX() methods" + def test_sortTestMethodsUsing__loadTestsFromName(self): + def reversed_cmp(x, y): + return -cmp(x, y) + + m = types.ModuleType('m') + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + m.Foo = Foo + + loader = unittest.TestLoader() + loader.sortTestMethodsUsing = reversed_cmp + + tests = loader.suiteClass([Foo('test_2'), Foo('test_1')]) + self.assertEqual(loader.loadTestsFromName('Foo', m), tests) + + # "Function to be used to compare method names when sorting them in + # getTestCaseNames() and all the loadTestsFromX() methods" + def test_sortTestMethodsUsing__loadTestsFromNames(self): + def reversed_cmp(x, y): + return -cmp(x, y) + + m = types.ModuleType('m') + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + m.Foo = Foo + + loader = unittest.TestLoader() + loader.sortTestMethodsUsing = reversed_cmp + + tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])] + self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests) + + # "Function to be used to compare method names when sorting them in + # getTestCaseNames()" + # + # Does it actually affect getTestCaseNames()? + def test_sortTestMethodsUsing__getTestCaseNames(self): + def reversed_cmp(x, y): + return -cmp(x, y) + + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + + loader = unittest.TestLoader() + loader.sortTestMethodsUsing = reversed_cmp + + test_names = ['test_2', 'test_1'] + self.assertEqual(loader.getTestCaseNames(Foo), test_names) + + # "The default value is the built-in cmp() function" + def test_sortTestMethodsUsing__default_value(self): + loader = unittest.TestLoader() + self.failUnless(loader.sortTestMethodsUsing is cmp) + + # "it can be set to None to disable the sort." + # + # XXX How is this different from reassigning cmp? Are the tests returned + # in a random order or something? This behaviour should die + def test_sortTestMethodsUsing__None(self): + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + + loader = unittest.TestLoader() + loader.sortTestMethodsUsing = None + + test_names = ['test_2', 'test_1'] + self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names)) + + ################################################################ + ### /Tests for TestLoader.sortTestMethodsUsing + + ### Tests for TestLoader.suiteClass + ################################################################ + + # "Callable object that constructs a test suite from a list of tests." + def test_suiteClass__loadTestsFromTestCase(self): + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + def foo_bar(self): pass + + tests = [Foo('test_1'), Foo('test_2')] + + loader = unittest.TestLoader() + loader.suiteClass = list + self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) + + # It is implicit in the documentation for TestLoader.suiteClass that + # all TestLoader.loadTestsFrom* methods respect it. Let's make sure + def test_suiteClass__loadTestsFromModule(self): + m = types.ModuleType('m') + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + def foo_bar(self): pass + m.Foo = Foo + + tests = [[Foo('test_1'), Foo('test_2')]] + + loader = unittest.TestLoader() + loader.suiteClass = list + self.assertEqual(loader.loadTestsFromModule(m), tests) + + # It is implicit in the documentation for TestLoader.suiteClass that + # all TestLoader.loadTestsFrom* methods respect it. Let's make sure + def test_suiteClass__loadTestsFromName(self): + m = types.ModuleType('m') + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + def foo_bar(self): pass + m.Foo = Foo + + tests = [Foo('test_1'), Foo('test_2')] + + loader = unittest.TestLoader() + loader.suiteClass = list + self.assertEqual(loader.loadTestsFromName('Foo', m), tests) + + # It is implicit in the documentation for TestLoader.suiteClass that + # all TestLoader.loadTestsFrom* methods respect it. Let's make sure + def test_suiteClass__loadTestsFromNames(self): + m = types.ModuleType('m') + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + def foo_bar(self): pass + m.Foo = Foo + + tests = [[Foo('test_1'), Foo('test_2')]] + + loader = unittest.TestLoader() + loader.suiteClass = list + self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests) + + # "The default value is the TestSuite class" + def test_suiteClass__default_value(self): + loader = unittest.TestLoader() + self.failUnless(loader.suiteClass is unittest.TestSuite) + + ################################################################ + ### /Tests for TestLoader.suiteClass + +### Support code for Test_TestSuite +################################################################ + +class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + def test_3(self): pass + def runTest(self): pass + +def _mk_TestSuite(*names): + return unittest.TestSuite(Foo(n) for n in names) + +################################################################ +### /Support code for Test_TestSuite + +class Test_TestSuite(TestCase, TestEquality): + + ### Set up attributes needed by inherited tests + ################################################################ + + # Used by TestEquality.test_eq + eq_pairs = [(unittest.TestSuite(), unittest.TestSuite()) + ,(unittest.TestSuite(), unittest.TestSuite([])) + ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))] + + # Used by TestEquality.test_ne + ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1')) + ,(unittest.TestSuite([]), _mk_TestSuite('test_1')) + ,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3')) + ,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))] + + ################################################################ + ### /Set up attributes needed by inherited tests + + ### Tests for TestSuite.__init__ + ################################################################ + + # "class TestSuite([tests])" + # + # The tests iterable should be optional + def test_init__tests_optional(self): + suite = unittest.TestSuite() + + self.assertEqual(suite.countTestCases(), 0) + + # "class TestSuite([tests])" + # ... + # "If tests is given, it must be an iterable of individual test cases + # or other test suites that will be used to build the suite initially" + # + # TestSuite should deal with empty tests iterables by allowing the + # creation of an empty suite + def test_init__empty_tests(self): + suite = unittest.TestSuite([]) + + self.assertEqual(suite.countTestCases(), 0) + + # "class TestSuite([tests])" + # ... + # "If tests is given, it must be an iterable of individual test cases + # or other test suites that will be used to build the suite initially" + # + # TestSuite should allow any iterable to provide tests + def test_init__tests_from_any_iterable(self): + def tests(): + yield unittest.FunctionTestCase(lambda: None) + yield unittest.FunctionTestCase(lambda: None) + + suite_1 = unittest.TestSuite(tests()) + self.assertEqual(suite_1.countTestCases(), 2) + + suite_2 = unittest.TestSuite(suite_1) + self.assertEqual(suite_2.countTestCases(), 2) + + suite_3 = unittest.TestSuite(set(suite_1)) + self.assertEqual(suite_3.countTestCases(), 2) + + # "class TestSuite([tests])" + # ... + # "If tests is given, it must be an iterable of individual test cases + # or other test suites that will be used to build the suite initially" + # + # Does TestSuite() also allow other TestSuite() instances to be present + # in the tests iterable? + def test_init__TestSuite_instances_in_tests(self): + def tests(): + ftc = unittest.FunctionTestCase(lambda: None) + yield unittest.TestSuite([ftc]) + yield unittest.FunctionTestCase(lambda: None) + + suite = unittest.TestSuite(tests()) + self.assertEqual(suite.countTestCases(), 2) + + ################################################################ + ### /Tests for TestSuite.__init__ + + # Container types should support the iter protocol + def test_iter(self): + test1 = unittest.FunctionTestCase(lambda: None) + test2 = unittest.FunctionTestCase(lambda: None) + suite = unittest.TestSuite((test1, test2)) + + self.assertEqual(list(suite), [test1, test2]) + + # "Return the number of tests represented by the this test object. + # ...this method is also implemented by the TestSuite class, which can + # return larger [greater than 1] values" + # + # Presumably an empty TestSuite returns 0? + def test_countTestCases_zero_simple(self): + suite = unittest.TestSuite() + + self.assertEqual(suite.countTestCases(), 0) + + # "Return the number of tests represented by the this test object. + # ...this method is also implemented by the TestSuite class, which can + # return larger [greater than 1] values" + # + # Presumably an empty TestSuite (even if it contains other empty + # TestSuite instances) returns 0? + def test_countTestCases_zero_nested(self): + class Test1(unittest.TestCase): + def test(self): + pass + + suite = unittest.TestSuite([unittest.TestSuite()]) + + self.assertEqual(suite.countTestCases(), 0) + + # "Return the number of tests represented by the this test object. + # ...this method is also implemented by the TestSuite class, which can + # return larger [greater than 1] values" + def test_countTestCases_simple(self): + test1 = unittest.FunctionTestCase(lambda: None) + test2 = unittest.FunctionTestCase(lambda: None) + suite = unittest.TestSuite((test1, test2)) + + self.assertEqual(suite.countTestCases(), 2) + + # "Return the number of tests represented by the this test object. + # ...this method is also implemented by the TestSuite class, which can + # return larger [greater than 1] values" + # + # Make sure this holds for nested TestSuite instances, too + def test_countTestCases_nested(self): + class Test1(unittest.TestCase): + def test1(self): pass + def test2(self): pass + + test2 = unittest.FunctionTestCase(lambda: None) + test3 = unittest.FunctionTestCase(lambda: None) + child = unittest.TestSuite((Test1('test2'), test2)) + parent = unittest.TestSuite((test3, child, Test1('test1'))) + + self.assertEqual(parent.countTestCases(), 4) + + # "Run the tests associated with this suite, collecting the result into + # the test result object passed as result." + # + # And if there are no tests? What then? + def test_run__empty_suite(self): + events = [] + result = LoggingResult(events) + + suite = unittest.TestSuite() + + suite.run(result) + + self.assertEqual(events, []) + + # "Note that unlike TestCase.run(), TestSuite.run() requires the + # "result object to be passed in." + def test_run__requires_result(self): + suite = unittest.TestSuite() + + try: + suite.run() + except TypeError: + pass + else: + self.fail("Failed to raise TypeError") + + # "Run the tests associated with this suite, collecting the result into + # the test result object passed as result." + def test_run(self): + events = [] + result = LoggingResult(events) + + class LoggingCase(unittest.TestCase): + def run(self, result): + events.append('run %s' % self._testMethodName) + + def test1(self): pass + def test2(self): pass + + tests = [LoggingCase('test1'), LoggingCase('test2')] + + unittest.TestSuite(tests).run(result) + + self.assertEqual(events, ['run test1', 'run test2']) + + # "Add a TestCase ... to the suite" + def test_addTest__TestCase(self): + class Foo(unittest.TestCase): + def test(self): pass + + test = Foo('test') + suite = unittest.TestSuite() + + suite.addTest(test) + + self.assertEqual(suite.countTestCases(), 1) + self.assertEqual(list(suite), [test]) + + # "Add a ... TestSuite to the suite" + def test_addTest__TestSuite(self): + class Foo(unittest.TestCase): + def test(self): pass + + suite_2 = unittest.TestSuite([Foo('test')]) + + suite = unittest.TestSuite() + suite.addTest(suite_2) + + self.assertEqual(suite.countTestCases(), 1) + self.assertEqual(list(suite), [suite_2]) + + # "Add all the tests from an iterable of TestCase and TestSuite + # instances to this test suite." + # + # "This is equivalent to iterating over tests, calling addTest() for + # each element" + def test_addTests(self): + class Foo(unittest.TestCase): + def test_1(self): pass + def test_2(self): pass + + test_1 = Foo('test_1') + test_2 = Foo('test_2') + inner_suite = unittest.TestSuite([test_2]) + + def gen(): + yield test_1 + yield test_2 + yield inner_suite + + suite_1 = unittest.TestSuite() + suite_1.addTests(gen()) + + self.assertEqual(list(suite_1), list(gen())) + + # "This is equivalent to iterating over tests, calling addTest() for + # each element" + suite_2 = unittest.TestSuite() + for t in gen(): + suite_2.addTest(t) + + self.assertEqual(suite_1, suite_2) + + # "Add all the tests from an iterable of TestCase and TestSuite + # instances to this test suite." + # + # What happens if it doesn't get an iterable? + def test_addTest__noniterable(self): + suite = unittest.TestSuite() + + try: + suite.addTests(5) + except TypeError: + pass + else: + self.fail("Failed to raise TypeError") + + def test_addTest__noncallable(self): + suite = unittest.TestSuite() + self.assertRaises(TypeError, suite.addTest, 5) + + def test_addTest__casesuiteclass(self): + suite = unittest.TestSuite() + self.assertRaises(TypeError, suite.addTest, Test_TestSuite) + self.assertRaises(TypeError, suite.... [truncated message content] |
From: <fwi...@us...> - 2011-03-13 03:32:58
|
Revision: 7221 http://jython.svn.sourceforge.net/jython/?rev=7221&view=rev Author: fwierzbicki Date: 2011-03-13 03:32:51 +0000 (Sun, 13 Mar 2011) Log Message: ----------- Switching to CPython 2.6 Lib + get regrtest to at least have lots of fail instead of just crashing outright. Modified Paths: -------------- trunk/jython/Lib/socket.py trunk/jython/Lib/test/regrtest.py trunk/jython/src/org/python/core/__builtin__.java trunk/jython/src/org/python/modules/_functools/_functools.java Property Changed: ---------------- trunk/jython/ Property changes on: trunk/jython ___________________________________________________________________ Modified: svn:externals - CPythonLib -r70085 https://svn.python.org/projects/python/branches/release25-maint/Lib/ + CPythonLib -r88766 https://svn.python.org/projects/python/branches/release26-maint/Lib/ Modified: trunk/jython/Lib/socket.py =================================================================== --- trunk/jython/Lib/socket.py 2011-03-12 20:13:35 UTC (rev 7220) +++ trunk/jython/Lib/socket.py 2011-03-13 03:32:51 UTC (rev 7221) @@ -1506,6 +1506,7 @@ raise StopIteration return line +_GLOBAL_DEFAULT_TIMEOUT = object() # Define the SSL support Modified: trunk/jython/Lib/test/regrtest.py =================================================================== --- trunk/jython/Lib/test/regrtest.py 2011-03-12 20:13:35 UTC (rev 7220) +++ trunk/jython/Lib/test/regrtest.py 2011-03-13 03:32:51 UTC (rev 7221) @@ -553,11 +553,12 @@ else: cfp = cStringIO.StringIO() + from test.junit_xml import Tee, write_direct_test try: save_stdout = sys.stdout + + indirect_test = None if junit_xml_dir: - from test.junit_xml import Tee, write_direct_test - indirect_test = None save_stderr = sys.stderr sys.stdout = stdout = Tee(sys.stdout) sys.stderr = stderr = Tee(sys.stderr) @@ -1445,6 +1446,15 @@ test_winreg test_winsound test_zipfile64 + + test_gzip + test_ftplib + test_logging + test_poplib + test_pydoc + test_queue + test_smtplib + test_telnetlib """ } _expectations['freebsd5'] = _expectations['freebsd4'] Modified: trunk/jython/src/org/python/core/__builtin__.java =================================================================== --- trunk/jython/src/org/python/core/__builtin__.java 2011-03-12 20:13:35 UTC (rev 7220) +++ trunk/jython/src/org/python/core/__builtin__.java 2011-03-13 03:32:51 UTC (rev 7221) @@ -15,6 +15,8 @@ import org.python.antlr.base.mod; import org.python.core.util.RelativeFile; +import org.python.modules._functools._functools; + class BuiltinFunctions extends PyBuiltinFunctionSet { public static final PyObject module = Py.newString("__builtin__"); @@ -167,7 +169,7 @@ case 33: return __builtin__.pow(arg1, arg2); case 35: - return __builtin__.reduce(arg1, arg2); + return _functools.reduce(arg1, arg2); case 29: return fancyCall(new PyObject[] {arg1, arg2}); case 30: @@ -209,7 +211,7 @@ case 33: return __builtin__.pow(arg1, arg2, arg3); case 35: - return __builtin__.reduce(arg1, arg2, arg3); + return _functools.reduce(arg1, arg2, arg3); case 39: __builtin__.setattr(arg1, arg2, arg3); return Py.None; Modified: trunk/jython/src/org/python/modules/_functools/_functools.java =================================================================== --- trunk/jython/src/org/python/modules/_functools/_functools.java 2011-03-12 20:13:35 UTC (rev 7220) +++ trunk/jython/src/org/python/modules/_functools/_functools.java 2011-03-13 03:32:51 UTC (rev 7221) @@ -21,4 +21,35 @@ // Hide from Python dict.__setitem__("classDictInit", null); } + + public static PyString __doc__reduce = new PyString( + "reduce(function, sequence[, initial]) -> value\n\n" + + "Apply a function of two arguments cumulatively to the items of a sequence,\n" + + "from left to right, so as to reduce the sequence to a single value.\n" + + "For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n" + + "((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n" + + "of the sequence in the calculation, and serves as a default when the\n" + + "sequence is empty."); + + public static PyObject reduce(PyObject f, PyObject l, PyObject z) { + PyObject result = z; + PyObject iter = Py.iter(l, "reduce() arg 2 must support iteration"); + + for (PyObject item; (item = iter.__iternext__()) != null;) { + if (result == null) { + result = item; + } else { + result = f.__call__(result, item); + } + } + if (result == null) { + throw Py.TypeError("reduce of empty sequence with no initial value"); + } + return result; + } + + public static PyObject reduce(PyObject f, PyObject l) { + return reduce(f, l, null); + } + } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2011-03-12 20:13:48
|
Revision: 7220 http://jython.svn.sourceforge.net/jython/?rev=7220&view=rev Author: fwierzbicki Date: 2011-03-12 20:13:35 +0000 (Sat, 12 Mar 2011) Log Message: ----------- Tests added from Python 2.6 - these should be reviewed for deletion after we switch to the 2.6 Lib. Added Paths: ----------- trunk/jython/Lib/test/exception_hierarchy.txt trunk/jython/Lib/test/output/test_global trunk/jython/Lib/test/output/test_grammar trunk/jython/Lib/test/test_asynchat.py trunk/jython/Lib/test/test_base64.py trunk/jython/Lib/test/test_contextlib.py trunk/jython/Lib/test/test_datetime.py trunk/jython/Lib/test/test_email.py trunk/jython/Lib/test/test_email_renamed.py trunk/jython/Lib/test/test_gettext.py trunk/jython/Lib/test/test_global.py trunk/jython/Lib/test/test_threading_local.py trunk/jython/Lib/test/test_wsgiref.py Added: trunk/jython/Lib/test/exception_hierarchy.txt =================================================================== --- trunk/jython/Lib/test/exception_hierarchy.txt (rev 0) +++ trunk/jython/Lib/test/exception_hierarchy.txt 2011-03-12 20:13:35 UTC (rev 7220) @@ -0,0 +1,49 @@ +BaseException + +-- SystemExit + +-- KeyboardInterrupt + +-- GeneratorExit + +-- Exception + +-- StopIteration + +-- StandardError + | +-- ArithmeticError + | | +-- FloatingPointError + | | +-- OverflowError + | | +-- ZeroDivisionError + | +-- AssertionError + | +-- AttributeError + | +-- EnvironmentError + | | +-- IOError + | | +-- OSError + | | +-- WindowsError (Windows) + | | +-- VMSError (VMS) + | +-- EOFError + | +-- ImportError + | +-- LookupError + | | +-- IndexError + | | +-- KeyError + | +-- MemoryError + | +-- NameError + | | +-- UnboundLocalError + | +-- ReferenceError + | +-- RuntimeError + | | +-- NotImplementedError + | +-- SyntaxError + | | +-- IndentationError + | | +-- TabError + | +-- SystemError + | +-- TypeError + | +-- ValueError + | +-- UnicodeError + | +-- UnicodeDecodeError + | +-- UnicodeEncodeError + | +-- UnicodeTranslateError + +-- Warning + +-- DeprecationWarning + +-- PendingDeprecationWarning + +-- RuntimeWarning + +-- SyntaxWarning + +-- UserWarning + +-- FutureWarning + +-- ImportWarning + +-- UnicodeWarning + +-- BytesWarning Added: trunk/jython/Lib/test/output/test_global =================================================================== --- trunk/jython/Lib/test/output/test_global (rev 0) +++ trunk/jython/Lib/test/output/test_global 2011-03-12 20:13:35 UTC (rev 7220) @@ -0,0 +1 @@ +test_global Added: trunk/jython/Lib/test/output/test_grammar =================================================================== --- trunk/jython/Lib/test/output/test_grammar (rev 0) +++ trunk/jython/Lib/test/output/test_grammar 2011-03-12 20:13:35 UTC (rev 7220) @@ -0,0 +1 @@ +test_grammar Added: trunk/jython/Lib/test/test_asynchat.py =================================================================== --- trunk/jython/Lib/test/test_asynchat.py (rev 0) +++ trunk/jython/Lib/test/test_asynchat.py 2011-03-12 20:13:35 UTC (rev 7220) @@ -0,0 +1,93 @@ +# test asynchat -- requires threading + +import thread # If this fails, we can't test this module +import asyncore, asynchat, socket, threading, time +import unittest +from test import test_support + +HOST = "127.0.0.1" +PORT = 54322 + +class echo_server(threading.Thread): + + def run(self): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + global PORT + PORT = test_support.bind_port(sock, HOST) + sock.listen(1) + conn, client = sock.accept() + buffer = "" + while "\n" not in buffer: + data = conn.recv(1) + if not data: + break + buffer = buffer + data + while buffer: + n = conn.send(buffer) + buffer = buffer[n:] + conn.close() + sock.close() + +class echo_client(asynchat.async_chat): + + def __init__(self, terminator): + asynchat.async_chat.__init__(self) + self.contents = None + self.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.connect((HOST, PORT)) + self.set_terminator(terminator) + self.buffer = "" + + def handle_connect(self): + pass + ##print "Connected" + + def collect_incoming_data(self, data): + self.buffer = self.buffer + data + + def found_terminator(self): + #print "Received:", repr(self.buffer) + self.contents = self.buffer + self.buffer = "" + self.close() + + +class TestAsynchat(unittest.TestCase): + def setUp (self): + pass + + def tearDown (self): + pass + + def test_line_terminator(self): + s = echo_server() + s.start() + time.sleep(1) # Give server time to initialize + c = echo_client('\n') + c.push("hello ") + c.push("world\n") + asyncore.loop() + s.join() + + self.assertEqual(c.contents, 'hello world') + + def test_numeric_terminator(self): + # Try reading a fixed number of bytes + s = echo_server() + s.start() + time.sleep(1) # Give server time to initialize + c = echo_client(6L) + c.push("hello ") + c.push("world\n") + asyncore.loop() + s.join() + + self.assertEqual(c.contents, 'hello ') + + +def test_main(verbose=None): + test_support.run_unittest(TestAsynchat) + +if __name__ == "__main__": + test_main(verbose=True) Added: trunk/jython/Lib/test/test_base64.py =================================================================== --- trunk/jython/Lib/test/test_base64.py (rev 0) +++ trunk/jython/Lib/test/test_base64.py 2011-03-12 20:13:35 UTC (rev 7220) @@ -0,0 +1,190 @@ +import unittest +from test import test_support +import base64 + + + +class LegacyBase64TestCase(unittest.TestCase): + def test_encodestring(self): + eq = self.assertEqual + eq(base64.encodestring("www.python.org"), "d3d3LnB5dGhvbi5vcmc=\n") + eq(base64.encodestring("a"), "YQ==\n") + eq(base64.encodestring("ab"), "YWI=\n") + eq(base64.encodestring("abc"), "YWJj\n") + eq(base64.encodestring(""), "") + eq(base64.encodestring("abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789!@#0^&*();:<>,. []{}"), + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" + "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" + "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n") + + def test_decodestring(self): + eq = self.assertEqual + eq(base64.decodestring("d3d3LnB5dGhvbi5vcmc=\n"), "www.python.org") + eq(base64.decodestring("YQ==\n"), "a") + eq(base64.decodestring("YWI=\n"), "ab") + eq(base64.decodestring("YWJj\n"), "abc") + eq(base64.decodestring("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" + "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" + "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n"), + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789!@#0^&*();:<>,. []{}") + eq(base64.decodestring(''), '') + + def test_encode(self): + eq = self.assertEqual + from cStringIO import StringIO + infp = StringIO('abcdefghijklmnopqrstuvwxyz' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + '0123456789!@#0^&*();:<>,. []{}') + outfp = StringIO() + base64.encode(infp, outfp) + eq(outfp.getvalue(), + 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE' + 'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT' + 'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n') + + def test_decode(self): + from cStringIO import StringIO + infp = StringIO('d3d3LnB5dGhvbi5vcmc=') + outfp = StringIO() + base64.decode(infp, outfp) + self.assertEqual(outfp.getvalue(), 'www.python.org') + + + +class BaseXYTestCase(unittest.TestCase): + def test_b64encode(self): + eq = self.assertEqual + # Test default alphabet + eq(base64.b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=") + eq(base64.b64encode('\x00'), 'AA==') + eq(base64.b64encode("a"), "YQ==") + eq(base64.b64encode("ab"), "YWI=") + eq(base64.b64encode("abc"), "YWJj") + eq(base64.b64encode(""), "") + eq(base64.b64encode("abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789!@#0^&*();:<>,. []{}"), + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" + "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" + "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==") + # Test with arbitrary alternative characters + eq(base64.b64encode('\xd3V\xbeo\xf7\x1d', altchars='*$'), '01a*b$cd') + # Test standard alphabet + eq(base64.standard_b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=") + eq(base64.standard_b64encode("a"), "YQ==") + eq(base64.standard_b64encode("ab"), "YWI=") + eq(base64.standard_b64encode("abc"), "YWJj") + eq(base64.standard_b64encode(""), "") + eq(base64.standard_b64encode("abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789!@#0^&*();:<>,. []{}"), + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" + "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" + "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==") + # Test with 'URL safe' alternative characters + eq(base64.urlsafe_b64encode('\xd3V\xbeo\xf7\x1d'), '01a-b_cd') + + def test_b64decode(self): + eq = self.assertEqual + eq(base64.b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") + eq(base64.b64decode('AA=='), '\x00') + eq(base64.b64decode("YQ=="), "a") + eq(base64.b64decode("YWI="), "ab") + eq(base64.b64decode("YWJj"), "abc") + eq(base64.b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" + "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT" + "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789!@#0^&*();:<>,. []{}") + eq(base64.b64decode(''), '') + # Test with arbitrary alternative characters + eq(base64.b64decode('01a*b$cd', altchars='*$'), '\xd3V\xbeo\xf7\x1d') + # Test standard alphabet + eq(base64.standard_b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org") + eq(base64.standard_b64decode("YQ=="), "a") + eq(base64.standard_b64decode("YWI="), "ab") + eq(base64.standard_b64decode("YWJj"), "abc") + eq(base64.standard_b64decode(""), "") + eq(base64.standard_b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" + "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" + "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="), + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789!@#0^&*();:<>,. []{}") + # Test with 'URL safe' alternative characters + eq(base64.urlsafe_b64decode('01a-b_cd'), '\xd3V\xbeo\xf7\x1d') + + def test_b64decode_error(self): + self.assertRaises(TypeError, base64.b64decode, 'abc') + + def test_b32encode(self): + eq = self.assertEqual + eq(base64.b32encode(''), '') + eq(base64.b32encode('\x00'), 'AA======') + eq(base64.b32encode('a'), 'ME======') + eq(base64.b32encode('ab'), 'MFRA====') + eq(base64.b32encode('abc'), 'MFRGG===') + eq(base64.b32encode('abcd'), 'MFRGGZA=') + eq(base64.b32encode('abcde'), 'MFRGGZDF') + + def test_b32decode(self): + eq = self.assertEqual + eq(base64.b32decode(''), '') + eq(base64.b32decode('AA======'), '\x00') + eq(base64.b32decode('ME======'), 'a') + eq(base64.b32decode('MFRA===='), 'ab') + eq(base64.b32decode('MFRGG==='), 'abc') + eq(base64.b32decode('MFRGGZA='), 'abcd') + eq(base64.b32decode('MFRGGZDF'), 'abcde') + + def test_b32decode_casefold(self): + eq = self.assertEqual + eq(base64.b32decode('', True), '') + eq(base64.b32decode('ME======', True), 'a') + eq(base64.b32decode('MFRA====', True), 'ab') + eq(base64.b32decode('MFRGG===', True), 'abc') + eq(base64.b32decode('MFRGGZA=', True), 'abcd') + eq(base64.b32decode('MFRGGZDF', True), 'abcde') + # Lower cases + eq(base64.b32decode('me======', True), 'a') + eq(base64.b32decode('mfra====', True), 'ab') + eq(base64.b32decode('mfrgg===', True), 'abc') + eq(base64.b32decode('mfrggza=', True), 'abcd') + eq(base64.b32decode('mfrggzdf', True), 'abcde') + # Expected exceptions + self.assertRaises(TypeError, base64.b32decode, 'me======') + # Mapping zero and one + eq(base64.b32decode('MLO23456'), 'b\xdd\xad\xf3\xbe') + eq(base64.b32decode('M1023456', map01='L'), 'b\xdd\xad\xf3\xbe') + eq(base64.b32decode('M1023456', map01='I'), 'b\x1d\xad\xf3\xbe') + + def test_b32decode_error(self): + self.assertRaises(TypeError, base64.b32decode, 'abc') + self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==') + + def test_b16encode(self): + eq = self.assertEqual + eq(base64.b16encode('\x01\x02\xab\xcd\xef'), '0102ABCDEF') + eq(base64.b16encode('\x00'), '00') + + def test_b16decode(self): + eq = self.assertEqual + eq(base64.b16decode('0102ABCDEF'), '\x01\x02\xab\xcd\xef') + eq(base64.b16decode('00'), '\x00') + # Lower case is not allowed without a flag + self.assertRaises(TypeError, base64.b16decode, '0102abcdef') + # Case fold + eq(base64.b16decode('0102abcdef', True), '\x01\x02\xab\xcd\xef') + + + +def test_main(): + test_support.run_unittest(__name__) + +if __name__ == '__main__': + test_main() Added: trunk/jython/Lib/test/test_contextlib.py =================================================================== --- trunk/jython/Lib/test/test_contextlib.py (rev 0) +++ trunk/jython/Lib/test/test_contextlib.py 2011-03-12 20:13:35 UTC (rev 7220) @@ -0,0 +1,337 @@ +"""Unit tests for contextlib.py, and other context managers.""" + +import sys +import os +import decimal +import tempfile +import unittest +import threading +from contextlib import * # Tests __all__ +from test import test_support + +class ContextManagerTestCase(unittest.TestCase): + + def test_contextmanager_plain(self): + state = [] + @contextmanager + def woohoo(): + state.append(1) + yield 42 + state.append(999) + with woohoo() as x: + self.assertEqual(state, [1]) + self.assertEqual(x, 42) + state.append(x) + self.assertEqual(state, [1, 42, 999]) + + def test_contextmanager_finally(self): + state = [] + @contextmanager + def woohoo(): + state.append(1) + try: + yield 42 + finally: + state.append(999) + try: + with woohoo() as x: + self.assertEqual(state, [1]) + self.assertEqual(x, 42) + state.append(x) + raise ZeroDivisionError() + except ZeroDivisionError: + pass + else: + self.fail("Expected ZeroDivisionError") + self.assertEqual(state, [1, 42, 999]) + + def test_contextmanager_no_reraise(self): + @contextmanager + def whee(): + yield + ctx = whee() + ctx.__enter__() + # Calling __exit__ should not result in an exception + self.failIf(ctx.__exit__(TypeError, TypeError("foo"), None)) + + def test_contextmanager_trap_yield_after_throw(self): + @contextmanager + def whoo(): + try: + yield + except: + yield + ctx = whoo() + ctx.__enter__() + self.assertRaises( + RuntimeError, ctx.__exit__, TypeError, TypeError("foo"), None + ) + + def test_contextmanager_except(self): + state = [] + @contextmanager + def woohoo(): + state.append(1) + try: + yield 42 + except ZeroDivisionError, e: + state.append(e.args[0]) + self.assertEqual(state, [1, 42, 999]) + with woohoo() as x: + self.assertEqual(state, [1]) + self.assertEqual(x, 42) + state.append(x) + raise ZeroDivisionError(999) + self.assertEqual(state, [1, 42, 999]) + + def test_contextmanager_attribs(self): + def attribs(**kw): + def decorate(func): + for k,v in kw.items(): + setattr(func,k,v) + return func + return decorate + @contextmanager + @attribs(foo='bar') + def baz(spam): + """Whee!""" + self.assertEqual(baz.__name__,'baz') + self.assertEqual(baz.foo, 'bar') + self.assertEqual(baz.__doc__, "Whee!") + +class NestedTestCase(unittest.TestCase): + + # XXX This needs more work + + def test_nested(self): + @contextmanager + def a(): + yield 1 + @contextmanager + def b(): + yield 2 + @contextmanager + def c(): + yield 3 + with nested(a(), b(), c()) as (x, y, z): + self.assertEqual(x, 1) + self.assertEqual(y, 2) + self.assertEqual(z, 3) + + def test_nested_cleanup(self): + state = [] + @contextmanager + def a(): + state.append(1) + try: + yield 2 + finally: + state.append(3) + @contextmanager + def b(): + state.append(4) + try: + yield 5 + finally: + state.append(6) + try: + with nested(a(), b()) as (x, y): + state.append(x) + state.append(y) + 1 // 0 + except ZeroDivisionError: + self.assertEqual(state, [1, 4, 2, 5, 6, 3]) + else: + self.fail("Didn't raise ZeroDivisionError") + + def test_nested_right_exception(self): + state = [] + @contextmanager + def a(): + yield 1 + class b(object): + def __enter__(self): + return 2 + def __exit__(self, *exc_info): + try: + raise Exception() + except: + pass + try: + with nested(a(), b()) as (x, y): + 1 // 0 + except ZeroDivisionError: + self.assertEqual((x, y), (1, 2)) + except Exception: + self.fail("Reraised wrong exception") + else: + self.fail("Didn't raise ZeroDivisionError") + + def test_nested_b_swallows(self): + @contextmanager + def a(): + yield + @contextmanager + def b(): + try: + yield + except: + # Swallow the exception + pass + try: + with nested(a(), b()): + 1 // 0 + except ZeroDivisionError: + self.fail("Didn't swallow ZeroDivisionError") + + def test_nested_break(self): + @contextmanager + def a(): + yield + state = 0 + while True: + state += 1 + with nested(a(), a()): + break + state += 10 + self.assertEqual(state, 1) + + def test_nested_continue(self): + @contextmanager + def a(): + yield + state = 0 + while state < 3: + state += 1 + with nested(a(), a()): + continue + state += 10 + self.assertEqual(state, 3) + + def test_nested_return(self): + @contextmanager + def a(): + try: + yield + except: + pass + def foo(): + with nested(a(), a()): + return 1 + return 10 + self.assertEqual(foo(), 1) + +class ClosingTestCase(unittest.TestCase): + + # XXX This needs more work + + def test_closing(self): + state = [] + class C: + def close(self): + state.append(1) + x = C() + self.assertEqual(state, []) + with closing(x) as y: + self.assertEqual(x, y) + self.assertEqual(state, [1]) + + def test_closing_error(self): + state = [] + class C: + def close(self): + state.append(1) + x = C() + self.assertEqual(state, []) + try: + with closing(x) as y: + self.assertEqual(x, y) + 1 // 0 + except ZeroDivisionError: + self.assertEqual(state, [1]) + else: + self.fail("Didn't raise ZeroDivisionError") + +class FileContextTestCase(unittest.TestCase): + + def testWithOpen(self): + tfn = tempfile.mktemp() + try: + f = None + with open(tfn, "w") as f: + self.failIf(f.closed) + f.write("Booh\n") + self.failUnless(f.closed) + f = None + try: + with open(tfn, "r") as f: + self.failIf(f.closed) + self.assertEqual(f.read(), "Booh\n") + 1 // 0 + except ZeroDivisionError: + self.failUnless(f.closed) + else: + self.fail("Didn't raise ZeroDivisionError") + finally: + try: + os.remove(tfn) + except os.error: + pass + +class LockContextTestCase(unittest.TestCase): + + def boilerPlate(self, lock, locked): + self.failIf(locked()) + with lock: + self.failUnless(locked()) + self.failIf(locked()) + try: + with lock: + self.failUnless(locked()) + 1 // 0 + except ZeroDivisionError: + self.failIf(locked()) + else: + self.fail("Didn't raise ZeroDivisionError") + + def testWithLock(self): + lock = threading.Lock() + self.boilerPlate(lock, lock.locked) + + def testWithRLock(self): + lock = threading.RLock() + self.boilerPlate(lock, lock._is_owned) + + def testWithCondition(self): + lock = threading.Condition() + def locked(): + return lock._is_owned() + self.boilerPlate(lock, locked) + + def testWithSemaphore(self): + lock = threading.Semaphore() + def locked(): + if lock.acquire(False): + lock.release() + return False + else: + return True + self.boilerPlate(lock, locked) + + def testWithBoundedSemaphore(self): + lock = threading.BoundedSemaphore() + def locked(): + if lock.acquire(False): + lock.release() + return False + else: + return True + self.boilerPlate(lock, locked) + +# This is needed to make the test actually run under regrtest.py! +def test_main(): + test_support.run_unittest(__name__) + + +if __name__ == "__main__": + test_main() Added: trunk/jython/Lib/test/test_datetime.py =================================================================== --- trunk/jython/Lib/test/test_datetime.py (rev 0) +++ trunk/jython/Lib/test/test_datetime.py 2011-03-12 20:13:35 UTC (rev 7220) @@ -0,0 +1,3367 @@ +"""Test date/time type. + +See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases +""" + +import sys +import pickle +import cPickle +import unittest + +from test import test_support + +from datetime import MINYEAR, MAXYEAR +from datetime import timedelta +from datetime import tzinfo +from datetime import time +from datetime import date, datetime + +pickle_choices = [(pickler, unpickler, proto) + for pickler in pickle, cPickle + for unpickler in pickle, cPickle + for proto in range(3)] +assert len(pickle_choices) == 2*2*3 + +# An arbitrary collection of objects of non-datetime types, for testing +# mixed-type comparisons. +OTHERSTUFF = (10, 10L, 34.5, "abc", {}, [], ()) + + +############################################################################# +# module tests + +class TestModule(unittest.TestCase): + + def test_constants(self): + import datetime + self.assertEqual(datetime.MINYEAR, 1) + self.assertEqual(datetime.MAXYEAR, 9999) + +############################################################################# +# tzinfo tests + +class FixedOffset(tzinfo): + def __init__(self, offset, name, dstoffset=42): + if isinstance(offset, int): + offset = timedelta(minutes=offset) + if isinstance(dstoffset, int): + dstoffset = timedelta(minutes=dstoffset) + self.__offset = offset + self.__name = name + self.__dstoffset = dstoffset + def __repr__(self): + return self.__name.lower() + def utcoffset(self, dt): + return self.__offset + def tzname(self, dt): + return self.__name + def dst(self, dt): + return self.__dstoffset + +class PicklableFixedOffset(FixedOffset): + def __init__(self, offset=None, name=None, dstoffset=None): + FixedOffset.__init__(self, offset, name, dstoffset) + +class TestTZInfo(unittest.TestCase): + + def test_non_abstractness(self): + # In order to allow subclasses to get pickled, the C implementation + # wasn't able to get away with having __init__ raise + # NotImplementedError. + useless = tzinfo() + dt = datetime.max + self.assertRaises(NotImplementedError, useless.tzname, dt) + self.assertRaises(NotImplementedError, useless.utcoffset, dt) + self.assertRaises(NotImplementedError, useless.dst, dt) + + def test_subclass_must_override(self): + class NotEnough(tzinfo): + def __init__(self, offset, name): + self.__offset = offset + self.__name = name + self.failUnless(issubclass(NotEnough, tzinfo)) + ne = NotEnough(3, "NotByALongShot") + self.failUnless(isinstance(ne, tzinfo)) + + dt = datetime.now() + self.assertRaises(NotImplementedError, ne.tzname, dt) + self.assertRaises(NotImplementedError, ne.utcoffset, dt) + self.assertRaises(NotImplementedError, ne.dst, dt) + + def test_normal(self): + fo = FixedOffset(3, "Three") + self.failUnless(isinstance(fo, tzinfo)) + for dt in datetime.now(), None: + self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3)) + self.assertEqual(fo.tzname(dt), "Three") + self.assertEqual(fo.dst(dt), timedelta(minutes=42)) + + def test_pickling_base(self): + # There's no point to pickling tzinfo objects on their own (they + # carry no data), but they need to be picklable anyway else + # concrete subclasses can't be pickled. + orig = tzinfo.__new__(tzinfo) + self.failUnless(type(orig) is tzinfo) + for pickler, unpickler, proto in pickle_choices: + green = pickler.dumps(orig, proto) + derived = unpickler.loads(green) + self.failUnless(type(derived) is tzinfo) + + def test_pickling_subclass(self): + # Make sure we can pickle/unpickle an instance of a subclass. + offset = timedelta(minutes=-300) + orig = PicklableFixedOffset(offset, 'cookie') + self.failUnless(isinstance(orig, tzinfo)) + self.failUnless(type(orig) is PicklableFixedOffset) + self.assertEqual(orig.utcoffset(None), offset) + self.assertEqual(orig.tzname(None), 'cookie') + for pickler, unpickler, proto in pickle_choices: + green = pickler.dumps(orig, proto) + derived = unpickler.loads(green) + self.failUnless(isinstance(derived, tzinfo)) + self.failUnless(type(derived) is PicklableFixedOffset) + self.assertEqual(derived.utcoffset(None), offset) + self.assertEqual(derived.tzname(None), 'cookie') + +############################################################################# +# Base clase for testing a particular aspect of timedelta, time, date and +# datetime comparisons. + +class HarmlessMixedComparison: + # Test that __eq__ and __ne__ don't complain for mixed-type comparisons. + + # Subclasses must define 'theclass', and theclass(1, 1, 1) must be a + # legit constructor. + + def test_harmless_mixed_comparison(self): + me = self.theclass(1, 1, 1) + + self.failIf(me == ()) + self.failUnless(me != ()) + self.failIf(() == me) + self.failUnless(() != me) + + self.failUnless(me in [1, 20L, [], me]) + self.failIf(me not in [1, 20L, [], me]) + + self.failUnless([] in [me, 1, 20L, []]) + self.failIf([] not in [me, 1, 20L, []]) + + def test_harmful_mixed_comparison(self): + me = self.theclass(1, 1, 1) + + self.assertRaises(TypeError, lambda: me < ()) + self.assertRaises(TypeError, lambda: me <= ()) + self.assertRaises(TypeError, lambda: me > ()) + self.assertRaises(TypeError, lambda: me >= ()) + + self.assertRaises(TypeError, lambda: () < me) + self.assertRaises(TypeError, lambda: () <= me) + self.assertRaises(TypeError, lambda: () > me) + self.assertRaises(TypeError, lambda: () >= me) + + self.assertRaises(TypeError, cmp, (), me) + self.assertRaises(TypeError, cmp, me, ()) + +############################################################################# +# timedelta tests + +class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): + + theclass = timedelta + + def test_constructor(self): + eq = self.assertEqual + td = timedelta + + # Check keyword args to constructor + eq(td(), td(weeks=0, days=0, hours=0, minutes=0, seconds=0, + milliseconds=0, microseconds=0)) + eq(td(1), td(days=1)) + eq(td(0, 1), td(seconds=1)) + eq(td(0, 0, 1), td(microseconds=1)) + eq(td(weeks=1), td(days=7)) + eq(td(days=1), td(hours=24)) + eq(td(hours=1), td(minutes=60)) + eq(td(minutes=1), td(seconds=60)) + eq(td(seconds=1), td(milliseconds=1000)) + eq(td(milliseconds=1), td(microseconds=1000)) + + # Check float args to constructor + eq(td(weeks=1.0/7), td(days=1)) + eq(td(days=1.0/24), td(hours=1)) + eq(td(hours=1.0/60), td(minutes=1)) + eq(td(minutes=1.0/60), td(seconds=1)) + eq(td(seconds=0.001), td(milliseconds=1)) + eq(td(milliseconds=0.001), td(microseconds=1)) + + def test_computations(self): + eq = self.assertEqual + td = timedelta + + a = td(7) # One week + b = td(0, 60) # One minute + c = td(0, 0, 1000) # One millisecond + eq(a+b+c, td(7, 60, 1000)) + eq(a-b, td(6, 24*3600 - 60)) + eq(-a, td(-7)) + eq(+a, td(7)) + eq(-b, td(-1, 24*3600 - 60)) + eq(-c, td(-1, 24*3600 - 1, 999000)) + eq(abs(a), a) + eq(abs(-a), a) + eq(td(6, 24*3600), a) + eq(td(0, 0, 60*1000000), b) + eq(a*10, td(70)) + eq(a*10, 10*a) + eq(a*10L, 10*a) + eq(b*10, td(0, 600)) + eq(10*b, td(0, 600)) + eq(b*10L, td(0, 600)) + eq(c*10, td(0, 0, 10000)) + eq(10*c, td(0, 0, 10000)) + eq(c*10L, td(0, 0, 10000)) + eq(a*-1, -a) + eq(b*-2, -b-b) + eq(c*-2, -c+-c) + eq(b*(60*24), (b*60)*24) + eq(b*(60*24), (60*b)*24) + eq(c*1000, td(0, 1)) + eq(1000*c, td(0, 1)) + eq(a//7, td(1)) + eq(b//10, td(0, 6)) + eq(c//1000, td(0, 0, 1)) + eq(a//10, td(0, 7*24*360)) + eq(a//3600000, td(0, 0, 7*24*1000)) + + def test_disallowed_computations(self): + a = timedelta(42) + + # Add/sub ints, longs, floats should be illegal + for i in 1, 1L, 1.0: + self.assertRaises(TypeError, lambda: a+i) + self.assertRaises(TypeError, lambda: a-i) + self.assertRaises(TypeError, lambda: i+a) + self.assertRaises(TypeError, lambda: i-a) + + # Mul/div by float isn't supported. + x = 2.3 + self.assertRaises(TypeError, lambda: a*x) + self.assertRaises(TypeError, lambda: x*a) + self.assertRaises(TypeError, lambda: a/x) + self.assertRaises(TypeError, lambda: x/a) + self.assertRaises(TypeError, lambda: a // x) + self.assertRaises(TypeError, lambda: x // a) + + # Division of int by timedelta doesn't make sense. + # Division by zero doesn't make sense. + for zero in 0, 0L: + self.assertRaises(TypeError, lambda: zero // a) + self.assertRaises(ZeroDivisionError, lambda: a // zero) + + def test_basic_attributes(self): + days, seconds, us = 1, 7, 31 + td = timedelta(days, seconds, us) + self.assertEqual(td.days, days) + self.assertEqual(td.seconds, seconds) + self.assertEqual(td.microseconds, us) + + def test_carries(self): + t1 = timedelta(days=100, + weeks=-7, + hours=-24*(100-49), + minutes=-3, + seconds=12, + microseconds=(3*60 - 12) * 1e6 + 1) + t2 = timedelta(microseconds=1) + self.assertEqual(t1, t2) + + def test_hash_equality(self): + t1 = timedelta(days=100, + weeks=-7, + hours=-24*(100-49), + minutes=-3, + seconds=12, + microseconds=(3*60 - 12) * 1000000) + t2 = timedelta() + self.assertEqual(hash(t1), hash(t2)) + + t1 += timedelta(weeks=7) + t2 += timedelta(days=7*7) + self.assertEqual(t1, t2) + self.assertEqual(hash(t1), hash(t2)) + + d = {t1: 1} + d[t2] = 2 + self.assertEqual(len(d), 1) + self.assertEqual(d[t1], 2) + + def test_pickling(self): + args = 12, 34, 56 + orig = timedelta(*args) + for pickler, unpickler, proto in pickle_choices: + green = pickler.dumps(orig, proto) + derived = unpickler.loads(green) + self.assertEqual(orig, derived) + + def test_compare(self): + t1 = timedelta(2, 3, 4) + t2 = timedelta(2, 3, 4) + self.failUnless(t1 == t2) + self.failUnless(t1 <= t2) + self.failUnless(t1 >= t2) + self.failUnless(not t1 != t2) + self.failUnless(not t1 < t2) + self.failUnless(not t1 > t2) + self.assertEqual(cmp(t1, t2), 0) + self.assertEqual(cmp(t2, t1), 0) + + for args in (3, 3, 3), (2, 4, 4), (2, 3, 5): + t2 = timedelta(*args) # this is larger than t1 + self.failUnless(t1 < t2) + self.failUnless(t2 > t1) + self.failUnless(t1 <= t2) + self.failUnless(t2 >= t1) + self.failUnless(t1 != t2) + self.failUnless(t2 != t1) + self.failUnless(not t1 == t2) + self.failUnless(not t2 == t1) + self.failUnless(not t1 > t2) + self.failUnless(not t2 < t1) + self.failUnless(not t1 >= t2) + self.failUnless(not t2 <= t1) + self.assertEqual(cmp(t1, t2), -1) + self.assertEqual(cmp(t2, t1), 1) + + for badarg in OTHERSTUFF: + self.assertEqual(t1 == badarg, False) + self.assertEqual(t1 != badarg, True) + self.assertEqual(badarg == t1, False) + self.assertEqual(badarg != t1, True) + + self.assertRaises(TypeError, lambda: t1 <= badarg) + self.assertRaises(TypeError, lambda: t1 < badarg) + self.assertRaises(TypeError, lambda: t1 > badarg) + self.assertRaises(TypeError, lambda: t1 >= badarg) + self.assertRaises(TypeError, lambda: badarg <= t1) + self.assertRaises(TypeError, lambda: badarg < t1) + self.assertRaises(TypeError, lambda: badarg > t1) + self.assertRaises(TypeError, lambda: badarg >= t1) + + def test_str(self): + td = timedelta + eq = self.assertEqual + + eq(str(td(1)), "1 day, 0:00:00") + eq(str(td(-1)), "-1 day, 0:00:00") + eq(str(td(2)), "2 days, 0:00:00") + eq(str(td(-2)), "-2 days, 0:00:00") + + eq(str(td(hours=12, minutes=58, seconds=59)), "12:58:59") + eq(str(td(hours=2, minutes=3, seconds=4)), "2:03:04") + eq(str(td(weeks=-30, hours=23, minutes=12, seconds=34)), + "-210 days, 23:12:34") + + eq(str(td(milliseconds=1)), "0:00:00.001000") + eq(str(td(microseconds=3)), "0:00:00.000003") + + eq(str(td(days=999999999, hours=23, minutes=59, seconds=59, + microseconds=999999)), + "999999999 days, 23:59:59.999999") + + def test_roundtrip(self): + for td in (timedelta(days=999999999, hours=23, minutes=59, + seconds=59, microseconds=999999), + timedelta(days=-999999999), + timedelta(days=1, seconds=2, microseconds=3)): + + # Verify td -> string -> td identity. + s = repr(td) + self.failUnless(s.startswith('datetime.')) + s = s[9:] + td2 = eval(s) + self.assertEqual(td, td2) + + # Verify identity via reconstructing from pieces. + td2 = timedelta(td.days, td.seconds, td.microseconds) + self.assertEqual(td, td2) + + def test_resolution_info(self): + self.assert_(isinstance(timedelta.min, timedelta)) + self.assert_(isinstance(timedelta.max, timedelta)) + self.assert_(isinstance(timedelta.resolution, timedelta)) + self.assert_(timedelta.max > timedelta.min) + self.assertEqual(timedelta.min, timedelta(-999999999)) + self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1)) + self.assertEqual(timedelta.resolution, timedelta(0, 0, 1)) + + def test_overflow(self): + tiny = timedelta.resolution + + td = timedelta.min + tiny + td -= tiny # no problem + self.assertRaises(OverflowError, td.__sub__, tiny) + self.assertRaises(OverflowError, td.__add__, -tiny) + + td = timedelta.max - tiny + td += tiny # no problem + self.assertRaises(OverflowError, td.__add__, tiny) + self.assertRaises(OverflowError, td.__sub__, -tiny) + + self.assertRaises(OverflowError, lambda: -timedelta.max) + + def test_microsecond_rounding(self): + td = timedelta + eq = self.assertEqual + + # Single-field rounding. + eq(td(milliseconds=0.4/1000), td(0)) # rounds to 0 + eq(td(milliseconds=-0.4/1000), td(0)) # rounds to 0 + eq(td(milliseconds=0.6/1000), td(microseconds=1)) + eq(td(milliseconds=-0.6/1000), td(microseconds=-1)) + + # Rounding due to contributions from more than one field. + us_per_hour = 3600e6 + us_per_day = us_per_hour * 24 + eq(td(days=.4/us_per_day), td(0)) + eq(td(hours=.2/us_per_hour), td(0)) + eq(td(days=.4/us_per_day, hours=.2/us_per_hour), td(microseconds=1)) + + eq(td(days=-.4/us_per_day), td(0)) + eq(td(hours=-.2/us_per_hour), td(0)) + eq(td(days=-.4/us_per_day, hours=-.2/us_per_hour), td(microseconds=-1)) + + def test_massive_normalization(self): + td = timedelta(microseconds=-1) + self.assertEqual((td.days, td.seconds, td.microseconds), + (-1, 24*3600-1, 999999)) + + def test_bool(self): + self.failUnless(timedelta(1)) + self.failUnless(timedelta(0, 1)) + self.failUnless(timedelta(0, 0, 1)) + self.failUnless(timedelta(microseconds=1)) + self.failUnless(not timedelta(0)) + + def test_subclass_timedelta(self): + + class T(timedelta): + @staticmethod + def from_td(td): + return T(td.days, td.seconds, td.microseconds) + + def as_hours(self): + sum = (self.days * 24 + + self.seconds / 3600.0 + + self.microseconds / 3600e6) + return round(sum) + + t1 = T(days=1) + self.assert_(type(t1) is T) + self.assertEqual(t1.as_hours(), 24) + + t2 = T(days=-1, seconds=-3600) + self.assert_(type(t2) is T) + self.assertEqual(t2.as_hours(), -25) + + t3 = t1 + t2 + self.assert_(type(t3) is timedelta) + t4 = T.from_td(t3) + self.assert_(type(t4) is T) + self.assertEqual(t3.days, t4.days) + self.assertEqual(t3.seconds, t4.seconds) + self.assertEqual(t3.microseconds, t4.microseconds) + self.assertEqual(str(t3), str(t4)) + self.assertEqual(t4.as_hours(), -1) + +############################################################################# +# date tests + +class TestDateOnly(unittest.TestCase): + # Tests here won't pass if also run on datetime objects, so don't + # subclass this to test datetimes too. + + def test_delta_non_days_ignored(self): + dt = date(2000, 1, 2) + delta = timedelta(days=1, hours=2, minutes=3, seconds=4, + microseconds=5) + days = timedelta(delta.days) + self.assertEqual(days, timedelta(1)) + + dt2 = dt + delta + self.assertEqual(dt2, dt + days) + + dt2 = delta + dt + self.assertEqual(dt2, dt + days) + + dt2 = dt - delta + self.assertEqual(dt2, dt - days) + + delta = -delta + days = timedelta(delta.days) + self.assertEqual(days, timedelta(-2)) + + dt2 = dt + delta + self.assertEqual(dt2, dt + days) + + dt2 = delta + dt + self.assertEqual(dt2, dt + days) + + dt2 = dt - delta + self.assertEqual(dt2, dt - days) + +class SubclassDate(date): + sub_var = 1 + +class TestDate(HarmlessMixedComparison, unittest.TestCase): + # Tests here should pass for both dates and datetimes, except for a + # few tests that TestDateTime overrides. + + theclass = date + + def test_basic_attributes(self): + dt = self.theclass(2002, 3, 1) + self.assertEqual(dt.year, 2002) + self.assertEqual(dt.month, 3) + self.assertEqual(dt.day, 1) + + def test_roundtrip(self): + for dt in (self.theclass(1, 2, 3), + self.theclass.today()): + # Verify dt -> string -> date identity. + s = repr(dt) + self.failUnless(s.startswith('datetime.')) + s = s[9:] + dt2 = eval(s) + self.assertEqual(dt, dt2) + + # Verify identity via reconstructing from pieces. + dt2 = self.theclass(dt.year, dt.month, dt.day) + self.assertEqual(dt, dt2) + + def test_ordinal_conversions(self): + # Check some fixed values. + for y, m, d, n in [(1, 1, 1, 1), # calendar origin + (1, 12, 31, 365), + (2, 1, 1, 366), + # first example from "Calendrical Calculations" + (1945, 11, 12, 710347)]: + d = self.theclass(y, m, d) + self.assertEqual(n, d.toordinal()) + fromord = self.theclass.fromordinal(n) + self.assertEqual(d, fromord) + if hasattr(fromord, "hour"): + # if we're checking something fancier than a date, verify + # the extra fields have been zeroed out + self.assertEqual(fromord.hour, 0) + self.assertEqual(fromord.minute, 0) + self.assertEqual(fromord.second, 0) + self.assertEqual(fromord.microsecond, 0) + + # Check first and last days of year spottily across the whole + # range of years supported. + for year in xrange(MINYEAR, MAXYEAR+1, 7): + # Verify (year, 1, 1) -> ordinal -> y, m, d is identity. + d = self.theclass(year, 1, 1) + n = d.toordinal() + d2 = self.theclass.fromordinal(n) + self.assertEqual(d, d2) + # Verify that moving back a day gets to the end of year-1. + if year > 1: + d = self.theclass.fromordinal(n-1) + d2 = self.theclass(year-1, 12, 31) + self.assertEqual(d, d2) + self.assertEqual(d2.toordinal(), n-1) + + # Test every day in a leap-year and a non-leap year. + dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + for year, isleap in (2000, True), (2002, False): + n = self.theclass(year, 1, 1).toordinal() + for month, maxday in zip(range(1, 13), dim): + if month == 2 and isleap: + maxday += 1 + for day in range(1, maxday+1): + d = self.theclass(year, month, day) + self.assertEqual(d.toordinal(), n) + self.assertEqual(d, self.theclass.fromordinal(n)) + n += 1 + + def test_extreme_ordinals(self): + a = self.theclass.min + a = self.theclass(a.year, a.month, a.day) # get rid of time parts + aord = a.toordinal() + b = a.fromordinal(aord) + self.assertEqual(a, b) + + self.assertRaises(ValueError, lambda: a.fromordinal(aord - 1)) + + b = a + timedelta(days=1) + self.assertEqual(b.toordinal(), aord + 1) + self.assertEqual(b, self.theclass.fromordinal(aord + 1)) + + a = self.theclass.max + a = self.theclass(a.year, a.month, a.day) # get rid of time parts + aord = a.toordinal() + b = a.fromordinal(aord) + self.assertEqual(a, b) + + self.assertRaises(ValueError, lambda: a.fromordinal(aord + 1)) + + b = a - timedelta(days=1) + self.assertEqual(b.toordinal(), aord - 1) + self.assertEqual(b, self.theclass.fromordinal(aord - 1)) + + def test_bad_constructor_arguments(self): + # bad years + self.theclass(MINYEAR, 1, 1) # no exception + self.theclass(MAXYEAR, 1, 1) # no exception + self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1) + self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1) + # bad months + self.theclass(2000, 1, 1) # no exception + self.theclass(2000, 12, 1) # no exception + self.assertRaises(ValueError, self.theclass, 2000, 0, 1) + self.assertRaises(ValueError, self.theclass, 2000, 13, 1) + # bad days + self.theclass(2000, 2, 29) # no exception + self.theclass(2004, 2, 29) # no exception + self.theclass(2400, 2, 29) # no exception + self.assertRaises(ValueError, self.theclass, 2000, 2, 30) + self.assertRaises(ValueError, self.theclass, 2001, 2, 29) + self.assertRaises(ValueError, self.theclass, 2100, 2, 29) + self.assertRaises(ValueError, self.theclass, 1900, 2, 29) + self.assertRaises(ValueError, self.theclass, 2000, 1, 0) + self.assertRaises(ValueError, self.theclass, 2000, 1, 32) + + def test_hash_equality(self): + d = self.theclass(2000, 12, 31) + # same thing + e = self.theclass(2000, 12, 31) + self.assertEqual(d, e) + self.assertEqual(hash(d), hash(e)) + + dic = {d: 1} + dic[e] = 2 + self.assertEqual(len(dic), 1) + self.assertEqual(dic[d], 2) + self.assertEqual(dic[e], 2) + + d = self.theclass(2001, 1, 1) + # same thing + e = self.theclass(2001, 1, 1) + self.assertEqual(d, e) + self.assertEqual(hash(d), hash(e)) + + dic = {d: 1} + dic[e] = 2 + self.assertEqual(len(dic), 1) + self.assertEqual(dic[d], 2) + self.assertEqual(dic[e], 2) + + def test_computations(self): + a = self.theclass(2002, 1, 31) + b = self.theclass(1956, 1, 31) + + diff = a-b + self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4))) + self.assertEqual(diff.seconds, 0) + self.assertEqual(diff.microseconds, 0) + + day = timedelta(1) + week = timedelta(7) + a = self.theclass(2002, 3, 2) + self.assertEqual(a + day, self.theclass(2002, 3, 3)) + self.assertEqual(day + a, self.theclass(2002, 3, 3)) + self.assertEqual(a - day, self.theclass(2002, 3, 1)) + self.assertEqual(-day + a, self.theclass(2002, 3, 1)) + self.assertEqual(a + week, self.theclass(2002, 3, 9)) + self.assertEqual(a - week, self.theclass(2002, 2, 23)) + self.assertEqual(a + 52*week, self.theclass(2003, 3, 1)) + self.assertEqual(a - 52*week, self.theclass(2001, 3, 3)) + self.assertEqual((a + week) - a, week) + self.assertEqual((a + day) - a, day) + self.assertEqual((a - week) - a, -week) + self.assertEqual((a - day) - a, -day) + self.assertEqual(a - (a + week), -week) + self.assertEqual(a - (a + day), -day) + self.assertEqual(a - (a - week), week) + self.assertEqual(a - (a - day), day) + + # Add/sub ints, longs, floats should be illegal + for i in 1, 1L, 1.0: + self.assertRaises(TypeError, lambda: a+i) + self.assertRaises(TypeError, lambda: a-i) + self.assertRaises(TypeError, lambda: i+a) + self.assertRaises(TypeError, lambda: i-a) + + # delta - date is senseless. + self.assertRaises(TypeError, lambda: day - a) + # mixing date and (delta or date) via * or // is senseless + self.assertRaises(TypeError, lambda: day * a) + self.assertRaises(TypeError, lambda: a * day) + self.assertRaises(TypeError, lambda: day // a) + self.assertRaises(TypeError, lambda: a // day) + self.assertRaises(TypeError, lambda: a * a) + self.assertRaises(TypeError, lambda: a // a) + # date + date is senseless + self.assertRaises(TypeError, lambda: a + a) + + def test_overflow(self): + tiny = self.theclass.resolution + + for delta in [tiny, timedelta(1), timedelta(2)]: + dt = self.theclass.min + delta + dt -= delta # no problem + self.assertRaises(OverflowError, dt.__sub__, delta) + self.assertRaises(OverflowError, dt.__add__, -delta) + + dt = self.theclass.max - delta + dt += delta # no problem + self.assertRaises(OverflowError, dt.__add__, delta) + self.assertRaises(OverflowError, dt.__sub__, -delta) + + def test_fromtimestamp(self): + import time + + # Try an arbitrary fixed value. + year, month, day = 1999, 9, 19 + ts = time.mktime((year, month, day, 0, 0, 0, 0, 0, -1)) + d = self.theclass.fromtimestamp(ts) + self.assertEqual(d.year, year) + self.assertEqual(d.month, month) + self.assertEqual(d.day, day) + + def test_insane_fromtimestamp(self): + # It's possible that some platform maps time_t to double, + # and that this test will fail there. This test should + # exempt such platforms (provided they return reasonable + # results!). + for insane in -1e200, 1e200: + self.assertRaises(ValueError, self.theclass.fromtimestamp, + insane) + + def test_today(self): + import time + + # We claim that today() is like fromtimestamp(time.time()), so + # prove it. + for dummy in range(3): + today = self.theclass.today() + ts = time.time() + todayagain = self.theclass.fromtimestamp(ts) + if today == todayagain: + break + # There are several legit reasons that could fail: + # 1. It recently became midnight, between the today() and the + # time() calls. + # 2. The platform time() has such fine resolution that we'll + # never get the same value twice. + # 3. The platform time() has poor resolution, and we just + # happened to call today() right before a resolution quantum + # boundary. + # 4. The system clock got fiddled between calls. + # In any case, wait a little while and try again. + time.sleep(0.1) + + # It worked or it didn't. If it didn't, assume it's reason #2, and + # let the test pass if they're within half a second of each other. + self.failUnless(today == todayagain or + abs(todayagain - today) < timedelta(seconds=0.5)) + + def test_weekday(self): + for i in range(7): + # March 4, 2002 is a Monday + self.assertEqual(self.theclass(2002, 3, 4+i).weekday(), i) + self.assertEqual(self.theclass(2002, 3, 4+i).isoweekday(), i+1) + # January 2, 1956 is a Monday + self.assertEqual(self.theclass(1956, 1, 2+i).weekday(), i) + self.assertEqual(self.theclass(1956, 1, 2+i).isoweekday(), i+1) + + def test_isocalendar(self): + # Check examples from + # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm + for i in range(7): + d = self.theclass(2003, 12, 22+i) + self.assertEqual(d.isocalendar(), (2003, 52, i+1)) + d = self.theclass(2003, 12, 29) + timedelta(i) + self.assertEqual(d.isocalendar(), (2004, 1, i+1)) + d = self.theclass(2004, 1, 5+i) + self.assertEqual(d.isocalendar(), (2004, 2, i+1)) + d = self.theclass(2009, 12, 21+i) + self.assertEqual(d.isocalendar(), (2009, 52, i+1)) + d = self.theclass(2009, 12, 28) + timedelta(i) + self.assertEqual(d.isocalendar(), (2009, 53, i+1)) + d = self.theclass(2010, 1, 4+i) + self.assertEqual(d.isocalendar(), (2010, 1, i+1)) + + def test_iso_long_years(self): + # Calculate long ISO years and compare to table from + # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm + ISO_LONG_YEARS_TABLE = """ + 4 32 60 88 + 9 37 65 93 + 15 43 71 99 + 20 48 76 + 26 54 82 + + 105 133 161 189 + 111 139 167 195 + 116 144 172 + 122 150 178 + 128 156 184 + + 201 229 257 285 + 207 235 263 291 + 212 240 268 296 + 218 246 274 + 224 252 280 + + 303 331 359 387 + 308 336 364 392 + 314 342 370 398 + 320 348 376 + 325 353 381 + """ + iso_long_years = map(int, ISO_LONG_YEARS_TABLE.split()) + iso_long_years.sort() + L = [] + for i in range(400): + d = self.theclass(2000+i, 12, 31) + d1 = self.theclass(1600+i, 12, 31) + self.assertEqual(d.isocalendar()[1:], d1.isocalendar()[1:]) + if d.isocalendar()[1] == 53: + L.append(i) + self.assertEqual(L, iso_long_years) + + def test_isoformat(self): + t = self.theclass(2, 3, 2) + self.assertEqual(t.isoformat(), "0002-03-02") + + def test_ctime(self): + t = self.theclass(2002, 3, 2) + self.assertEqual(t.ctime(), "Sat Mar 2 00:00:00 2002") + + def test_strftime(self): + t = self.theclass(2005, 3, 2) + self.assertEqual(t.strftime("m:%m d:%d y:%y"), "m:03 d:02 y:05") + self.assertEqual(t.strftime(""), "") # SF bug #761337 + self.assertEqual(t.strftime('x'*1000), 'x'*1000) # SF bug #1556784 + + self.assertRaises(TypeError, t.strftime) # needs an arg + self.assertRaises(TypeError, t.strftime, "one", "two") # too many args + self.assertRaises(TypeError, t.strftime, 42) # arg wrong type + + # test that unicode input is allowed (issue 2782) + self.assertEqual(t.strftime(u"%m"), "03") + + # A naive object replaces %z and %Z w/ empty strings. + self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''") + + #make sure that invalid format specifiers are handled correctly + #self.assertRaises(ValueError, t.strftime, "%e") + #self.assertRaises(ValueError, t.strftime, "%") + #self.assertRaises(ValueError, t.strftime, "%#") + + #oh well, some systems just ignore those invalid ones. + #at least, excercise them to make sure that no crashes + #are generated + for f in ["%e", "%", "%#"]: + try: + t.strftime(f) + except ValueError: + pass + + #check that this standard extension works + t.strftime("%f") + + + def test_format(self): + dt = self.theclass(2007, 9, 10) + self.assertEqual(dt.__format__(''), str(dt)) + + # check that a derived class's __str__() gets called + class A(self.theclass): + def __str__(self): + return 'A' + a = A(2007, 9, 10) + self.assertEqual(a.__format__(''), 'A') + + # check that a derived class's strftime gets called + class B(self.theclass): + def strftime(self, format_spec): + return 'B' + b = B(2007, 9, 10) + self.assertEqual(b.__format__(''), str(dt)) + + for fmt in ["m:%m d:%d y:%y", + "m:%m d:%d y:%y H:%H M:%M S:%S", + "%z %Z", + ]: + self.assertEqual(dt.__format__(fmt), dt.strftime(fmt)) + self.assertEqual(a.__format__(fmt), dt.strftime(fmt)) + self.assertEqual(b.__format__(fmt), 'B') + + def test_resolution_info(self): + self.assert_(isinstance(self.theclass.min, self.theclass)) + self.assert_(isinstance(self.theclass.max, self.theclass)) + self.assert_(isinstance(self.theclass.resolution, timedelta)) + self.assert_(self.theclass.max > self.theclass.min) + + def test_extreme_timedelta(self): + big = self.theclass.max - self.theclass.min + # 3652058 days, 23 hours, 59 minutes, 59 seconds, 999999 microseconds + n = (big.days*24*3600 + big.seconds)*1000000 + big.microseconds + # n == 315537897599999999 ~= 2**58.13 + justasbig = timedelta(0, 0, n) + self.assertEqual(big, justasbig) + self.assertEqual(self.theclass.min + big, self.theclass.max) + self.assertEqual(self.theclass.max - big, self.theclass.min) + + def test_timetuple(self): + for i in range(7): + # January 2, 1956 is a Monday (0) + d = self.theclass(1956, 1, 2+i) + t = d.timetuple() + self.assertEqual(t, (1956, 1, 2+i, 0, 0, 0, i, 2+i, -1)) + # February 1, 1956 is a Wednesday (2) + d = self.theclass(1956, 2, 1+i) + t = d.timetuple() + self.assertEqual(t, (1956, 2, 1+i, 0, 0, 0, (2+i)%7, 32+i, -1)) + # March 1, 1956 is a Thursday (3), and is the 31+29+1 = 61st day + # of the year. + d = self.theclass(1956, 3, 1+i) + t = d.timetuple() + self.assert... [truncated message content] |
From: <fwi...@us...> - 2011-03-12 20:12:01
|
Revision: 7219 http://jython.svn.sourceforge.net/jython/?rev=7219&view=rev Author: fwierzbicki Date: 2011-03-12 20:11:47 +0000 (Sat, 12 Mar 2011) Log Message: ----------- Files changed for new test_support.py Modified Paths: -------------- trunk/jython/Lib/test/test_jy_internals.py trunk/jython/Lib/test/test_optparse.py trunk/jython/Lib/test/test_pulldom.py trunk/jython/Lib/test/test_scope.py trunk/jython/Lib/test/test_select.py trunk/jython/Lib/test/test_select_new.py trunk/jython/Lib/test/test_socket.py trunk/jython/Lib/test/test_support.py Modified: trunk/jython/Lib/test/test_jy_internals.py =================================================================== --- trunk/jython/Lib/test/test_jy_internals.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_jy_internals.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -4,7 +4,7 @@ import gc import unittest import time -from test.test_support import run_suite +from test import test_support import java import jarray @@ -287,19 +287,7 @@ self.assertEquals(len(test.__dict__), 4) def test_main(): - test_suite = unittest.TestSuite() - test_loader = unittest.TestLoader() - def suite_add(case): - test_suite.addTest(test_loader.loadTestsFromTestCase(case)) - suite_add(WeakIdentityMapTests) - suite_add(LongAsScaledDoubleValueTests) - suite_add(ExtraMathTests) - suite_add(DatetimeTypeMappingTest) - suite_add(IdTest) - suite_add(FrameTest) - suite_add(ModuleTest) - suite_add(MemoryLeakTests) - run_suite(test_suite) + test_support.run_unittest(__name__) if __name__ == "__main__": test_main() Modified: trunk/jython/Lib/test/test_optparse.py =================================================================== --- trunk/jython/Lib/test/test_optparse.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_optparse.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -5,10 +5,9 @@ # (tar...@so...) -- translated from the original Optik # test suite to this PyUnit-based version. # -# $Id: test_optparse.py 50791 2006-07-23 16:05:51Z greg.ward $ +# $Id: test_optparse.py 83540 2010-08-02 18:40:55Z ezio.melotti $ # -import __builtin__ import sys import os import re @@ -17,7 +16,6 @@ import unittest from StringIO import StringIO -from pprint import pprint from test import test_support @@ -28,12 +26,6 @@ from optparse import _match_abbrev from optparse import _parse_num -# Do the right thing with boolean values for all known Python versions. -try: - True, False -except NameError: - (True, False) = (1, 0) - retype = type(re.compile('')) class InterceptedError(Exception): @@ -461,7 +453,7 @@ return int(value) else: return int(value[:-1]) * _time_units[value[-1]] - except ValueError, IndexError: + except (ValueError, IndexError): raise OptionValueError( 'option %s: invalid duration: %r' % (opt, value)) @@ -774,6 +766,11 @@ {'a': "-b3", 'boo': None, 'foo': None}, []) + def test_combined_single_invalid_option(self): + self.parser.add_option("-t", action="store_true") + self.assertParseFail(["-test"], + "no such option: -e") + class TestBool(BaseTest): def setUp(self): options = [make_option("-v", @@ -796,15 +793,13 @@ (options, args) = self.assertParseOK(["-q"], {'verbose': 0}, []) - if hasattr(__builtin__, 'False'): - self.failUnless(options.verbose is False) + self.assertTrue(options.verbose is False) def test_bool_true(self): (options, args) = self.assertParseOK(["-v"], {'verbose': 1}, []) - if hasattr(__builtin__, 'True'): - self.failUnless(options.verbose is True) + self.assertTrue(options.verbose is True) def test_bool_flicker_on_and_off(self): self.assertParseOK(["-qvq", "-q", "-v"], @@ -1466,15 +1461,9 @@ # we must restore its original value -- otherwise, this test # screws things up for other tests when it's part of the Python # test suite. - orig_columns = os.environ.get('COLUMNS') - os.environ['COLUMNS'] = str(columns) - try: + with test_support.EnvironmentVarGuard() as env: + env.set('COLUMNS', str(columns)) return InterceptingOptionParser(option_list=options) - finally: - if orig_columns is None: - del os.environ['COLUMNS'] - else: - os.environ['COLUMNS'] = orig_columns def assertHelpEquals(self, expected_output): if type(expected_output) is types.UnicodeType: @@ -1501,8 +1490,10 @@ self.assertHelpEquals(_expected_help_long_opts_first) def test_help_title_formatter(self): - self.parser.formatter = TitledHelpFormatter() - self.assertHelpEquals(_expected_help_title_formatter) + with test_support.EnvironmentVarGuard() as env: + env.set("COLUMNS", "80") + self.parser.formatter = TitledHelpFormatter() + self.assertHelpEquals(_expected_help_title_formatter) def test_wrap_columns(self): # Ensure that wrapping respects $COLUMNS environment variable. @@ -1624,21 +1615,11 @@ "option -l: invalid long integer value: '0x12x'") -def _testclasses(): - mod = sys.modules[__name__] - return [getattr(mod, name) for name in dir(mod) if name.startswith('Test')] - -def suite(): - if test_support.is_jython: - # XXX: CPython ref count specific test +def test_main(): + is_jython = sys.platform.startswith("java") + if is_jython: del TestOptionParser.test_refleak - suite = unittest.TestSuite() - for testclass in _testclasses(): - suite.addTest(unittest.makeSuite(testclass)) - return suite + test_support.run_unittest(__name__) -def test_main(): - test_support.run_suite(suite()) - if __name__ == '__main__': test_main() Modified: trunk/jython/Lib/test/test_pulldom.py =================================================================== --- trunk/jython/Lib/test/test_pulldom.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_pulldom.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -79,11 +79,7 @@ self.fail("Unexpected exception joining comment data pieces: %s" % str(x)) def test_main(): - tests = [ - UnicodeTests, - ] - suites = [unittest.makeSuite(klass, 'test') for klass in tests] - test_support.run_suite(unittest.TestSuite(suites)) + test_support.run_unittest(__name__) if __name__ == "__main__": test_main() Modified: trunk/jython/Lib/test/test_scope.py =================================================================== --- trunk/jython/Lib/test/test_scope.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_scope.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -1,4 +1,4 @@ -from test.test_support import verify, TestFailed, check_syntax, vereq, is_jython +from test.test_support import verify, TestFailed, check_syntax_error, vereq, is_jython import warnings warnings.filterwarnings("ignore", r"import \*", SyntaxWarning, "<string>") @@ -180,7 +180,13 @@ print "11. unoptimized namespaces" -check_syntax("""\ +class FakeTestCase(object): + def fail(self): + raise TestFailed + +fake = FakeTestCase() + +check_syntax_error(fake, """\ def unoptimized_clash1(strip): def f(s): from string import * @@ -188,7 +194,7 @@ return f """) -check_syntax("""\ +check_syntax_error(fake, """\ def unoptimized_clash2(): from string import * def f(s): @@ -196,7 +202,7 @@ return f """) -check_syntax("""\ +check_syntax_error(fake, """\ def unoptimized_clash2(): from string import * def g(): @@ -206,7 +212,7 @@ """) # XXX could allow this for exec with const argument, but what's the point -check_syntax("""\ +check_syntax_error(fake, """\ def error(y): exec "a = 1" def f(x): @@ -214,14 +220,14 @@ return f """) -check_syntax("""\ +check_syntax_error(fake, """\ def f(x): def g(): return x del x # can't del name """) -check_syntax("""\ +check_syntax_error(fake, """\ def f(): def g(): from string import * Modified: trunk/jython/Lib/test/test_select.py =================================================================== --- trunk/jython/Lib/test/test_select.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_select.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -222,16 +222,10 @@ p.close() def test_main(): - tests = [ - TestSelectInvalidParameters, - TestSelectClientSocket, - TestPollClientSocket, - ThreadedPollClientSocket, - ] - if sys.platform[:4] != 'java': - tests.append(TestPipes) - suites = [unittest.makeSuite(klass, 'test') for klass in tests] - test_support.run_suite(unittest.TestSuite(suites)) + if test_support.is_jython: + del TestPipes.test + test_support.run_unittest(__name__) + if __name__ == "__main__": test_main() Modified: trunk/jython/Lib/test/test_select_new.py =================================================================== --- trunk/jython/Lib/test/test_select_new.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_select_new.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -238,9 +238,7 @@ self.handler.verify_only_writable() def test_main(): - tests = [TestSelect, TestSelectOnAccept] - suites = [unittest.makeSuite(klass, 'test') for klass in tests] - test_support.run_suite(unittest.TestSuite(suites)) + test_support.run_unittest(__name__) if __name__ == "__main__": test_main() Modified: trunk/jython/Lib/test/test_socket.py =================================================================== --- trunk/jython/Lib/test/test_socket.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_socket.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -1856,7 +1856,7 @@ if False: tests.append(UDPBroadcastTest) suites = [unittest.makeSuite(klass, 'test') for klass in tests] - test_support.run_suite(unittest.TestSuite(suites)) + test_support._run_suite(unittest.TestSuite(suites)) if __name__ == "__main__": test_main() Modified: trunk/jython/Lib/test/test_support.py =================================================================== --- trunk/jython/Lib/test/test_support.py 2011-03-12 19:36:22 UTC (rev 7218) +++ trunk/jython/Lib/test/test_support.py 2011-03-12 20:11:47 UTC (rev 7219) @@ -207,10 +207,6 @@ on Windows), it will be set on the socket. This will prevent anyone else from bind()'ing to our host/port for the duration of the test. """ - - #XXX: This section is probably wrong as I (Frank Wierzbicki) don't really - # understand it, but I needed this to get the asynchat tests running - # again. if is_jython: # Find some random ports that hopefully no one is listening on. # Ideally each test would clean up after itself and not continue @@ -902,9 +898,7 @@ def threading_setup(): import threading - if is_jython: - return len(threading._active), 0 - return len(threading._active), len(threading._limbo) + return len(threading._active), 0 def threading_cleanup(num_active, num_limbo): import threading @@ -916,12 +910,6 @@ count += 1 time.sleep(0.1) - if not is_jython: - count = 0 - while len(threading._limbo) != num_limbo and count < _MAX_COUNT: - count += 1 - time.sleep(0.1) - def reap_children(): """Use this function at the end of test_main() whenever sub-processes are started. This will help ensure that no extra children (zombies) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2011-03-12 19:36:35
|
Revision: 7218 http://jython.svn.sourceforge.net/jython/?rev=7218&view=rev Author: fwierzbicki Date: 2011-03-12 19:36:22 +0000 (Sat, 12 Mar 2011) Log Message: ----------- First cut at Python.g grammar + associated fixes. The with statement is on by default. Passes test_grammar from Python 2.6. Modified Paths: -------------- trunk/jython/Lib/test/test_func_syntax_jy.py trunk/jython/grammar/Python.g trunk/jython/src/org/python/Version.java trunk/jython/src/org/python/antlr/GrammarActions.java trunk/jython/src/org/python/core/Options.java trunk/jython/src/org/python/core/Py.java trunk/jython/src/org/python/core/PySystemState.java trunk/jython/src/org/python/core/exceptions.java trunk/jython/src/org/python/indexer/Builtins.java Modified: trunk/jython/Lib/test/test_func_syntax_jy.py =================================================================== --- trunk/jython/Lib/test/test_func_syntax_jy.py 2011-03-12 19:30:30 UTC (rev 7217) +++ trunk/jython/Lib/test/test_func_syntax_jy.py 2011-03-12 19:36:22 UTC (rev 7218) @@ -10,7 +10,7 @@ "parrot(voltage=.5, \'dead\')") def test_dup_keywords(self): - self.assertRaises(TypeError, eval, + self.assertRaises(SyntaxError, eval, "complex(imag=4, imag=2)") def test_main(): Modified: trunk/jython/grammar/Python.g =================================================================== --- trunk/jython/grammar/Python.g 2011-03-12 19:30:30 UTC (rev 7217) +++ trunk/jython/grammar/Python.g 2011-03-12 19:36:22 UTC (rev 7218) @@ -991,12 +991,13 @@ : (AS | NAME) expr[expr_contextType.Store] { $etype = actions.castExpr($expr.tree); + actions.checkAssign($etype); } ; -//except_clause: 'except' [test [',' test]] +//except_clause: 'except' [test [('as' | ',') test]] except_clause - : EXCEPT (t1=test[expr_contextType.Load] (COMMA t2=test[expr_contextType.Store])?)? COLON suite[!$suite.isEmpty() && $suite::continueIllegal] + : EXCEPT (t1=test[expr_contextType.Load] ((COMMA | AS) t2=test[expr_contextType.Store])?)? COLON suite[!$suite.isEmpty() && $suite::continueIllegal] -> ^(EXCEPT<ExceptHandler>[$EXCEPT, actions.castExpr($t1.tree), actions.castExpr($t2.tree), actions.castStmts($suite.stypes)]) ; @@ -1639,7 +1640,9 @@ } ; -//arglist: (argument ',')* (argument [',']| '*' test [',' '**' test] | '**' test) +//arglist: (argument ',')* (argument [','] +// |'*' test (',' argument)* [',' '**' test] +// |'**' test) arglist returns [List args, List keywords, expr starargs, expr kwargs] @init { @@ -1647,9 +1650,9 @@ List kws = new ArrayList(); List gens = new ArrayList(); } - : argument[arguments, kws, gens, true] (COMMA argument[arguments, kws, gens, false])* + : argument[arguments, kws, gens, true, false] (COMMA argument[arguments, kws, gens, false, false])* (COMMA - ( STAR s=test[expr_contextType.Load] (COMMA DOUBLESTAR k=test[expr_contextType.Load])? + ( STAR s=test[expr_contextType.Load] (COMMA argument[arguments, kws, gens, false, true])* (COMMA DOUBLESTAR k=test[expr_contextType.Load])? | DOUBLESTAR k=test[expr_contextType.Load] )? )? @@ -1662,25 +1665,37 @@ $starargs=actions.castExpr($s.tree); $kwargs=actions.castExpr($k.tree); } - | STAR s=test[expr_contextType.Load] (COMMA DOUBLESTAR k=test[expr_contextType.Load])? + | STAR s=test[expr_contextType.Load] (COMMA argument[arguments, kws, gens, false, true])* (COMMA DOUBLESTAR k=test[expr_contextType.Load])? { $starargs=actions.castExpr($s.tree); - $kwargs=actions.castExpr($k.tree); + $keywords=kws; + $kwargs=actions.castExpr($k.tree); } | DOUBLESTAR k=test[expr_contextType.Load] { - $kwargs=actions.castExpr($k.tree); + $kwargs=actions.castExpr($k.tree); } ; //argument: test [gen_for] | test '=' test # Really [keyword '='] test argument - [List arguments, List kws, List gens, boolean first] returns [boolean genarg] + [List arguments, List kws, List gens, boolean first, boolean afterStar] returns [boolean genarg] : t1=test[expr_contextType.Load] ((ASSIGN t2=test[expr_contextType.Load]) { + expr newkey = actions.castExpr($t1.tree); + //Loop through all current keys and fail on duplicate. + for(Object o: $kws) { + List list = (List)o; + Object oldkey = list.get(0); + if (oldkey instanceof Name && newkey instanceof Name) { + if (((Name)oldkey).getId().equals(((Name)newkey).getId())) { + errorHandler.error("keyword arguments repeated", $t1.tree); + } + } + } List<expr> exprs = new ArrayList<expr>(); - exprs.add(actions.castExpr($t1.tree)); + exprs.add(newkey); exprs.add(actions.castExpr($t2.tree)); $kws.add(exprs); } @@ -1698,6 +1713,8 @@ { if (kws.size() > 0) { errorHandler.error("non-keyword arg after keyword arg", $t1.tree); + } else if (afterStar) { + errorHandler.error("only named arguments may follow *expression", $t1.tree); } $arguments.add($t1.tree); } @@ -1905,9 +1922,13 @@ INT : // Hex '0' ('x' | 'X') ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' )+ | // Octal - '0' ( '0' .. '7' )* - | '1'..'9' DIGITS* - ; + '0' ('o' | 'O') ( '0' .. '7' )* + | '0' ( '0' .. '7' )* + | // Binary + '0' ('b' | 'B') ( '0' .. '1' )* + | // Decimal + '1'..'9' DIGITS* +; COMPLEX : DIGITS+ ('j'|'J') @@ -1925,7 +1946,7 @@ * should make us exit loop not continue. */ STRING - : ('r'|'u'|'ur'|'R'|'U'|'UR'|'uR'|'Ur')? + : ('r'|'u'|'b'|'ur'|'R'|'U'|'B'|'UR'|'uR'|'Ur')? ( '\'\'\'' (options {greedy=false;}:TRIAPOS)* '\'\'\'' | '"""' (options {greedy=false;}:TRIQUOTE)* '"""' | '"' (ESC|~('\\'|'\n'|'"'))* '"' Modified: trunk/jython/src/org/python/Version.java =================================================================== --- trunk/jython/src/org/python/Version.java 2011-03-12 19:30:30 UTC (rev 7217) +++ trunk/jython/src/org/python/Version.java 2011-03-12 19:36:22 UTC (rev 7218) @@ -44,7 +44,7 @@ /** The flags that are set by default in a code object. */ private static final Collection<CodeFlag> defaultCodeFlags = Arrays.asList( - CodeFlag.CO_NESTED, CodeFlag.CO_GENERATOR_ALLOWED); + CodeFlag.CO_NESTED, CodeFlag.CO_GENERATOR_ALLOWED, CodeFlag.CO_FUTURE_WITH_STATEMENT); private static final String headURL = "$HeadURL$"; Modified: trunk/jython/src/org/python/antlr/GrammarActions.java =================================================================== --- trunk/jython/src/org/python/antlr/GrammarActions.java 2011-03-12 19:30:30 UTC (rev 7217) +++ trunk/jython/src/org/python/antlr/GrammarActions.java 2011-03-12 19:36:22 UTC (rev 7218) @@ -347,20 +347,22 @@ } List<keyword> makeKeywords(List args) { - List<keyword> k = new ArrayList<keyword>(); + List<keyword> keywords = new ArrayList<keyword>(); if (args != null) { - for(int i=0;i<args.size();i++) { - List e = (List)args.get(i); - checkAssign(castExpr(e.get(0))); - if (e.get(0) instanceof Name) { - Name arg = (Name)e.get(0); - k.add(new keyword(arg, arg.getInternalId(), castExpr(e.get(1)))); + for (Object o : args) { + List e = (List)o; + Object k = e.get(0); + Object v = e.get(1); + checkAssign(castExpr(k)); + if (k instanceof Name) { + Name arg = (Name)k; + keywords.add(new keyword(arg, arg.getInternalId(), castExpr(v))); } else { - errorHandler.error("keyword must be a name", (PythonTree)e.get(0)); + errorHandler.error("keyword must be a name", (PythonTree)k); } } } - return k; + return keywords; } Object makeFloat(Token t) { @@ -373,12 +375,21 @@ return Py.newImaginary(Double.valueOf(s)); } + //XXX: needs to handle NumberFormatException (on input like 0b2) and needs + // a better long guard than ndigits > 11 (this is much to short for + // binary for example) Object makeInt(Token t) { String s = t.getText(); int radix = 10; if (s.startsWith("0x") || s.startsWith("0X")) { radix = 16; s = s.substring(2, s.length()); + } else if (s.startsWith("0o") || s.startsWith("0O")) { + radix = 8; + s = s.substring(2, s.length()); + } else if (s.startsWith("0b") || s.startsWith("0B")) { + radix = 2; + s = s.substring(2, s.length()); } else if (s.startsWith("0")) { radix = 8; } Modified: trunk/jython/src/org/python/core/Options.java =================================================================== --- trunk/jython/src/org/python/core/Options.java 2011-03-12 19:30:30 UTC (rev 7217) +++ trunk/jython/src/org/python/core/Options.java 2011-03-12 19:36:22 UTC (rev 7218) @@ -75,7 +75,11 @@ /** Force stdin, stdout and stderr to be unbuffered, and opened in * binary mode */ public static boolean unbuffered = false; + + //XXX: place holder + public static int bytes_warning = 0; + /** * Enable division warning. The value maps to the registry values of * <ul> Modified: trunk/jython/src/org/python/core/Py.java =================================================================== --- trunk/jython/src/org/python/core/Py.java 2011-03-12 19:30:30 UTC (rev 7217) +++ trunk/jython/src/org/python/core/Py.java 2011-03-12 19:36:22 UTC (rev 7218) @@ -402,6 +402,11 @@ public static void UnicodeWarning(String message) { warning(UnicodeWarning, message); } + + public static PyObject BytesWarning; + public static void BytesWarning(String message) { + warning(BytesWarning, message); + } private static PyObject warnings_mod; @@ -775,6 +780,7 @@ FutureWarning = initExc("FutureWarning", exc, dict); ImportWarning = initExc("ImportWarning", exc, dict); UnicodeWarning = initExc("UnicodeWarning", exc, dict); + BytesWarning = initExc("BytesWarning", exc, dict); // Pre-initialize the PyJavaClass for OutOfMemoryError so when we need // it it creating the pieces for it won't cause an additional out of Modified: trunk/jython/src/org/python/core/PySystemState.java =================================================================== --- trunk/jython/src/org/python/core/PySystemState.java 2011-03-12 19:30:30 UTC (rev 7217) +++ trunk/jython/src/org/python/core/PySystemState.java 2011-03-12 19:36:22 UTC (rev 7218) @@ -65,6 +65,16 @@ public static PyTuple version_info; public final static int maxunicode = 1114111; + + //XXX: we should someday make this Long.MAX_VALUE, but see test_index.py + // for tests that would need to pass but today would not. + public final static int maxsize = Integer.MAX_VALUE; + + //XXX: place holder + public final static boolean py3kwarning = false; + + public final static Class flags = Options.class; + public static PyTuple subversion; /** * The copyright notice for this release. Modified: trunk/jython/src/org/python/core/exceptions.java =================================================================== --- trunk/jython/src/org/python/core/exceptions.java 2011-03-12 19:30:30 UTC (rev 7217) +++ trunk/jython/src/org/python/core/exceptions.java 2011-03-12 19:36:22 UTC (rev 7218) @@ -166,6 +166,10 @@ buildClass(dict, "UnicodeWarning", "Warning", "Base class for warnings about Unicode related problems, mostly\n" + "related to conversion problems."); + + buildClass(dict, "BytesWarning", "Warning", + "Base class for warnings about bytes and buffer related problems, mostly\n" + + "related to conversion from str or comparing to str."); // Initialize ZipImportError here, where it's safe to; it's // needed immediately Modified: trunk/jython/src/org/python/indexer/Builtins.java =================================================================== --- trunk/jython/src/org/python/indexer/Builtins.java 2011-03-12 19:30:30 UTC (rev 7217) +++ trunk/jython/src/org/python/indexer/Builtins.java 2011-03-12 19:36:22 UTC (rev 7218) @@ -99,8 +99,8 @@ Scope moduleTable; String[] builtin_exception_types = { - "ArithmeticError", "AssertionError", "AttributeError", - "BaseException", "Exception", "DeprecationWarning", "EOFError", + "ArithmeticError", "AssertionError", "AttributeError", "BaseException", + "BytesWarning", "Exception", "DeprecationWarning", "EOFError", "EnvironmentError", "FloatingPointError", "FutureWarning", "GeneratorExit", "IOError", "ImportError", "ImportWarning", "IndentationError", "IndexError", "KeyError", "KeyboardInterrupt", @@ -108,11 +108,10 @@ "NotImplementedError", "OSError", "OverflowError", "PendingDeprecationWarning", "ReferenceError", "RuntimeError", "RuntimeWarning", "StandardError", "StopIteration", "SyntaxError", - "SyntaxWarning", "SystemError", "SystemExit", "TabError", - "TypeError", "UnboundLocalError", "UnicodeDecodeError", - "UnicodeEncodeError", "UnicodeError", "UnicodeTranslateError", - "UnicodeWarning", "UserWarning", "ValueError", "Warning", - "ZeroDivisionError" + "SyntaxWarning", "SystemError", "SystemExit", "TabError", "TypeError", + "UnboundLocalError", "UnicodeDecodeError", "UnicodeEncodeError", + "UnicodeError", "UnicodeTranslateError", "UnicodeWarning", + "UserWarning", "ValueError", "Warning", "ZeroDivisionError" }; Set<NType> nativeTypes = new HashSet<NType>(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |