PK'ƒ5^>ÝÃ#Ã#testoob/testing.pyc;ò ßEc @s¤dZdZdefd„ƒYZed„Zd„Zed„Zeed„Zeed„Z d „Z d „Z eeeeeeeed „Z d d „Z dS(sUseful testing fuctions.isTestoobAssertionErrorcBs tZeed„Zd„ZRS(NcCs/ti||ƒ||_||_||_dS(N(sAssertionErrors__init__sselfsmessages long_messages description(sselfsmessages long_messages description((s-build/bdist.linux-i686/egg/testoob/testing.pys__init__s  cCs€g}|itj o|id|iƒn|i|iƒ|itj o!|idƒ|i|iƒndi|ƒSdS(Ns[%s]s----- long message -----s (sresultsselfs descriptionsNonesappendsmessages long_messagesjoin(sselfsresult((s-build/bdist.linux-i686/egg/testoob/testing.pys__str__s (s__name__s __module__sNones__init__s__str__(((s-build/bdist.linux-i686/egg/testoob/testing.pysTestoobAssertionErrorscCs‡ydkl}l}Wn&tj odkl}l}nX||d|d|d|ƒ}|i|ƒ\}}|||i fSdS(s_run_command(args, input=None) -> stdoutstring, stderrstring, returncode Runs the command, giving the input if any. The command is specified as a list: 'ls -l' would be sent as ['ls', '-l']. Returns the standard output and error as strings, and the return code(sPopensPIPEsstdinsstdoutsstderrN( s subprocesssPopensPIPEs ImportErrorscompatibility.subprocesssargssps communicatesinputsstdoutsstderrs returncode(sargssinputsstdoutsPopensPIPEspsstderr((s-build/bdist.linux-i686/egg/testoob/testing.pys _run_command%scCs dk}|idd|ƒSdS(Ns (\r\n|\r|\n)s (sressubsstring(sstringsre((s-build/bdist.linux-i686/egg/testoob/testing.pys_normalize_newlines4s cCs<|odSn|tjo d}nt|ddƒ‚dS(Nscondition not trues descriptionsassert_true failed(s conditionsmsgsNonesTestoobAssertionError(s conditionsmsg((s-build/bdist.linux-i686/egg/testoob/testing.pys assert_true8s   cCsi|tj o||ƒ}n||jodSn|tjod||f}nt|ddƒ‚dS(s)works like unittest.TestCase.assertEqualsNs%s != %ss descriptionsassert_equals failed(sfiltersNonesactualsexpectedsmsgsTestoobAssertionError(sexpectedsactualsmsgsfilter((s-build/bdist.linux-i686/egg/testoob/testing.pys assert_equals>s   cCsdk}|tj o||ƒ}n|i|||iƒtj odSn|tjodtƒ}nt |ddƒ‚dS(s2fail unless regex matches actual (using re.search)Ns9'%(actual)s' doesn't match regular expression '%(regex)s's descriptionsassert_matches failed( sresfiltersNonesactualssearchsregexsDOTALLsmsgsvarssTestoobAssertionError(sregexsactualsmsgsfiltersre((s-build/bdist.linux-i686/egg/testoob/testing.pysassert_matchesHs   cOszgi}|D]}|t|ƒƒq~gi}|iƒD]}|d|ƒq>~}d|i di |ƒfSdS(s‚ Generate a human-friendly call signature From recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307970 s%s=%rs%s(%s)s, N( sappends_[1]sargssargsreprskwargssitemssxsargvscallables__name__sjoin(scallablesargsskwargss_[1]sargvsargsx((s-build/bdist.linux-i686/egg/testoob/testing.pys_call_signatureTs\c s_dkl}|ˆdtƒ}|ˆdtƒ} ‡‡‡d†}‡d†}yˆˆˆŽWn߈j o} |tj o3t || i dd|ƒ| i || i fƒn| tj o9t| t| ƒdd|ƒ| i | t| ƒfƒq[n_d k}d |ƒ|ƒ|iƒd f} t| d d ƒ‚nXtd|ƒd d ƒ‚d S(sÎ Assert that a callable raises an exception, similar to unittest.py's assertRaises. Takes more ideas and code from recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307970 (s_pops expected_argssexpected_regexcstˆˆˆŽSdS(N(s_call_signaturescallablesargsskwargs((scallableskwargssargs(s-build/bdist.linux-i686/egg/testoob/testing.pyscallsigiscstˆdtˆƒƒSdS(Ns__name__(sgetattrsexception_classsstr((sexception_class(s-build/bdist.linux-i686/egg/testoob/testing.pysexc_namekssmsgs9%s raised %s with unexpected args: expected=%r, actual=%rs>%s raised %s, but the regular expression '%s' doesn't match %rNs>%s raised an unexpected exception type: expected=%s, actual=%sis descriptionsassert_raises faileds %s not raised(s testoob.utilss_popskwargssNones expected_argssexpected_regexscallsigsexc_namescallablesargssexception_classses assert_equalss __class__sassert_matchessstrssyssexc_infosmessagesTestoobAssertionError( sexception_classscallablesargsskwargsscallsigssyssexc_names expected_argss_popsexpected_regexsesmessage((sexception_classscallablesargsskwargss-build/bdist.linux-i686/egg/testoob/testing.pys assert_raises]s(    ' . #c Cs£t||ƒ\}} } |tj o1||| | ƒ} | tj ot | ƒqVnyÓ|tj ot || dt ƒn|tj ot ||dt ƒn|tj ot||dt ƒn|tj ot|| dt ƒn|tj ot || ƒn|tj ot|| ƒƒnWnstj og} | itjpt‚d„} didd|d| | d|ƒ| d| ƒgƒ| _‚nXd S( s  @param skip_check: a callable that will be called with 3 parameters - output, error, and rc - before any asserts are made. If it doesn't return None, the test will skip and the callable's return value will be used as the skip reason. sfiltercCsZ| o d|Sndk}|id|iƒ}|id||ƒ}d||fSdS(Ns == %s: NONEs^s%s: s== %s %s(svaluesnamesrescompiles MULTILINEsannotation_patternssubsannotated_value(snamesvaluesresannotation_patternsannotated_value((s-build/bdist.linux-i686/egg/testoob/testing.pysannotated_err_string­s   s scommand_line test faileds == args: %ss == rc: %ssstdoutsstderrN(s _run_commandsargssinputsoutputserrorsrcs skip_checksNones skip_reasonsskipsexpected_errors assert_equalss_normalize_newlinessexpected_outputsexpected_output_regexsassert_matchessexpected_error_regexs expected_rcs rc_predicates assert_truesTestoobAssertionErrorses long_messagesAssertionErrorsannotated_err_stringsjoin(sargssinputsexpected_outputsexpected_errorsexpected_output_regexsexpected_error_regexs expected_rcs rc_predicates skip_checksrcsannotated_err_stringses skip_reasonserrorsoutput((s-build/bdist.linux-i686/egg/testoob/testing.pys command_lineƒs0         ;sNo reason givencCsdkl}||ƒ‚dS(sSkip this test(sSkipTestExceptionN(stestoobsSkipTestExceptionsreason(sreasonsSkipTestException((s-build/bdist.linux-i686/egg/testoob/testing.pysskip¼s N(s__doc__s __unittestsAssertionErrorsTestoobAssertionErrorsNones _run_commands_normalize_newliness assert_trues assert_equalssassert_matchess_call_signatures assert_raisess command_linesskip( s assert_equalss __unittestsskips assert_raisess command_lines assert_trues _run_commandsTestoobAssertionErrors_call_signaturesassert_matchess_normalize_newlines((s-build/bdist.linux-i686/egg/testoob/testing.pys?s     &!9PKMqƒ5·b]  testoob/asserter.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Help hook into asserts, for verbose asserts" import sys class Asserter: # Singleton __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state # initialize _reporter only if it's the first time the ctor is called. if not self.__shared_state: self._reporters = {} def _import(self, package_name, class_name): return getattr(__import__(package_name), class_name) def _make_assert_report(self, Class, method_name): # Prevent recursion (accures in testoob tests, when ran with testoob :-) ). if getattr(Class, method_name).__name__ == "_assert_reporting_func": return variables = eval("Class.%s" % method_name).func_code.co_varnames setattr(Class, "_real_function_%s" % method_name, eval("Class.%s" % method_name)) method = eval("Class._real_function_%s" % method_name) def _assert_reporting_func(*args, **kwargs): num_free_args = len(variables) additional_args = () if kwargs: num_free_args -= 1 additional_args = (kwargs,) if len(args) > num_free_args: num_free_args -= 1 additional_args = args[num_free_args:] + additional_args # Can't be a dictionary, because the order matters. varList = zip(variables[1:], (args[1:num_free_args] + additional_args)) # Here is some evil did to find the function which called me. test = sys._getframe().f_back.f_locals["self"] # If we run something that has no reporter, it should just run # (happens in testing of testoob with testoob). if not self._reporters.get(test): return method(*args, **kwargs) try: method(*args, **kwargs) except Exception, e: self._reporters[test].addAssert(test, method_name, varList, e) raise self._reporters[test].addAssert(test, method_name, varList, None) setattr(Class, method_name, _assert_reporting_func) def set_reporter(self, test, reporter): self._reporters[test] = reporter def make_asserts_report(self, module_name, class_name, methods_pattern): Class = self._import(module_name, class_name) from re import match for method_name in dir(Class): if match(methods_pattern, method_name): self._make_assert_report(Class, method_name) def register_asserter(): Asserter().make_asserts_report("unittest", "TestCase", "(^assert)|(^fail[A-Z])|(^fail$)") Asserter().make_asserts_report("testoob", "testing", "^assert") PKšá4  lŠ  testoob/profiling.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Profiling support code" MAX_PROFILING_LINES_TO_PRINT = 30 def _helper_class(profiler_name): if profiler_name == "hotshot": return HotshotHelper if profiler_name == "profile": return ProfileHelper assert False # should never reach here def profiling_decorator(profiler_name, filename): def decorator(callable): def wrapper(*args, **kwargs): helper = _helper_class(profiler_name)(filename, callable, *args, **kwargs) print "Profiling information saved to file '%s'" % helper.filename helper.run() helper.print_stats(MAX_PROFILING_LINES_TO_PRINT) return helper.result return wrapper return decorator class ProfilingHelper(object): def __init__(self, filename, callable, *args, **kwargs): self.filename = filename self.callable = callable self.args = args self.kwargs = kwargs self.result = None def print_stats(self, *args): self.stats().sort_stats("time").print_stats(*args) def run(self): raise NotImplementedError def stats(self): raise NotImplementedError class HotshotHelper(ProfilingHelper): def run(self): import hotshot p = hotshot.Profile(self.filename) try: self.result = p.runcall(self.callable, *self.args, **self.kwargs) finally: p.close() def stats(self): from hotshot import stats try: return stats.load(self.filename) except hotshot.ProfilerError: raise IOError("Error reading stats from '%s', file may be corrupt" % filename) class ProfileHelper(ProfilingHelper): def run(self): def run_callable(): "A local function we can refer to in a string with profile.run" self.result = self.callable(*self.args, **self.kwargs) try: from cProfile import Profile except ImportError: from profile import Profile self.p = Profile().runctx("run_callable()", globals(), locals()) self.p.dump_stats(self.filename) def stats(self): import pstats return pstats.Stats(self.p) PK'ƒ5 ÙrJJtestoob/test_loaders.pyc;ò ÍŸ¦Dc@sXdZdkZdeifd„ƒYZdefd„ƒYZdefd„ƒYZdS(sSpecial test loadersNsCustomMethodNameLoadercBs tZdZd„Zd„ZRS(s&Load test methods based on a predicatecOs1ttidƒotii|||ŽndS(Ns__init__(shasattrsunittests TestLoaders__init__sselfsargsskwargs(sselfsargsskwargs((s2build/bdist.linux-i686/egg/testoob/test_loaders.pys__init__scs–‡‡d†}t|tˆƒƒ}xIˆiD]>}x5ˆi|ƒD]$}||jo|i |ƒqDqDWq.Wˆi o|i ˆi ƒn|SdS(s.Return the method names matching the predicatecs@ˆi|ƒ otSnttˆ|ƒƒ otSntSdS(N(sselfs_testNamePredicatesnamesFalsescallablesgetattrs testCaseClasssTrue(sname(sselfs testCaseClass(s2build/bdist.linux-i686/egg/testoob/test_loaders.pys isTestMethod s N( s isTestMethodsfiltersdirs testCaseClasss testFnNamess __bases__s baseclasssselfsgetTestCaseNamess testFnNamesappendssortTestMethodsUsingssort(sselfs testCaseClasss isTestMethods testFnNames testFnNamess baseclass((sselfs testCaseClasss2build/bdist.linux-i686/egg/testoob/test_loaders.pysgetTestCaseNamess   (s__name__s __module__s__doc__s__init__sgetTestCaseNames(((s2build/bdist.linux-i686/egg/testoob/test_loaders.pysCustomMethodNameLoaders  s RegexLoadercBs tZdZd„Zd„ZRS(s1Load test methods matching the regular expressioncCs,ti|ƒdk}|i|ƒ|_dS(N(sCustomMethodNameLoaders__init__sselfsrescompilesregexspattern(sselfsregexsre((s2build/bdist.linux-i686/egg/testoob/test_loaders.pys__init__/s  cCs|ii|ƒtj SdS(N(sselfspatternssearchsnamesNone(sselfsname((s2build/bdist.linux-i686/egg/testoob/test_loaders.pys_testNamePredicate4s(s__name__s __module__s__doc__s__init__s_testNamePredicate(((s2build/bdist.linux-i686/egg/testoob/test_loaders.pys RegexLoader-s  s GlobLoadercBs tZdZd„Zd„ZRS(s+Load test methods matching the glob patterncCsti|ƒ||_dS(N(sCustomMethodNameLoaders__init__sselfspattern(sselfspattern((s2build/bdist.linux-i686/egg/testoob/test_loaders.pys__init__9s cCs dk}|i||iƒSdS(N(sfnmatchsnamesselfspattern(sselfsnamesfnmatch((s2build/bdist.linux-i686/egg/testoob/test_loaders.pys_testNamePredicate=s (s__name__s __module__s__doc__s__init__s_testNamePredicate(((s2build/bdist.linux-i686/egg/testoob/test_loaders.pys GlobLoader7s  (s__doc__sunittests TestLoadersCustomMethodNameLoaders RegexLoaders GlobLoader(sunittestsCustomMethodNameLoaders GlobLoaders RegexLoader((s2build/bdist.linux-i686/egg/testoob/test_loaders.pys?s  PK„*5° ûÆÆtestoob/testing.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Useful testing fuctions." __unittest=1 class TestoobAssertionError(AssertionError): def __init__(self, message, long_message=None, description=None): AssertionError.__init__(self, message) self.message = message self.long_message = long_message self.description = description def __str__(self): result = [] if self.description is not None: result.append( "[%s]" % self.description ) result.append( self.message ) if self.long_message is not None: result.append( "----- long message -----" ) result.append(self.long_message) return "\n".join(result) def _run_command(args, input=None): """_run_command(args, input=None) -> stdoutstring, stderrstring, returncode Runs the command, giving the input if any. The command is specified as a list: 'ls -l' would be sent as ['ls', '-l']. Returns the standard output and error as strings, and the return code""" try: from subprocess import Popen, PIPE except ImportError: # Python 2.2 and 2.3 compatibility from compatibility.subprocess import Popen, PIPE p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate(input) return stdout, stderr, p.returncode def _normalize_newlines(string): import re return re.sub(r'(\r\n|\r|\n)', '\n', string) def assert_true(condition, msg=None): if condition: return if msg is None: msg = "condition not true" raise TestoobAssertionError(msg, description="assert_true failed") def assert_equals(expected, actual, msg=None, filter=None): "works like unittest.TestCase.assertEquals" if filter is not None: actual = filter(actual) if expected == actual: return if msg is None: msg = '%s != %s' % (expected, actual) raise TestoobAssertionError(msg, description="assert_equals failed") def assert_matches(regex, actual, msg=None, filter=None): "fail unless regex matches actual (using re.search)" import re if filter is not None: actual = filter(actual) if re.search(regex, actual, re.DOTALL) is not None: return if msg is None: msg = "'%(actual)s' doesn't match regular expression '%(regex)s'" % vars() raise TestoobAssertionError(msg, description="assert_matches failed") def _call_signature(callable, *args, **kwargs): """ Generate a human-friendly call signature From recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307970 """ argv = [repr(arg) for arg in args] + ["%s=%r" % x for x in kwargs.items()] return "%s(%s)" % (callable.__name__, ", ".join(argv)) def assert_raises(exception_class, callable, *args, **kwargs): """ Assert that a callable raises an exception, similar to unittest.py's assertRaises. Takes more ideas and code from recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307970 """ from testoob.utils import _pop expected_args = _pop(kwargs, "expected_args", None) expected_regex = _pop(kwargs, "expected_regex", None) def callsig(): return _call_signature(callable, *args, **kwargs) def exc_name(): return getattr(exception_class, "__name__", str(exception_class)) try: callable(*args, **kwargs) except exception_class, e: if expected_args is not None: assert_equals( expected_args, e.args, msg="%s raised %s with unexpected args: expected=%r, actual=%r" % (callsig(), e.__class__, expected_args, e.args) ) if expected_regex is not None: assert_matches( expected_regex, str(e), msg="%s raised %s, but the regular expression '%s' doesn't match %r" % (callsig(), e.__class__, expected_regex, str(e)) ) except: import sys message = "%s raised an unexpected exception type: expected=%s, actual=%s" % (callsig(), exc_name(), sys.exc_info()[0]) raise TestoobAssertionError(message, description="assert_raises failed") else: raise TestoobAssertionError( "%s not raised" % exc_name(), description="assert_raises failed") def command_line( args, input=None, expected_output=None, expected_error=None, expected_output_regex=None, expected_error_regex=None, expected_rc=None, rc_predicate=None, skip_check=None, ): """ @param skip_check: a callable that will be called with 3 parameters - output, error, and rc - before any asserts are made. If it doesn't return None, the test will skip and the callable's return value will be used as the skip reason. """ # run command output, error, rc = _run_command(args, input) if skip_check is not None: skip_reason = skip_check(output, error, rc) if skip_reason is not None: skip(skip_reason) # test try: if expected_error is not None: assert_equals(expected_error, error, filter=_normalize_newlines) if expected_output is not None: assert_equals(expected_output, output, filter=_normalize_newlines) if expected_output_regex is not None: assert_matches(expected_output_regex, output, filter=_normalize_newlines) if expected_error_regex is not None: assert_matches(expected_error_regex, error, filter=_normalize_newlines) if expected_rc is not None: assert_equals(expected_rc, rc) if rc_predicate is not None: assert_true(rc_predicate(rc)) except TestoobAssertionError, e: assert e.long_message is None def annotated_err_string(name, value): if not value: return "== %s: NONE" % name import re annotation_pattern = re.compile("^", re.MULTILINE) annotated_value = annotation_pattern.sub("%s: "%name, value) return "== %s\n%s" % (name, annotated_value) e.long_message = "\n".join([ "command_line test failed", "== args: %s" % args, "== rc: %s" % rc, annotated_err_string("stdout", output), annotated_err_string("stderr", error), ]) raise def skip(reason="No reason given"): "Skip this test" from testoob import SkipTestException raise SkipTestException(reason) PK'ƒ5¢›¡!testoob/coverage.pyc;ò ÍŸ¦Dc@sódZdkZdkZd„Zy dkZWn ej odklZnXyeWn%ej odk Z d„ZnXye WnGej o;ydk l Z WqÓej odk l Z qÓXnXd„Zdfd„ƒYZdS( sCode coverage moduleNcCstSdS(sIs coverage supported?N(sTrue(((s.build/bdist.linux-i686/egg/testoob/coverage.pys supporteds(stracecCstti|dƒS(Ni(sreducesoperatorsaddsseq(sseq((s.build/bdist.linux-i686/egg/testoob/coverage.pys"s(sSetcCs yt|dƒiƒ}Wn0tj o$}tid||fIJhSnX|idƒ o|d7}nt ||dƒ}t i |ƒ}t i||ƒSdS(sv A re-implementation of trace.find_executable_linenos working around compile's problems with missing EOLS srUs%Not printing coverage data for %r: %ss sexecN(sopensfilenamesreadsprogsIOErrorserrssyssstderrsendswithscompilescodestraces find_stringssstrss find_lines(sfilenamescodeserrsstrssprog((s.build/bdist.linux-i686/egg/testoob/coverage.pys_find_executable_linenos.s sCoveragecBsktZdZfd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z d „Z RS( s« Python code coverage module built specifically for checking code coverage in tests performed by Testoob. NOTE: This class depends on the 'trace' module. cCs1h|_ttii|ƒ|_ti|_dS(s initialize the code coverage module, gets list of directories and files which's coverage is not needed. N( sselfscoveragesmapsosspathsabspaths ignorepathsstracesmodname(sselfs ignorepaths((s.build/bdist.linux-i686/egg/testoob/coverage.pys__init__Is cOs6ti|iƒz|||ŽSWdtitƒXdS(so Runs the function with arguments and keyword arguments, and checks the code coverage. N(ssysssettracesselfs_tracersfuncsargsskwargssNone(sselfsfuncsargsskwargs((s.build/bdist.linux-i686/egg/testoob/coverage.pysrunfuncVs cCsAh}x0|iiƒD]\}}|i|ƒ||tgi}|iiƒD]}|||ƒƒq~ƒSdS(s(Helper method for _total_{lines,covered}N(ssumsappends_[1]sselfscoveragesvaluesscallable(sselfscallables_[1]scoverage((s.build/bdist.linux-i686/egg/testoob/coverage.pys _sum_coveragescCs|id„ƒSdS(NcCst|dƒS(Nslines(slenscoverage(scoverage((s.build/bdist.linux-i686/egg/testoob/coverage.pys†s(sselfs _sum_coverage(sself((s.build/bdist.linux-i686/egg/testoob/coverage.pys total_lines…scCs|id„ƒSdS(NcCst|dƒS(Nscovered(slenscoverage(scoverage((s.build/bdist.linux-i686/egg/testoob/coverage.pysˆs(sselfs _sum_coverage(sself((s.build/bdist.linux-i686/egg/testoob/coverage.pystotal_lines_covered‡scCs=|iƒdjodSntd|iƒ|iƒƒSdS(Niid(sselfs total_linessintstotal_lines_covered(sself((s.build/bdist.linux-i686/egg/testoob/coverage.pystotal_coverage_percentage‰scCsÕtii|iiƒ}|i}x)|i D]}|i |ƒot Sq+q+W|i dƒp |i dƒ ot Sn|ii|ƒ o2hdtt|ƒƒ<dtƒ<|i|>sys.stderr, "ERROR: Can't find test case '%s'" % testName(e) sys.exit(1) from commandline.parsing import ArgumentsError def _main(suite, defaultTest, options, test_names, parser): from commandline.parsing import require_posix, require_modules def conflicting_options(*option_names): given_options = [ name for name in option_names if getattr(options, name) is not None ] given_options.sort() if len(given_options) > 1: raise ArgumentsError( "The following options can't be specified together: %s" % ", ".join(given_options)) conflicting_options("threads", "timeout") conflicting_options("timeout", "timeout_with_threads") conflicting_options("threads", "processes", "processes_old", "processes_pyro", "stop_on_fail") conflicting_options("threads", "processes", "processes_old", "processes_pyro", "list") # specify runners conflicting_options("processes", "processes_old", "processes_pyro", "debug") conflicting_options("capture", "list") commandline.parsing.kwargs = { "verbosity" : _get_verbosity(options), "stop_on_fail" : options.stop_on_fail, "reporters" : [], "extraction_decorators" : [], "fixture_decorators" : [], "interval" : options.interval, } kwargs = commandline.parsing.kwargs # TODO: convert to calls to commandline.parsing.kwargs for processor in commandline.parsing.option_processors: processor(options) def get_test_loader(): if options.test_method_regex is not None: from test_loaders import RegexLoader return RegexLoader(options.test_method_regex) if options.test_method_glob is not None: from test_loaders import GlobLoader return GlobLoader(options.test_method_glob) return None # use the default kwargs["suites"] = _get_suites( suite, defaultTest, test_names, test_loader=get_test_loader()) if options.coverage is not None: from running import fixture_decorators from coverage import Coverage import os # Ignore coverage from the 'testoob' library (where this file is), and # from the python system library (assuming 'os' module placed there). cov = Coverage(map(os.path.dirname, [__file__, os.__file__])) kwargs["fixture_decorators"].append( fixture_decorators.get_coverage_fixture(cov)) if options.coverage != "silent": kwargs["coverage"] = (options.coverage, cov) if options.capture is not None: from running import fixture_decorators kwargs["fixture_decorators"].append( fixture_decorators.get_capture_fixture()) if options.vassert: import asserter asserter.register_asserter() if options.timeout is not None: require_posix("--timeout") from running import fixture_decorators kwargs["fixture_decorators"].append( fixture_decorators.get_alarmed_fixture(options.timeout)) def alarm(sig, stack_frame): raise AssertionError("Timeout") import signal signal.signal(signal.SIGALRM, alarm) if options.timeout_with_threads is not None: import thread if not hasattr(thread, "interrupt_main"): raise ArgumentsError("Older versions of Python don't support thread.interrupt_main") from running import fixture_decorators kwargs["fixture_decorators"].append( fixture_decorators.get_thread_timingout_fixture(options.timeout_with_threads)) if options.rerun_on_fail is not None: if options.debug is None: raise ArgumentsError("--rerun-on-fail requires --debug") if options.debug is not None: import pdb def runDebug(test, err_info, flavour, reporter, real_add): if options.timeout is not None: from signal import alarm alarm(0) # Don't timeout on debug. assert flavour in ("error", "failure") real_add(test, err_info) print "\nDebugging for %s in test: %s" % ( flavour, reporter.getDescription(test)) if options.rerun_on_fail is not None: #test.funcname will be our current test function #use that to get the function object for our method #and call it manually. WD-rpw 10-31-06 methodName = test.funcname() method = getattr( test.fixture, methodName) print "rerunning test for failed %s()" % (methodName) try: pdb.runcall( method ) except: pdb.post_mortem( err_info.traceback() ) else: pdb.post_mortem(err_info.traceback()) kwargs["runDebug"] = runDebug if options.threads is not None: from running import ThreadedRunner kwargs["runner"] = ThreadedRunner(num_threads = options.threads) kwargs["threads"] = True if options.profiler is not None: # this module is sometimes missing, apparently its license is a problem # for some OS distributions require_modules("--profiler", "profile") def text_run_decorator(): if options.profiler is not None: import profiling return profiling.profiling_decorator( options.profiler, options.profdata) # return a null decorator return lambda x: x # apply the decorator to running.text_run import running return text_run_decorator()(running.text_run)(**kwargs) def kwarg_to_option(arg, value): cmdarg = arg.replace("_", "-") if value is True: return "--%s" % cmdarg else: return "--%s=%s" % (cmdarg, value) def _config_file_args(): filename = os.path.expanduser("~/.testoobrc") if not os.path.exists(filename): return [] # No config file import ConfigParser try: config = ConfigParser.ConfigParser() config.read(filename) result = [] for option in config.options("default"): value = config.get("default", option) if value.lower() in ("true", "false"): if value.lower() == "true": result.append("--%s" % option) else: result.append("--%s=%s" % (option, value)) return result except ConfigParser.Error, e: import warnings warnings.warn("Error reading config file: %s" % e) return [] def _parse_args(): args = _config_file_args() + sys.argv[1:] parser = _arg_parser() options, args = parser.parse_args(args) return parser, options, args def main(suite=None, defaultTest=None, **kwargs): import sys for arg, value in kwargs.items(): sys.argv.append(kwarg_to_option(arg, value)) parser, options, test_names = _parse_args() try: sys.exit(not _main(suite, defaultTest, options, test_names, parser)) except ArgumentsError, e: parser.error(str(e)) PK'ƒ5R´ÙãI/I/testoob/main.pyc;ò ÞZKEc@sÕdZdkZdkZyeWnGej o;ydklZWqjej odklZqjXnXdk Z d„Z d„Z e d„Z dklZd„Zd„Zd „Zd „Ze e d „ZdS( smain() implementationN(sSetc Cs tii}|iddddddƒ|idddddd ƒ|id dddd ƒ|id d dddddddƒ|idd dddddƒ|idd dddddƒ|idddddƒ|idddddƒ|idd dddddƒ|id dddd!ƒd"d#d$d%d&g}|id'd d(dd)d*|dd+|ƒ|id,d d-dd.ƒ|id/d d0dd1ƒd2d3g}|id4dd)d*|dd5|ƒ|id6d d7dd8dd9ƒ|id:dddd;ƒ|SdS(<Ns-qs--quietsactions store_trueshelpsMinimal outputs-vs --verbosesVerbose outputs --vassertsMake asserts verboses --intervalsmetavarsSECONDSstypesfloatsdefaultisAdd interval between testss --timeoutsintsFail test if passes timeouts--timeout-with-threadss5Fail test if passes timeout, implemented with threadss--stop-on-failsStop tests on first failures--debugsRun pdb on tests that fails --threadss NUM_THREADSsRun in a threadpools --captures>Capture the output of the test, and show it only if test failsssilentsslimsnormalsmassivesxmls --coveragesAMOUNTschoiceschoicess5Test the coverage of the tested code, choices are: %ss--test-method-globsPATTERNs,Collect test methods based on a glob patterns--test-method-regexsREGEXs2Collect test methods based on a regular expressionshotshotsprofiles --profilers2Profile the tests with a profiler, choices are: %ss --profdatasFILEs testoob.statss<Target file for profiling information, default is '%default's--rerun-on-fails9Used with --debug, rerun a failing test when debugging it(s commandlinesparsingsparsersps add_optionscoverage_choicessprofiler_choices(spsprofiler_choicesscoverage_choices((s*build/bdist.linux-i686/egg/testoob/main.pys _arg_parser s( %) #cCs>|iodSn|iodSn|iodSndSdS(Niiii(soptionssquietsvassertsverbose(soptions((s*build/bdist.linux-i686/egg/testoob/main.pys_get_verbosity8s   c s |tj o |gSn|tjodk}|iƒ}ndk}t|ƒdjo |tjo|i |ƒSnt|ƒdjo |g}nt |ƒ}y|i ||ƒSWnNt j oB‰‡d†}dk}|id|ˆƒIJ|idƒnXdS(NicsFdk}|idtˆƒƒ}|tj pt‚|idƒSdS(Nshas no attribute '([^']+)'i(sressearchsstrsesmosNonesAssertionErrorsgroup(s exceptionsmosre(se(s*build/bdist.linux-i686/egg/testoob/main.pystestNameUs s ERROR: Can't find test case '%s'i(ssuitesNones test_loadersunittests TestLoaders__main__slens test_namess defaultTestsloadTestsFromModulessetsloadTestsFromNamessAttributeErrorsestestNamessyssstderrsexit( ssuites defaultTests test_namess test_loadersesunitteststestNamessyss__main__((ses*build/bdist.linux-i686/egg/testoob/main.pys _get_suites>s$          (sArgumentsErrorcsðdkl}l}‡d†} | ddƒ| ddƒ| ddddd ƒ| ddddd ƒ| dddd ƒ| d d ƒhd tˆƒ<d ˆi<dg<dg<dg<dˆiˆitj o#dk}|iˆiˆiƒSnd„SdS(NcCs|S(N(sx(sx((s*build/bdist.linux-i686/egg/testoob/main.pysçs(soptionssprofilersNones profilingsprofiling_decoratorsprofdata(s profiling(soptions(s*build/bdist.linux-i686/egg/testoob/main.pystext_run_decoratoràs (8scommandline.parsings require_posixsrequire_modulessconflicting_optionss_get_verbositysoptionss stop_on_failsintervals commandlinesparsingskwargssoption_processorss processorsget_test_loaders _get_suitesssuites defaultTests test_namesscoveragesNonesrunningsfixture_decoratorssCoveragesossmapspathsdirnames__file__scovsappendsget_coverage_fixturescapturesget_capture_fixturesvassertsassertersregister_asserterstimeoutsget_alarmed_fixturesalarmssignalsSIGALRMstimeout_with_threadssthreadshasattrsArgumentsErrorsget_thread_timingout_fixtures rerun_on_failsdebugspdbsrunDebugsthreadssThreadedRunnersTruesprofilerstext_run_decoratorstext_run(ssuites defaultTestsoptionss test_namessparsersrequire_modulessasserterssignalsget_test_loadersfixture_decoratorssCoverageskwargssThreadedRunnersconflicting_optionssrunDebugsrunningspdbs require_posixsthreadscovsalarmstext_run_decoratorsoss processor((soptionsspdbs*build/bdist.linux-i686/egg/testoob/main.pys_main`st   N      $         !   cCs=|iddƒ}|tjo d|Snd||fSdS(Ns_s-s--%ss--%s=%s(sargsreplacescmdargsvaluesTrue(sargsvaluescmdarg((s*build/bdist.linux-i686/egg/testoob/main.pyskwarg_to_optionís  cCs#tiidƒ}tii|ƒ ogSndk}y¯|iƒ}|i|ƒg}x…|i dƒD]t}|i d|ƒ}|i ƒddfjo,|i ƒdjo|id|ƒqÝqi|id||fƒqiW|SWn6|ij o'}dk}|id|ƒgSnXdS(Ns ~/.testoobrcsdefaultstruesfalses--%ss--%s=%ssError reading config file: %s(sosspaths expandusersfilenamesexistss ConfigParsersconfigsreadsresultsoptionssoptionsgetsvalueslowersappendsErrorseswarningsswarn(sesoptionswarningssvaluesfilenamesresultsconfigs ConfigParser((s*build/bdist.linux-i686/egg/testoob/main.pys_config_file_argsôs(    cCsCtƒtid}tƒ}|i|ƒ\}}|||fSdS(Ni(s_config_file_argsssyssargvsargss _arg_parsersparsers parse_argssoptions(sparsersargssoptions((s*build/bdist.linux-i686/egg/testoob/main.pys _parse_args s c Ks¤dk}x3|iƒD]%\}}|iit||ƒƒqWtƒ\}} }y$|i t ||| ||ƒ ƒWn(tj o}|it|ƒƒnXdS(N(ssysskwargssitemssargsvaluesargvsappendskwarg_to_options _parse_argssparsersoptionss test_namessexits_mainssuites defaultTestsArgumentsErrorseserrorsstr( ssuites defaultTestskwargssparsersesvaluessyss test_namessargsoptions((s*build/bdist.linux-i686/egg/testoob/main.pysmains  $(s__doc__sosssysssets NameErrorssetssSets ImportErrorscompatibility.setss commandlines _arg_parsers_get_verbositysNones _get_suitesscommandline.parsingsArgumentsErrors_mainskwarg_to_options_config_file_argss _parse_argssmain( ssets_mains _arg_parsers commandlines_config_file_argss _get_suitess_get_verbositys _parse_argsssyssArgumentsErrorskwarg_to_optionsmainsos((s*build/bdist.linux-i686/egg/testoob/main.pys?s$       PK'ƒ5CÔªººtestoob/exceptions.pyc;ò ÍŸ¦Dc@s dZdefd„ƒYZdS(sException classessSkipTestExceptioncBstZRS(N(s__name__s __module__(((s0build/bdist.linux-i686/egg/testoob/exceptions.pysSkipTestExceptionsN(s__doc__s ExceptionsSkipTestException(sSkipTestException((s0build/bdist.linux-i686/egg/testoob/exceptions.pys?sPK'ƒ5”"0ââtestoob/extracting.pyc;ò W˜öDc@sÛdZdklZydklZWn ej odklZnXed„Z d„Z e d„Z d„Z d„Z d„Zd „Zhd d <d d <dd an iterator on its direct sub-suites. For compatibility with Python versions before 2.4cCsd|_tSdS(Ns(stests_testoob_extra_descriptionsTrue(stest((s0build/bdist.linux-i686/egg/testoob/extracting.pysadd_extra_description_field.s N(sadd_extra_description_fields_ifiltersiterssuites TypeErrors_tests(ssuitesadd_extra_description_field((s0build/bdist.linux-i686/egg/testoob/extracting.pys suite_iter*s  cs8dk‰‡d†}t‡d†||d|ƒƒSdS(sQExtract the text fixtures from a suite. Descends recursively into sub-suites.Ncs)t|ˆiƒot|ƒSngSdS(N(s isinstancesnodesunittests TestSuites suite_iter(snode(sunittest(s0build/bdist.linux-i686/egg/testoob/extracting.pys test_children<scst|ˆiƒS(N(s isinstancestestsunittestsTestCase(stest(sunittest(s0build/bdist.linux-i686/egg/testoob/extracting.pys@sschildren(sunittests test_childrens_ifiltersrecursive_iteratorssuite(ssuitesrecursive_iteratorsunittests test_children((sunittests0build/bdist.linux-i686/egg/testoob/extracting.pysfull_extractor8s    cs‡d†}|SdS(Ncs‡‡d†}|SdS(Ncsˆˆ||ŽƒSdS(N(sfuncs extractorsargsskwargs(sargsskwargs(s extractorsfunc(s0build/bdist.linux-i686/egg/testoob/extracting.pyswrapperEs(swrapper(s extractorswrapper(sfunc(s extractors0build/bdist.linux-i686/egg/testoob/extracting.pys decoratorDs(s decorator(sfuncs decorator((sfuncs0build/bdist.linux-i686/egg/testoob/extracting.pys_iterable_decoratorCs cst‡d†ƒSdS(Ncs tˆ|ƒS(N(s_ifilterspredsiterable(siterable(spred(s0build/bdist.linux-i686/egg/testoob/extracting.pysKs(s_iterable_decorator(spred((spreds0build/bdist.linux-i686/egg/testoob/extracting.pys predicateJscs2dk}|i|ƒ‰‡d†}t|ƒSdS(s\Filter tests based on matching a regex to their id. Matching is performed with re.searchNcsˆi|iƒƒSdS(N(scompiledssearchstestsid(stest(scompiled(s0build/bdist.linux-i686/egg/testoob/extracting.pyspredRs(srescompilesregexscompiledspreds predicate(sregexsrespredscompiled((scompileds0build/bdist.linux-i686/egg/testoob/extracting.pysregexMs   cs&dk‰‡‡d†}t|ƒSdS(smFilter tests based on a matching glob pattern to their id. Matching is performed with fnmatch.fnmatchcaseNcsˆi|iƒˆƒSdS(N(sfnmatchs fnmatchcasestestsidspattern(stest(sfnmatchspattern(s0build/bdist.linux-i686/egg/testoob/extracting.pyspredYs(sfnmatchspreds predicate(spatternsfnmatchspred((spatternsfnmatchs0build/bdist.linux-i686/egg/testoob/extracting.pysglobUs isstisndisedccswxp|D]h}x_t|ƒD]Q}y+d|dti|ddƒf|_Wntt fj onX|VqWqWdS(Ns (%d%s iteration)isth( siterablesxsxranges num_timessisnumber_suffixessgets_testoob_extra_descriptionsAttributeErrors TypeError(s num_timessiterablesisx((s0build/bdist.linux-i686/egg/testoob/extracting.pys_irepeat_items`s +cst‡d†ƒSdS(s"Repeat each test a number of timescs tˆ|ƒS(N(s_irepeat_itemss num_timessiterable(siterable(s num_times(s0build/bdist.linux-i686/egg/testoob/extracting.pysmsN(s_iterable_decorator(s num_times((s num_timess0build/bdist.linux-i686/egg/testoob/extracting.pysrepeatkscCs^|tjodkl}ndkl}||ƒi}t|ƒ}||ƒt|ƒSdS(sŽ Randomize the iterable. Note: this evaluates the entire iterable to a sequence in memory, use this when this isn't an issue (sshuffle(sRandomN( sseedsNonesrandomsshufflesRandomslistsiterablesresultsiter(siterablesseedsshufflesRandomsresult((s0build/bdist.linux-i686/egg/testoob/extracting.pys _irandomizeos    cst‡d†ƒSdS(s Randomize the order of the testscs t|ˆƒS(N(s _irandomizesiterablesseed(siterable(sseed(s0build/bdist.linux-i686/egg/testoob/extracting.pyssN(s_iterable_decorator(sseed((sseeds0build/bdist.linux-i686/egg/testoob/extracting.pys randomizesN(s__doc__s __future__s generatorss itertoolssifilters_ifilters ImportErrorscompatibility.itertoolssiters_breadth_firsts suite_itersfull_extractors_iterable_decorators predicatesregexsglobsnumber_suffixess_irepeat_itemssrepeatsNones _irandomizes randomize(sregexs predicatesrepeats_irepeat_itemss_iterable_decoratorsglobsnumber_suffixessfull_extractors_ifilters generatorss_breadth_firsts _irandomizes suite_iters randomize((s0build/bdist.linux-i686/egg/testoob/extracting.pys?s"       !  PKšá4ï2)wÜÜtestoob/collecting.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Some useful test-collecting functions" from __future__ import generators try: from itertools import ifilter as _ifilter except ImportError: from compatibility.itertools import ifilter as _ifilter def _is_test_case(x): import types, unittest try: return issubclass(x, unittest.TestCase) except TypeError: # x isn't a class return False def collect(globals_dict): import warnings warnings.warn( "'collect' has been renamed to 'collector_from_globals'", category=DeprecationWarning ) return collector_from_globals(globals_dict) def collector_from_globals(globals_dict): """ Returns a function that collects all TestCases from the given globals dictionary, and registers them in a new TestSuite, returning it. """ import unittest def suite(): result = unittest.TestSuite() for test_case in _ifilter(_is_test_case, globals_dict.values()): result.addTest(unittest.makeSuite(test_case)) return result return suite def collect_from_modules(modules, globals_dict): import warnings warnings.warn( "'collect_from_modules' has been renamed to 'collector_from_modules'", category=DeprecationWarning ) return collector_from_modules(modules, globals_dict) def collector_from_modules(modules, globals_dict): """ Returns a function that collects all TestCases from the given module name list, and the given globals dictionary, and registers them in a new TestSuite, returning it. """ import unittest def suite(): result = unittest.TestSuite() for modulename in modules: NONEMPTYLIST = [None] # help(__import__) says we need this. result.addTest( __import__(modulename, globals_dict, None, NONEMPTYLIST).suite() ) return result return suite def _first_external_frame(): import sys current_file = sys._getframe().f_code.co_filename # find the first frame with a filename different than this one frame = sys._getframe() while frame.f_code.co_filename == current_file: frame = frame.f_back return frame def _calling_module_name(): return _first_external_frame().f_globals["__name__"] def _calling_module_directory(): from os.path import dirname, normpath return normpath(dirname(_first_external_frame().f_code.co_filename)) def _module_names(glob_pattern, modulename, path): import glob from os.path import splitext, basename, join return [ modulename + "." + splitext(basename(filename))[0] for filename in glob.glob( join(path, glob_pattern) ) ] def _load_suite(module_name): import unittest result = unittest.TestLoader().loadTestsFromName( module_name ) if len(result._tests) == 0: import warnings warnings.warn("No tests loaded for module '%s'" % module_name) return result def collect_from_files(glob_pattern, modulename=None, path=None): if modulename is None: modulename = _calling_module_name() if path is None: path = _calling_module_directory() # mimicking unittest.TestLoader.loadTestsFromNames, but with more checks suites = [ _load_suite(name) for name in _module_names(glob_pattern, modulename, path) ] import unittest return unittest.TestLoader().suiteClass(suites) PKµX5ð@‰!!testoob/extracting.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Extracting tests from a test suite" from __future__ import generators # Python 2.2 compatibility try: from itertools import ifilter as _ifilter except ImportError: from compatibility.itertools import ifilter as _ifilter # David Eppstein's breadth_first # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/231503 def _breadth_first(tree,children=iter): """Traverse the nodes of a tree in breadth-first order. The first argument should be the tree root; children should be a function taking as argument a tree node and returning an iterator of the node's children. """ yield tree last = tree for node in _breadth_first(tree,children): for child in children(node): yield child last = child if last == node: return def suite_iter(suite): """suite_iter(suite) -> an iterator on its direct sub-suites. For compatibility with Python versions before 2.4""" def add_extra_description_field(test): test._testoob_extra_description = "" return True try: return _ifilter(add_extra_description_field, iter(suite)) except TypeError: # Before 2.4, test suites weren't iterable return _ifilter(add_extra_description_field, iter(suite._tests)) def full_extractor(suite, recursive_iterator=_breadth_first): """Extract the text fixtures from a suite. Descends recursively into sub-suites.""" import unittest def test_children(node): if isinstance(node, unittest.TestSuite): return suite_iter(node) return [] return _ifilter(lambda test: isinstance(test, unittest.TestCase), recursive_iterator(suite, children=test_children)) def _iterable_decorator(func): def decorator(extractor): def wrapper(*args, **kwargs): return func(extractor(*args, **kwargs)) return wrapper return decorator def predicate(pred): return _iterable_decorator(lambda iterable: _ifilter(pred, iterable)) def regex(regex): """Filter tests based on matching a regex to their id. Matching is performed with re.search""" import re compiled = re.compile(regex) def pred(test):return compiled.search(test.id()) return predicate(pred) def glob(pattern): """Filter tests based on a matching glob pattern to their id. Matching is performed with fnmatch.fnmatchcase""" import fnmatch def pred(test): return fnmatch.fnmatchcase(test.id(), pattern) return predicate(pred) number_suffixes = {1: "st", 2: "nd", 3: "ed", } def _irepeat_items(num_times, iterable): for x in iterable: for i in xrange(num_times): try: x._testoob_extra_description = " (%d%s iteration)" % (i + 1, number_suffixes.get(i + 1, "th")) except (AttributeError, TypeError): # The unit tests may pass something that isn't an instance, so this # may fail pass yield x def repeat(num_times): "Repeat each test a number of times" return _iterable_decorator(lambda iterable: _irepeat_items(num_times, iterable)) def _irandomize(iterable, seed=None): """ Randomize the iterable. Note: this evaluates the entire iterable to a sequence in memory, use this when this isn't an issue """ if seed is None: from random import shuffle else: from random import Random shuffle = Random(seed).shuffle result = list(iterable) shuffle(result) return iter(result) def randomize(seed=None): "Randomize the order of the tests" return _iterable_decorator(lambda iterable: _irandomize(iterable, seed)) PK'ƒ5î-V‹½½testoob/__init__.pyc;ò ™ÊrEc@s:dZdZdZdklZdkZdkTdkTdS(s/An unittest-compatible Python testing frameworksThe Testoob Teams1.13(smainN(s*(s__doc__s __author__s __version__smainstestings collectings exceptions(smains __version__stestings __author__((s.build/bdist.linux-i686/egg/testoob/__init__.pys?s   PKšá4OwM+¾ ¾ testoob/test_loaders.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Special test loaders" import unittest class CustomMethodNameLoader(unittest.TestLoader): "Load test methods based on a predicate" def __init__(self, *args, **kwargs): # in Python 2.2, unittest.TestLoader gets no default __init__, so we # wrap it here if hasattr(unittest.TestLoader, "__init__"): unittest.TestLoader.__init__(self, *args, **kwargs) def getTestCaseNames(self, testCaseClass): "Return the method names matching the predicate" # code from unittest.TestLoader.getTestCaseNames, but with a predicate # hook def isTestMethod(name): if not self._testNamePredicate(name): return False if not callable(getattr(testCaseClass, name)): return False return True testFnNames = filter(isTestMethod, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: for testFnName in self.getTestCaseNames(baseclass): if testFnName not in testFnNames: # handle overridden methods testFnNames.append(testFnName) if self.sortTestMethodsUsing: testFnNames.sort(self.sortTestMethodsUsing) return testFnNames class RegexLoader(CustomMethodNameLoader): "Load test methods matching the regular expression" def __init__(self, regex): CustomMethodNameLoader.__init__(self) import re self.pattern = re.compile(regex) def _testNamePredicate(self, name): return self.pattern.search(name) is not None class GlobLoader(CustomMethodNameLoader): "Load test methods matching the glob pattern" def __init__(self, pattern): CustomMethodNameLoader.__init__(self) self.pattern = pattern def _testNamePredicate(self, name): import fnmatch return fnmatch.fnmatch(name, self.pattern) PK'ƒ5×çc+testoob/asserter.pyc;ò ³¾rEc@s/dZdkZdfd„ƒYZd„ZdS(s+Help hook into asserts, for verbose assertsNsAssertercBs;tZhZd„Zd„Zd„Zd„Zd„ZRS(NcCs(|i|_|i o h|_ndS(N(sselfs_Asserter__shared_states__dict__s _reporters(sself((s.build/bdist.linux-i686/egg/testoob/asserter.pys__init__s  cCstt|ƒ|ƒSdS(N(sgetattrs __import__s package_names class_name(sselfs package_names class_name((s.build/bdist.linux-i686/egg/testoob/asserter.pys_importscsŽt|ˆƒidjodSntdˆƒii‰t|dˆtdˆƒƒtdˆƒ‰‡‡‡‡d†}t|ˆ|ƒdS(Ns_assert_reporting_funcsClass.%ss_real_function_%ssClass._real_function_%scs"tˆƒ}f}|o|d8}|f}nt|ƒ|jo|d8}|||}ntˆd|d|!|ƒ}ti ƒi i d}ˆii|ƒ oˆ||ŽSnyˆ||ŽWn5tj o)}ˆi|i|ˆ||ƒ‚nXˆi|i|ˆ|tƒdS(Nisself(slens variabless num_free_argssadditional_argsskwargssargsszipsvarListssyss _getframesf_backsf_localsstestsselfs _reporterssgetsmethods Exceptionses addAsserts method_namesNone(sargsskwargssesvarLists num_free_argsstestsadditional_args(s method_names variablessmethodsself(s.build/bdist.linux-i686/egg/testoob/asserter.pys_assert_reporting_func&s$    ( sgetattrsClasss method_names__name__sevals func_codes co_varnamess variablesssetattrsmethods_assert_reporting_func(sselfsClasss method_names_assert_reporting_funcs variablessmethod((sselfs method_names variablessmethods.build/bdist.linux-i686/egg/testoob/asserter.pys_make_assert_reportscCs||i|> sys.stderr, ("Not printing coverage data for %r: %s" % (filename, err)) return {} # Adding trailing EOL if missing if not prog.endswith("\n"): prog += "\n" code = compile(prog, filename, "exec") strs = trace.find_strings(filename) return trace.find_lines(code, strs) class Coverage: """ Python code coverage module built specifically for checking code coverage in tests performed by Testoob. NOTE: This class depends on the 'trace' module. """ def __init__(self, ignorepaths=()): """ initialize the code coverage module, gets list of directories and files which's coverage is not needed. """ # coverage is a dictinary mapping filenames to another dictionary with # the following keys: # lines - a set of number of executable lines in the file. # covered - a set of numbers of executed lines in the file. self.coverage = {} self.ignorepaths = map(os.path.abspath, ignorepaths) self.modname = trace.modname def runfunc(self, func, *args, **kwargs): """ Runs the function with arguments and keyword arguments, and checks the code coverage. """ sys.settrace(self._tracer) try: return func(*args, **kwargs) finally: sys.settrace(None) def getstatistics(self): """ Returns a dictionary of statistics. the dictionary maps between a filename and the statistics associated to it. The statistics dictionary has 3 keys: lines - the number of executable lines in the file covered - the number of lines covered in the file percent - the percentage of covered lines. This dictionary also has a special "file" (key) called '__total__', which holds the statistics for all the files together. """ statistics = {} for filename, coverage in self.coverage.items(): statistics[filename] = self._single_file_statistics(coverage) return statistics def _single_file_statistics(self, coverage_dict): def num_lines(): return len(coverage_dict["lines"]) def num_lines_covered(): return len(coverage_dict["covered"]) def percentage(): if num_lines() > 0: return int(100 * num_lines_covered()) / num_lines() else: return 0 return { "lines" : num_lines(), "covered": num_lines_covered(), "percent": percentage(), } def _sum_coverage(self, callable): "Helper method for _total_{lines,covered}" return sum([callable(coverage) for coverage in self.coverage.values()]) def total_lines(self): return self._sum_coverage(lambda coverage: len(coverage["lines"])) def total_lines_covered(self): return self._sum_coverage(lambda coverage: len(coverage["covered"])) def total_coverage_percentage(self): if self.total_lines() == 0: return 0 return int(100 * self.total_lines_covered() / self.total_lines()) def _should_cover_frame(self, frame): "Should we check coverage for this file?" filename = os.path.abspath(frame.f_code.co_filename) lineno = frame.f_lineno for path in self.ignorepaths: if filename.startswith(path): return False if not (filename.endswith(".py") or filename.endswith(".pyc")): return False if not self.coverage.has_key(filename): self.coverage[filename] = { "lines": set(_find_executable_linenos(filename)), "covered": set() } return lineno in self.coverage[filename]["lines"] def _tracer(self, frame, why, arg): "Trace function to be put as input for sys.settrace()" if self._should_cover_frame(frame): filename = os.path.abspath(frame.f_code.co_filename) lineno = frame.f_lineno self.coverage[filename]["covered"].add(lineno) return self._tracer PK'ƒ5}aŽêêtestoob/utils.pyc;ò ÍŸ¦Dc@sjdZd„Zy dkZWnej odkZnXd„Zdefd„ƒYZe d„Z dS(s!General utilities used internallycCs^y|i||ƒSWntj onXz|i||ƒSWd||jo ||=nXdS(N(sdspopskeysdefaultsAttributeErrorsget(sdskeysdefault((s+build/bdist.linux-i686/egg/testoob/utils.pys_pops NcCs'yti|ƒtSWn tSnXdS(sIs the object pickleable?N(s_picklesdumpssobjsTruesFalse(sobj((s+build/bdist.linux-i686/egg/testoob/utils.pys_is_pickleable#s  sUnpickleableFieldErrorcBstZRS(N(s__name__s __module__(((s+build/bdist.linux-i686/egg/testoob/utils.pysUnpickleableFieldError+scs+‡d†}d„}||_||_dS(s Add pickling for 'fields' classes. A 'fields' class is a class who's methods all act as fields - accept no arguments and for a given class's state always return the same value. Useful for 'fields' classes that contain unpickleable members. Used in Testoob, http://testoob.sourceforge.net A contrived example for a 'fields' class: class Titles: def __init__(self, name): self.name = name def dr(self): return "Dr. " + self.name def mr(self): return "Mr. " + self.name If a method returns an unpickleable value there are two options: Default: Allow the instance to be pickled. If the method is called on the unpickled instance, an UnpickleableFieldError exception is raised. There is a possible performance concern here: each return value is pickled twice when pickling the instance. With disable_unpickleable_fields=True: Disallow pickling of instances with a method returning an unpickleable object. c s¦dkl}h‰g‰‡‡‡d†}xjt|ƒD]\}|dddddfjoq8nt||ƒ}t |ƒ|jo|||ƒq8q8WˆˆfSdS(N(s MethodTypecsfy<|ƒ}ˆp t|ƒo|ˆ|mscCstd|ƒ‚dS(Ns%s()'s result wasn't pickleable(sUnpickleableFieldErrorsname(sname((s+build/bdist.linux-i686/egg/testoob/utils.pysgetterqs(sstates fields_dictsunpickleable_fieldsskeyssnamessetattrsselfsgetter(sselfsstatesnamesgettersunpickleable_fieldss fields_dict((s fields_dicts+build/bdist.linux-i686/egg/testoob/utils.pysbuild_from_statehs   N(sstate_extractorsbuild_from_statesklasss __getstate__s __setstate__(sklasssdisable_unpickleable_fieldssstate_extractorsbuild_from_state((sdisable_unpickleable_fieldss+build/bdist.linux-i686/egg/testoob/utils.pysadd_fields_pickling-s    ( s__doc__s_popscPickles_pickles ImportErrorspickles_is_pickleables ExceptionsUnpickleableFieldErrorsFalsesadd_fields_pickling(sUnpickleableFieldErrorsadd_fields_picklings_pops_is_pickleables_pickle((s+build/bdist.linux-i686/egg/testoob/utils.pys?s   PKšá4“àß??testoob/utils.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "General utilities used internally" def _pop(d, key, default): try: return d.pop(key, default) except AttributeError: pass # In Python 2.2 we'll implement pop ourselves try: return d.get(key, default) finally: if key in d: del d[key] try: import cPickle as _pickle except ImportError: import pickle as _pickle def _is_pickleable(obj): "Is the object pickleable?" try: _pickle.dumps(obj) return True except: return False class UnpickleableFieldError(Exception): pass def add_fields_pickling(klass, disable_unpickleable_fields=False): """ Add pickling for 'fields' classes. A 'fields' class is a class who's methods all act as fields - accept no arguments and for a given class's state always return the same value. Useful for 'fields' classes that contain unpickleable members. Used in Testoob, http://testoob.sourceforge.net A contrived example for a 'fields' class: class Titles: def __init__(self, name): self.name = name def dr(self): return "Dr. " + self.name def mr(self): return "Mr. " + self.name If a method returns an unpickleable value there are two options: Default: Allow the instance to be pickled. If the method is called on the unpickled instance, an UnpickleableFieldError exception is raised. There is a possible performance concern here: each return value is pickled twice when pickling the instance. With disable_unpickleable_fields=True: Disallow pickling of instances with a method returning an unpickleable object. """ def state_extractor(self): from types import MethodType fields_dict = {} unpickleable_fields = [] def save_field(name, method): try: retval = method() if disable_unpickleable_fields or _is_pickleable(retval): fields_dict[name] = retval # call the method else: unpickleable_fields.append(name) except TypeError: raise TypeError("""not a "fields" class, problem with method '%s'""" % name) for attr_name in dir(self): if attr_name in ("__init__", "__getstate__", "__setstate__", "__getitem__", "__cmp__"): continue # skip constructor and state magic methods attr = getattr(self, attr_name) if type(attr) == MethodType: save_field(attr_name, attr) return (fields_dict, unpickleable_fields) def build_from_state(self, state): fields_dict, unpickleable_fields = state # saved fields for name in fields_dict.keys(): # set the default name argument to prevent overwriting the name setattr(self, name, lambda name=name:fields_dict[name]) # unpickleable fields for name in unpickleable_fields: def getter(name=name): raise UnpickleableFieldError( "%s()'s result wasn't pickleable" % name) setattr(self, name, getter) klass.__getstate__ = state_extractor klass.__setstate__ = build_from_state PKÌ¢è4ê€bÿ¼¼*testoob/commandline/timed_repeat_option.pyimport parsing parsing.parser.add_option("--timed-repeat", metavar="SECONDS", type="float", help="Repeat each test, for a limited time") def process_options(options): if options.timed_repeat is not None: from testoob.running import fixture_decorators parsing.kwargs["fixture_decorators"].append( fixture_decorators.get_timed_fixture(options.timed_repeat)) parsing.option_processors.append(process_options) PKS¦è4ò7OŠÞÞ(testoob/commandline/color_mode_option.pyimport parsing color_choices = ["never", "always", "auto"] parsing.parser.add_option( "--color-mode", metavar = "WHEN", type = "choice", choices = color_choices, default = "auto", help = "When should output be in color? Choices are " + str(color_choices) + ", default is '%default'" ) def auto_color_support(stream): import sys if sys.platform == "win32": return True if not hasattr(stream, "isatty"): return False if not stream.isatty(): return False # auto color only on TTYs try: import curses curses.setupterm() return curses.tigetnum("colors") > 2 except: # guess false in case of error return False def process_options(options): def color_output(): if options.color_mode == "always": return True # TODO: currently hard-coded to sys.stderr, fix this import sys if options.color_mode == "auto" and auto_color_support(sys.stderr): return True return False if color_output(): from testoob.reporting import ColoredTextReporter parsing.kwargs["reporter_class"] = ColoredTextReporter parsing.option_processors.append(process_options) PK'ƒ5fKäV‹‹+testoob/commandline/timed_repeat_option.pyc;ò Ñé¯Dc@sHdkZeiidddddddƒd„ZeiieƒdS( Ns--timed-repeatsmetavarsSECONDSstypesfloatshelps$Repeat each test, for a limited timecCsE|itj o1dkl}tidi|i|iƒƒndS(N(sfixture_decoratorssfixture_decorators( soptionss timed_repeatsNonestestoob.runningsfixture_decoratorssparsingskwargssappendsget_timed_fixture(soptionssfixture_decorators((sEbuild/bdist.linux-i686/egg/testoob/commandline/timed_repeat_option.pysprocess_optionss (sparsingsparsers add_optionsprocess_optionssoption_processorssappend(sprocess_optionssparsing((sEbuild/bdist.linux-i686/egg/testoob/commandline/timed_repeat_option.pys?s " PK͈c5ZeC£__testoob/commandline/parsing.pyclass ArgumentsError(Exception): pass def require_modules(option, *modules): assert len(modules) > 0 missing_modules = [] for modulename in modules: try: __import__(modulename) except ImportError: missing_modules.append(modulename) if missing_modules: raise ArgumentsError( "option '%(option)s' requires missing modules " "%(missing_modules)s" % vars()) def require_posix(option): try: import posix except ImportError: raise ArgumentsError("option '%s' requires a POSIX environment" % option) def _parser(): usage="""%prog [options] [test1 [test2 [...]]] examples: %prog - run default set of tests %prog MyTestSuite - run suite 'MyTestSuite' %prog MyTestCase.testSomething - run MyTestCase.testSomething %prog MyTestCase - run all 'test*' test methods in MyTestCase""" try: import optparse except ImportError: from testoob.compatibility import optparse formatter=optparse.TitledHelpFormatter(max_help_position=30) from testoob import __version__ as version return optparse.OptionParser( usage = usage, formatter = formatter, version = "Testoob %s" % version, ) parser = _parser() option_processors = [] PKÓ™á4ÚÀÎaŸŸ!testoob/commandline/pdf_option.pyimport parsing parsing.parser.add_option("--pdf", metavar="FILE", help="output results in PDF (requires ReportLab)") def process_options(options): if options.pdf is not None: parsing.require_modules("--pdf", "reportlab") from testoob.reporting import PdfReporter parsing.kwargs["reporters"].append( PdfReporter(filename=options.pdf) ) parsing.option_processors.append(process_options) PK'ƒ5F™Ž¦ãã#testoob/commandline/list_option.pyc;ò oŸ¦Dc@sadkZeiiddddddƒeiiddd dd ƒd „ZeiieƒdS( Ns-ls--listsactions store_trueshelps'List the test classes and methods founds--list-formattedsmetavars FORMATTERs,Like option '-l', just formatted (e.g. csv).cCs\dkl}|io|d|iƒtidbuild/bdist.linux-i686/egg/testoob/commandline/regex_option.pysprocess_optionss (sparsingsparsers add_optionsprocess_optionssoption_processorssappend(sprocess_optionssparsing((s>build/bdist.linux-i686/egg/testoob/commandline/regex_option.pys?s  PK/¤è4ÁY¤aa$testoob/commandline/repeat_option.pyimport parsing parsing.parser.add_option("--repeat", metavar="NUM_TIMES", type="int", help="Repeat each test") def process_options(options): if options.repeat is not None: from testoob.extracting import repeat parsing.kwargs["extraction_decorators"].append(repeat(options.repeat)) parsing.option_processors.append(process_options) PKÓ™á4íjDD'testoob/commandline/randomize_option.pyimport parsing parsing.parser.add_option("--randomize-order", action="store_true", help="Randomize the test order") parsing.parser.add_option("--randomize-seed", metavar="SEED", type="int", help="Seed for randomizing the test order, implies --randomize-order") def non_negative_seed(): """ Returns a non-negative int as seed, based on time.time The seed is based on time.time, os.urandom may be used in the future (like it is in module 'random') """ import time while True: result = hash(time.time()) # experiments show hash() works best if result >= 0: return result def randomize_order(seed): if seed is None: seed = non_negative_seed() import sys print >>sys.stderr, "seed=%s" % seed from testoob import extracting parsing.kwargs["extraction_decorators"].append(extracting.randomize(seed)) def process_options(options): if options.randomize_order is not None or options.randomize_seed is not None: randomize_order(options.randomize_seed) parsing.option_processors.append(process_options) PK'ƒ5ÕÆ®÷´´)testoob/commandline/color_mode_option.pyc;ò oð¯Dc@szdkZdddgZeiidddddd ed dd d eeƒd ƒd„Zd„ZeiieƒdS(Nsneversalwayssautos --color-modesmetavarsWHENstypeschoiceschoicessdefaultshelps,When should output be in color? Choices are s, default is '%default'cCsŒdk}|idjotSnt|dƒ otSn|iƒ otSny*dk}|iƒ|i dƒdjSWn tSnXdS(Nswin32sisattyscolorsi( ssyssplatformsTrueshasattrsstreamsFalsesisattyscursess setuptermstigetnum(sstreamscursesssys((sCbuild/bdist.linux-i686/egg/testoob/commandline/color_mode_option.pysauto_color_support s   cs8‡d†}|ƒodkl}|tidlBB"testoob/commandline/list_option.pyimport parsing parsing.parser.add_option("-l", "--list", action="store_true", help="List the test classes and methods found") parsing.parser.add_option("--list-formatted", metavar="FORMATTER", help="Like option '-l', just formatted (e.g. csv).") def process_options(options): from testoob.running import ListingRunner if options.list_formatted: parsing.kwargs["runner"] = ListingRunner(output_format=options.list_formatted) elif options.list is not None: parsing.kwargs["runner"] = ListingRunner() parsing.option_processors.append(process_options) PK(¥è4é~zkOO"testoob/commandline/glob_option.pyimport parsing parsing.parser.add_option("--glob", metavar="PATTERN", help="Filtering glob pattern") def process_options(options): if options.glob is not None: from testoob.extracting import glob parsing.kwargs["extraction_decorators"].append(glob(options.glob)) parsing.option_processors.append(process_options) PK'ƒ5JŒ¢[[#testoob/commandline/html_option.pyc;ò oŸ¦Dc@sBdkZeiidddddƒd„ZeiieƒdS(Ns--htmlsmetavarsFILEshelpsoutput results in HTMLcCsU|itj oAtiddƒdkl}tidi|d|iƒƒndS(Ns--htmlsFt.Xml(s HTMLReporters reporterssfilename( soptionsshtmlsNonesparsingsrequire_modulesstestoob.reportings HTMLReporterskwargssappend(soptionss HTMLReporter((s=build/bdist.linux-i686/egg/testoob/commandline/html_option.pysprocess_optionss (sparsingsparsers add_optionsprocess_optionssoption_processorssappend(sprocess_optionssparsing((s=build/bdist.linux-i686/egg/testoob/commandline/html_option.pys?s  PKÓ™á4^58ýÜÜtestoob/commandline/__init__.pyimport glob, os def module_name(path): return os.path.splitext(os.path.basename(path))[0] def current_path(): return os.path.dirname(__file__) def option_file_glob_pattern(): return os.path.join(current_path(), "*_option.py") def module_list(): return [ module_name(filename) for filename in glob.glob(option_file_glob_pattern()) ] def load_options(): for module in module_list(): exec "import %s" % module load_options() PK'ƒ5†öÅ--#testoob/commandline/pbar_option.pyc;ò +¬Dc@sBdkZeiidddddƒd„ZeiieƒdS(Ns--pbarsactions store_trueshelpsShow a progress barcCs<|itj o(dkl}tidi|ƒƒndS(N(sProgressBarReporters reporters(soptionsspbarsNonestestoob.reporting.progress_barsProgressBarReportersparsingskwargssappend(soptionssProgressBarReporter((s=build/bdist.linux-i686/egg/testoob/commandline/pbar_option.pysprocess_optionss (sparsingsparsers add_optionsprocess_optionssoption_processorssappend(sprocess_optionssparsing((s=build/bdist.linux-i686/egg/testoob/commandline/pbar_option.pys?s  PK¢~c5£E2üNN'testoob/commandline/processes_option.pyimport parsing parsing.parser.add_option("--processes", metavar="NUM_PROCESSES", type="int", help="Run in multiple processes, use Pyro if available") parsing.parser.add_option("--processes_pyro", metavar="NUM_PROCESSES", type="int", help="Run in multiple processes, requires Pyro") parsing.parser.add_option("--processes_old", metavar="NUM_PROCESSES", type="int", help="Run in multiple processes, old implementation") def enable_processes_pyro(nprocesses): parsing.require_posix("--processes_pyro") parsing.require_modules("--processes_pyro", "Pyro") from testoob.running import PyroRunner parsing.kwargs["runner"] = PyroRunner(max_processes = nprocesses) def enable_processes_old(nprocesses): parsing.require_posix("--processes_old") from testoob.running import ProcessedRunner parsing.kwargs["runner"] = ProcessedRunner(max_processes = nprocesses) def process_options(options): if options.processes_pyro is not None: enable_processes_pyro(options.processes_pyro) if options.processes_old is not None: enable_processes_old(options.processes_old) if options.processes is not None: try: enable_processes_pyro(options.processes) except parsing.ArgumentsError: enable_processes_old(options.processes) parsing.option_processors.append(process_options) PKræ4EÎ~bb"testoob/commandline/pbar_option.pyimport parsing parsing.parser.add_option("--pbar", action="store_true", help="Show a progress bar") def process_options(options): if options.pbar is not None: from testoob.reporting.progress_bar import ProgressBarReporter parsing.kwargs["reporters"].append( ProgressBarReporter() ) parsing.option_processors.append(process_options) PK'ƒ5LÞY5y y testoob/commandline/parsing.pyc;ò òZKEc@sDdefd„ƒYZd„Zd„Zd„ZeƒZgZdS(sArgumentsErrorcBstZRS(N(s__name__s __module__(((s9build/bdist.linux-i686/egg/testoob/commandline/parsing.pysArgumentsErrorscGs„t|ƒdjpt‚g}x?|D]7}yt|ƒWq'tj o|i|ƒq'Xq'W|otdt ƒƒ‚ndS(Nis@option '%(option)s' requires missing modules %(missing_modules)s( slensmodulessAssertionErrorsmissing_moduless modulenames __import__s ImportErrorsappendsArgumentsErrorsvars(soptionsmoduless modulenamesmissing_modules((s9build/bdist.linux-i686/egg/testoob/commandline/parsing.pysrequire_modulesscCs7y dk}Wn#tj otd|ƒ‚nXdS(Ns(option '%s' requires a POSIX environment(sposixs ImportErrorsArgumentsErrorsoption(soptionsposix((s9build/bdist.linux-i686/egg/testoob/commandline/parsing.pys require_posixs cCsyd}y dk}Wn tj odkl}nX|iddƒ}dkl}|i d|d|dd |ƒSdS( Ns5%prog [options] [test1 [test2 [...]]] examples: %prog - run default set of tests %prog MyTestSuite - run suite 'MyTestSuite' %prog MyTestCase.testSomething - run MyTestCase.testSomething %prog MyTestCase - run all 'test*' test methods in MyTestCase(soptparsesmax_help_positioni(s __version__susages formattersversions Testoob %s( susagesoptparses ImportErrorstestoob.compatibilitysTitledHelpFormatters formatterstestoobs __version__sversions OptionParser(susagesoptparses formattersversion((s9build/bdist.linux-i686/egg/testoob/commandline/parsing.pys_parsers   N(s ExceptionsArgumentsErrorsrequire_moduless require_posixs_parsersparsersoption_processors(s_parsers require_posixsArgumentsErrorsparsersrequire_modulessoption_processors((s9build/bdist.linux-i686/egg/testoob/commandline/parsing.pys?s    PK'ƒ5˜DIƒƒ(testoob/commandline/randomize_option.pyc;ò oŸ¦Dc@svdkZeiidddddƒeiidddd d dd ƒd „Zd „Zd„ZeiieƒdS(Ns--randomize-ordersactions store_trueshelpsRandomize the test orders--randomize-seedsmetavarsSEEDstypesints>Seed for randomizing the test order, implies --randomize-ordercCsCdk}x3to+t|iƒƒ}|djo|Sq q WdS(s® Returns a non-negative int as seed, based on time.time The seed is based on time.time, os.urandom may be used in the future (like it is in module 'random') Ni(stimesTrueshashsresult(sresultstime((sBbuild/bdist.linux-i686/egg/testoob/commandline/randomize_option.pysnon_negative_seeds  cCsb|tjo tƒ}ndk}|id|IJdkl}tidi |i |ƒƒdS(Nsseed=%s(s extractingsextraction_decorators( sseedsNonesnon_negative_seedssyssstderrstestoobs extractingsparsingskwargssappends randomize(sseedssyss extracting((sBbuild/bdist.linux-i686/egg/testoob/commandline/randomize_option.pysrandomize_orders     cCs5|itj p |itj ot|iƒndS(N(soptionssrandomize_ordersNonesrandomize_seed(soptions((sBbuild/bdist.linux-i686/egg/testoob/commandline/randomize_option.pysprocess_optionss (sparsingsparsers add_optionsnon_negative_seedsrandomize_ordersprocess_optionssoption_processorssappend(sprocess_optionssnon_negative_seedsrandomize_ordersparsing((sBbuild/bdist.linux-i686/egg/testoob/commandline/randomize_option.pys?s "  PK'ƒ5¡õ´ŽŽ%testoob/commandline/silent_option.pyc;ò Óî¯Dc@sEdkZeiiddddddƒd„ZeiieƒdS(Ns-ss--silentsactions store_trueshelpsno output to terminalcCs|itidEscCs;|i|ƒ|iid|ƒ|ƒ|iidƒdS(Nsresultstestcase(sselfs_start_testcase_tags test_infoswriterselementsresults add_elementssend(sselfs test_infosresults add_elements((s3build/bdist.linux-i686/egg/testoob/reporting/xml.pys_add_testcase_elementEs cCs$ti||ƒ|i|dƒdS(Nssuccess(s BaseReporters addSuccesssselfs test_infos_add_testcase_element(sselfs test_info((s3build/bdist.linux-i686/egg/testoob/reporting/xml.pys addSuccessKscs9tiˆ|ˆ|ƒ‡‡d†}ˆi|dƒdS(NcsˆiidˆiƒƒdS(Nsreason(sselfswriterselementserr_infosexception_value((sselfserr_info(s3build/bdist.linux-i686/egg/testoob/reporting/xml.pys add_elementsQssskip(s BaseReportersaddSkipsselfs test_infoserr_infos isRegistereds add_elementss_add_testcase_element(sselfs test_infoserr_infos isRegistereds add_elements((sselfserr_infos3build/bdist.linux-i686/egg/testoob/reporting/xml.pysaddSkipOscs)‡‡‡d†}ˆi|ˆ|ƒdS(Ncs5ˆiiˆtˆƒdˆiƒdˆiƒƒdS(s4Additional elements specific for failures and errorsstypesmessageN(sselfswriterselements failure_typesstrserr_infosexception_typesexception_value((s failure_typesselfserr_info(s3build/bdist.linux-i686/egg/testoob/reporting/xml.pys add_elementsVs(s add_elementssselfs_add_testcase_elements test_infos failure_type(sselfs failure_types test_infoserr_infos add_elements((sselfs failure_typeserr_infos3build/bdist.linux-i686/egg/testoob/reporting/xml.pys_add_unsuccessful_testcaseUscCs/|iiddt|ƒd|i|ƒƒdS(Nstestcasesnamestime(sselfswritersstartsstrs test_infos _test_time(sselfs test_info((s3build/bdist.linux-i686/egg/testoob/reporting/xml.pys_start_testcase_tag[scCs-tiƒ|i|}|i|=d|SdS(Ns%.4f(stimesselfs test_startss test_infosresult(sselfs test_infosresult((s3build/bdist.linux-i686/egg/testoob/reporting/xml.pys _test_time^s c Cs|iidƒxð|iƒiƒD]Ü\}}|iidd|dt|dƒdt|dƒdt|dƒƒ|i|i ƒ\}}gi }|D]!}||jo||ƒqœqœ~}|iit|ƒd d !id d ƒƒ|iidƒq#W|iidƒdS( Nscoverages sourcefilesnames statementsslinessexecutedscoveredspercentiiÿÿÿÿs s(sselfswritersstartscoverages getstatisticssitemssfilenamesstatssstrsvaluesslinesscoveredsappends_[1]slinesmissingsdatasreplacesend( sselfscoveragesstatssmissingslinessfilenames_[1]scoveredsline((s3build/bdist.linux-i686/egg/testoob/reporting/xml.pys_write_coveragecs 8)(s__name__s __module__s__doc__s__init__sstartsdonesget_xmls startTestsaddErrors addFailures_add_testcase_elements addSuccesssTruesaddSkips_add_unsuccessful_testcases_start_testcase_tags _test_times_write_coverage(((s3build/bdist.linux-i686/egg/testoob/reporting/xml.pys XMLReporters           sXMLFileReportercBstZd„Zd„ZRS(NcCsti|ƒ||_dS(N(s XMLReporters__init__sselfsfilename(sselfsfilename((s3build/bdist.linux-i686/egg/testoob/reporting/xml.pys__init__rs cCsHti|ƒt|idƒ}z|i|iƒƒWd|iƒXdS(Nsw( s XMLReportersdonesselfsfilesfilenamesfswritesget_xmlsclose(sselfsf((s3build/bdist.linux-i686/egg/testoob/reporting/xml.pysdonevs  (s__name__s __module__s__init__sdone(((s3build/bdist.linux-i686/egg/testoob/reporting/xml.pysXMLFileReporterqs (s__doc__sbases BaseReporterstimes XMLReportersXMLFileReporter(sXMLFileReporters XMLReporters BaseReporterstime((s3build/bdist.linux-i686/egg/testoob/reporting/xml.pys?s  ]PK'ƒ5äéº*dd%testoob/reporting/html_standalone.pyc;ò ìHKEc@s-dZdklZdefd„ƒYZdS(s>Standalone HTML reporting, doesn't need external XSLT services(s BaseReportersOldHTMLReportercBs˜tZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z d Z d „Z d Zed „ZdZd„Zd„ZRS(s<Direct HTML reporting. Deprecated in favor of XSLT reportingcCs^ti|ƒdkl}|ƒ|_dkl}||idƒ|_||_ h|_ dS(N(sStringIO(s XMLWritersutf-8( s BaseReporters__init__sselfs cStringIOsStringIOs_sioselementtree.SimpleXMLWriters XMLWriterswritersfilenames test_starts(sselfsfilenamesStringIOs XMLWriter((s?build/bdist.linux-i686/egg/testoob/reporting/html_standalone.pys__init__s     cCsti|ƒ|iƒdS(N(s BaseReportersstartsselfs _writeHeader(sself((s?build/bdist.linux-i686/egg/testoob/reporting/html_standalone.pysstart s cCsÙ|iidƒ|iidƒ|iiddƒ|iidƒ|iidƒ|iidddƒ|iid ƒ|iid d ƒ|iid d ƒ|iid d ƒ|iid dƒ|iid ƒdS(NshtmlsheadstitlesTESTOOB unit-test reportsbodystablesborders1strstds Test NamesTimesResults More info(sselfswritersstartselementsend(sself((s?build/bdist.linux-i686/egg/testoob/reporting/html_standalone.pys _writeHeader$scCs’ti|ƒ|iidƒ|iidd|iƒ|iidƒ|iidƒt|idƒ}z|i |i ƒƒWd|i ƒXdS(NstablespsTotal time: %.4fsbodyshtmlsw( s BaseReportersdonesselfswritersendselements total_timesfilesfilenamesfswrites_getHtmlsclose(sselfsf((s?build/bdist.linux-i686/egg/testoob/reporting/html_standalone.pysdone2s cCs|iiƒSdS(N(sselfs_siosgetvalue(sself((s?build/bdist.linux-i686/egg/testoob/reporting/html_standalone.pys_getHtml>scCs2dk}|idd|ƒ}|iddƒSdS(Ns File "(.+)",s$ File "\1",s s
(sressubsstrsreplace(sselfsstrsre((s?build/bdist.linux-i686/egg/testoob/reporting/html_standalone.pys_encodeExceptionAs cCs'ti||ƒtiƒ|i|%s%ssuccesscCs@ti||ƒ|iitit|ƒ|i |ƒfƒdS(N( s BaseReporters addSuccesssselfs test_infos_sioswrites HTMLReporters_SuccessTemplatesstrs _test_time(sselfs test_info((s?build/bdist.linux-i686/egg/testoob/reporting/html_standalone.pys addSuccessSssT%s%sskipped%scCsUti||||ƒ|iiti t |ƒ|i |ƒt |i ƒƒfƒdS(N( s BaseReportersaddSkipsselfs test_infoserr_infos isRegistereds_sioswrites HTMLReporters _SkipTemplatesstrs _test_timesexception_value(sselfs test_infoserr_infos isRegistered((s?build/bdist.linux-i686/egg/testoob/reporting/html_standalone.pysaddSkipXss] %s%s%s %s cCsE|iitit|ƒ|i|ƒ||i t|ƒƒfƒdS(N( sselfs_sioswrites HTMLReporters _FailTemplatesstrs test_infos _test_times failure_types_encodeExceptionserr_info(sselfs failure_types test_infoserr_info((s?build/bdist.linux-i686/egg/testoob/reporting/html_standalone.pys_add_unsuccessful_testcase`scCs-tiƒ|i|}|i|=d|SdS(Ns%.4f(s_timestimesselfs test_startss test_infosresult(sselfs test_infosresult((s?build/bdist.linux-i686/egg/testoob/reporting/html_standalone.pys _test_timecs (s__name__s __module__s__doc__s__init__sstarts _writeHeadersdones_getHtmls_encodeExceptions startTestsaddErrors addFailures_SuccessTemplates addSuccesss _SkipTemplatesTruesaddSkips _FailTemplates_add_unsuccessful_testcases _test_time(((s?build/bdist.linux-i686/egg/testoob/reporting/html_standalone.pysOldHTMLReporters"           N(s__doc__sbases BaseReportersOldHTMLReporter(sOldHTMLReporters BaseReporter((s?build/bdist.linux-i686/egg/testoob/reporting/html_standalone.pys?s PK'ƒ5^,Që´C´C testoob/reporting/textstream.pyc;ò ëHKEc@sidZdfd„ƒYZdefd„ƒYZdfd„ƒYZdklZdefd „ƒYZd S( s3A text-stream reporter, the most commonly used kinds StreamWritercBs#tZd„Zd„Zd„ZRS(NcCs ||_dS(N(sstreamsself(sselfsstream((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys__init__scCs|ii|ƒdS(N(sselfsstreamswritess(sselfss((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pyswritescCs|i|ƒ|idƒdS(Ns (sselfswritess(sselfss((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pyswritelns (s__name__s __module__s__init__swriteswriteln(((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys StreamWriters  s BogusWritercBstZdZd„ZRS(s For testingcCs4ti|dƒti||ƒti|dƒdS(Ns(s StreamWriterswritesselfss(sselfss((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pyswrites(s__name__s __module__s__doc__swrite(((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys BogusWriters s StreamWriterscBstZd„ZRS(NcCs.t|ƒ}||_|_|_|_dS(N(s StreamWritersstreamswritersselfsnormalssuccesssfailureswarning(sselfsstreamswriter((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys__init__%s (s__name__s __module__s__init__(((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys StreamWriters$s(s BaseReportersTextStreamReportercBs0tZdZddZddZeed„Zd„Zd„Z d„Z e d„Z d „Z d „Zd „Zd „Zd „Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z!d„Z"d„Z#d „Z$RS(!sReports to a text streams=iFs-cCsqdk}||_ti|ƒ||ƒ|_|dj|_|dj|_ |dj|_ ||_ ||_ dS(Nii( sresselfs BaseReporters__init__screate_writerssstreamswriterss verbositysshowAllsdotssvasserts immediates descriptions(sselfsstreams descriptionss verbositys immediatescreate_writerssre((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys__init__2s    cCsNti||ƒt|_|io'|i|i|ƒƒ|idƒndS(Ns ... ( s BaseReporters startTestsselfs test_infosFalsesmultiLineOutputsshowAlls_writesgetDescription(sselfs test_info((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys startTest=s   cCsN|io%|id|iƒ|i|ƒn|io|i|ƒndS(Ns ( sselfsshowAllswriterswritesmultiLineOutputswritelns long_stringsdotss short_string(sselfs long_strings short_stringswriter((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys_report_resultDs   cCs-ti||ƒ|idd|iiƒdS(NsOKs.(s BaseReporters addSuccesssselfs test_infos_report_resultswritersssuccess(sselfs test_info((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys addSuccessKscCs3ti||||ƒ|idd|iiƒdS(NsSKIPPEDsS( s BaseReportersaddSkipsselfs test_infoserr_infos isRegistereds_report_resultswritersswarning(sselfs test_infoserr_infos isRegistered((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pysaddSkipOscCs8|i|||ƒ|io|i|||ƒndS(N( sselfs_report_results long_strings short_stringswriters immediates_immediatePrints test_infoserr_info(sselfs long_strings short_stringswriters test_infoserr_info((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys_report_failureSs cCs6ti|||ƒ|idd|ii||ƒdS(NsERRORsE(s BaseReportersaddErrorsselfs test_infoserr_infos_report_failureswriterssfailure(sselfs test_infoserr_info((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pysaddErrorYscCs6ti|||ƒ|idd|ii||ƒdS(NsFAILsF(s BaseReporters addFailuresselfs test_infoserr_infos_report_failureswriterssfailure(sselfs test_infoserr_info((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys addFailure^scCs:ti||ƒ|io|i o|i|ƒndS(N(s BaseReportersstopTestsselfs test_infosvasserts immediates_printVasserts(sselfs test_info((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pysstopTestcscCsbd|d}|digi}|D](\}}||dt|ƒdƒq%~ƒ7}|SdS(Ns(s) s s: "s"( s assertNamesmsgsjoinsappends_[1]svarListsnamesvaluesstr(sselfs assertNamesvarListsnamesvalues_[1]smsg((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys_vassertMessagehsLcCs5|o|iiidƒn|iiidƒdS(s$Write a boolean to the proper writersPASSEDsFAILEDN(sisPassedsselfswritersssuccessswritesfailure(sselfsisPassed((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys_write_vassert_is_passedmscCsG|iiidƒ|i|ƒ|iiid|i||ƒƒdS(Ns [ s %s ]( sselfswriterssnormalswrites_write_vassert_is_passedsisPassedswritelns_vassertMessages assertNamesvarList(sselfs assertNamesvarListsisPassed((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys_write_vassert_messagets cCs>x7|i|D](\}}}|i|||tjƒqWdS(N(sselfsassertss test_infos assertNamesvarLists exceptions_write_vassert_messagesNone(sselfs test_infos exceptionsvarLists assertName((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys_printVassertsyscCs]|io|idƒn|i|||ƒ|i|iƒ|i o|idƒndS(Ns ( sselfsdotss_writes_printOneErrorsflavours test_infoserr_infos_writelns separator1sshowAll(sselfs test_infoserr_infosflavour((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys_immediatePrint}s   cCsçti|ƒ|ip|io|idƒn|i o|iƒnt|i ƒdjo|i ƒnt|i ƒdjo|i d|i ƒnt|i ƒdjo|i d|i ƒn|i|iƒ|iƒdS(Ns isErredsFailed(s BaseReportersdonesselfsdotssshowAlls_writes immediates _printErrorsslensskipss _printSkippedserrorss_printShortErrorssfailuress_writelns separator2s _printResults(sself((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pysdone…s  cCsdti|||||ƒ|io|io3|i d|i |||t jƒƒt |_ ndS(Ns (s BaseReporters addAssertsselfs test_infos assertNamesvarLists exceptions immediatesvasserts_writes_vassertMessagesNonesTruesmultiLineOutput(sselfs test_infos assertNamesvarLists exception((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys addAssertšs&c Cst|iidt|iƒIJ|iidigi}|iD]&\}}|d||i ƒfƒq>~ƒIJdS(NsSkipped %d testss s - %s (%s)( sselfswritersswarningslensskipssjoinsappends_[1]stestserrsexception_value(sselfs_[1]stestserr((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys _printSkipped sc Csh|iid|t|ƒfIJ|iidigi}|D]\}}|d|ƒq>~ƒIJdS(Ns %s %d testss s - %s( sselfswriterssfailuresflavourslenserrorssjoinsappends_[1]stestserr(sselfsflavourserrorsserrs_[1]stest((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys_printShortErrors§s cCs¤|itj o |idjo\|idjo|i|iƒn|idjo|i|iƒn|i|iƒn|idjodpd}|i d|i||i fƒ|itj o|i d|ii ƒƒn|i d ƒ|i ƒo|iid IJnŒg}t|iƒd jo|id t|iƒƒnt|iƒd jo|id t|iƒƒn|iiddi|ƒIJdS(NsslimsnormalsmassiveissssRan %d test%s in %.3fss (covered %s%% of the code)s sOKis failures=%ds errors=%ds FAILED (%s)s, (sselfs cover_amountsNones_print_coverage_statisticsscoverages_print_coverages_writelns separator2stestsRuns testssuffixs_writes total_timestotal_coverage_percentages isSuccessfulswritersssuccesssstringsslensfailuressappendserrorssfailuresjoin(sselfsstringss testssuffix((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys _printResults®s&    c CsÄ|i}|iidIJ|iidIJxU|iƒiƒD]A\}}|iid|d|d|d||ƒ|fIJq<W|iidIJ|iid|i ƒ|i ƒ|i ƒfIJdS(Ns&lines cov_n cov% module (path)s&--------------------------------------s%5d %5d %3d%% %s (%s)slinesscoveredspercents%5d %5d %3d%% TOTAL( scoveragesmodnamesselfswriterssnormals getstatisticssitemssfilenamesstatss total_linesstotal_lines_coveredstotal_coverage_percentage(sselfscoveragesstatssmodnamesfilename((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys_print_coverage_statisticsÈs  9cs+|i‰tt‡d†|iiƒƒƒ}d|}|ii |ddIJ|ii d|dIJxo|i ƒi ƒD][\}}|ii |dˆ|ƒ|d|d |d |i|i|iƒŒfIJqzW|ii d|dIJ|ii |d d |iƒ|iƒ|iƒfIJdS( Ncstˆ|ƒƒS(N(slensmodnamesx(sx(smodname(s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pysÕss%%- %dssmodules! lines cov_n cov% missings-s!---------------------------------s %5d %5d %3d%% %sslinesscoveredspercents %5d %5d %3d%%sTOTAL(scoveragesmodnamesmaxsmapskeyss maxmodules module_tmplsselfswriterssnormals getstatisticssitemssfilenamesstatss_get_missing_lines_strsvaluess total_linesstotal_lines_coveredstotal_coverage_percentage(sselfscoveragesmodnamesstatss maxmodulesfilenames module_tmpl((smodnames:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys_print_coverageÓs $  ScCsC|igi}|D]!}||jo||ƒqq~ƒSdS(N(sselfs_lines_list_shrinkersappends_[1]scoveredslineslines(sselfslinesscovereds_[1]sline((s:build/bdist.linux-i686/egg/testoob/reporting/textstream.pys_get_missing_lines_stráscCsÈ|iƒ|idƒdg}x“tt|ƒdƒD]{}||d||djo1|ddjot||ƒd|dti|ƒ||_d|_d|_d|_g|_dS(Ni(s BaseReporters__init__sselfsstreams success_counts failure_counts error_countsresult(sselfsstream((s4build/bdist.linux-i686/egg/testoob/reporting/html.pys__init__&s      cCsEti||ƒ|id7_|iid|iƒddfƒdS(Niis(s BaseReporters addSuccesssselfs test_infos success_countsresultsappends classname(sselfs test_info((s4build/bdist.linux-i686/egg/testoob/reporting/html.pys addSuccess8scCsNti|||ƒ|id7_|iid|iƒdt |ƒfƒdS(Niis( s BaseReportersaddErrorsselfs test_infoserr_infos error_countsresultsappends classnamesstr(sselfs test_infoserr_info((s4build/bdist.linux-i686/egg/testoob/reporting/html.pysaddError=scCsTti||iƒ|ƒ|id7_|iid|iƒdt |ƒfƒdS(Nis( s BaseReporters addFailuresselfs test_infos classnameserr_infos failure_countsresultsappendsstr(sselfs test_infoserr_info((s4build/bdist.linux-i686/egg/testoob/reporting/html.pys addFailureBscCsNti|ƒtƒ}dk}|iiƒ|_|ii |i |ƒƒdS(N( s BaseReportersdonesselfs get_runnersrunnersdatetimesnowsstopTimesstreamswritesgenerateReportString(sselfsrunnersdatetime((s4build/bdist.linux-i686/egg/testoob/reporting/html.pysdoneGs    (s__name__s __module__s__doc__s__init__s addSuccesssaddErrors addFailuresdone(((s4build/bdist.linux-i686/egg/testoob/reporting/html.pysNewHTMLReporter"s     N(s__doc__s ImportErrorsNones get_runnersbases BaseReportersNewHTMLReporter(s BaseReportersNewHTMLReporters get_runner((s4build/bdist.linux-i686/egg/testoob/reporting/html.pys?s  PK/~c5¬snÐÐ*Ð*testoob/reporting/textstream.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "A text-stream reporter, the most commonly used kind" class StreamWriter: def __init__(self, stream): self.stream = stream def write(self, s): self.stream.write(s) def writeln(self, s): self.write(s) self.write("\n") class BogusWriter(StreamWriter): # XXX "For testing" def write(self, s): StreamWriter.write(self, "<") StreamWriter.write(self, s) StreamWriter.write(self, ">") class StreamWriters: def __init__(self, stream): writer = StreamWriter(stream) self.normal = self.success = self.failure = self.warning = writer from base import BaseReporter class TextStreamReporter(BaseReporter): "Reports to a text stream" # Modified from unittest._TextTestResult # TODO: could be refactored quite a bit separator1 = '=' * 70 separator2 = '-' * 70 def __init__(self, stream, descriptions, verbosity, immediate = False, create_writers = StreamWriters): import re self.re = re BaseReporter.__init__(self) self.writers = create_writers(stream) self.showAll = verbosity > 1 self.dots = verbosity == 1 self.vassert = verbosity == 3 self.immediate = immediate self.descriptions = descriptions def startTest(self, test_info): BaseReporter.startTest(self, test_info) self.multiLineOutput = False if self.showAll: self._write(self.getDescription(test_info)) self._write(" ... ") def _report_result(self, long_string, short_string, writer): if self.showAll: writer.write("\n" * self.multiLineOutput) writer.writeln(long_string) elif self.dots: writer.write(short_string) def addSuccess(self, test_info): BaseReporter.addSuccess(self, test_info) self._report_result("OK", ".", self.writers.success) def addSkip(self, test_info, err_info, isRegistered=True): BaseReporter.addSkip(self, test_info, err_info, isRegistered) self._report_result("SKIPPED", "S", self.writers.warning) def _report_failure(self, long_string, short_string, writer, test_info, err_info): self._report_result(long_string, short_string, writer) if self.immediate: self._immediatePrint(test_info, err_info, long_string) def addError(self, test_info, err_info): BaseReporter.addError(self, test_info, err_info) self._report_failure( "ERROR", "E", self.writers.failure, test_info, err_info) def addFailure(self, test_info, err_info): BaseReporter.addFailure(self, test_info, err_info) self._report_failure( "FAIL", "F", self.writers.failure, test_info, err_info) def stopTest(self, test_info): BaseReporter.stopTest(self, test_info) if self.vassert and not self.immediate: self._printVasserts(test_info) def _vassertMessage(self, assertName, varList): msg = "(" + assertName + ") " msg += " ".join([name + ": \"" + str(value) + "\"" for name, value in varList]) return msg def _write_vassert_is_passed(self, isPassed): "Write a boolean to the proper writer" if isPassed: self.writers.success.write("PASSED") else: self.writers.failure.write("FAILED") def _write_vassert_message(self, assertName, varList, isPassed): self.writers.normal.write(" [ ") self._write_vassert_is_passed(isPassed) self.writers.normal.writeln(" %s ]" % self._vassertMessage(assertName, varList)) def _printVasserts(self, test_info): for assertName, varList, exception in self.asserts[test_info]: self._write_vassert_message(assertName, varList, exception is None) def _immediatePrint(self, test_info, err_info, flavour): if self.dots: self._write("\n") self._printOneError(flavour, test_info, err_info) self._writeln(self.separator1) if self.showAll: self._write("\n") def done(self): BaseReporter.done(self) if self.dots or self.showAll: self._write("\n") if not self.immediate: self._printErrors() if len(self.skips) > 0: self._printSkipped() if len(self.errors) > 0: self._printShortErrors("Erred", self.errors) if len(self.failures) > 0: self._printShortErrors("Failed", self.failures) self._writeln(self.separator2) self._printResults() def addAssert(self, test_info, assertName, varList, exception): BaseReporter.addAssert(self, test_info, assertName, varList, exception) if self.immediate and self.vassert: self._write("\n " + self._vassertMessage(assertName, varList, exception is None)) self.multiLineOutput = True def _printSkipped(self): print >>self.writers.warning, "Skipped %d tests" % len(self.skips) print >>self.writers.warning, "\n".join([ " - %s (%s)" % (test, err.exception_value()) for (test, err) in self.skips ]) def _printShortErrors(self, flavour, errors): print >>self.writers.failure, "%s %d tests" % (flavour, len(errors)) print >>self.writers.failure, "\n".join([ " - %s" % test for (test, err) in errors ]) def _printResults(self): if self.cover_amount is not None and self.cover_amount != "slim": if self.cover_amount == "normal": self._print_coverage_statistics(self.coverage) if self.cover_amount == "massive": self._print_coverage(self.coverage) self._writeln(self.separator2) testssuffix = self.testsRun > 1 and "s" or "" self._write("Ran %d test%s in %.3fs" % (self.testsRun, testssuffix, self.total_time)) if self.cover_amount is not None: self._write(" (covered %s%% of the code)" % self.coverage.total_coverage_percentage()) self._write("\n") if self.isSuccessful(): print >>self.writers.success, "OK" else: strings = [] if len(self.failures) > 0: strings.append("failures=%d" % len(self.failures)) if len(self.errors) > 0: strings.append("errors=%d" % len(self.errors)) print >>self.writers.failure, "FAILED (%s)" % ", ".join(strings) def _print_coverage_statistics(self, coverage): modname = coverage.modname print >>self.writers.normal, "lines cov_n cov% module (path)" print >>self.writers.normal, "--------------------------------------" for filename, stats in coverage.getstatistics().items(): print >>self.writers.normal, "%5d %5d %3d%% %s (%s)" % ( stats["lines"], stats["covered"], stats["percent"], modname(filename), filename) print >>self.writers.normal, "--------------------------------------" print >>self.writers.normal, "%5d %5d %3d%% TOTAL" % ( coverage.total_lines(), coverage.total_lines_covered(), coverage.total_coverage_percentage()) def _print_coverage(self, coverage): modname = coverage.modname maxmodule = max(map(lambda x: len(modname(x)), coverage.coverage.keys())) module_tmpl = "%%- %ds" % maxmodule print >>self.writers.normal, module_tmpl % "module" + " lines cov_n cov% missing" print >>self.writers.normal, "-" * maxmodule + "---------------------------------" for filename, stats in coverage.getstatistics().items(): print >>self.writers.normal, (module_tmpl + " %5d %5d %3d%% %s") % ( modname(filename), stats["lines"], stats["covered"], stats["percent"], self._get_missing_lines_str(*coverage.coverage[filename].values())) print >>self.writers.normal, "-" * maxmodule + "---------------------------------" print >>self.writers.normal, (module_tmpl + " %5d %5d %3d%%") % ("TOTAL", coverage.total_lines(), coverage.total_lines_covered(), coverage.total_coverage_percentage()) def _get_missing_lines_str(self, lines, covered): return self._lines_list_shrinker([line for line in covered if line not in lines]) def _lines_list_shrinker(self, l): l.sort() # adding a 'strange' value to the end of the list, so the last value # will be checked (iterating until (len(l) - 1)). l.append("") result = [""] for i in xrange(len(l) - 1): if l[i+1] == (l[i] + 1): if result[-1] == "": result[-1] = str(l[i]) + "-" else: result[-1] += str(l[i]) result.append("") result.pop() return result def _printErrors(self): self._printErrorList('ERROR', self.errors) self._printErrorList('FAIL', self.failures) def _printErrorList(self, flavour, errors): for test_info, err_info in errors: self._printOneError(flavour, test_info, err_info) self._write("\n") def _printOneError(self, flavour, test_info, err_info): self._writeln(self.separator1) print >>self.writers.failure, "%s: %s" % (flavour,self.getDescription(test_info)) self._writeln(self.separator2) self._write(str(err_info)) output = self.getTestsOutput(test_info) if output != "": self._writeln(self.separator1) print >>self.writers.warning, "Run's output" self._writeln(self.separator2) self._write(output) # TODO: Remove these once colord.py also uses a writer def _write(self, s): self.writers.normal.write(s) def _writeln(self, s): self.writers.normal.writeln(s) def getDescription(self, test_info): default_description = test_info.extrafuncname() + " (" + self.re.sub("^__main__.", "", test_info.id()) + ")" if self.descriptions: return test_info.short_description() or default_description else: return default_description PKæ™á4N~e³³"testoob/reporting/xslconverters.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "XSL converters for XML output" # TODO: only one converter, do we need this? def _read_file(filename): from os.path import join, dirname f = open(join(dirname(__file__), filename)) try: return f.read() finally: f.close() import html_xsl BASIC_CONVERTER = html_xsl.XSL PK'ƒ5o7pIM M testoob/reporting/err_info.pyc;ò ‘Ÿ¦Dc@sFdZd„Zd„Zdfd„ƒYZdklZeeƒdS(s getting information about errorscCs)t|tƒo|Snt||ƒSdS(s8 Factory method for creating ErrInfo instances. N(s isinstanceserrsErrInfostest(stestserr((s8build/bdist.linux-i686/egg/testoob/reporting/err_info.pyscreate_err_infoscCs;dk}yt||iƒSWntj o tSnXdS(N(stestoobs issubclasssexception_typesSkipTestExceptions TypeErrorsFalse(sexception_typestestoob((s8build/bdist.linux-i686/egg/testoob/reporting/err_info.pys _should_skips  sErrInfocBsDtZdZd„Zd„Zd„Zd„Zd„Zd„ZRS(sp An interface for getting information about test errors. Reporters receive instances of this class. cCs||_||_dS(N(stestsselfsexc_info(sselfstestsexc_info((s8build/bdist.linux-i686/egg/testoob/reporting/err_info.pys__init__(s cCs7dkl}dkl}||i||iƒƒSdS(N(sexc_info_to_string(sTestInfo(scommonsexc_info_to_strings test_infosTestInfosselfsexc_infostest(sselfsTestInfosexc_info_to_string((s8build/bdist.linux-i686/egg/testoob/reporting/err_info.pys__str__,s  cCst|idƒSdS(s½ Does the error signify a skip? Normally done by checking that exception_type derives from SkipTestException, but that can't be done after fields pickling. iN(s _should_skipsselfsexc_info(sself((s8build/bdist.linux-i686/egg/testoob/reporting/err_info.pysis_skip1scCst|idƒSdS(Ni(sstrsselfsexc_info(sself((s8build/bdist.linux-i686/egg/testoob/reporting/err_info.pysexception_type:scCst|idƒSdS(Ni(sstrsselfsexc_info(sself((s8build/bdist.linux-i686/egg/testoob/reporting/err_info.pysexception_value=scCs|idSdS(Ni(sselfsexc_info(sself((s8build/bdist.linux-i686/egg/testoob/reporting/err_info.pys traceback@s( s__name__s __module__s__doc__s__init__s__str__sis_skipsexception_typesexception_values traceback(((s8build/bdist.linux-i686/egg/testoob/reporting/err_info.pysErrInfo#s     (sadd_fields_picklingN(s__doc__screate_err_infos _should_skipsErrInfos testoob.utilssadd_fields_pickling(screate_err_infos _should_skipsadd_fields_picklingsErrInfo((s8build/bdist.linux-i686/egg/testoob/reporting/err_info.pys?s   PKæ™á4›°ÚWtestoob/reporting/html_xsl.pyXSL = """ Testoob report

Summarized results for tests performed on date

NameTimeResultInfo
Success
                      
                    
""".strip() PK/~c5qå(e e #testoob/reporting/reporter_proxy.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "The proxy used as a result object for PyUnit suites" # TODO: separate the PyUnit result-object passed to the fixtures and # the observable proxy that proxies everything to reporters. # Notice the '_apply_method' duplication in each method, this should # be removed. from test_info import create_test_info from err_info import create_err_info def synchronize(func, lock=None): if lock is None: import threading lock = threading.RLock() def wrapper(*args, **kwargs): lock.acquire() try: return func(*args, **kwargs) finally: lock.release() return wrapper class ReporterProxy: def __init__(self, threads=False): self.observing_reporters = [] if threads: self._apply_method = synchronize(self._apply_method) def add_observer(self, reporter): self.observing_reporters.append(reporter) def _apply_method(self, name, *args, **kwargs): for reporter in self.observing_reporters: getattr(reporter, name)(*args, **kwargs) def setParameters(self, **parameters): self._apply_method("setParameters", **parameters) def start(self): self._apply_method("start") def done(self): self._apply_method("done") def startTest(self, test): self._apply_method("startTest", create_test_info(test)) def stopTest(self, test): self._apply_method("stopTest", create_test_info(test)) def addError(self, test, err): test_info = create_test_info(test) err_info = create_err_info(test, err) if err_info.is_skip(): self._apply_method("addSkip", test_info, err_info) return self._apply_method("addError", test_info, err_info) def addFailure(self, test, err): self._apply_method("addFailure", create_test_info(test), create_err_info(test, err)) def addSuccess(self, test): self._apply_method("addSuccess", create_test_info(test)) def addAssert(self, test, assertName, varList, exception): self._apply_method("addAssert", create_test_info(test), assertName, varList, exception) def addSkip(self, test, err, isRegistered=True): self._apply_method("addSkip", create_test_info(test), create_err_info(test, err), isRegistered) def isSuccessful(self): for reporter in self.observing_reporters: if not reporter.isSuccessful(): return False # One failed reporter is enough return True PK'ƒ5™ÊŽ^__testoob/reporting/html_xslt.pyc;ò ‘Ÿ¦Dc@s-dZdklZdefd„ƒYZdS(s3Report results in HTML, using an XSL transformation(s XSLTReporters HTMLReportercBstZd„ZRS(NcCs#dk}ti|||iƒdS(N(s xslconverterss XSLTReporters__init__sselfsfilenamesBASIC_CONVERTER(sselfsfilenames xslconverters((s9build/bdist.linux-i686/egg/testoob/reporting/html_xslt.pys__init__s (s__name__s __module__s__init__(((s9build/bdist.linux-i686/egg/testoob/reporting/html_xslt.pys HTMLReportersN(s__doc__sxslts XSLTReporters HTMLReporter(s XSLTReporters HTMLReporter((s9build/bdist.linux-i686/egg/testoob/reporting/html_xslt.pys?s PK'ƒ5è_(@ÆÆ"testoob/reporting/progress_bar.pyc;ò ëHKEc@s_dZdkTdkZdkZdeifd„ƒYZdklZdefd„ƒYZdS(sSimple GUI progress bar(s*NsProgressBarGuiThreadcBs˜tZd„Zd„Zd„Zed„ƒZed„ƒZed„ƒZed„ƒZ ed„ƒZ ed „ƒZ d „Z d „Z d „ZRS( NcCs>tii|ƒ||_||_tiƒ|_t|_ dS(N( s threadingsThreads__init__sselfs num_testss bar_widthsEvents ready_eventsNoneserror(sselfs num_testss bar_width((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pys__init__s   cCs|iiƒdS(N(sselfs ready_eventswait(sself((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pyswait_until_readyscCs£zŽyetƒ|_d|_tƒ|_|iƒt|id|iƒiƒ|i i ƒ|ii ƒWn"t j ot iƒ|_nXWd|i i ƒXdS(Nis textvariable(sTksselfsrootscounts StringVarstextVarsupdatesLabelspacks ready_eventssetsmainloopsTclErrorssyssexc_infoserror(sself((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pysruns     cCst|iƒt|iƒS(N(sfloatsselfscounts num_tests(sself((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pys.scCsdtd|iƒS(Ns%%%did(sintsselfsratio(sself((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pys/scCst|i|iƒS(N(sintsselfsratios bar_width(sself((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pys1scCs|i|iS(N(sselfs bar_widthsdone_bar_length(sself((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pys2scCs|id|idS(Ns#s_(sselfsdone_bar_lengthsleft_bar_length(sself((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pys5scCsd|i|ifS(Ns%s %s(sselfstext_barspercent(sself((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pys8scCs|id7_|iƒdS(Ni(sselfscountsupdate(sself((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pysadvance:scCs|iiƒ|`|`dS(N(sselfsrootsquitstextVar(sself((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pysdie>s cCs|ii|iƒdS(N(sselfstextVarssetsstatus(sself((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pysupdateDs(s__name__s __module__s__init__swait_until_readysrunspropertysratiospercentsdone_bar_lengthsleft_bar_lengthstext_barsstatussadvancesdiesupdate(((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pysProgressBarGuiThreads     (s BaseReportersProgressBarReportercBsMtZdZdZd„Zd„Zd„Zd„Zd„Ze d„Z RS(sDisplays a progress baricCsnti|ƒtd|idd|iƒ|_|iiƒ|iiƒ|iio|iid‚ndS(Ns num_testss bar_widthi( s BaseReportersstartsselfsProgressBarGuiThreads parameterss BAR_WIDTHs_pbgswait_until_readyserror(sself((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pysstartMs    cCsti|ƒ|iiƒdS(N(s BaseReportersdonesselfs_pbgsdie(sself((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pysdoneXs cCs$ti|||ƒ|iiƒdS(N(s BaseReportersaddErrorsselfs test_infoserr_infos_pbgsadvance(sselfs test_infoserr_info((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pysaddError\scCs$ti|||ƒ|iiƒdS(N(s BaseReporters addFailuresselfs test_infoserr_infos_pbgsadvance(sselfs test_infoserr_info((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pys addFailure`scCs!ti||ƒ|iiƒdS(N(s BaseReporters addSuccesssselfs test_infos_pbgsadvance(sselfs test_info((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pys addSuccessdscCs'ti||||ƒ|iiƒdS(N(s BaseReportersaddSkipsselfs test_infoserr_infos isRegistereds_pbgsadvance(sselfs test_infoserr_infos isRegistered((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pysaddSkiphs( s__name__s __module__s__doc__s BAR_WIDTHsstartsdonesaddErrors addFailures addSuccesssTruesaddSkip(((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pysProgressBarReporterHs     ( s__doc__sTkinters threadingssyssThreadsProgressBarGuiThreadsbases BaseReportersProgressBarReporter(ssyss threadingsProgressBarReporters BaseReportersProgressBarGuiThread((s<build/bdist.linux-i686/egg/testoob/reporting/progress_bar.pys?s 3 PKæ™á4;9.ˆƒƒtestoob/reporting/pdf.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "PDF reporting using ReportLab's PDF library" from base import BaseReporter class PdfReporter(BaseReporter): def __init__(self, filename): BaseReporter.__init__(self) from reportlab.platypus import XPreformatted, Spacer self.filename = filename self.lst = [] self.lst.append(XPreformatted("Summary of test results",self._normal_style())) self.lst.append(Spacer(0, 20)) self.test_data = [("Name", "Result","Info")] def _normal_style(self): from reportlab.lib.styles import getSampleStyleSheet return getSampleStyleSheet()['Normal'] def addSuccess(self, test_info): BaseReporter.addSuccess(self, test_info) self.test_data.append((str(test_info), "Success", "")) def addError(self, test_info, err_info): BaseReporter.addError(self, test_info, err_info) self._add_unsuccessful_testcase("error", test_info, err_info) def addFailure(self, test_info, err_info): BaseReporter.addFailure(self, test_info, err_info) self._add_unsuccessful_testcase("failure", test_info, err_info) def _add_unsuccessful_testcase(self, failure_type, test_info, err_info): self.test_data.append((str(test_info), failure_type, str(err_info))) def done(self): BaseReporter.done(self) #create result table from reportlab.lib import colors from reportlab.platypus import SimpleDocTemplate, Table, TableStyle table = Table(self.test_data) table.setStyle(TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ('VALIGN', (0,0), (-1,-1), "TOP"), ('BACKGROUND',(0,0),(-1,0), colors.grey)])) for i in xrange(1,len(self.test_data)): if (self.test_data[i][1] == "Success"): color = colors.green else: color = colors.red table.setStyle(TableStyle([('TEXTCOLOR', (1,i),(1,i), color)])) self.lst.append(table) if (self.cover_amount != None): self._print_coverage(self.cover_amount, self.coverage) SimpleDocTemplate(self.filename).build(self.lst) def _print_coverage(self, amount, coverage): from reportlab.lib import colors from reportlab.platypus import Table, TableStyle, XPreformatted, Spacer self.lst.append(Spacer(0,20)) self.lst.append(XPreformatted("Coverage information\n\nCovered %3.2f%% of the code."%coverage.total_coverage_percentage(), self._normal_style())) if (amount != "slim"): self.lst.append(Spacer(0,20)) data = [("Lines", "Covered lines", "Percentage", "Module", "Path")] modname = coverage.modname for filename, stats in coverage.getstatistics().items(): data.append((str(stats["lines"]), str(stats["covered"]), str(stats["percent"])+"%", modname(filename), filename)) data.append((str(coverage.total_lines()), str(coverage.total_lines_covered()), str(coverage.total_coverage_percentage())+'%', "TOTAL","")) table = Table(data) table.setStyle(TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ('VALIGN', (0,0), (-1,-1), "TOP"), ('BACKGROUND',(0,0),(-1,0), colors.grey)])) self.lst.append(table) PK'ƒ5U¾n--testoob/reporting/__init__.pyc;ò àÞ­Dc@sedZdklZdklZdklZdklZdk l Z dk l Z dk lZdS( sReporting facilities subpackage(sColoredTextReporter(s HTMLReporter(sTextStreamReporter(sXMLFileReporter(s ReporterProxy(sTestInfo(s PdfReporterN(s__doc__scoloredsColoredTextReporters html_xslts HTMLReporters textstreamsTextStreamReportersxmlsXMLFileReportersreporter_proxys ReporterProxys test_infosTestInfospdfs PdfReporter(sTestInfosXMLFileReportersTextStreamReportersColoredTextReporters PdfReporters HTMLReporters ReporterProxy((s8build/bdist.linux-i686/egg/testoob/reporting/__init__.pys?s      PKÀ|5€Ô Òßßtestoob/reporting/colored.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Color text stream reporting" import os, sys try: import subprocess except ImportError: from testoob.compatibility import subprocess ANSI_CODES = { "reset" : "\x1b[0m", "bold" : "\x1b[01m", "teal" : "\x1b[36;06m", "turquoise" : "\x1b[36;01m", "fuscia" : "\x1b[35;01m", "purple" : "\x1b[35;06m", "blue" : "\x1b[34;01m", "darkblue" : "\x1b[34;06m", "green" : "\x1b[32;01m", "darkgreen" : "\x1b[32;06m", "yellow" : "\x1b[33;01m", "brown" : "\x1b[33;06m", "red" : "\x1b[31;01m", } from textstream import StreamWriter class TerminalColorWriter(StreamWriter): def __init__(self, stream, color): StreamWriter.__init__(self, stream) self.code = ANSI_CODES[color] self.reset = ANSI_CODES["reset"] def write(self, s): StreamWriter.write(self, self.code) StreamWriter.write(self, s) StreamWriter.write(self, self.reset) WIN32_SETCOLOR_CODES = { "reset" : "d", "red" : "r", "green" : "g", "yellow" : "y", } class WindowsColorBaseWriter(StreamWriter): """ All Windows writers set the color without writing special control characters, so this class is convenient. """ def write(self, s): self._set_color(self.code) StreamWriter.write(self, s) self._set_color(self.reset) class Win32ColorWriterWithExecutable(WindowsColorBaseWriter): setcolor_path = os.path.join(sys.prefix, "testoob", "setcolor.exe") setcolor_available = os.path.isfile(setcolor_path) def __init__(self, stream, color): StreamWriter.__init__(self, stream) self.code = WIN32_SETCOLOR_CODES[color] self.reset = WIN32_SETCOLOR_CODES["reset"] def _set_color(self, code): # TODO: fail in advance if setcolor.exe isn't availble? if self.setcolor_available: subprocess.Popen(r'"%s" %s' % (self.setcolor_path, code)).wait() class Win32ConsoleColorWriter(WindowsColorBaseWriter): def _out_handle(self): import win32console return win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) out_handle = property(_out_handle) def _codes(self): from win32console import FOREGROUND_RED, FOREGROUND_GREEN, FOREGROUND_INTENSITY return { "reset" : self.out_handle.GetConsoleScreenBufferInfo()['Attributes'], "red" : FOREGROUND_RED | FOREGROUND_INTENSITY, "green" : FOREGROUND_GREEN | FOREGROUND_INTENSITY, "yellow" : FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY, } CODES = property(_codes) def __init__(self, stream, color): StreamWriter.__init__(self, stream) self.code = self.CODES[color] self.reset = self.CODES["reset"] def _set_color(self, code): self.out_handle.SetConsoleTextAttribute( code ) class WindowsCtypesColorWriter(WindowsColorBaseWriter): # Constants from the Windows API STD_OUTPUT_HANDLE = -11 FOREGROUND_BLUE = 0x0001 # text color contains blue. FOREGROUND_GREEN = 0x0002 # text color contains green. FOREGROUND_RED = 0x0004 # text color contains red. FOREGROUND_INTENSITY = 0x0008 # text color is intensified. def _out_handle(self): import ctypes return ctypes.windll.kernel32.GetStdHandle(self.STD_OUTPUT_HANDLE) out_handle = property(_out_handle) def _console_screen_buffer_info(self): # Based on IPython's winconsole.py, written by Alexander Belchenko import ctypes, struct csbi = ctypes.create_string_buffer(22) res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(self.out_handle, csbi) assert res (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) return { "bufx" : bufx, "bufy" : bufy, "curx" : curx, "cury" : cury, "wattr" : wattr, "left" : left, "top" : top, "right" : right, "bottom" : bottom, "maxx" : maxx, "maxy" : maxy, } console_screen_buffer_info = property(_console_screen_buffer_info) def _codes(self): return { "reset" : self.console_screen_buffer_info["wattr"], "red" : self.FOREGROUND_RED | self.FOREGROUND_INTENSITY, "green" : self.FOREGROUND_GREEN | self.FOREGROUND_INTENSITY, "yellow" : self.FOREGROUND_GREEN | self.FOREGROUND_RED | self.FOREGROUND_INTENSITY, } CODES = property(_codes) def __init__(self, stream, color): StreamWriter.__init__(self, stream) self.code = self.CODES[color] self.reset = self.CODES["reset"] def _set_color(self, code): import ctypes ctypes.windll.kernel32.SetConsoleTextAttribute(self.out_handle, code) def color_writers_creator(writer_class): class ColorWriters: def __init__(self, stream): self.normal = StreamWriter(stream) self.success = writer_class(stream, "green") self.failure = writer_class(stream, "red") self.warning = writer_class(stream, "yellow") return ColorWriters from textstream import TextStreamReporter def create_colored_reporter(writer_class): class ColoredReporter(TextStreamReporter): def __init__(self, *args, **kwargs): kwargs["create_writers"] = color_writers_creator(writer_class) TextStreamReporter.__init__(self, *args, **kwargs) return ColoredReporter def choose_color_writer(): if "TESTOOB_COLOR_WRITER" in os.environ: print "DEBUG: using", os.environ["TESTOOB_COLOR_WRITER"] return eval(os.environ["TESTOOB_COLOR_WRITER"]) if sys.platform != "win32": return TerminalColorWriter try: import win32console return Win32ConsoleColorWriter except ImportError: pass try: import ctypes return WindowsCtypesColorWriter except ImportError: pass return Win32ColorWriterWithExecutable ColoredTextReporter = create_colored_reporter( choose_color_writer() ) PK'ƒ5ø¦¦testoob/reporting/xslt.pyc;ò “§Dc@s6dZdklZdkZdefd„ƒYZdS(s7Apply an XSL transformation to XMLReporter's xml output(s XMLReporterNs XSLTReportercBshtZdZdfd„ƒYZdefd„ƒYZdefd„ƒYZd„Zd„Zd „ZRS( sHThis reporter uses an XSL transformation scheme to convert an XML outputs IXSLTAppliercBs#tZdZd„Zhd„ZRS(sAn interface for XSLT libscCsdS(s7A constructor with the transformation to apply (string)N((sselfs transform((s4build/bdist.linux-i686/egg/testoob/reporting/xslt.pys__init__scCsdS(s‹Apply the transformation to the input and return the result. Params is a dictionary of extra parameters for the XSLT convertionN((sselfsinputsparams((s4build/bdist.linux-i686/egg/testoob/reporting/xslt.pysapplys(s__name__s __module__s__doc__s__init__sapply(((s4build/bdist.linux-i686/egg/testoob/reporting/xslt.pys IXSLTAppliers  sFourSuiteXSLTAppliercBs#tZdZd„Zhd„ZRS(sXSLT applier that uses 4SuitecCsRdkl}dkl}|iƒ|_|ii|dƒ}|ii |ƒdS(N(s Processor(s InputSources CONVERTER( s Ft.Xml.Xslts ProcessorsFt.Xmls InputSourcesselfs processorsDefaultFactorys fromStrings transforms trans_sourcesappendStylesheet(sselfs transforms InputSources trans_sources Processor((s4build/bdist.linux-i686/egg/testoob/reporting/xslt.pys__init__#s   cCs<dkl}|ii|dƒ}|ii|d|ƒSdS(N(s InputSourcesXMLstopLevelParams( sFt.Xmls InputSourcesDefaultFactorys fromStringsinputs input_sourcesselfs processorsrunsparams(sselfsinputsparamss InputSources input_source((s4build/bdist.linux-i686/egg/testoob/reporting/xslt.pysapply*s (s__name__s __module__s__doc__s__init__sapply(((s4build/bdist.linux-i686/egg/testoob/reporting/xslt.pysFourSuiteXSLTApplier!s  sWinCOMXSLTAppliercBs#tZdZd„Zhd„ZRS(sQXSLT applier that uses window's COM interface to use a common windows XML librarycCs2dk}|iidƒ|_|ii|ƒdS(NsMicrosoft.XMLDOM(swin32com.clientswin32comsclientsDispatchsselfs trans_objsloadXMLs transform(sselfs transformswin32com((s4build/bdist.linux-i686/egg/testoob/reporting/xslt.pys__init__1s cCs<dk}|iidƒ}|i|ƒ|i|i ƒSdS(NsMicrosoft.XMLDOM( swin32com.clientswin32comsclientsDispatchs input_objsloadXMLsinputs transformNodesselfs trans_obj(sselfsinputsparamss input_objswin32com((s4build/bdist.linux-i686/egg/testoob/reporting/xslt.pysapply6s  (s__name__s __module__s__doc__s__init__sapply(((s4build/bdist.linux-i686/egg/testoob/reporting/xslt.pysWinCOMXSLTApplier/s  cCs#ti|ƒ||_||_dS(N(s XMLReporters__init__sselfsfilenames converter(sselfsfilenames converter((s4build/bdist.linux-i686/egg/testoob/reporting/xslt.pys__init__=s  cCsoti|ƒ|iƒ|iƒ}|i|iƒdhdtt i ƒƒ<ƒ}t |i dƒi|ƒdS(Nsparamsudateswt(s XMLReportersdonesselfs_create_xslt_appliers converters xslt_appliersapplysget_xmlsunicodestimesasctimesresultsopensfilenameswrite(sselfs xslt_appliersresult((s4build/bdist.linux-i686/egg/testoob/reporting/xslt.pysdoneAs 0cCsYydk}tiSWnnXy$dk}|iidƒtiSWnnXt d‚dS(NsMicrosoft.XMLDOMs5Unable to find supported XSLT library (4Suite, MSXML)( sFt.XmlsFts XSLTReportersFourSuiteXSLTApplierswin32com.clientswin32comsclientsDispatchsWinCOMXSLTAppliers Exception(sselfswin32comsFt((s4build/bdist.linux-i686/egg/testoob/reporting/xslt.pys_create_xslt_applierGs    ( s__name__s __module__s__doc__s IXSLTAppliersFourSuiteXSLTAppliersWinCOMXSLTAppliers__init__sdones_create_xslt_applier(((s4build/bdist.linux-i686/egg/testoob/reporting/xslt.pys XSLTReporters    (s__doc__sxmls XMLReporterstimes XSLTReporter(s XSLTReporterstimes XMLReporter((s4build/bdist.linux-i686/egg/testoob/reporting/xslt.pys?s  PK0~c5ðÄÞÞtestoob/reporting/base.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Useful base class for reporters" class IReporter: "Interface for reporters" def setParameters(self, **parameters): "Set parameters for the reporter. Called before 'start' is called." def start(self): "Called when the testing is about to start" pass def done(self): "Called when the testing is done" pass ######################################## # Proxied result object methods ######################################## def startTest(self, test_info): "Called when the given test is about to be run" pass def stopTest(self, test_info): "Called when the given test has been run" pass def eraseTest(self, test_info): "Called when the given test shouldn't have been registered" pass def addError(self, test_info, err_info): """ Called when an error has occurred. @param test_info a TestInfo instance @param err_info an ErrInfo instance """ pass def addFailure(self, test_info, err_info): """ Called when a failure has occurred. @param test_info a TestInfo instance @param err_info an ErrInfo instance """ pass def addSuccess(self, test_info): "Called when a test has completed successfully" pass def addAssert(self, test_info, assertName, varList, exception): "Called when an assert was made (if exception is None, the assert passed)" pass ######################################## # Additional reporter's methods. ######################################## def getDescription(self, test_info): "Get a nice printable description of the test" pass def isSuccessful(self): "Tells whether or not this result was a success" pass def setCoverageInfo(self, cover_amount, coverage): "Sets the coverage info for the reporter" def addSkip(self, test_info, err_info, isRegistered=True): "Called when the test was skipped" import time as _time class BaseReporter(IReporter): """Base class for most reporters, with a sensible default implementation for most of the reporter methods""" # borrows a lot of code from unittest.TestResult def __init__(self): self.testsRun = 0 self.successes = [] self.failures = [] self.errors = [] self.skips = [] self.asserts = {} self.cover_amount = None self.coverage = None def setParameters(self, **parameters): self.parameters = parameters def start(self): self.start_time = _time.time() def done(self): self.total_time = _time.time() - self.start_time del self.start_time def startTest(self, test_info): self.testsRun += 1 self.asserts[test_info] = [] def stopTest(self, test_info): pass def addError(self, test_info, err_info): self.errors.append((test_info, err_info)) def addFailure(self, test_info, err_info): self.failures.append((test_info, err_info)) def addSuccess(self, test_info): self.successes.append(test_info) def addSkip(self, test_info, err_info, isRegistered=True): self.skips.append((test_info, err_info)) # We don't want to count skipped tests. if isRegistered: self.testsRun -= 1 def addAssert(self, test_info, assertName, varList, exception): self.asserts[test_info].append((assertName, varList, exception)) def isSuccessful(self): "Tells whether or not this result was a success" if len(self.failures) > 0: return False if len(self.errors) > 0: return False if len(self.successes) == 0: return False return True def setCoverageInfo(self, cover_amount, coverage): self.cover_amount = cover_amount self.coverage = coverage def getTestsOutput(self, test_info): "Get the output (stdout and stderr) captured from the test" try: return test_info.fixture._testOOB_output_txt except AttributeError: return "" PK/~c5ûoÑ ))testoob/reporting/xml.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Report results in XML format" from base import BaseReporter import time class XMLReporter(BaseReporter): """Reports test results in XML, in a format resembling Ant's JUnit xml formatting output.""" def __init__(self): BaseReporter.__init__(self) from cStringIO import StringIO self._sio = StringIO() try: from elementtree.SimpleXMLWriter import XMLWriter except ImportError: from testoob.compatibility.SimpleXMLWriter import XMLWriter self.writer = XMLWriter(self._sio, "utf-8") self.test_starts = {} def start(self): BaseReporter.start(self) self.writer.start("results") self.writer.start("testsuites") def done(self): BaseReporter.done(self) self.writer.element("total_time", value="%.4f"%self.total_time) self.writer.end("testsuites") if self.cover_amount is not None and self.cover_amount == "xml": self._write_coverage(self.coverage) self.writer.end("results") assert len(self.test_starts) == 0 def get_xml(self): return self._sio.getvalue() def startTest(self, test_info): BaseReporter.startTest(self, test_info) self.test_starts[test_info] = time.time() def addError(self, test_info, err_info): BaseReporter.addError(self, test_info, err_info) self._add_unsuccessful_testcase("error", test_info, err_info) def addFailure(self, test_info, err_info): BaseReporter.addFailure(self, test_info, err_info) self._add_unsuccessful_testcase("failure", test_info, err_info) def _add_testcase_element(self, test_info, result, add_elements = lambda:None): self._start_testcase_tag(test_info) self.writer.element("result", result) add_elements() self.writer.end("testcase") def addSuccess(self, test_info): BaseReporter.addSuccess(self, test_info) self._add_testcase_element(test_info, "success") def addSkip(self, test_info, err_info, isRegistered=True): BaseReporter.addSkip(self, test_info, err_info, isRegistered) def add_elements(): self.writer.element( "reason", err_info.exception_value() ) self._add_testcase_element(test_info, "skip") def _add_unsuccessful_testcase(self, failure_type, test_info, err_info): def add_elements(): "Additional elements specific for failures and errors" self.writer.element(failure_type, str(err_info), type=err_info.exception_type(), message=err_info.exception_value()) self._add_testcase_element(test_info, failure_type, add_elements) def _start_testcase_tag(self, test_info): self.writer.start("testcase", name=str(test_info), time=self._test_time(test_info)) def _test_time(self, test_info): result = time.time() - self.test_starts[test_info] del self.test_starts[test_info] return "%.4f" % result def _write_coverage(self, coverage): self.writer.start("coverage") for filename, stats in coverage.getstatistics().items(): # TODO: can probably extract loop body to a method self.writer.start("sourcefile", name=filename, statements=str(stats["lines"]), executed=str(stats["covered"]), percent=str(stats["percent"])) lines, covered = coverage.coverage[filename].values() missing = [line for line in covered if line not in lines] self.writer.data(str(missing)[1:-1].replace(" ", "")) self.writer.end("sourcefile") self.writer.end("coverage") class XMLFileReporter(XMLReporter): def __init__(self, filename): XMLReporter.__init__(self) self.filename = filename def done(self): XMLReporter.done(self) f = file(self.filename, "w") try: f.write(self.get_xml()) finally: f.close() PK0~c5€Ü¬¬$testoob/reporting/html_standalone.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Standalone HTML reporting, doesn't need external XSLT services" from base import BaseReporter class OldHTMLReporter(BaseReporter): "Direct HTML reporting. Deprecated in favor of XSLT reporting" def __init__(self, filename): BaseReporter.__init__(self) from cStringIO import StringIO self._sio = StringIO() from elementtree.SimpleXMLWriter import XMLWriter self.writer = XMLWriter(self._sio, "utf-8") self.filename = filename self.test_starts = {} def start(self): BaseReporter.start(self) self._writeHeader() def _writeHeader(self): self.writer.start("html") self.writer.start("head") self.writer.element("title", "TESTOOB unit-test report") self.writer.end("head") self.writer.start("body") self.writer.start("table", border="1") self.writer.start("tr") self.writer.element("td", "Test Name") self.writer.element("td", "Time") self.writer.element("td", "Result") self.writer.element("td", "More info") self.writer.end("tr") def done(self): BaseReporter.done(self) self.writer.end("table") self.writer.element("p", "Total time: %.4f"%self.total_time) self.writer.end("body") self.writer.end("html") #assert len(self.test_starts) == 0 f = file(self.filename, "w") try: f.write(self._getHtml()) finally: f.close() def _getHtml(self): return self._sio.getvalue() def _encodeException(self, str): import re str = re.sub(r'File "(.+)",', r' File "\1",', str) return str.replace("\n","
") def startTest(self, test_info): BaseReporter.startTest(self, test_info) self.test_starts[test_info] = _time.time() def addError(self, test_info, err_info): BaseReporter.addError(self, test_info, err_info) self._add_unsuccessful_testcase("error", test_info, err_info) def addFailure(self, test_info, err_info): BaseReporter.addFailure(self, test_info, err_info) self._add_unsuccessful_testcase("failure", test_info, err_info) _SuccessTemplate='%s%ssuccess' def addSuccess(self, test_info): BaseReporter.addSuccess(self, test_info) self._sio.write(HTMLReporter._SuccessTemplate%(str(test_info), self._test_time(test_info))) _SkipTemplate='%s%sskipped%s' def addSkip(self, test_info, err_info, isRegistered=True): BaseReporter.addSkip(self, test_info, err_info, isRegistered) self._sio.write(HTMLReporter._SkipTemplate%(str(test_info), self._test_time(test_info), str(err_info.exception_value()))) _FailTemplate=""" %s%s%s %s """ def _add_unsuccessful_testcase(self, failure_type, test_info, err_info): self._sio.write(HTMLReporter._FailTemplate%(str(test_info), self._test_time(test_info), failure_type, self._encodeException(str(err_info)))) def _test_time(self, test_info): result = _time.time() - self.test_starts[test_info] del self.test_starts[test_info] return "%.4f" % result PK'ƒ51Þ>Ä''testoob/reporting/pdf.pyc;ò ‘Ÿ¦Dc@s-dZdklZdefd„ƒYZdS(s+PDF reporting using ReportLab's PDF library(s BaseReporters PdfReportercBsPtZd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Z RS( NcCsƒti|ƒdkl}l}||_g|_|ii|d|i ƒƒƒ|ii|ddƒƒdddfg|_ dS(N(s XPreformattedsSpacers:Summary of test resultsiisNamesResultsInfo( s BaseReporters__init__sselfsreportlab.platypuss XPreformattedsSpacersfilenameslstsappends _normal_styles test_data(sselfsfilenames XPreformattedsSpacer((s3build/bdist.linux-i686/egg/testoob/reporting/pdf.pys__init__s   cCsdkl}|ƒdSdS(N(sgetSampleStyleSheetsNormal(sreportlab.lib.stylessgetSampleStyleSheet(sselfsgetSampleStyleSheet((s3build/bdist.linux-i686/egg/testoob/reporting/pdf.pys _normal_styles cCs3ti||ƒ|iit|ƒddfƒdS(NsSuccesss(s BaseReporters addSuccesssselfs test_infos test_datasappendsstr(sselfs test_info((s3build/bdist.linux-i686/egg/testoob/reporting/pdf.pys addSuccess#scCs*ti|||ƒ|id||ƒdS(Nserror(s BaseReportersaddErrorsselfs test_infoserr_infos_add_unsuccessful_testcase(sselfs test_infoserr_info((s3build/bdist.linux-i686/egg/testoob/reporting/pdf.pysaddError'scCs*ti|||ƒ|id||ƒdS(Nsfailure(s BaseReporters addFailuresselfs test_infoserr_infos_add_unsuccessful_testcase(sselfs test_infoserr_info((s3build/bdist.linux-i686/egg/testoob/reporting/pdf.pys addFailure+scCs)|iit|ƒ|t|ƒfƒdS(N(sselfs test_datasappendsstrs test_infos failure_typeserr_info(sselfs failure_types test_infoserr_info((s3build/bdist.linux-i686/egg/testoob/reporting/pdf.pys_add_unsuccessful_testcase/sc Cs¦ti|ƒdkl}dkl}l}l}||i ƒ}|i |dddfddfd|i fdddfddfd|i fdddfddfd fd ddfddf|i fgƒƒx|td t|i ƒƒD]b}|i |d d jo |i}n |i}|i |d d |fd |f|fgƒƒqéW|ii|ƒ|itjo|i|i|iƒn||iƒi|iƒdS(N(scolors(sSimpleDocTemplatesTables TableStyles INNERGRIDiiÿÿÿÿf0.25sBOXsVALIGNsTOPs BACKGROUNDisSuccesss TEXTCOLOR(s BaseReportersdonesselfs reportlab.libscolorssreportlab.platypussSimpleDocTemplatesTables TableStyles test_datastablessetStylesblacksgreysxrangeslensisgreenscolorsredslstsappends cover_amountsNones_print_coveragescoveragesfilenamesbuild(sselfsis TableStylescolorscolorsstablesTablesSimpleDocTemplate((s3build/bdist.linux-i686/egg/testoob/reporting/pdf.pysdone2s  Ž  2c Csdkl}dkl} l}l} l} |ii | ddƒƒ|ii | d|i ƒ|i ƒƒƒ|djo“|ii | ddƒƒddd d d fg} |i}xd|iƒiƒD]P\}}| i t|d ƒt|d ƒt|dƒd||ƒ|fƒqÈW| i t|iƒƒt|iƒƒt|i ƒƒdddfƒ| | ƒ}|i|dddfddfd|ifdddfddfd|ifdddfddfdfdddfddf|ifgƒƒ|ii |ƒndS(N(scolors(sTables TableStyles XPreformattedsSpaceriisUCoverage information Covered %3.2f%% of the code.sslimsLiness Covered liness PercentagesModulesPathslinesscoveredspercents%sTOTALss INNERGRIDiÿÿÿÿf0.25sBOXsVALIGNsTOPs BACKGROUND(s reportlab.libscolorssreportlab.platypussTables TableStyles XPreformattedsSpacersselfslstsappendscoveragestotal_coverage_percentages _normal_stylesamountsdatasmodnames getstatisticssitemssfilenamesstatssstrs total_linesstotal_lines_coveredstablessetStylesblacksgrey( sselfsamountscoveragesmodnamesstatss TableStylesfilenamescolorsstables XPreformattedsTablesdatasSpacer((s3build/bdist.linux-i686/egg/testoob/reporting/pdf.pys_print_coverageHs )   HD Ž( s__name__s __module__s__init__s _normal_styles addSuccesssaddErrors addFailures_add_unsuccessful_testcasesdones_print_coverage(((s3build/bdist.linux-i686/egg/testoob/reporting/pdf.pys PdfReporters      N(s__doc__sbases BaseReporters PdfReporter(s PdfReporters BaseReporter((s3build/bdist.linux-i686/egg/testoob/reporting/pdf.pys?s PKæ™á4jwR·õ õ testoob/reporting/test_info.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "getting information about tests" def create_test_info(arg): """ Factory method for creating TestInfo instances. """ if isinstance(arg, TestInfo): return arg return TestInfo(arg) class TestInfo: """ An interface for getting information about tests. Reporters receive instances of this class. """ def __init__(self, fixture): self.fixture = fixture def module(self): return self.fixture.__module__ def filename(self): import sys try: return sys.modules[self.module()].__file__ except KeyError: return "unknown file" def classname(self): return self.fixture.__class__.__name__ def funcname(self): # parsing id() because the function name is a private fixture field return self.fixture.id().split(".")[-1] def extrainfo(self): return self.fixture._testoob_extra_description def extrafuncname(self): return "%s%s" % (self.funcname(), self.extrainfo()) def docstring(self): if getattr(self.fixture, self.funcname()).__doc__: return getattr(self.fixture, self.funcname()).__doc__.splitlines()[0] return "" def funcinfo(self): return (self.funcname(), self.docstring(), self.extrainfo()) def failure_exception_type(self): # TODO: do we need this? return self.fixture.failureException def id(self): # TODO: do we need this? return self.fixture.id() def short_description(self): # TODO: do we need this? return self.fixture.shortDescription() def __str__(self): return str(self.fixture) # should be usable as dictionary keys, so define __hash__ and __cmp__ def __unique_string_repr(self): return "%s - %s" % (hash(self), str(self)) def __cmp__(self, other): try: return cmp(self.fixture, other.fixture) except AttributeError: return cmp(self.__unique_string_repr(), other.__unique_string_repr()) def __hash__(self): return hash(self.fixture) from testoob.utils import add_fields_pickling add_fields_pickling(TestInfo) PK'ƒ5ÌVkLÀÀtestoob/reporting/test_info.pyc;ò ‘Ÿ¦Dc@s=dZd„Zdfd„ƒYZdklZeeƒdS(sgetting information about testscCs&t|tƒo|Snt|ƒSdS(s9 Factory method for creating TestInfo instances. N(s isinstancesargsTestInfo(sarg((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pyscreate_test_infossTestInfocBsžtZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z d „Z d „Z d „Zd „Zd„Zd„Zd„ZRS(sj An interface for getting information about tests. Reporters receive instances of this class. cCs ||_dS(N(sfixturesself(sselfsfixture((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pys__init__ scCs|iiSdS(N(sselfsfixtures __module__(sself((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pysmodule#scCs?dk}y|i|iƒiSWntj o dSnXdS(Ns unknown file(ssyssmodulessselfsmodules__file__sKeyError(sselfssys((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pysfilename&s  cCs|iiiSdS(N(sselfsfixtures __class__s__name__(sself((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pys classname-scCs|iiƒidƒdSdS(Ns.iÿÿÿÿ(sselfsfixturesidssplit(sself((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pysfuncname0scCs|iiSdS(N(sselfsfixtures_testoob_extra_description(sself((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pys extrainfo4scCsd|iƒ|iƒfSdS(Ns%s%s(sselfsfuncnames extrainfo(sself((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pys extrafuncname7scCsKt|i|iƒƒio't|i|iƒƒiiƒdSndSdS(Nis(sgetattrsselfsfixturesfuncnames__doc__s splitlines(sself((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pys docstring:s'cCs#|iƒ|iƒ|iƒfSdS(N(sselfsfuncnames docstrings extrainfo(sself((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pysfuncinfo?scCs|iiSdS(N(sselfsfixturesfailureException(sself((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pysfailure_exception_typeBscCs|iiƒSdS(N(sselfsfixturesid(sself((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pysidEscCs|iiƒSdS(N(sselfsfixturesshortDescription(sself((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pysshort_descriptionHscCst|iƒSdS(N(sstrsselfsfixture(sself((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pys__str__KscCsdt|ƒt|ƒfSdS(Ns%s - %s(shashsselfsstr(sself((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pys__unique_string_reprOscCsJyt|i|iƒSWn,tj o t|iƒ|iƒƒSnXdS(N(scmpsselfsfixturesothersAttributeErrors_TestInfo__unique_string_repr(sselfsother((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pys__cmp__RscCst|iƒSdS(N(shashsselfsfixture(sself((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pys__hash__Xs(s__name__s __module__s__doc__s__init__smodulesfilenames classnamesfuncnames extrainfos extrafuncnames docstringsfuncinfosfailure_exception_typesidsshort_descriptions__str__s_TestInfo__unique_string_reprs__cmp__s__hash__(((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pysTestInfos"                (sadd_fields_picklingN(s__doc__screate_test_infosTestInfos testoob.utilssadd_fields_pickling(sTestInfosadd_fields_picklingscreate_test_info((s9build/bdist.linux-i686/egg/testoob/reporting/test_info.pys?s @ PKæ™á4W=\z+ + testoob/reporting/html.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ An HTML reporter. Based on Wai Yip Tung's HTMLTestRunner: http://tungwaiyip.info/software/HTMLTestRunner.html """ raise ImportError("HTMLTestRunner-based HTML reporting is still disabled") def get_runner(title=None, report_attrs=[], description=None): import HTMLTestRunner return HTMLTestRunner.HTMLTestRunner( title = title, report_attrs = report_attrs, description = description ) from base import BaseReporter class NewHTMLReporter(BaseReporter): "Creates an HTML file with the report" # Contains code directly from HTMLTestRunner's _TestResult class def __init__(self, stream): BaseReporter.__init__(self) self.stream = stream self.success_count = 0 self.failure_count = 0 self.error_count = 0 # result is a list of result in 4 tuple # ( # result code (0: success; 1: fail; 2: error), # TestCase object, # Test output (byte string), # stack trace, # ) self.result = [] def addSuccess(self, test_info): BaseReporter.addSuccess(self, test_info) self.success_count += 1 self.result.append((0, test_info.classname(), '', '')) def addError(self, test_info, err_info): BaseReporter.addError(self, test_info, err_info) self.error_count += 1 self.result.append((2, test_info.classname(), '', str(err_info))) def addFailure(self, test_info, err_info): BaseReporter.addFailure(self, test_info.classname(), err_info) self.failure_count += 1 self.result.append((1, test_info.classname(), '', str(err_info))) def done(self): BaseReporter.done(self) # TODO: deal with runner.startTime and runner.stopTime runner = get_runner() import datetime runner.stopTime = datetime.datetime.now() self.stream.write( runner.generateReportString(self) ) PK'ƒ5æ;ú‡ËË#testoob/reporting/xslconverters.pyc;ò ‘Ÿ¦Dc@s%dZd„ZdkZeiZdS(sXSL converters for XML outputcCsNdkl}l}t||tƒ|ƒƒ}z|iƒSWd|iƒXdS(N(sjoinsdirname( sos.pathsjoinsdirnamesopens__file__sfilenamesfsreadsclose(sfilenamesjoinsfsdirname((s=build/bdist.linux-i686/egg/testoob/reporting/xslconverters.pys _read_files N(s__doc__s _read_fileshtml_xslsXSLsBASIC_CONVERTER(s _read_filesBASIC_CONVERTERshtml_xsl((s=build/bdist.linux-i686/egg/testoob/reporting/xslconverters.pys?s  PKf9ç4j×›4••testoob/reporting/__init__.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Reporting facilities subpackage" from colored import ColoredTextReporter from html_xslt import HTMLReporter from textstream import TextStreamReporter from xml import XMLFileReporter from reporter_proxy import ReporterProxy from test_info import TestInfo from pdf import PdfReporter PK'ƒ5D\œR!R!testoob/reporting/base.pyc;ò ìHKEc@s<dZdfd„ƒYZdkZdefd„ƒYZdS(sUseful base class for reporterss IReportercBstZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z d „Z d „Z d „Zd „Zed„ZRS(sInterface for reporterscKsdS(sASet parameters for the reporter. Called before 'start' is called.N((sselfs parameters((s4build/bdist.linux-i686/egg/testoob/reporting/base.pys setParametersscCsdS(s)Called when the testing is about to startN((sself((s4build/bdist.linux-i686/egg/testoob/reporting/base.pysstartscCsdS(sCalled when the testing is doneN((sself((s4build/bdist.linux-i686/egg/testoob/reporting/base.pysdonescCsdS(s-Called when the given test is about to be runN((sselfs test_info((s4build/bdist.linux-i686/egg/testoob/reporting/base.pys startTest$scCsdS(s'Called when the given test has been runN((sselfs test_info((s4build/bdist.linux-i686/egg/testoob/reporting/base.pysstopTest(scCsdS(s9Called when the given test shouldn't have been registeredN((sselfs test_info((s4build/bdist.linux-i686/egg/testoob/reporting/base.pys eraseTest,scCsdS(sŽ Called when an error has occurred. @param test_info a TestInfo instance @param err_info an ErrInfo instance N((sselfs test_infoserr_info((s4build/bdist.linux-i686/egg/testoob/reporting/base.pysaddError0scCsdS(s— Called when a failure has occurred. @param test_info a TestInfo instance @param err_info an ErrInfo instance N((sselfs test_infoserr_info((s4build/bdist.linux-i686/egg/testoob/reporting/base.pys addFailure9scCsdS(s-Called when a test has completed successfullyN((sselfs test_info((s4build/bdist.linux-i686/egg/testoob/reporting/base.pys addSuccessBscCsdS(sHCalled when an assert was made (if exception is None, the assert passed)N((sselfs test_infos assertNamesvarLists exception((s4build/bdist.linux-i686/egg/testoob/reporting/base.pys addAssertFscCsdS(s,Get a nice printable description of the testN((sselfs test_info((s4build/bdist.linux-i686/egg/testoob/reporting/base.pysgetDescriptionMscCsdS(s.Tells whether or not this result was a successN((sself((s4build/bdist.linux-i686/egg/testoob/reporting/base.pys isSuccessfulQscCsdS(s'Sets the coverage info for the reporterN((sselfs cover_amountscoverage((s4build/bdist.linux-i686/egg/testoob/reporting/base.pyssetCoverageInfoUscCsdS(s Called when the test was skippedN((sselfs test_infoserr_infos isRegistered((s4build/bdist.linux-i686/egg/testoob/reporting/base.pysaddSkipXs(s__name__s __module__s__doc__s setParameterssstartsdones startTestsstopTests eraseTestsaddErrors addFailures addSuccesss addAssertsgetDescriptions isSuccessfulssetCoverageInfosTruesaddSkip(((s4build/bdist.linux-i686/egg/testoob/reporting/base.pys IReporters            Ns BaseReportercBstZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z e d „Z d „Zd „Zd „Zd„ZRS(sjBase class for most reporters, with a sensible default implementation for most of the reporter methodscCsLd|_g|_g|_g|_g|_h|_t|_t|_ dS(Ni( sselfstestsRuns successessfailuresserrorssskipssassertssNones cover_amountscoverage(sself((s4build/bdist.linux-i686/egg/testoob/reporting/base.pys__init__as       cKs ||_dS(N(s parameterssself(sselfs parameters((s4build/bdist.linux-i686/egg/testoob/reporting/base.pys setParameterskscCstiƒ|_dS(N(s_timestimesselfs start_time(sself((s4build/bdist.linux-i686/egg/testoob/reporting/base.pysstartnscCs tiƒ|i|_|`dS(N(s_timestimesselfs start_times total_time(sself((s4build/bdist.linux-i686/egg/testoob/reporting/base.pysdoneqscCs |id7_g|i|Converts a sys.exc_info()-style tuple of values into a string.Ns( s tracebackserrsexctypesvaluestbsis_framework_tracebackstb_nextstestsfailure_exception_types count_framework_traceback_levelsslengthsjoinsformat_exception(serrstests tracebacksvaluesexctypeslengthstb((s6build/bdist.linux-i686/egg/testoob/reporting/common.pysexc_info_to_strings  #cCs-|ii}|idƒp |idƒSdS(Ns __unittests __testoob(stbstb_frames f_globalssglobalsshas_key(stbsglobals((s6build/bdist.linux-i686/egg/testoob/reporting/common.pysis_framework_traceback"s cCs>d}x-|o t|ƒ o|d7}|i}q W|SdS(Nii(slengthstbsis_framework_tracebackstb_next(stbslength((s6build/bdist.linux-i686/egg/testoob/reporting/common.pys count_framework_traceback_levels&s  N(s__doc__sexc_info_to_stringsis_framework_tracebacks count_framework_traceback_levels(sis_framework_tracebacks count_framework_traceback_levelssexc_info_to_string((s6build/bdist.linux-i686/egg/testoob/reporting/common.pys?s PK'ƒ5ïaBÕNN$testoob/reporting/reporter_proxy.pyc;ò ëHKEc@sCdZdklZdklZed„Zdfd„ƒYZdS(s3The proxy used as a result object for PyUnit suites(screate_test_info(screate_err_infocs=ˆtjodk}|iƒ‰n‡‡d†}|SdS(Ncs-ˆiƒzˆ||ŽSWdˆiƒXdS(N(slocksacquiresfuncsargsskwargssrelease(sargsskwargs(slocksfunc(s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pyswrappers  (slocksNones threadingsRLockswrapper(sfuncslockswrappers threading((sfuncslocks>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pys synchronizes   s ReporterProxycBsŒtZed„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z d „Z d „Z d „Zed „Zd„ZRS(NcCs*g|_|ot|iƒ|_ndS(N(sselfsobserving_reporterssthreadss synchronizes _apply_method(sselfsthreads((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pys__init__)s cCs|ii|ƒdS(N(sselfsobserving_reporterssappendsreporter(sselfsreporter((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pys add_observer/scOs.x'|iD]}t||ƒ||Žq WdS(N(sselfsobserving_reporterssreportersgetattrsnamesargsskwargs(sselfsnamesargsskwargssreporter((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pys _apply_method2s cKs|id|dS(Ns setParameters(sselfs _apply_methods parameters(sselfs parameters((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pys setParameters6scCs|idƒdS(Nsstart(sselfs _apply_method(sself((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pysstart9scCs|idƒdS(Nsdone(sselfs _apply_method(sself((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pysdone<scCs|idt|ƒƒdS(Ns startTest(sselfs _apply_methodscreate_test_infostest(sselfstest((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pys startTest?scCs|idt|ƒƒdS(NsstopTest(sselfs _apply_methodscreate_test_infostest(sselfstest((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pysstopTestBscCsZt|ƒ}t||ƒ}|iƒo|id||ƒdSn|id||ƒdS(NsaddSkipsaddError( screate_test_infostests test_infoscreate_err_infoserrserr_infosis_skipsselfs _apply_method(sselfstestserrserr_infos test_info((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pysaddErrorEs   cCs&|idt|ƒt||ƒƒdS(Ns addFailure(sselfs _apply_methodscreate_test_infostestscreate_err_infoserr(sselfstestserr((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pys addFailureOscCs|idt|ƒƒdS(Ns addSuccess(sselfs _apply_methodscreate_test_infostest(sselfstest((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pys addSuccessRscCs#|idt|ƒ|||ƒdS(Ns addAssert(sselfs _apply_methodscreate_test_infostests assertNamesvarLists exception(sselfstests assertNamesvarLists exception((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pys addAssertUscCs)|idt|ƒt||ƒ|ƒdS(NsaddSkip(sselfs _apply_methodscreate_test_infostestscreate_err_infoserrs isRegistered(sselfstestserrs isRegistered((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pysaddSkipXscCs2x'|iD]}|iƒ otSq q WtSdS(N(sselfsobserving_reporterssreporters isSuccessfulsFalsesTrue(sselfsreporter((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pys isSuccessful[s   (s__name__s __module__sFalses__init__s add_observers _apply_methods setParameterssstartsdones startTestsstopTestsaddErrors addFailures addSuccesss addAssertsTruesaddSkips isSuccessful(((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pys ReporterProxy(s            N(s__doc__s test_infoscreate_test_infoserr_infoscreate_err_infosNones synchronizes ReporterProxy(screate_err_infos synchronizes ReporterProxyscreate_test_info((s>build/bdist.linux-i686/egg/testoob/reporting/reporter_proxy.pys?s   PK'ƒ5Šz̤¤testoob/reporting/html_xsl.pyc;ò ‘Ÿ¦Dc@sdiƒZdS(sñ Testoob report

Summarized results for tests performed on date

NameTimeResultInfo
Success
                      
                    
N(sstripsXSL(sXSL((s8build/bdist.linux-i686/egg/testoob/reporting/html_xsl.pys?sPKæ™á4‰ß.SŸŸtestoob/reporting/html_xslt.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Report results in HTML, using an XSL transformation" # TODO: insert the converter here from xslt import XSLTReporter class HTMLReporter(XSLTReporter): def __init__(self, filename): import xslconverters XSLTReporter.__init__(self, filename, xslconverters.BASIC_CONVERTER) PK'ƒ5LÔ###testoob/running/processedrunner.pyc;ò iŸ¦Dc@s-dZdklZdefd„ƒYZdS(sRun tests in processes(s BaseRunnersProcessedRunnercBs,tZdZdd„Zd„Zd„ZRS(s,Run tests using fork in different processes.icCs-dkl}ti|ƒ||ƒ|_dS(N(sProcessedRunnerHelper(sprocessed_helpersProcessedRunnerHelpers BaseRunners__init__sselfs max_processess_helper(sselfs max_processessProcessedRunnerHelper((s=build/bdist.linux-i686/egg/testoob/running/processedrunner.pys__init__s  cCs$ti||ƒ|ii|ƒdS(N(s BaseRunnersrunsselfsfixtures_helpersregister_fixture(sselfsfixture((s=build/bdist.linux-i686/egg/testoob/running/processedrunner.pysrunscCs$|ii|iƒti|ƒdS(N(sselfs_helpersstartsreporters BaseRunnersdone(sself((s=build/bdist.linux-i686/egg/testoob/running/processedrunner.pysdones(s__name__s __module__s__doc__s__init__srunsdone(((s=build/bdist.linux-i686/egg/testoob/running/processedrunner.pysProcessedRunners   N(s__doc__s baserunners BaseRunnersProcessedRunner(s BaseRunnersProcessedRunner((s=build/bdist.linux-i686/egg/testoob/running/processedrunner.pys?s PKЙá42pûPP#testoob/running/processed_helper.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Helper for processed running" class ProcessedRunnerHelper: "A helper class to make ProcessedRunner shorter and clearer." def __init__(self, max_processes): self._fixturesList = [[] for i in xrange(max_processes)] self._load_balance_idx = 0 def register_fixture(self, fixture): self._fixturesList[self._load_balance_idx].append(fixture) self._load_balance_idx = (self._load_balance_idx + 1) % len(self._fixturesList) def start(self, reporter): from os import fork, pipe, fdopen, waitpid from sys import exit children = [] for processFixtures in self._fixturesList: pid = fork() if pid == 0: self._run_fixtures(processFixtures, reporter) exit() children.append(pid) for child in children: waitpid(child, 0) def _run_fixtures(self, fixtures, reporter): [fixture(reporter) for fixture in fixtures] PK/~c5ÌBãã%testoob/running/fixture_decorators.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Decorators for standard fixtures" class BaseFixture: def __init__(self, fixture): self.fixture = fixture def __call__(self, *args): self.fixture(*args) def get_fixture(self): result = self.fixture while hasattr(result, "get_fixture"): result = result.get_fixture() return result class ManipulativeFixture(BaseFixture): """ A fixture that allows changing the original test method itself. """ def __init__(self, fixture): BaseFixture.__init__(self, fixture) self.coreFixture = self.get_fixture() self.testMethodName = self.coreFixture.id().split(".")[-1] self.testMethod = getattr(self.coreFixture, self.testMethodName) self.testSetUp = self.coreFixture.setUp self.testTearDown = self.coreFixture.tearDown def updateMethod(self, newMethod): setattr(self.coreFixture, self.testMethodName, newMethod) def get_alarmed_fixture(timeout): class AlarmedFixture(BaseFixture): """ A fixture that times out, implemented with SIGALRM. Needs signals to work, so doesn't work on Windows. Won't work properly some other code, like the test itself, sends SIGALRM or changes the signal handler. """ def __init__(self, fixture): BaseFixture.__init__(self, fixture) from signal import alarm self.alarm = alarm def __call__(self, *args): self.alarm(timeout) # Set timeout for a fixture. BaseFixture.__call__(self, *args) self.alarm(0) # Release the alarm that was set. return AlarmedFixture import thread, threading class TimeoutMain: """ Will raise a KeyboardInterrupt exception in the main thread on timeout. If cancelled, the timing-out thread may persist for a bit. """ def __init__(self, timeout): self.timeout = timeout self.timed_out = False self.cancelled = threading.Event() def start(self): thread.start_new_thread(self._timeout_method, ()) return self def cancel(self): self.cancelled.set() def verify_timeout(self): """ Should be called when the main thread receives a KeyboardInterrupt While waiting for a timeout. If no timeout occurred, re-raises KeyboardInterrupt. """ if not self.timed_out: raise KeyboardInterrupt def _timeout_method(self): self.cancelled.wait(self.timeout) if self.cancelled.isSet(): return self.timed_out = True thread.interrupt_main() def get_thread_timingout_fixture(timeout): assert timeout is not None timeout_main = TimeoutMain(timeout) class TimingOutFixture(ManipulativeFixture): """ A fixture that times out, implemented with threads. Also works on Windows. Known problem: thread.interrupt_main() raises an exception in the main thread only when the main thread has control, doesn't raise it while its blocking. """ def __init__(self, fixture): ManipulativeFixture.__init__(self, fixture) def testWithTimeout(): timeout_main.start() try: self.testMethod() timeout_main.cancel() except KeyboardInterrupt: timeout_main.verify_timeout() raise AssertionError("Timeout after %s seconds" % timeout) self.updateMethod(testWithTimeout) return TimingOutFixture def _fix_sourcefile_extension(filename): # from Python's logging module # TODO: support py2exe? #import sys #if hasattr(sys, 'frozen'): #support for py2exe # return "logging%s__init__%s" % (os.sep, filename[-4:]) if filename[-4:].lower() in ['.pyc', '.pyo']: return filename[:-4] + '.py' return filename def _fix_sourcefile(filename): from os.path import normcase, abspath return abspath(normcase(_fix_sourcefile_extension(filename))) def _module_sourcefile(module_name): return _fix_sourcefile(__import__(module_name).__file__) def get_coverage_fixture(coverage): from os.path import abspath class CoveredFixture(BaseFixture): def __init__(self, fixture): BaseFixture.__init__(self, fixture) coverage.ignorepaths.append(_module_sourcefile(fixture.__module__)) def __call__(self, *args): coverage.runfunc(BaseFixture.__call__, self, *args) return CoveredFixture def get_timed_fixture(time_limit): class TimedFixture(ManipulativeFixture): "Run the fixture repeatedly for a minimum time" def __init__(self, fixture): ManipulativeFixture.__init__(self, fixture) def timedTest(): from time import time start = time() # Run the test at least once anyway self.testMethod() while time() - start < time_limit: # TearDown the last test and setUp the next one. self.testTearDown() self.testSetUp() self.testMethod() self.updateMethod(timedTest) return TimedFixture def get_interrupterd_fixture(isRegistered=False): class InterruptedFixture(ManipulativeFixture): def __call__(self, reporter, *args): from testoob import SkipTestException exception = SkipTestException("Test was interrupted") # Skip the test you just registered. reporter.addSkip(self.get_fixture(), (SkipTestException, exception, None), isRegistered) return InterruptedFixture def get_capture_fixture(): class CaptureFixture(ManipulativeFixture): "Capture a test's output and error" def __init__(self, fixture): ManipulativeFixture.__init__(self, fixture) def CaptureTest(): # TODO: can't we just use a StringIO here instead of pipes? import sys, os stdout_fh = sys.stdout stderr_fh = sys.stderr (read_fd, write_fd) = os.pipe() writer = os.fdopen(write_fd, "w") reader = os.fdopen(read_fd, "r") sys.stdout = sys.stderr = writer try: self.testMethod() finally: writer.close() self.coreFixture._testOOB_output_txt = reader.read() reader.close() sys.stdout = stdout_fh sys.stderr = stderr_fh self.updateMethod(CaptureTest) return CaptureFixture PKЙá4úPÎrÌÌtestoob/running/threadpool.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Supply a ThreadPool, dispatching work to different threads. """ import sys import threading import Queue class Error(Exception): """ General threadpool error """ class _DismissalLetter: """ Sent to a worker thread to dismiss it """ class ThreadPool(object): """ I'm a simple thread pool using constant size. To run a function in a thread, call dispatch() with a callable and optional arguments and keywords. callable must be thread safe! Usage:: p = ThreadPool(10) p.start() try: p.dispatch(callable, foo, bar="baz") ... finally: p.stop() The pool keeps a constant number of worker threads active while its running, and dismiss all of them when you stop it. The pool can be stopped and started as needed. Before exiting the application, the pool must be stopped. Use try finally to make sure your app will quit. You can resize the pool while its running by modifying the size attribute. Unhandled exceptions in code executed by worker threads are printed to the pool logFile, defaulting to sys.stderr. The pool itself is NOT thread safe, and should be accessed by only one thread. """ # ------------------------------------------------------------------ # Initialization def __init__(self, size=10, logFile=None): """ Initialize a pool @param size: number of threads to employ. @param logFile: where exceptions go (default to sys.stderr) """ self._queue = Queue.Queue() # Safe worker threads so we can join them later when we stop self._workers = [] self._running = False self.setSize(size) self.logFile = logFile or sys.stderr # ------------------------------------------------------------------ # Running def start(self): """ Start a pool with size worker threads. Raise threadpool.Error if the pool is already running. """ if self._running: raise Error("the pool is already running.") for worker in range(self._size): self._employWorker() self._running = True def stop(self): """ Stop a pool. All workers are dismissed. Will block until all the workers finished their assignment, which can take some time. Raise threadpool.Error if the pool is not running. """ if not self._running: raise Error("the pool is not running.") workers = self._workers[:] for worker in workers: self._dismissWorker() for worker in workers: worker.join() self._running = False # ------------------------------------------------------------------ # Dispatching def dispatch(self, callable, *args, **kw): """ Add callable to the work queue. Raise threadpool.Error if the pool is not running. @param callable: a callable @param args: arguments for callable @param kw: keyword arguments for callable """ if not self._running: raise Error("the pool is not running.") self._queue.put((callable, args, kw)) # ------------------------------------------------------------------ # Accessing running = property(lambda self: self._running) def setSize(self, count): assert count >= 1, "at least one worker threads must be employed" self._size = count if self._running: self.stop() self.start() size = property(lambda self: self._size, setSize, doc="number of worker threads") workers = property(lambda self: len(self._workers)) def queueEmpty(self): """ Return True if the queue is empty, False otherwise. Because of multithreading semantics, this is not reliable. """ return self._queue.empty() # ------------------------------------------------------------------ # Private def _workerMainLoop(self): """ Loop forever, trying to get work from, the queue. """ me = threading.currentThread() while 1: callable, args, kw = self._queue.get() if callable is _DismissalLetter: break try: callable(*args, **kw) except: import traceback traceback.print_exc(file=self.logFile) del callable, args, kw self._workers.remove(me) def _employWorker(self): t = threading.Thread(target=self._workerMainLoop) self._workers.append(t) t.start() def _dismissWorker(self): """ Dismiss the unfortunate next waiting worker """ self.dispatch(_DismissalLetter) PK“*5 f¶8iitestoob/running/baserunner.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Useful base class for runners" import testoob.asserter class BaseRunner(object): """default implementations of setting a reporter and done()""" def __init__(self): self.reporter = None def run(self, fixture): # Let the assert functions know its reporter testoob.asserter.Asserter().set_reporter(fixture.get_fixture(), self.reporter) def done(self): self.reporter.done() def isSuccessful(self): return self.reporter.isSuccessful() PK'ƒ5‹ŽÕ  $testoob/running/processed_helper.pyc;ò iŸ¦Dc@sdZdfd„ƒYZdS(sHelper for processed runningsProcessedRunnerHelpercBs2tZdZd„Zd„Zd„Zd„ZRS(s;A helper class to make ProcessedRunner shorter and clearer.cCs=gi}t|ƒD]}|gƒq~|_d|_dS(Ni(sappends_[1]sxranges max_processessisselfs _fixturesLists_load_balance_idx(sselfs max_processess_[1]si((s>build/bdist.linux-i686/egg/testoob/running/processed_helper.pys__init__s0cCs8|i|ii|ƒ|idt|iƒ|_dS(Ni(sselfs _fixturesLists_load_balance_idxsappendsfixtureslen(sselfsfixture((s>build/bdist.linux-i686/egg/testoob/running/processed_helper.pysregister_fixturesc Cs¦dkl}l}l}l} dkl}g}xO|i D]D}|ƒ}|djo|i ||ƒ|ƒn|i|ƒq<Wx|D]} | | dƒq‹WdS(N(sforkspipesfdopenswaitpid(sexiti(sossforkspipesfdopenswaitpidssyssexitschildrensselfs _fixturesListsprocessFixturesspids _run_fixturessreportersappendschild( sselfsreportersforksprocessFixturessfdopenspidschildrenspipesexitschildswaitpid((s>build/bdist.linux-i686/egg/testoob/running/processed_helper.pysstarts     cCs/gi}|D]}|||ƒƒq~dS(N(sappends_[1]sfixturessfixturesreporter(sselfsfixturessreporters_[1]sfixture((s>build/bdist.linux-i686/egg/testoob/running/processed_helper.pys _run_fixtures,s(s__name__s __module__s__doc__s__init__sregister_fixturesstarts _run_fixtures(((s>build/bdist.linux-i686/egg/testoob/running/processed_helper.pysProcessedRunnerHelpers    N(s__doc__sProcessedRunnerHelper(sProcessedRunnerHelper((s>build/bdist.linux-i686/egg/testoob/running/processed_helper.pys?sPK'ƒ5âoÿÀ7À7&testoob/running/fixture_decorators.pyc;ò ëHKEc@s¬dZdfd„ƒYZdefd„ƒYZd„ZdkZdkZdfd„ƒYZd „Zd „Zd „Z d „Z d „Z d„Z e d„Zd„ZdS(s Decorators for standard fixturess BaseFixturecBs#tZd„Zd„Zd„ZRS(NcCs ||_dS(N(sfixturesself(sselfsfixture((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys__init__scGs|i|ŒdS(N(sselfsfixturesargs(sselfsargs((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys__call__scCs5|i}x!t|dƒo|iƒ}q W|SdS(Ns get_fixture(sselfsfixturesresultshasattrs get_fixture(sselfsresult((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys get_fixtures  (s__name__s __module__s__init__s__call__s get_fixture(((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys BaseFixtures  sManipulativeFixturecBs tZdZd„Zd„ZRS(sI A fixture that allows changing the original test method itself. cCsxti||ƒ|iƒ|_|iiƒidƒd|_t |i|iƒ|_ |ii |_ |ii |_dS(Ns.iÿÿÿÿ(s BaseFixtures__init__sselfsfixtures get_fixtures coreFixturesidssplitstestMethodNamesgetattrs testMethodssetUps testSetUpstearDowns testTearDown(sselfsfixture((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys__init__#s cCst|i|i|ƒdS(N(ssetattrsselfs coreFixturestestMethodNames newMethod(sselfs newMethod((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys updateMethod+s(s__name__s __module__s__doc__s__init__s updateMethod(((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pysManipulativeFixtures  cs!dtf‡d†ƒY}|SdS(NsAlarmedFixturecs#tZdZd„Z‡d†ZRS(sú A fixture that times out, implemented with SIGALRM. Needs signals to work, so doesn't work on Windows. Won't work properly some other code, like the test itself, sends SIGALRM or changes the signal handler. cCs*ti||ƒdkl}||_dS(N(salarm(s BaseFixtures__init__sselfsfixturessignalsalarm(sselfsfixturesalarm((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys__init__8s cs.|iˆƒti||Œ|idƒdS(Ni(sselfsalarmstimeouts BaseFixtures__call__sargs(sselfsargs(stimeout(s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys__call__=s (s__name__s __module__s__doc__s__init__s__call__((stimeout(s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pysAlarmedFixture/s  (s BaseFixturesAlarmedFixture(stimeoutsAlarmedFixture((stimeouts@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pysget_alarmed_fixture.sNs TimeoutMaincBs;tZdZd„Zd„Zd„Zd„Zd„ZRS(s” Will raise a KeyboardInterrupt exception in the main thread on timeout. If cancelled, the timing-out thread may persist for a bit. cCs%||_t|_tiƒ|_dS(N(stimeoutsselfsFalses timed_outs threadingsEvents cancelled(sselfstimeout((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys__init__Js  cCsti|ifƒ|SdS(N(sthreadsstart_new_threadsselfs_timeout_method(sself((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pysstartNscCs|iiƒdS(N(sselfs cancelledsset(sself((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pyscancelQscCs|i o t‚ndS(s¶ Should be called when the main thread receives a KeyboardInterrupt While waiting for a timeout. If no timeout occurred, re-raises KeyboardInterrupt. N(sselfs timed_outsKeyboardInterrupt(sself((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pysverify_timeoutSs cCsB|ii|iƒ|iiƒodSnt|_tiƒdS(N( sselfs cancelledswaitstimeoutsisSetsTrues timed_outsthreadsinterrupt_main(sself((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys_timeout_method[s  (s__name__s __module__s__doc__s__init__sstartscancelsverify_timeouts_timeout_method(((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys TimeoutMainDs     csDˆtj pt‚tˆƒ‰dtf‡‡d†ƒY}|SdS(NsTimingOutFixturecstZdZ‡‡d†ZRS(s A fixture that times out, implemented with threads. Also works on Windows. Known problem: thread.interrupt_main() raises an exception in the main thread only when the main thread has control, doesn't raise it while its blocking. cs3tiˆ|ƒ‡‡‡d†}ˆi|ƒdS(NcsVˆiƒyˆiƒˆiƒWn-tj o!ˆiƒtdˆƒ‚nXdS(NsTimeout after %s seconds( s timeout_mainsstartsselfs testMethodscancelsKeyboardInterruptsverify_timeoutsAssertionErrorstimeout((sselfstimeouts timeout_main(s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pystestWithTimeoutqs   (sManipulativeFixtures__init__sselfsfixturestestWithTimeouts updateMethod(sselfsfixturestestWithTimeout(stimeouts timeout_main(sselfs@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys__init__os(s__name__s __module__s__doc__s__init__((stimeouts timeout_main(s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pysTimingOutFixturees (stimeoutsNonesAssertionErrors TimeoutMains timeout_mainsManipulativeFixturesTimingOutFixture(stimeoutsTimingOutFixtures timeout_main((stimeouts timeout_mains@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pysget_thread_timingout_fixturebs cCs5|diƒddgjo|d dSn|SdS(Niüÿÿÿs.pycs.pyos.py(sfilenameslower(sfilename((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys_fix_sourcefile_extension|scCs-dkl}l}||t|ƒƒƒSdS(N(snormcasesabspath(sos.pathsnormcasesabspaths_fix_sourcefile_extensionsfilename(sfilenamesabspathsnormcase((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys_fix_sourcefile…scCstt|ƒiƒSdS(N(s_fix_sourcefiles __import__s module_names__file__(s module_name((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys_module_sourcefileˆscs.dkl}dtf‡d†ƒY}|SdS(N(sabspathsCoveredFixturecs tZ‡d†Z‡d†ZRS(Ncs-ti||ƒˆiit|iƒƒdS(N( s BaseFixtures__init__sselfsfixturescoverages ignorepathssappends_module_sourcefiles __module__(sselfsfixture(scoverage(s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys__init__Žscsˆiti||ŒdS(N(scoveragesrunfuncs BaseFixtures__call__sselfsargs(sselfsargs(scoverage(s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys__call__’s(s__name__s __module__s__init__s__call__((scoverage(s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pysCoveredFixtures (sos.pathsabspaths BaseFixturesCoveredFixture(scoveragesabspathsCoveredFixture((scoverages@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pysget_coverage_fixture‹s cs!dtf‡d†ƒY}|SdS(Ns TimedFixturecstZdZ‡d†ZRS(s-Run the fixture repeatedly for a minimum timecs0tiˆ|ƒ‡‡d†}ˆi|ƒdS(Ncs^dkl}|ƒ}ˆiƒx7|ƒ|ˆjo"ˆiƒˆiƒˆiƒq#WdS(N(stime(stimesstartsselfs testMethods time_limits testTearDowns testSetUp(sstartstime(s time_limitsself(s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys timedTest›s     (sManipulativeFixtures__init__sselfsfixtures timedTests updateMethod(sselfsfixtures timedTest(s time_limit(sselfs@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys__init__™s (s__name__s __module__s__doc__s__init__((s time_limit(s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys TimedFixture—s (sManipulativeFixtures TimedFixture(s time_limits TimedFixture((s time_limits@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pysget_timed_fixture–scs!dtf‡d†ƒY}|SdS(NsInterruptedFixturecstZ‡d†ZRS(Ncs?dkl}|dƒ}|i|iƒ||tfˆƒdS(N(sSkipTestExceptionsTest was interrupted( stestoobsSkipTestExceptions exceptionsreportersaddSkipsselfs get_fixturesNones isRegistered(sselfsreportersargss exceptionsSkipTestException(s isRegistered(s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys__call__ªs  (s__name__s __module__s__call__((s isRegistered(s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pysInterruptedFixture©s(sManipulativeFixturesInterruptedFixture(s isRegisteredsInterruptedFixture((s isRegistereds@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pysget_interrupterd_fixture¨scCsdtfd„ƒY}|SdS(NsCaptureFixturecBstZdZd„ZRS(s!Capture a test's output and errorcs-tiˆ|ƒ‡d†}ˆi|ƒdS(Ncs¸dk}dk}|i}|i}|iƒ\}}|i |dƒ}|i |dƒ}||_|_zˆi ƒWd|iƒ|iƒˆi_|iƒ||_||_XdS(Nswsr(ssyssossstdouts stdout_fhsstderrs stderr_fhspipesread_fdswrite_fdsfdopenswritersreadersselfs testMethodsclosesreads coreFixtures_testOOB_output_txt(s stderr_fhsread_fdswritersreaderssyss stdout_fhsosswrite_fd(sself(s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys CaptureTest¶s     (sManipulativeFixtures__init__sselfsfixtures CaptureTests updateMethod(sselfsfixtures CaptureTest((sselfs@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys__init__´s (s__name__s __module__s__doc__s__init__(((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pysCaptureFixture²s (sManipulativeFixturesCaptureFixture(sCaptureFixture((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pysget_capture_fixture±s(s__doc__s BaseFixturesManipulativeFixturesget_alarmed_fixturesthreads threadings TimeoutMainsget_thread_timingout_fixtures_fix_sourcefile_extensions_fix_sourcefiles_module_sourcefilesget_coverage_fixturesget_timed_fixturesFalsesget_interrupterd_fixturesget_capture_fixture(s_fix_sourcefilesthreadsget_coverage_fixtures_fix_sourcefile_extensionsget_timed_fixtures TimeoutMainsManipulativeFixturesget_alarmed_fixtures threadingsget_capture_fixturesget_thread_timingout_fixturesget_interrupterd_fixtures_module_sourcefiles BaseFixture((s@build/bdist.linux-i686/egg/testoob/running/fixture_decorators.pys?s       PK'ƒ5뫯ùù!testoob/running/listingrunner.pyc;ò iŸ¦Dc@s@dZdklZdefd„ƒYZdfd„ƒYZdS(s)Runner that lists tests that would be run(s BaseRunners ListingRunnercBs,tZdZed„Zd„Zd„ZRS(s.Just list the test names, don't run them. cCs||_tƒ|_dS(N(s output_formatsselfs _TestHistoryshistory(sselfs output_format((s;build/bdist.linux-i686/egg/testoob/running/listingrunner.pys__init__s cCs|ii|iƒƒdS(N(sselfshistorysrecord_fixturesfixtures get_fixture(sselfsfixture((s;build/bdist.linux-i686/egg/testoob/running/listingrunner.pysrunscCsN|itjo|iiƒGHn)|iiƒdjo|iiƒGHndS(Nscsv(sselfs output_formatsNoneshistorys get_stringslowersget_csv(sself((s;build/bdist.linux-i686/egg/testoob/running/listingrunner.pysdones(s__name__s __module__s__doc__sNones__init__srunsdone(((s;build/bdist.linux-i686/egg/testoob/running/listingrunner.pys ListingRunners   s _TestHistorycBsGtZd„Zd„Zd„Zd„Zd„Zd„Zd„ZRS(NcCs h|_dS(N(sselfsmodules(sself((s;build/bdist.linux-i686/egg/testoob/running/listingrunner.pys__init__&scCs9dkl}||ƒ}|i|ƒi|iƒƒdS(s?Store the info about each fixture, to show them later. (sTestInfoN(stestoob.reportingsTestInfosfixtures fixture_infosselfs_class_function_listsappendsfuncinfo(sselfsfixturesTestInfos fixture_info((s;build/bdist.linux-i686/egg/testoob/running/listingrunner.pysrecord_fixture)s  c CsÝg}xÃ|iiƒD]²\}}|id||dfƒxˆ|diƒD]v\}}|id|t |ƒfƒxJ|D]B}|id|d|d|do d |dpd fƒq~WqNWqWd i |ƒSd S( sShow all test methods. sModule: %s (%s)sfilenamesclassess Class: %s (%d test functions)s %s()%s%siiis - ss N( sresultsselfsmodulessitemss module_names module_infosappends class_names functionsslensfuncsjoin(sselfs functionss class_namesresultsfuncs module_names module_info((s;build/bdist.linux-i686/egg/testoob/running/listingrunner.pys get_string0s  Hc Cs£dg}x†|iiƒD]u\}}xf|diƒD]T\}}xE|D]=}|d|||d|dg}|i di |ƒƒqIWq6WqWdi |ƒSdS( s2Returns a CSV file structure for parsing. s"file,module,class,method,docstringsclassessfilenameiis,s N( sresultsselfsmodulessitemss module_names module_infos class_names functionssfuncsdatasappendsjoin(sselfs functionss class_namesdatasresultsfuncs module_names module_info((s;build/bdist.linux-i686/egg/testoob/running/listingrunner.pysget_csv?s   !"cCsF|ii|iƒhd|iƒ<dh<ƒ|i|iƒSdS(Nsfilenamesclasses(sselfsmoduless setdefaults fixture_infosmodulesfilename(sselfs fixture_info((s;build/bdist.linux-i686/egg/testoob/running/listingrunner.pys_modulePscCs;|i|ƒd}|i|iƒgƒ||iƒSdS(Nsclasses(sselfs_modules fixture_infos classes_dicts setdefaults classname(sselfs fixture_infos classes_dict((s;build/bdist.linux-i686/egg/testoob/running/listingrunner.pys_class_function_listYscCsSd}xB|iiƒD]1}x(|diƒD]}|t|ƒ7}q-WqW|SdS(Nisclasses(sresultsselfsmodulessvaluessmod_infos functionsslen(sselfsmod_infosresults functions((s;build/bdist.linux-i686/egg/testoob/running/listingrunner.pys_num_functions^s( s__name__s __module__s__init__srecord_fixtures get_stringsget_csvs_modules_class_function_lists_num_functions(((s;build/bdist.linux-i686/egg/testoob/running/listingrunner.pys _TestHistory%s     N(s__doc__s baserunners BaseRunners ListingRunners _TestHistory(s _TestHistorys BaseRunners ListingRunner((s;build/bdist.linux-i686/egg/testoob/running/listingrunner.pys?s PK'ƒ5þS:11testoob/running/__init__.pyc;ò ª6Ec@skdZdklZdklZdklZdklZdk l Z dk l Z dk lZlZdS( stest running logic(s BaseRunner(s SimpleRunner(sThreadedRunner(sProcessedRunner(s ListingRunner(s PyroRunner(srunstext_runN(s__doc__s baserunners BaseRunners simplerunners SimpleRunnersthreadedrunnersThreadedRunnersprocessedrunnersProcessedRunners listingrunners ListingRunners pyro_runners PyroRunners conveniencesrunstext_run(s SimpleRunnersThreadedRunners ListingRunners BaseRunnersProcessedRunnerstext_runs PyroRunnersrun((s6build/bdist.linux-i686/egg/testoob/running/__init__.pys?s      PK'ƒ5‚º’sÕ Õ testoob/running/pyro_runner.pyc;ò iŸ¦Dc@sLdZdklZdkZd„ZdklZdefd„ƒYZdS(s8Run tests in multiple processes, communicating with Pyro(s generatorsNcksaxZtoRy|i|}Wntj o|iƒ}nX||jodSn|VqWdS(sâ Iterate over a Queue.Queue instance until a sentinel is reached Will pass any extra keyword arguments to queue.get Created by Jimmy Retzlaff http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252498 N(sTruesqueuesgetskwargssresults TypeErrorssentinel(squeuessentinelskwargssresult((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys iter_queues (s BaseRunners PyroRunnercBsžtZdZdZd„Zd„Zd„Zdd„Zd„Zd „Z d „Z d „Z d „Z d „Z d„Zd„Zd„Zd„Zd„ZRS(Nf0.5icCsTti|ƒdkl}|ƒ|_||_h|_tiƒ|_ d|_ dS(N(sQueuei( s BaseRunners__init__sselfsQueuesqueues max_processess fixture_idssossgetpids _parent_pids num_fixtures(sselfs max_processessQueue((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys__init__+s     cCsd||ifSdS(s0Return the name mangled for use in Testoob's RPCs:testoob:%s:%sN(sbasenamesselfs _parent_pid(sselfsbasename((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys _pyro_name4scCsd|i|ƒSdS(s;Return the PYROLOC URI for the object, with proper manglingsPYROLOC://localhost/%sN(sselfs _pyro_namesbasename(sselfsbasename((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys _pyroloc_uri7si(cCs«dk}dk}dk}|i|ƒ}|iƒ}xb|iƒ||joJy|i i |ƒi ƒSWq9|i ij o|itiƒq9Xq9Wtdƒ‚dS(sASafely try to get a proxy to the object, looping until timing outNsgetting the proxy has timed out(stimes Pyro.coresPyros Pyro.errorssselfs _pyroloc_urisbasenamesuris starttimestimeoutscoresgetProxyForURIsgetProxyserrorss ProtocolErrorssleeps PyroRunners*SLEEP_INTERVAL_BETWEEN_RETRYING_CONNECTIONs RuntimeError(sselfsbasenamestimeouts starttimesurisPyrostime((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys_get_pyro_proxy;s cCsJy|id7_Wntj od|_nXd|i|ifSdS(Niis%s.%s(sselfs current_idsAttributeErrors _parent_pid(sself((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys_get_idHs cCs|i||iƒƒdS(N(sselfs_register_fixturesfixtures_get_id(sselfsfixture((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pysrunOscCsG||ijpt‚||i|<|ii|ƒ|id7_dS(Ni(sidsselfs fixture_idssAssertionErrorsfixturesqueuesputs num_fixtures(sselfsfixturesid((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys_register_fixtureRs cCsjtiƒdjodSnx>td|iƒƒD]'}tiƒdjo|iƒq1q1W|iƒdS(Nii(sossforksxrangesselfs_num_processessis _client_code(sselfsi((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys_spawn_processesXscCst|i|iƒSdS(s2Don't spawn more processes than there are fixturesN(sminsselfs max_processess num_fixtures(sself((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys_num_processesdscCsRx*t|iƒƒD]}|iitƒqW|iƒ|iƒt i |ƒdS(N( sxrangesselfs_num_processessisqueuesputsNones_spawn_processess _server_codes BaseRunnersdone(sselfsi((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pysdonehs   cCs0dk}|iiƒ}|i|iƒ|SdS(N(s Pyro.coresPyroscoresObjBasesresults delegateTosselfsqueue(sselfsPyrosresult((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys _pyro_queueqs cCs0dk}|iiƒ}|i|iƒ|SdS(N(s Pyro.coresPyroscoresSynchronizedObjBasesresults delegateTosselfsreporter(sselfsPyrosresult((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys_pyro_reporterws cs¨dk}dk}t|i_|iidtƒ|iiddƒ}|i ˆi ƒˆi dƒƒ|i ˆiƒˆi dƒƒ|id‡d†ƒ|iƒdS( s(The Pyro server code, runs in the parentNsbannershosts localhostsqueuesreporters conditioncsˆiiƒ S(N(sselfsqueuesempty((sself(s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pysŠs(s Pyro.coresPyrosTruesconfigsPYRO_MOBILE_CODEscores initServersFalsesDaemonsdaemonsconnectsselfs _pyro_queues _pyro_names_pyro_reporters requestLoopsshutdown(sselfsPyrosdaemon((sselfs9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys _server_code}s cCs|idƒ}|idƒ}dkl}|ƒ}|i|ƒx7t|t dt i ƒD]}|i |}||ƒqZWdS(Nsqueuesreporter(s ReporterProxystimeout(sselfs_get_pyro_proxysqueuesremote_reporters testoob.reporting.reporter_proxys ReporterProxyslocal_reporters add_observers iter_queuesNones PyroRunners GET_TIMEOUTsids fixture_idssfixture(sselfsfixturesremote_reporterslocal_reportersqueues ReporterProxysid((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys _run_fixturess    cCs¢dk}dk}dk}t|i_|iidtƒdk }y|i ƒWn=|i i j o+|idtiƒIJ|idƒnX|idƒdS(s'The Pyro client code, runs in the childNsbanners>[Testoob+Pyro pid=%d] child lost connection to parent, exitingii(s Pyro.errorssPyros Pyro.coresTruesconfigsPYRO_MOBILE_CODEscores initClientsFalsessyssselfs _run_fixturesserrorssConnectionClosedErrorsstderrsossgetpidsexit(sselfssyssPyro((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys _client_codeœs  (s__name__s __module__s*SLEEP_INTERVAL_BETWEEN_RETRYING_CONNECTIONs GET_TIMEOUTs__init__s _pyro_names _pyroloc_uris_get_pyro_proxys_get_idsruns_register_fixtures_spawn_processess_num_processessdones _pyro_queues_pyro_reporters _server_codes _run_fixturess _client_code(((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys PyroRunner(s"          (s__doc__s __future__s generatorssoss iter_queues baserunners BaseRunners PyroRunner(s PyroRunnersoss BaseRunners generatorss iter_queue((s9build/bdist.linux-i686/egg/testoob/running/pyro_runner.pys?s     PK'ƒ5ï*ciúútestoob/running/baserunner.pyc;ò ×$Ec@s)dZdkZdefd„ƒYZdS(sUseful base class for runnersNs BaseRunnercBs2tZdZd„Zd„Zd„Zd„ZRS(s8default implementations of setting a reporter and done()cCs t|_dS(N(sNonesselfsreporter(sself((s8build/bdist.linux-i686/egg/testoob/running/baserunner.pys__init__scCs&tiiƒi|iƒ|iƒdS(N(stestoobsassertersAsserters set_reportersfixtures get_fixturesselfsreporter(sselfsfixture((s8build/bdist.linux-i686/egg/testoob/running/baserunner.pysrunscCs|iiƒdS(N(sselfsreportersdone(sself((s8build/bdist.linux-i686/egg/testoob/running/baserunner.pysdonescCs|iiƒSdS(N(sselfsreporters isSuccessful(sself((s8build/bdist.linux-i686/egg/testoob/running/baserunner.pys isSuccessful s(s__name__s __module__s__doc__s__init__srunsdones isSuccessful(((s8build/bdist.linux-i686/egg/testoob/running/baserunner.pys BaseRunners    (s__doc__stestoob.asserterstestoobsobjects BaseRunner(s BaseRunnerstestoob((s8build/bdist.linux-i686/egg/testoob/running/baserunner.pys?s PKЙá4Iƒ[ö}} testoob/running/listingrunner.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Runner that lists tests that would be run" from baserunner import BaseRunner class ListingRunner(BaseRunner): """Just list the test names, don't run them. """ def __init__(self, output_format=None): self.output_format = output_format self.history = _TestHistory() def run(self, fixture): self.history.record_fixture(fixture.get_fixture()) def done(self): if self.output_format == None: print self.history.get_string() elif self.output_format.lower() == "csv": print self.history.get_csv() class _TestHistory: def __init__(self): self.modules = {} def record_fixture(self, fixture): """Store the info about each fixture, to show them later. """ from testoob.reporting import TestInfo fixture_info = TestInfo(fixture) self._class_function_list(fixture_info).append(fixture_info.funcinfo()) def get_string(self): """Show all test methods. """ result = [] for (module_name, module_info) in self.modules.items(): result.append("Module: %s (%s)" % \ (module_name, module_info["filename"])) for (class_name, functions) in module_info["classes"].items(): result.append("\tClass: %s (%d test functions)" %\ (class_name, len(functions))) for func in functions: result.append("\t\t%s()%s%s" % \ (func[0], func[2], func[1] and " - "+func[1] or "")) return "\n".join(result) def get_csv(self): """Returns a CSV file structure for parsing. """ #FIXXXME may be i should add the path that needs to be in sys.path # in order to import the module.... result = ["file,module,class,method,docstring"] for (module_name, module_info) in self.modules.items(): for (class_name, functions) in module_info["classes"].items(): for func in functions: data = [module_info["filename"], module_name, class_name, func[0], func[1]] result.append(",".join(data)) return "\n".join(result) def _module(self, fixture_info): self.modules.setdefault( fixture_info.module(), { "filename": fixture_info.filename(), "classes": {} }) return self.modules[fixture_info.module()] def _class_function_list(self, fixture_info): classes_dict = self._module(fixture_info)["classes"] classes_dict.setdefault(fixture_info.classname(), []) return classes_dict[fixture_info.classname()] def _num_functions(self): result = 0 for mod_info in self.modules.values(): for functions in mod_info["classes"].values(): result += len(functions) return result PK/~c5ŒšBåpptestoob/running/convenience.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "convenience functions for running tests" from __future__ import generators import time ############################################################################### # apply_runner ############################################################################### from testoob.extracting import suite_iter as _suite_iter from testoob.extracting import full_extractor as _full_extractor def apply_decorators(callable, decorators): "Wrap the callable in all the decorators" result = callable for decorator in decorators: result = decorator(result) return result class TestLoop(object): "Runs the suites" def __init__(self, suites, runner, interval=None, stop_on_fail=False, extraction_decorators=None, fixture_decorators=None): from fixture_decorators import BaseFixture self.suites = suites self.runner = runner self.interval = interval self.stop_on_fail = stop_on_fail self.extraction_decorators = extraction_decorators or [] self.fixture_decorators = fixture_decorators or [BaseFixture] self.runner.reporter.setParameters(num_tests = self.num_tests) def _all_fixtures(self): for suite in _suite_iter(self.suites): for fixture in self.test_extractor(suite): yield fixture all_fixtures = property(_all_fixtures) def _num_tests(self): result = 0 for suite in _suite_iter(self.suites): result += len(list(self.test_extractor(suite))) return result num_tests = property(_num_tests) test_extractor = property( lambda self: apply_decorators(_full_extractor, self.extraction_decorators) ) def _run_fixture(self, fixture): decorated_fixture = apply_decorators(fixture, self.fixture_decorators) if hasattr(self, "not_first") and self.interval is not None: time.sleep(self.interval) self.not_first = True self.last_result = self.runner.run(decorated_fixture) def _handle_interrupt(self, fixture): from fixture_decorators import get_interrupterd_fixture if hasattr(self, "last_interrupt") and (time.time() - self.last_interrupt < 1): # Two interrupts in less than a second, cause all # future tests to skip self.fixture_decorators = [get_interrupterd_fixture()] self.last_interrupt = time.time() # Run the current test again with InterruptedFixture decorator # So it'll be added to the skipped tests' list. decorated_fixture = apply_decorators(fixture, [get_interrupterd_fixture(True)]) self.runner.run(decorated_fixture) def _run_all_fixtures(self): for fixture in self.all_fixtures: try: self._run_fixture(fixture) if self.stop_on_fail and not self.last_result: return except KeyboardInterrupt, e: self._handle_interrupt(fixture) def run(self): self.runner.reporter.start() self._run_all_fixtures() self.runner.done() return self.runner.isSuccessful() ############################################################################### # run ############################################################################### def run(suite=None, suites=None, **kwargs): "Convenience frontend for text_run_suites" if suite is None and suites is None: raise TypeError("either suite or suites must be specified") if suite is not None and suites is not None: raise TypeError("only one of suite or suites may be specified") if suites is None: suites = [suite] return run_suites(suites, **kwargs) def _apply_debug(reporter, runDebug): if runDebug is None: return reporter def replace(reporter, flavor, methodname): original = getattr(reporter, methodname) def replacement(test, err): runDebug(test, err, flavor, reporter, original) setattr(reporter, methodname, replacement) replace(reporter, "error", "addError") replace(reporter, "failure", "addFailure") return reporter def _create_reporter_proxy(reporters, runDebug, threads): from testoob.reporting import ReporterProxy result = ReporterProxy(threads) for reporter in reporters: result.add_observer(_apply_debug(reporter, runDebug)) return result def run_suites(suites, reporters, runner=None, runDebug=None, threads=None, **kwargs): "Run the test suites" if runner is None: from simplerunner import SimpleRunner runner = SimpleRunner() runner.reporter = _create_reporter_proxy(reporters, runDebug, threads=threads) return TestLoop(suites=suites, runner=runner, **kwargs).run() ############################################################################### # text_run ############################################################################### def text_run(*args, **kwargs): """ Run suites with a TextStreamReporter. Accepts keyword 'verbosity' (0, 1, 2 or 3, default is 1) and 'immediate' (True or False) """ from testoob.utils import _pop verbosity = _pop(kwargs, "verbosity", 1) immediate = _pop(kwargs, "immediate", False) coverage = _pop(kwargs, "coverage", (None, None)) silent = _pop(kwargs, "silent", False) kwargs.setdefault("reporters", []) # Always have at least one base reporter, so isSuccessful always works from testoob.reporting.base import BaseReporter kwargs["reporters"].append(BaseReporter()) import sys from testoob.reporting import TextStreamReporter reporter_class = _pop(kwargs, "reporter_class", TextStreamReporter) if not silent: reporter_instance = reporter_class( verbosity=verbosity, immediate=immediate, descriptions=1, stream=sys.stderr) kwargs["reporters"].append(reporter_instance) for reporter in kwargs["reporters"]: reporter.setCoverageInfo(*coverage) return run(*args, **kwargs) PKЙá4Ç3¥¡¡testoob/running/simplerunner.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Simple runner" from baserunner import BaseRunner class SimpleRunner(BaseRunner): "Simple runner, simply runs each test (what more do you need? :-)" def run(self, fixture): BaseRunner.run(self, fixture) fixture(self.reporter) return self.reporter.isSuccessful() PKЙá4hã±>||!testoob/running/threadedrunner.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Run tests in multiple threads" from baserunner import BaseRunner class ThreadedRunner(BaseRunner): "Run tests using a threadpool" def __init__(self, num_threads): BaseRunner.__init__(self) from threadpool import ThreadPool self.pool = ThreadPool(num_threads) self.pool.start() def run(self, fixture): BaseRunner.run(self, fixture) self.pool.dispatch(fixture, self.reporter) def done(self): self.pool.stop() BaseRunner.done(self) PKЙá4=YÓN~~testoob/running/pyro_runner.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Run tests in multiple processes, communicating with Pyro" from __future__ import generators import os def iter_queue(queue, sentinel, **kwargs): """ Iterate over a Queue.Queue instance until a sentinel is reached Will pass any extra keyword arguments to queue.get Created by Jimmy Retzlaff http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252498 """ while True: try: result = queue.get(**kwargs) except TypeError: # bad kwargs, probably timeout with Python < 2.3 result = queue.get() if result == sentinel: return yield result from baserunner import BaseRunner class PyroRunner(BaseRunner): SLEEP_INTERVAL_BETWEEN_RETRYING_CONNECTION = 0.5 GET_TIMEOUT = 20 # don't wait more than this for a test, on Python >= 2.3 def __init__(self, max_processes): BaseRunner.__init__(self) from Queue import Queue self.queue = Queue() self.max_processes = max_processes self.fixture_ids = {} self._parent_pid = os.getpid() self.num_fixtures = 0 def _pyro_name(self, basename): "Return the name mangled for use in Testoob's RPC" return ":testoob:%s:%s" % (basename, self._parent_pid) def _pyroloc_uri(self, basename): "Return the PYROLOC URI for the object, with proper mangling" return 'PYROLOC://localhost/%s' % self._pyro_name(basename) def _get_pyro_proxy(self, basename, timeout=40): "Safely try to get a proxy to the object, looping until timing out" import time, Pyro.core, Pyro.errors uri = self._pyroloc_uri(basename) starttime = time.time() while time.time() - starttime <= timeout: try: return Pyro.core.getProxyForURI(uri).getProxy() except Pyro.errors.ProtocolError: # object at the URI is unavailable, sleep a little time.sleep(PyroRunner.SLEEP_INTERVAL_BETWEEN_RETRYING_CONNECTION) raise RuntimeError("getting the proxy has timed out") def _get_id(self): try: self.current_id += 1 except AttributeError: self.current_id = 0 return "%s.%s" % (self._parent_pid, self.current_id) def run(self, fixture): self._register_fixture(fixture, self._get_id()) def _register_fixture(self, fixture, id): assert id not in self.fixture_ids self.fixture_ids[id] = fixture self.queue.put(id) self.num_fixtures += 1 def _spawn_processes(self): # fork first child if os.fork() != 0: return # parent # fork the rest for i in xrange(1, self._num_processes()): if os.fork() == 0: # child self._client_code() # run the client code on the first child too self._client_code() def _num_processes(self): "Don't spawn more processes than there are fixtures" return min(self.max_processes, self.num_fixtures) def done(self): for i in xrange(self._num_processes()): self.queue.put(None) self._spawn_processes() self._server_code() BaseRunner.done(self) def _pyro_queue(self): import Pyro.core result = Pyro.core.ObjBase() result.delegateTo(self.queue) return result def _pyro_reporter(self): import Pyro.core result = Pyro.core.SynchronizedObjBase() result.delegateTo(self.reporter) return result def _server_code(self): "The Pyro server code, runs in the parent" import Pyro.core, Pyro Pyro.config.PYRO_MOBILE_CODE = True Pyro.core.initServer(banner=False) daemon = Pyro.core.Daemon(host="localhost") daemon.connect(self._pyro_queue(), self._pyro_name("queue")) daemon.connect(self._pyro_reporter(), self._pyro_name("reporter")) # == running daemon.requestLoop(condition=lambda:not self.queue.empty()) # == cleanup daemon.shutdown() def _run_fixtures(self): queue = self._get_pyro_proxy("queue") remote_reporter = self._get_pyro_proxy("reporter") from testoob.reporting.reporter_proxy import ReporterProxy local_reporter = ReporterProxy() local_reporter.add_observer(remote_reporter) for id in iter_queue(queue, None, timeout=PyroRunner.GET_TIMEOUT): fixture = self.fixture_ids[id] fixture(local_reporter) def _client_code(self): "The Pyro client code, runs in the child" import Pyro.errors, Pyro.core, Pyro Pyro.config.PYRO_MOBILE_CODE = True Pyro.core.initClient(banner=False) import sys try: self._run_fixtures() except Pyro.errors.ConnectionClosedError: # report the error gracefully print >>sys.stderr, "[Testoob+Pyro pid=%d] " \ "child lost connection to parent, exiting" % os.getpid() sys.exit(1) sys.exit(0) # everything was successful PK'ƒ5®²E]7#7#testoob/running/convenience.pyc;ò ëHKEc@s•dZdklZdkZdklZdklZd„Z de fd„ƒYZ e e d„Z d „Zd „Ze e e d „Zd „ZdS( s'convenience functions for running tests(s generatorsN(s suite_iter(sfull_extractorcCs+|}x|D]}||ƒ}q W|SdS(s'Wrap the callable in all the decoratorsN(scallablesresults decoratorss decorator(scallables decoratorssresults decorator((s9build/bdist.linux-i686/egg/testoob/running/convenience.pysapply_decoratorss sTestLoopcBs€tZdZeeeed„Zd„ZeeƒZd„Z ee ƒZ ed„ƒZ d„Z d„Z d„Zd„ZRS( sRuns the suitescCsqdkl}||_||_||_||_|pg|_|p|g|_|iii d|i ƒdS(N(s BaseFixtures num_tests( sfixture_decoratorss BaseFixturessuitessselfsrunnersintervals stop_on_failsextraction_decoratorssreporters setParameterss num_tests(sselfssuitessrunnersintervals stop_on_failsextraction_decoratorssfixture_decoratorss BaseFixture((s9build/bdist.linux-i686/egg/testoob/running/convenience.pys__init__%s     ccs<x5t|iƒD]$}x|i|ƒD] }|Vq&WqWdS(N(s _suite_itersselfssuitesssuitestest_extractorsfixture(sselfssuitesfixture((s9build/bdist.linux-i686/egg/testoob/running/convenience.pys _all_fixtures3s cCsGd}x6t|iƒD]%}|tt|i|ƒƒƒ7}qW|SdS(Ni(sresults _suite_itersselfssuitesssuiteslensliststest_extractor(sselfsresultssuite((s9build/bdist.linux-i686/egg/testoob/running/convenience.pys _num_tests9s #cCstt|iƒS(N(sapply_decoratorss_full_extractorsselfsextraction_decorators(sself((s9build/bdist.linux-i686/egg/testoob/running/convenience.pysAscCsht||iƒ}t|dƒo |itj oti |iƒnt |_ |i i |ƒ|_dS(Ns not_first(sapply_decoratorssfixturesselfsfixture_decoratorssdecorated_fixtureshasattrsintervalsNonestimessleepsTrues not_firstsrunnersruns last_result(sselfsfixturesdecorated_fixture((s9build/bdist.linux-i686/egg/testoob/running/convenience.pys _run_fixtureDs   cCs…dkl}t|dƒotiƒ|idjo|ƒg|_ntiƒ|_t||tƒgƒ}|i i |ƒdS(N(sget_interrupterd_fixtureslast_interrupti( sfixture_decoratorssget_interrupterd_fixtureshasattrsselfstimeslast_interruptsapply_decoratorssfixturesTruesdecorated_fixturesrunnersrun(sselfsfixturesdecorated_fixturesget_interrupterd_fixture((s9build/bdist.linux-i686/egg/testoob/running/convenience.pys_handle_interruptKs  *cCskxd|iD]Y}y.|i|ƒ|io|i odSnWq tj o}|i|ƒq Xq WdS(N( sselfs all_fixturessfixtures _run_fixtures stop_on_fails last_resultsKeyboardInterruptses_handle_interrupt(sselfsesfixture((s9build/bdist.linux-i686/egg/testoob/running/convenience.pys_run_all_fixturesXs   cCs8|iiiƒ|iƒ|iiƒ|iiƒSdS(N(sselfsrunnersreportersstarts_run_all_fixturessdones isSuccessful(sself((s9build/bdist.linux-i686/egg/testoob/running/convenience.pysrunas  (s__name__s __module__s__doc__sNonesFalses__init__s _all_fixturesspropertys all_fixturess _num_testss num_testsstest_extractors _run_fixtures_handle_interrupts_run_all_fixturessrun(((s9build/bdist.linux-i686/egg/testoob/running/convenience.pysTestLoop#s       cKs|tjo |tjotdƒ‚n|tj o |tj otdƒ‚n|tjo |g}nt||SdS(s(Convenience frontend for text_run_suitess(either suite or suites must be specifieds,only one of suite or suites may be specifiedN(ssuitesNonessuitess TypeErrors run_suitesskwargs(ssuitessuitesskwargs((s9build/bdist.linux-i686/egg/testoob/running/convenience.pysrunjs  csIˆtjo|Sn‡d†}||ddƒ||ddƒ|SdS(Ncs8tˆ|ƒ‰‡‡‡‡d†}tˆ||ƒdS(Ncsˆ||ˆˆˆƒdS(N(srunDebugstestserrsflavorsreportersoriginal(stestserr(sreportersrunDebugsflavorsoriginal(s9build/bdist.linux-i686/egg/testoob/running/convenience.pys replacement|s(sgetattrsreporters methodnamesoriginals replacementssetattr(sreportersflavors methodnamesoriginals replacement(srunDebug(sreportersflavorsoriginals9build/bdist.linux-i686/egg/testoob/running/convenience.pysreplacezsserrorsaddErrorsfailures addFailure(srunDebugsNonesreportersreplace(sreportersrunDebugsreplace((srunDebugs9build/bdist.linux-i686/egg/testoob/running/convenience.pys _apply_debugvs   cCsHdkl}||ƒ}x$|D]}|it||ƒƒq W|SdS(N(s ReporterProxy( stestoob.reportings ReporterProxysthreadssresults reporterssreporters add_observers _apply_debugsrunDebug(s reporterssrunDebugsthreadssreportersresults ReporterProxy((s9build/bdist.linux-i686/egg/testoob/running/convenience.pys_create_reporter_proxy…s   cKs_|tjodkl}|ƒ}nt||d|ƒ|_t d|d||i ƒSdS(sRun the test suites(s SimpleRunnersthreadsssuitessrunnerN( srunnersNones simplerunners SimpleRunners_create_reporter_proxys reporterssrunDebugsthreadssreportersTestLoopssuitesskwargssrun(ssuitess reporterssrunnersrunDebugsthreadsskwargss SimpleRunner((s9build/bdist.linux-i686/egg/testoob/running/convenience.pys run_suitesŒs    c Os(dkl}||ddƒ}||dtƒ}||dttfƒ} ||dtƒ}|i dgƒdk l } |di | ƒƒd k }d kl} ||d | ƒ}| o9|d|d|d dd |iƒ} |di | ƒnx|dD]}|i| ŒqWt||ŽSd S(s Run suites with a TextStreamReporter. Accepts keyword 'verbosity' (0, 1, 2 or 3, default is 1) and 'immediate' (True or False) (s_pops verbosityis immediatescoveragessilents reporters(s BaseReporterN(sTextStreamReportersreporter_classs descriptionssstream(s testoob.utilss_popskwargss verbositysFalses immediatesNonescoveragessilents setdefaultstestoob.reporting.bases BaseReportersappendssysstestoob.reportingsTextStreamReportersreporter_classsstderrsreporter_instancesreporterssetCoverageInfosrunsargs( sargsskwargsssilentsreportersreporter_classs verbositys_pops immediatessyss BaseReporterscoveragesTextStreamReportersreporter_instance((s9build/bdist.linux-i686/egg/testoob/running/convenience.pystext_run˜s,      (s__doc__s __future__s generatorsstimestestoob.extractings suite_iters _suite_itersfull_extractors_full_extractorsapply_decoratorssobjectsTestLoopsNonesruns _apply_debugs_create_reporter_proxys run_suitesstext_run( s_full_extractors run_suitessruns_create_reporter_proxys _suite_iterstext_runs generatorssTestLoopstimesapply_decoratorss _apply_debug((s9build/bdist.linux-i686/egg/testoob/running/convenience.pys?s     G   PK˜*5 UÙBŸŸtestoob/running/__init__.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "test running logic" from baserunner import BaseRunner from simplerunner import SimpleRunner from threadedrunner import ThreadedRunner from processedrunner import ProcessedRunner from listingrunner import ListingRunner from pyro_runner import PyroRunner from convenience import run, text_run PKЙá4peñ"testoob/running/processedrunner.py# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Run tests in processes" from baserunner import BaseRunner class ProcessedRunner(BaseRunner): "Run tests using fork in different processes." def __init__(self, max_processes=1): from processed_helper import ProcessedRunnerHelper BaseRunner.__init__(self) self._helper = ProcessedRunnerHelper(max_processes) def run(self, fixture): BaseRunner.run(self, fixture) self._helper.register_fixture(fixture) def done(self): self._helper.start(self.reporter) BaseRunner.done(self) PK'ƒ5Aýtt testoob/running/simplerunner.pyc;ò iŸ¦Dc@s-dZdklZdefd„ƒYZdS(s Simple runner(s BaseRunners SimpleRunnercBstZdZd„ZRS(s@Simple runner, simply runs each test (what more do you need? :-)cCs.ti||ƒ||iƒ|iiƒSdS(N(s BaseRunnersrunsselfsfixturesreporters isSuccessful(sselfsfixture((s:build/bdist.linux-i686/egg/testoob/running/simplerunner.pysruns (s__name__s __module__s__doc__srun(((s:build/bdist.linux-i686/egg/testoob/running/simplerunner.pys SimpleRunners N(s__doc__s baserunners BaseRunners SimpleRunner(s SimpleRunners BaseRunner((s:build/bdist.linux-i686/egg/testoob/running/simplerunner.pys?s PK'ƒ5Õ˜håå"testoob/running/threadedrunner.pyc;ò iŸ¦Dc@s-dZdklZdefd„ƒYZdS(sRun tests in multiple threads(s BaseRunnersThreadedRunnercBs)tZdZd„Zd„Zd„ZRS(sRun tests using a threadpoolcCs:ti|ƒdkl}||ƒ|_|iiƒdS(N(s ThreadPool(s BaseRunners__init__sselfs threadpools ThreadPools num_threadsspoolsstart(sselfs num_threadss ThreadPool((s<build/bdist.linux-i686/egg/testoob/running/threadedrunner.pys__init__s  cCs*ti||ƒ|ii||iƒdS(N(s BaseRunnersrunsselfsfixturespoolsdispatchsreporter(sselfsfixture((s<build/bdist.linux-i686/egg/testoob/running/threadedrunner.pysrunscCs|iiƒti|ƒdS(N(sselfspoolsstops BaseRunnersdone(sself((s<build/bdist.linux-i686/egg/testoob/running/threadedrunner.pysdone!s (s__name__s __module__s__doc__s__init__srunsdone(((s<build/bdist.linux-i686/egg/testoob/running/threadedrunner.pysThreadedRunners   N(s__doc__s baserunners BaseRunnersThreadedRunner(sThreadedRunners BaseRunner((s<build/bdist.linux-i686/egg/testoob/running/threadedrunner.pys?s PK'ƒ5w„testoob/running/threadpool.pyc;ò iŸ¦Dc@sddZdkZdkZdkZdefd„ƒYZdfd„ƒYZdefd„ƒYZdS(s= Supply a ThreadPool, dispatching work to different threads. NsErrorcBstZdZRS(s General threadpool error (s__name__s __module__s__doc__(((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pysErrors s_DismissalLettercBstZdZRS(s' Sent to a worker thread to dismiss it (s__name__s __module__s__doc__(((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pys_DismissalLetters s ThreadPoolcBs›tZdZded„Zd„Zd„Zd„Zed„ƒZ d„Z ed„e d d ƒZ ed „ƒZ d „Z d „Zd„Zd„ZRS(s¿ I'm a simple thread pool using constant size. To run a function in a thread, call dispatch() with a callable and optional arguments and keywords. callable must be thread safe! Usage:: p = ThreadPool(10) p.start() try: p.dispatch(callable, foo, bar="baz") ... finally: p.stop() The pool keeps a constant number of worker threads active while its running, and dismiss all of them when you stop it. The pool can be stopped and started as needed. Before exiting the application, the pool must be stopped. Use try finally to make sure your app will quit. You can resize the pool while its running by modifying the size attribute. Unhandled exceptions in code executed by worker threads are printed to the pool logFile, defaulting to sys.stderr. The pool itself is NOT thread safe, and should be accessed by only one thread. i cCsEtiƒ|_g|_t|_|i|ƒ|pt i |_dS(sš Initialize a pool @param size: number of threads to employ. @param logFile: where exceptions go (default to sys.stderr) N( sQueuesselfs_queues_workerssFalses_runningssetSizessizeslogFilessyssstderr(sselfssizeslogFile((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pys__init__Cs    cCsK|iotdƒ‚nx!t|iƒD]}|iƒq*Wt|_dS(sp Start a pool with size worker threads. Raise threadpool.Error if the pool is already running. sthe pool is already running.N(sselfs_runningsErrorsranges_sizesworkers _employWorkersTrue(sselfsworker((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pysstartUs cCsh|i otdƒ‚n|i}x|D]}|iƒq,Wx|D]}|iƒqGWt|_dS(sÔ Stop a pool. All workers are dismissed. Will block until all the workers finished their assignment, which can take some time. Raise threadpool.Error if the pool is not running. sthe pool is not running.N( sselfs_runningsErrors_workerssworkerssworkers_dismissWorkersjoinsFalse(sselfsworkersworkers((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pysstopas  cOs8|i otdƒ‚n|ii|||fƒdS(sè Add callable to the work queue. Raise threadpool.Error if the pool is not running. @param callable: a callable @param args: arguments for callable @param kw: keyword arguments for callable sthe pool is not running.N(sselfs_runningsErrors_queuesputscallablesargsskw(sselfscallablesargsskw((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pysdispatchws cCs|iS(N(sselfs_running(sself((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pysˆscCsF|djp td‚||_|io|iƒ|iƒndS(Nis,at least one worker threads must be employed(scountsAssertionErrorsselfs_sizes_runningsstopsstart(sselfscount((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pyssetSizeŠs    cCs|iS(N(sselfs_size(sself((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pys‘ssdocsnumber of worker threadscCs t|iƒS(N(slensselfs_workers(sself((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pys”scCs|iiƒSdS(s Return True if the queue is empty, False otherwise. Because of multithreading semantics, this is not reliable. N(sselfs_queuesempty(sself((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pys queueEmpty–scCs™tiƒ}xvnon|iiƒ\}}}|t joPny|||ŽWn#dk }|i d|i ƒnX~~~qW|i i|ƒdS(s3 Loop forever, trying to get work from, the queue. iNsfile(s threadings currentThreadsmesselfs_queuesgetscallablesargsskws_DismissalLetters tracebacks print_excslogFiles_workerssremove(sselfsmes tracebacksargsscallableskw((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pys_workerMainLoop s   cCs3tid|iƒ}|ii|ƒ|iƒdS(Nstarget(s threadingsThreadsselfs_workerMainLoopsts_workerssappendsstart(sselfst((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pys _employWorker°scCs|itƒdS(s- Dismiss the unfortunate next waiting worker N(sselfsdispatchs_DismissalLetter(sself((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pys_dismissWorkerµs(s__name__s __module__s__doc__sNones__init__sstartsstopsdispatchspropertysrunningssetSizessizesworkerss queueEmptys_workerMainLoops _employWorkers_dismissWorker(((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pys ThreadPool s        ( s__doc__ssyss threadingsQueues ExceptionsErrors_DismissalLettersobjects ThreadPool(sQueues ThreadPools_DismissalLetterssyss threadingsError((s8build/bdist.linux-i686/egg/testoob/running/threadpool.pys?s    PKšá4S¿gEVV(testoob/compatibility/SimpleXMLWriter.py# This file is taken from the ElementTree project, # http://effbot.org/zone/element-index.htm # SimpleXMLWriter # $Id: SimpleXMLWriter.py 1862 2004-06-18 07:31:02Z Fredrik $ # # a simple XML writer # # history: # 2001-12-28 fl created # 2002-11-25 fl fixed attribute encoding # 2002-12-02 fl minor fixes for 1.5.2 # 2004-06-17 fl added pythondoc markup # # Copyright (c) 2001-2004 by Fredrik Lundh # # fredrik@pythonware.com # http://www.pythonware.com # # -------------------------------------------------------------------- # The SimpleXMLWriter module is # # Copyright (c) 2001-2004 by Fredrik Lundh # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # -------------------------------------------------------------------- ## # Tools to write XML files, without having to deal with encoding # issues, well-formedness, etc. #

# The current version does not provide built-in support for # namespaces. To create files using namespaces, you have to provide # "xmlns" attributes and explicitly add prefixes to tags and # attributes. # #

Patterns

# # The following example generates a small XHTML document. #
#
# from elementtree.SimpleXMLWriter import XMLWriter
# import sys
#
# w = XMLWriter(sys.stdout)
#
# html = w.start("html")
#
# w.start("head")
# w.element("title", "my document")
# w.element("meta", name="generator", value="my application 1.0")
# w.end()
#
# w.start("body")
# w.element("h1", "this is a heading")
# w.element("p", "this is a paragraph")
#
# w.start("p")
# w.data("this is ")
# w.element("b", "bold")
# w.data(" and ")
# w.element("i", "italic")
# w.data(".")
# w.end("p")
#
# w.close(html)
# 
## import re, sys, string try: unicode("") except NameError: def encode(s, encoding): # 1.5.2: application must use the right encoding return s _escape = re.compile(r"[&<>\"\x80-\xff]+") # 1.5.2 else: def encode(s, encoding): return s.encode(encoding) _escape = re.compile(eval(r'u"[&<>\"\u0080-\uffff]+"')) def encode_entity(text, pattern=_escape): # map reserved and non-ascii characters to numerical entities def escape_entities(m): out = [] for char in m.group(): out.append("&#%d;" % ord(char)) return string.join(out, "") return encode(pattern.sub(escape_entities, text), "ascii") del _escape # # the following functions assume an ascii-compatible encoding # (or "utf-16") def escape_cdata(s, encoding=None, replace=string.replace): s = replace(s, "&", "&") s = replace(s, "<", "<") s = replace(s, ">", ">") if encoding: try: return encode(s, encoding) except UnicodeError: return encode_entity(s) return s def escape_attrib(s, encoding=None, replace=string.replace): s = replace(s, "&", "&") s = replace(s, "'", "'") s = replace(s, "\"", """) s = replace(s, "<", "<") s = replace(s, ">", ">") if encoding: try: return encode(s, encoding) except UnicodeError: return encode_entity(s) return s ## # XML writer class. # # @param file A file or file-like object. This object must implement # a write method that takes an 8-bit string. # @param encoding Optional encoding. class XMLWriter: def __init__(self, file, encoding="us-ascii"): self.__write = file.write self.__open = 0 # true if start tag is open self.__tags = [] self.__data = [] self.__encoding = encoding def __flush(self): if self.__open: self.__write(">") self.__open = 0 if self.__data: data = string.join(self.__data, "") self.__write(escape_cdata(data, self.__encoding)) self.__data = [] ## # Opens a new element. Attributes can be given as keyword # arguments, or as a string/string dictionary. You can pass in # 8-bit strings or Unicode strings; the former are assumed to use # the encoding passed to the constructor. The method returns an # opaque identifier that can be passed to the close method, # to close all open elements up to and including this one. # # @param tag Element tag. # @param attrib Attribute dictionary. Alternatively, attributes # can be given as keyword arguments. # @return An element identifier. def start(self, tag, attrib={}, **extra): self.__flush() tag = escape_cdata(tag, self.__encoding) self.__data = [] self.__tags.append(tag) self.__write("<%s" % tag) if attrib or extra: attrib = attrib.copy() attrib.update(extra) attrib = attrib.items() attrib.sort() for k, v in attrib: k = escape_cdata(k, self.__encoding) v = escape_attrib(v, self.__encoding) self.__write(" %s=\"%s\"" % (k, v)) self.__open = 1 return len(self.__tags)-1 ## # Adds a comment to the output stream. # # @param comment Comment text, as an 8-bit string or Unicode string. def comment(self, comment): self.__flush() self.__write("\n" % escape_cdata(comment, self.__encoding)) ## # Adds character data to the output stream. # # @param text Character data, as an 8-bit string or Unicode string. def data(self, text): self.__data.append(text) ## # Closes the current element (opened by the most recent call to # start). # # @param tag Element tag. If given, the tag must match the start # tag. If omitted, the current element is closed. def end(self, tag=None): if tag: assert self.__tags, "unbalanced end(%s)" % tag assert escape_cdata(tag, self.__encoding) == self.__tags[-1],\ "expected end(%s), got %s" % (self.__tags[-1], tag) else: assert self.__tags, "unbalanced end()" tag = self.__tags.pop() if self.__data: self.__flush() elif self.__open: self.__open = 0 self.__write(" />") return self.__write("" % tag) ## # Closes open elements, up to (and including) the element identified # by the given identifier. # # @param id Element identifier, as returned by the start method. def close(self, id): while len(self.__tags) > id: self.end() ## # Adds an entire element. This is the same as calling start, # data, and end in sequence. The text argument # can be omitted. def element(self, tag, text=None, attrib={}, **extra): apply(self.start, (tag, attrib), extra) if text: self.data(text) self.end() PK'ƒ50ôÈaŸŸ)testoob/compatibility/SimpleXMLWriter.pyc;ò ÊŸ¦Dc@s¿dkZdkZdkZyedƒWn+ej od„ZeidƒZn Xd„ZeiedƒƒZed„Z [e ei d„Z e ei d„Z d fd „ƒYZdS( NscCs|SdS(N(ss(sssencoding((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pysencode_ss[&<>\"\x80-\xff]+cCs|i|ƒSdS(N(sssencodesencoding(sssencoding((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pysencodedssu"[&<>\"\u0080-\uffff]+"cCs&d„}t|i||ƒdƒSdS(NcCsHg}x+|iƒD]}|idt|ƒƒqWti|dƒSdS(Ns&#%d;s(soutsmsgroupscharsappendsordsstringsjoin(smscharsout((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pysescape_entitiesjs  sascii(sescape_entitiessencodespatternssubstext(stextspatternsescape_entities((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pys encode_entityhs cCsz||ddƒ}||ddƒ}||ddƒ}|o5yt||ƒSWqrtj ot|ƒSqrXn|SdS(Ns&s&ss>(sreplacesssencodingsencodes UnicodeErrors encode_entity(sssencodingsreplace((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pys escape_cdatawscCsž||ddƒ}||ddƒ}||ddƒ}||ddƒ}||d d ƒ}|o5yt||ƒSWq–tj ot|ƒSq–Xn|SdS( Ns&s&s's's"s"ss>(sreplacesssencodingsencodes UnicodeErrors encode_entity(sssencodingsreplace((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pys escape_attrib‚ss XMLWritercBs_tZdd„Zd„Zhd„Zd„Zd„Zed„Zd„Z ehd „Z RS( Nsus-asciicCs4|i|_d|_g|_g|_||_dS(Ni( sfileswritesselfs_XMLWriter__writes_XMLWriter__opens_XMLWriter__tagss_XMLWriter__datasencodings_XMLWriter__encoding(sselfsfilesencoding((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pys__init__˜s     cCsm|io|idƒd|_n|io;ti|idƒ}|it||iƒƒg|_ndS(Ns>is( sselfs_XMLWriter__opens_XMLWriter__writes_XMLWriter__datasstringsjoinsdatas escape_cdatas_XMLWriter__encoding(sselfsdata((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pys__flushŸs    cKs÷|iƒt||iƒ}g|_|ii|ƒ|id|ƒ|p|o…|i ƒ}|i |ƒ|i ƒ}|iƒxS|D]G\}}t||iƒ}t||iƒ}|id||fƒqŠWnd|_t|iƒdSdS(Ns<%ss %s="%s"i(sselfs_XMLWriter__flushs escape_cdatastags_XMLWriter__encodings_XMLWriter__datas_XMLWriter__tagssappends_XMLWriter__writesattribsextrascopysupdatesitemsssortsksvs escape_attribs_XMLWriter__openslen(sselfstagsattribsextrasvsk((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pysstartµs"        cCs+|iƒ|idt||iƒƒdS(Ns (sselfs_XMLWriter__flushs_XMLWriter__writes escape_cdatascomments_XMLWriter__encoding(sselfscomment((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pyscommentÌs cCs|ii|ƒdS(N(sselfs_XMLWriter__datasappendstext(sselfstext((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pysdataÕscCsÖ|oW|iptd|‚t||iƒ|idjptd|id|f‚n|ip td‚|iiƒ}|io|iƒn)|i od|_ |i dƒdSn|i d|ƒdS(Nsunbalanced end(%s)iÿÿÿÿsexpected end(%s), got %ssunbalanced end()is />s( stagsselfs_XMLWriter__tagssAssertionErrors escape_cdatas_XMLWriter__encodingspops_XMLWriter__datas_XMLWriter__flushs_XMLWriter__opens_XMLWriter__write(sselfstag((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pysendßs?    cCs,x%t|iƒ|jo|iƒqWdS(N(slensselfs_XMLWriter__tagssidsend(sselfsid((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pyscloseõscKs?t|i||f|ƒ|o|i|ƒn|iƒdS(N( sapplysselfsstartstagsattribsextrastextsdatasend(sselfstagstextsattribsextra((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pyselementþs( s__name__s __module__s__init__s_XMLWriter__flushsstartscommentsdatasNonesendscloseselement(((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pys XMLWriter–s     (sressyssstringsunicodes NameErrorsencodescompiles_escapesevals encode_entitysNonesreplaces escape_cdatas escape_attribs XMLWriter( s XMLWritersstrings escape_cdatassyssres escape_attribsencodes_escapes encode_entity((sCbuild/bdist.linux-i686/egg/testoob/compatibility/SimpleXMLWriter.pys?Zs    PKšá4 ´‘¢¨L¨Ltestoob/compatibility/sets.py"""Classes to represent arbitrary sets (including sets of sets). This module implements sets using dictionaries whose values are ignored. The usual operations (union, intersection, deletion, etc.) are provided as both methods and operators. Important: sets are not sequences! While they support 'x in s', 'len(s)', and 'for x in s', none of those operations are unique for sequences; for example, mappings support all three as well. The characteristic operation for sequences is subscripting with small integers: s[i], for i in range(len(s)). Sets don't support subscripting at all. Also, sequences allow multiple occurrences and their elements have a definite order; sets on the other hand don't record multiple occurrences and don't remember the order of element insertion (which is why they don't support s[i]). The following classes are provided: BaseSet -- All the operations common to both mutable and immutable sets. This is an abstract class, not meant to be directly instantiated. Set -- Mutable sets, subclass of BaseSet; not hashable. ImmutableSet -- Immutable sets, subclass of BaseSet; hashable. An iterable argument is mandatory to create an ImmutableSet. _TemporarilyImmutableSet -- A wrapper around a Set, hashable, giving the same hash value as the immutable set equivalent would have. Do not use this class directly. Only hashable objects can be added to a Set. In particular, you cannot really add a Set as an element to another Set; if you try, what is actually added is an ImmutableSet built from it (it compares equal to the one you tried adding). When you ask if `x in y' where x is a Set and y is a Set or ImmutableSet, x is wrapped into a _TemporarilyImmutableSet z, and what's tested is actually `z in y'. """ # Code history: # # - Greg V. Wilson wrote the first version, using a different approach # to the mutable/immutable problem, and inheriting from dict. # # - Alex Martelli modified Greg's version to implement the current # Set/ImmutableSet approach, and make the data an attribute. # # - Guido van Rossum rewrote much of the code, made some API changes, # and cleaned up the docstrings. # # - Raymond Hettinger added a number of speedups and other # improvements. from __future__ import generators try: from itertools import ifilter, ifilterfalse except ImportError: # Code to make the module run under Py2.2 def ifilter(predicate, iterable): if predicate is None: def predicate(x): return x for x in iterable: if predicate(x): yield x def ifilterfalse(predicate, iterable): if predicate is None: def predicate(x): return x for x in iterable: if not predicate(x): yield x try: True, False except NameError: True, False = (0==0, 0!=0) __all__ = ['BaseSet', 'Set', 'ImmutableSet'] class BaseSet(object): """Common base class for mutable and immutable sets.""" __slots__ = ['_data'] # Constructor def __init__(self): """This is an abstract class.""" # Don't call this from a concrete subclass! if self.__class__ is BaseSet: raise TypeError, ("BaseSet is an abstract class. " "Use Set or ImmutableSet.") # Standard protocols: __len__, __repr__, __str__, __iter__ def __len__(self): """Return the number of elements of a set.""" return len(self._data) def __repr__(self): """Return string representation of a set. This looks like 'Set([])'. """ return self._repr() # __str__ is the same as __repr__ __str__ = __repr__ def _repr(self, sorted=False): elements = self._data.keys() if sorted: elements.sort() return '%s(%r)' % (self.__class__.__name__, elements) def __iter__(self): """Return an iterator over the elements or a set. This is the keys iterator for the underlying dict. """ return self._data.iterkeys() # Three-way comparison is not supported. However, because __eq__ is # tried before __cmp__, if Set x == Set y, x.__eq__(y) returns True and # then cmp(x, y) returns 0 (Python doesn't actually call __cmp__ in this # case). def __cmp__(self, other): raise TypeError, "can't compare sets using cmp()" # Equality comparisons using the underlying dicts. Mixed-type comparisons # are allowed here, where Set == z for non-Set z always returns False, # and Set != z always True. This allows expressions like "x in y" to # give the expected result when y is a sequence of mixed types, not # raising a pointless TypeError just because y contains a Set, or x is # a Set and y contain's a non-set ("in" invokes only __eq__). # Subtle: it would be nicer if __eq__ and __ne__ could return # NotImplemented instead of True or False. Then the other comparand # would get a chance to determine the result, and if the other comparand # also returned NotImplemented then it would fall back to object address # comparison (which would always return False for __eq__ and always # True for __ne__). However, that doesn't work, because this type # *also* implements __cmp__: if, e.g., __eq__ returns NotImplemented, # Python tries __cmp__ next, and the __cmp__ here then raises TypeError. def __eq__(self, other): if isinstance(other, BaseSet): return self._data == other._data else: return False def __ne__(self, other): if isinstance(other, BaseSet): return self._data != other._data else: return True # Copying operations def copy(self): """Return a shallow copy of a set.""" result = self.__class__() result._data.update(self._data) return result __copy__ = copy # For the copy module def __deepcopy__(self, memo): """Return a deep copy of a set; used by copy module.""" # This pre-creates the result and inserts it in the memo # early, in case the deep copy recurses into another reference # to this same set. A set can't be an element of itself, but # it can certainly contain an object that has a reference to # itself. from copy import deepcopy result = self.__class__() memo[id(self)] = result data = result._data value = True for elt in self: data[deepcopy(elt, memo)] = value return result # Standard set operations: union, intersection, both differences. # Each has an operator version (e.g. __or__, invoked with |) and a # method version (e.g. union). # Subtle: Each pair requires distinct code so that the outcome is # correct when the type of other isn't suitable. For example, if # we did "union = __or__" instead, then Set().union(3) would return # NotImplemented instead of raising TypeError (albeit that *why* it # raises TypeError as-is is also a bit subtle). def __or__(self, other): """Return the union of two sets as a new set. (I.e. all elements that are in either set.) """ if not isinstance(other, BaseSet): return NotImplemented return self.union(other) def union(self, other): """Return the union of two sets as a new set. (I.e. all elements that are in either set.) """ result = self.__class__(self) result._update(other) return result def __and__(self, other): """Return the intersection of two sets as a new set. (I.e. all elements that are in both sets.) """ if not isinstance(other, BaseSet): return NotImplemented return self.intersection(other) def intersection(self, other): """Return the intersection of two sets as a new set. (I.e. all elements that are in both sets.) """ if not isinstance(other, BaseSet): other = Set(other) if len(self) <= len(other): little, big = self, other else: little, big = other, self common = ifilter(big._data.has_key, little) return self.__class__(common) def __xor__(self, other): """Return the symmetric difference of two sets as a new set. (I.e. all elements that are in exactly one of the sets.) """ if not isinstance(other, BaseSet): return NotImplemented return self.symmetric_difference(other) def symmetric_difference(self, other): """Return the symmetric difference of two sets as a new set. (I.e. all elements that are in exactly one of the sets.) """ result = self.__class__() data = result._data value = True selfdata = self._data try: otherdata = other._data except AttributeError: otherdata = Set(other)._data for elt in ifilterfalse(otherdata.has_key, selfdata): data[elt] = value for elt in ifilterfalse(selfdata.has_key, otherdata): data[elt] = value return result def __sub__(self, other): """Return the difference of two sets as a new Set. (I.e. all elements that are in this set and not in the other.) """ if not isinstance(other, BaseSet): return NotImplemented return self.difference(other) def difference(self, other): """Return the difference of two sets as a new Set. (I.e. all elements that are in this set and not in the other.) """ result = self.__class__() data = result._data try: otherdata = other._data except AttributeError: otherdata = Set(other)._data value = True for elt in ifilterfalse(otherdata.has_key, self): data[elt] = value return result # Membership test def __contains__(self, element): """Report whether an element is a member of a set. (Called in response to the expression `element in self'.) """ try: return element in self._data except TypeError: transform = getattr(element, "__as_temporarily_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught return transform() in self._data # Subset and superset test def issubset(self, other): """Report whether another set contains this set.""" self._binary_sanity_check(other) if len(self) > len(other): # Fast check for obvious cases return False for elt in ifilterfalse(other._data.has_key, self): return False return True def issuperset(self, other): """Report whether this set contains another set.""" self._binary_sanity_check(other) if len(self) < len(other): # Fast check for obvious cases return False for elt in ifilterfalse(self._data.has_key, other): return False return True # Inequality comparisons using the is-subset relation. __le__ = issubset __ge__ = issuperset def __lt__(self, other): self._binary_sanity_check(other) return len(self) < len(other) and self.issubset(other) def __gt__(self, other): self._binary_sanity_check(other) return len(self) > len(other) and self.issuperset(other) # Assorted helpers def _binary_sanity_check(self, other): # Check that the other argument to a binary operation is also # a set, raising a TypeError otherwise. if not isinstance(other, BaseSet): raise TypeError, "Binary operation only permitted between sets" def _compute_hash(self): # Calculate hash code for a set by xor'ing the hash codes of # the elements. This ensures that the hash code does not depend # on the order in which elements are added to the set. This is # not called __hash__ because a BaseSet should not be hashable; # only an ImmutableSet is hashable. result = 0 for elt in self: result ^= hash(elt) return result def _update(self, iterable): # The main loop for update() and the subclass __init__() methods. data = self._data # Use the fast update() method when a dictionary is available. if isinstance(iterable, BaseSet): data.update(iterable._data) return value = True if type(iterable) in (list, tuple, xrange): # Optimized: we know that __iter__() and next() can't # raise TypeError, so we can move 'try:' out of the loop. it = iter(iterable) while True: try: for element in it: data[element] = value return except TypeError: transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught data[transform()] = value else: # Safe: only catch TypeError where intended for element in iterable: try: data[element] = value except TypeError: transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught data[transform()] = value class ImmutableSet(BaseSet): """Immutable set class.""" __slots__ = ['_hashcode'] # BaseSet + hashing def __init__(self, iterable=None): """Construct an immutable set from an optional iterable.""" self._hashcode = None self._data = {} if iterable is not None: self._update(iterable) def __hash__(self): if self._hashcode is None: self._hashcode = self._compute_hash() return self._hashcode def __getstate__(self): return self._data, self._hashcode def __setstate__(self, state): self._data, self._hashcode = state class Set(BaseSet): """ Mutable set class.""" __slots__ = [] # BaseSet + operations requiring mutability; no hashing def __init__(self, iterable=None): """Construct a set from an optional iterable.""" self._data = {} if iterable is not None: self._update(iterable) def __getstate__(self): # getstate's results are ignored if it is not return self._data, def __setstate__(self, data): self._data, = data def __hash__(self): """A Set cannot be hashed.""" # We inherit object.__hash__, so we must deny this explicitly raise TypeError, "Can't hash a Set, only an ImmutableSet." # In-place union, intersection, differences. # Subtle: The xyz_update() functions deliberately return None, # as do all mutating operations on built-in container types. # The __xyz__ spellings have to return self, though. def __ior__(self, other): """Update a set with the union of itself and another.""" self._binary_sanity_check(other) self._data.update(other._data) return self def union_update(self, other): """Update a set with the union of itself and another.""" self._update(other) def __iand__(self, other): """Update a set with the intersection of itself and another.""" self._binary_sanity_check(other) self._data = (self & other)._data return self def intersection_update(self, other): """Update a set with the intersection of itself and another.""" if isinstance(other, BaseSet): self &= other else: self._data = (self.intersection(other))._data def __ixor__(self, other): """Update a set with the symmetric difference of itself and another.""" self._binary_sanity_check(other) self.symmetric_difference_update(other) return self def symmetric_difference_update(self, other): """Update a set with the symmetric difference of itself and another.""" data = self._data value = True if not isinstance(other, BaseSet): other = Set(other) if self is other: self.clear() for elt in other: if elt in data: del data[elt] else: data[elt] = value def __isub__(self, other): """Remove all elements of another set from this set.""" self._binary_sanity_check(other) self.difference_update(other) return self def difference_update(self, other): """Remove all elements of another set from this set.""" data = self._data if not isinstance(other, BaseSet): other = Set(other) if self is other: self.clear() for elt in ifilter(data.has_key, other): del data[elt] # Python dict-like mass mutations: update, clear def update(self, iterable): """Add all values from an iterable (such as a list or file).""" self._update(iterable) def clear(self): """Remove all elements from this set.""" self._data.clear() # Single-element mutations: add, remove, discard def add(self, element): """Add an element to a set. This has no effect if the element is already present. """ try: self._data[element] = True except TypeError: transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught self._data[transform()] = True def remove(self, element): """Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. """ try: del self._data[element] except TypeError: transform = getattr(element, "__as_temporarily_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught del self._data[transform()] def discard(self, element): """Remove an element from a set if it is a member. If the element is not a member, do nothing. """ try: self.remove(element) except KeyError: pass def pop(self): """Remove and return an arbitrary set element.""" return self._data.popitem()[0] def __as_immutable__(self): # Return a copy of self as an immutable set return ImmutableSet(self) def __as_temporarily_immutable__(self): # Return self wrapped in a temporarily immutable set return _TemporarilyImmutableSet(self) class _TemporarilyImmutableSet(BaseSet): # Wrap a mutable set as if it was temporarily immutable. # This only supplies hashing and equality comparisons. def __init__(self, set): self._set = set self._data = set._data # Needed by ImmutableSet.__eq__() def __hash__(self): return self._set._compute_hash() PK'ƒ5¦ç‚……$testoob/compatibility/subprocess.pyc;ò ÊŸ¦Dc@sBdZdkZeidjZdkZdkZdkZeoüdkZdkZy1dk Tdfd„ƒYZ dfd„ƒYZ Wq`e j o¦dk Z dk lZlZlZlZd k lZlZlZlZd klZd klZd klZl Z lZlZlZd kl Z l!Z!l"Z"q`Xn%dk#Z#dk$Z$dk%Z%dk&Z&ddddgZ'yei(dƒZ)Wn dZ)nXye*Wne+j odZ*dZ,nXgZ-d„Z.dZ/dZ0d„Z1d„Z2de3fd„ƒYZ4d„Z5d„Z6e7djoeo e6ƒq>e5ƒndS(sO)subprocess - Subprocesses with accessible I/O streams This module allows you to spawn processes and connect to their input/output/error pipes and obtain their return codes under Unix. This module intends to replace several other, older modules and functions, like: os.system os.spawn* os.popen* popen2.* commands.* Information about how the subprocess module can be used to replace these modules and functions can be found below. Using the subprocess module =========================== This module defines one class called Popen: class Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0): Arguments are: args should be a string, or a sequence of program arguments. The program to execute is normally the first item in the args sequence or string, but can be explicitly set by using the executable argument. On UNIX, with shell=False (default): In this case, the Popen class uses os.execvp() to execute the child program. args should normally be a sequence. A string will be treated as a sequence with the string as the only item (the program to execute). On UNIX, with shell=True: If args is a string, it specifies the command string to execute through the shell. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional shell arguments. On Windows: the Popen class uses CreateProcess() to execute the child program, which operates on strings. If args is a sequence, it will be converted to a string using the list2cmdline method. Please note that not all MS Windows applications interpret the command line the same way: The list2cmdline is designed for applications using the same rules as the MS C runtime. bufsize, if given, has the same meaning as the corresponding argument to the built-in open() function: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which usually means fully buffered. The default value for bufsize is 0 (unbuffered). stdin, stdout and stderr specify the executed programs' standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. With None, no redirection will occur; the child's file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout. If preexec_fn is set to a callable object, this object will be called in the child process just before the child is executed. If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. if shell is true, the specified command will be executed through the shell. If cwd is not None, the current directory will be changed to cwd before the child is executed. If env is not None, it defines the environment variables for the new process. If universal_newlines is true, the file objects stdout and stderr are opened as a text files, but lines may be terminated by any of ' ', the Unix end-of-line convention, ' ', the Macintosh convention or ' ', the Windows convention. All of these external representations are seen as ' ' by the Python program. Note: This feature is only available if Python is built with universal newline support (the default). Also, the newlines attribute of the file objects stdout, stdin and stderr are not updated by the communicate() method. The startupinfo and creationflags, if given, will be passed to the underlying CreateProcess() function. They can specify things such as appearance of the main window and priority for the new process. (Windows only) This module also defines two shortcut functions: call(*args, **kwargs): Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) Exceptions ---------- Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent. Additionally, the exception object will have one extra attribute called 'child_traceback', which is a string containing traceback information from the childs point of view. The most common exception raised is OSError. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for OSErrors. A ValueError will be raised if Popen is called with invalid arguments. Security -------- Unlike some other popen functions, this implementation will never call /bin/sh implicitly. This means that all characters, including shell metacharacters, can safely be passed to child processes. Popen objects ============= Instances of the Popen class have the following methods: poll() Check if child process has terminated. Returns returncode attribute. wait() Wait for child process to terminate. Returns returncode attribute. communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional stdin argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). Note: The data read is buffered in memory, so do not use this method if the data size is large or unlimited. The following attributes are also available: stdin If the stdin argument is PIPE, this attribute is a file object that provides input to the child process. Otherwise, it is None. stdout If the stdout argument is PIPE, this attribute is a file object that provides output from the child process. Otherwise, it is None. stderr If the stderr argument is PIPE, this attribute is file object that provides error output from the child process. Otherwise, it is None. pid The process ID of the child process. returncode The child return code. A None value indicates that the process hasn't terminated yet. A negative value -N indicates that the child was terminated by signal N (UNIX only). Replacing older functions with the subprocess module ==================================================== In this section, "a ==> b" means that b can be used as a replacement for a. Note: All functions in this section fail (more or less) silently if the executed program cannot be found; this module raises an OSError exception. In the following examples, we assume that the subprocess module is imported with "from subprocess import *". Replacing /bin/sh shell backquote --------------------------------- output=`mycmd myarg` ==> output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] Replacing shell pipe line ------------------------- output=`dmesg | grep hda` ==> p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout) output = p2.communicate()[0] Replacing os.system() --------------------- sts = os.system("mycmd" + " myarg") ==> p = Popen("mycmd" + " myarg", shell=True) sts = os.waitpid(p.pid, 0) Note: * Calling the program through the shell is usually not required. * It's easier to look at the returncode attribute than the exitstatus. A more real-world example would look like this: try: retcode = call("mycmd" + " myarg", shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e Replacing os.spawn* ------------------- P_NOWAIT example: pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") ==> pid = Popen(["/bin/mycmd", "myarg"]).pid P_WAIT example: retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") ==> retcode = call(["/bin/mycmd", "myarg"]) Vector example: os.spawnvp(os.P_NOWAIT, path, args) ==> Popen([path] + args[1:]) Environment example: os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) ==> Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) Replacing os.popen* ------------------- pipe = os.popen(cmd, mode='r', bufsize) ==> pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout pipe = os.popen(cmd, mode='w', bufsize) ==> pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdin, child_stdout) = (p.stdin, p.stdout) (child_stdin, child_stdout, child_stderr) = os.popen3(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) (child_stdin, child_stdout, child_stderr) = (p.stdin, p.stdout, p.stderr) (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) Replacing popen2.* ------------------ Note: If the cmd argument to popen2 functions is a string, the command is executed through /bin/sh. If it is a list, the command is directly executed. (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) ==> p = Popen(["somestring"], shell=True, bufsize=bufsize stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode) ==> p = Popen(["mycmd", "myarg"], bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen, except that: * subprocess.Popen raises an exception if the execution fails * the capturestderr argument is replaced with the stderr argument. * stdin=PIPE and stdout=PIPE must be specified. * popen2 closes all filedescriptors by default, but you have to specify close_fds=True with subprocess.Popen. Nswin32(s*s STARTUPINFOcBs tZdZeZeZeZRS(Ni(s__name__s __module__sdwFlagssNones hStdInputs hStdOutputs hStdError(((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys STARTUPINFOvss pywintypescBstZeZRS(N(s__name__s __module__sIOErrorserror(((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys pywintypes{s(s GetStdHandlesSTD_INPUT_HANDLEsSTD_OUTPUT_HANDLEsSTD_ERROR_HANDLE(sGetCurrentProcesssDuplicateHandlesGetModuleFileNames GetVersion(sDUPLICATE_SAME_ACCESS(s CreatePipe(s CreateProcesss STARTUPINFOsGetExitCodeProcesssSTARTF_USESTDHANDLESsCREATE_NEW_CONSOLE(sWaitForSingleObjectsINFINITEs WAIT_OBJECT_0sPopensPIPEsSTDOUTscalls SC_OPEN_MAXiiicCs xtD]}|iƒqWdS(N(s_activesinstspoll(sinst((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys_cleanupŸsiÿÿÿÿiþÿÿÿcOst||ŽiƒSdS(sÓRun command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) N(sPopensargsskwargsswait(sargsskwargs((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pyscall§scCsFg}t}x&|D]}g}|o|idƒnd|jp d|j}|o|idƒnx–|D]Ž}|djo|i|ƒqo|djo2|idt|ƒdƒg}|idƒqo|o|i |ƒg}n|i|ƒqoW|o|i |ƒn|o|idƒqqWdi |ƒSdS( s• Translate a sequence of arguments into a command line string, using the same rules as the MS C runtime: 1) Arguments are delimited by white space, which is either a space or a tab. 2) A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. 3) A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark. 4) Backslashes are interpreted literally, unless they immediately precede a double quotation mark. 5) If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3. s s s"s\is\"sN( sresultsFalses needquotesseqsargsbs_bufsappendscslensextendsjoin(sseqscs needquotesresultsargsbs_buf((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys list2cmdline²s8    cBsâtZdeeeeeeeeeeedd„ Zd„ZeoOd„Zd„Zd„Z d„Z d„Z d „Z d „Z ed „ZnLd „Zd „Zd„Zd„Z d„Zd„Z d„Z ed„ZRS(NicCs×tƒto8|tj otdƒ‚n|otdƒ‚q€n;| tj otdƒ‚n|djotdƒ‚nt|_ t|_ t|_ t|_ t|_ | |_|i|||ƒ\}}}}}}|i||||| | | | || ||||||ƒ|oti|d|ƒ|_ n|o?| oti|d|ƒ|_ q€ti|d|ƒ|_ n|o?| oti|d|ƒ|_ qÆti|d|ƒ|_ nti |ƒd S( sCreate new Popen instance.s0preexec_fn is not supported on Windows platformss/close_fds is not supported on Windows platformss2startupinfo is only supported on Windows platformsis4creationflags is only supported on Windows platformsswbsrUsrbN(!s_cleanups mswindowss preexec_fnsNones ValueErrors close_fdss startupinfos creationflagssselfsstdinsstdoutsstderrspids returncodesuniversal_newliness _get_handlessp2creadsp2cwritesc2preadsc2pwriteserrreadserrwrites_execute_childsargss executablescwdsenvsshellsossfdopensbufsizes_activesappend(sselfsargssbufsizes executablesstdinsstdoutsstderrs preexec_fns close_fdssshellscwdsenvsuniversal_newliness startupinfos creationflagsserrreadsc2preadserrwritesc2pwritesp2creadsp2cwrite((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys__init__ösF         '   cCs,|iddƒ}|iddƒ}|SdS(Ns s s (sdatasreplace(sselfsdata((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys_translate_newlines?sc Cs²|tjo|tjo |tjottttttfSnttf\}}ttf\} }ttf\}}|tjot t ƒ}nƒ|t jo7t tdƒ\}}|iƒ}ti|dƒ}n?t|ƒtijoti|ƒ}nti|iƒƒ}|i|ƒ}|tjot tƒ}nƒ|t jo7t tdƒ\} }| iƒ} ti| dƒ} n?t|ƒtijoti|ƒ}nti|iƒƒ}|i|ƒ}|tjot tƒ}nš|t jo7t tdƒ\}}|iƒ}ti|dƒ}nV|tjo |}n?t|ƒtijoti|ƒ}nti|iƒƒ}|i|ƒ}||| |||fSdS(s|Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite iN(sstdinsNonesstdoutsstderrsp2creadsp2cwritesc2preadsc2pwriteserrreadserrwrites GetStdHandlesSTD_INPUT_HANDLEsPIPEs CreatePipesDetachsmsvcrtsopen_osfhandlestypestypessIntTypes get_osfhandlesfilenosselfs_make_inheritablesSTD_OUTPUT_HANDLEsSTD_ERROR_HANDLEsSTDOUT( sselfsstdinsstdoutsstderrserrreadsp2creadsp2cwriteserrwritesc2pwritesc2pread((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys _get_handlesIsN'           cCs#ttƒ|tƒddtƒSdS(s2Return a duplicate of handle, which is inheritableiiN(sDuplicateHandlesGetCurrentProcessshandlesDUPLICATE_SAME_ACCESS(sselfshandle((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys_make_inheritable…s  cCstiitiitdƒƒdƒ}tii|ƒ oLtiitiitiƒdƒ}tii|ƒ ot dƒ‚q‡n|SdS(s,Find and return absolut path to w9xpopen.exeis w9xpopen.exesZCannot locate w9xpopen.exe, which is needed for Popen to work with your shell or platform.N( sosspathsjoinsdirnamesGetModuleFileNamesw9xpopensexistsssyss exec_prefixs RuntimeError(sselfsw9xpopen((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys_find_w9xpopenŒs  c CsÙt|tiƒ ot|ƒ}n| o€tiiddƒ}|d|}t ƒdjpti i |ƒi ƒdjo*|iƒ}d||f}| tO} q«n|tjo tƒ}nt| ||fj o.|itO_| |_||_||_ny4t||ttd| |||ƒ \}}}}Wn't&i'j o}t)|iŒ‚nX||_*||_$|i+ƒ| tjo| i+ƒn|tjo|i+ƒn|tjo|i+ƒndS( s$Execute program (MS Windows version)sCOMSPECscmd.exes /c ls command.coms"%s" %siN(,s isinstancesargsstypess StringTypess list2cmdlinesshellsossenvironsgetscomspecs GetVersionspathsbasenameslowersselfs_find_w9xpopensw9xpopens creationflagssCREATE_NEW_CONSOLEs startupinfosNones STARTUPINFOsp2creadsc2pwriteserrwritesdwFlagssSTARTF_USESTDHANDLESs hStdInputs hStdOutputs hStdErrors CreateProcesss executablesenvscwdshpshtspidstids pywintypesserrorses WindowsErrors_handlesClose(sselfsargss executables preexec_fns close_fdsscwdsenvsuniversal_newliness startupinfos creationflagssshellsp2creadsp2cwritesc2preadsc2pwriteserrreadserrwritespidscomspecstidshpshtsesw9xpopen((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys_execute_childœsH/             cCs[|itjo@t|idƒtjo#t|iƒ|_ti|ƒqPn|iSdS(sQCheck if child process has terminated. Returns returncode attribute.iN( sselfs returncodesNonesWaitForSingleObjects_handles WAIT_OBJECT_0sGetExitCodeProcesss_activesremove(sself((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pyspollés cCsP|itjo5t|itƒ}t|iƒ|_ti |ƒn|iSdS(sOWait for child process to terminate. Returns returncode attribute.N( sselfs returncodesNonesWaitForSingleObjects_handlesINFINITEsobjsGetExitCodeProcesss_activesremove(sselfsobj((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pyswaitós cCs|i|iƒƒdS(N(sbuffersappendsfhsread(sselfsfhsbuffer((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys _readerthreadýscCs¶t}t}|ioEg}tid|id|i|fƒ}|it ƒ|i ƒn|ioEg}tid|id|i|fƒ}|it ƒ|i ƒn|i o2|tjo|i i|ƒn|i iƒn|io|iƒn|io|iƒn|tjo|d}n|tjo|d}n|io ttdƒo8|o|i|ƒ}n|o|i|ƒ}qžn|iƒ||fSdS(szInteract with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr).stargetsargsisnewlinesN(sNonesstdoutsstderrsselfs threadingsThreads _readerthreads stdout_threads setDaemonsTruesstarts stderr_threadsstdinsinputswritesclosesjoinsuniversal_newlinesshasattrsopens_translate_newlinesswait(sselfsinputsstdoutsstderrs stdout_threads stderr_thread((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys communicatesD           c Cs‡ttf\}}ttf\} }ttf\}}|tjonP|tjot i ƒ\}}n-t |ƒt i jo |}n |iƒ}|tjonP|tjot i ƒ\} }n-t |ƒt i jo |}n |iƒ}|tjong|tjot i ƒ\}}nD|tjo |}n-t |ƒt i jo |}n |iƒ}||| |||fSdS(s|Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite N(sNonesp2creadsp2cwritesc2preadsc2pwriteserrreadserrwritesstdinsPIPEsosspipestypestypessIntTypesfilenosstdoutsstderrsSTDOUT( sselfsstdinsstdoutsstderrserrreadsp2creadsp2cwriteserrwritesc2pwritesc2pread((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys _get_handles:s8              cCs\y ti}Wntj o d}nXti|tiƒ}ti|ti||BƒdS(Ni(sfcntls FD_CLOEXECs cloexec_flagsAttributeErrorsfdsF_GETFDsoldsF_SETFD(sselfsfdsolds cloexec_flag((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys_set_cloexec_flaggs   cCsMxFtdtƒD]5}||joqnyti|ƒWqqXqWdS(Ni(srangesMAXFDsisbutsossclose(sselfsbutsi((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys _close_fdsqs cCsNt|tiƒo |g}n| oddg|}n|tjo|d}ntiƒ\}}|i |ƒti ƒ|_|idjoy—| oti| ƒn| oti| ƒn|oti|ƒnti|ƒ| oti| dƒn|oti|dƒn|oti|dƒn| oti| ƒn|o || fjoti|ƒn|o|| |fjoti|ƒn|o|id|ƒn|tjoti|ƒn|ot|ƒn|tjoti||ƒnti|||ƒWn\t i!ƒ\}}}t%i&|||ƒ}di(|ƒ|_)ti*|t+i,|ƒƒnXti-dƒnti|ƒ| o| oti| ƒn|o| oti|ƒn|o|oti|ƒnti.|d ƒ}ti|ƒ|djot+i0|ƒ}|‚nd S( sExecute program (POSIX version)s/bin/shs-ciiisbutsiÿiN(2s isinstancesargsstypess StringTypessshells executablesNonesosspipes errpipe_reads errpipe_writesselfs_set_cloexec_flagsforkspidsp2cwritesclosesc2preadserrreadsp2creadsdup2sc2pwriteserrwrites close_fdss _close_fdsscwdschdirs preexec_fnsapplysenvsexecvpsexecvpessyssexc_infosexc_types exc_valuestbs tracebacksformat_exceptions exc_linessjoinschild_tracebackswritespicklesdumpss_exitsreadsdatasloadsschild_exception(sselfsargss executables preexec_fns close_fdsscwdsenvsuniversal_newliness startupinfos creationflagssshellsp2creadsp2cwritesc2preadsc2pwriteserrreadserrwrites exc_linesschild_exceptions errpipe_writesexc_typestbsdatas errpipe_reads exc_value((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys_execute_child{sx           cCsjti|ƒoti|ƒ |_n3ti|ƒoti|ƒ|_n tdƒ‚t i |ƒdS(NsUnknown child exit status!( soss WIFSIGNALEDsstssWTERMSIGsselfs returncodes WIFEXITEDs WEXITSTATUSs RuntimeErrors_activesremove(sselfssts((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys_handle_exitstatusÝs  cCs{|itjo`yCti|itiƒ\}}||ijo|i|ƒnWqpti j oqpXn|iSdS(sQCheck if child process has terminated. Returns returncode attribute.N( sselfs returncodesNonesosswaitpidspidsWNOHANGsstss_handle_exitstatusserror(sselfspidssts((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pyspollés cCsG|itjo,ti|idƒ\}}|i|ƒn|iSdS(sOWait for child process to terminate. Returns returncode attribute.iN(sselfs returncodesNonesosswaitpidspidsstss_handle_exitstatus(sselfspidssts((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pyswaitös c Cs»g}g}t}t} |io9|iiƒ|o|i |iƒq[|ii ƒn|io|i |iƒg}n|io|i |iƒg} nxk|p|o\t i ||gƒ\}} }|i| joVti|iiƒ|d ƒ}||}| o!|ii ƒ|i|iƒq8n|i|joZti|iiƒdƒ}|djo!|ii ƒ|i|iƒn|i |ƒn|i|joZti|iiƒdƒ}|djo!|ii ƒ|i|iƒn| i |ƒq¦q¦W|tjodi|ƒ}n| tjodi| ƒ} n|io ttdƒo8|o|i|ƒ}n| o|i| ƒ} q£n|iƒ|| fSdS(szInteract with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr).iissnewlinesN(sread_sets write_setsNonesstdoutsstderrsselfsstdinsflushsinputsappendsclosesselectsrlistswlistsxlistsosswritesfilenos bytes_writtensremovesreadsdatasjoinsuniversal_newlinesshasattrsopens_translate_newlinesswait( sselfsinputsrlistsxlistsstdouts write_setsdatas bytes_writtensread_setsstderrswlist((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys communicateÿs`               (s__name__s __module__sNonesFalses__init__s_translate_newliness mswindowss _get_handless_make_inheritables_find_w9xpopens_execute_childspollswaits _readerthreads communicates_set_cloexec_flags _close_fdss_handle_exitstatus(((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pysPopenõs&0I  <   M 9 - b cCs.tdgdtƒiƒd}dGH|GHtiƒdjo&tdgdd„ƒ}|iƒndGHtd gdtƒ}td d gd |i dtƒ}t |iƒdƒGHHd GHytdgƒiƒGHWnJt j o>}|itijodGHdGH|iGHq*dG|iGHnXtidIJdS(Nspssstdoutis Process list:sids preexec_fncCs tidƒS(Nid(sosssetuid(((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pysVssLooking for 'hda'...sdmesgsgrepshdasstdinsTrying a weird file...s/this/path/does/not/exists'The file didn't exist. I thought so...sChild traceback:sErrorsGosh. No error.(sPopensPIPEs communicatesplistsossgetuidspswaitsp1sstdoutsp2sreprsOSErrorseserrnosENOENTschild_tracebackssyssstderr(sp2sp1sespsplist((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys _demo_posixJs*! cCsldGHtddtdtƒ}tdd|idtƒ}t|iƒdƒGHdGHtd ƒ}|i ƒdS( Ns%Looking for 'PROMPT' in set output...ssetsstdoutsshells find "PROMPT"sstdinisExecuting calc...scalc( sPopensPIPEsTruesp1sstdoutsp2sreprs communicatespswait(sp2sp1sp((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys _demo_windowsss s__main__(8s__doc__ssyssplatforms mswindowssosstypess tracebacks threadingsmsvcrts _subprocesss STARTUPINFOs pywintypess ImportErrorswin32apis GetStdHandlesSTD_INPUT_HANDLEsSTD_OUTPUT_HANDLEsSTD_ERROR_HANDLEsGetCurrentProcesssDuplicateHandlesGetModuleFileNames GetVersionswin32consDUPLICATE_SAME_ACCESSs win32pipes CreatePipes win32processs CreateProcesssGetExitCodeProcesssSTARTF_USESTDHANDLESsCREATE_NEW_CONSOLEs win32eventsWaitForSingleObjectsINFINITEs WAIT_OBJECT_0sselectserrnosfcntlspickles__all__ssysconfsMAXFDsFalses NameErrorsTrues_actives_cleanupsPIPEsSTDOUTscalls list2cmdlinesobjectsPopens _demo_posixs _demo_windowss__name__(+sfcntls GetStdHandlesSTDOUTsWaitForSingleObjectsGetExitCodeProcesssGetModuleFileNames pywintypessselectsPIPEs CreatePipesGetCurrentProcesss__all__serrnos _demo_posixs CreateProcesssmsvcrts_cleanupscallsTrues _demo_windowss mswindowssMAXFDs STARTUPINFOs WAIT_OBJECT_0sSTARTF_USESTDHANDLESsPopenssyssINFINITEsDuplicateHandlestypessDUPLICATE_SAME_ACCESSsFalsespickles_actives tracebacks list2cmdlines threadingsSTD_ERROR_HANDLEsCREATE_NEW_CONSOLEs GetVersionsSTD_INPUT_HANDLEsossSTD_OUTPUT_HANDLE((s>build/bdist.linux-i686/egg/testoob/compatibility/subprocess.pys?hsb         %"        CÿÿW )   PKšá4o¢€9ž9ž#testoob/compatibility/subprocess.py# This file is taken from the PyPy project, http://codespeak.net/pypy # subprocess - Subprocesses with accessible I/O streams # # For more information about this module, see PEP 324. # # Copyright (c) 2003-2004 by Peter Astrand # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of the # author not be used in advertising or publicity pertaining to # distribution of the software without specific, written prior # permission. # # THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """subprocess - Subprocesses with accessible I/O streams This module allows you to spawn processes and connect to their input/output/error pipes and obtain their return codes under Unix. This module intends to replace several other, older modules and functions, like: os.system os.spawn* os.popen* popen2.* commands.* Information about how the subprocess module can be used to replace these modules and functions can be found below. Using the subprocess module =========================== This module defines one class called Popen: class Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0): Arguments are: args should be a string, or a sequence of program arguments. The program to execute is normally the first item in the args sequence or string, but can be explicitly set by using the executable argument. On UNIX, with shell=False (default): In this case, the Popen class uses os.execvp() to execute the child program. args should normally be a sequence. A string will be treated as a sequence with the string as the only item (the program to execute). On UNIX, with shell=True: If args is a string, it specifies the command string to execute through the shell. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional shell arguments. On Windows: the Popen class uses CreateProcess() to execute the child program, which operates on strings. If args is a sequence, it will be converted to a string using the list2cmdline method. Please note that not all MS Windows applications interpret the command line the same way: The list2cmdline is designed for applications using the same rules as the MS C runtime. bufsize, if given, has the same meaning as the corresponding argument to the built-in open() function: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which usually means fully buffered. The default value for bufsize is 0 (unbuffered). stdin, stdout and stderr specify the executed programs' standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. With None, no redirection will occur; the child's file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout. If preexec_fn is set to a callable object, this object will be called in the child process just before the child is executed. If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. if shell is true, the specified command will be executed through the shell. If cwd is not None, the current directory will be changed to cwd before the child is executed. If env is not None, it defines the environment variables for the new process. If universal_newlines is true, the file objects stdout and stderr are opened as a text files, but lines may be terminated by any of '\n', the Unix end-of-line convention, '\r', the Macintosh convention or '\r\n', the Windows convention. All of these external representations are seen as '\n' by the Python program. Note: This feature is only available if Python is built with universal newline support (the default). Also, the newlines attribute of the file objects stdout, stdin and stderr are not updated by the communicate() method. The startupinfo and creationflags, if given, will be passed to the underlying CreateProcess() function. They can specify things such as appearance of the main window and priority for the new process. (Windows only) This module also defines two shortcut functions: call(*args, **kwargs): Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) Exceptions ---------- Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent. Additionally, the exception object will have one extra attribute called 'child_traceback', which is a string containing traceback information from the childs point of view. The most common exception raised is OSError. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for OSErrors. A ValueError will be raised if Popen is called with invalid arguments. Security -------- Unlike some other popen functions, this implementation will never call /bin/sh implicitly. This means that all characters, including shell metacharacters, can safely be passed to child processes. Popen objects ============= Instances of the Popen class have the following methods: poll() Check if child process has terminated. Returns returncode attribute. wait() Wait for child process to terminate. Returns returncode attribute. communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional stdin argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). Note: The data read is buffered in memory, so do not use this method if the data size is large or unlimited. The following attributes are also available: stdin If the stdin argument is PIPE, this attribute is a file object that provides input to the child process. Otherwise, it is None. stdout If the stdout argument is PIPE, this attribute is a file object that provides output from the child process. Otherwise, it is None. stderr If the stderr argument is PIPE, this attribute is file object that provides error output from the child process. Otherwise, it is None. pid The process ID of the child process. returncode The child return code. A None value indicates that the process hasn't terminated yet. A negative value -N indicates that the child was terminated by signal N (UNIX only). Replacing older functions with the subprocess module ==================================================== In this section, "a ==> b" means that b can be used as a replacement for a. Note: All functions in this section fail (more or less) silently if the executed program cannot be found; this module raises an OSError exception. In the following examples, we assume that the subprocess module is imported with "from subprocess import *". Replacing /bin/sh shell backquote --------------------------------- output=`mycmd myarg` ==> output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] Replacing shell pipe line ------------------------- output=`dmesg | grep hda` ==> p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout) output = p2.communicate()[0] Replacing os.system() --------------------- sts = os.system("mycmd" + " myarg") ==> p = Popen("mycmd" + " myarg", shell=True) sts = os.waitpid(p.pid, 0) Note: * Calling the program through the shell is usually not required. * It's easier to look at the returncode attribute than the exitstatus. A more real-world example would look like this: try: retcode = call("mycmd" + " myarg", shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e Replacing os.spawn* ------------------- P_NOWAIT example: pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") ==> pid = Popen(["/bin/mycmd", "myarg"]).pid P_WAIT example: retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") ==> retcode = call(["/bin/mycmd", "myarg"]) Vector example: os.spawnvp(os.P_NOWAIT, path, args) ==> Popen([path] + args[1:]) Environment example: os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) ==> Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) Replacing os.popen* ------------------- pipe = os.popen(cmd, mode='r', bufsize) ==> pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout pipe = os.popen(cmd, mode='w', bufsize) ==> pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdin, child_stdout) = (p.stdin, p.stdout) (child_stdin, child_stdout, child_stderr) = os.popen3(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) (child_stdin, child_stdout, child_stderr) = (p.stdin, p.stdout, p.stderr) (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) Replacing popen2.* ------------------ Note: If the cmd argument to popen2 functions is a string, the command is executed through /bin/sh. If it is a list, the command is directly executed. (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) ==> p = Popen(["somestring"], shell=True, bufsize=bufsize stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode) ==> p = Popen(["mycmd", "myarg"], bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen, except that: * subprocess.Popen raises an exception if the execution fails * the capturestderr argument is replaced with the stderr argument. * stdin=PIPE and stdout=PIPE must be specified. * popen2 closes all filedescriptors by default, but you have to specify close_fds=True with subprocess.Popen. """ import sys mswindows = (sys.platform == "win32") import os import types import traceback if mswindows: import threading import msvcrt try: from _subprocess import * class STARTUPINFO: dwFlags = 0 hStdInput = None hStdOutput = None hStdError = None class pywintypes: error = IOError except ImportError: import pywintypes from win32api import GetStdHandle, STD_INPUT_HANDLE, \ STD_OUTPUT_HANDLE, STD_ERROR_HANDLE from win32api import GetCurrentProcess, DuplicateHandle, \ GetModuleFileName, GetVersion from win32con import DUPLICATE_SAME_ACCESS from win32pipe import CreatePipe from win32process import CreateProcess, STARTUPINFO, \ GetExitCodeProcess, STARTF_USESTDHANDLES, \ CREATE_NEW_CONSOLE from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0 else: import select import errno import fcntl import pickle __all__ = ["Popen", "PIPE", "STDOUT", "call"] try: MAXFD = os.sysconf("SC_OPEN_MAX") except: MAXFD = 256 # True/False does not exist on 2.2.0 try: False except NameError: False = 0 True = 1 _active = [] def _cleanup(): for inst in _active[:]: inst.poll() PIPE = -1 STDOUT = -2 def call(*args, **kwargs): """Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) """ return Popen(*args, **kwargs).wait() def list2cmdline(seq): """ Translate a sequence of arguments into a command line string, using the same rules as the MS C runtime: 1) Arguments are delimited by white space, which is either a space or a tab. 2) A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. 3) A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark. 4) Backslashes are interpreted literally, unless they immediately precede a double quotation mark. 5) If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3. """ # See # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp result = [] needquote = False for arg in seq: bs_buf = [] # Add a space to separate this argument from the others if result: result.append(' ') needquote = (" " in arg) or ("\t" in arg) if needquote: result.append('"') for c in arg: if c == '\\': # Don't know if we need to double yet. bs_buf.append(c) elif c == '"': # Double backspaces. result.append('\\' * len(bs_buf)*2) bs_buf = [] result.append('\\"') else: # Normal char if bs_buf: result.extend(bs_buf) bs_buf = [] result.append(c) # Add remaining backspaces, if any. if bs_buf: result.extend(bs_buf) if needquote: result.append('"') return ''.join(result) class Popen(object): def __init__(self, args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0): """Create new Popen instance.""" _cleanup() if mswindows: if preexec_fn is not None: raise ValueError("preexec_fn is not supported on Windows " "platforms") if close_fds: raise ValueError("close_fds is not supported on Windows " "platforms") else: # POSIX if startupinfo is not None: raise ValueError("startupinfo is only supported on Windows " "platforms") if creationflags != 0: raise ValueError("creationflags is only supported on Windows " "platforms") self.stdin = None self.stdout = None self.stderr = None self.pid = None self.returncode = None self.universal_newlines = universal_newlines # Input and output objects. The general principle is like # this: # # Parent Child # ------ ----- # p2cwrite ---stdin---> p2cread # c2pread <--stdout--- c2pwrite # errread <--stderr--- errwrite # # On POSIX, the child objects are file descriptors. On # Windows, these are Windows file handles. The parent objects # are file descriptors on both platforms. The parent objects # are None when not using PIPEs. The child objects are None # when not redirecting. (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) = self._get_handles(stdin, stdout, stderr) self._execute_child(args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) if p2cwrite: self.stdin = os.fdopen(p2cwrite, 'wb', bufsize) if c2pread: if universal_newlines: self.stdout = os.fdopen(c2pread, 'rU', bufsize) else: self.stdout = os.fdopen(c2pread, 'rb', bufsize) if errread: if universal_newlines: self.stderr = os.fdopen(errread, 'rU', bufsize) else: self.stderr = os.fdopen(errread, 'rb', bufsize) _active.append(self) def _translate_newlines(self, data): data = data.replace("\r\n", "\n") data = data.replace("\r", "\n") return data if mswindows: # # Windows methods # def _get_handles(self, stdin, stdout, stderr): """Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ if stdin == None and stdout == None and stderr == None: return (None, None, None, None, None, None) p2cread, p2cwrite = None, None c2pread, c2pwrite = None, None errread, errwrite = None, None if stdin == None: p2cread = GetStdHandle(STD_INPUT_HANDLE) elif stdin == PIPE: p2cread, p2cwrite = CreatePipe(None, 0) # Detach and turn into fd p2cwrite = p2cwrite.Detach() p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0) elif type(stdin) == types.IntType: p2cread = msvcrt.get_osfhandle(stdin) else: # Assuming file-like object p2cread = msvcrt.get_osfhandle(stdin.fileno()) p2cread = self._make_inheritable(p2cread) if stdout == None: c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) elif stdout == PIPE: c2pread, c2pwrite = CreatePipe(None, 0) # Detach and turn into fd c2pread = c2pread.Detach() c2pread = msvcrt.open_osfhandle(c2pread, 0) elif type(stdout) == types.IntType: c2pwrite = msvcrt.get_osfhandle(stdout) else: # Assuming file-like object c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) c2pwrite = self._make_inheritable(c2pwrite) if stderr == None: errwrite = GetStdHandle(STD_ERROR_HANDLE) elif stderr == PIPE: errread, errwrite = CreatePipe(None, 0) # Detach and turn into fd errread = errread.Detach() errread = msvcrt.open_osfhandle(errread, 0) elif stderr == STDOUT: errwrite = c2pwrite elif type(stderr) == types.IntType: errwrite = msvcrt.get_osfhandle(stderr) else: # Assuming file-like object errwrite = msvcrt.get_osfhandle(stderr.fileno()) errwrite = self._make_inheritable(errwrite) return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) def _make_inheritable(self, handle): """Return a duplicate of handle, which is inheritable""" return DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), 0, 1, DUPLICATE_SAME_ACCESS) def _find_w9xpopen(self): """Find and return absolut path to w9xpopen.exe""" w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), "w9xpopen.exe") if not os.path.exists(w9xpopen): # Eeek - file-not-found - possibly an embedding # situation - see if we can locate it in sys.exec_prefix w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), "w9xpopen.exe") if not os.path.exists(w9xpopen): raise RuntimeError("Cannot locate w9xpopen.exe, which is " "needed for Popen to work with your " "shell or platform.") return w9xpopen def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (MS Windows version)""" if not isinstance(args, types.StringTypes): args = list2cmdline(args) if shell: comspec = os.environ.get("COMSPEC", "cmd.exe") args = comspec + " /c " + args if (GetVersion() >= 0x80000000L or os.path.basename(comspec).lower() == "command.com"): # Win9x, or using command.com on NT. We need to # use the w9xpopen intermediate program. For more # information, see KB Q150956 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp) w9xpopen = self._find_w9xpopen() args = '"%s" %s' % (w9xpopen, args) # Not passing CREATE_NEW_CONSOLE has been known to # cause random failures on win9x. Specifically a # dialog: "Your program accessed mem currently in # use at xxx" and a hopeful warning about the # stability of your system. Cost is Ctrl+C wont # kill children. creationflags |= CREATE_NEW_CONSOLE # Process startup details if startupinfo == None: startupinfo = STARTUPINFO() if not None in (p2cread, c2pwrite, errwrite): startupinfo.dwFlags |= STARTF_USESTDHANDLES startupinfo.hStdInput = p2cread startupinfo.hStdOutput = c2pwrite startupinfo.hStdError = errwrite # Start the process try: hp, ht, pid, tid = CreateProcess(executable, args, # no special security None, None, # must inherit handles to pass std # handles 1, creationflags, env, cwd, startupinfo) except pywintypes.error, e: # Translate pywintypes.error to WindowsError, which is # a subclass of OSError. FIXME: We should really # translate errno using _sys_errlist (or simliar), but # how can this be done from Python? raise WindowsError(*e.args) # Retain the process handle, but close the thread handle self._handle = hp self.pid = pid ht.Close() # Child is launched. Close the parent's copy of those pipe # handles that only the child should have open. You need # to make sure that no handles to the write end of the # output pipe are maintained in this process or else the # pipe will not close when the child process exits and the # ReadFile will hang. if p2cread != None: p2cread.Close() if c2pwrite != None: c2pwrite.Close() if errwrite != None: errwrite.Close() def poll(self): """Check if child process has terminated. Returns returncode attribute.""" if self.returncode == None: if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0: self.returncode = GetExitCodeProcess(self._handle) _active.remove(self) return self.returncode def wait(self): """Wait for child process to terminate. Returns returncode attribute.""" if self.returncode == None: obj = WaitForSingleObject(self._handle, INFINITE) self.returncode = GetExitCodeProcess(self._handle) _active.remove(self) return self.returncode def _readerthread(self, fh, buffer): buffer.append(fh.read()) def communicate(self, input=None): """Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr).""" stdout = None # Return stderr = None # Return if self.stdout: stdout = [] stdout_thread = threading.Thread(target=self._readerthread, args=(self.stdout, stdout)) stdout_thread.setDaemon(True) stdout_thread.start() if self.stderr: stderr = [] stderr_thread = threading.Thread(target=self._readerthread, args=(self.stderr, stderr)) stderr_thread.setDaemon(True) stderr_thread.start() if self.stdin: if input != None: self.stdin.write(input) self.stdin.close() if self.stdout: stdout_thread.join() if self.stderr: stderr_thread.join() # All data exchanged. Translate lists into strings. if stdout != None: stdout = stdout[0] if stderr != None: stderr = stderr[0] # Translate newlines, if requested. We cannot let the file # object do the translation: It is based on stdio, which is # impossible to combine with select (unless forcing no # buffering). if self.universal_newlines and hasattr(open, 'newlines'): if stdout: stdout = self._translate_newlines(stdout) if stderr: stderr = self._translate_newlines(stderr) self.wait() return (stdout, stderr) else: # # POSIX methods # def _get_handles(self, stdin, stdout, stderr): """Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ p2cread, p2cwrite = None, None c2pread, c2pwrite = None, None errread, errwrite = None, None if stdin == None: pass elif stdin == PIPE: p2cread, p2cwrite = os.pipe() elif type(stdin) == types.IntType: p2cread = stdin else: # Assuming file-like object p2cread = stdin.fileno() if stdout == None: pass elif stdout == PIPE: c2pread, c2pwrite = os.pipe() elif type(stdout) == types.IntType: c2pwrite = stdout else: # Assuming file-like object c2pwrite = stdout.fileno() if stderr == None: pass elif stderr == PIPE: errread, errwrite = os.pipe() elif stderr == STDOUT: errwrite = c2pwrite elif type(stderr) == types.IntType: errwrite = stderr else: # Assuming file-like object errwrite = stderr.fileno() return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) def _set_cloexec_flag(self, fd): try: cloexec_flag = fcntl.FD_CLOEXEC except AttributeError: cloexec_flag = 1 old = fcntl.fcntl(fd, fcntl.F_GETFD) fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag) def _close_fds(self, but): for i in range(3, MAXFD): if i == but: continue try: os.close(i) except: pass def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (POSIX version)""" if isinstance(args, types.StringTypes): args = [args] if shell: args = ["/bin/sh", "-c"] + args if executable == None: executable = args[0] # For transferring possible exec failure from child to parent # The first char specifies the exception type: 0 means # OSError, 1 means some other error. errpipe_read, errpipe_write = os.pipe() self._set_cloexec_flag(errpipe_write) self.pid = os.fork() if self.pid == 0: # Child try: # Close parent's pipe ends if p2cwrite: os.close(p2cwrite) if c2pread: os.close(c2pread) if errread: os.close(errread) os.close(errpipe_read) # Dup fds for child if p2cread: os.dup2(p2cread, 0) if c2pwrite: os.dup2(c2pwrite, 1) if errwrite: os.dup2(errwrite, 2) # Close pipe fds. Make sure we doesn't close the same # fd more than once. if p2cread: os.close(p2cread) if c2pwrite and c2pwrite not in (p2cread,): os.close(c2pwrite) if errwrite and errwrite not in (p2cread, c2pwrite): os.close(errwrite) # Close all other fds, if asked for if close_fds: self._close_fds(but=errpipe_write) if cwd != None: os.chdir(cwd) if preexec_fn: apply(preexec_fn) if env == None: os.execvp(executable, args) else: os.execvpe(executable, args, env) except: exc_type, exc_value, tb = sys.exc_info() # Save the traceback and attach it to the exception object exc_lines = traceback.format_exception(exc_type, exc_value, tb) exc_value.child_traceback = ''.join(exc_lines) os.write(errpipe_write, pickle.dumps(exc_value)) # This exitcode won't be reported to applications, so it # really doesn't matter what we return. os._exit(255) # Parent os.close(errpipe_write) if p2cread and p2cwrite: os.close(p2cread) if c2pwrite and c2pread: os.close(c2pwrite) if errwrite and errread: os.close(errwrite) # Wait for exec to fail or succeed; possibly raising exception data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB os.close(errpipe_read) if data != "": child_exception = pickle.loads(data) raise child_exception def _handle_exitstatus(self, sts): if os.WIFSIGNALED(sts): self.returncode = -os.WTERMSIG(sts) elif os.WIFEXITED(sts): self.returncode = os.WEXITSTATUS(sts) else: # Should never happen raise RuntimeError("Unknown child exit status!") _active.remove(self) def poll(self): """Check if child process has terminated. Returns returncode attribute.""" if self.returncode == None: try: pid, sts = os.waitpid(self.pid, os.WNOHANG) if pid == self.pid: self._handle_exitstatus(sts) except os.error: pass return self.returncode def wait(self): """Wait for child process to terminate. Returns returncode attribute.""" if self.returncode == None: pid, sts = os.waitpid(self.pid, 0) self._handle_exitstatus(sts) return self.returncode def communicate(self, input=None): """Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr).""" read_set = [] write_set = [] stdout = None # Return stderr = None # Return if self.stdin: # Flush stdio buffer. This might block, if the user has # been writing to .stdin in an uncontrolled fashion. self.stdin.flush() if input: write_set.append(self.stdin) else: self.stdin.close() if self.stdout: read_set.append(self.stdout) stdout = [] if self.stderr: read_set.append(self.stderr) stderr = [] while read_set or write_set: rlist, wlist, xlist = select.select(read_set, write_set, []) if self.stdin in wlist: # When select has indicated that the file is writable, # we can write up to PIPE_BUF bytes without risk # blocking. POSIX defines PIPE_BUF >= 512 bytes_written = os.write(self.stdin.fileno(), input[:512]) input = input[bytes_written:] if not input: self.stdin.close() write_set.remove(self.stdin) if self.stdout in rlist: data = os.read(self.stdout.fileno(), 1024) if data == "": self.stdout.close() read_set.remove(self.stdout) stdout.append(data) if self.stderr in rlist: data = os.read(self.stderr.fileno(), 1024) if data == "": self.stderr.close() read_set.remove(self.stderr) stderr.append(data) # All data exchanged. Translate lists into strings. if stdout != None: stdout = ''.join(stdout) if stderr != None: stderr = ''.join(stderr) # Translate newlines, if requested. We cannot let the file # object do the translation: It is based on stdio, which is # impossible to combine with select (unless forcing no # buffering). if self.universal_newlines and hasattr(open, 'newlines'): if stdout: stdout = self._translate_newlines(stdout) if stderr: stderr = self._translate_newlines(stderr) self.wait() return (stdout, stderr) def _demo_posix(): # # Example 1: Simple redirection: Get process list # plist = Popen(["ps"], stdout=PIPE).communicate()[0] print "Process list:" print plist # # Example 2: Change uid before executing child # if os.getuid() == 0: p = Popen(["id"], preexec_fn=lambda: os.setuid(100)) p.wait() # # Example 3: Connecting several subprocesses # print "Looking for 'hda'..." p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) print repr(p2.communicate()[0]) # # Example 4: Catch execution error # print print "Trying a weird file..." try: print Popen(["/this/path/does/not/exist"]).communicate() except OSError, e: if e.errno == errno.ENOENT: print "The file didn't exist. I thought so..." print "Child traceback:" print e.child_traceback else: print "Error", e.errno else: print >>sys.stderr, "Gosh. No error." def _demo_windows(): # # Example 1: Connecting several subprocesses # print "Looking for 'PROMPT' in set output..." p1 = Popen("set", stdout=PIPE, shell=True) p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE) print repr(p2.communicate()[0]) # # Example 2: Simple execution of program # print "Executing calc..." p = Popen("calc") p.wait() if __name__ == "__main__": if mswindows: _demo_windows() else: _demo_posix() PKšá4RIc)®Ç®Ç!testoob/compatibility/optparse.py# This file is taken from the PyPy project, http://codespeak.net/pypy """optparse - a powerful, extensible, and easy-to-use option parser. By Greg Ward Originally distributed as Optik; see http://optik.sourceforge.net/ . If you have problems with this module, please do not file bugs, patches, or feature requests with Python; instead, use Optik's SourceForge project page: http://sourceforge.net/projects/optik For support, use the optik-users@lists.sourceforge.net mailing list (http://lists.sourceforge.net/lists/listinfo/optik-users). """ # Python developers: please do not make changes to this file, since # it is automatically generated from the Optik source code. __version__ = "1.4.1+" __all__ = ['Option', 'SUPPRESS_HELP', 'SUPPRESS_USAGE', 'STD_HELP_OPTION', 'STD_VERSION_OPTION', 'Values', 'OptionContainer', 'OptionGroup', 'OptionParser', 'HelpFormatter', 'IndentedHelpFormatter', 'TitledHelpFormatter', 'OptParseError', 'OptionError', 'OptionConflictError', 'OptionValueError', 'BadOptionError'] __copyright__ = """ Copyright (c) 2001-2003 Gregory P. Ward. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import sys, os import types import textwrap class OptParseError (Exception): def __init__ (self, msg): self.msg = msg def __str__ (self): return self.msg class OptionError (OptParseError): """ Raised if an Option instance is created with invalid or inconsistent arguments. """ def __init__ (self, msg, option): self.msg = msg self.option_id = str(option) def __str__ (self): if self.option_id: return "option %s: %s" % (self.option_id, self.msg) else: return self.msg class OptionConflictError (OptionError): """ Raised if conflicting options are added to an OptionParser. """ class OptionValueError (OptParseError): """ Raised if an invalid option value is encountered on the command line. """ class BadOptionError (OptParseError): """ Raised if an invalid or ambiguous option is seen on the command-line. """ class HelpFormatter: """ Abstract base class for formatting option help. OptionParser instances should use one of the HelpFormatter subclasses for formatting help; by default IndentedHelpFormatter is used. Instance attributes: indent_increment : int the number of columns to indent per nesting level max_help_position : int the maximum starting column for option help text help_position : int the calculated starting column for option help text; initially the same as the maximum width : int total number of columns for output level : int current indentation level current_indent : int current indentation level (in columns) help_width : int number of columns available for option help text (calculated) """ def __init__ (self, indent_increment, max_help_position, width, short_first): self.indent_increment = indent_increment self.help_position = self.max_help_position = max_help_position self.width = width self.current_indent = 0 self.level = 0 self.help_width = width - max_help_position self.short_first = short_first def indent (self): self.current_indent += self.indent_increment self.level += 1 def dedent (self): self.current_indent -= self.indent_increment assert self.current_indent >= 0, "Indent decreased below 0." self.level -= 1 def format_usage (self, usage): raise NotImplementedError, "subclasses must implement" def format_heading (self, heading): raise NotImplementedError, "subclasses must implement" def format_description (self, description): desc_width = self.width - self.current_indent indent = " "*self.current_indent return textwrap.fill(description, desc_width, initial_indent=indent, subsequent_indent=indent) def format_option (self, option): # The help for each option consists of two parts: # * the opt strings and metavars # eg. ("-x", or "-fFILENAME, --file=FILENAME") # * the user-supplied help string # eg. ("turn on expert mode", "read data from FILENAME") # # If possible, we write both of these on the same line: # -x turn on expert mode # # But if the opt string list is too long, we put the help # string on a second line, indented to the same column it would # start in if it fit on the first line. # -fFILENAME, --file=FILENAME # read data from FILENAME result = [] opts = option.option_strings opt_width = self.help_position - self.current_indent - 2 if len(opts) > opt_width: opts = "%*s%s\n" % (self.current_indent, "", opts) indent_first = self.help_position else: # start help on same line as opts opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts) indent_first = 0 result.append(opts) if option.help: help_lines = textwrap.wrap(option.help, self.help_width) result.append("%*s%s\n" % (indent_first, "", help_lines[0])) result.extend(["%*s%s\n" % (self.help_position, "", line) for line in help_lines[1:]]) elif opts[-1] != "\n": result.append("\n") return "".join(result) def store_option_strings (self, parser): self.indent() max_len = 0 for opt in parser.option_list: strings = self.format_option_strings(opt) opt.option_strings = strings max_len = max(max_len, len(strings) + self.current_indent) self.indent() for group in parser.option_groups: for opt in group.option_list: strings = self.format_option_strings(opt) opt.option_strings = strings max_len = max(max_len, len(strings) + self.current_indent) self.dedent() self.dedent() self.help_position = min(max_len + 2, self.max_help_position) def format_option_strings (self, option): """Return a comma-separated list of option strings & metavariables.""" if option.takes_value(): metavar = option.metavar or option.dest.upper() short_opts = [sopt + metavar for sopt in option._short_opts] long_opts = [lopt + "=" + metavar for lopt in option._long_opts] else: short_opts = option._short_opts long_opts = option._long_opts if self.short_first: opts = short_opts + long_opts else: opts = long_opts + short_opts return ", ".join(opts) class IndentedHelpFormatter (HelpFormatter): """Format help with indented section bodies. """ def __init__ (self, indent_increment=2, max_help_position=24, width=79, short_first=1): HelpFormatter.__init__( self, indent_increment, max_help_position, width, short_first) def format_usage (self, usage): return "usage: %s\n" % usage def format_heading (self, heading): return "%*s%s:\n" % (self.current_indent, "", heading) class TitledHelpFormatter (HelpFormatter): """Format help with underlined section headers. """ def __init__ (self, indent_increment=0, max_help_position=24, width=79, short_first=0): HelpFormatter.__init__ ( self, indent_increment, max_help_position, width, short_first) def format_usage (self, usage): return "%s %s\n" % (self.format_heading("Usage"), usage) def format_heading (self, heading): return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading)) _builtin_cvt = { "int" : (int, "integer"), "long" : (long, "long integer"), "float" : (float, "floating-point"), "complex" : (complex, "complex") } def check_builtin (option, opt, value): (cvt, what) = _builtin_cvt[option.type] try: return cvt(value) except ValueError: raise OptionValueError( #"%s: invalid %s argument %r" % (opt, what, value)) "option %s: invalid %s value: %r" % (opt, what, value)) def check_choice(option, opt, value): if value in option.choices: return value else: choices = ", ".join(map(repr, option.choices)) raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % (opt, value, choices)) # Not supplying a default is different from a default of None, # so we need an explicit "not supplied" value. NO_DEFAULT = "NO"+"DEFAULT" class Option: """ Instance attributes: _short_opts : [string] _long_opts : [string] action : string type : string dest : string default : any nargs : int const : any choices : [string] callback : function callback_args : (any*) callback_kwargs : { string : any } help : string metavar : string """ # The list of instance attributes that may be set through # keyword args to the constructor. ATTRS = ['action', 'type', 'dest', 'default', 'nargs', 'const', 'choices', 'callback', 'callback_args', 'callback_kwargs', 'help', 'metavar'] # The set of actions allowed by option parsers. Explicitly listed # here so the constructor can validate its arguments. ACTIONS = ("store", "store_const", "store_true", "store_false", "append", "count", "callback", "help", "version") # The set of actions that involve storing a value somewhere; # also listed just for constructor argument validation. (If # the action is one of these, there must be a destination.) STORE_ACTIONS = ("store", "store_const", "store_true", "store_false", "append", "count") # The set of actions for which it makes sense to supply a value # type, ie. where we expect an argument to this option. TYPED_ACTIONS = ("store", "append", "callback") # The set of known types for option parsers. Again, listed here for # constructor argument validation. TYPES = ("string", "int", "long", "float", "complex", "choice") # Dictionary of argument checking functions, which convert and # validate option arguments according to the option type. # # Signature of checking functions is: # check(option : Option, opt : string, value : string) -> any # where # option is the Option instance calling the checker # opt is the actual option seen on the command-line # (eg. "-a", "--file") # value is the option argument seen on the command-line # # The return value should be in the appropriate Python type # for option.type -- eg. an integer if option.type == "int". # # If no checker is defined for a type, arguments will be # unchecked and remain strings. TYPE_CHECKER = { "int" : check_builtin, "long" : check_builtin, "float" : check_builtin, "complex" : check_builtin, "choice" : check_choice, } # CHECK_METHODS is a list of unbound method objects; they are called # by the constructor, in order, after all attributes are # initialized. The list is created and filled in later, after all # the methods are actually defined. (I just put it here because I # like to define and document all class attributes in the same # place.) Subclasses that add another _check_*() method should # define their own CHECK_METHODS list that adds their check method # to those from this class. CHECK_METHODS = None # -- Constructor/initialization methods ---------------------------- def __init__ (self, *opts, **attrs): # Set _short_opts, _long_opts attrs from 'opts' tuple. # Have to be set now, in case no option strings are supplied. self._short_opts = [] self._long_opts = [] opts = self._check_opt_strings(opts) self._set_opt_strings(opts) # Set all other attrs (action, type, etc.) from 'attrs' dict self._set_attrs(attrs) # Check all the attributes we just set. There are lots of # complicated interdependencies, but luckily they can be farmed # out to the _check_*() methods listed in CHECK_METHODS -- which # could be handy for subclasses! The one thing these all share # is that they raise OptionError if they discover a problem. for checker in self.CHECK_METHODS: checker(self) def _check_opt_strings (self, opts): # Filter out None because early versions of Optik had exactly # one short option and one long option, either of which # could be None. opts = filter(None, opts) if not opts: raise TypeError("at least one option string must be supplied") return opts def _set_opt_strings (self, opts): for opt in opts: if len(opt) < 2: raise OptionError( "invalid option string %r: " "must be at least two characters long" % opt, self) elif len(opt) == 2: if not (opt[0] == "-" and opt[1] != "-"): raise OptionError( "invalid short option string %r: " "must be of the form -x, (x any non-dash char)" % opt, self) self._short_opts.append(opt) else: if not (opt[0:2] == "--" and opt[2] != "-"): raise OptionError( "invalid long option string %r: " "must start with --, followed by non-dash" % opt, self) self._long_opts.append(opt) def _set_attrs (self, attrs): for attr in self.ATTRS: if attrs.has_key(attr): setattr(self, attr, attrs[attr]) del attrs[attr] else: if attr == 'default': setattr(self, attr, NO_DEFAULT) else: setattr(self, attr, None) if attrs: raise OptionError( "invalid keyword arguments: %s" % ", ".join(attrs.keys()), self) # -- Constructor validation methods -------------------------------- def _check_action (self): if self.action is None: self.action = "store" elif self.action not in self.ACTIONS: raise OptionError("invalid action: %r" % self.action, self) def _check_type (self): if self.type is None: # XXX should factor out another class attr here: list of # actions that *require* a type if self.action in ("store", "append"): if self.choices is not None: # The "choices" attribute implies "choice" type. self.type = "choice" else: # No type given? "string" is the most sensible default. self.type = "string" else: if self.type not in self.TYPES: raise OptionError("invalid option type: %r" % self.type, self) if self.action not in self.TYPED_ACTIONS: raise OptionError( "must not supply a type for action %r" % self.action, self) def _check_choice(self): if self.type == "choice": if self.choices is None: raise OptionError( "must supply a list of choices for type 'choice'", self) elif type(self.choices) not in (types.TupleType, types.ListType): raise OptionError( "choices must be a list of strings ('%s' supplied)" % str(type(self.choices)).split("'")[1], self) elif self.choices is not None: raise OptionError( "must not supply choices for type %r" % self.type, self) def _check_dest (self): if self.action in self.STORE_ACTIONS and self.dest is None: # No destination given, and we need one for this action. # Glean a destination from the first long option string, # or from the first short option string if no long options. if self._long_opts: # eg. "--foo-bar" -> "foo_bar" self.dest = self._long_opts[0][2:].replace('-', '_') else: self.dest = self._short_opts[0][1] def _check_const (self): if self.action != "store_const" and self.const is not None: raise OptionError( "'const' must not be supplied for action %r" % self.action, self) def _check_nargs (self): if self.action in self.TYPED_ACTIONS: if self.nargs is None: self.nargs = 1 elif self.nargs is not None: raise OptionError( "'nargs' must not be supplied for action %r" % self.action, self) def _check_callback (self): if self.action == "callback": if not callable(self.callback): raise OptionError( "callback not callable: %r" % self.callback, self) if (self.callback_args is not None and type(self.callback_args) is not types.TupleType): raise OptionError( "callback_args, if supplied, must be a tuple: not %r" % self.callback_args, self) if (self.callback_kwargs is not None and type(self.callback_kwargs) is not types.DictType): raise OptionError( "callback_kwargs, if supplied, must be a dict: not %r" % self.callback_kwargs, self) else: if self.callback is not None: raise OptionError( "callback supplied (%r) for non-callback option" % self.callback, self) if self.callback_args is not None: raise OptionError( "callback_args supplied for non-callback option", self) if self.callback_kwargs is not None: raise OptionError( "callback_kwargs supplied for non-callback option", self) CHECK_METHODS = [_check_action, _check_type, _check_choice, _check_dest, _check_const, _check_nargs, _check_callback] # -- Miscellaneous methods ----------------------------------------- def __str__ (self): return "/".join(self._short_opts + self._long_opts) def takes_value (self): return self.type is not None # -- Processing methods -------------------------------------------- def check_value (self, opt, value): checker = self.TYPE_CHECKER.get(self.type) if checker is None: return value else: return checker(self, opt, value) def process (self, opt, value, values, parser): # First, convert the value(s) to the right type. Howl if any # value(s) are bogus. if value is not None: if self.nargs == 1: value = self.check_value(opt, value) else: value = tuple([self.check_value(opt, v) for v in value]) # And then take whatever action is expected of us. # This is a separate method to make life easier for # subclasses to add new actions. return self.take_action( self.action, self.dest, opt, value, values, parser) def take_action (self, action, dest, opt, value, values, parser): if action == "store": setattr(values, dest, value) elif action == "store_const": setattr(values, dest, self.const) elif action == "store_true": setattr(values, dest, True) elif action == "store_false": setattr(values, dest, False) elif action == "append": values.ensure_value(dest, []).append(value) elif action == "count": setattr(values, dest, values.ensure_value(dest, 0) + 1) elif action == "callback": args = self.callback_args or () kwargs = self.callback_kwargs or {} self.callback(self, opt, value, parser, *args, **kwargs) elif action == "help": parser.print_help() sys.exit(0) elif action == "version": parser.print_version() sys.exit(0) else: raise RuntimeError, "unknown action %r" % self.action return 1 # class Option def get_prog_name (): return os.path.basename(sys.argv[0]) SUPPRESS_HELP = "SUPPRESS"+"HELP" SUPPRESS_USAGE = "SUPPRESS"+"USAGE" STD_HELP_OPTION = Option("-h", "--help", action="help", help="show this help message and exit") STD_VERSION_OPTION = Option("--version", action="version", help="show program's version number and exit") class Values: def __init__ (self, defaults=None): if defaults: for (attr, val) in defaults.items(): setattr(self, attr, val) def __repr__ (self): return ("<%s at 0x%x: %r>" % (self.__class__.__name__, id(self), self.__dict__)) def _update_careful (self, dict): """ Update the option values from an arbitrary dictionary, but only use keys from dict that already have a corresponding attribute in self. Any keys in dict without a corresponding attribute are silently ignored. """ for attr in dir(self): if dict.has_key(attr): dval = dict[attr] if dval is not None: setattr(self, attr, dval) def _update_loose (self, dict): """ Update the option values from an arbitrary dictionary, using all keys from the dictionary regardless of whether they have a corresponding attribute in self or not. """ self.__dict__.update(dict) def _update (self, dict, mode): if mode == "careful": self._update_careful(dict) elif mode == "loose": self._update_loose(dict) else: raise ValueError, "invalid update mode: %r" % mode def read_module (self, modname, mode="careful"): __import__(modname) mod = sys.modules[modname] self._update(vars(mod), mode) def read_file (self, filename, mode="careful"): vars = {} execfile(filename, vars) self._update(vars, mode) def ensure_value (self, attr, value): if not hasattr(self, attr) or getattr(self, attr) is None: setattr(self, attr, value) return getattr(self, attr) class OptionContainer: """ Abstract base class. Class attributes: standard_option_list : [Option] list of standard options that will be accepted by all instances of this parser class (intended to be overridden by subclasses). Instance attributes: option_list : [Option] the list of Option objects contained by this OptionContainer _short_opt : { string : Option } dictionary mapping short option strings, eg. "-f" or "-X", to the Option instances that implement them. If an Option has multiple short option strings, it will appears in this dictionary multiple times. [1] _long_opt : { string : Option } dictionary mapping long option strings, eg. "--file" or "--exclude", to the Option instances that implement them. Again, a given Option can occur multiple times in this dictionary. [1] defaults : { string : any } dictionary mapping option destination names to default values for each destination [1] [1] These mappings are common to (shared by) all components of the controlling OptionParser, where they are initially created. """ def __init__ (self, option_class, conflict_handler, description): # Initialize the option list and related data structures. # This method must be provided by subclasses, and it must # initialize at least the following instance attributes: # option_list, _short_opt, _long_opt, defaults. self._create_option_list() self.option_class = option_class self.set_conflict_handler(conflict_handler) self.set_description(description) def _create_option_mappings (self): # For use by OptionParser constructor -- create the master # option mappings used by this OptionParser and all # OptionGroups that it owns. self._short_opt = {} # single letter -> Option instance self._long_opt = {} # long option -> Option instance self.defaults = {} # maps option dest -> default value def _share_option_mappings (self, parser): # For use by OptionGroup constructor -- use shared option # mappings from the OptionParser that owns this OptionGroup. self._short_opt = parser._short_opt self._long_opt = parser._long_opt self.defaults = parser.defaults def set_conflict_handler (self, handler): if handler not in ("ignore", "error", "resolve"): raise ValueError, "invalid conflict_resolution value %r" % handler self.conflict_handler = handler def set_description (self, description): self.description = description # -- Option-adding methods ----------------------------------------- def _check_conflict (self, option): conflict_opts = [] for opt in option._short_opts: if self._short_opt.has_key(opt): conflict_opts.append((opt, self._short_opt[opt])) for opt in option._long_opts: if self._long_opt.has_key(opt): conflict_opts.append((opt, self._long_opt[opt])) if conflict_opts: handler = self.conflict_handler if handler == "ignore": # behaviour for Optik 1.0, 1.1 pass elif handler == "error": # new in 1.2 raise OptionConflictError( "conflicting option string(s): %s" % ", ".join([co[0] for co in conflict_opts]), option) elif handler == "resolve": # new in 1.2 for (opt, c_option) in conflict_opts: if opt.startswith("--"): c_option._long_opts.remove(opt) del self._long_opt[opt] else: c_option._short_opts.remove(opt) del self._short_opt[opt] if not (c_option._short_opts or c_option._long_opts): c_option.container.option_list.remove(c_option) def add_option (self, *args, **kwargs): """add_option(Option) add_option(opt_str, ..., kwarg=val, ...) """ if type(args[0]) is types.StringType: option = self.option_class(*args, **kwargs) elif len(args) == 1 and not kwargs: option = args[0] if not isinstance(option, Option): raise TypeError, "not an Option instance: %r" % option else: raise TypeError, "invalid arguments" self._check_conflict(option) self.option_list.append(option) option.container = self for opt in option._short_opts: self._short_opt[opt] = option for opt in option._long_opts: self._long_opt[opt] = option if option.dest is not None: # option has a dest, we need a default if option.default is not NO_DEFAULT: self.defaults[option.dest] = option.default elif not self.defaults.has_key(option.dest): self.defaults[option.dest] = None return option def add_options (self, option_list): for option in option_list: self.add_option(option) # -- Option query/removal methods ---------------------------------- def get_option (self, opt_str): return (self._short_opt.get(opt_str) or self._long_opt.get(opt_str)) def has_option (self, opt_str): return (self._short_opt.has_key(opt_str) or self._long_opt.has_key(opt_str)) def remove_option (self, opt_str): option = self._short_opt.get(opt_str) if option is None: option = self._long_opt.get(opt_str) if option is None: raise ValueError("no such option %r" % opt_str) for opt in option._short_opts: del self._short_opt[opt] for opt in option._long_opts: del self._long_opt[opt] option.container.option_list.remove(option) # -- Help-formatting methods --------------------------------------- def format_option_help (self, formatter): if not self.option_list: return "" result = [] for option in self.option_list: if not option.help is SUPPRESS_HELP: result.append(formatter.format_option(option)) return "".join(result) def format_description (self, formatter): if self.description: return formatter.format_description(self.description) else: return "" def format_help (self, formatter): if self.description: desc = self.format_description(formatter) + "\n" else: desc = "" return desc + self.format_option_help(formatter) class OptionGroup (OptionContainer): def __init__ (self, parser, title, description=None): self.parser = parser OptionContainer.__init__( self, parser.option_class, parser.conflict_handler, description) self.title = title def _create_option_list (self): self.option_list = [] self._share_option_mappings(self.parser) def set_title (self, title): self.title = title # -- Help-formatting methods --------------------------------------- def format_help (self, formatter): result = formatter.format_heading(self.title) formatter.indent() result += OptionContainer.format_help(self, formatter) formatter.dedent() return result class OptionParser (OptionContainer): """ Class attributes: standard_option_list : [Option] list of standard options that will be accepted by all instances of this parser class (intended to be overridden by subclasses). Instance attributes: usage : string a usage string for your program. Before it is displayed to the user, "%prog" will be expanded to the name of your program (self.prog or os.path.basename(sys.argv[0])). prog : string the name of the current program (to override os.path.basename(sys.argv[0])). allow_interspersed_args : boolean = true if true, positional arguments may be interspersed with options. Assuming -a and -b each take a single argument, the command-line -ablah foo bar -bboo baz will be interpreted the same as -ablah -bboo -- foo bar baz If this flag were false, that command line would be interpreted as -ablah -- foo bar -bboo baz -- ie. we stop processing options as soon as we see the first non-option argument. (This is the tradition followed by Python's getopt module, Perl's Getopt::Std, and other argument- parsing libraries, but it is generally annoying to users.) rargs : [string] the argument list currently being parsed. Only set when parse_args() is active, and continually trimmed down as we consume arguments. Mainly there for the benefit of callback options. largs : [string] the list of leftover arguments that we have skipped while parsing options. If allow_interspersed_args is false, this list is always empty. values : Values the set of option values currently being accumulated. Only set when parse_args() is active. Also mainly for callbacks. Because of the 'rargs', 'largs', and 'values' attributes, OptionParser is not thread-safe. If, for some perverse reason, you need to parse command-line arguments simultaneously in different threads, use different OptionParser instances. """ standard_option_list = [] def __init__ (self, usage=None, option_list=None, option_class=Option, version=None, conflict_handler="error", description=None, formatter=None, add_help_option=1, prog=None): OptionContainer.__init__( self, option_class, conflict_handler, description) self.set_usage(usage) self.prog = prog self.version = version self.allow_interspersed_args = 1 if formatter is None: formatter = IndentedHelpFormatter() self.formatter = formatter # Populate the option list; initial sources are the # standard_option_list class attribute, the 'option_list' # argument, and the STD_VERSION_OPTION (if 'version' supplied) # and STD_HELP_OPTION globals. self._populate_option_list(option_list, add_help=add_help_option) self._init_parsing_state() # -- Private methods ----------------------------------------------- # (used by our or OptionContainer's constructor) def _create_option_list (self): self.option_list = [] self.option_groups = [] self._create_option_mappings() def _populate_option_list (self, option_list, add_help=1): if self.standard_option_list: self.add_options(self.standard_option_list) if option_list: self.add_options(option_list) if self.version: self.add_option(STD_VERSION_OPTION) if add_help: self.add_option(STD_HELP_OPTION) def _init_parsing_state (self): # These are set in parse_args() for the convenience of callbacks. self.rargs = None self.largs = None self.values = None def _get_prog_name(self): if self.prog: return self.prog else: return get_prog_name() # -- Simple modifier methods --------------------------------------- def set_usage (self, usage): if usage is None: self.usage = "%prog [options]" elif usage is SUPPRESS_USAGE: self.usage = None elif usage.startswith("usage: "): # for backwards compatibility with Optik 1.3 and earlier self.usage = usage[7:] else: self.usage = usage def enable_interspersed_args (self): self.allow_interspersed_args = 1 def disable_interspersed_args (self): self.allow_interspersed_args = 0 def set_default (self, dest, value): self.defaults[dest] = value def set_defaults (self, **kwargs): self.defaults.update(kwargs) def get_default_values (self): return Values(self.defaults) # -- OptionGroup methods ------------------------------------------- def add_option_group (self, *args, **kwargs): # XXX lots of overlap with OptionContainer.add_option() if type(args[0]) is types.StringType: group = OptionGroup(self, *args, **kwargs) elif len(args) == 1 and not kwargs: group = args[0] if not isinstance(group, OptionGroup): raise TypeError, "not an OptionGroup instance: %r" % group if group.parser is not self: raise ValueError, "invalid OptionGroup (wrong parser)" else: raise TypeError, "invalid arguments" self.option_groups.append(group) return group def get_option_group (self, opt_str): option = (self._short_opt.get(opt_str) or self._long_opt.get(opt_str)) if option and option.container is not self: return option.container return None # -- Option-parsing methods ---------------------------------------- def _get_args (self, args): if args is None: return sys.argv[1:] else: return args[:] # don't modify caller's list def parse_args (self, args=None, values=None): """ parse_args(args : [string] = sys.argv[1:], values : Values = None) -> (values : Values, args : [string]) Parse the command-line options found in 'args' (default: sys.argv[1:]). Any errors result in a call to 'error()', which by default prints the usage message to stderr and calls sys.exit() with an error message. On success returns a pair (values, args) where 'values' is an Values instance (with all your option values) and 'args' is the list of arguments left over after parsing options. """ rargs = self._get_args(args) if values is None: values = self.get_default_values() # Store the halves of the argument list as attributes for the # convenience of callbacks: # rargs # the rest of the command-line (the "r" stands for # "remaining" or "right-hand") # largs # the leftover arguments -- ie. what's left after removing # options and their arguments (the "l" stands for "leftover" # or "left-hand") self.rargs = rargs self.largs = largs = [] self.values = values try: stop = self._process_args(largs, rargs, values) except (BadOptionError, OptionValueError), err: self.error(err.msg) args = largs + rargs return self.check_values(values, args) def check_values (self, values, args): """ check_values(values : Values, args : [string]) -> (values : Values, args : [string]) Check that the supplied option values and leftover arguments are valid. Returns the option values and leftover arguments (possibly adjusted, possibly completely new -- whatever you like). Default implementation just returns the passed-in values; subclasses may override as desired. """ return (values, args) def _process_args (self, largs, rargs, values): """_process_args(largs : [string], rargs : [string], values : Values) Process command-line arguments and populate 'values', consuming options and arguments from 'rargs'. If 'allow_interspersed_args' is false, stop at the first non-option argument. If true, accumulate any interspersed non-option arguments in 'largs'. """ while rargs: arg = rargs[0] # We handle bare "--" explicitly, and bare "-" is handled by the # standard arg handler since the short arg case ensures that the # len of the opt string is greater than 1. if arg == "--": del rargs[0] return elif arg[0:2] == "--": # process a single long option (possibly with value(s)) self._process_long_opt(rargs, values) elif arg[:1] == "-" and len(arg) > 1: # process a cluster of short options (possibly with # value(s) for the last one only) self._process_short_opts(rargs, values) elif self.allow_interspersed_args: largs.append(arg) del rargs[0] else: return # stop now, leave this arg in rargs # Say this is the original argument list: # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] # ^ # (we are about to process arg(i)). # # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of # [arg0, ..., arg(i-1)] (any options and their arguments will have # been removed from largs). # # The while loop will usually consume 1 or more arguments per pass. # If it consumes 1 (eg. arg is an option that takes no arguments), # then after _process_arg() is done the situation is: # # largs = subset of [arg0, ..., arg(i)] # rargs = [arg(i+1), ..., arg(N-1)] # # If allow_interspersed_args is false, largs will always be # *empty* -- still a subset of [arg0, ..., arg(i-1)], but # not a very interesting subset! def _match_long_opt (self, opt): """_match_long_opt(opt : string) -> string Determine which long option string 'opt' matches, ie. which one it is an unambiguous abbrevation for. Raises BadOptionError if 'opt' doesn't unambiguously match any long option string. """ return _match_abbrev(opt, self._long_opt) def _process_long_opt (self, rargs, values): arg = rargs.pop(0) # Value explicitly attached to arg? Pretend it's the next # argument. if "=" in arg: (opt, next_arg) = arg.split("=", 1) rargs.insert(0, next_arg) had_explicit_value = 1 else: opt = arg had_explicit_value = 0 opt = self._match_long_opt(opt) option = self._long_opt[opt] if option.takes_value(): nargs = option.nargs if len(rargs) < nargs: if nargs == 1: self.error("%s option requires a value" % opt) else: self.error("%s option requires %d values" % (opt, nargs)) elif nargs == 1: value = rargs.pop(0) else: value = tuple(rargs[0:nargs]) del rargs[0:nargs] elif had_explicit_value: self.error("%s option does not take a value" % opt) else: value = None option.process(opt, value, values, self) def _process_short_opts (self, rargs, values): arg = rargs.pop(0) stop = 0 i = 1 for ch in arg[1:]: opt = "-" + ch option = self._short_opt.get(opt) i += 1 # we have consumed a character if not option: self.error("no such option: %s" % opt) if option.takes_value(): # Any characters left in arg? Pretend they're the # next arg, and stop consuming characters of arg. if i < len(arg): rargs.insert(0, arg[i:]) stop = 1 nargs = option.nargs if len(rargs) < nargs: if nargs == 1: self.error("%s option requires a value" % opt) else: self.error("%s option requires %s values" % (opt, nargs)) elif nargs == 1: value = rargs.pop(0) else: value = tuple(rargs[0:nargs]) del rargs[0:nargs] else: # option doesn't take a value value = None option.process(opt, value, values, self) if stop: break # -- Feedback methods ---------------------------------------------- def error (self, msg): """error(msg : string) Print a usage message incorporating 'msg' to stderr and exit. If you override this in a subclass, it should not return -- it should either exit or raise an exception. """ self.print_usage(sys.stderr) sys.exit("%s: error: %s" % (self._get_prog_name(), msg)) def get_usage (self): if self.usage: return self.formatter.format_usage( self.usage.replace("%prog", self._get_prog_name())) else: return "" def print_usage (self, file=None): """print_usage(file : file = stdout) Print the usage message for the current program (self.usage) to 'file' (default stdout). Any occurence of the string "%prog" in self.usage is replaced with the name of the current program (basename of sys.argv[0]). Does nothing if self.usage is empty or not defined. """ if self.usage: print >>file, self.get_usage() def get_version (self): if self.version: return self.version.replace("%prog", self._get_prog_name()) else: return "" def print_version (self, file=None): """print_version(file : file = stdout) Print the version message for this program (self.version) to 'file' (default stdout). As with print_usage(), any occurence of "%prog" in self.version is replaced by the current program's name. Does nothing if self.version is empty or undefined. """ if self.version: print >>file, self.get_version() def format_option_help (self, formatter=None): if formatter is None: formatter = self.formatter formatter.store_option_strings(self) result = [] result.append(formatter.format_heading("options")) formatter.indent() if self.option_list: result.append(OptionContainer.format_option_help(self, formatter)) result.append("\n") for group in self.option_groups: result.append(group.format_help(formatter)) result.append("\n") formatter.dedent() # Drop the last "\n", or the header if no options or option groups: return "".join(result[:-1]) def format_help (self, formatter=None): if formatter is None: formatter = self.formatter result = [] if self.usage: result.append(self.get_usage() + "\n") if self.description: result.append(self.format_description(formatter) + "\n") result.append(self.format_option_help(formatter)) return "".join(result) def print_help (self, file=None): """print_help(file : file = stdout) Print an extended help message, listing all options and any help text provided with them, to 'file' (default stdout). """ if file is None: file = sys.stdout file.write(self.format_help()) # class OptionParser def _match_abbrev (s, wordmap): """_match_abbrev(s : string, wordmap : {string : Option}) -> string Return the string key in 'wordmap' for which 's' is an unambiguous abbreviation. If 's' is found to be ambiguous or doesn't match any of 'words', raise BadOptionError. """ # Is there an exact match? if wordmap.has_key(s): return s else: # Isolate all words with s as a prefix. possibilities = [word for word in wordmap.keys() if word.startswith(s)] # No exact match, so there had better be just one possibility. if len(possibilities) == 1: return possibilities[0] elif not possibilities: raise BadOptionError("no such option: %s" % s) else: # More than one possible completion: ambiguous prefix. raise BadOptionError("ambiguous option: %s (%s?)" % (s, ", ".join(possibilities))) # Some day, there might be many Option classes. As of Optik 1.3, the # preferred way to instantiate Options is indirectly, via make_option(), # which will become a factory function when there are many Option # classes. make_option = Option PK'ƒ5{˜´öÛÛ"testoob/compatibility/optparse.pyc;ò ÊŸ¦Dc@sBdZdZdddddddd d d d d dddddgZdZdkZdkZdkZdkZdefd„ƒYZ de fd„ƒYZ de fd„ƒYZ de fd„ƒYZ de fd„ƒYZ d fd„ƒYZd efd„ƒYZd efd„ƒYZhdedf<ded f<d!ed"f<d#ed#f Originally distributed as Optik; see http://optik.sourceforge.net/ . If you have problems with this module, please do not file bugs, patches, or feature requests with Python; instead, use Optik's SourceForge project page: http://sourceforge.net/projects/optik For support, use the optik-users@lists.sourceforge.net mailing list (http://lists.sourceforge.net/lists/listinfo/optik-users). s1.4.1+sOptions SUPPRESS_HELPsSUPPRESS_USAGEsSTD_HELP_OPTIONsSTD_VERSION_OPTIONsValuessOptionContainers OptionGroups OptionParsers HelpFormattersIndentedHelpFormattersTitledHelpFormatters OptParseErrors OptionErrorsOptionConflictErrorsOptionValueErrorsBadOptionErrorsØ Copyright (c) 2001-2003 Gregory P. Ward. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. NcBstZd„Zd„ZRS(NcCs ||_dS(N(smsgsself(sselfsmsg((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys__init__LscCs |iSdS(N(sselfsmsg(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys__str__Os(s__name__s __module__s__init__s__str__(((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys OptParseErrorKs cBs tZdZd„Zd„ZRS(s] Raised if an Option instance is created with invalid or inconsistent arguments. cCs||_t|ƒ|_dS(N(smsgsselfsstrsoptions option_id(sselfsmsgsoption((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys__init__Ys cCs-|iod|i|ifSn|iSdS(Ns option %s: %s(sselfs option_idsmsg(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys__str__]s (s__name__s __module__s__doc__s__init__s__str__(((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys OptionErrorSs  cBstZdZRS(sE Raised if conflicting options are added to an OptionParser. (s__name__s __module__s__doc__(((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysOptionConflictErrorcs cBstZdZRS(sS Raised if an invalid option value is encountered on the command line. (s__name__s __module__s__doc__(((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysOptionValueErrorhs cBstZdZRS(sO Raised if an invalid or ambiguous option is seen on the command-line. (s__name__s __module__s__doc__(((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysBadOptionErrorns cBs_tZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z RS( s( Abstract base class for formatting option help. OptionParser instances should use one of the HelpFormatter subclasses for formatting help; by default IndentedHelpFormatter is used. Instance attributes: indent_increment : int the number of columns to indent per nesting level max_help_position : int the maximum starting column for option help text help_position : int the calculated starting column for option help text; initially the same as the maximum width : int total number of columns for output level : int current indentation level current_indent : int current indentation level (in columns) help_width : int number of columns available for option help text (calculated) cCsN||_||_|_||_d|_d|_|||_||_dS(Ni( sindent_incrementsselfsmax_help_positions help_positionswidthscurrent_indentslevels help_widths short_first(sselfsindent_incrementsmax_help_positionswidths short_first((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys__init__s     cCs%|i|i7_|id7_dS(Ni(sselfscurrent_indentsindent_incrementslevel(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysindentšscCs?|i|i8_|idjp td‚|id8_dS(NisIndent decreased below 0.i(sselfscurrent_indentsindent_incrementsAssertionErrorslevel(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysdedentžscCs td‚dS(Nssubclasses must implement(sNotImplementedError(sselfsusage((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys format_usage£scCs td‚dS(Nssubclasses must implement(sNotImplementedError(sselfsheading((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysformat_heading¦scCs=|i|i}d|i}ti||d|d|ƒSdS(Ns sinitial_indentssubsequent_indent(sselfswidthscurrent_indents desc_widthsindentstextwrapsfills description(sselfs descriptions desc_widthsindent((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysformat_description©s   c Cs>g}|i}|i|id}t|ƒ|jo#d|id|f}|i}n d|id||f}d}|i |ƒ|i o|t i |i |iƒ}|i d|d|dfƒ|igi }|dD] }|d|id|fƒqÝ~ƒn#|ddjo|i dƒndi|ƒSdS( Nis%*s%s ss %*s%-*s iiiÿÿÿÿs (sresultsoptionsoption_stringssoptssselfs help_positionscurrent_indents opt_widthslens indent_firstsappendshelpstextwrapswraps help_widths help_linessextends_[1]slinesjoin( sselfsoptions indent_firsts_[1]s opt_widthsresultslinesoptss help_lines((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys format_option°s     FcCsï|iƒd}xE|iD]:}|i|ƒ}||_t |t |ƒ|i ƒ}qW|iƒxY|i D]N}xE|iD]:}|i|ƒ}||_t |t |ƒ|i ƒ}q|WqlW|iƒ|iƒt|d|iƒ|_dS(Nii(sselfsindentsmax_lensparsers option_listsoptsformat_option_stringssstringssoption_stringssmaxslenscurrent_indents option_groupssgroupsdedentsminsmax_help_positions help_position(sselfsparsersoptsgroupsmax_lensstrings((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysstore_option_stringsÒs$        $  c CsÏ|iƒo}|ip |iiƒ}gi}|iD]}|||ƒq7~}gi}|i D]}||d|ƒqe~}n|i}|i }|io||}n ||}di|ƒSdS(s@Return a comma-separated list of option strings & metavariables.s=s, N(soptions takes_valuesmetavarsdestsuppersappends_[1]s _short_optsssopts short_optss _long_optsslopts long_optssselfs short_firstsoptssjoin( sselfsoptions long_optssloptssoptsmetavars_[1]s short_optssopts((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysformat_option_stringsãs .6    ( s__name__s __module__s__doc__s__init__sindentsdedents format_usagesformat_headingsformat_descriptions format_optionsstore_option_stringssformat_option_strings(((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys HelpFormatterts       " cBs5tZdZddddd„Zd„Zd„ZRS(s.Format help with indented section bodies. iiiOicCsti|||||ƒdS(N(s HelpFormatters__init__sselfsindent_incrementsmax_help_positionswidths short_first(sselfsindent_incrementsmax_help_positionswidths short_first((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys__init__øscCs d|SdS(Ns usage: %s (susage(sselfsusage((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys format_usagescCsd|id|fSdS(Ns%*s%s: s(sselfscurrent_indentsheading(sselfsheading((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysformat_headings(s__name__s __module__s__doc__s__init__s format_usagesformat_heading(((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysIndentedHelpFormatterôs  cBs5tZdZddddd„Zd„Zd„ZRS(s1Format help with underlined section headers. iiiOcCsti|||||ƒdS(N(s HelpFormatters__init__sselfsindent_incrementsmax_help_positionswidths short_first(sselfsindent_incrementsmax_help_positionswidths short_first((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys__init__ scCsd|idƒ|fSdS(Ns%s %s sUsage(sselfsformat_headingsusage(sselfsusage((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys format_usagescCs#d|d|it|ƒfSdS(Ns%s %s s=-(sheadingsselfslevelslen(sselfsheading((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysformat_headings(s__name__s __module__s__doc__s__init__s format_usagesformat_heading(((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysTitledHelpFormatters  sintsintegerslongs long integersfloatsfloating-pointscomplexcCsTt|i\}}y||ƒSWn,tj o td|||fƒ‚nXdS(Nsoption %s: invalid %s value: %r( s _builtin_cvtsoptionstypescvtswhatsvalues ValueErrorsOptionValueErrorsopt(soptionsoptsvalueswhatscvt((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys check_builtins cCsP||ijo|Sn5ditt|iƒƒ}td|||fƒ‚dS(Ns, s.option %s: invalid choice: %r (choose from %s)(svaluesoptionschoicessjoinsmapsreprsOptionValueErrorsopt(soptionsoptsvalueschoices((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys check_choice(ssNOsDEFAULTc Bs|tZdZddddddddd d d d g Zd ddddddd df Zd dddddfZd ddfZddddddfZhde<de<de<de<de invalid option string %r: must be at least two characters longis-isMinvalid short option string %r: must be of the form -x, (x any non-dash char)s--sGinvalid long option string %r: must start with --, followed by non-dash(soptssoptslens OptionErrorsselfs _short_optssappends _long_opts(sselfsoptssopt((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys_set_opt_stringsºs  #  &  cCs¥xq|iD]f}|i|ƒot||||ƒ||=q |djot||tƒq t||tƒq W|o&tddi |i ƒƒ|ƒ‚ndS(Nsdefaultsinvalid keyword arguments: %ss, ( sselfsATTRSsattrsattrsshas_keyssetattrs NO_DEFAULTsNones OptionErrorsjoinskeys(sselfsattrssattr((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys _set_attrsÏs   cCsN|itjo d|_n.|i|ijotd|i|ƒ‚ndS(Nsstoresinvalid action: %r(sselfsactionsNonesACTIONSs OptionError(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys _check_actionás cCs²|itjoD|iddfjo*|itj o d|_qPd|_q®n[|i|ijotd|i|ƒ‚n|i|ijotd|i|ƒ‚ndS(Nsstoresappendschoicesstringsinvalid option type: %rs$must not supply a type for action %r(sselfstypesNonesactionschoicessTYPESs OptionErrors TYPED_ACTIONS(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys _check_typeçs cCsº|idjo||itjotd|ƒ‚q¶t|iƒtitifjo3tdtt|iƒƒi dƒd|ƒ‚q¶n+|itj otd|i|ƒ‚ndS(Nschoices/must supply a list of choices for type 'choice's1choices must be a list of strings ('%s' supplied)s'is#must not supply choices for type %r( sselfstypeschoicessNones OptionErrorstypess TupleTypesListTypesstrssplit(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys _check_choiceùs"&cCsm|i|ijo |itjoF|io$|iddiddƒ|_qi|idd|_ndS(Niis-s_i(sselfsactions STORE_ACTIONSsdestsNones _long_optssreplaces _short_opts(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys _check_dests# $cCs>|idjo |itj otd|i|ƒ‚ndS(Ns store_consts*'const' must not be supplied for action %r(sselfsactionsconstsNones OptionError(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys _check_consts  cCsb|i|ijo!|itjo d|_q^n+|itj otd|i|ƒ‚ndS(Nis*'nargs' must not be supplied for action %r(sselfsactions TYPED_ACTIONSsnargssNones OptionError(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys _check_nargss  cCs9|idjoµt|iƒ otd|i|ƒ‚n|itj ot|iƒti j otd|i|ƒ‚n|i tj ot|i ƒti j otd|i |ƒ‚q5nq|itj otd|i|ƒ‚n|itj otd|ƒ‚n|i tj otd|ƒ‚ndS(Nscallbackscallback not callable: %rs3callback_args, if supplied, must be a tuple: not %rs4callback_kwargs, if supplied, must be a dict: not %rs.callback supplied (%r) for non-callback options.callback_args supplied for non-callback options0callback_kwargs supplied for non-callback option( sselfsactionscallablescallbacks OptionErrors callback_argssNonestypestypess TupleTypescallback_kwargssDictType(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys_check_callback s )  )   cCsdi|i|iƒSdS(Ns/(sjoinsselfs _short_optss _long_opts(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys__str__GscCs|itj SdS(N(sselfstypesNone(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys takes_valueJscCs>|ii|iƒ}|tjo|Sn||||ƒSdS(N(sselfs TYPE_CHECKERsgetstypescheckersNonesvaluesopt(sselfsoptsvalueschecker((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys check_valuePs cCs–|tj oc|idjo|i||ƒ}qptgi}|D]}||i||ƒƒqD~ƒ}n|i |i |i ||||ƒSdS(Ni(svaluesNonesselfsnargss check_valuesoptstuplesappends_[1]svs take_actionsactionsdestsvaluessparser(sselfsoptsvaluesvaluessparsers_[1]sv((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysprocessWs  =c Cs—|djot|||ƒno|djot|||iƒnK|djot||tƒn*|djot||tƒn |djo|i |gƒi |ƒnß|djo$t|||i |dƒdƒn®|d jo@|i pf}|i ph}|i||||||Žna|d jo|iƒtidƒn9|d jo|iƒtidƒntd |i‚dSdS( Nsstores store_consts store_trues store_falsesappendscountiiscallbackshelpsversionsunknown action %r(sactionssetattrsvaluessdestsvaluesselfsconstsTruesFalses ensure_valuesappends callback_argssargsscallback_kwargsskwargsscallbacksoptsparsers print_helpssyssexits print_versions RuntimeError( sselfsactionsdestsoptsvaluesvaluessparsersargsskwargs((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys take_actiongs0      $      (s__name__s __module__s__doc__sATTRSsACTIONSs STORE_ACTIONSs TYPED_ACTIONSsTYPESs check_builtins check_choices TYPE_CHECKERsNones CHECK_METHODSs__init__s_check_opt_stringss_set_opt_stringss _set_attrss _check_actions _check_types _check_choices _check_dests _check_consts _check_nargss_check_callbacks__str__s takes_values check_valuesprocesss take_action(((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysOption6s2 *!  3           cCstiitidƒSdS(Ni(sosspathsbasenamessyssargv(((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys get_prog_name†ssSUPPRESSsHELPsUSAGEs-hs--helpsactionshelpsshow this help message and exits --versionsversions&show program's version number and exitcBsYtZed„Zd„Zd„Zd„Zd„Zdd„Zdd„Z d „Z RS( NcCs<|o1x.|iƒD]\}}t|||ƒqWndS(N(sdefaultssitemssattrsvalssetattrsself(sselfsdefaultssvalsattr((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys__init__—s cCs$d|iit|ƒ|ifSdS(Ns<%s at 0x%x: %r>(sselfs __class__s__name__sids__dict__(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys__repr__œscCsZxSt|ƒD]E}|i|ƒo/||}|tj ot|||ƒqRq q WdS(sû Update the option values from an arbitrary dictionary, but only use keys from dict that already have a corresponding attribute in self. Any keys in dict without a corresponding attribute are silently ignored. N(sdirsselfsattrsdictshas_keysdvalsNonessetattr(sselfsdictsattrsdval((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys_update_careful s   cCs|ii|ƒdS(sÅ Update the option values from an arbitrary dictionary, using all keys from the dictionary regardless of whether they have a corresponding attribute in self or not. N(sselfs__dict__supdatesdict(sselfsdict((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys _update_loose­scCsM|djo|i|ƒn,|djo|i|ƒntd|‚dS(Nscarefulsloosesinvalid update mode: %r(smodesselfs_update_carefulsdicts _update_looses ValueError(sselfsdictsmode((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys_updateµs   scarefulcCs1t|ƒti|}|it|ƒ|ƒdS(N( s __import__smodnamessyssmodulessmodsselfs_updatesvarssmode(sselfsmodnamesmodesmod((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys read_module½s  cCs'h}t||ƒ|i||ƒdS(N(svarssexecfilesfilenamesselfs_updatesmode(sselfsfilenamesmodesvars((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys read_fileÂs cCsLt||ƒ pt||ƒtjot|||ƒnt||ƒSdS(N(shasattrsselfsattrsgetattrsNonessetattrsvalue(sselfsattrsvalue((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys ensure_valueÇs'( s__name__s __module__sNones__init__s__repr__s_update_carefuls _update_looses_updates read_modules read_files ensure_value(((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysValues•s      cBsŒtZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z d „Z d „Z d „Zd „Zd„ZRS(s“ Abstract base class. Class attributes: standard_option_list : [Option] list of standard options that will be accepted by all instances of this parser class (intended to be overridden by subclasses). Instance attributes: option_list : [Option] the list of Option objects contained by this OptionContainer _short_opt : { string : Option } dictionary mapping short option strings, eg. "-f" or "-X", to the Option instances that implement them. If an Option has multiple short option strings, it will appears in this dictionary multiple times. [1] _long_opt : { string : Option } dictionary mapping long option strings, eg. "--file" or "--exclude", to the Option instances that implement them. Again, a given Option can occur multiple times in this dictionary. [1] defaults : { string : any } dictionary mapping option destination names to default values for each destination [1] [1] These mappings are common to (shared by) all components of the controlling OptionParser, where they are initially created. cCs1|iƒ||_|i|ƒ|i|ƒdS(N(sselfs_create_option_lists option_classsset_conflict_handlersconflict_handlersset_descriptions description(sselfs option_classsconflict_handlers description((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys__init__ís   cCsh|_h|_h|_dS(N(sselfs _short_opts _long_optsdefaults(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys_create_option_mappingsøs  cCs(|i|_|i|_|i|_dS(N(sparsers _short_optsselfs _long_optsdefaults(sselfsparser((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys_share_option_mappingss  cCs4|dddfjotd|‚n||_dS(Nsignoreserrorsresolves$invalid conflict_resolution value %r(shandlers ValueErrorsselfsconflict_handler(sselfshandler((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysset_conflict_handlerscCs ||_dS(N(s descriptionsself(sselfs description((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysset_description scCs§g}xB|iD]7}|ii|ƒo|i||i|fƒqqWxB|iD]7}|i i|ƒo|i||i |fƒqUqUW|o |i }|djoq£|djoEt ddi gi}|D]}||dƒqØ~ƒ|ƒ‚q£|djoxŒ|D]€\}}|idƒo|ii|ƒ|i |=n|ii|ƒ|i|=|ip|i o|iii|ƒqqWq£ndS(Nsignoreserrors conflicting option string(s): %ss, isresolves--(s conflict_optssoptions _short_optssoptsselfs _short_optshas_keysappends _long_optss _long_optsconflict_handlershandlersOptionConflictErrorsjoins_[1]scosc_options startswithsremoves containers option_list(sselfsoptionsoptscos_[1]shandlers conflict_optssc_option((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys_check_conflicts4 " "   8    cOsZt|dƒtijo|i||Ž}nUt|ƒdjo| o0|d}t |t ƒ ot d|‚q„n t d‚|i |ƒ|i i|ƒ||_x|iD]}||i| (values : Values, args : [string]) Parse the command-line options found in 'args' (default: sys.argv[1:]). Any errors result in a call to 'error()', which by default prints the usage message to stderr and calls sys.exit() with an error message. On success returns a pair (values, args) where 'values' is an Values instance (with all your option values) and 'args' is the list of arguments left over after parsing options. N(sselfs _get_argssargssrargssvaluessNonesget_default_valuesslargss _process_argssstopsBadOptionErrorsOptionValueErrorserrserrorsmsgs check_values(sselfsargssvaluesserrslargssstopsrargs((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys parse_argsJs      cCs||fSdS(s³ check_values(values : Values, args : [string]) -> (values : Values, args : [string]) Check that the supplied option values and leftover arguments are valid. Returns the option values and leftover arguments (possibly adjusted, possibly completely new -- whatever you like). Default implementation just returns the passed-in values; subclasses may override as desired. N(svaluessargs(sselfsvaluessargs((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys check_valuesqs cCs¿x¸|o°|d}|djo|d=dSq|dd!djo|i||ƒq|d djot|ƒdjo|i||ƒq|io|i |ƒ|d=qdSqWdS(s˜_process_args(largs : [string], rargs : [string], values : Values) Process command-line arguments and populate 'values', consuming options and arguments from 'rargs'. If 'allow_interspersed_args' is false, stop at the first non-option argument. If true, accumulate any interspersed non-option arguments in 'largs'. is--Niis-( srargssargsselfs_process_long_optsvaluesslens_process_short_optssallow_interspersed_argsslargssappend(sselfslargssrargssvaluessarg((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys _process_args~s   $   cCst||iƒSdS(s_match_long_opt(opt : string) -> string Determine which long option string 'opt' matches, ie. which one it is an unambiguous abbrevation for. Raises BadOptionError if 'opt' doesn't unambiguously match any long option string. N(s _match_abbrevsoptsselfs _long_opt(sselfsopt((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys_match_long_opt±sc CsY|idƒ} d| jo2| iddƒ\}}|id|ƒd}n | }d}|i |ƒ}|i |}|i ƒoš|i }t|ƒ|jo=|djo|id|ƒq|id||fƒq?|djo|idƒ}q?t|d|!ƒ}|d|5n#|o|id|ƒnt}|i||||ƒdS(Nis=is%s option requires a values%s option requires %d valuess%s option does not take a value(srargsspopsargssplitsoptsnext_argsinsertshad_explicit_valuesselfs_match_long_opts _long_optsoptions takes_valuesnargsslenserrorsvaluestuplesNonesprocesssvalues( sselfsrargssvaluessoptsoptionsnext_argsnargsshad_explicit_valuesvaluesarg((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys_process_long_optºs.       c Csw|idƒ} d}d}xU| dD]I}d|}|ii |ƒ}|d7}| o|i d|ƒn|i ƒoË|t | ƒjo|id| |ƒd}n|i}t |ƒ|jo=|djo|i d|ƒqC|i d||fƒqM|djo|idƒ} qMt|d|!ƒ} |d|5nt} |i|| ||ƒ|oPq&q&WdS(Niis-sno such option: %ss%s option requires a values%s option requires %s values(srargsspopsargsstopsischsoptsselfs _short_optsgetsoptionserrors takes_valueslensinsertsnargssvaluestuplesNonesprocesssvalues( sselfsrargssvaluessoptschsoptionsisnargssstopsvaluesarg((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys_process_short_optsßs6        cCs1|itiƒtid|iƒ|fƒdS(sÜerror(msg : string) Print a usage message incorporating 'msg' to stderr and exit. If you override this in a subclass, it should not return -- it should either exit or raise an exception. s %s: error: %sN(sselfs print_usagessyssstderrsexits_get_prog_namesmsg(sselfsmsg((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pyserror scCs;|io)|ii|iid|iƒƒƒSndSdS(Ns%progs(sselfsusages formatters format_usagesreplaces_get_prog_name(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys get_usages )cCs"|io||iƒIJndS(s`print_usage(file : file = stdout) Print the usage message for the current program (self.usage) to 'file' (default stdout). Any occurence of the string "%prog" in self.usage is replaced with the name of the current program (basename of sys.argv[0]). Does nothing if self.usage is empty or not defined. N(sselfsusagesfiles get_usage(sselfsfile((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys print_usages cCs/|io|iid|iƒƒSndSdS(Ns%progs(sselfsversionsreplaces_get_prog_name(sself((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys get_version&s cCs"|io||iƒIJndS(sDprint_version(file : file = stdout) Print the version message for this program (self.version) to 'file' (default stdout). As with print_usage(), any occurence of "%prog" in self.version is replaced by the current program's name. Does nothing if self.version is empty or undefined. N(sselfsversionsfiles get_version(sselfsfile((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys print_version,s cCs×|tjo |i}n|i|ƒg}|i|idƒƒ|iƒ|io*|it i ||ƒƒ|idƒnx4|i D])}|i|i |ƒƒ|idƒq‹W|iƒdi|d ƒSdS(Nsoptionss siÿÿÿÿ(s formattersNonesselfsstore_option_stringssresultsappendsformat_headingsindents option_listsOptionContainersformat_option_helps option_groupssgroups format_helpsdedentsjoin(sselfs formattersgroupsresult((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pysformat_option_help7s       cCs”|tjo |i}ng}|io|i|iƒdƒn|io|i|i|ƒdƒn|i|i |ƒƒdi |ƒSdS(Ns s( s formattersNonesselfsresultsusagesappends get_usages descriptionsformat_descriptionsformat_option_helpsjoin(sselfs formattersresult((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys format_helpHs    cCs1|tjo ti}n|i|iƒƒdS(s°print_help(file : file = stdout) Print an extended help message, listing all options and any help text provided with them, to 'file' (default stdout). N(sfilesNonessyssstdoutswritesselfs format_help(sselfsfile((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys print_helpSs  ("s__name__s __module__s__doc__sstandard_option_listsNonesOptions__init__s_create_option_lists_populate_option_lists_init_parsing_states_get_prog_names set_usagesenable_interspersed_argssdisable_interspersed_argss set_defaults set_defaultssget_default_valuessadd_option_groupsget_option_groups _get_argss parse_argss check_valuess _process_argss_match_long_opts_process_long_opts_process_short_optsserrors get_usages print_usages get_versions print_versionsformat_option_helps format_helps print_help(((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys OptionParserœs< 0$          ' 3 % *    cCs·|i|ƒo|Snœgi}|iƒD]$}|i|ƒo||ƒq,q,~}t |ƒdjo |dSn<| ot d|ƒ‚n t d|di |ƒfƒ‚dS(sû_match_abbrev(s : string, wordmap : {string : Option}) -> string Return the string key in 'wordmap' for which 's' is an unambiguous abbreviation. If 's' is found to be ambiguous or doesn't match any of 'words', raise BadOptionError. iisno such option: %ssambiguous option: %s (%s?)s, N( swordmapshas_keysssappends_[1]skeysswords startswiths possibilitiesslensBadOptionErrorsjoin(ssswordmaps_[1]swords possibilities((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys _match_abbrev`sA (%s__doc__s __version__s__all__s __copyright__ssyssosstypesstextwraps Exceptions OptParseErrors OptionErrorsOptionConflictErrorsOptionValueErrorsBadOptionErrors HelpFormattersIndentedHelpFormattersTitledHelpFormattersintslongsfloatscomplexs _builtin_cvts check_builtins check_choices NO_DEFAULTsOptions get_prog_names SUPPRESS_HELPsSUPPRESS_USAGEsSTD_HELP_OPTIONsSTD_VERSION_OPTIONsValuessOptionContainers OptionGroups OptionParsers _match_abbrevs make_option(sIndentedHelpFormatters check_builtins _builtin_cvts HelpFormatters OptParseErrorsOptionValueErrorsOptions__all__sTitledHelpFormattersSTD_HELP_OPTIONs check_choices __version__s OptionParsersOptionContainerstextwrapssyssOptionConflictErrorsValuess NO_DEFAULTs get_prog_names OptionGroupstypess SUPPRESS_HELPs __copyright__s OptionErrorsBadOptionErrors _match_abbrevsSTD_VERSION_OPTIONs make_optionsSUPPRESS_USAGEsos((s<build/bdist.linux-i686/egg/testoob/compatibility/optparse.pys?sH9  €B ÿQ      8¶ÿÅ PK'ƒ5=ê÷ó9q9q#testoob/compatibility/itertools.pyc;ò ÊŸ¦Dc@sdZdklZdddddddd d d d d ddgZdfd„ƒYZdfd„ƒYZdfd„ƒYZdfd„ƒYZdfd„ƒYZdfd„ƒYZ de fd„ƒYZ de fd„ƒYZ d fd„ƒYZ d fd„ƒYZ d fd„ƒYZd fd„ƒYZd fd„ƒYZdfd„ƒYZdefd „ƒYZd!efd"„ƒYZd#d$„Zd%S(&sÌFunctional tools for creating and using iterators. Infinite iterators: count([n]) --> n, n+1, n+2, ... cycle(p) --> p0, p1, ... plast, p0, p1, ... repeat(elem [,n]) --> elem, elem, elem, ... endlessly or up to n times Iterators terminating on the shortest input sequence: izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... ifilter(pred, seq) --> elements of seq where pred(elem) is True ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False islice(seq, [start,] stop [, step]) --> elements from seq[start:stop:step] imap(fun, p, q, ...) --> fun(p0, q0), fun(p1, q1), ... starmap(fun, seq) --> fun(*seq[0]), fun(*seq[1]), ... tee(it, n=2) --> (it1, it2 , ... itn) splits one iterator into n chain(p, q, ...) --> p0, p1, ... plast, q0, q1, ... takewhile(pred, seq) --> seq[0], seq[1], until pred fails dropwhile(pred, seq) --> seq[n], seq[n+1], starting when pred fails groupby(iterable[, keyfunc]) --> sub-iterators grouped by value of keyfunc(v) (s generatorsschainscountscycles dropwhilesgroupbysifilters ifilterfalsesimapsislicesizipsrepeatsstarmaps takewhilesteecBs)tZdZd„Zd„Zd„ZRS(s}Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Equivalent to : def chain(*iterables): for it in iterables: for element in it: yield element cGs+ttt|ƒƒ|_tgƒ|_dS(N(sitersmaps iterablessselfs_iterables_iters_cur_iterable_iter(sselfs iterables((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__init__+scCs|SdS(N(sself(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__iter__0scCsªy|iiƒ}WnŒtj o[t|iiƒƒ|_y|iiƒ}Wq¢tj otd|iƒ‚q¢Xn'tj otd|iƒ‚nX|SdS(Ns%s has no next() method( sselfs_cur_iterable_itersnextsnext_elts StopIterationsiters_iterables_itersAttributeErrors TypeError(sselfsnext_elt((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysnext3s(s__name__s __module__s__doc__s__init__s__iter__snext(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pyschains   cBs5tZdZdd„Zd„Zd„Zd„ZRS(sðMake an iterator that returns consecutive integers starting with n. If not specified n defaults to zero. Does not currently support python long integers. Often used as an argument to imap() to generate consecutive data points. Also, used with izip() to add sequence numbers. Equivalent to : def count(n=0): if not isinstance(n, int): raise TypeError("%s is not a regular integer" % n) while True: yield n n += 1 icCs6t|tƒ otd|ƒ‚n|d|_dS(Ns%s is not a regular integeri(s isinstancesnsints TypeErrorsselfstimes(sselfsn((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__init__WscCs|SdS(N(sself(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__iter__\scCs|id7_|iSdS(Ni(sselfstimes(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysnext_scCsd|idSdS(Ns count(%d)i(sselfstimes(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__repr__cs(s__name__s __module__s__doc__s__init__s__iter__snexts__repr__(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pyscountGs    cBs)tZdZd„Zd„Zd„ZRS(s¬Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Equivalent to : def cycle(iterable): saved = [] for element in iterable: yield element saved.append(element) while saved: for element in saved: yield element cCs%t|ƒ|_g|_t|_dS(N(sitersiterablesselfs _cur_iters_savedsTrues _must_save(sselfsiterable((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__init__xs cCs|SdS(N(sself(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__iter__}scCsžy1|iiƒ}|io|ii|ƒnWnbtj o1t|iƒ|_|iiƒ}t |_n't j ot d|iƒ‚nX|SdS(Ns%s has no next() method( sselfs _cur_itersnextsnext_elts _must_saves_savedsappends StopIterationsitersFalsesAttributeErrors TypeError(sselfsnext_elt((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysnext€s  (s__name__s __module__s__doc__s__init__s__iter__snext(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pyscyclehs   cBs)tZdZd„Zd„Zd„ZRS(sùMake an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element. Note, the iterator does not produce any output until the predicate is true, so it may have a lengthy start-up time. Equivalent to : def dropwhile(predicate, iterable): iterable = iter(iterable) for x in iterable: if not predicate(x): yield x break for x in iterable: yield x cCs%||_t|ƒ|_t|_dS(N(s predicatesselfs _predicatesitersiterables_itersFalses_dropped(sselfs predicatesiterable((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__init__¢s cCs|SdS(N(sself(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__iter__§scCs†y|iiƒ}Wn&tj otd|iƒ‚nX|io|Snx$|i|ƒo|iiƒ}qQWt|_|SdS(Ns%s has no next() method( sselfs_itersnextsvaluesAttributeErrors TypeErrors_droppeds _predicatesTrue(sselfsvalue((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysnextªs  (s__name__s __module__s__doc__s__init__s__iter__snext(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys dropwhile‘s   cBs5tZdZed„Zd„Zd„Zd„ZRS(s.Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function. The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list: groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) cCsS|tjo d„}n||_t|ƒ|_tdƒ|_|_ |_ dS(NcCs|S(N(sx(sx((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysÍsi( skeysNonesselfskeyfuncsitersiterablesitsxrangestgtkeyscurrkeys currvalue(sselfsiterableskey((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__init__Ës    cCs|SdS(N(sself(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__iter__ÒscCs˜xl|i|ijoXy|iiƒ|_Wn&tj otd|iƒ‚nX|i|iƒ|_qW|i|_|i|i |iƒfSdS(Ns%s has no next() method( sselfscurrkeystgtkeysitsnexts currvaluesAttributeErrors TypeErrorskeyfuncs_grouper(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysnextÕs ccsJxC|i|jo2|iV|iiƒ|_|i|iƒ|_qWdS(N(sselfscurrkeystgtkeys currvaluesitsnextskeyfunc(sselfstgtkey((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys_grouperás (s__name__s __module__s__doc__sNones__init__s__iter__snexts_grouper(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysgroupby¸s    s _ifilter_basecBs tZdZd„Zd„ZRS(s'base class for ifilter and ifilterflasecCs6t|ƒ|_|tjo t|_n ||_dS(N(sitersiterablesselfs_iters predicatesNonesbools _predicate(sselfs predicatesiterable((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__init__ës  cCs|SdS(N(sself(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__iter__ós(s__name__s __module__s__doc__s__init__s__iter__(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys _ifilter_baseés  cBstZdZd„ZRS(s`Make an iterator that filters elements from iterable returning only those for which the predicate is True. If predicate is None, return the items that are true. Equivalent to : def ifilter: if predicate is None: predicate = bool for x in iterable: if predicate(x): yield x cCsvy|iiƒ}Wn&tj otd|iƒ‚nXx3to+|i|ƒo|Sn|iiƒ}q?WdS(Ns%s has no next() method(sselfs_itersnextsnext_eltsAttributeErrors TypeErrorsTrues _predicate(sselfsnext_elt((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysnexts(s__name__s __module__s__doc__snext(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysifilterös cBstZdZd„ZRS(s€Make an iterator that filters elements from iterable returning only those for which the predicate is False. If predicate is None, return the items that are false. Equivalent to : def ifilterfalse(predicate, iterable): if predicate is None: predicate = bool for x in iterable: if not predicate(x): yield x cCswy|iiƒ}Wn&tj otd|iƒ‚nXx4to,|i|ƒ o|Sn|iiƒ}q?WdS(Ns%s has no next() method(sselfs_itersnextsnext_eltsAttributeErrors TypeErrorsTrues _predicate(sselfsnext_elt((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysnexts(s__name__s __module__s__doc__snext(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys ifilterfalses cBs)tZdZd„Zd„Zd„ZRS(s(Make an iterator that computes the function using arguments from each of the iterables. If function is set to None, then imap() returns the arguments as a tuple. Like map() but stops when the shortest iterable is exhausted instead of filling in None for shorter iterables. The reason for the difference is that infinite iterator arguments are typically an error for map() (because the output is fully evaluated) but represent a common and useful way of supplying arguments to imap(). Equivalent to : def imap(function, *iterables): iterables = map(iter, iterables) while True: args = [i.next() for i in iterables] if function is None: yield tuple(args) else: yield function(*args) cGs&||_tt|f|ƒ|_dS(N(sfunctionsselfs_funcsmapsitersiterablesother_iterabless_iters(sselfsfunctionsiterablesother_iterables((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__init__Cs cCs|SdS(N(sself(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__iter__GscCs‰y4gi}|iD]}||iƒƒq~}Wn#tj otd|ƒ‚nX|i t jot |ƒSn|i |ŒSdS(Ns%s has no next() method( sappends_[1]sselfs_iterssitsnextsargssAttributeErrors TypeErrors_funcsNonestuple(sselfsargssits_[1]((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysnextJs4(s__name__s __module__s__doc__s__init__s__iter__snext(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysimap-s   cBs)tZdZd„Zd„Zd„ZRS(sÑMake an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped. If stop is None, then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position. Unlike regular slicing, islice() does not support negative values for start, stop, or step. Can be used to extract related fields from data where the internal structure has been flattened (for example, a multi-line report may list a name field on every third line). cGs0t|Œ}|ipd|i|if\|_|_|_t|itt fƒ ot dƒ‚n|it j ot|itt fƒ ot dƒ‚n|it jo d|_n|idjp-|it j o |idjp |idjo t d‚nt |ƒ|_t |_d|_dS(Nis!Start argument must be an integers(Stop argument must be an integer or Noneis%indices for islice() must be positive(sslicesargssssstartsstopsstepsselfs isinstancesintslongs ValueErrorsNonesitersiterablesitsdonextscnt(sselfsiterablesargsss((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__init__es 1* @  cCs|SdS(N(sself(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__iter__uscCsÓ|itjo3y|ii|_WqCtj o t‚qCXnx1|i|ijo|iƒ|id7_qFW|i tjp|i|i jo/|i|i 7_|id7_|iƒSnt ‚dS(Ni( sselfsdonextsNonesitsnextsAttributeErrors TypeErrorscntsstartsstopssteps StopIteration(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysnextxs #(s__name__s __module__s__doc__s__init__s__iter__snext(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysisliceXs   cBs)tZdZd„Zd„Zd„ZRS(sœMake an iterator that aggregates elements from each of the iterables. Like zip() except that it returns an iterator instead of a list. Used for lock-step iteration over several iterables at a time. Equivalent to : def izip(*iterables): iterables = map(iter, iterables) while iterables: result = [i.next() for i in iterables] yield tuple(result) cGs/tt|ƒ|_tgt|iƒ|_dS(N(smapsiters iterablessselfs _iteratorssNoneslens_result(sselfs iterables((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__init__•scCs|SdS(N(sself(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__iter__™scCsz|i o tƒ‚ny8tgi}|iD]}||iƒƒq/~ƒSWn#tj ot d|ƒ‚nXdS(Ns%s has no next() method( sselfs _iteratorss StopIterationstuplesappends_[1]sisnextsAttributeErrors TypeError(sselfs_[1]si((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysnextœs   8(s__name__s __module__s__doc__s__init__s__iter__snext(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysizip‡s   cBs>tZdZed„Zd„Zd„Zd„Zd„ZRS(sòMake an iterator that returns object over and over again. Runs indefinitely unless the times argument is specified. Used as argument to imap() for invariant parameters to the called function. Also used with izip() to create an invariant part of a tuple record. Equivalent to : def repeat(object, times=None): if times is None: while True: yield object else: for i in xrange(times): yield object cCsH||_|tj o%t|ƒ|djo d}q;n||_dS(Ni(sobjsselfs_objstimessNonesxranges_times(sselfsobjstimes((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__init__·s     cCs|SdS(N(sself(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__iter__¿scCsK|itj o0|idjo tƒ‚n|id8_n|iSdS(Nii(sselfs_timessNones StopIterations_obj(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysnextÂs  cCs:|itj od|i|ifSnd|ifSdS(Nsrepeat(%r, %r)s repeat(%r)(sselfs_timessNones_obj(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__repr__ÊscCs;|idjp |itjotdƒ‚n|iSdS(Niÿÿÿÿslen() of uniszed object(sselfs_timessNones TypeError(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__len__Ðs ( s__name__s __module__s__doc__sNones__init__s__iter__snexts__repr__s__len__(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysrepeat¦s     cBs)tZdZd„Zd„Zd„ZRS(s Make an iterator that computes the function using arguments tuples obtained from the iterable. Used instead of imap() when argument parameters are already grouped in tuples from a single iterable (the data has been ``pre-zipped''). The difference between imap() and starmap() parallels the distinction between function(a,b) and function(*c). Equivalent to : def starmap(function, iterable): iterable = iter(iterable) while True: yield function(*iterable.next()) cCs||_t|ƒ|_dS(N(sfunctionsselfs_funcsitersiterables_iter(sselfsfunctionsiterable((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__init__ås cCs|SdS(N(sself(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__iter__éscCsny|iiƒ}Wn&tj otd|iƒ‚nXt|tƒ otdƒ‚n|i|ŒSdS(Ns%s has no next() methodsiterator must return a tuple( sselfs_itersnextstsAttributeErrors TypeErrors isinstancestuples_func(sselfst((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysnextìs(s__name__s __module__s__doc__s__init__s__iter__snext(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysstarmapÖs   cBs)tZdZd„Zd„Zd„ZRS(sMake an iterator that returns elements from the iterable as long as the predicate is true. Equivalent to : def takewhile(predicate, iterable): for x in iterable: if predicate(x): yield x else: break cCs||_t|ƒ|_dS(N(s predicatesselfs _predicatesitersiterables_iter(sselfs predicatesiterable((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__init__s cCs|SdS(N(sself(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__iter__ scCsby|iiƒ}Wn&tj otd|iƒ‚nX|i|ƒ o tƒ‚n|SdS(Ns%s has no next() method(sselfs_itersnextsvaluesAttributeErrors TypeErrors _predicates StopIteration(sselfsvalue((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysnext s (s__name__s __module__s__doc__s__init__s__iter__snext(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys takewhileùs   sTeeDatacBs tZdZd„Zd„ZRS(s"Holds cached values for TeeObjectscCsg|_||_dS(N(sselfsdatasiterators_iter(sselfsiterator((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__init__s cCssxa|t|iƒjoJy|ii|iiƒƒWqtj otd|iƒ‚qXqW|i|SdS(Ns%s has no next() method( sislensselfsdatasappends_itersnextsAttributeErrors TypeError(sselfsi((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys __getitem__s(s__name__s __module__s__doc__s__init__s __getitem__(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysTeeDatas  s TeeObjectcBs/tZdZeed„Zd„Zd„ZRS(s7Iterables / Iterators as returned by the tee() functioncCsk|o||_d|_nKt|tƒo|i|_|i|_ntt|ƒƒ|_d|_dS(Ni(stee_datasselfsposs isinstancesiterables TeeObjectsTeeDatasiter(sselfsiterablestee_data((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__init__,s   cCs'|i|i}|id7_|SdS(Ni(sselfstee_dataspossdata(sselfsdata((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysnext8scCs|SdS(N(sself(sself((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys__iter__=s(s__name__s __module__s__doc__sNones__init__snexts__iter__(((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys TeeObject*s  icCs¬t|tƒoLt|ggi}t|dƒD]}|td|i ƒƒq1~ƒSnt t |ƒƒ}tgi}t|ƒD]}|td|ƒƒq…~ƒSdS(s­Return n independent iterators from a single iterable. Note : once tee() has made a split, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed. Note : this member of the toolkit may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator is going to use most or all of the data before the other iterator, it is faster to use list() instead of tee() Equivalent to : def tee(iterable, n=2): def gen(next, data={}, cnt=[0]): for i in count(): if i == cnt[0]: item = data[i] = next() cnt[0] += 1 else: item = data.pop(i) yield item it = iter(iterable) return tuple([gen(it.next) for i in range(n)]) istee_dataN( s isinstancesiterables TeeObjectstuplesappends_[1]sxrangesnsistee_datasTeeDatasiter(siterablesnstee_datasis_[1]((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pysteeAs LN(s__doc__s __future__s generatorss__all__schainscountscycles dropwhilesgroupbys _ifilter_basesifilters ifilterfalsesimapsislicesizipsrepeatsstarmaps takewhilesobjectsTeeDatas TeeObjectstee(scountsifiltersrepeatsstarmaps__all__schains _ifilter_basesizipsteesimaps takewhiles TeeObjects generatorssislices ifilterfalsesTeeDatas dropwhilesgroupbyscycle((s=build/bdist.linux-i686/egg/testoob/compatibility/itertools.pys?s& 0)!)'1 +/0# PK'ƒ5iBÈ È "testoob/compatibility/__init__.pyc;ò ÊŸ¦Dc@s dZdS(s% Modules needed for compatibility Some files in this directory are taken from the PyPy project, http://codespeak.net/pypy They are licensed under the MIT license, reproduced below. The full licensing and the copyright information is at http://codespeak.net/svn/pypy/dist/LICENSE The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Some files are taken from the ElementTree project, http://effbot.org/zone/element-index.htm Their license is: The ElementTree Library is Copyright (c) 1999-2005 by Secret Labs AB Copyright (c) 1999-2005 by Fredrik Lundh By obtaining, using, and/or copying this software and/or its associated documentation, you agree that you have read, understood, and will comply with the following terms and conditions: Permission to use, copy, modify, and distribute this software and its associated documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appears in all copies, and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Secret Labs AB or the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. N(s__doc__(((s<build/bdist.linux-i686/egg/testoob/compatibility/__init__.pys??sPK'ƒ50X¿Í?0?0"testoob/compatibility/textwrap.pyc;ò ÊŸ¦Dc@s¡dZdZdkZdkZyeefWn%ej oddf\ZZnXdddgZdZdfd „ƒYZ d d „Z d d „Z d „Z dS(sText wrapping and filling. s;$Id: textwrap.py,v 1.32.8.2 2004/05/13 01:48:15 gward Exp $Niis TextWrapperswrapsfills cBsâtZdZeiedeeƒƒZhZe dƒZ x!e e eƒD]Z e ee string Munge whitespace in text: expand tabs and convert all other whitespace characters to spaces. Eg. " foo bar baz" becomes " foo bar baz". N( sselfs expand_tabsstexts expandtabssreplace_whitespaces isinstancesstrs translateswhitespace_transsunicodesunicode_whitespace_trans(sselfstext((s<build/bdist.linux-i686/egg/testoob/compatibility/textwrap.pys_munge_whitespacers  cCs)|ii|ƒ}tt|ƒ}|SdS(s£_split(text : string) -> [string] Split the text to wrap into indivisible chunks. Chunks are not quite the same as words; see wrap_chunks() for full details. As an example, the text Look, goof-ball -- use the -b option! breaks into the following chunks: 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', 'use', ' ', 'the', ' ', '-b', ' ', 'option!' N(sselfs wordsep_ressplitstextschunkssfiltersNone(sselfstextschunks((s<build/bdist.linux-i686/egg/testoob/compatibility/textwrap.pys_splitƒs cCsd}|i}xk|t|ƒdjoS||ddjo|i||ƒod||d<|d7}q|d7}qWdS(sf_fix_sentence_endings(chunks : [string]) Correct for sentence endings buried in 'chunks'. Eg. when the original text contains "... foo. Bar ...", munge_whitespace() and split() will convert that to [..., "foo.", " ", "Bar", ...] which has one too few spaces; this method simply changes the one space to two. iis s iN(sisselfssentence_end_respatslenschunksssearch(sselfschunkssispat((s<build/bdist.linux-i686/egg/testoob/compatibility/textwrap.pys_fix_sentence_endings’s )cCsqt||dƒ}|io.|i|dd|!ƒ|d||d [string] Wrap a sequence of text chunks and return a list of lines of length 'self.width' or less. (If 'break_long_words' is false, some lines may be longer than this.) Chunks correspond roughly to words and the whitespace between them: each chunk is indivisible (modulo 'break_long_words'), but a line break can come between any two chunks. Chunks should not have internal whitespace; ie. a chunk is either all whitespace or a "word". Whitespace chunks will be removed from the beginning and end of lines, but apart from that whitespace is preserved. isinvalid width %r (must be > 0)siÿÿÿÿN(slinessselfswidths ValueErrorschunksscur_linescur_lenssubsequent_indentsindentsinitial_indentslensstripslsappendspops_handle_long_wordsjoin(sselfschunkssindentscur_lenslinesslscur_lineswidth((s<build/bdist.linux-i686/egg/testoob/compatibility/textwrap.pys _wrap_chunksÀs8     #cCsS|i|ƒ}|i}|i|ƒ}|io|i|ƒn|i |ƒSdS(s^wrap(text : string) -> [string] Reformat the single paragraph in 'text' so it fits in lines of no more than 'self.width' columns, and return a list of wrapped lines. Tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. N( sselfs_munge_whitespacestextsinitial_indentsindents_splitschunkssfix_sentence_endingss_fix_sentence_endingss _wrap_chunks(sselfstextschunkssindent((s<build/bdist.linux-i686/egg/testoob/compatibility/textwrap.pyswraps  cCsdi|i|ƒƒSdS(sÞfill(text : string) -> string Reformat the single paragraph in 'text' to fit in lines of no more than 'self.width' columns, and return a new string containing the entire wrapped paragraph. s N(sjoinsselfswrapstext(sselfstext((s<build/bdist.linux-i686/egg/testoob/compatibility/textwrap.pysfills(s__name__s __module__s__doc__sstrings maketranss _whitespaceslenswhitespace_transsunicode_whitespace_transsordsuspacesmapsxsrescompiles wordsep_res lowercasessentence_end_resTruesFalses__init__s_munge_whitespaces_splits_fix_sentence_endingss_handle_long_words _wrap_chunksswrapsfill(((s<build/bdist.linux-i686/egg/testoob/compatibility/textwrap.pys TextWrapper!s" "      E iFcKs#td||}|i|ƒSdS(sÈWrap a single paragraph of text, returning a list of wrapped lines. Reformat the single paragraph in 'text' so it fits in lines of no more than 'width' columns, and return a list of wrapped lines. By default, tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. swidthN(s TextWrapperswidthskwargsswswrapstext(stextswidthskwargssw((s<build/bdist.linux-i686/egg/testoob/compatibility/textwrap.pyswrap!s cKs#td||}|i|ƒSdS(s–Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. swidthN(s TextWrapperswidthskwargsswsfillstext(stextswidthskwargssw((s<build/bdist.linux-i686/egg/testoob/compatibility/textwrap.pysfill.scCsá|iƒidƒ}t}xe|D]]}|iƒ}| oq"nt |ƒt |ƒ}|tjo |}q"t ||ƒ}q"W|tj o |djo3x0t t |ƒƒD]}||||| string Remove any whitespace than can be uniformly removed from the left of every line in `text`. This can be used e.g. to make triple-quoted strings line up with the left edge of screen/whatever, while still presenting it in the source code in indented form. For example: def test(): # end first line with \ to avoid the empty line! s = ''' hello world ''' print repr(s) # prints ' hello world ' print repr(dedent(s)) # prints 'hello world ' s iN(stexts expandtabsssplitslinessNonesmarginslineslstripscontentslensindentsminsrangesisjoin(stextsindentsislinesscontentslinesmargin((s<build/bdist.linux-i686/egg/testoob/compatibility/textwrap.pysdedent=s"   ( s__doc__s __revision__sstringsresTruesFalses NameErrors__all__s _whitespaces TextWrapperswrapsfillsdedent( sdedents __revision__sFalsesstrings__all__s TextWrappersres _whitespaceswrapsTruesfill((s<build/bdist.linux-i686/egg/testoob/compatibility/textwrap.pys?s ÿ PK'ƒ5m Ò,¬]¬]testoob/compatibility/sets.pyc;ò ÊŸ¦Dc@sÿdZdklZydklZlZWngej o[d„Zd„ZyeefWq”e j o%ddjddjf\ZZq”XnXdddgZ de fd „ƒYZ de fd „ƒYZ de fd „ƒYZd e fd „ƒYZdS(såClasses to represent arbitrary sets (including sets of sets). This module implements sets using dictionaries whose values are ignored. The usual operations (union, intersection, deletion, etc.) are provided as both methods and operators. Important: sets are not sequences! While they support 'x in s', 'len(s)', and 'for x in s', none of those operations are unique for sequences; for example, mappings support all three as well. The characteristic operation for sequences is subscripting with small integers: s[i], for i in range(len(s)). Sets don't support subscripting at all. Also, sequences allow multiple occurrences and their elements have a definite order; sets on the other hand don't record multiple occurrences and don't remember the order of element insertion (which is why they don't support s[i]). The following classes are provided: BaseSet -- All the operations common to both mutable and immutable sets. This is an abstract class, not meant to be directly instantiated. Set -- Mutable sets, subclass of BaseSet; not hashable. ImmutableSet -- Immutable sets, subclass of BaseSet; hashable. An iterable argument is mandatory to create an ImmutableSet. _TemporarilyImmutableSet -- A wrapper around a Set, hashable, giving the same hash value as the immutable set equivalent would have. Do not use this class directly. Only hashable objects can be added to a Set. In particular, you cannot really add a Set as an element to another Set; if you try, what is actually added is an ImmutableSet built from it (it compares equal to the one you tried adding). When you ask if `x in y' where x is a Set and y is a Set or ImmutableSet, x is wrapped into a _TemporarilyImmutableSet z, and what's tested is actually `z in y'. (s generators(sifilters ifilterfalseccsD|tjo d„}nx#|D]}||ƒo|Vq!q!WdS(NcCs|SdS(N(sx(sx((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys predicate@s(s predicatesNonesiterablesx(s predicatesiterablesx((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pysifilter>s    ccsE|tjo d„}nx$|D]}||ƒ o|Vq!q!WdS(NcCs|SdS(N(sx(sx((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys predicateGs(s predicatesNonesiterablesx(s predicatesiterablesx((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys ifilterfalseEs   isBaseSetsSets ImmutableSetcBstZdZdgZd„Zd„Zd„ZeZed„Z d„Z d„Z d„Z d „Z d „ZeZd „Zd „Zd „Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„ZeZeZd„Zd„Zd„Z d„Z!d„Z"RS(s1Common base class for mutable and immutable sets.s_datacCs!|itjo td‚ndS(sThis is an abstract class.s7BaseSet is an abstract class. Use Set or ImmutableSet.N(sselfs __class__sBaseSets TypeError(sself((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys__init__ZscCst|iƒSdS(s'Return the number of elements of a set.N(slensselfs_data(sself((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys__len__cscCs|iƒSdS(seReturn string representation of a set. This looks like 'Set([])'. N(sselfs_repr(sself((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys__repr__gscCs<|iiƒ}|o|iƒnd|ii|fSdS(Ns%s(%r)(sselfs_dataskeysselementsssortedssorts __class__s__name__(sselfssortedselements((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys_reprqscCs|iiƒSdS(ssReturn an iterator over the elements or a set. This is the keys iterator for the underlying dict. N(sselfs_datasiterkeys(sself((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys__iter__wscCs td‚dS(Nscan't compare sets using cmp()(s TypeError(sselfsother((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys__cmp__ƒscCs,t|tƒo|i|ijSntSdS(N(s isinstancesothersBaseSetsselfs_datasFalse(sselfsother((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys__eq__•scCs,t|tƒo|i|ijSntSdS(N(s isinstancesothersBaseSetsselfs_datasTrue(sselfsother((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys__ne__›scCs'|iƒ}|ii|iƒ|SdS(sReturn a shallow copy of a set.N(sselfs __class__sresults_datasupdate(sselfsresult((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pyscopy£s cCsddkl}|iƒ}||t|ƒ<|i}t }x!|D]}|||||ƒtZdZdgZed„Zd„Zd„Zd„ZRS(sImmutable set class.s _hashcodecCs4t|_h|_|tj o|i|ƒndS(s5Construct an immutable set from an optional iterable.N(sNonesselfs _hashcodes_datasiterables_update(sselfsiterable((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys__init__s    cCs.|itjo|iƒ|_n|iSdS(N(sselfs _hashcodesNones _compute_hash(sself((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys__hash__—scCs|i|ifSdS(N(sselfs_datas _hashcode(sself((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys __getstate__œscCs|\|_|_dS(N(sstatesselfs_datas _hashcode(sselfsstate((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys __setstate__Ÿs( s__name__s __module__s__doc__s __slots__sNones__init__s__hash__s __getstate__s __setstate__(((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys ImmutableSet‰s     cBsËtZdZgZed„Zd„Zd„Zd„Zd„Z d„Z d„Z d„Z d „Z d „Zd „Zd „Zd „Zd„Zd„Zd„Zd„Zd„Zd„Zd„ZRS(s Mutable set class.cCs+h|_|tj o|i|ƒndS(s*Construct a set from an optional iterable.N(sselfs_datasiterablesNones_update(sselfsiterable((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys__init__©s  cCs|ifSdS(N(sselfs_data(sself((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys __getstate__¯scCs|\|_dS(N(sdatasselfs_data(sselfsdata((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys __setstate__³scCs td‚dS(sA Set cannot be hashed.s'Can't hash a Set, only an ImmutableSet.N(s TypeError(sself((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys__hash__¶scCs(|i|ƒ|ii|iƒ|SdS(s2Update a set with the union of itself and another.N(sselfs_binary_sanity_checksothers_datasupdate(sselfsother((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys__ior__Às cCs|i|ƒdS(s2Update a set with the union of itself and another.N(sselfs_updatesother(sselfsother((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys union_updateÆscCs%|i|ƒ||@i|_|SdS(s9Update a set with the intersection of itself and another.N(sselfs_binary_sanity_checksothers_data(sselfsother((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys__iand__Ês cCs7t|tƒo||M}n|i|ƒi|_dS(s9Update a set with the intersection of itself and another.N(s isinstancesothersBaseSetsselfs intersections_data(sselfsother((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pysintersection_updateÐscCs"|i|ƒ|i|ƒ|SdS(sAUpdate a set with the symmetric difference of itself and another.N(sselfs_binary_sanity_checksotherssymmetric_difference_update(sselfsother((s8build/bdist.linux-i686/egg/testoob/compatibility/sets.pys__ixor__×s  cCs‚|i}t}t|tƒ ot|ƒ}n||jo|i ƒnx0|D](}||jo ||=qR||| [ARGS] Meta-options: --help Display this help then exit. --version Output version information then exit. Otherwise, exactly one of the following three options must be given: -t, --trace Print each line to sys.stdout before it is executed. -c, --count Count the number of times each line is executed and write the counts to .cover for each module executed, in the module's directory. See also `--coverdir', `--file', `--no-report' below. -l, --listfuncs Keep track of which functions are executed at least once and write the results to sys.stdout after the program exits. -T, --trackcalls Keep track of caller/called pairs and write the results to sys.stdout after the program exits. -r, --report Generate a report from a counts file; do not execute any code. `--file' must specify the results file to read, which must have been created in a previous run with `--count --file=FILE'. Modifiers: -f, --file= File to accumulate counts over several runs. -R, --no-report Do not generate the coverage report files. Useful if you want to accumulate over several runs. -C, --coverdir= Directory where the report files. The coverage report for . is written to file //.cover. -m, --missing Annotate executable lines that were not executed with '>>>>>> '. -s, --summary Write a brief summary on stdout for each file. (Can only be used with --count or --report.) Filters, may be repeated multiple times: --ignore-module= Ignore the given module and its submodules (if it is a package). --ignore-dir= Ignore files in the given directory (multiple directories can be joined by os.pathsep). i(soutfileswritessyssargv(soutfile((s9build/bdist.linux-i686/egg/testoob/compatibility/trace.pysusageCss#pragma NO COVERs ^\s*(#.*)?$sIgnorecBs tZeed„Zd„ZRS(NcCsQ|pg|_|pg|_ttii|iƒ|_hdd<|_ dS(Nsi( smodulessselfs_modssdirss_dirssmapsosspathsnormpaths_ignore(sselfsmodulessdirs((s9build/bdist.linux-i686/egg/testoob/compatibility/trace.pys__init__sscCs|ii|ƒo|i|Snxv|iD]k}||jod|i|s %s.%s -> %s.%sss.pycs.pyoiÿÿÿÿs.coveridslines cov% module (path)s%5d %3d%% %s (%s)swbis"Can't save counts files because %sN(=sselfs calledfuncsskeysscallsssortsfilenames modulenamesfuncnamescallersslastfiles lastcfilespfilespmodspfuncscfilescmodscfuncsper_filescountsslinenosgets lines_hitssumss iteritemsscountsendswithscoverdirsNonesosspathsdirnamesabspathsdirsmodnamesexistssmakedirss fullmodnames show_missingsfind_executable_linenosslnotabs linecachesgetlinesssourcesjoins coverpathswrite_results_filesn_hitssn_linesssummarysintspercentsmodssmsoutfilespicklesdumpsopensIOErrorserrssyssstderr(sselfs show_missingssummaryscoverdirs modulenameserrscmods lines_hitscfuncsper_filespfuncspmodspercents lastcfilesfilenamessourceslinenos coverpathscfilespfilesn_linesssumsscountsmodssn_hitsscallssmsfuncnamesdirslnotabslastfile((s9build/bdist.linux-i686/egg/testoob/compatibility/trace.pys write_resultsósŠ                    c CsSyt|dƒ} Wn6tj o*}tid||fIJddfSnXd}d}xàt |ƒD]Ò\}} |d} | |jo-| id|| ƒ|d7}|d7}niti| ƒo| idƒnH| |jot||j o| idƒ|d7}n| idƒ| i||idƒƒqeW| iƒ||fSd S( s'Return a coverage results file in path.sws2trace: Could not open %r for writing: %s- skippingiis%5d: s s>>>>>> iN(sopenspathsoutfilesIOErrorserrssyssstderrsn_linessn_hitss enumerateslinessislineslinenos lines_hitswritesrx_blanksmatchslnotabsPRAGMA_NOCOVERs expandtabssclose( sselfspathslinesslnotabs lines_hitsn_hitsserrsisn_linessoutfileslinenosline((s9build/bdist.linux-i686/egg/testoob/compatibility/trace.pyswrite_results_fileLs0       ( s__name__s __module__sNones__init__supdatesTruesFalses write_resultsswrite_results_file(((s9build/bdist.linux-i686/egg/testoob/compatibility/trace.pysCoverageResultsÆs Yc Csžh}d„}gi}||iƒD]}|t|ƒƒq&~} t | ƒ} t }|i }x3| D]+}||7}||jod|||iD]3}t|tiƒo|i t ||ƒƒqqW|SdS(s<Return lineno dict for all code objects reachable from code.N( sfind_lines_from_codescodesstrsslinenoss co_constsscs isinstancestypessCodeTypesupdates find_lines(scodesstrsscslinenos((s9build/bdist.linux-i686/egg/testoob/compatibility/trace.pys find_lines„s cCsÇh}ti}t|ƒ}x—ti|i ƒD]ƒ\} } }}} | tijoX|tijoD|\} }|\}}x)t| |dƒD]} d|| |d8|d9|ƒ}y|i3d?| fƒWnBt4j o$}t+d@tid|fƒnt6j onX|i.ƒ} | o| i/| d |d:|ƒndS(ANistcrRf:d:msC:lTshelpsversionstracescountsreports no-reportssummarysfile=smissingsignore-module=s ignore-dir=s coverdir=s listfuncss trackcallss%s: %s is%Try `%s --help' for more information s--helps --versions trace 2.0 s-Ts --trackcallss-ls --listfuncss-ts--traces-cs--counts-rs--reports-Rs --no-reports-fs--files-ms --missings-Cs --coverdirs-ss --summarys--ignore-modules --ignore-dirs$prefixslibspythonis $exec_prefixsShould never get heres8cannot specify both --listfuncs and (--trace or --count)sLmust specify one of --trace, --count, --report, --listfuncs, or --trackcallss,cannot specify both --report and --no-reports--report requires a --filesmissing name of file to runsinfilesoutfilescoverdirs countfuncss countcallerss ignoremodss ignoredirss execfile(%r)sCannot run file %r because: %s(7sgetoptsargvsNonessyssoptss prog_argvserrorsmsgsstderrswritesexitstracescountsreports no_reports counts_filesmissingsignore_moduless ignore_dirsscoverdirssummarysFalses listfuncss countcallerssoptsvalsusagesstdoutsTruesappendssplitsosspathsepssspaths expandvarssreplacesjoinsprefixsversions exec_prefixsnormpathsAssertionErrors _err_exitslensCoverageResultssresultss write_resultssprognamesTracestsrunsIOErrorserrs SystemExit(sargvserrs no_reports prog_argvsvalstsmsgsgetopts ignore_dirssoptstracesmissingsprognamesresultssreports listfuncss countcallersscountscoverdirs counts_filessummarysssignore_modulessopts((s9build/bdist.linux-i686/egg/testoob/compatibility/trace.pysmain‰sÔ   =!         $      s__main__(s__doc__s linecachesossressyss threadingstokenstokenizestypessgcscPicklespickles ImportErrorsusagesPRAGMA_NOCOVERscompilesrx_blanksIgnoresmodnames fullmodnamesCoverageResultssfind_lines_from_codes find_liness find_stringssfind_executable_linenossTraces _err_exitsNonesmains__name__(s _err_exitsgcs linecaches fullmodnamesfind_executable_linenossTraces find_linessfind_lines_from_codestokenizesusagesmainsCoverageResultsscPickles find_stringssIgnoresrestypesssyssmodnamesoss threadingstokensPRAGMA_NOCOVERsrx_blankspickle((s9build/bdist.linux-i686/egg/testoob/compatibility/trace.pys?1s<            *5  ª   Ò  PKšá4“æ–üMüM"testoob/compatibility/itertools.py# This file is taken from the PyPy project, http://codespeak.net/pypy """Functional tools for creating and using iterators. Infinite iterators: count([n]) --> n, n+1, n+2, ... cycle(p) --> p0, p1, ... plast, p0, p1, ... repeat(elem [,n]) --> elem, elem, elem, ... endlessly or up to n times Iterators terminating on the shortest input sequence: izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... ifilter(pred, seq) --> elements of seq where pred(elem) is True ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False islice(seq, [start,] stop [, step]) --> elements from seq[start:stop:step] imap(fun, p, q, ...) --> fun(p0, q0), fun(p1, q1), ... starmap(fun, seq) --> fun(*seq[0]), fun(*seq[1]), ... tee(it, n=2) --> (it1, it2 , ... itn) splits one iterator into n chain(p, q, ...) --> p0, p1, ... plast, q0, q1, ... takewhile(pred, seq) --> seq[0], seq[1], until pred fails dropwhile(pred, seq) --> seq[n], seq[n+1], starting when pred fails groupby(iterable[, keyfunc]) --> sub-iterators grouped by value of keyfunc(v) """ from __future__ import generators __all__ = ['chain', 'count', 'cycle', 'dropwhile', 'groupby', 'ifilter', 'ifilterfalse', 'imap', 'islice', 'izip', 'repeat', 'starmap', 'takewhile', 'tee'] class chain: """Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Equivalent to : def chain(*iterables): for it in iterables: for element in it: yield element """ def __init__(self, *iterables): self._iterables_iter = iter(map(iter, iterables)) # little trick for the first chain.next() call self._cur_iterable_iter = iter([]) def __iter__(self): return self def next(self): try: next_elt = self._cur_iterable_iter.next() except StopIteration: # The current list's iterator is exhausted, switch to next one self._cur_iterable_iter = iter(self._iterables_iter.next()) try: next_elt = self._cur_iterable_iter.next() except AttributeError: # CPython raises a TypeError when next() is not defined raise TypeError('%s has no next() method' % \ (self._cur_iterable_iter)) except AttributeError: # CPython raises a TypeError when next() is not defined raise TypeError('%s has no next() method' % \ (self._cur_iterable_iter)) return next_elt class count: """Make an iterator that returns consecutive integers starting with n. If not specified n defaults to zero. Does not currently support python long integers. Often used as an argument to imap() to generate consecutive data points. Also, used with izip() to add sequence numbers. Equivalent to : def count(n=0): if not isinstance(n, int): raise TypeError("%s is not a regular integer" % n) while True: yield n n += 1 """ def __init__(self, n=0): if not isinstance(n, int): raise TypeError('%s is not a regular integer' % n) self.times = n-1 def __iter__(self): return self def next(self): self.times += 1 return self.times def __repr__(self): return 'count(%d)' % (self.times + 1) class cycle: """Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Equivalent to : def cycle(iterable): saved = [] for element in iterable: yield element saved.append(element) while saved: for element in saved: yield element """ def __init__(self, iterable): self._cur_iter = iter(iterable) self._saved = [] self._must_save = True def __iter__(self): return self def next(self): # XXX Could probably be improved try: next_elt = self._cur_iter.next() if self._must_save: self._saved.append(next_elt) except StopIteration: self._cur_iter = iter(self._saved) next_elt = self._cur_iter.next() self._must_save = False except AttributeError: # CPython raises a TypeError when next() is not defined raise TypeError('%s has no next() method' % \ (self._cur_iter)) return next_elt class dropwhile: """Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element. Note, the iterator does not produce any output until the predicate is true, so it may have a lengthy start-up time. Equivalent to : def dropwhile(predicate, iterable): iterable = iter(iterable) for x in iterable: if not predicate(x): yield x break for x in iterable: yield x """ def __init__(self, predicate, iterable): self._predicate = predicate self._iter = iter(iterable) self._dropped = False def __iter__(self): return self def next(self): try: value = self._iter.next() except AttributeError: # CPython raises a TypeError when next() is not defined raise TypeError('%s has no next() method' % \ (self._iter)) if self._dropped: return value while self._predicate(value): value = self._iter.next() self._dropped = True return value class groupby: """Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function. The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list: groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) """ def __init__(self, iterable, key=None): if key is None: key = lambda x: x self.keyfunc = key self.it = iter(iterable) self.tgtkey = self.currkey = self.currvalue = xrange(0) def __iter__(self): return self def next(self): while self.currkey == self.tgtkey: try: self.currvalue = self.it.next() # Exit on StopIteration except AttributeError: # CPython raises a TypeError when next() is not defined raise TypeError('%s has no next() method' % \ (self.it)) self.currkey = self.keyfunc(self.currvalue) self.tgtkey = self.currkey return (self.currkey, self._grouper(self.tgtkey)) def _grouper(self, tgtkey): while self.currkey == tgtkey: yield self.currvalue self.currvalue = self.it.next() # Exit on StopIteration self.currkey = self.keyfunc(self.currvalue) class _ifilter_base: """base class for ifilter and ifilterflase""" def __init__(self, predicate, iterable): # Make sure iterable *IS* iterable self._iter = iter(iterable) if predicate is None: self._predicate = bool else: self._predicate = predicate def __iter__(self): return self class ifilter(_ifilter_base): """Make an iterator that filters elements from iterable returning only those for which the predicate is True. If predicate is None, return the items that are true. Equivalent to : def ifilter: if predicate is None: predicate = bool for x in iterable: if predicate(x): yield x """ def next(self): try: next_elt = self._iter.next() except AttributeError: # CPython raises a TypeError when next() is not defined raise TypeError('%s has no next() method' % \ (self._iter)) while True: if self._predicate(next_elt): return next_elt next_elt = self._iter.next() class ifilterfalse(_ifilter_base): """Make an iterator that filters elements from iterable returning only those for which the predicate is False. If predicate is None, return the items that are false. Equivalent to : def ifilterfalse(predicate, iterable): if predicate is None: predicate = bool for x in iterable: if not predicate(x): yield x """ def next(self): try: next_elt = self._iter.next() except AttributeError: # CPython raises a TypeError when next() is not defined raise TypeError('%s has no next() method' % \ (self._iter)) while True: if not self._predicate(next_elt): return next_elt next_elt = self._iter.next() class imap: """Make an iterator that computes the function using arguments from each of the iterables. If function is set to None, then imap() returns the arguments as a tuple. Like map() but stops when the shortest iterable is exhausted instead of filling in None for shorter iterables. The reason for the difference is that infinite iterator arguments are typically an error for map() (because the output is fully evaluated) but represent a common and useful way of supplying arguments to imap(). Equivalent to : def imap(function, *iterables): iterables = map(iter, iterables) while True: args = [i.next() for i in iterables] if function is None: yield tuple(args) else: yield function(*args) """ def __init__(self, function, iterable, *other_iterables): self._func = function self._iters = map(iter, (iterable, ) + other_iterables) def __iter__(self): return self def next(self): try: args = [it.next() for it in self._iters] except AttributeError: # CPython raises a TypeError when next() is not defined raise TypeError('%s has no next() method' % \ (it)) if self._func is None: return tuple(args) else: return self._func(*args) class islice: """Make an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped. If stop is None, then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position. Unlike regular slicing, islice() does not support negative values for start, stop, or step. Can be used to extract related fields from data where the internal structure has been flattened (for example, a multi-line report may list a name field on every third line). """ def __init__(self, iterable, *args): s = slice(*args) self.start, self.stop, self.step = s.start or 0, s.stop, s.step if not isinstance(self.start, (int, long)): raise ValueError("Start argument must be an integer") if self.stop is not None and not isinstance(self.stop, (int,long)): raise ValueError("Stop argument must be an integer or None") if self.step is None: self.step = 1 if self.start<0 or (self.stop is not None and self.stop<0 ) or self.step<=0: raise ValueError, "indices for islice() must be positive" self.it = iter(iterable) self.donext = None self.cnt = 0 def __iter__(self): return self def next(self): if self.donext is None: try: self.donext = self.it.next except AttributeError: raise TypeError while self.cnt < self.start: self.donext() self.cnt += 1 if self.stop is None or self.cnt < self.stop: self.start += self.step self.cnt += 1 return self.donext() raise StopIteration class izip: """Make an iterator that aggregates elements from each of the iterables. Like zip() except that it returns an iterator instead of a list. Used for lock-step iteration over several iterables at a time. Equivalent to : def izip(*iterables): iterables = map(iter, iterables) while iterables: result = [i.next() for i in iterables] yield tuple(result) """ def __init__(self, *iterables): self._iterators = map(iter, iterables) self._result = [None] * len(self._iterators) def __iter__(self): return self def next(self): if not self._iterators: raise StopIteration() try: return tuple([i.next() for i in self._iterators]) except AttributeError: # CPython raises a TypeError when next() is not defined raise TypeError('%s has no next() method' % (i)) class repeat: """Make an iterator that returns object over and over again. Runs indefinitely unless the times argument is specified. Used as argument to imap() for invariant parameters to the called function. Also used with izip() to create an invariant part of a tuple record. Equivalent to : def repeat(object, times=None): if times is None: while True: yield object else: for i in xrange(times): yield object """ def __init__(self, obj, times=None): self._obj = obj if times is not None: xrange(times) # Raise a TypeError if times < 0: times = 0 self._times = times def __iter__(self): return self def next(self): # next() *need* to decrement self._times when consumed if self._times is not None: if self._times <= 0: raise StopIteration() self._times -= 1 return self._obj def __repr__(self): if self._times is not None: return 'repeat(%r, %r)' % (self._obj, self._times) else: return 'repeat(%r)' % (self._obj,) def __len__(self): if self._times == -1 or self._times is None: raise TypeError("len() of uniszed object") return self._times class starmap: """Make an iterator that computes the function using arguments tuples obtained from the iterable. Used instead of imap() when argument parameters are already grouped in tuples from a single iterable (the data has been ``pre-zipped''). The difference between imap() and starmap() parallels the distinction between function(a,b) and function(*c). Equivalent to : def starmap(function, iterable): iterable = iter(iterable) while True: yield function(*iterable.next()) """ def __init__(self, function, iterable): self._func = function self._iter = iter(iterable) def __iter__(self): return self def next(self): # CPython raises a TypeError when the iterator doesn't return a tuple try: t = self._iter.next() except AttributeError: # CPython raises a TypeError when next() is not defined raise TypeError('%s has no next() method' % self._iter) if not isinstance(t, tuple): raise TypeError("iterator must return a tuple") return self._func(*t) class takewhile: """Make an iterator that returns elements from the iterable as long as the predicate is true. Equivalent to : def takewhile(predicate, iterable): for x in iterable: if predicate(x): yield x else: break """ def __init__(self, predicate, iterable): self._predicate = predicate self._iter = iter(iterable) def __iter__(self): return self def next(self): try: value = self._iter.next() except AttributeError: # CPython raises a TypeError when next() is not defined raise TypeError('%s has no next() method' % \ (self._iter)) if not self._predicate(value): raise StopIteration() return value class TeeData(object): """Holds cached values for TeeObjects""" def __init__(self, iterator): self.data = [] self._iter = iterator def __getitem__(self, i): # iterates until 'i' if not done yet while i>= len(self.data): try: self.data.append( self._iter.next() ) except AttributeError: # CPython raises a TypeError when next() is not defined raise TypeError('%s has no next() method' % self._iter) return self.data[i] class TeeObject(object): """Iterables / Iterators as returned by the tee() function""" def __init__(self, iterable=None, tee_data=None): if tee_data: self.tee_data = tee_data self.pos = 0 # <=> Copy constructor elif isinstance(iterable, TeeObject): self.tee_data = iterable.tee_data self.pos = iterable.pos else: self.tee_data = TeeData(iter(iterable)) self.pos = 0 def next(self): data = self.tee_data[self.pos] self.pos += 1 return data def __iter__(self): return self def tee(iterable, n=2): """Return n independent iterators from a single iterable. Note : once tee() has made a split, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed. Note : this member of the toolkit may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator is going to use most or all of the data before the other iterator, it is faster to use list() instead of tee() Equivalent to : def tee(iterable, n=2): def gen(next, data={}, cnt=[0]): for i in count(): if i == cnt[0]: item = data[i] = next() cnt[0] += 1 else: item = data.pop(i) yield item it = iter(iterable) return tuple([gen(it.next) for i in range(n)]) """ if isinstance(iterable, TeeObject): # a,b = tee(range(10)) ; c,d = tee(a) ; self.assert_(a is c) return tuple([iterable] + [TeeObject(tee_data=iterable.tee_data) for i in xrange(n-1)]) tee_data = TeeData(iter(iterable)) return tuple([TeeObject(tee_data=tee_data) for i in xrange(n)]) PKšá4g9H4646!testoob/compatibility/textwrap.py# This file is taken from the PyPy project, http://codespeak.net/pypy """Text wrapping and filling. """ # Copyright (C) 1999-2001 Gregory P. Ward. # Copyright (C) 2002, 2003 Python Software Foundation. # Written by Greg Ward __revision__ = "$Id: textwrap.py,v 1.32.8.2 2004/05/13 01:48:15 gward Exp $" import string, re # Do the right thing with boolean values for all known Python versions # (so this module can be copied to projects that don't depend on Python # 2.3, e.g. Optik and Docutils). try: True, False except NameError: (True, False) = (1, 0) __all__ = ['TextWrapper', 'wrap', 'fill'] # Hardcode the recognized whitespace characters to the US-ASCII # whitespace characters. The main reason for doing this is that in # ISO-8859-1, 0xa0 is non-breaking whitespace, so in certain locales # that character winds up in string.whitespace. Respecting # string.whitespace in those cases would 1) make textwrap treat 0xa0 the # same as any other whitespace char, which is clearly wrong (it's a # *non-breaking* space), 2) possibly cause problems with Unicode, # since 0xa0 is not in range(128). _whitespace = '\t\n\x0b\x0c\r ' class TextWrapper: """ Object for wrapping/filling text. The public interface consists of the wrap() and fill() methods; the other methods are just there for subclasses to override in order to tweak the default behaviour. If you want to completely replace the main wrapping algorithm, you'll probably have to override _wrap_chunks(). Several instance attributes control various aspects of wrapping: width (default: 70) the maximum width of wrapped lines (unless break_long_words is false) initial_indent (default: "") string that will be prepended to the first line of wrapped output. Counts towards the line's width. subsequent_indent (default: "") string that will be prepended to all lines save the first of wrapped output; also counts towards each line's width. expand_tabs (default: true) Expand tabs in input text to spaces before further processing. Each tab will become 1 .. 8 spaces, depending on its position in its line. If false, each tab is treated as a single character. replace_whitespace (default: true) Replace all whitespace characters in the input text by spaces after tab expansion. Note that if expand_tabs is false and replace_whitespace is true, every tab will be converted to a single space! fix_sentence_endings (default: false) Ensure that sentence-ending punctuation is always followed by two spaces. Off by default because the algorithm is (unavoidably) imperfect. break_long_words (default: true) Break words longer than 'width'. If false, those words will not be broken, and some lines might be longer than 'width'. """ whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace)) unicode_whitespace_trans = {} uspace = ord(u' ') for x in map(ord, _whitespace): unicode_whitespace_trans[x] = uspace # This funky little regex is just the trick for splitting # text up into word-wrappable chunks. E.g. # "Hello there -- you goof-ball, use the -b option!" # splits into # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option! # (after stripping out empty strings). wordsep_re = re.compile(r'(\s+|' # any whitespace r'-*\w{2,}-(?=\w{2,})|' # hyphenated words r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash # XXX will there be a locale-or-charset-aware version of # string.lowercase in 2.3? sentence_end_re = re.compile(r'[%s]' # lowercase letter r'[\.\!\?]' # sentence-ending punct. r'[\"\']?' # optional end-of-quote % string.lowercase) def __init__(self, width=70, initial_indent="", subsequent_indent="", expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True): self.width = width self.initial_indent = initial_indent self.subsequent_indent = subsequent_indent self.expand_tabs = expand_tabs self.replace_whitespace = replace_whitespace self.fix_sentence_endings = fix_sentence_endings self.break_long_words = break_long_words # -- Private methods ----------------------------------------------- # (possibly useful for subclasses to override) def _munge_whitespace(self, text): """_munge_whitespace(text : string) -> string Munge whitespace in text: expand tabs and convert all other whitespace characters to spaces. Eg. " foo\tbar\n\nbaz" becomes " foo bar baz". """ if self.expand_tabs: text = text.expandtabs() if self.replace_whitespace: if isinstance(text, str): text = text.translate(self.whitespace_trans) elif isinstance(text, unicode): text = text.translate(self.unicode_whitespace_trans) return text def _split(self, text): """_split(text : string) -> [string] Split the text to wrap into indivisible chunks. Chunks are not quite the same as words; see wrap_chunks() for full details. As an example, the text Look, goof-ball -- use the -b option! breaks into the following chunks: 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', 'use', ' ', 'the', ' ', '-b', ' ', 'option!' """ chunks = self.wordsep_re.split(text) chunks = filter(None, chunks) return chunks def _fix_sentence_endings(self, chunks): """_fix_sentence_endings(chunks : [string]) Correct for sentence endings buried in 'chunks'. Eg. when the original text contains "... foo.\nBar ...", munge_whitespace() and split() will convert that to [..., "foo.", " ", "Bar", ...] which has one too few spaces; this method simply changes the one space to two. """ i = 0 pat = self.sentence_end_re while i < len(chunks)-1: if chunks[i+1] == " " and pat.search(chunks[i]): chunks[i+1] = " " i += 2 else: i += 1 def _handle_long_word(self, chunks, cur_line, cur_len, width): """_handle_long_word(chunks : [string], cur_line : [string], cur_len : int, width : int) Handle a chunk of text (most likely a word, not whitespace) that is too long to fit in any line. """ space_left = max(width - cur_len, 1) # If we're allowed to break long words, then do so: put as much # of the next chunk onto the current line as will fit. if self.break_long_words: cur_line.append(chunks[0][0:space_left]) chunks[0] = chunks[0][space_left:] # Otherwise, we have to preserve the long word intact. Only add # it to the current line if there's nothing already there -- # that minimizes how much we violate the width constraint. elif not cur_line: cur_line.append(chunks.pop(0)) # If we're not allowed to break long words, and there's already # text on the current line, do nothing. Next time through the # main loop of _wrap_chunks(), we'll wind up here again, but # cur_len will be zero, so the next line will be entirely # devoted to the long word that we can't handle right now. def _wrap_chunks(self, chunks): """_wrap_chunks(chunks : [string]) -> [string] Wrap a sequence of text chunks and return a list of lines of length 'self.width' or less. (If 'break_long_words' is false, some lines may be longer than this.) Chunks correspond roughly to words and the whitespace between them: each chunk is indivisible (modulo 'break_long_words'), but a line break can come between any two chunks. Chunks should not have internal whitespace; ie. a chunk is either all whitespace or a "word". Whitespace chunks will be removed from the beginning and end of lines, but apart from that whitespace is preserved. """ lines = [] if self.width <= 0: raise ValueError("invalid width %r (must be > 0)" % self.width) while chunks: # Start the list of chunks that will make up the current line. # cur_len is just the length of all the chunks in cur_line. cur_line = [] cur_len = 0 # Figure out which static string will prefix this line. if lines: indent = self.subsequent_indent else: indent = self.initial_indent # Maximum width for this line. width = self.width - len(indent) # First chunk on line is whitespace -- drop it, unless this # is the very beginning of the text (ie. no lines started yet). if chunks[0].strip() == '' and lines: del chunks[0] while chunks: l = len(chunks[0]) # Can at least squeeze this chunk onto the current line. if cur_len + l <= width: cur_line.append(chunks.pop(0)) cur_len += l # Nope, this line is full. else: break # The current line is full, and the next chunk is too big to # fit on *any* line (not just this one). if chunks and len(chunks[0]) > width: self._handle_long_word(chunks, cur_line, cur_len, width) # If the last chunk on this line is all whitespace, drop it. if cur_line and cur_line[-1].strip() == '': del cur_line[-1] # Convert current line back to a string and store it in list # of all lines (return value). if cur_line: lines.append(indent + ''.join(cur_line)) return lines # -- Public interface ---------------------------------------------- def wrap(self, text): """wrap(text : string) -> [string] Reformat the single paragraph in 'text' so it fits in lines of no more than 'self.width' columns, and return a list of wrapped lines. Tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. """ text = self._munge_whitespace(text) indent = self.initial_indent chunks = self._split(text) if self.fix_sentence_endings: self._fix_sentence_endings(chunks) return self._wrap_chunks(chunks) def fill(self, text): """fill(text : string) -> string Reformat the single paragraph in 'text' to fit in lines of no more than 'self.width' columns, and return a new string containing the entire wrapped paragraph. """ return "\n".join(self.wrap(text)) # -- Convenience interface --------------------------------------------- def wrap(text, width=70, **kwargs): """Wrap a single paragraph of text, returning a list of wrapped lines. Reformat the single paragraph in 'text' so it fits in lines of no more than 'width' columns, and return a list of wrapped lines. By default, tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ w = TextWrapper(width=width, **kwargs) return w.wrap(text) def fill(text, width=70, **kwargs): """Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ w = TextWrapper(width=width, **kwargs) return w.fill(text) # -- Loosely related functionality ------------------------------------- def dedent(text): """dedent(text : string) -> string Remove any whitespace than can be uniformly removed from the left of every line in `text`. This can be used e.g. to make triple-quoted strings line up with the left edge of screen/whatever, while still presenting it in the source code in indented form. For example: def test(): # end first line with \ to avoid the empty line! s = '''\ hello world ''' print repr(s) # prints ' hello\n world\n ' print repr(dedent(s)) # prints 'hello\n world\n' """ lines = text.expandtabs().split('\n') margin = None for line in lines: content = line.lstrip() if not content: continue indent = len(line) - len(content) if margin is None: margin = indent else: margin = min(margin, indent) if margin is not None and margin > 0: for i in range(len(lines)): lines[i] = lines[i][margin:] return '\n'.join(lines) PKšá4XF2÷q÷qtestoob/compatibility/trace.py#!/usr/bin/env python # portions copyright 2001, Autonomous Zones Industries, Inc., all rights... # err... reserved and offered to the public under the terms of the # Python 2.2 license. # Author: Zooko O'Whielacronx # http://zooko.com/ # mailto:zooko@zooko.com # # Copyright 2000, Mojam Media, Inc., all rights reserved. # Author: Skip Montanaro # # Copyright 1999, Bioreason, Inc., all rights reserved. # Author: Andrew Dalke # # Copyright 1995-1997, Automatrix, Inc., all rights reserved. # Author: Skip Montanaro # # Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved. # # # Permission to use, copy, modify, and distribute this Python software and # its associated documentation for any purpose without fee is hereby # granted, provided that the above copyright notice appears in all copies, # and that both that copyright notice and this permission notice appear in # supporting documentation, and that the name of neither Automatrix, # Bioreason or Mojam Media be used in advertising or publicity pertaining to # distribution of the software without specific, written prior permission. # """program/module to trace Python program or function execution Sample use, command line: trace.py -c -f counts --ignore-dir '$prefix' spam.py eggs trace.py -t --ignore-dir '$prefix' spam.py eggs trace.py --trackcalls spam.py eggs Sample use, programmatically import sys # create a Trace object, telling it what to ignore, and whether to # do tracing or line-counting or both. tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, count=1) # run the new command using the given tracer tracer.run('main()') # make a report, placing output in /tmp r = tracer.results() r.write_results(show_missing=True, coverdir="/tmp") """ import linecache import os import re import sys import threading import token import tokenize import types import gc try: import cPickle pickle = cPickle except ImportError: import pickle def usage(outfile): outfile.write("""Usage: %s [OPTIONS] [ARGS] Meta-options: --help Display this help then exit. --version Output version information then exit. Otherwise, exactly one of the following three options must be given: -t, --trace Print each line to sys.stdout before it is executed. -c, --count Count the number of times each line is executed and write the counts to .cover for each module executed, in the module's directory. See also `--coverdir', `--file', `--no-report' below. -l, --listfuncs Keep track of which functions are executed at least once and write the results to sys.stdout after the program exits. -T, --trackcalls Keep track of caller/called pairs and write the results to sys.stdout after the program exits. -r, --report Generate a report from a counts file; do not execute any code. `--file' must specify the results file to read, which must have been created in a previous run with `--count --file=FILE'. Modifiers: -f, --file= File to accumulate counts over several runs. -R, --no-report Do not generate the coverage report files. Useful if you want to accumulate over several runs. -C, --coverdir= Directory where the report files. The coverage report for . is written to file //.cover. -m, --missing Annotate executable lines that were not executed with '>>>>>> '. -s, --summary Write a brief summary on stdout for each file. (Can only be used with --count or --report.) Filters, may be repeated multiple times: --ignore-module= Ignore the given module and its submodules (if it is a package). --ignore-dir= Ignore files in the given directory (multiple directories can be joined by os.pathsep). """ % sys.argv[0]) PRAGMA_NOCOVER = "#pragma NO COVER" # Simple rx to find lines with no code. rx_blank = re.compile(r'^\s*(#.*)?$') class Ignore: def __init__(self, modules = None, dirs = None): self._mods = modules or [] self._dirs = dirs or [] self._dirs = map(os.path.normpath, self._dirs) self._ignore = { '': 1 } def names(self, filename, modulename): if self._ignore.has_key(modulename): return self._ignore[modulename] # haven't seen this one before, so see if the module name is # on the ignore list. Need to take some care since ignoring # "cmp" musn't mean ignoring "cmpcache" but ignoring # "Spam" must also mean ignoring "Spam.Eggs". for mod in self._mods: if mod == modulename: # Identical names, so ignore self._ignore[modulename] = 1 return 1 # check if the module is a proper submodule of something on # the ignore list n = len(mod) # (will not overflow since if the first n characters are the # same and the name has not already occurred, then the size # of "name" is greater than that of "mod") if mod == modulename[:n] and modulename[n] == '.': self._ignore[modulename] = 1 return 1 # Now check that __file__ isn't in one of the directories if filename is None: # must be a built-in, so we must ignore self._ignore[modulename] = 1 return 1 # Ignore a file when it contains one of the ignorable paths for d in self._dirs: # The '+ os.sep' is to ensure that d is a parent directory, # as compared to cases like: # d = "/usr/local" # filename = "/usr/local.py" # or # d = "/usr/local.py" # filename = "/usr/local.py" if filename.startswith(d + os.sep): self._ignore[modulename] = 1 return 1 # Tried the different ways, so we don't ignore this module self._ignore[modulename] = 0 return 0 def modname(path): """Return a plausible module name for the patch.""" base = os.path.basename(path) filename, ext = os.path.splitext(base) return filename def fullmodname(path): """Return a plausible module name for the path.""" # If the file 'path' is part of a package, then the filename isn't # enough to uniquely identify it. Try to do the right thing by # looking in sys.path for the longest matching prefix. We'll # assume that the rest is the package name. longest = "" for dir in sys.path: if path.startswith(dir) and path[len(dir)] == os.path.sep: if len(dir) > len(longest): longest = dir if longest: base = path[len(longest) + 1:] else: base = path base = base.replace(os.sep, ".") if os.altsep: base = base.replace(os.altsep, ".") filename, ext = os.path.splitext(base) return filename class CoverageResults: def __init__(self, counts=None, calledfuncs=None, infile=None, callers=None, outfile=None): self.counts = counts if self.counts is None: self.counts = {} self.counter = self.counts.copy() # map (filename, lineno) to count self.calledfuncs = calledfuncs if self.calledfuncs is None: self.calledfuncs = {} self.calledfuncs = self.calledfuncs.copy() self.callers = callers if self.callers is None: self.callers = {} self.callers = self.callers.copy() self.infile = infile self.outfile = outfile if self.infile: # Try to merge existing counts file. try: counts, calledfuncs, callers = \ pickle.load(open(self.infile, 'rb')) self.update(self.__class__(counts, calledfuncs, callers)) except (IOError, EOFError, ValueError), err: print >> sys.stderr, ("Skipping counts file %r: %s" % (self.infile, err)) def update(self, other): """Merge in the data from another CoverageResults""" counts = self.counts calledfuncs = self.calledfuncs callers = self.callers other_counts = other.counts other_calledfuncs = other.calledfuncs other_callers = other.callers for key in other_counts.keys(): counts[key] = counts.get(key, 0) + other_counts[key] for key in other_calledfuncs.keys(): calledfuncs[key] = 1 for key in other_callers.keys(): callers[key] = 1 def write_results(self, show_missing=True, summary=False, coverdir=None): """ @param coverdir """ if self.calledfuncs: print print "functions called:" calls = self.calledfuncs.keys() calls.sort() for filename, modulename, funcname in calls: print ("filename: %s, modulename: %s, funcname: %s" % (filename, modulename, funcname)) if self.callers: print print "calling relationships:" calls = self.callers.keys() calls.sort() lastfile = lastcfile = "" for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in calls: if pfile != lastfile: print print "***", pfile, "***" lastfile = pfile lastcfile = "" if cfile != pfile and lastcfile != cfile: print " -->", cfile lastcfile = cfile print " %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc) # turn the counts data ("(filename, lineno) = count") into something # accessible on a per-file basis per_file = {} for filename, lineno in self.counts.keys(): lines_hit = per_file[filename] = per_file.get(filename, {}) lines_hit[lineno] = self.counts[(filename, lineno)] # accumulate summary info, if needed sums = {} for filename, count in per_file.iteritems(): # skip some "files" we don't care about... if filename == "": continue if filename.endswith(".pyc") or filename.endswith(".pyo"): filename = filename[:-1] if coverdir is None: dir = os.path.dirname(os.path.abspath(filename)) modulename = modname(filename) else: dir = coverdir if not os.path.exists(dir): os.makedirs(dir) modulename = fullmodname(filename) # If desired, get a list of the line numbers which represent # executable content (returned as a dict for better lookup speed) if show_missing: lnotab = find_executable_linenos(filename) else: lnotab = {} source = linecache.getlines(filename) coverpath = os.path.join(dir, modulename + ".cover") n_hits, n_lines = self.write_results_file(coverpath, source, lnotab, count) if summary and n_lines: percent = int(100 * n_hits / n_lines) sums[modulename] = n_lines, percent, modulename, filename if summary and sums: mods = sums.keys() mods.sort() print "lines cov% module (path)" for m in mods: n_lines, percent, modulename, filename = sums[m] print "%5d %3d%% %s (%s)" % sums[m] if self.outfile: # try and store counts and module info into self.outfile try: pickle.dump((self.counts, self.calledfuncs, self.callers), open(self.outfile, 'wb'), 1) except IOError, err: print >> sys.stderr, "Can't save counts files because %s" % err def write_results_file(self, path, lines, lnotab, lines_hit): """Return a coverage results file in path.""" try: outfile = open(path, "w") except IOError, err: print >> sys.stderr, ("trace: Could not open %r for writing: %s" "- skipping" % (path, err)) return 0, 0 n_lines = 0 n_hits = 0 for i, line in enumerate(lines): lineno = i + 1 # do the blank/comment match to try to mark more lines # (help the reader find stuff that hasn't been covered) if lineno in lines_hit: outfile.write("%5d: " % lines_hit[lineno]) n_hits += 1 n_lines += 1 elif rx_blank.match(line): outfile.write(" ") else: # lines preceded by no marks weren't hit # Highlight them if so indicated, unless the line contains # #pragma: NO COVER if lineno in lnotab and not PRAGMA_NOCOVER in lines[i]: outfile.write(">>>>>> ") n_lines += 1 else: outfile.write(" ") outfile.write(lines[i].expandtabs(8)) outfile.close() return n_hits, n_lines def find_lines_from_code(code, strs): """Return dict where keys are lines in the line number table.""" linenos = {} #line_increments = [ord(c) for c in code.co_lnotab[1::2]] # XXX Replaced above line with Python 2.2-compatible line (orip) def odd_indexed_items(seq): return [seq[i] for i in xrange(1, len(seq), 2)] line_increments = [ord(c) for c in odd_indexed_items(code.co_lnotab)] table_length = len(line_increments) docstring = False lineno = code.co_firstlineno for li in line_increments: lineno += li if lineno not in strs: linenos[lineno] = 1 return linenos def find_lines(code, strs): """Return lineno dict for all code objects reachable from code.""" # get all of the lineno information from the code of this scope level linenos = find_lines_from_code(code, strs) # and check the constants for references to other code objects for c in code.co_consts: if isinstance(c, types.CodeType): # find another code object, so recurse into it linenos.update(find_lines(c, strs)) return linenos def find_strings(filename): """Return a dict of possible docstring positions. The dict maps line numbers to strings. There is an entry for line that contains only a string or a part of a triple-quoted string. """ d = {} # If the first token is a string, then it's the module docstring. # Add this special case so that the test in the loop passes. prev_ttype = token.INDENT f = open(filename) for ttype, tstr, start, end, line in tokenize.generate_tokens(f.readline): if ttype == token.STRING: if prev_ttype == token.INDENT: sline, scol = start eline, ecol = end for i in range(sline, eline + 1): d[i] = 1 prev_ttype = ttype f.close() return d def find_executable_linenos(filename): """Return dict where keys are line numbers in the line number table.""" try: prog = open(filename, "rU").read() except IOError, err: print >> sys.stderr, ("Not printing coverage data for %r: %s" % (filename, err)) return {} code = compile(prog, filename, "exec") strs = find_strings(filename) return find_lines(code, strs) class Trace: def __init__(self, count=1, trace=1, countfuncs=0, countcallers=0, ignoremods=(), ignoredirs=(), infile=None, outfile=None): """ @param count true iff it should count number of times each line is executed @param trace true iff it should print out each line that is being counted @param countfuncs true iff it should just output a list of (filename, modulename, funcname,) for functions that were called at least once; This overrides `count' and `trace' @param ignoremods a list of the names of modules to ignore @param ignoredirs a list of the names of directories to ignore all of the (recursive) contents of @param infile file from which to read stored counts to be added into the results @param outfile file in which to write the results """ self.infile = infile self.outfile = outfile self.ignore = Ignore(ignoremods, ignoredirs) self.counts = {} # keys are (filename, linenumber) self.blabbed = {} # for debugging self.pathtobasename = {} # for memoizing os.path.basename self.donothing = 0 self.trace = trace self._calledfuncs = {} self._callers = {} self._caller_cache = {} if countcallers: self.globaltrace = self.globaltrace_trackcallers elif countfuncs: self.globaltrace = self.globaltrace_countfuncs elif trace and count: self.globaltrace = self.globaltrace_lt self.localtrace = self.localtrace_trace_and_count elif trace: self.globaltrace = self.globaltrace_lt self.localtrace = self.localtrace_trace elif count: self.globaltrace = self.globaltrace_lt self.localtrace = self.localtrace_count else: # Ahem -- do nothing? Okay. self.donothing = 1 def run(self, cmd): import __main__ dict = __main__.__dict__ if not self.donothing: sys.settrace(self.globaltrace) threading.settrace(self.globaltrace) try: exec cmd in dict, dict finally: if not self.donothing: sys.settrace(None) threading.settrace(None) def runctx(self, cmd, globals=None, locals=None): if globals is None: globals = {} if locals is None: locals = {} if not self.donothing: sys.settrace(self.globaltrace) threading.settrace(self.globaltrace) try: exec cmd in globals, locals finally: if not self.donothing: sys.settrace(None) threading.settrace(None) def runfunc(self, func, *args, **kw): result = None if not self.donothing: sys.settrace(self.globaltrace) try: result = func(*args, **kw) finally: if not self.donothing: sys.settrace(None) return result def file_module_function_of(self, frame): code = frame.f_code filename = code.co_filename if filename: modulename = modname(filename) else: modulename = None funcname = code.co_name clsname = None if code in self._caller_cache: if self._caller_cache[code] is not None: clsname = self._caller_cache[code] else: self._caller_cache[code] = None ## use of gc.get_referrers() was suggested by Michael Hudson # all functions which refer to this code object funcs = [f for f in gc.get_referrers(code) if hasattr(f, "func_doc")] # require len(func) == 1 to avoid ambiguity caused by calls to # new.function(): "In the face of ambiguity, refuse the # temptation to guess." if len(funcs) == 1: dicts = [d for d in gc.get_referrers(funcs[0]) if isinstance(d, dict)] if len(dicts) == 1: classes = [c for c in gc.get_referrers(dicts[0]) if hasattr(c, "__bases__")] if len(classes) == 1: # ditto for new.classobj() clsname = str(classes[0]) # cache the result - assumption is that new.* is # not called later to disturb this relationship # _caller_cache could be flushed if functions in # the new module get called. self._caller_cache[code] = clsname if clsname is not None: # final hack - module name shows up in str(cls), but we've already # computed module name, so remove it clsname = clsname.split(".")[1:] clsname = ".".join(clsname) funcname = "%s.%s" % (clsname, funcname) return filename, modulename, funcname def globaltrace_trackcallers(self, frame, why, arg): """Handler for call events. Adds information about who called who to the self._callers dict. """ if why == 'call': # XXX Should do a better job of identifying methods this_func = self.file_module_function_of(frame) parent_func = self.file_module_function_of(frame.f_back) self._callers[(parent_func, this_func)] = 1 def globaltrace_countfuncs(self, frame, why, arg): """Handler for call events. Adds (filename, modulename, funcname) to the self._calledfuncs dict. """ if why == 'call': this_func = self.file_module_function_of(frame) self._calledfuncs[this_func] = 1 def globaltrace_lt(self, frame, why, arg): """Handler for call events. If the code block being entered is to be ignored, returns `None', else returns self.localtrace. """ if why == 'call': code = frame.f_code filename = code.co_filename if filename: # XXX modname() doesn't work right for packages, so # the ignore support won't work right for packages modulename = modname(filename) if modulename is not None: ignore_it = self.ignore.names(filename, modulename) if not ignore_it: if self.trace: print (" --- modulename: %s, funcname: %s" % (modulename, code.co_name)) return self.localtrace else: return None def localtrace_trace_and_count(self, frame, why, arg): if why == "line": # record the file name and line number of every trace filename = frame.f_code.co_filename lineno = frame.f_lineno key = filename, lineno self.counts[key] = self.counts.get(key, 0) + 1 bname = os.path.basename(filename) print "%s(%d): %s" % (bname, lineno, linecache.getline(filename, lineno)), return self.localtrace def localtrace_trace(self, frame, why, arg): if why == "line": # record the file name and line number of every trace filename = frame.f_code.co_filename lineno = frame.f_lineno bname = os.path.basename(filename) print "%s(%d): %s" % (bname, lineno, linecache.getline(filename, lineno)), return self.localtrace def localtrace_count(self, frame, why, arg): if why == "line": filename = frame.f_code.co_filename lineno = frame.f_lineno key = filename, lineno self.counts[key] = self.counts.get(key, 0) + 1 return self.localtrace def results(self): return CoverageResults(self.counts, infile=self.infile, outfile=self.outfile, calledfuncs=self._calledfuncs, callers=self._callers) def _err_exit(msg): sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) sys.exit(1) def main(argv=None): import getopt if argv is None: argv = sys.argv try: opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lT", ["help", "version", "trace", "count", "report", "no-report", "summary", "file=", "missing", "ignore-module=", "ignore-dir=", "coverdir=", "listfuncs", "trackcalls"]) except getopt.error, msg: sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) sys.stderr.write("Try `%s --help' for more information\n" % sys.argv[0]) sys.exit(1) trace = 0 count = 0 report = 0 no_report = 0 counts_file = None missing = 0 ignore_modules = [] ignore_dirs = [] coverdir = None summary = 0 listfuncs = False countcallers = False for opt, val in opts: if opt == "--help": usage(sys.stdout) sys.exit(0) if opt == "--version": sys.stdout.write("trace 2.0\n") sys.exit(0) if opt == "-T" or opt == "--trackcalls": countcallers = True continue if opt == "-l" or opt == "--listfuncs": listfuncs = True continue if opt == "-t" or opt == "--trace": trace = 1 continue if opt == "-c" or opt == "--count": count = 1 continue if opt == "-r" or opt == "--report": report = 1 continue if opt == "-R" or opt == "--no-report": no_report = 1 continue if opt == "-f" or opt == "--file": counts_file = val continue if opt == "-m" or opt == "--missing": missing = 1 continue if opt == "-C" or opt == "--coverdir": coverdir = val continue if opt == "-s" or opt == "--summary": summary = 1 continue if opt == "--ignore-module": ignore_modules.append(val) continue if opt == "--ignore-dir": for s in val.split(os.pathsep): s = os.path.expandvars(s) # should I also call expanduser? (after all, could use $HOME) s = s.replace("$prefix", os.path.join(sys.prefix, "lib", "python" + sys.version[:3])) s = s.replace("$exec_prefix", os.path.join(sys.exec_prefix, "lib", "python" + sys.version[:3])) s = os.path.normpath(s) ignore_dirs.append(s) continue assert 0, "Should never get here" if listfuncs and (count or trace): _err_exit("cannot specify both --listfuncs and (--trace or --count)") if not (count or trace or report or listfuncs or countcallers): _err_exit("must specify one of --trace, --count, --report, " "--listfuncs, or --trackcalls") if report and no_report: _err_exit("cannot specify both --report and --no-report") if report and not counts_file: _err_exit("--report requires a --file") if no_report and len(prog_argv) == 0: _err_exit("missing name of file to run") # everything is ready if report: results = CoverageResults(infile=counts_file, outfile=counts_file) results.write_results(missing, summary=summary, coverdir=coverdir) else: sys.argv = prog_argv progname = prog_argv[0] sys.path[0] = os.path.split(progname)[0] t = Trace(count, trace, countfuncs=listfuncs, countcallers=countcallers, ignoremods=ignore_modules, ignoredirs=ignore_dirs, infile=counts_file, outfile=counts_file) try: t.run('execfile(%r)' % (progname,)) except IOError, err: _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err)) except SystemExit: pass results = t.results() if not no_report: results.write_results(missing, summary=summary, coverdir=coverdir) if __name__=='__main__': main() PK&ƒ5vð“§  EGG-INFO/PKG-INFOMetadata-Version: 1.0 Name: testoob Version: 1.13 Summary: Testoob - An advanced unit testing framework Home-page: http://testoob.sourceforge.net Author: Ori Peleg Author-email: testoob@gmail.com License: Apache License, Version 2.0 Download-URL: http://sourceforge.net/project/showfiles.php?group_id=138557 Description: Testoob - Python Testing Out Of (The) Box Testoob is an advanced unit testing framework for Python. It integrates effortlessly with existing PyUnit (module "unittest") test suites. Platform: any Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: OS Independent Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: POSIX Classifier: Programming Language :: Python Classifier: Topic :: Software Development :: Quality Assurance Classifier: Topic :: Software Development :: Testing PK&ƒ5“×2EGG-INFO/dependency_links.txt PK&ƒ58õØ  EGG-INFO/SOURCES.txtMANIFEST.in README setup.py docs/CHANGELOG docs/COPYING docs/INSTALL docs/LICENSE-2.0.txt other/setcolor.c other/setcolor.exe src/testoob/__init__.py src/testoob/asserter.py src/testoob/collecting.py src/testoob/coverage.py src/testoob/exceptions.py src/testoob/extracting.py src/testoob/main.py src/testoob/profiling.py src/testoob/test_loaders.py src/testoob/testing.py src/testoob/testoob src/testoob/utils.py src/testoob.egg-info/PKG-INFO src/testoob.egg-info/SOURCES.txt src/testoob.egg-info/dependency_links.txt src/testoob.egg-info/top_level.txt src/testoob/commandline/__init__.py src/testoob/commandline/color_mode_option.py src/testoob/commandline/glob_option.py src/testoob/commandline/html_option.py src/testoob/commandline/immediate_option.py src/testoob/commandline/list_option.py src/testoob/commandline/parsing.py src/testoob/commandline/pbar_option.py src/testoob/commandline/pdf_option.py src/testoob/commandline/processes_option.py src/testoob/commandline/randomize_option.py src/testoob/commandline/regex_option.py src/testoob/commandline/repeat_option.py src/testoob/commandline/silent_option.py src/testoob/commandline/timed_repeat_option.py src/testoob/commandline/xml_option.py src/testoob/compatibility/SimpleXMLWriter.py src/testoob/compatibility/__init__.py src/testoob/compatibility/itertools.py src/testoob/compatibility/optparse.py src/testoob/compatibility/sets.py src/testoob/compatibility/subprocess.py src/testoob/compatibility/textwrap.py src/testoob/compatibility/trace.py src/testoob/reporting/__init__.py src/testoob/reporting/base.py src/testoob/reporting/colored.py src/testoob/reporting/common.py src/testoob/reporting/err_info.py src/testoob/reporting/html.py src/testoob/reporting/html_standalone.py src/testoob/reporting/html_xsl.py src/testoob/reporting/html_xslt.py src/testoob/reporting/pdf.py src/testoob/reporting/progress_bar.py src/testoob/reporting/reporter_proxy.py src/testoob/reporting/test_info.py src/testoob/reporting/textstream.py src/testoob/reporting/xml.py src/testoob/reporting/xslconverters.py src/testoob/reporting/xslt.py src/testoob/running/__init__.py src/testoob/running/baserunner.py src/testoob/running/convenience.py src/testoob/running/fixture_decorators.py src/testoob/running/listingrunner.py src/testoob/running/processed_helper.py src/testoob/running/processedrunner.py src/testoob/running/pyro_runner.py src/testoob/running/simplerunner.py src/testoob/running/threadedrunner.py src/testoob/running/threadpool.py tests/alltests.py tests/benchmark_suites.py tests/helpers.py tests/mock.py tests/procutils.py tests/suites.py tests/large/__init__.py tests/large/dummyproject.py tests/large/dummyprojecttests.py tests/large/missing_eol.py tests/large/missing_eol_tests.py tests/large/test_commandline.py tests/medium/__init__.py tests/medium/test_extracting.py tests/medium/test_running.py tests/medium/test_threadpool.py tests/small/__init__.py tests/small/coverage_sample_module.py tests/small/test_coverage.py tests/small/test_extracting.py tests/small/test_reporting.py tests/small/test_running.py tests/small/test_testing.py PK&ƒ5R‘‚‚EGG-INFO/top_level.txttestoob PK'ƒ5“×2EGG-INFO/not-zip-safe PK'ƒ5¨†SSEGG-INFO/scripts/testoob#!/tmp/py2.3/bin/python import sys def parseArgs(printUsage=False): if printUsage: sys.argv.append("-h") parser, options, free_args = testoob_main("_parse_args")() if len(free_args) == 0: parser.error("No filename specified") file_name = free_args[0] test_names = free_args[1:] return options, file_name, test_names, parser def addPythonPath(path): from os.path import normpath sys.path.insert(0, normpath(path)) def testoob_main(attrname): exec "from testoob.main import %(attrname)s as result" % vars() return result options, file_name, test_names, parser = parseArgs() # Add the path of the ran file to the python path, so that includes # from the same directory would work. from os.path import dirname, basename addPythonPath(dirname(file_name)) # run the file given on the command line name = __name__ __name__ = basename(file_name).split(".")[0] execfile(file_name) __name__ = name try: sys.exit(not testoob_main("_main")(None, None, options, test_names, parser)) except testoob_main("ArgumentsError"), e: parser.error(str(e)) PK'ƒ5^>ÝÃ#Ã#€testoob/testing.pycPKMqƒ5·b]  €ô#testoob/asserter.pyPKšá4  lŠ  €41testoob/profiling.pyPK'ƒ5 ÙrJJ€z<testoob/test_loaders.pycPK„*5° ûÆÆ€úJtestoob/testing.pyPK'ƒ5¢›¡!€ðftestoob/coverage.pycPKšá4½ÝÈ··€?†testoob/exceptions.pyPK'ƒ5õ`ññ€)‰testoob/collecting.pycPK'ƒ5¹œ!ý$$€N¢testoob/profiling.pycPKÈc53^”u+u+€¥¶testoob/main.pyPK'ƒ5R´ÙãI/I/€Gâtestoob/main.pycPK'ƒ5CÔªºº€¾testoob/exceptions.pycPK'ƒ5”"0â‬testoob/extracting.pycPKšá4ï2)wÜÜ€Â0testoob/collecting.pyPKµX5ð@‰!!€Ñ@testoob/extracting.pyPK'ƒ5î-V‹½½€%Rtestoob/__init__.pycPKšá4OwM+¾ ¾ €Ttestoob/test_loaders.pyPK'ƒ5×çc+€^testoob/asserter.pycPK&xƒ5/…‹7SS€Éltestoob/__init__.pyPKšá4¦ø€Mptestoob/coverage.pyPK'ƒ5}aŽêꀎ†testoob/utils.pycPKšá4“àß??€§™testoob/utils.pyPKÌ¢è4ê€bÿ¼¼*€©testoob/commandline/timed_repeat_option.pyPKS¦è4ò7OŠÞÞ(€«testoob/commandline/color_mode_option.pyPK'ƒ5fKäV‹‹+€<°testoob/commandline/timed_repeat_option.pycPK͈c5ZeC£__€´testoob/commandline/parsing.pyPKÓ™á4ÚÀÎaŸŸ!€«¹testoob/commandline/pdf_option.pyPK'ƒ5F™Ž¦ãã#€‰»testoob/commandline/list_option.pycPK'ƒ5U1f««(€­¿testoob/commandline/immediate_option.pycPK'ƒ5o&¦þþ#€žÂtestoob/commandline/glob_option.pycPK¼¥è4÷&#v'€ÝÅtestoob/commandline/immediate_option.pyPK'ƒ5»pÌcýý$€'Çtestoob/commandline/regex_option.pycPK/¤è4ÁY¤aa$€fÊtestoob/commandline/repeat_option.pyPKÓ™á4íjDD'€ Ìtestoob/commandline/randomize_option.pyPK'ƒ5ÕÆ®÷´´)€’Ðtestoob/commandline/color_mode_option.pycPKw¥è40gRuîî$€Øtestoob/commandline/silent_option.pyPKÓ™á4Ðk-LL#€½Ùtestoob/commandline/regex_option.pyPKÓ™á4á®—‘ŽŽ"€JÛtestoob/commandline/html_option.pyPK'ƒ5™ ¯dll €Ýtestoob/commandline/__init__.pycPK'ƒ5iu·##"€Âãtestoob/commandline/xml_option.pycPKÓ™á4µ2å\\!€%çtestoob/commandline/xml_option.pyPK'ƒ5êSæ__(€Àètestoob/commandline/processes_option.pycPK'ƒ5_¥Y/%€eñtestoob/commandline/repeat_option.pycPK'ƒ5u,7djj"€Åôtestoob/commandline/pdf_option.pycPKÓ™á4TÆ>lBB"€oøtestoob/commandline/list_option.pyPK(¥è4é~zkOO"€ñútestoob/commandline/glob_option.pyPK'ƒ5JŒ¢[[#€€ütestoob/commandline/html_option.pycPKÓ™á4^58ýÜÜ€testoob/commandline/__init__.pyPK'ƒ5†öÅ--#€5testoob/commandline/pbar_option.pycPK¢~c5£E2üNN'€£testoob/commandline/processes_option.pyPKræ4EÎ~bb"€6 testoob/commandline/pbar_option.pyPK'ƒ5LÞY5y y €Ø testoob/commandline/parsing.pycPK'ƒ5˜DIƒƒ(€Žtestoob/commandline/randomize_option.pycPK'ƒ5¡õ´ŽŽ%€Wtestoob/commandline/silent_option.pycPK/~c5 ªµ  !€(!testoob/reporting/progress_bar.pyPK'ƒ5 ’î®’’€|.testoob/reporting/xml.pycPK'ƒ5äéº*dd%€ENtestoob/reporting/html_standalone.pycPK'ƒ5^,Që´C´C €ìftestoob/reporting/textstream.pycPKæ™á4‚èdp€Þªtestoob/reporting/err_info.pyPK«â4©é˜rú ú €(³testoob/reporting/xslt.pyPK'ƒ5%Æ~,,€YÀtestoob/reporting/colored.pycPKæ™á4­œùll€­ìtestoob/reporting/common.pyPK'ƒ5¨3R; ; €Rótestoob/reporting/html.pycPK/~c5¬snÐÐ*Ð*€Åÿtestoob/reporting/textstream.pyPKæ™á4N~e³³"€Ò*testoob/reporting/xslconverters.pyPK'ƒ5o7pIM M €Å.testoob/reporting/err_info.pycPKæ™á4›°ÚW€N;testoob/reporting/html_xsl.pyPK/~c5qå(e e #€@testoob/reporting/reporter_proxy.pyPK'ƒ5™ÊŽ^__€5Mtestoob/reporting/html_xslt.pycPK'ƒ5è_(@ÆÆ"€ÑPtestoob/reporting/progress_bar.pycPKæ™á4;9.ˆƒƒ€×itestoob/reporting/pdf.pyPK'ƒ5U¾n--€ztestoob/reporting/__init__.pycPKÀ|5€Ô Òß߀ù}testoob/reporting/colored.pyPK'ƒ5ø¦¦€™testoob/reporting/xslt.pycPK0~c5ðÄÞÞ€ð­testoob/reporting/base.pyPK/~c5ûoÑ ))€Átestoob/reporting/xml.pyPK0~c5€Ü¬¬$€dÓtestoob/reporting/html_standalone.pyPK'ƒ51Þ>Ä''€Rãtestoob/reporting/pdf.pycPKæ™á4jwR·õ õ €°ùtestoob/reporting/test_info.pyPK'ƒ5ÌVkLÀÀ€átestoob/reporting/test_info.pycPKæ™á4W=\z+ + €Þtestoob/reporting/html.pyPK'ƒ5æ;ú‡ËË#€@#testoob/reporting/xslconverters.pycPKf9ç4j×›4••€L&testoob/reporting/__init__.pyPK'ƒ5D\œR!R!€*testoob/reporting/base.pycPK'ƒ5ñÚÐɉ‰€¦Ktestoob/reporting/common.pycPK'ƒ5ïaBÕNN$€iRtestoob/reporting/reporter_proxy.pycPK'ƒ5Šz̤¤€ùhtestoob/reporting/html_xsl.pycPKæ™á4‰ß.SŸŸ€Ùntestoob/reporting/html_xslt.pyPK'ƒ5LÔ###€´rtestoob/running/processedrunner.pycPKЙá42pûPP#€ytestoob/running/processed_helper.pyPK/~c5ÌBãã%€©testoob/running/fixture_decorators.pyPKЙá4úPÎrÌ̀Ϝtestoob/running/threadpool.pyPK“*5 f¶8ii€Ö²testoob/running/baserunner.pyPK'ƒ5‹ŽÕ  $€z·testoob/running/processed_helper.pycPK'ƒ5âoÿÀ7À7&€ÛÀtestoob/running/fixture_decorators.pycPK'ƒ5뫯ùù!€ßøtestoob/running/listingrunner.pycPK'ƒ5þS:11€ testoob/running/__init__.pycPK'ƒ5‚º’sÕ Õ €‚testoob/running/pyro_runner.pycPK'ƒ5ï*ciúú€”1testoob/running/baserunner.pycPKЙá4Iƒ[ö}} €Ê7testoob/running/listingrunner.pyPK/~c5ŒšBåpp€…Ftestoob/running/convenience.pyPKЙá4Ç3¥¡¡€1atestoob/running/simplerunner.pyPKЙá4hã±>||!€etestoob/running/threadedrunner.pyPKЙá4=YÓN~~€Êitestoob/running/pyro_runner.pyPK'ƒ5®²E]7#7#€„€testoob/running/convenience.pycPK˜*5 UÙBŸŸ€ø£testoob/running/__init__.pyPKЙá4peñ"€Ð§testoob/running/processedrunner.pyPK'ƒ5Aýtt €­¬testoob/running/simplerunner.pycPK'ƒ5Õ˜håå"€_°testoob/running/threadedrunner.pycPK'ƒ5w„€„¶testoob/running/threadpool.pycPKšá4S¿gEVV(€ÀÒtestoob/compatibility/SimpleXMLWriter.pyPK'ƒ50ôÈaŸŸ)€\òtestoob/compatibility/SimpleXMLWriter.pycPKšá4 ´‘¢¨L¨L€B testoob/compatibility/sets.pyPK'ƒ5¦ç‚……$€%Ytestoob/compatibility/subprocess.pycPKšá4o¢€9ž9ž#€öÞtestoob/compatibility/subprocess.pyPKšá4RIc)®Ç®Ç!€p}testoob/compatibility/optparse.pyPK'ƒ5{˜´öÛÛ"€]Etestoob/compatibility/optparse.pycPK'ƒ5=ê÷ó9q9q#€² testoob/compatibility/itertools.pycPK'ƒ5iBÈ È "€,’ testoob/compatibility/__init__.pycPK'ƒ50X¿Í?0?0"€4ž testoob/compatibility/textwrap.pycPK'ƒ5m Ò,¬]¬]€³Î testoob/compatibility/sets.pycPKšá4_PŬ, , !€›, testoob/compatibility/__init__.pyPK'ƒ5ø`ÅæCmCm€8 testoob/compatibility/trace.pycPKšá4“æ–üMüM"€†¥ testoob/compatibility/itertools.pyPKšá4g9H4646!€Âó testoob/compatibility/textwrap.pyPKšá4XF2÷q÷q€5* testoob/compatibility/trace.pyPK&ƒ5vð“§  €hœ EGG-INFO/PKG-INFOPK&ƒ5“×2€£  EGG-INFO/dependency_links.txtPK&ƒ58õØ  €ß  EGG-INFO/SOURCES.txtPK&ƒ5R‘‚‚€0­ EGG-INFO/top_level.txtPK'ƒ5“×2€l­ EGG-INFO/not-zip-safePK'ƒ5¨†SSí ­ EGG-INFO/scripts/testoobPK„„>')²