B º²Z üËã!@stdZdZdddddddd 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 mZd#d&lmZed'd(ƒZiZd)d„ZedƒZedƒZedƒZedƒZedƒZedƒZeeBeBeBeBeBZed ƒZed ƒZed ƒZed ƒZedƒZeeBeBeBeBZ d*Z!d+Z"d,d-„Z#dsd/d0„Z$d1d2„Z%d3d4„Z&dtd6d7„Z'd8d9„Z(Gd:d;„d;eƒZ)dd?„Z+d@dA„Z,GdBdC„dCej-ƒZ.dDdE„Z/GdFd„dƒZ0GdGd„dƒZ1GdHd„dƒZ2GdId„dƒZ3GdJd„dƒZ4GdKd„dƒZ5GdLd„de6ƒZ7GdMd„de6ƒZ8GdNd„de4ƒZ9d$a:dudQd„Z;dOd$d$d$d$dOd#d$dPe2ƒd$f dRd„ZdUd„Z?GdVdW„dWe j@ƒZAGdXdY„dYeAƒZBGdZd[„d[e jCƒZDdwd\d„ZEGd]d^„d^eAƒZFdOd$d$e2ƒd$fd_d`„ZGdad„ZHdbd„ZIdcd „ZJdxddd!„ZKdydedf„ZLdzdgd"„ZMGdhdi„diƒZNeNdjdkdldmdndoœZOdpdq„ZPeQdrkrpe  RePƒ¡d$S){aÅModule 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 enÚregister_optionflagÚDONT_ACCEPT_TRUE_FOR_1ÚDONT_ACCEPT_BLANKLINEÚNORMALIZE_WHITESPACEÚELLIPSISÚSKIPÚIGNORE_EXCEPTION_DETAILÚCOMPARISON_FLAGSÚ REPORT_UDIFFÚ REPORT_CDIFFÚ REPORT_NDIFFÚREPORT_ONLY_FIRST_FAILUREÚREPORTING_FLAGSÚ FAIL_FASTÚExampleÚDocTestÚ DocTestParserÚ DocTestFinderÚ DocTestRunnerÚ OutputCheckerÚDocTestFailureÚUnexpectedExceptionÚ DebugRunnerÚtestmodÚtestfileÚrun_docstring_examplesÚ DocTestSuiteÚ DocFileSuiteÚset_unittest_reportflagsÚscript_from_examplesÚ testsourceÚ debug_srcÚdebugéN)ÚStringIO)Ú namedtupleÚ TestResultszfailed attemptedcCst |dttƒ>¡S)Né)ÚOPTIONFLAGS_BY_NAMEÚ setdefaultÚlen)Úname©r+ú*/opt/alt/python37/lib/python3.7/doctest.pyr„sz z...cCs<d}x2tjD](}| |d¡}|tt|ƒkr ||jO}q W|S)z… Return the compiler-flags associated with the future features that have been imported into the given namespace (globs). r"N)Ú __future__Zall_feature_namesÚgetÚgetattrZ compiler_flag)ÚglobsÚflagsZfnameZfeaturer+r+r,Ú_extract_future_flags·s   r2écCsVt |¡r|St|tƒr,t|tƒtƒdgƒS|dkrJtjt  |¡j dSt dƒ‚dS)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) ÚinspectÚismoduleÚ isinstanceÚstrÚ __import__ÚglobalsÚlocalsÚsysÚmodulesÚ _getframeÚ f_globalsÚ TypeError)ÚmoduleZdepthr+r+r,Ú_normalize_moduleÃs  rCcCsxdD]}| |d¡}qW|S)N)z ú Ú )Úreplace)ÚdataÚnewliner+r+r,Ú_newline_convertÖs rIc Csz|rVt|dƒ}t||ƒ}t|ddƒdk rVt|jdƒrV|j |¡}| |¡}t|ƒ|fSt||d}|  ¡|fSQRXdS)NéÚ __loader__Úget_data)Úencoding) rCÚ_module_relative_pathr/ÚhasattrrKrLÚdecoderIÚopenÚread)ÚfilenameÚpackageÚmodule_relativerMZ file_contentsÚfr+r+r,Ú_load_testfileÝs      rWécCst d|d|¡S)z~ Add the given number of space characters to the beginning of every non-blank line in `s`, and return the result. z (?m)^(?!$)ú )ÚreÚsub)ÚsÚindentr+r+r,Ú_indentësr^cCs*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#Ú tracebackÚprint_exceptionÚgetvalue)Úexc_infoZexcoutÚexc_typeZexc_valZexc_tbr+r+r,Ú_exception_tracebackós rec@seZdZdd„Zddd„ZdS)Ú _SpoofOutcCs$t |¡}|r | d¡s |d7}|S)NrE)r#rbÚendswith)ÚselfÚresultr+r+r,rbs z_SpoofOut.getvalueNcCs| |¡t |¡dS)N)Úseekr#Útruncate)rhÚsizer+r+r,rk s z_SpoofOut.truncate)N)r5Ú __module__Ú __qualname__rbrkr+r+r+r,rfÿs rfcCsÄt|kr||kS| t¡}dt|ƒ}}|d}|rR| |¡rNt|ƒ}|d=ndS|d}|r€| |¡r||t|ƒ8}|d=ndS||krŒdSx2|D]*}| |||¡}|dkr°dS|t|ƒ7}q’WdS)z_ Essentially the only subtle case: >>> _ellipsis_match('aa...aa', 'aaa') False r"FéÿÿÿÿT)ÚELLIPSIS_MARKERÚsplitr)Ú startswithrgÚfind)ÚwantÚgotZwsÚstartposÚendposÚwr+r+r,Ú_ellipsis_matchs0     rycCs| ¡}|rd|SdSdS)z)Return a commented form of the given linez# ú#N)Úrstrip)Úliner+r+r,Ú _comment_line?sr}cCshdt|ƒ}}| d¡}|dkr$|}| dd|¡}|dkr>|}| dd|¡}|dkr\|d}|||…S)Nr"rEú:Ú.r&)r)rsÚrfind)ÚmsgÚstartÚendÚir+r+r,Ú_strip_exception_detailsGs  r…c@s2eZdZdZdd„Zd dd„Zdd„Zd d „ZdS) Ú_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(||_d|_tjj||ddd|_dS)NFT)ÚstdoutÚnosigintr&)Ú_OutputRedirectingPdb__outÚ$_OutputRedirectingPdb__debugger_usedÚpdbÚPdbÚ__init__Z use_rawinput)rhÚoutr+r+r,rgsz_OutputRedirectingPdb.__init__NcCs*d|_|dkrt ¡j}tj ||¡dS)NT)rŠr=r?Úf_backr‹rŒÚ set_trace)rhÚframer+r+r,ros z_OutputRedirectingPdb.set_tracecCs|jrtj |¡dS)N)rŠr‹rŒÚ set_continue)rhr+r+r,r’usz"_OutputRedirectingPdb.set_continuecGs.tj}|jt_ztjj|f|žŽS|t_XdS)N)r=r‡r‰r‹rŒÚtrace_dispatch)rhÚargsÚ save_stdoutr+r+r,r“{s z$_OutputRedirectingPdb.trace_dispatch)N)r5rmrnÚ__doc__rrr’r“r+r+r+r,r†as  r†cCsòt |¡std|ƒ‚| d¡r(tdƒ‚tjj| d¡Ž}t |dƒrXtj |j ¡d}nŒ|j dkržt t jƒdkr–t jddkr–tj t jd¡d}qätj}nFt |dƒrÖx,|jD]"}tj ||¡}tj |¡r°|Sq°Wtd |j ƒ‚tj ||¡S) NzExpected a module: %rú/z1Module-relative files may not have absolute pathsÚ__file__r"Ú__main__ÚÚ__path__zBCan't resolve paths relative to the module %r (it has no __file__))r6r7rArrÚ ValueErrorÚosÚpathÚjoinrqrOr˜r5r)r=ÚargvÚcurdirr›Úexists)rBZ test_pathZbasedirZ directoryZfullpathr+r+r,rN†s&         rNc@s*eZdZdZd dd„Zdd„Zdd „ZdS) 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 precede 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| d¡s|d7}|r(| d¡s(|d7}|dk rB| d¡sB|d7}||_||_||_||_|dkrfi}||_||_dS)NrE)rgÚsourcertÚlinenor]ÚoptionsÚexc_msg)rhr£rtr¦r¤r]r¥r+r+r,r×s zExample.__init__cCs\t|ƒt|ƒk rtS|j|jkoZ|j|jkoZ|j|jkoZ|j|jkoZ|j|jkoZ|j|jkS)N)ÚtypeÚNotImplementedr£rtr¤r]r¥r¦)rhÚotherr+r+r,Ú__eq__és     zExample.__eq__cCst|j|j|j|j|jfƒS)N)Úhashr£rtr¤r]r¦)rhr+r+r,Ú__hash__ôszExample.__hash__)Nr"r"N)r5rmrnr–rrªr¬r+r+r+r,r´s "  c@s8eZdZdZdd„Zdd„Zdd„Zdd „Zd d „Zd S) 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,||_||_| ¡|_||_||_||_dS)zŒ Create a new DocTest containing the given examples. The DocTest's globals are initialized with a copy of `globs`. N)ÚexamplesÚ docstringÚcopyr0r*rSr¤)rhr­r0r*rSr¤r®r+r+r,rs  zDocTest.__init__cCsRt|jƒdkrd}n"t|jƒdkr(d}ndt|jƒ}d|jj|j|j|j|fS)Nr"z no examplesr&z 1 examplez %d examplesz<%s %s from %s:%s (%s)>)r)r­Ú __class__r5r*rSr¤)rhr­r+r+r,Ú__repr__szDocTest.__repr__cCs\t|ƒt|ƒk rtS|j|jkoZ|j|jkoZ|j|jkoZ|j|jkoZ|j|jkoZ|j|jkS)N)r§r¨r­r®r0r*rSr¤)rhr©r+r+r,rª)s     zDocTest.__eq__cCst|j|j|j|jfƒS)N)r«r®r*rSr¤)rhr+r+r,r¬4szDocTest.__hash__cCs:t|tƒstS|j|j|jt|ƒf|j|j|jt|ƒfkS)N)r8rr¨r*rSr¤Úid)rhr©r+r+r,Ú__lt__8s zDocTest.__lt__N) r5rmrnr–rr±rªr¬r³r+r+r+r,røs   c@sªeZdZdZe dejejB¡Ze dejejBej B¡Z e d¡j Z ddd„Z dd „Zdd d „Zd d „Ze dej¡Zdd„Ze dej¡Zdd„Zdd„Zdd„ZdS)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| ¡}| |¡‰ˆdkr8d ‡fdd„| d¡Dƒ¡}g}d\}}xª|j |¡D]š}| ||| ¡…¡|| d|| ¡¡7}|  |||¡\}}} } |  |¡sÊ| t || | |ˆt |  d¡ƒ|d¡|| d| ¡| ¡¡7}| ¡}qRW| ||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"rEcsg|]}|ˆd…‘qS)Nr+)Ú.0Úl)Ú min_indentr+r,ú sz'DocTestParser.parse..)r"r"r])r¤r]r¥N)Ú expandtabsÚ _min_indentrŸrqÚ _EXAMPLE_REÚfinditerÚappendr‚ÚcountÚ_parse_exampleÚ_IS_BLANK_OR_COMMENTrr)Úgrouprƒ) rhÚstringr*ÚoutputZcharnor¤Úmr£r¥rtr¦r+)r·r,Úparsess&     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)rhrÂr0r*rSr¤r+r+r,Ú get_doctestšs zDocTestParser.get_doctestcCsdd„| ||¡DƒS)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|tƒr|‘qSr+)r8r)rµÚxr+r+r,r¸±sz.DocTestParser.get_examples..)rÅ)rhrÂr*r+r+r,rƦs zDocTestParser.get_examplesc s t| d¡ƒ‰| d¡ d¡}| |ˆ||¡| |dd…dˆd||¡d ‡fdd „|Dƒ¡}| d ¡}| d¡}t|ƒdkrœt d |d ¡rœ|d =| |dˆ||t|ƒ¡d ‡fd 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. r]r£rEr&NrYrcsg|]}|ˆdd…‘qS)rXNr+)rµZsl)r]r+r,r¸Çsz0DocTestParser._parse_example..rtz *$rocsg|]}|ˆd…‘qS)Nr+)rµZwl)r]r+r,r¸Òsr) r)rÁrqÚ_check_prompt_blankÚ _check_prefixrŸrZÚmatchÚ _EXCEPTION_REÚ _find_options) rhrÄr*r¤Ú source_linesr£rtÚ want_linesr¦r¥r+)r]r,r¿´s$      zDocTestParser._parse_examplez#\s*doctest:\s*([^\n\'"]*)$c Cs´i}xŠ|j |¡D]z}| d¡ dd¡ ¡}x^|D]V}|ddksR|dd…tkrhtd|d||fƒ‚t|dd…}|ddk||<q2WqW|r°| |¡r°td |||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&ú,rYr"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_REr¼rÁrFrqr'rœrÀ) rhr£r*r¤r¥rÄZoption_stringsÚoptionÚflagr+r+r,rÍês  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))rµr]r+r+r,r¸ sz-DocTestParser._min_indent..r"N)Ú _INDENT_REÚfindallr)Úmin)rhr\Úindentsr+r+r,rºs zDocTestParser._min_indentc Csbx\t|ƒD]P\}}t|ƒ|dkr ||ddkr td||d||||d…|fƒ‚q WdS)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. rXrJrYz8line %r of the docstring for %s lacks blank after %s: %rr&N)Ú enumerater)rœ)rhÚlinesr]r*r¤r„r|r+r+r,rÉs   z!DocTestParser._check_prompt_blankcCsBxr™)r/rœr§r6Ú getmoduleZ getsourcefilerAZgetfileÚ linecacheÚgetlinesÚ__dict__r¯ÚupdateÚ_findÚsort) rhÚobjr*rBr0Ú extraglobsr_rÎÚtestsr+r+r,rsMsJ$         zDocTestFinder.findcCsÂ|dkr dSt |¡dk r(|t |¡kSt |¡r>|j|jkSt |¡r|t|dƒr\|jj}nt|dƒrn|j}ndS|j |kSt  |¡r’|j |jkSt|dƒr¨|j |jkSt |t ƒr¶dSt dƒ‚dS)zY Return true if the given object is defined in the given module. NTÚ __objclass__rmz"object must be a class or function)r6réÚ isfunctionrìÚ __globals__ZismethoddescriptorrOrórmr5Úisclassr8Úpropertyrœ)rhrBÚobjectZobj_modr+r+r,Ú _from_module³s(            zDocTestFinder._from_modulec Cs*|jrtd|ƒt|ƒ|kr"dSd|t|ƒ<| |||||¡}|dk rR| |¡t |¡rÂ|jrÂx^|j  ¡D]P\} } d|| f} t  t  | ¡¡sœt  | ¡rn|  || ¡rn| || | ||||¡qnWt |¡rv|jrvxžt|diƒ  ¡D]Š\} } t| tƒstdt| ƒfƒ‚t  | ¡sPt  | ¡sPt | ¡sPt| tƒsPtdt| ƒfƒ‚d|| f} | || | ||||¡qèWt  |¡r&|jr&xš|j  ¡D]Œ\} } t| tƒr´t|| ƒ} t| tƒrÌt|| ƒj} t  | ¡sðt  | ¡sðt| tƒr–|  || ¡r–d|| f} | || | ||||¡q–WdS) 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)ráÚprintr²Ú _get_testr½r6r7rârìÚitemsZ isroutineZunwraprörùrîr/r8r9rœr§Ú staticmethodÚ classmethodÚ__func__r÷) rhròrðr*rBrÎr0ÚseenÚtestZvalnameÚvalr+r+r,rîÏsP                 zDocTestFinder._findc CsÄt|tƒr|}nJy,|jdkr"d}n|j}t|tƒs:t|ƒ}Wnttfk rXd}YnX| ||¡}|jrt|stdS|dkr‚d}n.t|ddƒp’|j}|dd…dkr°|dd…}|j   |||||¡S)zs Return a DocTest for the given object, if it defines a docstring; otherwise, return None. Nršr˜éüÿÿÿz.pycro) r8r9r–rAÚAttributeErrorÚ _find_linenorãr/r5ràrÇ) rhrðr*rBr0rÎr®r¤rSr+r+r,rüs(         zDocTestFinder._get_testcCsd}t |¡rd}t |¡rd|dkr(dSt dt|ddƒ¡}x$t|ƒD]\}}| |¡rH|}PqHWt |¡rt|j }t  |¡r„|j }t  |¡r”|j }t |¡r¤|j}t |¡r¾t|ddƒd}|dk r |dkrØ|dSt d¡}x(t|t|ƒƒD]}| ||¡rò|SqòWdS) 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\br5ú-Úco_firstlinenor&z(^|.*:)\s*\w*("|\'))r6r7rörZrÜr/rÙrËZismethodrrôÚ__code__Z istracebackÚtb_frameZisframeÚf_codeZiscodeÚranger))rhrðrÎr¤Zpatr„r|r+r+r,r4s<          zDocTestFinder._find_lineno)NNNN) r5rmrnr–rrrsrùrîrürr+r+r+r,r.s f?&c@s†eZdZdZdZddd„Zdd„Zd d „Zd d „Zd d„Z dd„Z dd„Z dd„Z e  d¡Zd dd„Zd!dd„Zd"dd„Zdd„ZdS)#ra3 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`. zF**********************************************************************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Ú_checkerr=r ráÚ optionflagsÚoriginal_optionflagsÚtriesÚfailuresÚ_name2ftrfÚ_fakeout)rhÚcheckerrärr+r+r,r¤s  zDocTestRunner.__init__cCsH|jrD|jr.|dt|jƒdt|jƒƒn|dt|jƒdƒdS)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)rártr^r£)rhrŽrÚexampler+r+r,Ú report_startÈs  zDocTestRunner.report_startcCs|jr|dƒdS)zt Report that the given example ran successfully. (Only displays a message if verbose=True) zok N)rá)rhrŽrrrur+r+r,Úreport_successÕszDocTestRunner.report_successcCs&|| ||¡|j |||j¡ƒdS)z7 Report that the given example failed. N)Ú_failure_headerr Úoutput_differencer)rhrŽrrrur+r+r,Úreport_failureÝs zDocTestRunner.report_failurecCs$|| ||¡dtt|ƒƒƒdS)zO Report that the given example raised an unexpected exception. zException raised: N)rr^re)rhrŽrrrcr+r+r,Úreport_unexpected_exceptionäsz)DocTestRunner.report_unexpected_exceptioncCs”|jg}|jrR|jdk r4|jdk r4|j|jd}nd}| d|j||jf¡n| d|jd|jf¡| d¡|j}| t|ƒ¡d |¡S)Nr&ú?zFile "%s", line %s, in %szLine %s, in %szFailed example:rE)ÚDIVIDERrSr¤r½r*r£r^rŸ)rhrrrŽr¤r£r+r+r,rës zDocTestRunner._failure_headerc CsŒd}}|j}tdƒ\}}} |jj} xFt|jƒD]6\} } |jt@oL|dk} ||_| jr–x:| j ¡D],\}}|r‚|j|O_qf|j|M_qfW|jt @r¢q2|d7}| s¼|  ||| ¡d|j | f}y,t t | j|d|dƒ|jƒ|j ¡d}Wn4tk r‚Ynt ¡}|j ¡YnX|j ¡}|j d¡|}|dkrh| | j||jƒrä|}n|tj|dd…Žd}| s|t|ƒ7}| jdkr¢| }nB| | j||jƒrº|}n*|jt@rä| t| jƒt|ƒ|jƒrä|}||kr| sZ| ||| |¡nT||kr0| s&|  ||| |¡|d7}n*|| krZ| sP| !||| |¡|d7}n|r2|jt"@r2Pq2W||_| #|||¡t$||ƒS) 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"rJr&zZsingleNr3ro)%rr r Ú check_outputrÙr­r r¥rýrrr*ÚexecrÜr£r0Údebuggerr’ÚKeyboardInterruptr=rcrrbrkrtr`Úformat_exception_onlyrer¦rr…rrrrÚ_DocTestRunner__record_outcomer%)rhrÚ compileflagsrŽrrrÚSUCCESSÚFAILUREZBOOMZcheckÚ examplenumrÚquietZ optionflagrrSZ exceptionruZoutcomer¦r+r+r,Z__runÿs€                   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. )r"r"N)rr.r*rr)rhrrVÚtÚf2Út2r+r+r,Z__record_outcome|szDocTestRunner.__record_outcomez..+)\[(?P\d+)\]>$cCsV|j |¡}|rF| d¡|jjkrF|jjt| d¡ƒ}|jjddS|  ||¡SdS)Nr*r'T)Úkeepends) Ú%_DocTestRunner__LINECACHE_FILENAME_RErËrÁrr*r­Úintr£Ú splitlinesÚsave_linecache_getlines)rhrSÚmodule_globalsrÄrr+r+r,Z__patched_linecache_getlines‰s  z*DocTestRunner.__patched_linecache_getlinesTc sþ||_|dkrt|jƒ}tj‰|dkrVˆj‰ˆdks@ˆ ¡dkrHˆj}n‡‡fdd„}|jt_t  ¡}t j }t ˆƒ|_ |j  ¡|j j t _ tj|_|jt_tj}tjt_z| |||¡Sˆt_|t _ t |¡|jt_|t_|rø|j ¡ddl}d|_XdS)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. Nzutf-8cs t| ˆd¡ˆƒ}ˆ |¡dS)NÚbackslashreplace)r9ÚencodeÚwrite)r\)rMr•r+r,rޱszDocTestRunner.run..outr")rr2r0r=r‡rMÚlowerr4rÚgettracer‹rr†r Úresetrêrër0Ú*_DocTestRunner__patched_linecache_getlinesÚ displayhookÚ__displayhook__Ú_DocTestRunner__runÚsettraceÚclearÚbuiltinsÚ_) rhrr$rŽÚ clear_globsZ save_traceZsave_set_traceZsave_displayhookr>r+)rMr•r,Úrun‘s<      zDocTestRunner.runc Cs¢|dkr|j}g}g}g}d}}xd|j ¡D]V}|\}\} } || 7}|| 7}| dkrb| |¡q.| dkrz| || f¡q.| |¡q.W|rú|r¾tt|ƒdƒ| ¡x|D]} td| ƒq¬W|rútt|ƒdƒ| ¡x |D]\} } td| | fƒqÞW|rJt|jƒtt|ƒdƒ| ¡x(|D] \} \} } td| | | fƒq&W|rvt|d t|jƒd ƒt||d |d ƒ|rŠtd |dƒn|r˜tdƒt||ƒS)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.) rárrýr½rûr)rïrr%) rhräZnotestsZpassedZfailedZtotaltZtotalfrÈr*rVr)Úthingr¾r+r+r,Ú summarizeÚsP     zDocTestRunner.summarizecCsV|j}xJ|j ¡D]<\}\}}||krB||\}}||}||}||f||<qWdS)N)rrý)rhr©Údr*rVr)r*r+r+r+r,Úmerges zDocTestRunner.merge)NNr")N)NNT)N)r5rmrnr–rrrrrrrr;r#rZrÜr-r8rArCrEr+r+r+r,rhs7 $ }   I 9c@s0eZdZdZdd„Zdd„Zdd„Zdd „Zd S) 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. cCst| dd¡dƒS)z= Convert string to hex-escaped ASCII string. ÚASCIIr2)r9r3)rhr\r+r+r,Ú_toAscii(szOutputChecker._toAsciicCsÌ| |¡}| |¡}||kr dS|t@sH||fdkr8dS||fdkrHdS|t@s‚t dt t¡d|¡}t dd|¡}||kr‚dS|t@r²d |  ¡¡}d |  ¡¡}||kr²dS|t @rÈt ||ƒrÈdSdS) 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*?$ršz(?m)^[^\S\n]+$rYF) rGrrrZr[ÚescapeÚBLANKLINE_MARKERrrŸrqrry)rhrtrurr+r+r,r.s0     zOutputChecker.check_outputcCs<|ttBtB@sdS|t@r dS| d¡dko:| d¡dkS)NFTrEr3)r r r r¾)rhrtrurr+r+r,Ú_do_a_fancy_diffms zOutputChecker._do_a_fancy_diffc Cs(|j}|t@st dt|¡}| |||¡rà|jdd}|jdd}|t@rptj ||dd}t |ƒdd…}d}nZ|t @ržtj ||dd}t |ƒdd…}d}n,|t @rÊtjtjd } t |  ||¡ƒ}d }nd |td  |¡ƒS|rü|rüd t|ƒt|ƒfS|rdt|ƒ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)^[ ]*(?= )T)r,r3)ÚnNz#unified diff with -expected +actualz-context diff with expected followed by actual)Zcharjunkzndiff with -expected +actualzDifferences (%s): ršzExpected: %sGot: %szExpected: %sGot nothing zExpected nothing Got: %szExpected nothing Got nothing )rtrrZr[rIrJr/r ÚdifflibZ unified_diffÚlistr Z context_diffr ZDifferZIS_CHARACTER_JUNKZcomparer^rŸ) rhrrurrtrÏZ got_linesZdiffZkindZenginer+r+r,r„s4    zOutputChecker.output_differenceN)r5rmrnr–rGrrJrr+r+r+r,r s ?c@s eZdZdZdd„Zdd„ZdS)rzÖA 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)rrru)rhrrrur+r+r,r½szDocTestFailure.__init__cCs t|jƒS)N)r9r)rhr+r+r,Ú__str__ÂszDocTestFailure.__str__N)r5rmrnr–rrNr+r+r+r,r²s c@s eZdZdZdd„Zdd„ZdS)rzæA 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)rrrc)rhrrrcr+r+r,rÐszUnexpectedException.__init__cCs t|jƒS)N)r9r)rhr+r+r,rNÕszUnexpectedException.__str__N)r5rmrnr–rrNr+r+r+r,rÅs c@s*eZdZdZd dd„Zdd„Zdd „ZdS) ra‹ 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 as f: ... failure = f >>> failure.test is test True >>> failure.example.want '42\n' >>> exc_info = failure.exc_info >>> raise exc_info[1] # Already has the traceback 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 as f: ... failure = f 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): ... doctest.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 {} NTcCs$t ||||d¡}|r |j ¡|S)NF)rrAr0r=)rhrr$rŽr@Úrr+r+r,rA3s zDebugRunner.runcCst|||ƒ‚dS)N)r)rhrŽrrrcr+r+r,r9sz'DebugRunner.report_unexpected_exceptioncCst|||ƒ‚dS)N)r)rhrŽrrrur+r+r,r<szDebugRunner.report_failure)NNT)r5rmrnr–rArrr+r+r+r,rØsY TFc Csº|dkrtj d¡}t |¡s,td|fƒ‚|dkr:|j}t|d} |rVt||d} n t ||d} x$| j ||||dD]} |   | ¡qvW|r”|   ¡t dkr¢| a n t  | ¡t| j| jƒS)a* 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. Nr™ztestmod: module required; %r)rç)rär)r0rñ)r=r>r.r6r7rAr5rrrrsrArCÚmasterrEr%rr) rÄr*r0räÚreportrrñÚraise_on_errorrçÚfinderÚrunnerrr+r+r,rHs$E     c CsÞ|r|stdƒ‚t|||| pdƒ\} }|dkr:tj |¡}|dkrHi}n| ¡}|dk rb| |¡d|krrd|d<| r„t||d} n t||d} |   | |||d¡}|   |¡|r¸|   ¡t dkrÆ| a n t   | ¡t| j| jƒS)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 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. Optional keyword arg "parser" specifies a DocTestParser (or subclass) that should be used to extract tests from the files. Optional keyword arg "encoding" specifies an encoding that should be used to convert the file to unicode. 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. z8Package may only be specified for module-relative paths.zutf-8Nr5r™)rärr")rœrWrržÚbasenamer¯rírrrÇrArCrPrEr%rr)rSrUr*rTr0rärQrrñrRrårMÚtextrTrr+r+r,r°s0R     ÚNoNamec CsDt|dd}t||d}x&|j|||dD]}|j||dq*WdS)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)räræ)rär)r0)r$N)rrrsrA) rVr0rär*r$rrSrTrr+r+r,r+s  cCs"|t@|krtd|ƒ‚t}|a|S)a?Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> 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 zOnly reporting flags allowed)r rœÚ_unittest_reportflags)r1Úoldr+r+r,rHs   c@sjeZdZddd„Zdd„Zdd„Zd d „Zd d „Zd d„Zdd„Z dd„Z dd„Z dd„Z e Z dd„ZdS)Ú DocTestCaser"NcCs.tj |¡||_||_||_||_||_dS)N)ÚunittestÚTestCaserÚ_dt_optionflagsÚ _dt_checkerÚ_dt_testÚ _dt_setUpÚ _dt_tearDown)rhrrÚsetUpÚtearDownrr+r+r,rns  zDocTestCase.__init__cCs|j}|jdk r| |¡dS)N)r_r`)rhrr+r+r,rbxs zDocTestCase.setUpcCs(|j}|jdk r| |¡|j ¡dS)N)r_rar0r=)rhrr+r+r,rc~s  zDocTestCase.tearDowncCs~|j}tj}tƒ}|j}|t@s(|tO}t||jdd}z d|_ |j ||j dd\}}Wd|t_X|rz|  |  | ¡¡¡‚dS)NF)rrräzF----------------------------------------------------------------------)rŽr@)r_r=r‡r#r]r rXrr^rrAr4ZfailureExceptionÚformat_failurerb)rhrrYÚnewrrTrrr+r+r,ÚrunTest†s zDocTestCase.runTestcCsP|j}|jdkrd}n d|j}d |j d¡dd…¡}d|j|j|||fS)Nzunknown line numberz%srroz:Failed doctest test for %s File "%s", line %s, in %s %s)r_r¤rŸr*rqrS)rhÚerrrr¤Zlnamer+r+r,rdžs  zDocTestCase.format_failurecCs6| ¡t|j|jdd}|j|jdd| ¡dS)aÒRun 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 as f: ... failure = f 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[1] # Already has the traceback 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 as f: ... failure = f 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' F)rrrä)r@N)rbrr]r^rAr_rc)rhrTr+r+r,r!ªs B zDocTestCase.debugcCs|jjS)N)r_r*)rhr+r+r,r²òszDocTestCase.idcCsPt|ƒt|ƒk rtS|j|jkoN|j|jkoN|j|jkoN|j|jkoN|j|jkS)N)r§r¨r_r]r`rar^)rhr©r+r+r,rªõs    zDocTestCase.__eq__cCst|j|j|j|jfƒS)N)r«r]r`rar^)rhr+r+r,r¬ÿszDocTestCase.__hash__cCs,|jj d¡}d|dd |dd…¡fS)Nrz%s (%s)ro)r_r*rqrŸ)rhr*r+r+r,r± szDocTestCase.__repr__cCs d|jjS)Nz Doctest: )r_r*)rhr+r+r,ÚshortDescription szDocTestCase.shortDescription)r"NNN)r5rmrnrrbrcrfrdr!r²rªr¬r±rNrhr+r+r+r,rZls  H rZc@s0eZdZdd„Zdd„Zdd„Zdd„ZeZd S) ÚSkipDocTestCasecCs||_t |d¡dS)N)rBrZr)rhrBr+r+r,r szSkipDocTestCase.__init__cCs| d¡dS)Nz-DocTestSuite will not work with -O2 and above)ZskipTest)rhr+r+r,rb szSkipDocTestCase.setUpcCsdS)Nr+)rhr+r+r,Ú test_skip szSkipDocTestCase.test_skipcCs d|jjS)NzSkipping tests from %s)rBr5)rhr+r+r,rh sz SkipDocTestCase.shortDescriptionN)r5rmrnrrbrjrhrNr+r+r+r,ri s ric@seZdZdd„ZdS)Ú _DocTestSuitecCsdS)Nr+)rhÚindexr+r+r,Ú_removeTestAtIndex sz _DocTestSuite._removeTestAtIndexN)r5rmrnrmr+r+r+r,rk srkc Ks¾|dkrtƒ}t|ƒ}|j|||d}|sNtjjdkrNtƒ}| t|ƒ¡|S|  ¡tƒ}x\|D]T}t |j ƒdkrvqb|j s¤|j }|dd…dkrž|dd…}||_ | t|f|Ž¡qbW|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. N)r0rñr3r"rz.pycro)rrCrsr=r1ÚoptimizerkÚaddTestrirïr)r­rSr˜rZ) rBr0rñZ test_finderr¥ròÚsuiterrSr+r+r,r# s(%  c@s(eZdZdd„Zdd„ZeZdd„ZdS)Ú DocFileCasecCsd |jj d¡¡S)Nr?r)rŸr_r*rq)rhr+r+r,r²e szDocFileCase.idcCs|jjS)N)r_rS)rhr+r+r,r±h szDocFileCase.__repr__cCsd|jj|jj|fS)Nz2Failed doctest test for %s File "%s", line 0 %s)r_r*rS)rhrgr+r+r,rdl szDocFileCase.format_failureN)r5rmrnr²r±rNrdr+r+r+r,rqc srqc Ksv|dkri}n| ¡}|r&|s&tdƒ‚t||||p4dƒ\}}d|krL||d<tj |¡}| ||||d¡} t| f|ŽS)Nz8Package may only be specified for module-relative paths.zutf-8r˜r")r¯rœrWrržrUrÇrq) ržrUrTr0rårMr¥Údocr*rr+r+r,Ú DocFileTestq s rscOsHtƒ}| dd¡r$t| d¡ƒ|d<x|D]}| t|f|Ž¡q*W|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. encoding An encoding that will be used to convert the files to unicode. rUTrT)rkr.rCrors)ÚpathsÚkwrpržr+r+r,r‹ s 8  cCsÚg}xˆtƒ |¡D]x}t|tƒrj| |jdd…¡|j}|rŠ| d¡|dd„| d¡dd…Dƒ7}q|dd„| d¡dd…Dƒ7}qWx|rª|ddkrª| ¡qWx|rÊ|d dkrÊ| d ¡q®Wd  |¡dS) awExtract script from text with examples. Converts text with examples to a Python script. Example input is converted to regular code. Example output and all other words are converted to comments: >>> 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 Nroz # Expected:cSsg|] }d|‘qS)z## r+)rµr¶r+r+r,r¸ sz(script_from_examples..rEcSsg|] }t|ƒ‘qSr+)r})rµr¶r+r+r,r¸ srzr") rrÅr8rr½r£rtrqÚpoprŸ)r\rÃZpiecertr+r+r,rÔ s:  " csJt|ƒ}tƒ |¡}‡fdd„|Dƒ}|s4tˆdƒ‚|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|]}|jˆkr|‘qSr+)r*)rµr))r*r+r,r¸/ sztestsource..znot found in testsr")rCrrsrœrr®)rBr*ròrÚtestsrcr+)r*r,r& s   cCst|ƒ}t|||ƒdS)z4Debug a single doctest docstring, in argument `src`'N)rÚ debug_script)ÚsrcÚpmr0rwr+r+r,r 6 scCs”ddl}|r| ¡}ni}|rvyt|||ƒWqtt ¡dƒ|jdd}| ¡| dt ¡d¡YqXn|jdd  d|||¡dS)z7Debug a test script. `src` is the script, as a string.r"Nr&T)rˆr3zexec(%r)) r‹r¯rrûr=rcrŒr7Z interactionrA)ryrzr0r‹Úpr+r+r,rx; s  rxcCs$t|ƒ}t||ƒ}t|||jƒdS)zåDebug 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)rCrrxrì)rBr*rzrwr+r+r,r!O s c@s(eZdZdZdd„Zdd„Zdd„ZdS) Ú _TestClasszå 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)z„val -> _TestClass object with associated value val. >>> t = _TestClass(123) >>> print(t.get()) 123 N)r)rhrr+r+r,rk sz_TestClass.__init__cCs|jd|_|S)zosquare() -> square TestClass's associated value >>> _TestClass(13).square().get() 169 r3)r)rhr+r+r,Úsquareu s z_TestClass.squarecCs|jS)z~get() -> return TestClass's associated value. >>> x = _TestClass(-42) >>> print(x.get()) -42 )r)rhr+r+r,r. sz_TestClass.getN)r5rmrnr–rr}r.r+r+r+r,r|] s   r|zÄ Example of a string object, searched as-is. >>> x = 1; y = 2 >>> x + y, x * y (3, 2) aÜ 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 zç Blank lines can be marked with : >>> print('foo\n\nbar\n') foo bar zú If the ellipsis flag is used, then '...' can be used to elide substrings in the desired output: >>> print(list(range(1000))) #doctest: +ELLIPSIS [0, 1, 2, ..., 999] aƒ If the whitespace normalization flag is used, then differences in whitespace are ignored. >>> print(list(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] )r|rÂzbool-int equivalencez blank linesZellipsiszwhitespace normalizationc Cs*ddl}|jdd}|jdddddd |jd d d t ¡gd d|jddddd|jdddd| ¡}|j}|j}d}x|jD]}|t|O}q„W|j r¦|t O}x~|D]v}|  d¡rt j  |¡\}}tj  d|¡t|dd…ƒ} tj d=t| ||d\} } nt|d||d\} } | r¬dSq¬WdS)Nr"zdoctest runner)Z descriptionz-vz --verboseÚ store_trueFz'print very verbose output for all tests)ÚactionÚdefaultÚhelpz-oz--optionr½zqspecify a doctest option flag to apply to the test run; may be specified more than once to apply multiple options)rÚchoicesr€rz-fz --fail-fastzystop running tests after first failure (this is a shorthand for -o FAIL_FAST, and is in addition to any other -o options))rrr_rÑz file containing the tests to run)Únargsrz.pyéýÿÿÿ)rär)rUrärr&)ÚargparseÚArgumentParserÚ add_argumentr'ÚkeysÚ parse_argsr_rärÓZ fail_fastrrgrržrqr=Úinsertr:rr) r…rår”Z testfilesrär¥rÓrSÚdirnamerÄrr?r+r+r,Ú_test¼ s>       rŒr™)r3)rX) NNNNTr"NFF)FrWNr")NNNN)FN)FN)F)Sr–Z __docformat__Ú__all__r-rLr6rêrr‹rZr=r`r[Úior#Ú collectionsr$r%r'rrrrrrrrr r r r rr rIrpr2rCrIrWr^rerfryr}r…rŒr†rNrrrrrrÚ ExceptionrrrrPrrrrXrr\rZriZ TestSuiterkrrqrsrrrr rxr!r|rúrŒr5Úexitr+r+r+r,Ú.s      1%.DKl<;n f x $! @ IR   ,  -