U e+X!@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%lmZed&deed#iZd'dZedZedZedZedZedZeeBeBeBeBZed Zed Zed Zed ZeeBeBeBZ d(Z!d)Z"d*dZ#d+d,Z$d^d.d/Z%d_d1d2Z&d3d4Z'Gd5d6d6eZ(d7d8Z)d9d:Z*Gd;d<dZ-Gd?ddZ.Gd@ddZ/GdAddZ0GdBddZ1GdCddZ2GdDddZ3GdEdde4Z5GdFdde4Z6GdGdde2Z7d$a8d`dJdZ9dHd$d$d$d$dHd#d$dIe0f dKdZ:dadMdZ;GdNddZGdPdQdQe j?Z@dbdRdZAGdSdTdTe@ZBdHd$d$e0fdUdVZCdWdZDdXdZEdYd ZFdcdZd!ZGddd[d\ZHded]d"ZIiZJd$S)faModule 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. zreStructuredText enregister_optionflagDONT_ACCEPT_TRUE_FOR_1DONT_ACCEPT_BLANKLINENORMALIZE_WHITESPACEELLIPSISIGNORE_EXCEPTION_DETAILCOMPARISON_FLAGS REPORT_UDIFF REPORT_CDIFF REPORT_NDIFFREPORT_ONLY_FIRST_FAILUREREPORTING_FLAGS is_privateExampleDocTest DocTestParser DocTestFinder DocTestRunner OutputCheckerDocTestFailureUnexpectedException DebugRunnertestmodtestfilerun_docstring_examplesTester DocTestSuite DocFileSuiteset_unittest_reportflagsscript_from_examples testsource debug_srcdebugN)StringIOignorecCst|dtt>S)N)OPTIONFLAGS_BY_NAME setdefaultlennamer+?/opt/hc_python/lib/python3.8/site-packages/nose/ext/dtcompat.pyrsz z...cCsJtjdtdd|dddkoH|dddkoB|ddkn S) a}prefix, base -> true iff name prefix + "." + base is "private". Prefix may be an empty string, and base does not contain a period. Prefix is ignored (although functions you write conforming to this protocol may make use of it). Return true iff base begins with an (at least one) underscore, but does not both begin and end with (at least) two underscores. zVis_private is deprecated; it wasn't useful; examine DocTestFinder.find() lists instead stacklevelNr%___)warningswarnDeprecationWarning)prefixbaser+r+r,r s cCs8d}tjD](}||d}|tt|kr ||jO}q |S)z Return the compiler-flags associated with the future features that have been imported into the given namespace (globs). r"N) __future__all_feature_namesgetgetattr compiler_flag)globsflagsfnamefeaturer+r+r,_extract_future_flagss    rAr-cCsVt|r|St|tr,t|ttdgS|dkrJtjt |j dSt ddS)a 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. *N__name__z"Expected a module, string, or None) inspectismodule isinstancestr __import__globalslocalssysmodules _getframe f_globals TypeError)moduledepthr+r+r,_normalize_modules  rRcCstd|d|S)z{ Add the given number of space characters to the beginning every non-blank line in `s`, and return the result. z (?m)^(?!$) )resub)sindentr+r+r,_indentsrYcCs*t}|\}}}tj||||d|S)zz Return a string containing a traceback message for the given exc_info tuple (as returned by sys.exc_info()). )file)r# tracebackprint_exceptiongetvalue)exc_infoZexcoutexc_typeexc_valexc_tbr+r+r,_exception_tracebacks rbc@seZdZddZdddZdS) _SpoofOutcCs2t|}|r |ds |d7}t|dr.|`|S)N softspace)r#r]endswithhasattrre)selfresultr+r+r,r]s   z_SpoofOut.getvalueNcCst||t|dr|`dS)Nre)r#truncatergre)rhsizer+r+r,rjs  z_SpoofOut.truncate)N)rC __module__ __qualname__r]rjr+r+r+r,rcs rccCst|kr||kS|t}t|dks*tdt|}}|d}|rb||r^t|}|d=ndS|d}|r||r|t|8}|d=ndS||krdS|D],}||||}|dkrdS|t|7}qdS)Nr-r"FT)ELLIPSIS_MARKERsplitr(AssertionError startswithrffind)wantgotwsstartposendposwr+r+r,_ellipsis_match s2    rzcCs|}|rd|SdSdS)z)Return a commented form of the given linez# #Nrstrip)liner+r+r, _comment_line9src@s eZdZdZddZddZdS)_OutputRedirectingPdbz 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. cCs||_tj|dSN)_OutputRedirectingPdb__outpdbPdb__init__)rhoutr+r+r,rGsz_OutputRedirectingPdb.__init__cGs2tj}|jt_ztjj|f|WS|t_XdSr)rKstdoutrrrtrace_dispatch)rhargs save_stdoutr+r+r,rKs z$_OutputRedirectingPdb.trace_dispatchN)rCrlrm__doc__rrr+r+r+r,rAsrcCst|std||dr(tdt|drFtj|j d}nV|j dkrt t j dkrt j ddkrtjt j dd}qtj}ntd|d tjj|f|dS) NzExpected a module: %r/z1Module-relative files may not have absolute paths__file__r"__main__z+Can't resolve paths relative to the module z (it has no __file__))rDrErOrr ValueErrorrgospathrprrCr(rKargvcurdirjoin)rPrZbasedirr+r+r,_module_relative_pathVs      rc@seZdZdZdddZdS)ran 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. Nr"cCsv|ds|d7}|r(|ds(|d7}|dk rB|dsB|d7}||_||_||_||_|dkrfi}||_||_dS)Nrd)rfsourcertlinenorXoptionsexc_msg)rhrrtrrrXrr+r+r,rs zExample.__init__)Nr"r"N)rCrlrmrrr+r+r+r,rzs"c@s(eZdZdZddZddZddZdS) rae 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>t|trtd||_||_||_||_||_||_ dS)z Create a new DocTest containing the given examples. The DocTest's globals are initialized with a copy of `globs`. z8DocTest no longer accepts str; use DocTestParser insteadN) rFrGrqexamples docstringcopyr=r*filenamer)rhrr=r*rrrr+r+r,rs  zDocTest.__init__cCsLt|jdkrd}n"t|jdkr(d}ndt|j}d|j|j|j|fS)Nr"z no examplesr%z 1 examplez %d examplesz)r(rr*rr)rhrr+r+r,__repr__szDocTest.__repr__cCs<t|tsdSt|j|j|jt|f|j|j|jt|fS)Nrn)rFrcmpr*rridrhotherr+r+r,__cmp__s  zDocTest.__cmp__N)rCrlrmrrrrr+r+r+r,rs c@seZdZdZedejejBZedejejBej BZ edj Z dddZ dd Zdd d Zd d ZedejZddZedejZddZddZddZdS)rzD A class used to parse strings containing doctest examples. a # 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 )*) a # 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. z ^[ ]*(#.*)?$c s|}||dkr8dfdd|dD}g}d\}}|j|D]}||||||d||7}| |||\}}} } | |s|t || | |t | d|d||d||7}|}qP|||d|S) a= 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. r"rdcsg|]}|dqSrr+.0lZ min_indentr+r, 'sz'DocTestParser.parse..r"r"rX)rrXrN) expandtabs _min_indentrrp _EXAMPLE_REfinditerappendstartcount_parse_example_IS_BLANK_OR_COMMENTrr(groupend) rhstringr*outputZcharnormrrrtrr+rr,parses*     zDocTestParser.parsecCst||||||||S)a" 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. )r get_examples)rhrr=r*rrr+r+r, get_doctestBs zDocTestParser.get_doctestcCsdd|||DS)a 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. cSsg|]}t|tr|qSr+)rFr)rxr+r+r,rYs z.DocTestParser.get_examples..)r)rhrr*r+r+r,rNs zDocTestParser.get_examplesc s t|d|dd}||||||dddd||dfdd |D}|d }|d}t|dkrtd |d r|d =||d||t|dfd d |D}|j|}|r|d}nd}| |||} || ||fS)a 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. rXrrdr%NrT.csg|]}|ddqS)rSNr+)rslrXr+r,rosz0DocTestParser._parse_example..rtz *$rncsg|]}|dqSrr+)rZwlrr+r,rzsmsg) r(rrp_check_prompt_blank _check_prefixrrUmatch _EXCEPTION_RE _find_options) rhrr*r source_linesrrt want_linesrrr+rr,r\s&       zDocTestParser._parse_examplez#\s*doctest:\s*([^\n\'"]*)$c Csi}|j|D]v}|ddd}|D]V}|ddksN|ddtkrdtd|d||ft|dd}|ddk||<q.q|r||rtd |||f|S) a Return a dictionary containing option overrides extracted from option directives in the given source string. `name` is the string's name, and `lineno` is the line number where the example starts; both are used for error messages. r%,rTr"z+-Nz7line %r of the doctest for %s has an invalid option: %r+zSline %r of the doctest for %s has an option directive on a line with no example: %r)_OPTION_DIRECTIVE_RErrreplacerpr&rr) rhrr*rrroption_stringsoptionflagr+r+r,rs"  zDocTestParser._find_optionsz ^([ ]*)(?=\S)cCs2dd|j|D}t|dkr*t|SdSdS)z;Return the minimum indentation of any non-blank line in `s`cSsg|] }t|qSr+)r()rrXr+r+r,rsz-DocTestParser._min_indent..r"N) _INDENT_REfindallr(min)rhrWindentsr+r+r,rs zDocTestParser._min_indentc Cs^t|D]P\}}t||dkr||ddkrtd||d||||d|fqdS)a  Given the lines of a source string (including prompts and leading indentation), check to make sure that every prompt is followed by a space character. If any line is not followed by a space character, then raise ValueError. rSrTz8line %r of the docstring for %s lacks blank after %s: %rr%N) enumerater(r)rhlinesrXr*rir~r+r+r,rs  z!DocTestParser._check_prompt_blankcCs>t|D]0\}}|r||std||d||fqdS)z Check that every line in the given list starts with the given prefix; if any line does not, then raise a ValueError. zGline %r of the docstring for %s has inconsistent leading whitespace: %rr%N)rrrr)rhrr6r*rrr~r+r+r,rs zDocTestParser._check_prefixN)r)r)rCrlrmrrUcompile MULTILINEVERBOSErDOTALLrrrrrrrrrrrrrr+r+r+r,rs(    ' 3c@sXeZdZdZdedddfddZdddZd d Zd d Zd dZ ddZ ddZ dS)ra< A class used to extract the DocTests that are relevant to a given object, from its docstring and the docstrings of its contained objects. Doctests can currently be extracted from the following object types: modules, functions, classes, methods, staticmethods, classmethods, and properties. FTNcCs"||_||_||_||_||_dS)at Create a new doctest finder. The optional argument `parser` specifies a class or function that should be used to create new DocTest objects (or objects that implement the same interface as DocTest). The signature for this factory function should match the signature of the DocTest constructor. If the optional argument `recurse` is false, then `find` will only examine the given object, and not any contained objects. If the optional argument `exclude_empty` is false, then `find` will include tests for objects with empty docstrings. N)_parser_verbose_recurse_exclude_empty _namefilter)rhverboseparserrecurser exclude_emptyr+r+r,rs zDocTestFinder.__init__c Cs|dkr.t|dd}|dkr.tdt|f|dkr|jt|ddkSt|dk rZ|t|kSt|drp|j|j kSt |t r~dSt ddS)zY Return true if the given object is defined in the given module. NTrlz"object must be a class or function) rD isfunctionr __globals__isclassrCr;rrgrlrFpropertyr)rhrPobjectr+r+r, _from_moduleSs      zDocTestFinder._from_modulec CsT|jrtd|t||kr"dSd|t|<||||||}|dk rR||t|r|jrt|j D]Z\} } | | || rqpd|| f} t | st | rp||| rp||| | ||||qpt|r|jrtt|di D]\} } t| tstdt| ft | sht | sht| sht| sht| tshtdt| fd|| f} ||| | ||||qt |rP|jrPt|j D]\} } | | || rʐqt| trt|| } t| trt|| j} t | st | st| tr||| rd|| f} ||| | ||||qdS) zm Find tests for the given object and any contained objects, and add them to `tests`. zFinding tests in %sNr%z%s.%s__test__z5DocTestFinder.find: __test__ keys must be strings: %rz`DocTestFinder.find: __test__ values must be strings, functions, methods, classes, or modules: %rz%s.__test__.%s)rprintr _get_testrrDrErlistritemsrrrrrr;rFrGrrismethod staticmethod classmethod__func__r) rhrrr*rPrr=seentestZvalnamevalr+r+r,rhsv              zDocTestFinder._findc Cst|tr|}nJz,|jdkr"d}n|j}t|ts:t|}Wnttfk rXd}YnX|||}|jrt|stdS|dkrd}nRt|d|j}|dddkr|dd}n&t j dr| drd |dd }|j |||||S) zs Return a DocTest for the given object, if it defines a docstring; otherwise, return None. Nrrz.pycz.pyornjava $py.class%s.py)rFrGrrOAttributeError _find_linenorr;rCrKplatformrrrfrr) rhrr*rPr=rrrrr+r+r,rs4         zDocTestFinder._get_testcCsd}t|rd}t|rb|dkr(dStdt|dd}t|D]\}}||rF|}qbqFt|rr|j }t |r|j }t |r|j }t|r|j}t|rt|ddd}|dk r |dkr|dStd}t|t|D]}|||r|SqdS) z Return a line number of the given object's docstring. Note: this method assumes that the object has a docstring. Nr"z^\s*class\s*%s\brC-co_firstlinenor%z(^|.*:)\s*\w*("|'))rDrErrUrr;rrrrr__code__ istracebacktb_frameisframef_codeiscoderanger()rhrrrpatrr~r+r+r,r s>            zDocTestFinder._find_lineno)NNNN) rCrlrmrrrrsrrrrr r+r+r+r,rs  TE(c@seZdZdZdddZddZdd Zd d Zd d ZddZ ddZ ddZ e dZddZdddZd ddZddZdS)!rzF**********************************************************************Nr"cCsN|pt|_|dkrdtjk}||_||_||_d|_d|_i|_ t |_ dS)ac 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. Nz-vr") r_checkerrKrr optionflagsoriginal_optionflagstriesfailures_name2ftrc_fakeout)rhcheckerrrr+r+r,rs  zDocTestRunner.__init__cCsH|jrD|jr.|dt|jdt|jn|dt|jddS)z Report that the test runner is about to process the given example. (Only displays a message if verbose=True) zTrying: z Expecting: zExpecting nothing N)rrtrYr)rhrrexampler+r+r, report_start2szDocTestRunner.report_startcCs|jr|ddS)zt Report that the given example ran successfully. (Only displays a message if verbose=True) zok N)rrhrrr!rur+r+r,report_success?szDocTestRunner.report_successcCs&|||||j|||jdS)z7 Report that the given example failed. N)_failure_headerroutput_differencerr#r+r+r,report_failureGs zDocTestRunner.report_failurecCs$||||dtt|dS)zO Report that the given example raised an unexpected exception. zException raised: N)r%rYrbrhrrr!r^r+r+r,report_unexpected_exceptionNs   z)DocTestRunner.report_unexpected_exceptioncCs|jg}|jrR|jdk r4|jdk r4|j|jd}nd}|d|j||jfn|d|jd|jf|d|j}|t|d|S)Nr%?zFile "%s", line %s, in %szLine %s, in %szFailed example:rd)DIVIDERrrrr*rrYr)rhrr!rrrr+r+r,r%Us  zDocTestRunner._failure_headerc Csd}}|j}ttd\}}} |jj} t|jD]Z\} } |jt@oL|dk} ||_| jrt| j D],\}}|r|j|O_qh|j|M_qh|d7}| s| ||| d|j | f}z,t t | j|d|d|j|jd}Wn4tk rYnt}|jYnX|j}|jd|}|dkr\| | j||jr|}nt}tj|ddd}| s|t|7}| jdkr| }nj| | j||jr|}nR|jt@rtd | j}td |}|r|r| | d| d|jr|}||kr*| s|!||| |q2||krT| sJ|"||| ||d7}q2|| kr~| st|#||| ||d7}q2d s2t$d |fq2||_|%|||||fS) a 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`. r"rr%zZsingleNr-rnz[^:]*:Fzunknown outcome)&rrrr check_outputrrr rrr"r*execrrr=debuggerZ set_continueKeyboardInterruptrKr^rr]rjrtr[format_exception_onlyrbrrrUrrr$r'r)rq_DocTestRunner__record_outcome)rhr compileflagsrrrrSUCCESSFAILUREZBOOMcheck examplenumr!quietZ optionflagrr exceptionruoutcomer^rm1m2r+r+r,Z__runis                 zDocTestRunner.__runcCsL|j|jd\}}||||f|j|j<|j|7_|j|7_dS)z{ Record the fact that the given DocTest (`test`) generated `f` failures out of `t` tried examples. rN)rr:r*rr)rhrftf2t2r+r+r,Z__record_outcomeszDocTestRunner.__record_outcomez3[\w\.]+)\[(?P\d+)\]>$cCsR|j|}|rD|d|jjkrD|jjt|d}|jdS| |SdS)Nr*r6T) %_DocTestRunner__LINECACHE_FILENAME_RErrrr*rintr splitlinessave_linecache_getlines)rhrrr!r+r+r,Z__patched_linecache_getliness   z*DocTestRunner.__patched_linecache_getlinesTcCs||_|dkrt|j}tj}|dkr,|j}|jt_tj}t ||_ |j |j jt_t j |_|jt _ z||||WS|t_|t_|jt _ |r|jXdS)aJ 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)rrAr=rKrwriterr set_tracerr.resetrrrC*_DocTestRunner__patched_linecache_getlinesclear_DocTestRunner__run)rhrr2r clear_globsrZsave_set_tracer+r+r,runs(    zDocTestRunner.runc Cs|dkr|j}g}g}g}d}}t|jD]b}|\}\} } | | ksLt|| 7}|| 7}| dkrp||q0| dkr||| fq0||q0|r|rtt|d||D]} td| q|rtt|d||D]\} } td| | fq|rJt|j tt|d||D] \} \} } td| | | fq(|rvt|d t|jd t||d |d |rtd |dn|rtd||fS)a 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. Nr"zitems had no tests:z zitems passed all tests:z %3d tests in %szitems had failures:z %3d of %3d in %sztests inzitems.z passed andzfailed.z***Test Failed***z failures.z Test passed.) rrrrrqrrr(rr+) rhrZnotestsZpassedfailedZtotaltZtotalfrr*r<r=thingrr+r+r, summarize/sR        zDocTestRunner.summarizecCsf|j}t|jD]L\}\}}||krTtd|d||\}}||}||}||f||<qdS)Nz*** DocTestRunner.merge: 'z$' in both testers; summing outcomes.)rrrr)rhrdr*r<r=r>r?r+r+r,mergehs zDocTestRunner.merge)NNr")NNT)N)rCrlrmr+rr"r$r'r)r%rIr1rUrr@rGrKrNrPr+r+r+r,r s $ x  9 9c@s(eZdZdZddZddZddZdS) ra_ 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||kr dS|t@s4||fdkr$dS||fdkr4dS|t@sntdttd|}tdd|}||krndS|t@rd|}d|}||krdS|t @rt ||rdSdS) a 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. T)zTrue z1 )zFalse z0 z (?m)^%s\s*?$rz (?m)^\s*?$rTF) rrrUrVescapeBLANKLINE_MARKERrrrprrzrhrtrurr+r+r,r,{s0    zOutputChecker.check_outputcCs<|ttBtB@sdS|t@r dS|ddko:|ddkS)NFTrdr-)rr r rrSr+r+r,_do_a_fancy_diffs zOutputChecker._do_a_fancy_diffc CsB|j}|t@stdt|}||||r|d}|d}|t@rltj ||dd}t |dd}d}nf|t @rtj ||dd}t |dd}d}n8|t @rtjtjd} t | ||}d }n d std d d |D}d|td|S|r|rdt|t|fS|r(dt|S|r:dt|SdSdS)z 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`. z(?m)^[ ]*(?= )Tr-)nNz#unified diff with -expected +actualz-context diff with expected followed by actual)Zcharjunkzndiff with -expected +actualr"zBad diff optioncSsg|]}|dqS)rdr|)rr~r+r+r,rsz3OutputChecker.output_difference..zDifferences (%s): rzExpected: %sGot: %szExpected: %sGot nothing zExpected nothing Got: %szExpected nothing Got nothing )rtrrUrVrRrTrBrdifflibZ unified_diffrr Z context_diffr ZDifferZIS_CHARACTER_JUNKcomparerqrYr) rhr!rurrtrZ got_linesdiffkindZenginer+r+r,r&s8      zOutputChecker.output_differenceN)rCrlrmrr,rTr&r+r+r+r,rss6c@s eZdZdZddZddZdS)rzA DocTest example has failed in debugging mode. The exception instance has variables: - test: the DocTest object being run - excample: the Example object that failed - got: the actual output cCs||_||_||_dSr)rr!ru)rhrr!rur+r+r,rszDocTestFailure.__init__cCs t|jSrrGrrhr+r+r,__str__szDocTestFailure.__str__NrCrlrmrrr\r+r+r+r,rs c@s eZdZdZddZddZdS)rzA DocTest example has encountered an unexpected exception The exception instance has variables: - test: the DocTest object being run - excample: the Example object that failed - exc_info: the exception info cCs||_||_||_dSr)rr!r^)rhrr!r^r+r+r,rszUnexpectedException.__init__cCs t|jSrrZr[r+r+r,r\szUnexpectedException.__str__Nr]r+r+r+r,r s c@s&eZdZd ddZddZddZdS) rNTcCs$t||||d}|r |j|S)NF)rrKr=rH)rhrr2rrJrr+r+r,rK s zDebugRunner.runcCst|||dSr)rr(r+r+r,r)&sz'DebugRunner.report_unexpected_exceptioncCst|||dSr)rr#r+r+r,r')szDebugRunner.report_failure)NNT)rCrlrmrKr)r'r+r+r+r,rs TFc Cs|dk rtdt|dkr(tjd}t|s@td|f|dkrN|j }t || d} |rlt ||d} n t ||d} | j ||||dD]} | | q|r| tdkr| an t| | j| jfS)a m=None, name=None, globs=None, verbose=None, isprivate=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__. Unless isprivate is specified, private names are not skipped. 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 doctest.__doc__ 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 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. Deprecated in Python 2.4: Optional keyword arg "isprivate" specifies a function used to determine whether a name is private. The default function is treat all functions as public. Optionally, "isprivate" can be set to doctest.is_private to skip over functions marked as private using the underscore naming convention; see its docs for details. 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. NzPthe isprivate argument is deprecated; examine DocTestFinder.find() lists insteadrztestmod: module required; %r)rrrrr=r)r3r4r5rKrLr:rDrErOrCrrrrsrKrNmasterrPrr) rr*r=r isprivatereportrrraise_on_errorrfinderrunnerrr+r+r,r5s,K      c Cs|r|std|r&t|}t||}|dkr:tj|}|dkrHi}n|}|dk rb||| rtt||d} n t ||d} t | } | | |||d} | | |r| tdkr| an t| | j| jfS)a Test examples in the given file. Return (#failures, #tests). Optional keyword arg "module_relative" specifies how filenames should be interpreted: - If "module_relative" is True (the default), then "filename" specifies a module-relative path. By default, this path is relative to the calling module's directory; but if the "package" argument is specified, then it is relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and should not be an absolute path (i.e., it may not begin with "/"). - If "module_relative" is False, then "filename" specifies an os-specific path. The path may be absolute or relative (to the current working directory). Optional keyword arg "name" gives the name of the test; by default use the file's basename. Optional keyword argument "package" is a Python package or the name of a Python package whose directory should be used as the base directory for a module relative filename. If no package is specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. Optional keyword arg "globs" gives a dict to be used as the globals when executing examples; by default, use {}. 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. 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. Possible values (see the docs for details): DONT_ACCEPT_TRUE_FOR_1 DONT_ACCEPT_BLANKLINE NORMALIZE_WHITESPACE ELLIPSIS 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. Optional keyword arg "parser" specifies a DocTestParser (or subclass) that should be used to extract tests from the files. 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. 8Package may only be specified for module-relative paths.Nr_r")rrRrrrbasenamerrrropenreadrrKrNrarPrr)rmodule_relativer*packager=rrcrrrdrrfrWrr+r+r,rs0M       NoNamec Cs@t|dd}t||d}|j|||dD]}|j||dq(dS)ar Test examples in the given object's docstring (`f`), using `globs` as globals. Optional argument `name` is used in failure messages. If the optional argument `verbose` is true, then generate output even if there are no failures. `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`. Optional keyword arg `optionflags` specifies options for the testing and output. See the documentation for `testmod` for more information. F)rrr_)r=)r2N)rrrsrK) r<r=rr*r2rrerfrr+r+r,rs  c@sLeZdZdddZddZdddZdd d Zd d Zdd dZddZ dS)rNr"cCstjdtdd|dkr(|dkr(td|dk rHt|sHtd|f|dkrV|j}||_||_||_ ||_ t |d|_ t ||d|_dS)NzCclass Tester is deprecated; use class doctest.DocTestRunner insteadr-r.z*Tester.__init__: must specify mod or globsz)Tester.__init__: mod must be a module; %rrr_)r3r4r5rOrDrErr=rrbrr testfinderr testrunner)rhmodr=rrbrr+r+r,r=s( zTester.__init__cCsTt||j|dd}|jr&td||j|\}}|jrLt|d|d|||fS)NzRunning stringZofzexamples failed in string)rrr=rrrorK)rhrWr*rr<r=r+r+r, runstringSs zTester.runstringc CsRd}}|jj||||jd}|D]&}|j|\}} |||| }}q"||fS)Nr")rPr=)rnrsr=rorK) rhrr*rPr<r=rrr>r?r+r+r,rundoc\s z Tester.rundoccCs8ddl}||}|j||dkr*d}||||S)Nr"F)newrPrrrr)rhrOr*rPrsrr+r+r,rundictes   zTester.rundictcCs$ddl}||}||_|||S)Nr")rsrPrrr)rhrOr*rsrr+r+r, run__test__ms zTester.run__test__cCs |j|Sr)rorN)rhrr+r+r,rNsszTester.summarizecCs|j|jdSr)rorPrr+r+r,rPvsz Tester.merge)NNNNr")NN)N)N) rCrlrmrrqrrrtrurNrPr+r+r+r,r<s   cCs"|t@|krtd|t}|a|S)NzOnly reporting flags allowed)r r_unittest_reportflags)r>oldr+r+r,rs   c@sZeZdZdddZddZddZd d Zd d Zd dZddZ ddZ e Z ddZ dS) DocTestCaser"NcCs.tj|||_||_||_||_||_dSr)unittestTestCaser_dt_optionflags _dt_checker_dt_test _dt_setUp _dt_tearDown)rhrrsetUptearDownr r+r+r,rs  zDocTestCase.__init__cCs|j}|jdk r||dSr)r}r~rhrr+r+r,rs zDocTestCase.setUpcCs(|j}|jdk r|||jdSr)r}rr=rHrr+r+r,rs  zDocTestCase.tearDowncCs~|j}tj}t}|j}|t@s(|tO}t||jdd}z d|_ |j ||j dd\}}W5|t_X|rz| | |dS)NFrr rzF----------------------------------------------------------------------)rrJ)r}rKrr#r{r rvrr|r+rKrDZfailureExceptionformat_failurer])rhrrwrsrrfrrr+r+r,runTests(zDocTestCase.runTestcCsP|j}|jdkrd}n d|j}d|jddd}d|j|j|||fS)Nzunknown line numberz%srrnz:Failed doctest test for %s File "%s", line %s, in %s %s)r}rrr*rpr)rherrrrlnamer+r+r,rs  zDocTestCase.format_failurecCs2|t|j|jdd}||j|dS)NFr)rrr{r|rKr}r)rhrfr+r+r,r!s zDocTestCase.debugcCs|jjSrr}r*r[r+r+r,rszDocTestCase.idcCs,|jjd}d|dd|ddfS)Nrz%s (%s)rn)r}r*rpr)rhr*r+r+r,rszDocTestCase.__repr__cCs d|jjS)Nz Doctest: rr[r+r+r,shortDescriptionszDocTestCase.shortDescription)r"NNN) rCrlrmrrrrrr!rrr\rr+r+r+r,rxs  rxc Ks|dkrt}t|}|j|||d}|dkr4|j}|sBt|d|t}|D]|}t|j dkrjqV|j s|j }|dddkr|dd}n&t j dr|d rd |dd }||_ |t|f|qV|S) a 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. Nr`z has no testsr"rrrnrr r r )rrRrsrrrry TestSuiter(rrrrKrrrrfaddTestrx) rPr=rZ test_finderrrsuiterrr+r+r,rs0%  c@s(eZdZddZddZeZddZdS) DocFileCasecCsd|jjdS)Nr0r)rr}r*rpr[r+r+r,rszDocFileCase.idcCs|jjSr)r}rr[r+r+r,r!szDocFileCase.__repr__cCsd|jj|jj|fS)Nz2Failed doctest test for %s File "%s", line 0 %s)r}r*r)rhrr+r+r,r%szDocFileCase.format_failureN)rCrlrmrrr\rr+r+r+r,rsrc Ksh|dkr i}|r|std|r2t|}t||}tj|}t|}|||||d}t |f|S)Nrgr") rrRrrrrhrirjrr) rrkrlr=rrr*docrr+r+r, DocFileTest*s   rcOsFt}|ddr&t|d|d<|D]}|t|f|q*|S)a>A unittest suite for one or more doctest files. The path to each doctest file is given as a string; the interpretation of that string depends on the keyword argument "module_relative". A number of options may be provided as keyword arguments: module_relative If "module_relative" is True, then the given file paths are interpreted as os-independent module-relative paths. By default, these paths are relative to the calling module's directory; but if the "package" argument is specified, then they are relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and may not be an absolute path (i.e., it may not begin with "/"). If "module_relative" is False, then the given file paths are interpreted as os-specific paths. These paths may be absolute or relative (to the current working directory). package A Python package or the name of a Python package whose directory should be used as the base directory for module relative paths. If "package" is not specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. 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. parser A DocTestParser (or subclass) that should be used to extract tests from the files. rkTrl)ryrr:rRrr)pathskwrrr+r+r,r@s 5 cCsg}t|D]x}t|trh||jdd|j}|r|d|dd|dddD7}q|dd|dddD7}q|r|ddkr|q|r|ddkr|dqd |dS) Nrnz # Expected:cSsg|] }d|qS)z## r+rr+r+r,rsz(script_from_examples..rdcSsg|] }t|qSr+)rrr+r+r,rsr{r") rrrFrrrrtrppopr)rWrZpiecertr+r+r,rs   "   csJt|}t|}fdd|D}|s4td|d}t|j}|S)aExtract 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. csg|]}|jkr|qSr+r))rr=r)r+r,rs ztestsource..znot found in testsr")rRrrsrrr)rPr*rrtestsrcr+r)r,rs   cCst|}t|||dS)z4Debug a single doctest docstring, in argument `src`'N)r debug_script)srcpmr=rr+r+r,r sc Csddl}tdd}t|d}|||z~|r@|}ni}|rz t t t| |d||Wqt t d|t dYqXn|d |||W5t|XdS) z7Debug a test script. `src` is the script, as a string.r"Nz.pyZ doctestdebugryr-r%r-z execfile(%r))rtempfilemktemprirDcloserremoverr-rrjrrKr^Z post_mortemrK)rrr=rZ srcfilenamer<r+r+r,rs"     rcCs$t|}t||}t|||jdS)zDebug 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)rRrrr)rPr*rrr+r+r,r!s )r-)rS) NNNNNTr"NFF)FrmNr")NNNN)FN)FN)F)Kr __docformat____all__r8rKr[rDrrrUryrVrrr3ior#filterwarningsr5rCr&rrrrrrrrr r r r rRror rArRrYrbrcrzrrrrrrrrrr Exceptionrrrrarrrrrvrrzrxrrrrrrr rr!rr+r+r+r,s'.0      ,$5<l5l t v A Q B F