e SrSr/SQrSSKrSSKrSSKrSSKrSSKrSSKrSSK r SSK r SSK r SSK r SSK JrJr SSKJr SSKrSSKJrJr "SS \"S S 55r0rS r\"S 5r\"S 5r\"S5r\"S5r\"S5r\"S5r\\-\-\-\-\-r\"S5r\"S5r \"S5r!\"S5r"\"S5r#\\ -\!-\"-\#-r$Sr%Sr&Sr'S\Sjr(Sr)Sr*S]Sjr+Sr,"SS \5r-S!r.S"r/S#r0"S$S%\Rb5r2S&r3"S'S(5r4"S)S*5r5"S+S,5r6"S-S.5r7"S/S05r8S1\9\:-S2\;4S3jr<"S4S55r="S6S7\>5r?"S8S9\>5r@"S:S;\85rASqBS^S>jrCS), 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) ANSIColors can_colorizec<^\rSrSrSS.U4SjjrU4SjrSrU=r$) TestResultsor#skippedc4>[TU]XU5nX4lU$N)super__new__r-)clsfailed attemptedr-results __class__s -/opt/imh/python3.13/lib/python3.13/doctest.pyr1TestResults.__new__ps'/#y9!c>UR(a*SURSURSURS3$[TU]5$)NzTestResults(failed=z , attempted=z , skipped=))r-r3r4r0__repr__)selfr6s r7r<TestResults.__repr__usN <<)$++7!!% 01#||nA/ 0 7#% %r9)__name__ __module__ __qualname____firstlineno__r1r<__static_attributes__ __classcell__)r6s@r7r*r*os34 &&r9r*zfailed attemptedcN[RUS[[5-5$)N)OPTIONFLAGS_BY_NAME setdefaultlen)names r7rrs  ) )$S9L5M0M NNr9rrrrrrr r r r rz z...cSn[RH8nURUS5nU[[U5LdM*XR-nM: U$)zy 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 r7_extract_future_flagsrVsM E--))E4( gj%0 0 ** *E. Lr9c[R"U5(aU$[U[5(a[ U[ 5[ 5S/5$Uc)[R[R"U5$[S5e![a7 [R[R"U5RSs$f=f![a gf=f)ag 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. *Nr@z"Expected a module, string, or None)inspectismodule isinstancestr __import__globalslocalssysmodules_getframemodulenameAttributeError _getframe f_globalsKeyError TypeError)moduledepths r7_normalize_modulerjs FC &')VXu==   O{{3#:#:5#ABB <== " O{{3==#7#A#A*#MNN O   s*&B >C C C  C CCc:[SS5RUS5$NT)r%decode)datas r7_newline_convertros $T4 0 7 7d CCr9cU(a~[US5n[X5n[USS5=ncURRn[ US5(a/URU5nURU5n[U5U4$[XS9nUR5U4sSSS5 $![ a Nqf=f!,(df  g=f)N __loader__get_data)encoding) rj_module_relative_pathrP__spec__loaderrchasattrrsrmroopenread)filenamepackagemodule_relativertrw file_contentsfs r7_load_testfilers#GQ/(;g|T: :F C  ))00 6: & &"OOH5M)00:M$M2H< < h *avvx! + *"   + *sB+B;+ B87B8; C c8[R"SUS-U5$)zr 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 r7_indentrs 66,s A ..r9cj[5nUup#n[R"X#XAS9 UR5$)zn 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 r7_exception_tracebackr s2 ZF (Hv hE ?? r9c$\rSrSrSrSSjrSrg) _SpoofOuticv[R"U5nU(aURS5(dUS- nU$N )r$rendswith)r=results r7r_SpoofOut.getvalues3""4( &//$// dNF r9NcRURU5 [R"U5 gr/)seekr$truncate)r=sizes r7r_SpoofOut.truncate"s $$r9r?r/)r@rArBrCrrrDr?r9r7rrs  r9rc[U;aX:H$UR[5n[U5S:deS[U5pCUSnU(a&URU5(a[U5nUS OgUSnU(a)UR U5(aU[U5-nUS OgX4:agUH+nUR XSU5nUS:a gU[U5- nM- g)zO Essentially the only subtle case: >>> _ellipsis_match('aa...aa', 'aaa') False r#FT)ELLIPSIS_MARKERsplitrJ startswithrfind)wantgotwsstartposendposws r7_ellipsis_matchr's d"{ O $B r7a<<#c(f 1A >>!  1vH1 2A <<?? c!f F2 88A0 a<CF r9c<UR5nU(aSU-$g)z)Return a commented form of the given linez# #)rstrip)lines r7 _comment_linerXs ;;=D Dyr9cS[U5p!URS5nUS:aUnURSSU5nUS:aUnURSSU5nUS:aUS-nXU$)Nr#r:.rG)rJrrfind)msgstartendis r7_strip_exception_detailsr`srCH3 AAv aAAv #q#AAv! c?r9c4\rSrSrSrSrS SjrSrSrSr g) _OutputRedirectingPdbizz 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. chXlSUl[RR XSS9 SUlg)NFT)stdoutnosigintrG)_OutputRedirectingPdb__out$_OutputRedirectingPdb__debugger_usedpdbPdb__init__ use_rawinput)r=outs r7r_OutputRedirectingPdb.__init__s. $ D9r9NcSUlUc[R"5Rn[R R X5 grl)rr`rdf_backrr set_trace)r=frames r7r_OutputRedirectingPdb.set_traces2# =MMO**E $&r9cfUR(a [RRU5 ggr/)rrr set_continuer=s r7r"_OutputRedirectingPdb.set_continues$    GG  & r9c[RnUR[l[RR "U/UQ76U[l$!U[lf=fr/)r`rrrrtrace_dispatch)r=args save_stdouts r7r$_OutputRedirectingPdb.trace_dispatchsAjj ZZ  %77))$66$CJCJs A A )__debugger_used__outrr/) r@rArBrC__doc__rrrrrDr?r9r7rrzs ' ' %r9rc[R"U5(d[SU-5eURS5(a [ S5e[ R R"URS56n[US5(a.[ R RUR5SnGO URS:Xay[[R5S:aK[RSS:wa4[ R R[RS5SnO[ RnO[US5(aZUR HJn[ R RX15n[ R R#U5(dMHUs $ [ S UR-5e[ R RX!5$) 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__))rYrZrgr ValueErrorospathjoinrrxrr@rJr`argvcurdirrexists)rh test_pathbasedir directoryfullpaths r7rurusT   F # #/&899C  LMM ys35Ivz""''--03 J & sxx=?sxx{b0ggmmCHHQK03GiiG 6: & &#__ 77<< =77>>(++#O- 3!??+, , 77<< ++r9c2\rSrSrSrSSjrSrSrSrg) ria 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 URS5(dUS- nU(aURS5(dUS- nUbURS5(dUS- nXlX lX@lXPlUc0nX`lX0lgr)rsourcerlinenoroptionsexc_msg)r=rrrrrrs r7rExample.__init__s|t$$ dNF  d++ DLD  w'7'7'='= tOG    ?bG  r9c[U5[U5La[$URUR:H=(a URUR:H=(ay URUR:H=(aY UR UR :H=(a9 UR UR :H=(a URUR:H$r/)typeNotImplementedrrrrrrr=others r7__eq__Example.__eq__s :T%[ (! !{{ell*-yyEJJ&-{{ell*-{{ell*-||u}}, - ||u}},  -r9c[URURURURUR 45$r/)hashrrrrrrs r7__hash__Example.__hash__ s3T[[$))T[[$++\\#$ $r9)rrrrrr)Nr#r#N) r@rArBrCrrrrrDr?r9r7rrs!!DEF$ -$r9rc6\rSrSrSrSrSrSrSrSr Sr g ) ria% 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. c[U[5(aS5eXlX`lUR 5UlX0lX@lXPlg)zt 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[r\examples docstringcopyrRrKr{r)r=rrRrKr{rrs r7rDocTest.__init__)sI h,, JI J, "ZZ\    r9c 4[UR5S:XaSnO4[UR5S:XaSnOS[UR5-nSURR<SUR<SUR <S UR <S U<S 3 $) Nr#z no examplesrGz 1 examplez %d examples)rJrr6r@rKr{r)r=rs r7r<DocTest.__repr__7sp t}}  "$H  1 $"H$s4=='99H((DMM4;;B Cr9c[U5[U5La[$URUR:H=(a URUR:H=(ay URUR:H=(aY UR UR :H=(a9 UR UR :H=(a URUR:H$r/)rrrrrRrKr{rrs r7rDocTest.__eq__Bs :T%[ (! !}}.+~~0+zzU[[(+yyEJJ&+}}. + {{ell*  +r9cp[URURURUR45$r/)rrrKr{rrs r7rDocTest.__hash__Ms&T^^TYY t{{KLLr9c2[U[5(d[$URb UROSnURb UROSnURUR U[ U54URUR U[ U54:$)Nr)r[rrrrKr{id)r=rself_lno other_lnos r7__lt__DocTest.__lt__Qsy%))! !"&++"94;;r$)LL$U^^Y5 BC Dr9)rrr{rRrrKN) r@rArBrCrrr<rrrrDr?r9r7rrs#.  C +MDr9rc\rSrSrSr\R "S\R\R-5r \R "S\R\R-\R-5r \R "S5Rr SSjrSrSSjrS r\R "S \R5rS r\R "S \R5rS rSrSrSrg)ri^z< 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 ^[ ]*(#.*)?$cUR5nURU5nUS:a3SRURS5Vs/sHoDUSPM sn5n/nSupgURR U5HnUR XUR55 XqRSXhR55- nURXU5uppURU 5(d7UR [XU UU[URS55-U S95 XqRSUR5UR55- nUR5nM UR XS5 U$s snf)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#rN)r#r#r)rrr) expandtabs _min_indentrr _EXAMPLE_REfinditerappendrcount_parse_example_IS_BLANK_OR_COMMENTrrJgroupr) r=stringrK min_indentloutputcharnormrrrrs r7parseDocTestParser.parsesX""$%%f- >YY T8JK8J1*+8JKLF!!**62A MM& 2 3 ll4; ;F((&9 -Vd,,V44 wvW+1+5c!''(:K6L+L,3 57 ll4AEEG< c<[URX5UX4XQ5$)z 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)r=rrRrKr{rs r7 get_doctestDocTestParser.get_doctests%t((6v7 7r9c~URX5Vs/sHn[U[5(dMUPM sn$s snf)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. )r"r[r)r=rrKxs r7r%DocTestParser.get_exampless< ::f3+3aa)3+ ++s::c [URS55nURS5RS5nURXTX#5 UR USSSU-S-X#5 SR UVs/sH ofUS-SPM sn5nURS 5nURS5n [U 5S:a"[ R"S U S 5(aU S UR U SU-UU[U5-5 SR U V s/sHoUSPM sn 5nURRU5nU(aURS 5n OSn URXrU5n X|X4$s snfs sn f) 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. rrrrGNrrrz *$rr) rJrr_check_prompt_blank _check_prefixrrmatch _EXCEPTION_RE _find_options) r=r!rKrr source_linesslrr want_lineswlrrs r7rDocTestParser._parse_examplesjQWWX&'wwx(..t4    tD <+SZ#-=tLLALbvaxyMLAB wwvZZ% z?Q 288FJrN#C#C2 :s6z4!C $55 7yy ; "VW+ ;<    $ $T * ggenGG$$V6:--/B??+6!":6!'c!1 )< t0088$dF45 5r9z ^([ ]*)(?=\S)cURRU5Vs/sHn[U5PM nn[U5S:a [U5$gs snf)z;Return the minimum indentation of any non-blank line in `s`r#) _INDENT_REfindallrJmin)r=rrindentss r7rDocTestParser._min_indent#sJ-1__-D-DQ-GH-G63v;-GH w "((1*d"&fQh"7"?@@(r9c [U5H@upVU(dMURU5(aM&[SXE-S-<SU<SU<35e g)zv Check that every line in the given list starts with the given prefix; if any line does not, then raise a ValueError. r9rGrHz& has inconsistent leading whitespace: N)rIrr)r=rJprefixrKrrrs r7r.DocTestParser._check_prefix9sG !'GAtDOOF33 "((1*dD":;;(r9r?N)z)r@rArBrCrrcompile MULTILINEVERBOSErDOTALLr0r/rr"r&r%rr;r1rBrr-r.rDr?r9r7rr^s**  \\BJJ & (K,JJ ZZ",, & 2 4M::o6<<%N 7 +*.f::&D&(ll48,bll;J @ ;r9rc\\rSrSrSrS\"5SS4SjrSSjrSrS r S r S r S r S r g)riIa$ 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. FTc4X lXlX0lX@lg)a 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 r7rDocTestFinder.__init__Rs"   +r9Nc Uc([USS5nUc[S[U5<35eUSLaSnOUc[R"U5n[R "U5nU(d'[R "U5nUSUSS-S:XdSnUcSnOCUb![R"XcR5nO[R"U5nU(dSnUc!Uc0nO+URR5nOUR5nUbURU5 SU;aSUS'/nURXX#Xt05 UR5 U$![a SnNf=f) a 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)rPrrrY getmodule getsourcefilegetfile linecachegetlines__dict__rgrupdate_findsort) r=objrKrhrR extraglobsrr2testss r7rDocTestFinder.findhspH <3 D1D| "&s)".// U?F ^&&s+F  (((-Ds+AwtBCy(E1$4|# %$-#5#5dOO#LL$-#5#5d#;L##'L =~,,.JJLE  ! LL $ U " *E*  5t\"E   Y L sE E%$E%cUcg[R"U5bU[R"U5L$[R"U5(aURURL$[R "U5(d "U5(aV[US5(aURRnO[US5(a URnOgURU:H$[R"U5(aURUR:H$[US5(aURUR:H$[U[5(ag[S5e)zA Return true if the given object is defined in the given module. T __objclass__rAz"object must be a class or function)rYr` isfunctionre __globals__ismethoddescriptorismethodwrapperrxrnrAr@isclassr[propertyr)r=rhobjectobj_mods r7 _from_moduleDocTestFinder._from_modules% >   v & 2W..v66 6    ' '??f&8&88 8((00%%f--v~.. --88.. ++??g- - __V $ $??f&7&77 7 V\ * *??f&7&77 7  ) )AB Br9cUn[R"U5n[R"U5$![a N"f=f)z< Safely unwrap objects and determine if they are functions. )rYunwrapr isroutine)r=ri maybe_routines r7 _is_routineDocTestFinder._is_routinesC  #NN=9M  //   s 0 ==c ^UR(a[SU-5 [U5U;agSU[U5'URX#XFU5nUbUR U5 [ R "U5(aUR(aURR5HmupU<SU <3n URU 5(d[ R"U 5(dMAURXJ5(dMYURXXUXg5 Mo [ R "U5(aUR(a[US05R5Hup[U [ 5(d[#S[%U 5<35e[ R&"U 5(dc[ R"U 5(dH[ R "U 5(d-[U [ 5(d[#S[%U 5<35eU<SU <3n URXXUXg5 M [ R"U5(aUR(aURR5Hup[U [([*45(a U R,n [ R&"U 5(d2[ R"U 5(d[U [.5(dMyURXJ5(dMU<SU <3n URXXUXg5 M ggg) zU Find tests for the given object and any contained objects, and add them to `tests`. zFinding tests in %sNrGr__test__z3DocTestFinder.find: __test__ keys must be strings: z^DocTestFinder.find: __test__ values must be strings, functions, methods, classes, or modules: z .__test__.)rVprintr  _get_testrrYrZrWreitemsr}rsrwrgrPr[r\rrr{ staticmethod classmethod__func__rt) r=rkrirKrhr2rRseentestvalnamevals r7rgDocTestFinder._findsh == '$. / c7d? RW ~~c E   LL    C T]] # 2 2 4 %)73%%c**gooc.B.B%%f22JJu7L$, !5   C T]] 'Z < B B D !'3//$&*7m&677 ))#..'//#2F2F((--C1E1E$'+3i&233/3G< 5w  (!E ??3  DMM # 2 2 4 cL+#>??,,C&&s++ws/C/C h//''44)-w7GJJu7L$,!5%2 r9c[U[5(aUnO=URcSnO,URn[U[5(d [U5nUR X5nUR (aU(dgUcSnO.[USS5=(d URnUSSS:XaUSSnURRXdUX5$![[4a SnNf=f)z[ Return a DocTest for the given object, if it defines a docstring; otherwise, return None. Nrr.pycr) r[r\rrgrc _find_linenorXrPr@rUr&) r=rirKrhrRr2rrr{s r7rDocTestFinder._get_test3s c3  I ;;& "I # I%i55$' N ""35   y >Hvz48KFOOH}&#CR=||'' $(0: :%~.   sC,CC&%C&c dSn[USS5n[R"U5(aUbSn[R"U5(amUbjUcg[R "S[R "[USS55-5n[U5HupgURU5(dMUn O [R"U5(a URn[U[5(a URn[R"U5(a5[USS5(a#[R"U5nUR n[R$"U5(a UR&n[R("U5(a UR*n[R,"U5(aUR.S- nUbVUcUS-$[R "S5n[1U[3U55HnURX#5(dMUs $ g!["a gf=f) zv 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@-rGz(^|.*:)\s*\w*("|\'))rPrYrZrsrrOescaperIr/ismethodrr[rtfgetrorz__code__rc istracebacktb_frameisframef_codeiscodeco_firstlinenorangerJ)r=rir2rrpatrrs r7rDocTestFinder._find_linenoYs CD1    C Y%:F ??3  I$9#**0YYwsJ'DEFGC$\299T??F3   C  # c8 $ $((C   c " "wsIt'D'D..%C ll   s # #3<>#  ''!+F  #ax**34CL(9:99\122!M; 1"   s H"" H/.H/)rXrUrWrVNNNN)r@rArBrCrrrrrwr}rgrrrDr?r9r7rrIs= %]_T,,dLC: 0;,z$:L;r9rc\rSrSrSrSrSSjrSrSrSr S r S r S r S r \R"S 5rSSjrSSjrSSjrSrSrg)ria 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 TestResults instance. >>> save_colorize = _colorize.COLORIZE >>> _colorize.COLORIZE = False >>> 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 TestResults instance: >>> runner.summarize(verbose=1) 4 items passed all tests: 2 tests in _TestClass 2 tests in _TestClass.__init__ 2 tests in _TestClass.get 1 test in _TestClass.square 7 tests in 4 items. 7 passed. Test passed. TestResults(failed=0, attempted=7) The aggregated number of tried examples and failed examples is also available via the `tries`, `failures` and `skips` attributes: >>> runner.tries 7 >>> runner.failures 0 >>> runner.skips 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`. >>> _colorize.COLORIZE = save_colorize zF**********************************************************************NcU=(d [5UlUcS[R;nX lX0lX0lSUlSUlSUl 0Ul [5Ul g)a 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_checkerr`rrV optionflagsoriginal_optionflagstriesfailuresskips_statsr_fakeout)r=checkerrYrs r7rDocTestRunner.__init__s_" 2=? ?chh&G &$/!    "  r9cUR(akUR(a8U"S[UR5-S-[UR5-5 gU"S[UR5-S-5 gg)zo 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)rVrrr)r=rrexamples r7 report_startDocTestRunner.report_startsj ==||K''.."99"#%,W\\%:;<K''.."99)*+ r9c8UR(a U"S5 gg)z\ Report that the given example ran successfully. (Only displays a message if verbose=True) zok N)rVr=rrrrs r7report_successDocTestRunner.report_successs == K r9cU"URX#5URRX4UR5-5 g)z' Report that the given example failed. N)_failure_headerroutput_differencerrs r7report_failureDocTestRunner.report_failures: D  / MM + +G$:J:J K L Mr9cbU"URX#5S-[[U55-5 g)z? Report that the given example raised an unexpected exception. zException raised: N)rrrr=rrrrs r7report_unexpected_exception)DocTestRunner.report_unexpected_exceptions6 D  / ! "$+,@,J$K L Mr9cv[5(a [R[R4OSup4UURU3/nUR (akUR b*UR bUR UR -S-nOSnURSUR <SU<SUR<35 O0URSUR S-<SUR<35 URS5 URnUR[U55 S RU5$) N)rrrG?zFile "", line , in zLine zFailed example:r) r(r'REDRESETDIVIDERr{rrrKrrr)r=rrredresetrrrs r7rDocTestRunner._failure_header$s2>..Z^^Z-- .h t||nUG,- =={{&7>>+Ew~~59 JJ vtyy: ; JJ7>>!+;TYYG H $% 76?#yy~r9c ^S=n=pVURn[S5upn URRn [ UR 5GHTupUS- nUR[ -=(a US:nXplU R(aXU RR5H:unnU(aU=RU-slM$U=RU)-slM< UR[-(aUS- nMU(dURX1U 5 SURU 4-n[[U RUSUS5UR5 UR R#5 SnUR*R-5nUR*R/S5 U nUc'U "U R0UUR5(aUnGO0[2R4"USS6n[7US[85(aWUSR:S 3USR<S USR:S 34m[?U4S j[ U555nUUSnS RAU5nU(dU[CU5- nU RDcU nOuU "U RDUUR5(aUnOOUR[F-(a7U "[IU RD5[IU5UR5(aUnUULaU(dURKX1U U5 OSUU La U(dURMX1U U5 US- nO.UU La U(dUROX1U U5 US- nO S U45eU(dGM:UR[P-(dGMU O XplURSXXV5 [UXEUS9$![$a e [&R("5nUR R#5 GN=f)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 TestResults instance. The examples are run in the namespace `test.globs`. r#rqrGzsingleTNrrrc3\># UH!upURT5(dMUv M# g7fr/)r).0indexrexception_line_prefixess r7 &DocTestRunner.__run..s))+BKE??+BC+Bs, ,rzunknown outcomer,)+rrr check_outputrIrr rrrrrKexecrOrrRdebuggerrKeyboardInterruptr`rrrrrrformat_exception_only issubclass SyntaxErrorrBrAnextrrrrrrrrr_DocTestRunner__record_outcomer*)r=r compileflagsrrr4rrSUCCESSFAILUREBOOMcheck examplenumrquiet optionflagrr{ exceptionroutcome formatted_ex exc_msg_indexrrs @r7__runDocTestRunner.__run;s()((9 $//!&q$ **$-T]]#; J NI%%(AA"\  4 )0)>)>)@%Z((J6(((ZK7( *A$& !!#W5 *TYY ,CCH -WW^^Xx)4126**> **, --((*C MM " "1 %G sD,<,<==%G )>> "1 N ilK88 %Q<445Q7$Q<2231Yq\5N5N4OqQ/+%))+4\+B)%M $0 #?L'',// ::C??*"G7??GT5E5EFF%G%%(??5gooF5g>!--//#*'!''7C@G#''7C@A D44S5>@A :0'::uxD,,y88a$>_%  -LLN  **,s /A O;PcURRURS5upVnX%-X6-XG-4URUR'U=RU- slU=RU- slU=R U- slg)zn Record the fact that the given DocTest (`test`) generated `failures` failures out of `tries` tried examples. )r#r#r#N)rrOrKrrr)r=rrrr failures2tries2skips2s r7__record_outcomeDocTestRunner.__record_outcomesq %)KKOODIIy$I! 6"*"6"'."'."2 DII !  e  e r9z..+)\[(?P\d+)\]>$cNURRU5nU(asURS5URR:XaJURR [ URS55nURRSS9$URX5$)NrKrTkeepends) %_DocTestRunner__LINECACHE_FILENAME_REr/rrrKrintr splitlinessave_linecache_getlines)r=r{module_globalsr!rs r7__patched_linecache_getlines*DocTestRunner.__patched_linecache_getliness}  ( ( . .x 8 DIINN2ii((QWW\-B)CDG>>,,d,; ;//I Ir9c^ ^XlUc[UR5n[RmUc7TR m T bT R 5S:Xa TRnOU U4SjnUR[l[R"5n[Rn[T5Ul URR5 URR[l [R UlUR$[l[R&n[R([l[*R,nS[*lSSS.n U H%n [.R0R3U S5X'M' UR5XU5T[lU[l [R6"U5 UR"[lU[lU[*lU R95HupU cM U [.R0U 'M U(a&URR;5 SSKn SU l$$!T[lU[l [R6"U5 UR"[lU[lU[*lU R95HupU cM U [.R0U 'M U(a&URR;5 SSKn SU lff=f)a 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`>[URTS5T5nTRU5 g)Nbackslashreplace)r\encodewrite)rrtrs r7rDocTestRunner.run..outs)AHHX/ABHMA%%a(r9cgNFr?)rkwargss r7#DocTestRunner.run..sr9) PYTHON_COLORS FORCE_COLORr#) rrVrRr`rrtlowerrrgettracerrrrrrcrdr*_DocTestRunner__patched_linecache_getlines displayhook__displayhook__ _colorizer(renvironpop_DocTestRunner__runsettracerclearbuiltins_)r=rrr clear_globs save_tracesave_set_tracesave_displayhooksaved_can_colorizecolor_variableskeyvaluerrtrs @@r7runDocTestRunner.runs>(  0>#3w#>!'')]] \\^ -k:   // (1'9'9$!>> ??--&33!> ,0F"C#%::>>#t#[[U5S35 UR5 UHn[SU35 M U(aS[U[U5SU35 [U5H)unnUS:XaSOSn[SUUS S US UU35 M+ U(a`[UUR U35 [[U5S 35 [U5Hunupn [SU S S U S S U35 M! U(a[US:XaSOSn[US US [UR5S35 U(a SUUSU3OSn[UXV- SUUS35 U(aDUS:XaSOSnUSUSUU3nU(aUS:XaSOSnUSUUSUU3n[US35 OU(a[U SU35 [#XeUS9$)a  Print a summary of all the test cases that have been run by this DocTestRunner, and return a TestResults instance. The optional `verbose` argument controls how detailed the summary is. If the verbosity is not specified, then the DocTestRunner's verbosity is used. r#z had no tests:z z passed all tests:rGrrr3dz testz in z had failures:z of rz and z failedz passedz***Test Failed*** z failurez skipped testz Test passed.r,)rVrrrr  get_colors BOLD_GREENBOLD_REDGREENrrYELLOWr_n_itemsrhsortedrr*)r=rYnotestspassedr3 total_triestotal_failures total_skipsrKrrransi bold_greenbold_redgreenrryellowrrand_frs r7 summarizeDocTestRunner.summarize1s  ?mmG"$b"566 6n.2kk.?.?.A *D*8E$ $$  K  &N  Kzt$Q tm, t%=>?/B##%__ == hh  '*+>:; #DD-($ 011CE7KL#)&>KD%#qjcAAeWU2JeA3d4&HI$2  SE$,,w/ 0 Xf%&n5 628...x(2d5*D?@3A !Q&CA [Mqcht{{.C-DAF G"u^,GE7;')  UGK89waP Q $)sAJ00@E7SC%*BU6(;-}QCwO SE)   ZL UG4 5> LLr9cURnURR5H'unupEnX2;aX#upxn XG-nXX-nXi-nXEU4X#'M) gr/)rr) r=rdrKrrrrrrs r7mergeDocTestRunner.merges` KK.3ll.@.@.B *D*8Ey,-G) 6#/.AG /Cr9) rrrrVrrrrrrrr)NNr#r/NNT)r@rArBrCrrrrrrrrrrrrOrrrr1r5rDr?r9r7rrsn<~G$J +MM.K?Z !jj*FGJL"bKM`/r9rrreturnc:[U5nUS:XaSOSnUSU3$)z4 Helper to pluralise the number of items in a list. rGrrz item)rJ)rnrs r7r$r$s* E A1f#ASaS>r9c0\rSrSrSrSrSrSrSrSr g) riaC A class used to check 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:[URSS5S5$)z- Convert string to hex-escaped ASCII string. ASCIIr)r\r)r=rs r7_toAsciiOutputChecker._toAsciis188G%78'BBr9c0URU5nURU5nX!:XagU[-(dX!4S:XagX!4S:XagU[-(dQ[R"S[R "[ 5-SU5n[R"SSU5nX!:XagU[-(aDSRUR55nSRUR55nX!:XagU[-(a[X5(agg) ae 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]+$rF) r>rrrrrBLANKLINE_MARKERrrrrrr=rrrs r7rOutputChecker.check_outputs mmC }}T" ;44z..z//3366/BII6F,GGd$D&&*B4C{ - -((399;'C88DJJL)D{  !t))r9cU[[-[--(dgU[-(agURS5S:=(a URS5S:$)NFTrr)r r r rrBs r7_do_a_fancy_diffOutputChecker._do_a_fancy_diffsVl*+*+,  %zz$!#; $!(;;r9c:URnU[-(d[R"S[U5nUR XBU5(aUR SS9nUR SS9nU[-(a&[R"XVSS9n[U5SSnSnOU[-(a&[R"XVSS9n[U5SSnSnOTU[-(a?[R"[RS 9n [U R!XV55nS nOS 5eS U-[#S R%U55-$U(a#U(aS[#U5<S[#U5<3$U(aS[#U5-$U(aS[#U5-$g)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)r:Nz#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 )rrrrrArErr difflib unified_difflistr context_diffr DifferIS_CHARACTER_JUNKcomparerr) r=rrrrr4 got_linesdiffkindengines r7rOutputChecker.output_differencesZ||33&&*, >4r9r?N) r@rArBrCrr>rrErrDr?r9r7rrsC <~<.,5r9rc$\rSrSrSrSrSrSrg)ri'zA 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(XlX lX0lgr/)rrr)r=rrrs r7rDocTestFailure.__init__2s  r9c,[UR5$r/r\rrs r7__str__DocTestFailure.__str__7499~r9)rrrNr@rArBrCrrrZrDr?r9r7rr's  r9rc$\rSrSrSrSrSrSrg)ri:zA 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(XlX lX0lgr/)rrr)r=rrrs r7rUnexpectedException.__init__Es   r9c,[UR5$r/rYrs r7rZUnexpectedException.__str__Jr\r9)rrrNr]r?r9r7rr:s ! r9rc.\rSrSrSrSSjrSrSrSrg) riMaRun 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 {} Ncv[RXX#S5nU(aURR5 U$r)rrrRr)r=rrrrrs r7rDebugRunner.runs.   d,U C  JJ   r9c[X#U5er/)rrs r7r'DebugRunner.report_unexpected_exceptions!$::r9c[X#U5er/)rrs r7rDebugRunner.report_failuresTC00r9r?r7) r@rArBrCrrrrrDr?r9r7rrMsX t ;1r9rTFc  Uc[RRS5n[R"U5(d[ SU<35eUc UR n[US9n U(a [X5S9n O [X5S9n U RXX&S9Hn U RU 5 M U(aU R5 [cU q O[RU 5 [U R U R"U R$S9$)af 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; )r\rYrrRrjr,)r`rarOrYrZrgr@rrrrrr1masterr5r*rrr) r!rKrRrYreportrrjraise_on_errorr\finderrunnerrs r7rrsJ y KKOOJ '   A  !=>> |zz 7FWFwH A5 H 4I ~ V v fll KKr9c LU(aU(d [S5e[XUU =(d S5upUc[RR U5nUc0nOUR 5nUbUR U5 SU;aSUS'U (a [XWS9n O [XWS9n U RXX S5nU RU5 U(aU R5 [cU q O[RU 5 [U RU R U R"S9$)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@rrlr#r,)rrrrbasenamerrfrrr&rr1rnr5r*rrr)r{r}rKr|rRrYrorrjrprZrttextrrrs r7rr&sd+, ,$H$,$79ND |ww) }  Z &jWFwH   d41 =D JJt  ~ V v fll KKr9cv[USS9n[X%S9nURXUS9HnURXS9 M g)aB 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)rYr[rl)rR)rN)rrrr) rrRrYrKrrrqrrrs r7rrs?$7E :F 7 DF A5 1 4 32r9cHU[-U:wa [SU5e[nUqU$)aSets 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)rSolds r7rrs/: E)7?? C! Jr9cv\rSrSrSSjrSrSrSrSrSr S r S r S r S r \RrS rSrg) DocTestCaseiNc~[RRU5 X lXPlXlX0lX@lgr/)unittestTestCaser_dt_optionflags _dt_checker_dt_test _dt_setUp _dt_tearDown)r=rrsetUptearDownrs r7rDocTestCase.__init__s4 ""4(*" $r9cURnURR5UlURbUR U5 ggr/)rrRr _dt_globsrr=rs r7rDocTestCase.setUps8}}* >> % NN4  &r9cURnURbURU5 URR5 URR UR 5 gr/)rrrRrrfrrs r7rDocTestCase.tearDownsM}}    (   d #  $..)r9cURn[Rn[5nURnU[ -(d U[ -n[UURSS9nSUl URXRSS9nURUR:Xa[R"S5eU[lUR (a.UR#UR%UR'555eg!U[lf=f)NFrrrYzF----------------------------------------------------------------------)rrzall examples were skipped)rr`rr$rrryrrrrrr-r4r~SkipTestr3failureExceptionformat_failurer)r=rrznewrrrr5s r7runTestDocTestCase.runTest s}}jjj** o- 0 0K;'+'7'7H #FNjj99%jHG'"3"33''(CDD4CJ >>''(;(;CLLN(KL L CJs AC== D c URnURcSnOSUR-nSRURR S5SS5nSUR<SUR <SU<SU<S U<3 $) Nzunknown line numberz%srrFailed doctest test for File "rrz )rrrrKrr{)r=errrrlnames r7rDocTestCase.format_failure sj}} ;; *FDKK'F-bc2399dmmVUCA r9cUR5 [URURSS9nUR UR SS9 UR 5 g)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=rrs r7r"DocTestCase.debug% sID )=)=%)%5%5uF 4==e 4 r9c.URR$r/rrKrs r7r DocTestCase.idm s}}!!!r9cn[U5[U5La[$URUR:H=(ay URUR:H=(aY URUR:H=(a9 UR UR :H=(a UR UR :H$r/)rrrrrrrrs r7rDocTestCase.__eq__p s :T%[ (! !}}.5##u'<'<<5~~05  E$6$6655#4#44  5r9cp[URURURUR45$r/)rrrrrrs r7rDocTestCase.__hash__z s3T))4>>4;L;L%%'( (r9cURRRS5nUS<SSRUSS5<S3$)Nrrrr;)rrKrr)r=rKs r7r<DocTestCase.__repr__~ s:}}!!'', HchhtCRy&9::r9c4SURR-$)Nz Doctest: rrs r7shortDescriptionDocTestCase.shortDescription sT]]////r9)rrrrrr)r#NNN)r@rArBrCrrrrrr"r rrr<rurZrrDr?r9r7r|r|sMAE%!*M2 FP"5(;nnG0r9r|c0\rSrSrSrSrSrSr\rSr g)SkipDocTestCasei c<Xl[RUS5 gr/)rhr|r)r=rhs r7rSkipDocTestCase.__init__ s T4(r9c&URS5 g)Nz-DocTestSuite will not work with -O2 and above)skipTestrs r7rSkipDocTestCase.setUp s EFr9cgr/r?rs r7 test_skipSkipDocTestCase.test_skip  r9c4SURR-$)NzSkipping tests from %s)rhr@rs r7r SkipDocTestCase.shortDescription s'$++*>*>>>r9)rhN) r@rArBrCrrrrrZrDr?r9r7rr s)G ?Gr9rc\rSrSrSrSrg) _DocTestSuitei cgr/r?)r=rs r7_removeTestAtIndex _DocTestSuite._removeTestAtIndex rr9r?N)r@rArBrCrrDr?r9r7rr s r9rc Uc [5n[U5nURXUS9nU(dD[RR S:a&[ 5nUR[U55 U$UR5 [ 5nUHjn[UR5S:XaMUR(d URnUSSS:XaUSSnXl UR[U40UD65 Ml U$)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. Nrmrr#rrr)rrjrr`rSoptimizeraddTestrrhrJrr{rr|) rhrRrj test_finderrrksuiterr{s r7rr sJ#o v &F   VZ  HE SYY''!+ of-.  JJL OE t}}  " }}H}&#CR=$M k$2'23 Lr9c&\rSrSrSrSrSrSrg) DocFileCasei cjSRURRRS55$)Nrr)rrrKrrs r7r DocFileCase.id s&xx **00566r9c.URR$r/)rr{rs r7r<DocFileCase.__repr__ s}}%%%r9cnSURR<SURR<SU<3$)Nrrz ", line 0 )rrKr{)r=rs r7rDocFileCase.format_failure s(==%%t}}'='=sD r9r?N)r@rArBrCr r<rrDr?r9r7rr s7&r9rc Uc0nOUR5nU(aU(d [S5e[XUU=(d S5uppSU;aXS'[RR U5nUR XsXS5n [U 40UD6$)Nrtrrr#)rrrrrrur&r) rr}r|rRrZrtrdocrKrs r7 DocFileTestr s } +, ,to'274IC j 77  D !D   c$a 8D t 'w ''r9c[5nURSS5(a[URS55US'UHnUR[ U40UD65 M U$)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. r}Tr|)rrOrjrr)pathskwrrs r7rr s^p OE  vv&&)"&&*;<9  k$-"-. Lr9c/n[5RU5Hn[U[5(apUR UR SS5 UR nU(a=UR S5 XRS5SSVs/sHnSU-PM sn- nMMUURS5SSVs/sHn[U5PM sn- nM U(a+USS:Xa"UR5 U(a USS:XaM"U(a,USS:Xa#URS5 U(a USS:XaM#SRU5S-$s snfs snf)aExtract 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:rz## rr#) rr"r[rrrrrrr r)rrpiecerrs r7rrN s>tF&&q) eW % % MM%,,s+ ,::D m,JJt,>2G N 0s A7A7c2[U5n[X1U5 g)z4Debug a single doctest docstring, in argument `src`'N)r debug_script)srcpmrRrs r7r!r! s"3'Ge$r9cSSKnU(aUR5nO0nU(a[XU5 gUR "SS9RSU-X"5 g! [[R "5S5 UR "SS9nUR5 URS[R "5S5 g=f)z7Debug a test script. `src` is the script, as a string.r#NrGT)rrzexec(%r)) rrrrr`rrr interactionr)rrrRrps r7rr s    3 U # "":#3UB  3 #,,.# $&A GGI MM$ q 1 2s AA+Cc\[U5n[X5n[X2UR5 g)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)rjr rre)rhrKrrs r7r"r" s&v &F&Gfoo.r9c*\rSrSrSrSrSrSrSrg) _TestClassi z 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' cXlg)zdval -> _TestClass object with associated value val. >>> t = _TestClass(123) >>> print(t.get()) 123 Nr)r=rs r7r_TestClass.__init__ s r9c.URS-UlU$)zWsquare() -> square TestClass's associated value >>> _TestClass(13).square().get() 169 rrrs r7square_TestClass.square s88q= r9cUR$)z^get() -> return TestClass's associated value. >>> x = _TestClass(-42) >>> print(x.get()) -42 rrs r7rO_TestClass.get s xxr9rN) r@rArBrCrrrrOrDr?r9r7rr s r9rz 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] )rrzbool-int equivalencez blank linesellipsiszwhitespace normalizationc SSKnURSS9nURSSSSSS 9 URS S S [R 5/S S9 URSSSSS9 URSSSS9 UR 5nUR nURnSnURHnU[U-nM UR(a U[-nUHnURS5(am[RRU5up[RR!SU5 [#USS5n [RS [%XUS9upO ['USXES9upU (dM g g)Nr#zdoctest runner) descriptionrz --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)rchoicesrrz-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))rrrr:z file containing the tests to run)nargsrz.pyrl)r}rYrrG)argparseArgumentParser add_argumentrHkeys parse_argsrrYr> fail_fastrrrrrr`insertr]rr) rrZr testfilesrYrr>r{dirnamer!rrs r7_testr6 s  $ $1A $ BF k,FH j 3 8 8 :BEG  mLFH c?A    D IllGG++&v.. ~~9   U # #!# h 7 G HHOOAw '8CR=)A !!'JKHa"8U-4KKH 8 r9r)r)r,) NNNNTr#NFF)FNoNameNr#r)FN)F)[r __docformat____all__rMrIrYrcrrrr`rr~ior$r% collectionsr&r r'r(r*rHrrrrrrrr r r r r rrrArrVrjrorrrrrrrrrrurrrrrrKdictr\r$r Exceptionrrrrnrrrryrrr|r TestSuiterrrrrrr r!rr"rrrr@exitr?r9r7rs\%N& + Z 2".&*],>?&LO--EF+,CD*+AB z *6"-.GH*)*()  , ,#>2 ">2 ">2 /0KL  ,   -- !& >2D"$/     /b4"%CGG"%J ,\B$B$HGDGDZd;d;VKKb o/o/dD4KCP5P5dY&)&e1-e1\ 373705fLR(,$dU=?yLx:B:;46!Hb0(##b0Hk" H&& >@ + '+D=?(4CRP$d % C( /**X%%( )Q0 f* Z zHHUWr9