^Rc!@sdZdZdddddddd d d d d ddddddddddddddddddd d!d"g!Zd#d$lZd#d$lZd#d$lZd#d$lZd#d$lZd#d$lZd#d$l Z d#d$l Z d#d$l Z d#d$l Z d#d$l Z d#d$lZd#d%lmZd#d&lmZed'd(ZiZd)ZedZedZedZedZedZedZeeBeBeBeBeBZed Zed Zed Zed ZeeBeBeBZ d*Z!d+Z"d,Z#d-d.Z$d/Z%e&ej'd0e(p)d1Z)d2d3Z*d4Z+d5efd6YZ,d7Z-d8Z.d9e j/fd:YZ0d;Z1dfd<YZ2dfd=YZ3dfd>YZ4dfd?YZ5dfd@YZ6dfdAYZ7de8fdBYZ9de8fdCYZ:de6fdDYZ;e(a<e(e(e(e(e=dEe(e>e>dF Z?e=e(e(e(e(e=dEe(e>e4e(dG Z@e>dHe(dEdIZAdfdJYZBdEaCdKZDdLe jEfdMYZFdNeFfdOYZGe(e(e(e(dPZHdQeFfdRYZIe=e(e(e4e(dSZJdTZKdUZLdVZMe>e(dWZNe>e(dXZOe>dYZPdZfd[YZQieQdZ6d\d]6d^d_6d`da6dbdc6ddde6ZRdfZSeTdgkrejUeSnd$S(hsModule doctest -- a framework for running examples in docstrings. In simplest use, end each module M to be tested with: def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test() Then running the module as a script will cause the examples in the docstrings to get executed and verified: python M.py This won't display anything unless an example fails, in which case the failing example(s) and the cause(s) of the failure(s) are printed to stdout (why not stderr? because stderr is a lame hack <0.2 wink>), and the final line of output is "Test failed.". Run it with the -v switch instead: python M.py -v and a detailed report of all examples tried is printed to stdout, along with assorted summaries at the end. You can force verbose mode by passing "verbose=True" to testmod, or prohibit it by passing "verbose=False". In either of those cases, sys.argv is not examined by testmod. There are a variety of other ways to run doctests, including integration with the unittest framework, and support for running non-Python text files containing doctests. There are also many ways to override parts of doctest's default behaviors. See the Library Reference Manual for details. sreStructuredText entregister_optionflagtDONT_ACCEPT_TRUE_FOR_1tDONT_ACCEPT_BLANKLINEtNORMALIZE_WHITESPACEtELLIPSIStSKIPtIGNORE_EXCEPTION_DETAILtCOMPARISON_FLAGSt REPORT_UDIFFt REPORT_CDIFFt REPORT_NDIFFtREPORT_ONLY_FIRST_FAILUREtREPORTING_FLAGStExampletDocTestt DocTestParsert DocTestFindert DocTestRunnert OutputCheckertDocTestFailuretUnexpectedExceptiont DebugRunnerttestmodttestfiletrun_docstring_examplestTestert DocTestSuitet DocFileSuitetset_unittest_reportflagstscript_from_examplest testsourcet debug_srctdebugiN(tStringIO(t namedtuplet TestResultssfailed attemptedcCstj|dtt>S(Ni(tOPTIONFLAGS_BY_NAMEt setdefaulttlen(tname((s/usr/lib/python2.7/doctest.pyRss s...cCsUd}xHtjD]=}|j|d}|tt|kr||jO}qqW|S(s Return the compiler-flags associated with the future features that have been imported into the given namespace (globs). iN(t __future__tall_feature_namestgettNonetgetattrt compiler_flag(tglobstflagstfnametfeature((s/usr/lib/python2.7/doctest.pyt_extract_future_flagss icCs{tj|r|St|ttfrDt|ttdgS|dkrkt j t j |j dSt ddS(s Return the module specified by `module`. In particular: - If `module` is a module, then return module. - If `module` is a string, then import and return the module with that name. - If `module` is None, then return the calling module. The calling module is assumed to be the module of the stack frame at the given depth in the call stack. t*t__name__s"Expected a module, string, or NoneN(tinspecttismodulet isinstancetstrtunicodet __import__tglobalstlocalsR+tsystmodulest _getframet f_globalst TypeError(tmoduletdepth((s/usr/lib/python2.7/doctest.pyt_normalize_modules  cCs|rvt|d}t||}t|drvt|jdrs|jj|}|jtjd|fSqvnt|}|j |fSWdQXdS(Nit __loader__tget_datas ( RDt_module_relative_paththasattrRERFtreplacetostlineseptopentread(tfilenametpackagetmodule_relativet file_contentstf((s/usr/lib/python2.7/doctest.pyt_load_testfilestencodingsutf-8icCs;t|tr$|jtd}ntjd|d|S(s Add the given number of space characters to the beginning of every non-blank line in `s`, and return the result. If the string `s` is Unicode, it is encoded using the stdout encoding and the `backslashreplace` error handler. tbackslashreplaces (?m)^(?!$)t (R7R9tencodet _encodingtretsub(tstindent((s/usr/lib/python2.7/doctest.pyt_indentscCs;t}|\}}}tj|||d||jS(sz Return a string containing a traceback message for the given exc_info tuple (as returned by sys.exc_info()). tfile(R!t tracebacktprint_exceptiontgetvalue(texc_infotexcouttexc_typetexc_valtexc_tb((s/usr/lib/python2.7/doctest.pyt_exception_tracebacks t _SpoofOutcBseZdZddZRS(cCsNtj|}|r2|jd r2|d7}nt|drJ|`n|S(Ns t softspace(R!RatendswithRHRi(tselftresult((s/usr/lib/python2.7/doctest.pyRas   cCsAtj||t|dr(|`n|js=d|_ndS(NRit(R!ttruncateRHRitbuf(Rktsize((s/usr/lib/python2.7/doctest.pyRns   N(R4t __module__RaR+Rn(((s/usr/lib/python2.7/doctest.pyRhs cCst|kr||kS|jt}dt|}}|d}|rt|j|rmt|}|d=qttSn|d}|r|j|r|t|8}|d=qtSn||krtSxC|D];}|j|||}|dkrtS|t|7}qWtS(s_ Essentially the only subtle case: >>> _ellipsis_match('aa...aa', 'aaa') False ii(tELLIPSIS_MARKERtsplitR&t startswithtFalseRjtfindtTrue(twanttgottwststartpostendpostw((s/usr/lib/python2.7/doctest.pyt_ellipsis_matchs0          cCs"|j}|rd|SdSdS(s)Return a commented form of the given lines# t#N(trstrip(tline((s/usr/lib/python2.7/doctest.pyt _comment_lineAs t_OutputRedirectingPdbcBs5eZdZdZddZdZdZRS(s A specialized version of the python debugger that redirects stdout to a given stream when interacting with the user. Stdout is *not* redirected when traced code is executed. cCs5||_t|_tjj|d|d|_dS(Ntstdouti(t_OutputRedirectingPdb__outRut$_OutputRedirectingPdb__debugger_usedtpdbtPdbt__init__t use_rawinput(Rktout((s/usr/lib/python2.7/doctest.pyROs  cCs>t|_|dkr'tjj}ntjj||dS(N( RwRR+R=R?tf_backRRt set_trace(Rktframe((s/usr/lib/python2.7/doctest.pyRVs  cCs |jrtjj|ndS(N(RRRt set_continue(Rk((s/usr/lib/python2.7/doctest.pyR\s cGs=tj}|jt_ztjj||SWd|t_XdS(N(R=RRRRttrace_dispatch(Rktargst save_stdout((s/usr/lib/python2.7/doctest.pyRbs   N(R4Rqt__doc__RR+RRR(((s/usr/lib/python2.7/doctest.pyRIs    cCstj|std|n|jdr:tdnt|dretjj|j d}nw|j dkrt t j dkrt j ddkrtjjt j dd}qtj}ntd|d tjj||jdS( NsExpected a module: %rt/s1Module-relative files may not have absolute pathst__file__it__main__Rms+Can't resolve paths relative to the module s (it has no __file__)(R5R6RARtt ValueErrorRHRJtpathRsRR4R&R=targvtcurdirtjoin(RBRtbasedir((s/usr/lib/python2.7/doctest.pyRGms (  cBs>eZdZdddddZdZdZdZRS(sn A single doctest example, consisting of source code and expected output. `Example` defines the following attributes: - source: A single Python statement, always ending with a newline. The constructor adds a newline if needed. - want: The expected output from running the source code (either from stdout, or a traceback in case of exception). `want` ends with a newline unless it's empty, in which case it's an empty string. The constructor adds a newline if needed. - exc_msg: The exception message generated by the example, if the example is expected to generate an exception; or `None` if it is not expected to generate an exception. This exception message is compared against the return value of `traceback.format_exception_only()`. `exc_msg` ends with a newline unless it's `None`. The constructor adds a newline if needed. - lineno: The line number within the DocTest string containing this Example where the Example begins. This line number is zero-based, with respect to the beginning of the DocTest. - indent: The example's indentation in the DocTest string. I.e., the number of space characters that preceed the example's first prompt. - options: A dictionary mapping from option flags to True or False, which is used to override default options for this example. Any option flags not contained in this dictionary are left at their default value (as specified by the DocTestRunner's optionflags). By default, no options are set. icCs|jds|d7}n|r?|jd r?|d7}n|dk rh|jd rh|d7}n||_||_||_||_|dkri}n||_||_dS(Ns (RjR+tsourceRxtlinenoR\toptionstexc_msg(RkRRxRRR\R((s/usr/lib/python2.7/doctest.pyRs         cCst|t|k rtS|j|jko|j|jko|j|jko|j|jko|j|jko|j|jkS(N(ttypetNotImplementedRRxRR\RR(Rktother((s/usr/lib/python2.7/doctest.pyt__eq__scCs ||k S(N((RkR((s/usr/lib/python2.7/doctest.pyt__ne__scCs(t|j|j|j|j|jfS(N(thashRRxRR\R(Rk((s/usr/lib/python2.7/doctest.pyt__hash__sN(R4RqRR+RRRR(((s/usr/lib/python2.7/doctest.pyR s "   cBsDeZdZdZdZdZdZdZdZRS(se A collection of doctest examples that should be run in a single namespace. Each `DocTest` defines the following attributes: - examples: the list of examples. - globs: The namespace (aka globals) that the examples should be run in. - name: A name identifying the DocTest (typically, the name of the object whose docstring this DocTest was extracted from). - filename: The name of the file that this DocTest was extracted from, or `None` if the filename is unknown. - lineno: The line number within filename where this DocTest begins, or `None` if the line number is unavailable. This line number is zero-based, with respect to the beginning of the file. - docstring: The string that the examples were extracted from, or `None` if the string is unavailable. cCs@||_||_|j|_||_||_||_dS(s Create a new DocTest containing the given examples. The DocTest's globals are initialized with a copy of `globs`. N(texamplest docstringtcopyR.R'RNR(RkRR.R'RNRR((s/usr/lib/python2.7/doctest.pyRs     cCslt|jdkrd}n1t|jdkr<d}ndt|j}d|j|j|j|fS(Nis no examplesis 1 examples %d exampless(R&RR'RNR(RkR((s/usr/lib/python2.7/doctest.pyt__repr__s  cCst|t|k rtS|j|jko|j|jko|j|jko|j|jko|j|jko|j|jkS(N(RRRRR.R'RNR(RkR((s/usr/lib/python2.7/doctest.pyR scCs ||k S(N((RkR((s/usr/lib/python2.7/doctest.pyRscCs"t|j|j|j|jfS(N(RRR'RNR(Rk((s/usr/lib/python2.7/doctest.pyRscCsVt|tsdSt|j|j|jt|f|j|j|jt|fS(Ni(R7RtcmpR'RNRtid(RkR((s/usr/lib/python2.7/doctest.pyt__cmp__s!( R4RqRRRRRRR(((s/usr/lib/python2.7/doctest.pyRs   cBseZdZejdejejBZejdejejBejBZ ejdj Z ddZ dZ ddZdZejd ejZd Zejd ejZd Zd ZdZRS(sD A class used to parse strings containing doctest examples. s # Source consists of a PS1 line followed by zero or more PS2 lines. (?P (?:^(?P [ ]*) >>> .*) # PS1 line (?:\n [ ]* \.\.\. .*)*) # PS2 lines \n? # Want consists of any non-blank lines that do not start with PS1. (?P (?:(?![ ]*$) # Not a blank line (?![ ]*>>>) # Not a line starting with PS1 .*$\n? # But any other line )*) s # Grab the traceback header. Different versions of Python have # said different things on the first traceback line. ^(?P Traceback\ \( (?: most\ recent\ call\ last | innermost\ last ) \) : ) \s* $ # toss trailing whitespace on the header. (?P .*?) # don't blink: absorb stuff until... ^ (?P \w+ .*) # a line *starts* with alphanum. s ^[ ]*(#.*)?$sc Csx|j}|j|}|dkrYdjg|jdD]}||^q=}ng}d\}}x|jj|D]}|j|||j!||jd||j7}|j |||\} } } } |j | s.|jt | | | d|d|t |j dd| n||jd|j|j7}|j}q~W|j|||S(s= Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument `name` is a name identifying this string, and is only used for error messages. is RR\R(ii(t expandtabst _min_indentRRst _EXAMPLE_REtfinditertappendtstarttcountt_parse_examplet_IS_BLANK_OR_COMMENTR R&tgrouptend( RktstringR't min_indenttltoutputtcharnoRtmRRRxR((s/usr/lib/python2.7/doctest.pytparseUs&  2 ! %cCs%t|j|||||||S(s" Extract all doctest examples from the given string, and collect them into a `DocTest` object. `globs`, `name`, `filename`, and `lineno` are attributes for the new `DocTest` object. See the documentation for `DocTest` for more information. (Rt get_examples(RkRR.R'RNR((s/usr/lib/python2.7/doctest.pyt get_doctest|s cCs2g|j||D]}t|tr|^qS(s Extract all doctest examples from the given string, and return them as a list of `Example` objects. Line numbers are 0-based, because it's most common in doctests that nothing interesting appears on the same line as opening triple-quote, and so the first interesting line is called "line 1" then. The optional argument `name` is a name identifying this string, and is only used for error messages. (RR7R (RkRR'tx((s/usr/lib/python2.7/doctest.pyRs c Cs~t|jd}|jdjd}|j|||||j|dd|d||djg|D]}||d^qr}|jd}|jd} t| dkrtjd | d r| d =n|j| d|||t|djg| D]} | |^q}|jj|}|rS|jd } nd } |j |||} || || fS( s Given a regular expression match from `_EXAMPLE_RE` (`m`), return a pair `(source, want)`, where `source` is the matched example's source code (with prompts and indentation stripped); and `want` is the example's expected output (with indentation stripped). `name` is the string's name, and `lineno` is the line number where the example starts; both are used for error messages. R\Rs iRVt.iRxs *$itmsgN( R&RRst_check_prompt_blankt _check_prefixRRYtmatcht _EXCEPTION_RER+t _find_options( RkRR'RR\t source_linestslRRxt want_linestwlRR((s/usr/lib/python2.7/doctest.pyRs$ "*( &s#\s*doctest:\s*([^\n\'"]*)$c Csi}x|jj|D]}|jdjddj}xp|D]h}|ddksm|dtkrtd|d||fnt|d}|ddk||$                 cCs|dkrtStj|dk r8|tj|kStj|rW|j|jkStj|rv|j|j kSt |dr|j|j kSt |t rtSt ddS(sY Return true if the given object is defined in the given module. Rqs"object must be a class or functionN(R+RwR5Rt isfunctionRt func_globalstisclassR4RqRHR7tpropertyR(RkRBtobject((s/usr/lib/python2.7/doctest.pyt _from_modules c Cs |jrd|GHnt||kr+dSd|t|<|j|||||}|dk rr|j|ntj|r|jrx|jj D]n\} } d|| f} tj | stj | r|j || r|j || | ||||qqWntj|r|jrxt|dij D]\} } t| tswtdt| fntj | ptj | ptj| ptj| pt| tstdt| fnd|| f} |j || | ||||q@Wntj |r|jrx|jj D]\} } t| trit|| } nt| trt|| j} ntj | stj | st| tr<|j || r<d|| f} |j || | ||||q<q<WndS( sm Find tests for the given object and any contained objects, and add them to `tests`. sFinding tests in %sNis%s.%st__test__s5DocTestFinder.find: __test__ keys must be strings: %rs`DocTestFinder.find: __test__ values must be strings, functions, methods, classes, or modules: %rs%s.__test__.%s(RRt _get_testR+RR5R6RRtitemsRRRRR,R7t basestringRRtismethodt staticmethodt classmethodtim_funcR( RkRRR'RBRR.tseenttesttvalnametval((s/usr/lib/python2.7/doctest.pyRsP   %c Cst|tr|}ncyC|jdkr3d}n'|j}t|tsZt|}nWnttfk rzd}nX|j||}|jr| rdS|dkrd}n2t |d|j }|ddkr|d }n|j j |||||S( ss Return a DocTest for the given object, if it defines a docstring; otherwise, return None. RmRis.pycs.pyoiN(s.pycs.pyo( R7RRR+R8RAtAttributeErrort _find_linenoRR,R4RR( RkRR'RBR.RRRRN((s/usr/lib/python2.7/doctest.pyRs(       cCsd}tj|rd}ntj|r|dkr=dStjdt|dd}x6t|D]%\}}|j|ri|}PqiqiWntj |r|j }ntj |r|j }ntj |r|j}ntj|r|j}ntj|r)t|ddd}n|dk r|dkrI|dStjd}x7t|t|D]}|j||rn|SqnWndS( s Return a line number of the given object's docstring. Note: this method assumes that the object has a docstring. is^\s*class\s*%s\bR4t-tco_firstlinenois(^|.*:)\s*\w*("|')N(R+R5R6RRYRR,RRRRRt func_codet istracebackttb_frametisframetf_codetiscodetrangeR&(RkRRRtpatRR((s/usr/lib/python2.7/doctest.pyRs<           N( R4RqRRuRRwRR+RvRRRR(((s/usr/lib/python2.7/doctest.pyRs ]  ? %cBseZdZddZddddZdZdZdZdZ d Z d Z d Z e jd Zdd ZddedZddZdZRS(s2 A class used to run DocTest test cases, and accumulate statistics. The `run` method is used to process a single DocTest case. It returns a tuple `(f, t)`, where `t` is the number of test cases tried, and `f` is the number of test cases that failed. >>> tests = DocTestFinder().find(_TestClass) >>> runner = DocTestRunner(verbose=False) >>> tests.sort(key = lambda test: test.name) >>> for test in tests: ... print test.name, '->', runner.run(test) _TestClass -> TestResults(failed=0, attempted=2) _TestClass.__init__ -> TestResults(failed=0, attempted=2) _TestClass.get -> TestResults(failed=0, attempted=2) _TestClass.square -> TestResults(failed=0, attempted=1) The `summarize` method prints a summary of all the test cases that have been run by the runner, and returns an aggregated `(f, t)` tuple: >>> runner.summarize(verbose=1) 4 items passed all tests: 2 tests in _TestClass 2 tests in _TestClass.__init__ 2 tests in _TestClass.get 1 tests in _TestClass.square 7 tests in 4 items. 7 passed and 0 failed. Test passed. TestResults(failed=0, attempted=7) The aggregated number of tried examples and failed examples is also available via the `tries` and `failures` attributes: >>> runner.tries 7 >>> runner.failures 0 The comparison between expected outputs and actual outputs is done by an `OutputChecker`. This comparison may be customized with a number of option flags; see the documentation for `testmod` for more information. If the option flags are insufficient, then the comparison may also be customized by passing a subclass of `OutputChecker` to the constructor. The test runner's display output can be controlled in two ways. First, an output function (`out) can be passed to `TestRunner.run`; this function will be called with strings that should be displayed. It defaults to `sys.stdout.write`. If capturing the output is not sufficient, then the display output can be also customized by subclassing DocTestRunner, and overriding the methods `report_start`, `report_success`, `report_unexpected_exception`, and `report_failure`. R3iFicCsv|p t|_|dkr0dtjk}n||_||_||_d|_d|_ i|_ t |_ dS(sc Create a new test runner. Optional keyword arg `checker` is the `OutputChecker` that should be used to compare the expected outputs and actual outputs of doctest examples. Optional keyword arg 'verbose' prints lots of stuff if true, only failures if false; by default, it's true iff '-v' is in sys.argv. Optional argument `optionflags` can be used to control how the test runner compares expected output to actual output, and how it displays failures. See the documentation for `testmod` for more information. s-viN( Rt_checkerR+R=RRt optionflagstoriginal_optionflagsttriestfailurest_name2ftRht_fakeout(RktcheckerRR((s/usr/lib/python2.7/doctest.pyRts       cCs_|jr[|jr=|dt|jdt|jq[|dt|jdndS(s Report that the test runner is about to process the given example. (Only displays a message if verbose=True) sTrying: s Expecting: sExpecting nothing N(RRxR]R(RkRRtexample((s/usr/lib/python2.7/doctest.pyt report_starts   (cCs|jr|dndS(st Report that the given example ran successfully. (Only displays a message if verbose=True) sok N(R(RkRRRRy((s/usr/lib/python2.7/doctest.pytreport_successs cCs3||j|||jj|||jdS(s7 Report that the given example failed. N(t_failure_headerRtoutput_differenceR(RkRRRRy((s/usr/lib/python2.7/doctest.pytreport_failurescCs.||j||dtt|dS(sO Report that the given example raised an unexpected exception. sException raised: N(RR]Rg(RkRRRRb((s/usr/lib/python2.7/doctest.pytreport_unexpected_exceptionscCs|jg}|jrs|jdk rJ|jdk rJ|j|jd}nd}|jd|j||jfn!|jd|jd|jf|jd|j}|jt|dj|S(Nit?sFile "%s", line %s, in %ssLine %s, in %ssFailed example:s ( tDIVIDERRNRR+RR'RR]R(RkRRRRR((s/usr/lib/python2.7/doctest.pyRs   !  c Bsd}}|j}ed\}}} |jj} x'e|jD]\} } |je@of|dk} ||_| jrxH| jjD]4\}}|r|j|O_q|j|M_qWn|je @rqDn|d7}| s|j ||| nd|j | f}y7e | j |d|d|jU|jjd }Wn3ek r_n ej}|jjnX|jj}|jjd|}|d kr| | j||jr|}qnej}ej|d d}| s|e|7}n| jd kr(| }n| | j||jrI|}ns|je@rejd| j}ejd|}|r|r| |j d|j d|jr|}qn||kr| sZ|j!||| |qZqD||kr"| s|j"||| |n|d7}qD|| krD| sM|j#||| |n|d7}qDqDW||_|j$|||e%||S( s Run the examples in `test`. Write the outcome of each example with one of the `DocTestRunner.report_*` methods, using the writer function `out`. `compileflags` is the set of compiler flags that should be used to execute examples. Return a tuple `(f, t)`, where `t` is the number of examples tried, and `f` is the number of examples that failed. The examples are run in the namespace `test.globs`. iiistsingleiis(?:[^:]*\.)?([^:]*:)N(&RRRt check_outputRRR RRRRR'RRR.tdebuggerRR+tKeyboardInterruptR=RbRRaRnRxR_tformat_exception_onlyRgRRRYRRRR R!t_DocTestRunner__record_outcomeR#(RkRt compileflagsRRRRtSUCCESStFAILUREtBOOMtcheckt examplenumRtquiett optionflagRRNt exceptionRytoutcomeRbRtm1tm2((s/usr/lib/python2.7/doctest.pyt__runs                   '         cCs^|jj|jd\}}||||f|j|j<|j|7_|j|7_dS(s{ Record the fact that the given DocTest (`test`) generated `f` failures out of `t` tried examples. iN(ii(RR*R'RR(RkRRRtttf2tt2((s/usr/lib/python2.7/doctest.pyt__record_outcomeKss..+)\[(?P\d+)\]>$cCs|jj|}|r|jd|jjkr|jjt|jd}|j}t|t r|j dd}n|j t S|j ||SdS(NR'R/tasciiRU(t%_DocTestRunner__LINECACHE_FILENAME_RERRRR'RtintRR7R9RWt splitlinesRwtsave_linecache_getlines(RkRNtmodule_globalsRRR((s/usr/lib/python2.7/doctest.pyt__patched_linecache_getlinesXs!  cCs||_|dkr't|j}ntj}|dkrH|j}n|jt_tj }t ||_ |j j |j j t_ t j|_|jt _tj}tjt_z|j|||SWd|t_|t_ |jt _|t_|r |jjnXdS(sJ Run the examples in `test`, and display the results using the writer function `out`. The examples are run in the namespace `test.globs`. If `clear_globs` is true (the default), then this namespace will be cleared after the test runs, to help with garbage collection. If you would like to examine the namespace after the test completes, then use `clear_globs=False`. `compileflags` gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to `globs`. The output of each example is checked using `DocTestRunner.check_output`, and the results are formatted by the `DocTestRunner.report_*` methods. N(RR+R2R.R=RtwriteRRRRR&tresetRRR?t*_DocTestRunner__patched_linecache_getlinest displayhookt__displayhook__t_DocTestRunner__runtclear(RkRR*Rt clear_globsRtsave_set_tracetsave_displayhook((s/usr/lib/python2.7/doctest.pytruncs.                c Cs|dkr|j}ng}g}g}d}}x|jjD]w}|\}\} } || 7}|| 7}| dkr|j|qD| dkr|j|| fqD|j|qDW|rL|rt|GdGH|jx|D]} dG| GHqWn|rLt|GdGH|jx&|D]\} } d| | fGHq'WqLn|r|jGHt|GdGH|jx/|D]$\} \} } d| | | fGHqzWn|r|GdGt|jGd GH||Gd G|Gd GHn|rd G|Gd GHn|rdGHnt||S(s Print a summary of all the test cases that have been run by this DocTestRunner, and return a tuple `(f, t)`, where `f` is the total number of failed examples, and `t` is the total number of tried examples. The optional `verbose` argument controls how detailed the summary is. If the verbosity is not specified, then the DocTestRunner's verbosity is used. isitems had no tests:s sitems passed all tests:s %3d tests in %ssitems had failures:s %3d of %3d in %sstests insitems.s passed andsfailed.s***Test Failed***s failures.s Test passed.N( R+RRRRR&RR#R#( RkRtnoteststpassedtfailedttotaltttotalfRR'RRR7tthingR((s/usr/lib/python2.7/doctest.pyt summarizesP           cCsv|j}xf|jjD]U\}\}}||kr^||\}}||}||}n||f|| 9cBs)eZdZdZdZdZRS(s_ A class used to check the whether the actual output from a doctest example matches the expected output. `OutputChecker` defines two methods: `check_output`, which compares a given pair of outputs, and returns true if they match; and `output_difference`, which returns a string describing the differences between two outputs. cCs||krtS|t@sI||fd kr0tS||fd krItSn|t@stjdtjtd|}tjdd|}||krtSn|t@rdj|j }dj|j }||krtSn|t @rt ||rtSnt S( s Return True iff the actual output from an example (`got`) matches the expected output (`want`). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See the documentation for `TestRunner` for more information about option flags. sTrue s1 sFalse s0 s (?m)^%s\s*?$Rms (?m)^\s*?$RV(sTrue s1 (sFalse s0 ( RwRRRYRZtescapetBLANKLINE_MARKERRRRsRR~Ru(RkRxRyR((s/usr/lib/python2.7/doctest.pyR%s,        cCsL|ttBtB@stS|t@r$tS|jddkoK|jddkS(Ns i(RR R RuRwR(RkRxRyR((s/usr/lib/python2.7/doctest.pyt_do_a_fancy_diff%s c Cs|j}|t@s+tjdt|}n|j|||rR|jt}|jt}|t@rt j ||dd}t |d}d}n{|t @rt j ||dd}t |d}d}n@|t@rt jdt j} t | j||}d}ng|D]} | jd^q}d |td j|S|rx|rxd t|t|fS|rd t|S|rd t|SdSdS(s Return a string describing the differences between the expected output for a given example (`example`) and the actual output (`got`). `optionflags` is the set of option flags used to compare `want` and `got`. s(?m)^[ ]*(?= )tnis#unified diff with -expected +actuals-context diff with expected followed by actualtcharjunksndiff with -expected +actuals sDifferences (%s): RmsExpected: %sGot: %ssExpected: %sGot nothing sExpected nothing Got: %ssExpected nothing Got nothing N(RxRRYRZRWRXR>RwRtdifflibt unified_difftlistR t context_diffR tDiffertIS_CHARACTER_JUNKtcompareRR]R( RkRRyRRxRt got_linestdifftkindtengineR((s/usr/lib/python2.7/doctest.pyR<s6        # (R4RqRR%RXR(((s/usr/lib/python2.7/doctest.pyRs 6 cBs eZdZdZdZRS(sA DocTest example has failed in debugging mode. The exception instance has variables: - test: the DocTest object being run - example: the Example object that failed - got: the actual output cCs||_||_||_dS(N(RRRy(RkRRRy((s/usr/lib/python2.7/doctest.pyRws  cCs t|jS(N(R8R(Rk((s/usr/lib/python2.7/doctest.pyt__str__|s(R4RqRRRf(((s/usr/lib/python2.7/doctest.pyRls  cBs eZdZdZdZRS(sA DocTest example has encountered an unexpected exception The exception instance has variables: - test: the DocTest object being run - example: the Example object that failed - exc_info: the exception info cCs||_||_||_dS(N(RRRb(RkRRRb((s/usr/lib/python2.7/doctest.pyRs  cCs t|jS(N(R8R(Rk((s/usr/lib/python2.7/doctest.pyRfs(R4RqRRRf(((s/usr/lib/python2.7/doctest.pyRs  cBs2eZdZddedZdZdZRS(s{ Run doc tests but raise an exception as soon as there is a failure. If an unexpected exception occurs, an UnexpectedException is raised. It contains the test, the example, and the original exception: >>> runner = DebugRunner(verbose=False) >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42', ... {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) ... except UnexpectedException, failure: ... pass >>> failure.test is test True >>> failure.example.want '42\n' >>> exc_info = failure.exc_info >>> raise exc_info[0], exc_info[1], exc_info[2] Traceback (most recent call last): ... KeyError We wrap the original exception to give the calling application access to the test and example information. If the output doesn't match, then a DocTestFailure is raised: >>> test = DocTestParser().get_doctest(''' ... >>> x = 1 ... >>> x ... 2 ... ''', {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) ... except DocTestFailure, failure: ... pass DocTestFailure objects provide access to the test: >>> failure.test is test True As well as to the example: >>> failure.example.want '2\n' and the actual output: >>> failure.got '1\n' If a failure or error occurs, the globals are left intact: >>> del test.globs['__builtins__'] >>> test.globs {'x': 1} >>> test = DocTestParser().get_doctest(''' ... >>> x = 2 ... >>> raise KeyError ... ''', {}, 'foo', 'foo.py', 0) >>> runner.run(test) Traceback (most recent call last): ... UnexpectedException: >>> del test.globs['__builtins__'] >>> test.globs {'x': 2} But the globals are cleared if there is no error: >>> test = DocTestParser().get_doctest(''' ... >>> x = 2 ... ''', {}, 'foo', 'foo.py', 0) >>> runner.run(test) TestResults(failed=0, attempted=1) >>> test.globs {} cCs5tj||||t}|r1|jjn|S(N(RRLRuR.RH(RkRR*RRItr((s/usr/lib/python2.7/doctest.pyRLscCst|||dS(N(R(RkRRRRb((s/usr/lib/python2.7/doctest.pyR!scCst|||dS(N(R(RkRRRRy((s/usr/lib/python2.7/doctest.pyR sN(R4RqRR+RwRLR!R (((s/usr/lib/python2.7/doctest.pyRsY ic Cs|dkr!tjjd}ntj|sFtd|fn|dkr^|j}ntd|} |rt d|d|} nt d|d|} x3| j ||d|d|D]} | j | qW|r| j ntdkr| an tj| t| j| jS( s* m=None, name=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False Test examples in docstrings in functions and classes reachable from module m (or the current module if m is not supplied), starting with m.__doc__. Also test examples reachable from dict m.__test__ if it exists and is not None. m.__test__ maps names to functions, classes and strings; function and class docstrings are tested even if the name is private; strings are tested directly, as if they were docstrings. Return (#failures, #tests). See help(doctest) for an overview. Optional keyword arg "name" gives the name of the module; by default use m.__name__. Optional keyword arg "globs" gives a dict to be used as the globals when executing examples; by default, use m.__dict__. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg "extraglobs" gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. This is new in 2.4. Optional keyword arg "verbose" prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg "report" prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg "optionflags" or's together module constants, and defaults to 0. This is new in 2.3. Possible values (see the docs for details): DONT_ACCEPT_TRUE_FOR_1 DONT_ACCEPT_BLANKLINE NORMALIZE_WHITESPACE ELLIPSIS SKIP IGNORE_EXCEPTION_DETAIL REPORT_UDIFF REPORT_CDIFF REPORT_NDIFF REPORT_ONLY_FIRST_FAILURE Optional keyword arg "raise_on_error" raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. Rstestmod: module required; %rRRRR.RN(R+R=R>R*R5R6RAR4RRRRvRLRStmasterRUR#RR( RR'R.RtreportRRtraise_on_errorRtfindertrunnerR((s/usr/lib/python2.7/doctest.pyRs$E   %    c Csl|r| rtdnt|||\} }|dkrUtjj|}n|dkrji}n |j}|dk r|j|nd|krd|d>> import doctest >>> old = doctest._unittest_reportflags >>> doctest.set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> doctest.set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True sOnly reporting flags allowed(R Rt_unittest_reportflags(R/told((s/usr/lib/python2.7/doctest.pyREs t DocTestCasecBseZdd d d dZdZdZdZdZdZdZ dZ d Z d Z d Z e Zd ZRS(icCsAtjj|||_||_||_||_||_dS(N(tunittesttTestCaseRt_dt_optionflagst _dt_checkert_dt_testt _dt_setUpt _dt_tearDown(RkRRtsetUpttearDownR((s/usr/lib/python2.7/doctest.pyRks     cCs,|j}|jdk r(|j|ndS(N(RRR+(RkR((s/usr/lib/python2.7/doctest.pyRus cCs9|j}|jdk r(|j|n|jjdS(N(RRR+R.RH(RkR((s/usr/lib/python2.7/doctest.pyR{s cCs|j}tj}t}|j}|t@s;|tO}ntd|d|jdt }z5dd|_ |j |d|j dt \}}Wd|t_X|r|j |j|jndS(NRRRR iFRRI(RR=RR!RR RRRRuR#RLRBtfailureExceptiontformat_failureRa(RkRRtnewRRlRR((s/usr/lib/python2.7/doctest.pytrunTests        " cCsj|j}|jdkr!d}n d|j}dj|jjdd}d|j|j|||fS(Nsunknown line numbers%sRis:Failed doctest test for %s File "%s", line %s, in %s %s(RRR+RR'RsRN(RkterrRRtlname((s/usr/lib/python2.7/doctest.pyRs   cCsO|jtd|jd|jdt}|j|jdt|jdS(sRun the test case without results and without catching exceptions The unit test framework includes a debug method on test cases and test suites to support post-mortem debugging. The test code is run in such a way that errors are not caught. This way a caller can catch the errors and initiate post-mortem debugging. The DocTestCase provides a debug method that raises UnexpectedException errors if there is an unexpected exception: >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42', ... {}, 'foo', 'foo.py', 0) >>> case = DocTestCase(test) >>> try: ... case.debug() ... except UnexpectedException, failure: ... pass The UnexpectedException contains the test, the example, and the original exception: >>> failure.test is test True >>> failure.example.want '42\n' >>> exc_info = failure.exc_info >>> raise exc_info[0], exc_info[1], exc_info[2] Traceback (most recent call last): ... KeyError If the output doesn't match, then a DocTestFailure is raised: >>> test = DocTestParser().get_doctest(''' ... >>> x = 1 ... >>> x ... 2 ... ''', {}, 'foo', 'foo.py', 0) >>> case = DocTestCase(test) >>> try: ... case.debug() ... except DocTestFailure, failure: ... pass DocTestFailure objects provide access to the test: >>> failure.test is test True As well as to the example: >>> failure.example.want '2\n' and the actual output: >>> failure.got '1\n' RRRRIN(RRRRRuRLRR(RkRl((s/usr/lib/python2.7/doctest.pyR s B cCs |jjS(N(RR'(Rk((s/usr/lib/python2.7/doctest.pyRscCstt|t|k rtS|j|jkos|j|jkos|j|jkos|j|jkos|j|jkS(N(RRRRRRR(RkR((s/usr/lib/python2.7/doctest.pyRscCs ||k S(N((RkR((s/usr/lib/python2.7/doctest.pyRscCs"t|j|j|j|jfS(N(RRRRR(Rk((s/usr/lib/python2.7/doctest.pyRscCs4|jjjd}d|ddj|d fS(NRs%s (%s)i(RR'RsR(RkR'((s/usr/lib/python2.7/doctest.pyR scCsd|jjS(Ns Doctest: (RR'(Rk((s/usr/lib/python2.7/doctest.pytshortDescription sN(R4RqR+RRRRRR RRRRRRfR(((s/usr/lib/python2.7/doctest.pyRis     H    tSkipDocTestCasecBs2eZdZdZdZdZeZRS(cCs||_tj|ddS(N(RBRRR+(RkRB((s/usr/lib/python2.7/doctest.pyR s cCs|jddS(Ns-DocTestSuite will not work with -O2 and above(tskipTest(Rk((s/usr/lib/python2.7/doctest.pyR scCsdS(N((Rk((s/usr/lib/python2.7/doctest.pyt test_skip scCsd|jjS(NsSkipping tests from %s(RBR4(Rk((s/usr/lib/python2.7/doctest.pyR s(R4RqRRRRRf(((s/usr/lib/python2.7/doctest.pyR s     c Ks*|d krt}nt|}|j|d|d|}| r{tjjdkr{tj}|j t ||S|st |dn|j tj}xz|D]r}t |jdkrqn|js |j}|dd kr|d }n||_n|j t||qW|S( s Convert doctest tests for a module to a unittest test suite. This converts each documentation string in a module that contains doctest tests to a unittest test case. If any of the tests in a doc string fail, then the test case fails. An exception is raised showing the name of the file containing the test and a (sometimes approximate) line number. The `module` argument provides the module to be tested. The argument can be either a module or a module name. If no argument is given, the calling module is used. A number of options may be provided as keyword arguments: setUp A set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown A tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. R.Rishas no docstringsiis.pycs.pyoiN(s.pycs.pyo(R+RRDRvR=R/toptimizeRt TestSuitetaddTestRRRR&RRNRR( RBR.Rt test_finderRRtsuiteRRN((s/usr/lib/python2.7/doctest.pyR s,%           t DocFileCasecBs)eZdZdZeZdZRS(cCsdj|jjjdS(Nt_R(RRR'Rs(Rk((s/usr/lib/python2.7/doctest.pyRh scCs |jjS(N(RRN(Rk((s/usr/lib/python2.7/doctest.pyRk scCsd|jj|jj|fS(Ns2Failed doctest test for %s File "%s", line 0 %s(RR'RN(RkR((s/usr/lib/python2.7/doctest.pyRo s(R4RqRRRfR(((s/usr/lib/python2.7/doctest.pyRf s  c Ks|dkri}n |j}|r=| r=tdnt|||\}}d|krn||d>> text = ''' ... Here are examples of simple math. ... ... Python has super accurate integer addition ... ... >>> 2 + 2 ... 5 ... ... And very friendly error messages: ... ... >>> 1/0 ... To Infinity ... And ... Beyond ... ... You can use logic if you want: ... ... >>> if 0: ... ... blah ... ... blah ... ... ... ... Ho hum ... ''' >>> print script_from_examples(text) # Here are examples of simple math. # # Python has super accurate integer addition # 2 + 2 # Expected: ## 5 # # And very friendly error messages: # 1/0 # Expected: ## To Infinity ## And ## Beyond # # You can use logic if you want: # if 0: blah blah # # Ho hum is # Expected:s s## Ri( RRR7R RRRxRsRtpopR(R[RtpieceRxR((s/usr/lib/python2.7/doctest.pyR s:  4.cCs{t|}tj|}g|D]}|j|kr%|^q%}|s^t|dn|d}t|j}|S(sExtract the test sources from a doctest docstring as a script. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object with the doc string with tests to be debugged. snot found in testsi(RDRRvR'RRR(RBR'RR7Rttestsrc((s/usr/lib/python2.7/doctest.pyR, s ( cCs t|}t|||dS(s4Debug a single doctest docstring, in argument `src`'N(Rt debug_script(tsrctpmR.R((s/usr/lib/python2.7/doctest.pyR< s cCsddl}tjdd}t|d}|j||jz|r\|j}ni}|ryt|||Wqtj dGH|j tj dqXn|j d|||Wdt j |XdS( s7Debug a test script. `src` is the script, as a string.iNs.pyt doctestdebugR}iis execfile(%r)(RttempfiletmktempRLRBtcloseRtexecfileR=Rbt post_mortemRLRJtremove(RRR.Rt srcfilenameRR((s/usr/lib/python2.7/doctest.pyRA s"   cCs2t|}t||}t|||jdS(sDebug a single doctest docstring. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object with the docstring with tests to be debugged. N(RDRRR(RBR'RR((s/usr/lib/python2.7/doctest.pyR a s t _TestClasscBs)eZdZdZdZdZRS(s A pointless class, for sanity-checking of docstring testing. Methods: square() get() >>> _TestClass(13).get() + _TestClass(-12).get() 1 >>> hex(_TestClass(13).square().get()) '0xa9' cCs ||_dS(sval -> _TestClass object with associated value val. >>> t = _TestClass(123) >>> print t.get() 123 N(R(RkR((s/usr/lib/python2.7/doctest.pyR} scCs|jd|_|S(sosquare() -> square TestClass's associated value >>> _TestClass(13).square().get() 169 i(R(Rk((s/usr/lib/python2.7/doctest.pytsquare scCs|jS(s}get() -> return TestClass's associated value. >>> x = _TestClass(-42) >>> print x.get() -42 (R(Rk((s/usr/lib/python2.7/doctest.pyR* s(R4RqRRRR*(((s/usr/lib/python2.7/doctest.pyRo s  s Example of a string object, searched as-is. >>> x = 1; y = 2 >>> x + y, x * y (3, 2) Rs In 2.2, boolean expressions displayed 0 or 1. By default, we still accept them. This can be disabled by passing DONT_ACCEPT_TRUE_FOR_1 to the new optionflags argument. >>> 4 == 4 1 >>> 4 == 4 True >>> 4 > 4 0 >>> 4 > 4 False sbool-int equivalences Blank lines can be marked with : >>> print 'foo\n\nbar\n' foo bar s blank liness If the ellipsis flag is used, then '...' can be used to elide substrings in the desired output: >>> print range(1000) #doctest: +ELLIPSIS [0, 1, 2, ..., 999] tellipsiss| If the whitespace normalization flag is used, then differences in whitespace are ignored. >>> print range(30) #doctest: +NORMALIZE_WHITESPACE [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] swhitespace normalizationcCs1gtjdD]"}|r|ddkr|^q}|stjjtjd}dtkrtjj|\}}ndj|GHdSx|D]}|jdrtjj |\}}tjj d|t |d }tjd=t |\}}nt |d t\}}|rdSqWdS( NiiR REsusage: {0} [-v] file ...is.pyiRP(R=RRJRRmR;tsplitexttformatRjRstinsertR:RRRu(targt testfilesR'RRNtdirnameRR((s/usr/lib/python2.7/doctest.pyt_test s$6  R(VRt __docformat__t__all__R(R=R_R5RRJRYRR[RRRrR!t collectionsR"R#R$RRRRRRRRRR R R R RWRrR2RDRSR,t __stdout__R+RXR]RgRhR~RRRRGR RRRRRt ExceptionRRRRhRwRuRRRRRRRRRRRRRRRRRR RRRR4texit(((s/usr/lib/python2.7/doctest.pyt.s  H0                 1 $ $HL)n  f    z? $I   I R  ,