cinap_lenrekadd hg and python4bb9e2215 years agoHistory
792 lines · 28.4 KB · Python
RawDownload
        finally:            if not self.donothing:                sys.settrace(None)                threading.settrace(None)     def runfunc(self, func, *args, **kw):        result = None        if not self.donothing:            sys.settrace(self.globaltrace)        try:            result = func(*args, **kw)        finally:            if not self.donothing:                sys.settrace(None)        return result     def file_module_function_of(self, frame):        code = frame.f_code        filename = code.co_filename        if filename:            modulename = modname(filename)        else:            modulename = None         funcname = code.co_name        clsname = None        if code in self._caller_cache:            if self._caller_cache[code] is not None:                clsname = self._caller_cache[code]        else:            self._caller_cache[code] = None            ## use of gc.get_referrers() was suggested by Michael Hudson            # all functions which refer to this code object            funcs = [f for f in gc.get_referrers(code)                         if hasattr(f, "func_doc")]            # require len(func) == 1 to avoid ambiguity caused by calls to            # new.function(): "In the face of ambiguity, refuse the            # temptation to guess."            if len(funcs) == 1:                dicts = [d for d in gc.get_referrers(funcs[0])                             if isinstance(d, dict)]                if len(dicts) == 1:                    classes = [c for c in gc.get_referrers(dicts[0])                                   if hasattr(c, "__bases__")]                    if len(classes) == 1:                        # ditto for new.classobj()                        clsname = str(classes[0])                        # cache the result - assumption is that new.* is                        # not called later to disturb this relationship                        # _caller_cache could be flushed if functions in                        # the new module get called.                        self._caller_cache[code] = clsname        if clsname is not None:            # final hack - module name shows up in str(cls), but we've already            # computed module name, so remove it            clsname = clsname.split(".")[1:]            clsname = ".".join(clsname)            funcname = "%s.%s" % (clsname, funcname)         return filename, modulename, funcname     def globaltrace_trackcallers(self, frame, why, arg):        """Handler for call events.         Adds information about who called who to the self._callers dict.        """        if why == 'call':            # XXX Should do a better job of identifying methods            this_func = self.file_module_function_of(frame)            parent_func = self.file_module_function_of(frame.f_back)            self._callers[(parent_func, this_func)] = 1     def globaltrace_countfuncs(self, frame, why, arg):        """Handler for call events.         Adds (filename, modulename, funcname) to the self._calledfuncs dict.        """        if why == 'call':            this_func = self.file_module_function_of(frame)            self._calledfuncs[this_func] = 1     def globaltrace_lt(self, frame, why, arg):        """Handler for call events.         If the code block being entered is to be ignored, returns `None',        else returns self.localtrace.        """        if why == 'call':            code = frame.f_code            filename = frame.f_globals.get('__file__', None)            if filename:                # XXX modname() doesn't work right for packages, so                # the ignore support won't work right for packages                modulename = modname(filename)                if modulename is not None:                    ignore_it = self.ignore.names(filename, modulename)                    if not ignore_it:                        if self.trace:                            print (" --- modulename: %s, funcname: %s"                                   % (modulename, code.co_name))                        return self.localtrace            else:                return None     def localtrace_trace_and_count(self, frame, why, arg):        if why == "line":            # record the file name and line number of every trace            filename = frame.f_code.co_filename            lineno = frame.f_lineno            key = filename, lineno            self.counts[key] = self.counts.get(key, 0) + 1             bname = os.path.basename(filename)            print "%s(%d): %s" % (bname, lineno,                                  linecache.getline(filename, lineno)),        return self.localtrace     def localtrace_trace(self, frame, why, arg):        if why == "line":            # record the file name and line number of every trace            filename = frame.f_code.co_filename            lineno = frame.f_lineno             bname = os.path.basename(filename)            print "%s(%d): %s" % (bname, lineno,                                  linecache.getline(filename, lineno)),        return self.localtrace     def localtrace_count(self, frame, why, arg):        if why == "line":            filename = frame.f_code.co_filename            lineno = frame.f_lineno            key = filename, lineno            self.counts[key] = self.counts.get(key, 0) + 1        return self.localtrace     def results(self):        return CoverageResults(self.counts, infile=self.infile,                               outfile=self.outfile,                               calledfuncs=self._calledfuncs,                               callers=self._callers) def _err_exit(msg):    sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))    sys.exit(1) def main(argv=None):    import getopt     if argv is None:        argv = sys.argv    try:        opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lT",                                        ["help", "version", "trace", "count",                                         "report", "no-report", "summary",                                         "file=", "missing",                                         "ignore-module=", "ignore-dir=",                                         "coverdir=", "listfuncs",                                         "trackcalls"])     except getopt.error, msg:        sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))        sys.stderr.write("Try `%s --help' for more information\n"                         % sys.argv[0])        sys.exit(1)     trace = 0    count = 0    report = 0    no_report = 0    counts_file = None    missing = 0    ignore_modules = []    ignore_dirs = []    coverdir = None    summary = 0    listfuncs = False    countcallers = False     for opt, val in opts:        if opt == "--help":            usage(sys.stdout)            sys.exit(0)         if opt == "--version":            sys.stdout.write("trace 2.0\n")            sys.exit(0)         if opt == "-T" or opt == "--trackcalls":            countcallers = True            continue         if opt == "-l" or opt == "--listfuncs":            listfuncs = True            continue         if opt == "-t" or opt == "--trace":            trace = 1            continue         if opt == "-c" or opt == "--count":            count = 1            continue         if opt == "-r" or opt == "--report":            report = 1            continue         if opt == "-R" or opt == "--no-report":            no_report = 1            continue         if opt == "-f" or opt == "--file":            counts_file = val            continue         if opt == "-m" or opt == "--missing":            missing = 1            continue         if opt == "-C" or opt == "--coverdir":            coverdir = val            continue         if opt == "-s" or opt == "--summary":            summary = 1            continue         if opt == "--ignore-module":            ignore_modules.append(val)            continue         if opt == "--ignore-dir":            for s in val.split(os.pathsep):                s = os.path.expandvars(s)                # should I also call expanduser? (after all, could use $HOME)                 s = s.replace("$prefix",                              os.path.join(sys.prefix, "lib",                                           "python" + sys.version[:3]))                s = s.replace("$exec_prefix",                              os.path.join(sys.exec_prefix, "lib",                                           "python" + sys.version[:3]))                s = os.path.normpath(s)                ignore_dirs.append(s)            continue         assert 0, "Should never get here"     if listfuncs and (count or trace):        _err_exit("cannot specify both --listfuncs and (--trace or --count)")     if not (count or trace or report or listfuncs or countcallers):        _err_exit("must specify one of --trace, --count, --report, "                  "--listfuncs, or --trackcalls")     if report and no_report:        _err_exit("cannot specify both --report and --no-report")     if report and not counts_file:        _err_exit("--report requires a --file")     if no_report and len(prog_argv) == 0:        _err_exit("missing name of file to run")     # everything is ready    if report:        results = CoverageResults(infile=counts_file, outfile=counts_file)        results.write_results(missing, summary=summary, coverdir=coverdir)    else:        sys.argv = prog_argv        progname = prog_argv[0]        sys.path[0] = os.path.split(progname)[0]         t = Trace(count, trace, countfuncs=listfuncs,                  countcallers=countcallers, ignoremods=ignore_modules,                  ignoredirs=ignore_dirs, infile=counts_file,                  outfile=counts_file)        try:            t.run('execfile(%r)' % (progname,))        except IOError, err:            _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err))        except SystemExit:            pass         results = t.results()         if not no_report:            results.write_results(missing, summary=summary, coverdir=coverdir) if __name__=='__main__':    main()

Lines 501–792 of 792. Previous lines

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t