Qf PdZdZgdZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl mZmZddlmZeddZiZd Zed Zed Zed Zed ZedZedZeezezezezezZedZedZedZedZedZ eezezeze zZ!dZ"dZ#dZ$dWdZ%dZ&dZ'dXdZ(dZ)GddeZ*dZ+d Z,d!Z-Gd"d#ej\Z/d$Z0Gd%d&Z1Gd'd(Z2Gd)d*Z3Gd+d,Z4Gd-d.Z5Gd/d0Z6Gd1d2e7Z8Gd3d4e7Z9Gd5d6e5Z:da; dYd9Zda?d<Z@Gd=d>e jZBGd?d@eBZCGdAdBe jZEd[dCZFGdDdEeBZGd7dde3dfdFZHdGZIdHZJdIZKd\dJZLd\dKZMd]dLZNGdMdNZOeOdOdPdQdRdSdTZPdUZQeRdVk(re jeQyy)^aModule 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_optionflagDONT_ACCEPT_TRUE_FOR_1DONT_ACCEPT_BLANKLINENORMALIZE_WHITESPACEELLIPSISSKIPIGNORE_EXCEPTION_DETAILCOMPARISON_FLAGS REPORT_UDIFF REPORT_CDIFF REPORT_NDIFFREPORT_ONLY_FIRST_FAILUREREPORTING_FLAGS FAIL_FASTExampleDocTest DocTestParser DocTestFinder DocTestRunner OutputCheckerDocTestFailureUnexpectedException DebugRunnertestmodtestfilerun_docstring_examples DocTestSuite DocFileSuiteset_unittest_reportflagsscript_from_examples testsource debug_srcdebugN)StringIOIncrementalNewlineDecoder) namedtuple TestResultszfailed attemptedcNtj|dttzS)N)OPTIONFLAGS_BY_NAME setdefaultlen)names ./opt/alt/python312/lib64/python3.12/doctest.pyrrs  ) )$S9L5M0M NNrrrrrrr r r r rz z...cd}tjD]6}|j|d}|tt|us(||jz}8|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)globsflagsfnamefeatures r._extract_future_flagsr:sO E--))E4( gj%0 0 W** *E. Lr/ctj|r|St|trt |t t dgS|( tjtj|Std#t$r6tjtj|jdcYSwxYw#t$rYywxYw)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_getframemodulenameAttributeError _getframe f_globalsKeyError TypeError)moduledepths r._normalize_modulerOs FC &')VXu==   O{{3#:#:5#ABB <== " O{{3==#7#A#A*#MNN O   s* %A<<:B;;B>> C  C c:tddj|dSNT)r%decode)datas r._newline_convertrTs $T4 0 7 7d CCr/c|ryt|d}t||}t|ddx} |jj}t |dr/|j|}|j|}t||fSt||5}|j|fcdddS#t $rYowxYw#1swYyxYw)N __loader__get_data)encoding) rO_module_relative_pathr4__spec__loaderrHhasattrrXrRrTopenread)filenamepackagemodule_relativerYr\ file_contentsfs r._load_testfileres#GQ/((;g|T: :F C  ))00 6: &"OOH5M)00:M$M2H< < h *avvx!"""   + *sB% B4% B10B14B=c6tjd|dz|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)^(?!$) )resub)sindents r._indentrls 66,s A ..r/ctt}|\}}}tj|||||jS)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_infoexcoutexc_typeexc_valexc_tbs r._exception_tracebackrws8 ZF (Hgv hfE ?? r/ceZdZdZddZy) _SpoofOutc`tj|}|r|jds|dz }|SN )r$rqendswith)selfresults r.rqz_SpoofOut.getvalues0""4( &//$/ dNF r/NcP|j|tj|yN)seekr$truncate)r~sizes r.rz_SpoofOut.truncates $$r/r)r= __module__ __qualname__rqrr/r.ryrys  r/ryct|vr||k(S|jt}t|dk\sJdt|}}|d}|r!|j|rt|}|d=ny|d}|r$|j |r|t|z}|d=ny||kDry|D]*}|j |||}|dkry|t|z },y)z_ Essentially the only subtle case: >>> _ellipsis_match('aa...aa', 'aaa') False r#FT)ELLIPSIS_MARKERsplitr, startswithr}find)wantgotwsstartposendposws r._ellipsis_matchrs d"s{ O $B r7a<<#c(fH 1A >>! 1vH1 2A <<? c!f F2& 88Ax0 a<CF r/c2|j}|rd|zSy)z)Return a commented form of the given linez# #)rstrip)lines r. _comment_linerFs ;;=D Dyr/cdt|}}|jd}|dk\r|}|jdd|}|dk\r|}|jdd|}|dk\r|dz}|||S)Nr#r|:.r))r,rrfind)msgstartendis r._strip_exception_detailsrNsvCH3E AAv aAAv #q#AAv! uc?r/c*eZdZdZdZddZdZdZy)_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. cr||_d|_tjj ||dd|_y)NFT)stdoutnosigintr))_OutputRedirectingPdb__out$_OutputRedirectingPdb__debugger_usedpdbPdb__init__ use_rawinput)r~outs r.rz_OutputRedirectingPdb.__init__ns2 $ cD9r/Ncd|_|tjj}tj j ||yrQ)rrErIf_backrr set_trace)r~frames r.rz_OutputRedirectingPdb.set_tracevs4# =MMO**E $&r/c\|jr tjj|yyr)rrr set_continuer~s r.rz"_OutputRedirectingPdb.set_continue|s$    GG  & r/ctj}|jt_ tjj |g||t_S#|t_wxYwr)rErrrrtrace_dispatch)r~args save_stdouts r.rz$_OutputRedirectingPdb.trace_dispatchsAjj ZZ  %77))$66$CJCJs A Ar)r=rr__doc__rrrrrr/r.rrhs ' ' %r/rctj|std|z|jdr t dt j j|jd}t|dr-t j j|jd}n|jdk(rwttjdkDrJtjddk7r4t j jtjdd}nt j}nxt|drT|j D]E}t j j||}t j j#|sC|cSt d |jzt j j||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__))r>r?rLr ValueErrorospathjoinrr]rr=r,rEargvcurdirrexists)rM test_pathbasedir directoryfullpaths r.rZrZsI   F #/&899C LMM ys35Ivz"''--03 J & sxx=?sxx{b0ggmmCHHQK03GiiG 6: &#__ 77<< 9=77>>(+#O- 3!??+, , 77<< ++r/c(eZdZdZ ddZdZdZy)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. Nc|jds|dz }|r|jds|dz }||jds|dz }||_||_||_||_|i}||_||_yr{)r}sourcerlinenorkoptionsexc_msg)r~rrrrrkrs r.rzExample.__init__st$ dNF  d+ DLD  w'7'7'= tOG    ?bG  r/czt|t|urtS|j|jk(xr|j|jk(xrj|j|jk(xrO|j |j k(xr4|j |j k(xr|j|jk(Sr)typeNotImplementedrrrrkrrr~others r.__eq__zExample.__eq__s :T%[ (! !{{ell*-yyEJJ&-{{ell*-{{ell*-||u}}, - ||u}},  -r/ct|j|j|j|j|j fSr)hashrrrrkrrs r.__hash__zExample.__hash__s3T[[$))T[[$++\\#$ $r/)Nr#r#N)r=rrrrrrrr/r.rrs!!DEF$ -$r/rc.eZdZdZdZdZdZdZdZy)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. ct|trJd||_||_|j |_||_||_||_y)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) r@rAexamples docstringcopyr6r-r`r)r~rr6r-r`rrs r.rzDocTest.__init__sP h, JI J,  "ZZ\     r/c &t|jdk(rd}n3t|jdk(rd}ndt|jz}d|jjd|jd|j d |j d |d S) Nr#z no examplesr)z 1 examplez %d examples)r,r __class__r=r-r`r)r~rs r.__repr__zDocTest.__repr__%sp t}}  "$H  1 $"H$s4=='99H((DMM4;;B Cr/czt|t|urtS|j|jk(xr|j|jk(xrj|j|jk(xrO|j |j k(xr4|j |j k(xr|j|jk(Sr)rrrrr6r-r`rrs r.rzDocTest.__eq__0s :T%[ (! !}}.+~~0+zzU[[(+yyEJJ&+}}. + {{ell*  +r/cpt|j|j|j|jfSr)rrr-r`rrs r.rzDocTest.__hash__;s&T^^TYY t{{KLLr/c$t|tstS|j |jnd}|j |jnd}|j|j |t |f|j|j |t |fkS)Nr)r@rrrr-r`id)r~rself_lno other_lnos r.__lt__zDocTest.__lt__?sv%)! !"&++"94;;r$)LL$U^^Y5 BC Dr/N) r=rrrrrrrrrr/r.rrs#.  C +MDr/rceZdZdZej dej ejzZej dejej zejzZ ej djZ ddZ dZddZdZej d ej Zd Zej d ej Zd Zd ZdZy)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 |j}|j|}|dkDr1dj|jdDcgc]}||d c}}g}d\}}|jj |D]}|j |||j||jd||jz }|j|||\} } } } |j| s;|j t| | | ||t|jdz| ||jd|j|jz }|j}|j ||d|Scc}w)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#r|Nr#r#rk)rrkr) expandtabs _min_indentrr _EXAMPLE_REfinditerappendrcount_parse_example_IS_BLANK_OR_COMMENTrr,groupr) r~stringr- min_indentloutputcharnormrrrrs r.parsezDocTestParser.parse|sk""$%%f- >YY T8JK8J1*+8JKLF!!**62A MM& 2 3 fll4; ;F((D&9 -VWdG,,V4 wvtW+1+5c!''(:K6L+L,3 57 fll4AEEG<  ::fd3+3aa)3+ ++s1c t|jd}|jdjd}|j|||||j |ddd|zdz||dj |Dcgc] }||dzd c}}|jd }|jd} t| dkDrt jd | d r| d =|j | d|z||t|zdj | D cgc]} | |d c} }|jj|}|r|jd } nd} |j|||} || || fScc}wcc} w) 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. rkrr|r)Nrgrrz *$rr) r,rr_check_prompt_blank _check_prefixrrhmatch _EXCEPTION_RE _find_options) r~rr-rrk source_linesslrr want_lineswlrrs r.rzDocTestParser._parse_exampleswQWWX&'wwx(..t4    vtVD <+SZ#-=tVLLALbBvaxyMLAB wwvZZ% z?Q 288FJrN#C2 :s6z4!C $55 7yy ; ""VW+ ;<    $ $T * ggenGG$$VT6:wg--/B??+6!":6!'c!1 )< t008$dF45 5r/z ^([ ]*)(?=\S)c|jj|Dcgc] }t|}}t|dkDr t|Sycc}w)z;Return the minimum indentation of any non-blank line in `s`r#) _INDENT_REfindallr,min)r~rjrkindentss r.rzDocTestParser._min_indentsJ-1__-D-DQ-GH-G63v;-GH w "((1*d"&vfQh"7"?@@(r/c t|D]3\}}|s |j|rtd||zdzd|d|y)z Check that every line in the given list starts with the given prefix; if any line does not, then raise a ValueError. rr)rz& has inconsistent leading whitespace: N)r rr)r~r!prefixr-rrrs r.rzDocTestParser._check_prefix'sF !'GAtDOOF3 "((1*dD":;;(r/N)z)r=rrrrhcompile MULTILINEVERBOSErDOTALLr r rrrrrrr rrrrrr/r.rrLs"**  \\BJJ & (K,BJJ ZZ",, & 2 4M&2::o6<<%N 7 +*.f&2::&D&(ll48,bll;J @ ;r/rcPeZdZdZdeddfdZd dZdZdZd Z d Z d Z y) 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. FTc<||_||_||_||_y)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)r~verboseparserrecurse exclude_emptys r.rzDocTestFinder.__init__@s!"   +r/Nc |&t|dd}|tdt||durd}n|tj|} tj |}|s%tj |}|d|ddzdk(sd}|d}n=|!tj||j}ntj|}|sd} | |i}n+|jj}n|j}||j|d|vrd|d<g}|j||||||i|j|S#t$rd}YwxYw) aj Return a list of the DocTests that are defined by the given object's docstring, or by any of its contained objects' docstrings. The optional parameter `module` is the module that contains the given object. If the module is not specified or is None, then the test finder will attempt to automatically determine the correct module. The object's module is used: - As a default namespace, if `globs` is not specified. - To prevent the DocTestFinder from extracting DocTests from objects that are imported from other modules. - To find the name of the file containing the object. - To help find the line number of the object within its file. Contained objects whose module does not match `module` are ignored. If `module` is False, no attempt to find the module will be made. This is obscure, of use mostly in tests: if `module` is False, or is None but cannot be found automatically, then all objects are considered to belong to the (non-existent) module, so all contained objects will (recursively) be searched for doctests. The globals for each DocTest is formed by combining `globs` and `extraglobs` (bindings in `extraglobs` override bindings in `globs`). A new copy of the globals dictionary is created for each DocTest. If `globs` is not specified, then it defaults to the module's `__dict__`, if specified, or {} otherwise. If `extraglobs` is not specified, then it defaults to {}. Nr=zHDocTestFinder.find: name must be given when obj.__name__ doesn't exist: Fr#z<]>r)r4rrr> getmodule getsourcefilegetfile linecachegetlines__dict__rLrupdate_findsort) r~objr-rMr6 extraglobsrnr testss r.rzDocTestFinder.findVsxH <3 D1D| "&s)".// U?F ^&&s+F  (((-Ds+AwtBCy(E1$4|# %$-#5#5dFOO#LL$-#5#5d#;L##'L =~,,.JJLE  ! LL $ U " *E*  5#tV\5"E   Y L sD?? E  E c|ytj||tj|uStj|r|j|juStj |stj |rLt|dr|jj}nt|dr |j}ny|j|k(Stj|r|j|jk(St|dr|j|jk(St|trytd)zY Return true if the given object is defined in the given module. T __objclass__rz"object must be a class or function)r>r4 isfunctionr9 __globals__ismethoddescriptorismethodwrapperr]rArr=isclassr@propertyr)r~rMobjectobj_mods r. _from_modulezDocTestFinder._from_modules  >   v & 2W..v66 6    '??f&8&88 8((0%%f-v~. --88. ++??g- - __V $??f&7&77 7 V\ *??f&7&77 7  )AB Br/cz|} tj|}tj|S#t$rY wxYw)zL Safely unwrap objects and determine if they are functions. )r>unwrapr isroutine)r~r= maybe_routines r. _is_routinezDocTestFinder._is_routinesC  #NN=9M  //   s . ::c z|jrtd|zt||vryd|t|<|j|||||}||j |t j |r|jrz|jjD]]\} } |d| } |j| st j| s4|j|| sG|j|| | ||||_t j |r|jrt|dijD]\} } t| t st#dt%| t j&| sQt j| sr?r,r9itemsrOrFrJr;r4r@rArrrM staticmethod classmethod__func__rG) r~r?r=r-rMr r6seentestvalnamevals r.r;zDocTestFinder._findsX == '$. / c7d? RW ~~c4 E   LL    C T]] # 2 2 4 %)73%%c*gooc.B%%fc2JJuc7FL$d, !5   C T]] 'Z < B B D !'3/$&*7m&677 ))#.'//#2F((-C1E$'+3i&233/3G< 5#w  $(!E ??3 DMM # 2 2 4 cL+#>?,,C&&s+ws/C h/''4)-w7GJJuc7FL$d,!5%2 r/ct|tr|}n7 |jd}n'|j}t|ts t|}|j ||}|j r|sy|d}n(t|ddxs |j}|dddk(r|dd}|jj|||||S#ttf$rd}YwxYw)zs Return a DocTest for the given object, if it defines a docstring; otherwise, return None. Nrr.pycr) r@rArrLrH _find_linenor-r4r=r*r) r~r=r-rMr6r rrr`s r.rSzDocTestFinder._get_test!s c3 I ;;& "I # I%i5$' N ""3 5   y >Hvz48KFOOH}&#CR=||'' 5$(0&: :%~.   s6B88C  C c d}t|dd}tj|r|d}tj|rc|a|yt j dt j t|ddz}t|D]\}}|j|s|}ntj|r |j}t|tr |j}tj|r/t|ddr"tj|} |j }tj$|r |j&}tj(|r |j*}tj,|r|j.dz }|N||dzSt j d}t1|t3|D]}|j||s|cSy#t"$rYywxYw) z Return a line number of the given object's docstring. Returns `None` if the given object does not have a docstring. Nrr#z^\s*class\s*%s\br=-r)z(^|.*:)\s*\w*("|\'))r4r>r?rFrhr$escaper r ismethodrWr@rGfgetrBrL__code__rH istracebacktb_frameisframef_codeiscodeco_firstlinenoranger,)r~r=r rrpatrrs r.r_zDocTestFinder._find_linenoGs CD1    C Y%:F ??3 I$9#**0YYwsJ'DEFGC$\2499T?F3   C  # c8 $((C   c "wsIt'D..%C ll   s #3<># ''!+F  #ax**34CL(9:99\&12!M; 1"   s G G%$G%NNNN) r=rrrrrrrJrOr;rSr_rr/r.rr7s= %]_T,,dLC: 0;,z$:L;r/rceZdZdZdZddZdZdZdZdZ d Z d Z d Z e jd Zdd ZddZddZdZy)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**********************************************************************Nc|xs t|_|dtjv}||_||_||_d|_d|_i|_ t|_ y)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. N-vr#) r_checkerrErr+ optionflagsoriginal_optionflagstriesfailures_name2ftry_fakeout)r~checkerr.rss r.rzDocTestRunner.__init__s^" 2=? ?chh&G &$/!   "  r/c|jrf|jr8|dt|jzdzt|jzy|dt|jzdzyy)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+rrlr)r~rrYexamples r. report_startzDocTestRunner.report_startsj ==||K''.."99"#%,W\\%:;<K''.."99)*+ r/c.|jr |dyy)zt Report that the given example ran successfully. (Only displays a message if verbose=True) zok N)r+r~rrYr{rs r.report_successzDocTestRunner.report_successs == K r/c||j|||jj|||jzy)z7 Report that the given example failed. N)_failure_headerrroutput_differencersr~s r.report_failurezDocTestRunner.report_failures> D w / MM + +GS$:J:J K L Mr/cd||j||dztt|zy)zO Report that the given example raised an unexpected exception. zException raised: N)rrlrwr~rrYr{rrs r.report_unexpected_exceptionz)DocTestRunner.report_unexpected_exceptions8 D w / ! "$+,@,J$K L Mr/c|jg}|jrf|j)|j|j|jzdz}nd}|jd|jd|d|jn.|jd|jdzd|j|jd|j }|jt |dj|S) Nr)?zFile "", line , in zLine zFailed example:r|)DIVIDERr`rrr-rrlr)r~rYr{rrrs r.rzDocTestRunner._failure_header s||n =={{&7>>+Ew~~59 JJ vtyy: ; JJ7>>!+;TYYG H $% 76?#yy~r/c \dx}}|j}td\}}} |jj} t |j D]\} } |jt zxr|dkD} ||_| jrP| jjD]3\}}|r|xj|zc_|xj|zc_5|jtzr|dz }| s|j||| d|j| fz} tt| j|d|d|j|j j#d}|j*j-}|j*j/d|}|#| | j0||jr|}nt3j4|dd}t7|dt8rV|dj:d |dj<d |dj:d ft?fd t |D}||d}d jA|}| s|tC|z }| jD| }nf| | jD||jr|}nE|jtFzr2| tI| jDtI||jr|}||ur| s^|jK||| |nI||ur| s|jM||| ||dz }n)|| ur| s|jO||| ||dz }n Jd |f|s|jtPzsn||_|jS|||tU||S#t$$rt'j(}|j j#YRxYw)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#rVr)zsingleTNrrrc3JK|]\}}|jr|ywr)r).0indexrexception_line_prefixess r. z&DocTestRunner.__run..xs*)+BKE4??+BC+Bs #rzunknown outcome)+rsrlrr check_outputr rr rrTrr|r-execr$rr6debuggerrKeyboardInterruptrErrrxrqrrroformat_exception_only issubclass SyntaxErrorrrnextrrwrrrrrrr_DocTestRunner__record_outcomer')r~rY compileflagsrrvrurtSUCCESSFAILUREBOOMcheck examplenumr{quiet optionflagr[r` exceptionroutcome formatted_ex exc_msg_indexrrs @r.__runzDocTestRunner.__runs5 $//!&q$ **$-T]]#; J%%(AA"\  4D )0)>)>)@%Z((J6(((ZK7( *A$& QJE!!#tW5 *TYY ,CCH -WW^^Xx)4126**> **, --((*C MM " "1 %G sD,<,<=%G )>> "1 N ilK8 %Q<445Q7$Q<2231Yq\5N5N4OqQ/+%))+4\+B)%M $0 #?L'',// ::C??*"G7??GT5E5EF%G%%(??5gooF5g>!--/#*'!''T7C@G#''T7C@A D44S$5>@A :0'::uD,,y8_$.+)\[(?P\d+)\]>$cJ|jj|}|ru|jd|jjk(rM|jj t |jd}|jjdS|j||S)Nr-rTkeepends) %_DocTestRunner__LINECACHE_FILENAME_REr rrYr-rintr splitlinessave_linecache_getlines)r~r`module_globalsrr{s r.__patched_linecache_getlinesz*DocTestRunner.__patched_linecache_getliness  ( ( . .x 8 DIINN2ii((QWW\-B)CDG>>,,d,; ;//.I Ir/cv ||_|t|j}tj |4 j  j dk(r j}n fd}|jt_tj}tj}t |_ |jj|jjt_ tj |_|j$t_tj&}tj(t_ |j+||| t_|t_ tj,||j"t_|t_|r&|jj/ddl}d|_SS# t_|t_ tj,||j"t_|t_|r&|jj/ddl}d|_wwxYw)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. Nutf-8c`t|jd}j|y)Nbackslashreplace)rAencodewrite)rjrYrs r.rzDocTestRunner.run..outs)AHHX/ABHMA%%a(r/r#)rYr:r6rErrYlowerrrxgettracerrrrresetr7r8r*_DocTestRunner__patched_linecache_getlines displayhook__displayhook___DocTestRunner__runsettraceclearbuiltins_) r~rYrr clear_globs save_tracesave_set_tracesave_displayhookrrYrs @@r.runzDocTestRunner.runs(  0>#3w#>!'')]] \\^ -k:   // (1'9'9$!>> ??-- "::dL#6$CJ*CM LL $!%!=!=I .CO   "!  %CJ*CM LL $!%!=!=I .CO   "! s =GA5H8c| |j}g}g}g}dx}}|jjD]\}|\}\} } | | ksJ|| z }|| z }| dk(r|j|3| dk(r|j|| fL|j|^|r{|r8t t |d|j |D]} t d| |r?t t |d|j |D]\} } t d| | fz|rXt |jt t |d|j |D]\} \} } t d| | | fz|r2t |dt |jd t ||z d |d |rt d |d n |r t dt||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. r#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+rwrTrrRr,r<rr') r~r.notestspassedfailedtotalttotalfrr-rdrthingrs r. summarizezDocTestRunner.summarize s ?mmG$$&ALD&1a6M6 aKF aKFAvt$a ay* a ' c'l$9: $E%'%c&k#<= $*LE5,u~=>%+  $,,  #f+4 5 KKM!' v1)Q5M9:"(  &*c$--&8( C &6/< C  %v{ ;  . !66**r/c|j}|jjD]%\}\}}||vr||\}}||z}||z}||f||<'yr)rwrT)r~rdr-rdrrrs r.mergezDocTestRunner.mergeDs_ MM!NN002LD&1aqy 4BFFdAdG3r/)NNr#rNNT)r=rrrrrr|rrrrrrrhr$rrrrrrr/r.rrsn6rG$H +MM(L,\)bjj*FGJD"R4+r r/rc(eZdZdZdZdZdZdZy)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. c:t|jdddS)z= Convert string to hex-escaped ASCII string. ASCIIr)rAr)r~rjs r._toAsciizOutputChecker._toAsciiYs188G%78'BBr/c|j|}|j|}||k(ry|tzs||fdk(ry||fdk(ry|tzsNtjdtj t zd|}tjdd|}||k(ry|tzrDdj|j}dj|j}||k(ry|tzr t||ryy) 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\n]+$rgF) rrrrhrirbBLANKLINE_MARKERrrrrrr~rrrss r.rzOutputChecker.check_output_s mmC }}T" $;44Dz..Dz//3366/BII6F,GGd$D&&*B4Cd{ - -((399;'C88DJJL)Dd{  !tS)r/c|ttztzzsy|tzry|jddkDxr|jddkDS)NFTr|r)r r r rrs r._do_a_fancy_diffzOutputChecker._do_a_fancy_diffsVl*+*+,  %zz$!#; $!(;;r/c|j}|tzstjdt|}|j |||r|j d}|j d}|tzr)tj||d}t|dd}d}n|tzr)tj||d}t|dd}d}nR|tzrBtjtj } t| j!||}d }nJd d |zt#d j%|zS|r|rdt#|dt#|S|rdt#|zS|rdt#|zSy)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)^[ ]*(?= )Trr)nNz#unified diff with -expected +actualz-context diff with expected followed by actual)charjunkzndiff with -expected +actualzBad diff optionzDifferences (%s): rz Expected: zGot: zExpected: %sGot nothing zExpected nothing Got: %szExpected nothing Got nothing )rrrhrirrrr difflib unified_difflistr context_diffr DifferIS_CHARACTER_JUNKcomparerlr) r~r{rrsrr got_linesdiffkindengines r.rzOutputChecker.output_differences_||33&&*, >4r/N)r=rrrrrrrrr/r.rrQsC <~<.,5r/rceZdZdZdZdZy)rzA 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 c.||_||_||_yr)rYr{r)r~rYr{rs r.rzDocTestFailure.__init__s  r/c,t|jSrrArYrs r.__str__zDocTestFailure.__str__499~r/Nr=rrrrrrr/r.rrs  r/rceZdZdZdZdZy)rzA 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 c.||_||_||_yr)rYr{rr)r~rYr{rrs r.rzUnexpectedException.__init__s    r/c,t|jSrrrs r.rzUnexpectedException.__str__rr/Nrrr/r.rrs ! r/rc$eZdZdZddZdZdZy)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 {} Ncptj||||d}|r|jj|S)NF)rrr6r)r~rYrrrrs r.rzDebugRunner.runds2   dD,U C  JJ   r/ct|||r)rrs r.rz'DebugRunner.report_unexpected_exceptionjs!$::r/ct|||r)rr~s r.rzDebugRunner.report_failuremsT7C00r/r)r=rrrrrrrr/r.rr sX t ;1r/rTFc |tjjd}tj|st d|| |j }t|} |rt||} n t||} | j||||D]} | j| |r| jt| a ntj| 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. rztestmod: module required; )r1r.rsr6r>)rErFr3r>r?rLr=rrrrrrmasterrr'rvru) rr-r6r.reportrsr>raise_on_errorr1finderrunnerrYs r.rrysJ y KKOOJ '   A !=>> |zz 7FW+FwKH At5Z H 4I ~ V v 55r/c |r |s tdt|||| xsd\} }|tjj |}|i}n|j }||j |d|vrd|d<| rt||} n t||} | j| |||d}| j||r| jt| a ntj| 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. 8Package may only be specified for module-relative paths.rr=rrr#)rrerrbasenamerr:rrrrrrrr'rvru)r`rbr-rar6r.rrsr>rr/rYtextrrYs r.rrs d+, ,$Hg$,$79ND( |ww) }  Z &jW+FwKH   dE41 =D JJt  ~ V v 55r/ct|d}t||}|j|||D]}|j||y)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.r0r)r6)rN)rrrr) rdr6r.r-rrsrrrYs r.rr\sE$7E :F 7 DF At5 1 4l 32r/cF|tz|k7r td|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)rr_unittest_reportflags)r7olds r.rrys/: E)7?? C! Jr/cleZdZ d dZdZdZdZdZdZdZ d Z d Z d Z e jZd Zy) DocTestCaseNctjj|||_||_||_||_||_yr)unittestTestCaser_dt_optionflags _dt_checker_dt_test _dt_setUp _dt_tearDown)r~rYrssetUptearDownrys r.rzDocTestCase.__init__s> ""4(*" $r/c|j}|jj|_|j|j |yyr)rr6r _dt_globsrr~rYs r.rzDocTestCase.setUps8}}* >> % NN4  &r/c|j}|j|j||jj|jj |j yr)rrr6rr:rrs r.rzDocTestCase.tearDownsM}}    (   d #  $..)r/c|j}tj}t}|j}|t zs |t z}t||jd} d|_ |j||jd\}}|t_|r.|j|j|jy#|t_wxYw)NFrsryr.zF----------------------------------------------------------------------)rr)rrErr$rrr rrrrrfailureExceptionformat_failurerq)r~rYrnewrsrrvrus r.runTestzDocTestCase.runTests}}jjj** o- 0 0K;'+'7'7H #FN$jj#)))8OHeCJ ''(;(;CLLN(KL L CJs (C Cc |j}|jd}nd|jz}dj|jj ddd}d|jd|j d|d|d | S) Nzunknown line numberz%srrFailed doctest test for File "rrz )rrrr-rr`)r~errrYrlnames r.r"zDocTestCase.format_failuresj}} ;; *FDKK'F-bc2399dmmVUCA r/c|jt|j|jd}|j |j d|j y)aRun 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' Fr )rN)rrrrrrr)r~rs r.r"zDocTestCase.debugsID )=)=%)%5%5uF 4==e 4 r/c.|jjSrrr-rs r.rzDocTestCase.id& s}}!!!r/cDt|t|urtS|j|jk(xrj|j|jk(xrO|j|jk(xr4|j |j k(xr|j |j k(Sr)rrrrrrrrs r.rzDocTestCase.__eq__) s :T%[ (! !}}.5##u'<'<<5~~05  E$6$6655#4#44  5r/cpt|j|j|j|jfSr)rrrrrrs r.rzDocTestCase.__hash__3 s3T))4>>4;L;L%%'( (r/c|jjjd}|dddj|dddS)Nrrr))rr-rr)r~r-s r.rzDocTestCase.__repr__7 s:}}!!'', HchhtCRy&9::r/c4d|jjzS)Nz Doctest: r,rs r.shortDescriptionzDocTestCase.shortDescription= sT]]////r/)r#NNN)r=rrrrrr$r"r"rrrrrHrr2rr/r.rrsMAE%!*M0 FP"5(;nnG0r/rc(eZdZdZdZdZdZeZy)SkipDocTestCasec>||_tj|dyr)rMrr)r~rMs r.rzSkipDocTestCase.__init__A s T4(r/c&|jdy)Nz-DocTestSuite will not work with -O2 and above)skipTestrs r.rzSkipDocTestCase.setUpE s EFr/cyrrrs r. test_skipzSkipDocTestCase.test_skipH  r/c4d|jjzS)NzSkipping tests from %s)rMr=rs r.r2z SkipDocTestCase.shortDescriptionK s'$++*>*>>>r/N)r=rrrrr9r2rrr/r.r4r4@ s)G ?Gr/r4ceZdZdZy) _DocTestSuitecyrr)r~rs r._removeTestAtIndexz _DocTestSuite._removeTestAtIndexS r:r/N)r=rrr?rr/r.r=r=Q s r/r=c | t}t|}|j|||}|sCtjj dk\r&t }|jt||S|jt }|D]b}t|jdk(r|js |j}|dddk(r|dd}||_ |jt|fi|d|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. Nrrr#r]r^r)rrOrrEr7optimizer=addTestr4r<r,rr`rr) rMr6r> test_finderrr?suiterYr`s r.rrW sJ#o v &F   V5Z  HE SYY''!+ of-.  JJL OE t}}  " }}H}&#CR=$DM k$2'23 Lr/ceZdZdZdZdZy) DocFileCasecjdj|jjjdS)Nrr)rrr-rrs r.rzDocFileCase.id s&xx **00566r/c.|jjSr)rr`rs r.rzDocFileCase.__repr__ s}}%%%r/chd|jjd|jjd|S)Nr&r'z ", line 0 )rr-r`)r~r(s r.r"zDocFileCase.format_failure s(==%%t}}'='=sD r/N)r=rrrrr"rr/r.rFrF s7&r/rFc |i}n|j}|r |s tdt||||xsd\}}d|vr||d<tjj |}|j ||||d} t| fi|S)Nrrrr#)rrrerrr rrF) rrbrar6r/rYrdocr-rYs r. DocFileTestrL s } +, ,tWo'274IC j 77  D !D   c5$a 8D t 'w ''r/ct}|jddrt|jd|d<|D]}|jt |fi||S)aA 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. rbTra)r=r3rOrBrL)pathskwrDrs r.rr s[p OE  vv&)"&&*;<9  k$-"-. Lr/c^g}tj|D]}t|trg|j |j dd|j }|s@|j d||jdddDcgc]}d|z c}z }z||jdddDcgc] }t|c}z }|r#|ddk(r|j|r |ddk(r|r$|ddk(r|jd|r |ddk(rdj|dzScc}wcc}w)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 Nrz # Expected:r|z## rr#) rrr@rrrrrrpopr)rjrpiecerrs r.rr s8tF&&q) eW % MM%,,s+ ,::D m,DJJt,>2G N 0s A.A.c4t|}t|||y)z4Debug a single doctest docstring, in argument `src`'N)r debug_script)srcpmr6rTs r.r!r!i s"3'G"e$r/cddl}|r|j}ni}|r t|||y|j djd|z||y#tt j d|j d}|j|jdt j dYyxYw)z7Debug a test script. `src` is the script, as a string.r#Nr)T)rrzexec(%r)) rrrrRrErrrr interactionr)rWrXr6rps r.rVrVn s    3 eU # "":#3UEB  3 #,,.# $&A GGI MM$ q 1 2s AA,Cc`t|}t||}t|||jy)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)rOr rVr9)rMr-rXrTs r.r"r" s*v &F&G"foo.r/c"eZdZdZdZdZdZy) _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' c||_y)zval -> _TestClass object with associated value val. >>> t = _TestClass(123) >>> print(t.get()) 123 Nr[)r~r[s r.rz_TestClass.__init__ s r/c.|jdz|_|S)zosquare() -> square TestClass's associated value >>> _TestClass(13).square().get() 169 rr`rs r.squarez_TestClass.square s88q= r/c|jS)z~get() -> return TestClass's associated value. >>> x = _TestClass(-42) >>> print(x.get()) -42 r`rs r.r3z_TestClass.get s xxr/N)r=rrrrrbr3rr/r.r^r^ s r/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^rzbool-int equivalencez blank linesellipsiszwhitespace normalizationcddl}|jd}|jddddd |jd d d tj gd |jdddd|jddd|j }|j }|j}d}|jD]}|t|z}|jr |tz}|D]}|jdrstjj|\}}tjj!d|t#|dd} tjd=t%| ||\} } nt'|d||\} } | syy)Nr#zdoctest runner) descriptionrqz --verbose store_trueFz'print very verbose output for all tests)actiondefaulthelpz-oz--optionrzqspecify a doctest option flag to apply to the test run; may be specified more than once to apply multiple options)rhchoicesrirjz-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))rhrjrnrz file containing the tests to run)nargsrjz.pyr)rbr.rsr))argparseArgumentParser add_argumentr*keys parse_argsrnr.r fail_fastrr}rrrrEinsertrBrr) rnr/r testfilesr.rrr`dirnamerrvrs r._testrw s  $ $1A $ BF k,FH j 3 8 8 :BEG  mLFH c?A    D IllGG++&v.. ~~9   U #!# h 7 GX HHOOAw '8CR=)A !!W'JKHa"8U-4'KKHa  r/r)r)r) NNNNTr#NFF)FNoNameNr#rn)FN)F)Tr __docformat____all__r1rr>r7rrrhrErorior$r% collectionsr&r'r*rrrrrrrr r r r r rrrrr:rOrTrerlrwryrrrrrrZrrrrrr Exceptionrrrrrrrr rrrr4 TestSuiter=rrFrLrrr r!rVr"r^rQrwr=exitrr/r.rs7%N& + Z 2"(:; .O--EF+,CD*+AB z *6"-.GH*)*()  , ,#>2 ">2 ">2 /0KL  ,   -- !& >2D"$/     /b4"%CGG"%J ,\B$B$HGDGDZd;d;VKKb GGRP5P5dY&)&e1-e1\ 373705f6P(,$dU=?y6v:B:;46!Ha0(##a0Fk" H&& >@ + '+D=?(4CRP$d % C( /**X%%( )Q0 f* Z z CHHUWr/