3 \=p @s,dZddgZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl mZy ddlZWn"ek rejZddZYnXdd Zd dZd ZGd d d ZddZddZGdddZddZddZdddZddZGdddZddZe dkr(edS) 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) monotoniccCstjddS)N)syssettracerr/usr/lib64/python3.6/trace.py _unsettraceEsr cCstj|tj|dS)N) threadingrr)funcrrr _settraceHs r cCstjdtjddS)N)rrr rrrrr Ls z#pragma NO COVERc@seZdZdddZddZdS)_IgnoreNcCs:|s tnt||_|sgn dd|D|_ddi|_dS)NcSsg|]}tjj|qSr)ospathnormpath).0drrr Usz$_Ignore.__init__..z)set_mods_dirs_ignore)selfmodulesdirsrrr__init__Ss z_Ignore.__init__cCs||jkr|j|S||jkr,d|j|<dSx*|jD] }|j|dr4d|j|<dSq4W|dkrnd|j|<dSx,|jD]"}|j|tjrvd|j|<dSqvWd|j|<dS)Nr.r)rr startswithrrsep)rfilename modulenamemodrrrrnamesYs$          z _Ignore.names)NN)__name__ __module__ __qualname__rr#rrrrr Rs r cCs tjj|}tjj|\}}|S)z-Return a plausible module name for the patch.)rrbasenamesplitext)rbaser extrrr_modnames r+cCstjj|}d}xJtjD]@}tjj|}|j|r|t|tjkrt|t|kr|}qW|rv|t|dd}n|}tjj|\}}|jtjd}tj r|jtj d}tjj |\}}|j dS)z,Return a plausible module name for the path.rNr) rrnormcaserrlenr splitdrivereplacealtsepr(lstrip)rZ comparepathZlongestdirr)Zdriver r*rrr _fullmodnames    r4c@s:eZdZdddZddZddZdd d Zdd d ZdS)rNcCs||_|jdkri|_|jj|_||_|jdkr8i|_|jj|_||_|jdkrZi|_|jj|_||_||_|jry@t|jd}tj |\}}}WdQRX|j |j |||Wn@t t tfk r}ztd|j|ftjdWYdd}~XnXdS)NrbzSkipping counts file %r: %s)file)countscopyZcounter calledfuncscallersinfileoutfileopenpickleloadupdate __class__OSErrorEOFError ValueErrorprintrstderr)rr7r9r;r:r<ferrrrrrs,      zCoverageResults.__init__cCs|jdo|jdS)z_Return True if the filename does not refer to a file we want to have reported. <>)rendswith)rr rrris_ignored_filenamesz#CoverageResults.is_ignored_filenamec Csz|j}|j}|j}|j}|j}|j}x$|D]}|j|d||||<q*Wx|D] }d||<qPWx|D] }d||<qfWdS)z.Merge in the data from another CoverageResultsrrN)r7r9r:get) rotherr7r9r:Z other_countsZother_calledfuncsZ other_callerskeyrrrr@s    zCoverageResults.updateTFc!Cs|jrDttd|j}x(t|D]\}}}td|||fq$W|jrttdd}} xvt|jD]h\\} } } \} }}| |krttd| d| }d} | | kr| | krtd| | } td| | ||fqlWi}x8|jD].\}}|j|i}||<|j||f||<qWi}x$|jD]\}}|j|r@q&|jdrX|d d}|d krt j j t j j |}t |}n$|}t j j|st j|t|}|rt|}ni}tj|}t j j||d }t|d }tj|j\}}Wd QRX|j|||||\}}|r&|r&td ||}||||f||<q&W|r|rtdx2t|D]&}||\}}}}td||q`W|jry&tj|j|j|jft|jdd Wn6tk r} ztd| tj dWYd d } ~ XnXd 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: %s, modulename: %s, funcname: %szcalling relationships:r,z***z -->z %s.%s -> %s.%sz.pycNrz.coverr5dzlines cov% module (path)z%5d %3d%% %s (%s)wbz"Can't save counts files because %s)r6)!r9rEsortedr:r7rMitemsrLrKrrdirnameabspathr+existsmakedirsr4_find_executable_linenos linecachegetlinesjoinr=tokenizedetect_encodingreadlinewrite_results_fileintr<r>dumprBrrF)!rZ show_missingsummarycoverdirZcallsr r!funcnameZlastfileZ lastcfileZpfileZpmodZpfunccfileZcmodZcfuncZper_filelineno lines_hitZsumscountr3lnotabsourceZ coverpathfpencoding_n_hitsn_linesZpercentmrHrrr write_resultss|              zCoverageResults.write_resultsc Csyt|d|d}Wn6tk rH}ztd||ftjdd Sd}~XnXd}d} |xt|dD]r\} } | |kr|jd|| | d7} |d7}n.| |krt| kr|jd |d7}n |jd |j| jd qdWWdQRX| |fS) z'Return a coverage results file in path.w)rmz3trace: Could not open %r for writing: %s - skipping)r6rNrz%5d: z>>>>>> z )rr) r=rBrErrF enumeratewritePRAGMA_NOCOVER expandtabs) rrlinesrjrhrmr<rHrprorglinerrrr`5s(    z"CoverageResults.write_results_file)NNNNN)TFN)N)r$r%r&rrLr@rrr`rrrrrs   [cCs0i}x&tj|D]\}}||krd||<qW|S)z:Return dict where keys are lines in the line number table.r)disZfindlinestarts)codestrslinenosrnrgrrr_find_lines_from_codeUs  rcCs8t||}x(|jD]}tj|r|jt||qW|S)z.rcSsg|]}t|tr|qSr) isinstancer)rrrrrrsrcSsg|]}t|dr|qS) __bases__)hasattr)rrrrrrsz%s.%s) f_code co_filenamer+co_namergcZ get_referrersr.r$) rframer|r r!reZclsnameZfuncsZdictsclassesrrrfile_module_function_ofs,          zTrace.file_module_function_ofcCs0|dkr,|j|}|j|j}d|j||f<dS)zkHandler for call events. Adds information about who called who to the self._callers dict. callrN)rf_backr)rrwhyarg this_funcZ parent_funcrrrrs  zTrace.globaltrace_trackcallerscCs |dkr|j|}d|j|<dS)zoHandler for call events. Adds (filename, modulename, funcname) to the self._calledfuncs dict. rrN)rr)rrrrrrrrrs zTrace.globaltrace_countfuncscCsj|dkrf|j}|jjdd}|rbt|}|dk rf|jj||}|sf|jrZtd||jf|j SndSdS)zHandler for call events. If the code block being entered is to be ignored, returns `None', else returns self.localtrace. r__file__Nz! --- modulename: %s, funcname: %s) r f_globalsrMr+rr#rrErr)rrrrr|r r!Z ignore_itrrrrszTrace.globaltrace_ltcCs|dkr~|jj}|j}||f}|jj|dd|j|<|jrTtdt|jddtj j |}td||t j ||fdd|j S) Nrzrrz%.2f )rz %s(%d): %sr,)rrf_linenor7rMrrErrrr'rZgetliner)rrrrr rgrObnamerrrr2s z Trace.localtrace_trace_and_countcCsd|dkr^|jj}|j}|jr4tdt|jddtjj|}td||t j ||fdd|j S)Nrzz%.2fr)rz %s(%d): %sr,) rrrrrErrrr'rZrr)rrrrr rgrrrrrAs zTrace.localtrace_tracecCs<|dkr6|jj}|j}||f}|jj|dd|j|<|jS)Nrzrr)rrrr7rMr)rrrrr rgrOrrrrNs zTrace.localtrace_countcCst|j|j|j|j|jdS)N)r;r<r9r:)rr7r;r<rr)rrrrresultsVs z Trace.results)NN)r$r%r&rrrrrrrrrrrrrrrrrs 0  )   c stj}|jdddd|jdd}|jddd d d |jd d d dd |jddd dd |jddd dd |jd}|j}|jddd dd |jddd dd |jdddd|jd d!d"d|jd#d$d d%d |jd&d'd d(d |jd)d*d d+d |jd,d-}|jd.d/gd0d1|jd2d/gd3d1|jd4d5d6d7|jd8tjd9d7|j}|jrd:d;jt j f}t j j t jf|t j j t jf|fdd?|jD|_fd@d?|jD|_|jr|js|jdAt|j|jdB}|j|j|j|jSt|j|j|j|jgs*|jdC|jrL|jsB|jrL|jdD|jrh|j rh|jdE|jdkr~|jdF|jf|jt _ t j j!|jt j dG<t"|j|j|j|j|j|j|j|j|j#dH }yJt$|j}t%|j&|jdI}WdQRX|jdJdddK} |j'|| | WnPt(k rT} zt j)dLt j dG| fWYdd} ~ Xnt*k rhYnX|j+}|j,s|j|j|j|jdS)MNz --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.Z 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 tracingZFilterszCan 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).r ?zfile to run as main program)nargsr argumentszarguments to the programlibzpython{0.major}.{0.minor}cs4tjjtjj|}|jdjd}tjj|S)Nz$prefixz $exec_prefix)rr expanduser expandvarsr0r)s) _exec_prefix_prefixrrparse_ignore_dirszmain..parse_ignore_dircSs$g|]}|jdD] }|jqqS),)splitstrip)rrr"rrrrszmain..cs&g|]}|jtjD] }|qqSr)rrpathsep)rrr)rrrrsz-r/--report requires -f/--file)r;r<zLmust 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 --reportz3filename is missing: required with the main optionsr)rrrrr;r<rrr)rr$ __package__ __cached__zCannot run file %r because: %s)-argparseArgumentParser add_argumentZadd_argument_groupZadd_mutually_exclusive_groupZ REMAINDER parse_argsZ ignore_dirformatr version_inforrr\ base_prefixbase_exec_prefixZ ignore_moduleZreportr6errorrrrZmissingrcrdanyrriZ listfuncsZ trackcallsr rargvrUrrr=rrrrBexit SystemExitrZ no_report) parserZgrpZ_grpZoptsZrel_pathrtrlr|ZglobsrHr)rrrrmain\s                       (rr)N)!__doc____all__rrZrrerrr]rrr{r>Ztimerrr ImportErrorrr r rwr r+r4rrrrrYrrr$rrrr1sH  2/  M