Best Python code snippet using pytest
runner.py
Source:runner.py
...195 when=self.when, value=value, status=status196 )197def pytest_runtest_makereport(item, call):198 return TestReport.from_item_and_call(item, call)199def pytest_make_collect_report(collector):200 call = CallInfo.from_call(lambda: list(collector.collect()), "collect")201 longrepr = None202 if not call.excinfo:203 outcome = "passed"204 else:205 from _pytest import nose206 skip_exceptions = (Skipped,) + nose.get_skip_exceptions()207 if call.excinfo.errisinstance(skip_exceptions):208 outcome = "skipped"209 r = collector._repr_failure_py(call.excinfo, "line").reprcrash210 longrepr = (str(r.path), r.lineno, r.message)211 else:212 outcome = "failed"213 errorinfo = collector.repr_failure(call.excinfo)214 if not hasattr(errorinfo, "toterminal"):215 errorinfo = CollectErrorRepr(errorinfo)216 longrepr = errorinfo217 rep = CollectReport(218 collector.nodeid, outcome, longrepr, getattr(call, "result", None)219 )220 rep.call = call # see collect_one_node221 return rep222class SetupState:223 """ shared state for setting up/tearing down test items or collectors. """224 def __init__(self):225 self.stack = []226 self._finalizers = {}227 def addfinalizer(self, finalizer, colitem):228 """ attach a finalizer to the given colitem.229 if colitem is None, this will add a finalizer that230 is called at the end of teardown_all().231 """232 assert colitem and not isinstance(colitem, tuple)233 assert callable(finalizer)234 # assert colitem in self.stack # some unit tests don't setup stack :/235 self._finalizers.setdefault(colitem, []).append(finalizer)236 def _pop_and_teardown(self):237 colitem = self.stack.pop()238 self._teardown_with_finalization(colitem)239 def _callfinalizers(self, colitem):240 finalizers = self._finalizers.pop(colitem, None)241 exc = None242 while finalizers:243 fin = finalizers.pop()244 try:245 fin()246 except TEST_OUTCOME:247 # XXX Only first exception will be seen by user,248 # ideally all should be reported.249 if exc is None:250 exc = sys.exc_info()251 if exc:252 _, val, tb = exc253 raise val.with_traceback(tb)254 def _teardown_with_finalization(self, colitem):255 self._callfinalizers(colitem)256 if hasattr(colitem, "teardown"):257 colitem.teardown()258 for colitem in self._finalizers:259 assert (260 colitem is None or colitem in self.stack or isinstance(colitem, tuple)261 )262 def teardown_all(self):263 while self.stack:264 self._pop_and_teardown()265 for key in list(self._finalizers):266 self._teardown_with_finalization(key)267 assert not self._finalizers268 def teardown_exact(self, item, nextitem):269 needed_collectors = nextitem and nextitem.listchain() or []270 self._teardown_towards(needed_collectors)271 def _teardown_towards(self, needed_collectors):272 exc = None273 while self.stack:274 if self.stack == needed_collectors[: len(self.stack)]:275 break276 try:277 self._pop_and_teardown()278 except TEST_OUTCOME:279 # XXX Only first exception will be seen by user,280 # ideally all should be reported.281 if exc is None:282 exc = sys.exc_info()283 if exc:284 _, val, tb = exc285 raise val.with_traceback(tb)286 def prepare(self, colitem):287 """ setup objects along the collector chain to the test-method288 and teardown previously setup objects."""289 needed_collectors = colitem.listchain()290 self._teardown_towards(needed_collectors)291 # check if the last collection node has raised an error292 for col in self.stack:293 if hasattr(col, "_prepare_exc"):294 _, val, tb = col._prepare_exc295 raise val.with_traceback(tb)296 for col in needed_collectors[len(self.stack) :]:297 self.stack.append(col)298 try:299 col.setup()300 except TEST_OUTCOME:301 col._prepare_exc = sys.exc_info()302 raise303def collect_one_node(collector):304 ihook = collector.ihook305 ihook.pytest_collectstart(collector=collector)306 rep = ihook.pytest_make_collect_report(collector=collector)307 call = rep.__dict__.pop("call", None)308 if call and check_interactive_exception(call, rep):309 ihook.pytest_exception_interact(node=collector, call=call, report=rep)...
hookspec.py
Source:hookspec.py
...26def pytest_collectreport(report):27 """ collector finished collecting. """28def pytest_deselected(items):29 """ called for test items deselected by keyword. """30def pytest_make_collect_report(collector):31 """ perform a collection and return a collection. """ 32pytest_make_collect_report.firstresult = True33# XXX rename to item_collected()? meaning in distribution context? 34def pytest_itemstart(item, node=None):35 """ test item gets collected. """36# -------------------------------------------------------------------------37# Python test function related hooks38# -------------------------------------------------------------------------39def pytest_pycollect_makeitem(collector, name, obj):40 """ return custom item/collector for a python object in a module, or None. """41pytest_pycollect_makeitem.firstresult = True42def pytest_pyfunc_call(pyfuncitem):43 """ perform function call to the with the given function arguments. """ 44pytest_pyfunc_call.firstresult = True...
integration.py
Source:integration.py
...19 class MyClass:20 pass21 """)22 # this hook finds funcarg factories23 rep = modcol.ihook.pytest_make_collect_report(collector=modcol)24 clscol = rep.result[0]25 clscol.obj = lambda arg1: None26 clscol.funcargs = {}27 pytest._fillfuncargs(clscol)28 assert clscol.funcargs['arg1'] == 4229 def test_autouse_fixture(self, testdir): # rough jstests usage30 testdir.makeconftest("""31 import pytest32 def pytest_pycollect_makeitem(collector, name, obj):33 if name == "MyClass":34 return MyCollector(name, parent=collector)35 class MyCollector(pytest.Collector):36 def reportinfo(self):37 return self.fspath, 3, "xyz"38 """)39 modcol = testdir.getmodulecol("""40 import pytest41 @pytest.fixture(autouse=True)42 def hello():43 pass44 def pytest_funcarg__arg1(request):45 return 4246 class MyClass:47 pass48 """)49 # this hook finds funcarg factories50 rep = modcol.ihook.pytest_make_collect_report(collector=modcol)51 clscol = rep.result[0]52 clscol.obj = lambda: None53 clscol.funcargs = {}54 pytest._fillfuncargs(clscol)55 assert not clscol.funcargs56class TestMockDecoration:57 def test_wrapped_getfuncargnames(self):58 from _pytest.python import getfuncargnames59 def wrap(f):60 def func():61 pass62 func.__wrapped__ = f63 return func64 @wrap...
plugin.py
Source:plugin.py
...52 self.durations["pytest_runtestloop"] = end - start53 # === Reporting Hooks ===54 # https://docs.pytest.org/en/stable/reference.html#reporting-hooks55 @pytest.hookimpl(hookwrapper=True, tryfirst=True)56 def pytest_make_collect_report(self, collector):57 """Despite being a Reporting hook, this fires during the Collection phase58 and can find `test_*.py` level import slowdowns."""59 start = time.time()60 yield61 end = time.time()62 self.durations[f"pytest_make_collect_report\t{collector.nodeid}"] = end - start63 def pytest_terminal_summary(self, terminalreporter, exitstatus, config):64 """Where we emit our report."""65 min_duration = config.option.minimum_duration_in_ms66 terminalreporter.section("pytest-execution-timer")67 terminalreporter.write_line(68 f"Durations of pytest phases in seconds (min {min_duration}ms):"69 )70 for key, value in self.durations.items():...
Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.
Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.
https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP
Get 100 minutes of automation test minutes FREE!!