\dr dZddgZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl mZddlZdZGddZd Zd ZGd dZd Zd ZddZdZGddZdZedkr edSdS)aprogram/module to trace Python program or function execution Sample use, command line: trace.py -c -f counts --ignore-dir '$prefix' spam.py eggs trace.py -t --ignore-dir '$prefix' spam.py eggs trace.py --trackcalls spam.py eggs Sample use, programmatically import sys # create a Trace object, telling it what to ignore, and whether to # do tracing or line-counting or both. tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,], trace=0, count=1) # run the new command using the given tracer tracer.run('main()') # make a report, placing output in /tmp r = tracer.results() r.write_results(show_missing=True, coverdir="/tmp") TraceCoverageResultsN) monotonicz#pragma NO COVERceZdZddZdZdS)_IgnoreNc|stnt||_|sgn d|D|_ddi|_dS)NcLg|]!}tj|"S)ospathnormpath.0ds ..\python\lib\trace.py z$_Ignore.__init__..Hs8*9*9*9./+-'*:*:1*=*=*9*9*9z)set_mods_dirs_ignore)selfmodulesdirss r__init__z_Ignore.__init__FsX");SUUUs7|| #9RR*9*937*9*9*9 #Q( rc\||jvr |j|S||jvr d|j|<dS|jD]'}||dzr d|j|<dS(| d|j|<dS|jD]1}||tjzr d|j|<dS2d|j|<dS)Nr.r)rr startswithrr sep)rfilename modulenamemodrs rnamesz _Ignore.namesLs  % %< + +  # #'(DL $1:  C$$S3Y// +, Z(qq   '(DL $1  A""1rv:.. +, Z(qq  $% Z qrNN)__name__ __module__ __qualname__rr$r rrrrEs7)))) )))))rrctj|}tj|\}}|S),Return a plausible module name for the path.)r r basenamesplitext)r baser!exts r_modnamer/ws7 7  D ! !DG$$T**MHc Orctj|}d}tjD]{}tj|}||rE|t |tjkr"t |t |kr|}||r|t |dzd}n|}tj|\}}|tjd}tj r |tj d}tj |\}}| dS)r*rNr) r r normcasesysrlenr splitdrivereplacealtsepr,lstrip)r comparepathlongestdirr-driver!r.s r _fullmodnamer=~s0'""4((KGxgs##  ! !# & & ;s3xx+@BF+J+J3xx#g,,&&CLL1$%%&'$$T**KE4 << $ $D y,||BIs++G$$T**MHc ??3  rc6eZdZ d dZdZdZd dZd dZdS) rNc||_|ji|_|j|_||_|ji|_|j|_||_|ji|_|j|_||_||_|jr t|jd5}tj |\}}}dddn #1swxYwY| | |||dS#tttf$r1}td|jd|t jYd}~dSd}~wwxYwdS)Nrb)callerszSkipping counts file : file)countscopycounter calledfuncsrAinfileoutfileopenpickleloadupdate __class__OSErrorEOFError ValueErrorprintr3stderr)rrErHrIrArJferrs rrzCoverageResults.__init__s ; DK{'')) &   #!D +0022 < DL|((**   ; N N$+t,,B39;q>>0FKBBBBBBBBBBBBBBB DNN6;NPPQQQQQXz2 N N N)-cc;BE*NNNNNNNNNN N  N Ns<0D"C* D"*C..D"1C.2.D""E*9&E%%E*cV|do|dS)z_Return True if the filename does not refer to a file we want to have reported. <>)rendswith)rr!s ris_ignored_filenamez#CoverageResults.is_ignored_filenames+""3''BH,=,=c,B,BBrc|j}|j}|j}|j}|j}|j}|D]$}||d||z||<%|D]}d||<|D]}d||<dS)z.Merge in the data from another CoverageResultsrrN)rErHrAget) rotherrErHrA other_countsother_calledfuncs other_callerskeys rrNzCoverageResults.updates& ,| !-  A AC **S!,,|C/@@F3KK$ ! !C K     CGCLL  rTFc |jrRttd|j}t|D]\}}}td|d|d||jrttddx}} t|jD]o\\} } } \} }}| |kr#ttd| d| }d} | | kr| | krtd| | } td | d | d |d |pi}|jD]2\}}||ix}||<|j||f||<3i}|D]\}}||r|d r |d d}|Ltj tj |}t|}nD|}tj |stj|t!|}|rt#|}ni}t%j|}tj ||dz}t+|d5}t-j|j\}}d d d n #1swxYwY||||||\}}|r |rt5d|z|z }||||f||<|rH|rFtdt|D]'}||\}}}}td||z(|jr t+|jd5} t9j|j|j|jf| dd d d d S#1swxYwYd S#t<$r)}!td|!zt>j Yd }!~!d Sd }!~!wwxYwd S)af Write the coverage results. :param show_missing: Show lines that had no hits. :param summary: Include coverage summary per module. :param coverdir: If None, the results of each module are placed in its directory, otherwise it is included in the directory specified. zfunctions called:z filename: z, modulename: , funcname: zcalling relationships:r1z***z -->z rz -> z.pycNz.coverr@dzlines cov% module (path)z%5d %3d%% %s (%s)wbrz"Can't save counts files because %srC)!rHrSsortedrArEr]itemsr[rZr r dirnameabspathr/existsmakedirsr=_find_executable_linenos linecachegetlinesjoinrKtokenizedetect_encodingreadlinewrite_results_fileintrJrLdumprPr3rT)"r show_missingsummarycoverdircallsr!r"funcnamelastfile lastcfilepfilepmodpfunccfilecmodcfuncper_filelineno lines_hitsumscountr;lnotabsource coverpathfpencoding_n_hitsn_linespercentmrUrVs" r write_resultszCoverageResults.write_resultss   < GGG % & & &$E28-- < <.*h"((JJJ:<<<< < I GGG * + + +#% %Hydl++ I I<%%u';tUH$$GGG%...$H "IE>>i5&8&8'5))) %IdddEEE444GHHHH $  @ @ Hf-5\\(B-G-G GI* $ Xv,> ?If  '~~// J JOHe''11   (( )#CRC=goobgooh&?&?@@%h// w~~c**%K$$$)(33  1(;;'11F S*x*?@@Ih%% D&6r{CC ! D D D D D D D D D D D D D D D"55i6 M !1&&&&&&&&&&&&&&&&&&&&& S S S:S@szRRRRRRRRRR S  S SsNJ))J- 0J- N)N NNNNN O(O  Oc4 t|d|}n:#t$r-}td|d|dtjYd}~dSd}~wwxYwd }d } |5t |d D]\} } | |vr)|d || z| d z } |d z }n=| |vr$t| vr|d |d z }n|d || d dddn #1swxYwY| |fS)z'Return a coverage results file in path.wrztrace: Could not open z for writing: z - skippingrCN)rrrrz%5d: z>>>>>> z ) rKrPrSr3rT enumeratewritePRAGMA_NOCOVER expandtabs) rr linesrrrrJrVrrrlines rruz"CoverageResults.write_results_file)s 4x888GG    E26$$=DGJ P P P P44444    2 2 )% 3 3 2 2 Y&&MM'If,="=>>>aKFqLGGv%%n.D.DMM),,,qLGGMM),,, dooa001111 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2"ws' A "AA B)D  DD)NNNNN)TFNN)r&r'r(rr[rNrrur rrrrs=A'+NNNN4CCC $ZSZSZSZSxrcPi}tj|D]\}}||vrd||<|S)z:Return dict where keys are lines in the line number table.r)disfindlinestarts)codestrslinenosrrs r_find_lines_from_coderIs?G'--  6   GFO Nrct||}|jD]9}tj|r#|t ||:|S)z!   1 NN;q$// 0 0 0 NrcLi}tj}t||5}tj|j}|D]O\}}}} } |tjkr5|tjkr%|\} } | \} }t| | dzD]}d||<|}P dddn #1swxYwY|S)zReturn a dict of possible docstring positions. The dict maps line numbers to strings. There is an entry for line that contains only a string or a part of a triple-quoted string. rrN)tokenINDENTrKrrgenerate_tokensrtSTRINGrange)r!rr prev_ttyperUtokttypetstrstartendrslinescolelineecolis r _find_stringsr_s  AJ h * * * a&qz22-0   )E4T $$--"'KE4"%KE4"5%!)44!! !JJ                 HsA,BB Bcj tj|5}|}|j}dddn #1swxYwYn:#t$r-}t d|d|t jicYd}~Sd}~wwxYwt||d}t||}t||S)zAReturn dict where keys are line numbers in the line number table.NzNot printing coverage data for rBrCexec) rrrKreadrrPrSr3rTcompilerr)r!rUprogrrVrrs rrnrnvs ]8 $ $ "6688DzH " " " " " " " " " " " " " " "  !)3307:z C C C C  46 * *D 8 , ,D tT " ""s=A > A AA AA B"A<6B<Bc`eZdZ ddZdZddZd Zd Zd Zd Z d Z dZ dZ dZ dZdS)rrrr NFc ||_||_t|||_i|_i|_d|_||_i|_i|_ i|_ d|_ | rt|_ |r|j |_dS|r|j|_dS|r|r|j|_|j|_dS|r|j|_|j|_dS|r|j|_|j|_dSd|_dS)ax @param count true iff it should count number of times each line is executed @param trace true iff it should print out each line that is being counted @param countfuncs true iff it should just output a list of (filename, modulename, funcname,) for functions that were called at least once; This overrides `count' and `trace' @param ignoremods a list of the names of modules to ignore @param ignoredirs a list of the names of directories to ignore all of the (recursive) contents of @param infile file from which to read stored counts to be added into the results @param outfile file in which to write the results @param timing true iff timing information be displayed rNr)rIrJrignorerEpathtobasename donothingtrace _calledfuncs_callers _caller_cache start_time_timeglobaltrace_trackcallers globaltraceglobaltrace_countfuncsglobaltrace_ltlocaltrace_trace_and_count localtracelocaltrace_tracelocaltrace_count) rrr countfuncs countcallers ignoremods ignoredirsrIrJtimings rrzTrace.__init__s(  j*55       &#ggDO  #B6~ +  t/ 0 0 0 L) * * * ) gv & & &> ) T""""4((((( ) )4> ) T""""4(((( )s B2B9cd}|jstj|j ||i|}|jstjdn!#|jstjdwwxYw|Sr)rr3rr)rfuncargskwresults rrunfuncz Trace.runfuncs~ + L) * * * #T4&2&&F> # T"""> # T"""" # s AA&c<|j}|j}|rt|}nd}|j}d}||jvr|j| |j|}nd|j|<dt j|D}t|dkrdt j|dD}t|dkrNdt j|dD} t| dkr| dj}||j|<||d|}|||fS)Nc:g|]}tj||Sr )r isfunction)rrUs rrz1Trace.file_module_function_of..s73331#.q113Q333rrc<g|]}t|t|Sr ) isinstancerrs rrz1Trace.file_module_function_of..s6555q *1d 3 35555rrc2g|]}t|d|S) __bases__)hasattr)rrs rrz1Trace.file_module_function_of..s6???Q&-a&=&=?q???rr) f_code co_filenamer/co_namergc get_referrersr4r&) rframerr!r"r|clsnamefuncsdictsclassess rfile_module_function_ofzTrace.file_module_function_ofs_|#  !(++JJJ< 4% % %!$'3,T2'+D t $33 0 6 6333E 5zzQ55B$4U1X$>$>555u::????"*:58*D*D???G7||q((")!*"5 4;*40  ")''884HX--rc|dkr=||}||j}d|j||f<dSdS)zkHandler for call events. Adds information about who called who to the self._callers dict. callrN)rf_backr)rrwhyarg this_func parent_funcs rrzTrace.globaltrace_trackcallerssS &==44U;;I66u|DDK67DM; 2 3 3 3 =rcT|dkr!||}d|j|<dSdS)zoHandler for call events. Adds (filename, modulename, funcname) to the self._calledfuncs dict. rrN)rr)rrrrrs rrzTrace.globaltrace_countfuncss: &==44U;;I+,D i ( ( ( =rc|dkr|j}|jdd}|rZt|}|E|j||}|s*|jrtd|d|j|j SdSdSdSdS)zHandler for call events. If the code block being entered is to be ignored, returns `None', else returns self.localtrace. r__file__Nz --- modulename: rd) r f_globalsr]r/rr$rrSrr)rrrrrr!r" ignore_its rrzTrace.globaltrace_lts &==tj d?fd@dA|j D|_ fdB|jD|_|j r]|j s| dCt|j |j D}||j|j|jSt'|j|j|j|jgs| dE|jr#|js|jr| dF|jr|js| dG|j| dHt3|j|j|j|j|j |j|j |j |jI } |jrVddl}|j}||\} } } | jg|jt@_!dJ| j| j"| j#| ddK} n|jg|jt@_!tHj%&|jt@j%d<tOj(|j5} tS| *|jdL} dddn #1swxYwY|jdJdddM} |+| | | nL#tX$r4}tAj-dNt@j!ddO|Yd}~nd}~wt\$rYnwxYw|/}|j0s(||j|j|jdSdS)PNrz --versionversionz trace 2.0)actionrz Main optionsz(One of these (or --report) must be givenz-cz--count store_truezCount the number of times each line is executed and write the counts to .cover for each module executed, in the module's directory. See also --coverdir, --file, --no-report below.)rhelpz-tz--tracez3Print each line to sys.stdout before it is executedz-lz --listfuncszKeep track of which functions are executed at least once and write the results to sys.stdout after the program exits. Cannot be specified alongside --trace or --count.z-Tz --trackcallsz^Keep track of caller/called pairs and write the results to sys.stdout after the program exits. Modifiersz-rz--reportzGenerate a report from a counts file; does not execute any code. --file must specify the results file to read, which must have been created in a previous run with --count --file=FILEz-Rz --no-reportz^Do not generate the coverage report files. Useful if you want to accumulate over several runs.z-fz--filez+File to accumulate counts over several runs)rz-Cz --coverdirzDirectory where the report files go. The coverage report for . will be written to file //.coverz-mz --missingz?Annotate executable lines that were not executed with ">>>>>> "z-sz --summaryz\Write a brief summary for each file to sys.stdout. Can only be used with --count or --reportz-gz--timingzQPrefix each line with the time since the program started. Only used while tracingFilterszCan be specified multiple timesz--ignore-moduleappendzqIgnore the given module(s) and its submodules (if it is a package). Accepts comma separated list of module names.)rdefaultrz --ignore-dirzWIgnore files in the given directory (multiple directories can be joined by os.pathsep).z--moduleFzTrace a module. progname?zfile to run as main program)nargsr argumentszarguments to the programstdlib platstdlibctjtj|}|dd}tj|S)Nz$prefixz $exec_prefix)r r expanduser expandvarsr6r )s _exec_prefix_prefixs rparse_ignore_dirzmain..parse_ignore_dirsa G  rw11!44 5 5 IIi ) ) 1 1., O Ow"""rcfg|].}|dD]}|/S),)splitstrip)rrr#s rrzmain..sWOOOOO:=))++OOOOrcjg|]/}|tjD] }|0Sr )r1r pathsep)rrr+r.s rrzmain..s_NNN9L9LNN45('**NNNNrz-r/--report requires -f/--file)rIrJzLmust specify one of --trace, --count, --report, --listfuncs, or --trackcallsz8cannot specify both --listfuncs and (--trace or --count)z3--summary can only be used with --count or --reportz3progname is missing: required with the main options)rrrrrIrJrr)r&r  __package__ __loader____spec__ __cached__r)r r&r5r8zCannot run file z because: )1argparseArgumentParser add_argumentadd_argument_groupadd_mutually_exclusive_group REMAINDER parse_args ignore_dir sysconfigget_path ignore_modulereportrDerrorrrmissingryrzanyrr listfuncs trackcallsr"rrmodulerunpy_get_module_detailsrr%r3argvparentloaderr r rjio open_coderrrrPexit SystemExitr no_report)r9parsergrp_grpoptsrtrK module_namemod_namemod_specrglobsrrVr,r-r.s @@@rmainr^RsQOOO  $ $ & &F  I{KKK  # #N 6 8 8CT9\&''' T9\FHHHT=EFFFT>,7888  # #K 0 0C  + + - -DdJ|    dM,GHHHT8>@@@T<2333T;|T;|=>>>T:l+,,,  # #I - / /C&x!"""^HbGHHH  </111  #.000  8+=+---     D 8$X.. ),77 ###### OO#'#5OOODNNNN $NNNDO {Py ; LL9 : : :!DIFFF$$T\4<OOO  DJH I I5 4 5 5 5 ~Q4:QQ OPPP |LDJL JKKK } JKKK dj$*?t7Ii  5 5 5A ;  LLL-K','@'@'M'M $Hh(:4>:CH& ,'&o$" EE 77CH'//$-88CHQKdm,, Arwwyy$-@@ A A A A A A A A A A A A A A A!M&#" E ue$$$$ HHH SXa[[[##FGGGGGGGG      iikkG >IdlDL$-HHHHHIIsC CT )S TSTS&T U *T== U  U rr)__doc____all__rPror r3rArrrrrrrLtimerrrrrr/r=rrrrrnrr^r&r rrrbs<( % &    #######00000000d   8mmmmmmmm^       . # # #L6L6L6L6L6L6L6L6\PIPIPId ZDFFFFFr