def from_call( cls, func: "Callable[[], TResult]", when: "Literal['collect', 'setup', 'call', 'teardown']", reraise: Optional[Union[Type[BaseException], Tuple[Type[BaseException], ...]]] = None, ) -> "CallInfo[TResult]": excinfo = None start = timing.time() precise_start = timing.perf_counter() try: result: Optional[TResult] = func() except BaseException: excinfo = ExceptionInfo.from_current() if reraise is not None and isinstance(excinfo.value, reraise): raise result = None # use the perf counter precise_stop = timing.perf_counter() duration = precise_stop - precise_start stop = timing.time() return cls( start=start, stop=stop, duration=duration, when=when, result=result, excinfo=excinfo, )
def test_store() -> None: start_time = Timing.time() Timing.sleep(0.5) Timing.StopTimer() try: Timing.StopTimer() except Exception as e: print("!! Error:", e) assert True else: assert False Timing.sleep(1) Timing.StartTimer() Timing.sleep(0.5) assert int(Timing.time()) == int(start_time + 1) try: Timing.StartTimer() except Exception as e: print("!! Error:", e) assert True else: assert False # Reset the timer for other tests to start from clean Timing._paused_for = 0
def from_call(cls, func, when, reraise=None) -> "CallInfo": #: context of invocation: one of "setup", "call", #: "teardown", "memocollect" excinfo = None start = timing.time() precise_start = timing.perf_counter() try: result = func() except BaseException: excinfo = ExceptionInfo.from_current() if reraise is not None and excinfo.errisinstance(reraise): raise result = None # use the perf counter precise_stop = timing.perf_counter() duration = precise_stop - precise_start stop = timing.time() return cls( start=start, stop=stop, duration=duration, when=when, result=result, excinfo=excinfo, )
def pytest_sessionstart(self, session: "Session") -> None: self._session = session self._sessionstarttime = timing.time() if not self.showheader: return self.write_sep("=", "test session starts", bold=True) verinfo = platform.python_version() if not self.no_header: msg = f"platform {sys.platform} -- Python {verinfo}" pypy_version_info = getattr(sys, "pypy_version_info", None) if pypy_version_info: verinfo = ".".join(map(str, pypy_version_info[:3])) msg += "[pypy-{}-{}]".format(verinfo, pypy_version_info[3]) msg += ", pytest-{}, py-{}, pluggy-{}".format( _pytest._version.version, py.__version__, pluggy.__version__ ) if ( self.verbosity > 0 or self.config.option.debug or getattr(self.config.option, "pastebin", None) ): msg += " -- " + str(sys.executable) self.write_line(msg) lines = self.config.hook.pytest_report_header( config=self.config, startpath=self.startpath, startdir=self.startdir ) self._write_report_lines_from_hooks(lines)
def pytest_collection(self) -> None: if self.isatty: if self.config.option.verbose >= 0: self.write("collecting ... ", flush=True, bold=True) self._collect_report_last_write = timing.time() elif self.config.option.verbose >= 1: self.write("collecting ... ", flush=True, bold=True)
def pytest_sessionfinish(self) -> None: dirname = os.path.dirname(os.path.abspath(self.logfile)) if not os.path.isdir(dirname): os.makedirs(dirname) logfile = open(self.logfile, "w", encoding="utf-8") suite_stop_time = timing.time() suite_time_delta = suite_stop_time - self.suite_start_time numtests = ( self.stats["passed"] + self.stats["failure"] + self.stats["skipped"] + self.stats["error"] - self.cnt_double_fail_tests ) logfile.write('<?xml version="1.0" encoding="utf-8"?>') suite_node = Junit.testsuite( self._get_global_properties_node(), [x.to_xml() for x in self.node_reporters_ordered], name=self.suite_name, errors=str(self.stats["error"]), failures=str(self.stats["failure"]), skipped=str(self.stats["skipped"]), tests=str(numtests), time="%.3f" % suite_time_delta, timestamp=datetime.fromtimestamp(self.suite_start_time).isoformat(), hostname=platform.node(), ) logfile.write(Junit.testsuites([suite_node]).unicode(indent=0)) logfile.close()
def pytest_sessionfinish(self) -> None: dirname = os.path.dirname(os.path.abspath(self.logfile)) if not os.path.isdir(dirname): os.makedirs(dirname) logfile = open(self.logfile, "w", encoding="utf-8") suite_stop_time = timing.time() suite_time_delta = suite_stop_time - self.suite_start_time numtests = (self.stats["passed"] + self.stats["failure"] + self.stats["skipped"] + self.stats["error"] - self.cnt_double_fail_tests) logfile.write('<?xml version="1.0" encoding="utf-8"?>') suite_node = ET.Element( "testsuite", name=self.suite_name, errors=str(self.stats["error"]), failures=str(self.stats["failure"]), skipped=str(self.stats["skipped"]), tests=str(numtests), time="%.3f" % suite_time_delta, timestamp=datetime.fromtimestamp( self.suite_start_time).isoformat(), hostname=platform.node(), ) global_properties = self._get_global_properties_node() if global_properties is not None: suite_node.append(global_properties) for node_reporter in self.node_reporters_ordered: suite_node.append(node_reporter.to_xml()) testsuites = ET.Element("testsuites") testsuites.append(suite_node) logfile.write(ET.tostring(testsuites, encoding="unicode")) logfile.close()
def report_collect(self, final: bool = False) -> None: if self.config.option.verbose < 0: return if not final: # Only write "collecting" report every 0.5s. t = timing.time() if (self._collect_report_last_write is not None and self._collect_report_last_write > t - REPORT_COLLECTING_RESOLUTION): return self._collect_report_last_write = t errors = len(self.stats.get("error", [])) skipped = len(self.stats.get("skipped", [])) deselected = len(self.stats.get("deselected", [])) selected = self._numcollected - errors - skipped - deselected line = "collected " if final else "collecting " line += (str(self._numcollected) + " item" + ("" if self._numcollected == 1 else "s")) if errors: line += " / %d error%s" % (errors, "s" if errors != 1 else "") if deselected: line += " / %d deselected" % deselected if skipped: line += " / %d skipped" % skipped if self._numcollected > selected > 0: line += " / %d selected" % selected if self.isatty: self.rewrite(line, bold=True, erase=True) if final: self.write("\n") else: self.write_line(line)
def from_call( cls, func: "Callable[[], TResult]", when: "Literal['collect', 'setup', 'call', 'teardown']", reraise: Optional[ Union[Type[BaseException], Tuple[Type[BaseException], ...]] ] = None, ) -> "CallInfo[TResult]": """Call func, wrapping the result in a CallInfo. :param func: The function to call. Called without arguments. :param when: The phase in which the function is called. :param reraise: Exception or exceptions that shall propagate if raised by the function, instead of being wrapped in the CallInfo. """ excinfo = None start = timing.time() precise_start = timing.perf_counter() try: result: Optional[TResult] = func() except BaseException: excinfo = ExceptionInfo.from_current() if reraise is not None and isinstance(excinfo.value, reraise): raise result = None # use the perf counter precise_stop = timing.perf_counter() duration = precise_stop - precise_start stop = timing.time() return cls( start=start, stop=stop, duration=duration, when=when, result=result, excinfo=excinfo, _ispytest=True, )
def summary_stats(self) -> None: if self.verbosity < -1: return session_duration = timing.time() - self._sessionstarttime (parts, main_color) = self.build_summary_stats_line() line_parts = [] display_sep = self.verbosity >= 0 if display_sep: fullwidth = self._tw.fullwidth for text, markup in parts: with_markup = self._tw.markup(text, **markup) if display_sep: fullwidth += len(with_markup) - len(text) line_parts.append(with_markup) msg = ", ".join(line_parts) main_markup = {main_color: True} duration = " in {}".format(format_session_duration(session_duration)) duration_with_markup = self._tw.markup(duration, **main_markup) if display_sep: fullwidth += len(duration_with_markup) - len(duration) msg += duration_with_markup if display_sep: markup_for_end_sep = self._tw.markup("", **main_markup) if markup_for_end_sep.endswith("\x1b[0m"): markup_for_end_sep = markup_for_end_sep[:-4] fullwidth += len(markup_for_end_sep) msg += markup_for_end_sep if display_sep: self.write_sep("=", msg, fullwidth=fullwidth, **main_markup) else: self.write_line(msg, **main_markup)
def pytest_sessionstart(self) -> None: self.suite_start_time = timing.time()