How to use pytest_warning_recorded method in Pytest

Best Python code snippet using pytest

plugin.py

Source:plugin.py Github

copy

Full Screen

...140 self.context["tests"].append(testrun)141 del self._active_tests[nodeid]142 # the pytest_warning_recorded hook was introduced in pytest 6.0143 if hasattr(_pytest.hookspec, "pytest_warning_recorded"):144 def pytest_warning_recorded(self, warning_message):145 self.context["warnings"].append(warning_message)146 else:147 def pytest_warning_captured(self, warning_message):148 self.context["warnings"].append(warning_message)149 def pytest_sessionfinish(self, session):150 self.context["ended"] = time.time()151 logging.getLogger().removeHandler(self._log_handler)152 self.config.hook.pytest_reporter_save(config=self.config)153 def pytest_reporter_save(self, config):154 # Create a list of all directories that may contain templates155 dirs_list = config.hook.pytest_reporter_template_dirs(config=config)156 dirs = list(chain.from_iterable(dirs_list))157 config.hook.pytest_reporter_loader(dirs=dirs, config=config)158 config.hook.pytest_reporter_context(context=self.context, config=config)...

Full Screen

Full Screen

warnings.py

Source:warnings.py Github

copy

Full Screen

1import re2import sys3import warnings4from contextlib import contextmanager5from functools import lru_cache6from typing import Generator7from typing import Optional8from typing import Tuple9import pytest10from _pytest.compat import TYPE_CHECKING11from _pytest.config import Config12from _pytest.config.argparsing import Parser13from _pytest.main import Session14from _pytest.nodes import Item15from _pytest.terminal import TerminalReporter16if TYPE_CHECKING:17 from typing import Type18 from typing_extensions import Literal19@lru_cache(maxsize=50)20def _parse_filter(21 arg: str, *, escape: bool22) -> "Tuple[str, str, Type[Warning], str, int]":23 """Parse a warnings filter string.24 This is copied from warnings._setoption, but does not apply the filter,25 only parses it, and makes the escaping optional.26 """27 parts = arg.split(":")28 if len(parts) > 5:29 raise warnings._OptionError("too many fields (max 5): {!r}".format(arg))30 while len(parts) < 5:31 parts.append("")32 action_, message, category_, module, lineno_ = [s.strip() for s in parts]33 action = warnings._getaction(action_) # type: str # type: ignore[attr-defined]34 category = warnings._getcategory(35 category_36 ) # type: Type[Warning] # type: ignore[attr-defined]37 if message and escape:38 message = re.escape(message)39 if module and escape:40 module = re.escape(module) + r"\Z"41 if lineno_:42 try:43 lineno = int(lineno_)44 if lineno < 0:45 raise ValueError46 except (ValueError, OverflowError) as e:47 raise warnings._OptionError("invalid lineno {!r}".format(lineno_)) from e48 else:49 lineno = 050 return (action, message, category, module, lineno)51def pytest_addoption(parser: Parser) -> None:52 group = parser.getgroup("pytest-warnings")53 group.addoption(54 "-W",55 "--pythonwarnings",56 action="append",57 help="set which warnings to report, see -W option of python itself.",58 )59 parser.addini(60 "filterwarnings",61 type="linelist",62 help="Each line specifies a pattern for "63 "warnings.filterwarnings. "64 "Processed after -W/--pythonwarnings.",65 )66def pytest_configure(config: Config) -> None:67 config.addinivalue_line(68 "markers",69 "filterwarnings(warning): add a warning filter to the given test. "70 "see https://docs.pytest.org/en/stable/warnings.html#pytest-mark-filterwarnings ",71 )72@contextmanager73def catch_warnings_for_item(74 config: Config,75 ihook,76 when: "Literal['config', 'collect', 'runtest']",77 item: Optional[Item],78) -> Generator[None, None, None]:79 """80 Context manager that catches warnings generated in the contained execution block.81 ``item`` can be None if we are not in the context of an item execution.82 Each warning captured triggers the ``pytest_warning_recorded`` hook.83 """84 cmdline_filters = config.getoption("pythonwarnings") or []85 inifilters = config.getini("filterwarnings")86 with warnings.catch_warnings(record=True) as log:87 # mypy can't infer that record=True means log is not None; help it.88 assert log is not None89 if not sys.warnoptions:90 # if user is not explicitly configuring warning filters, show deprecation warnings by default (#2908)91 warnings.filterwarnings("always", category=DeprecationWarning)92 warnings.filterwarnings("always", category=PendingDeprecationWarning)93 warnings.filterwarnings("error", category=pytest.PytestDeprecationWarning)94 # filters should have this precedence: mark, cmdline options, ini95 # filters should be applied in the inverse order of precedence96 for arg in inifilters:97 warnings.filterwarnings(*_parse_filter(arg, escape=False))98 for arg in cmdline_filters:99 warnings.filterwarnings(*_parse_filter(arg, escape=True))100 nodeid = "" if item is None else item.nodeid101 if item is not None:102 for mark in item.iter_markers(name="filterwarnings"):103 for arg in mark.args:104 warnings.filterwarnings(*_parse_filter(arg, escape=False))105 yield106 for warning_message in log:107 ihook.pytest_warning_captured.call_historic(108 kwargs=dict(109 warning_message=warning_message,110 when=when,111 item=item,112 location=None,113 )114 )115 ihook.pytest_warning_recorded.call_historic(116 kwargs=dict(117 warning_message=warning_message,118 nodeid=nodeid,119 when=when,120 location=None,121 )122 )123def warning_record_to_str(warning_message: warnings.WarningMessage) -> str:124 """Convert a warnings.WarningMessage to a string."""125 warn_msg = warning_message.message126 msg = warnings.formatwarning(127 str(warn_msg),128 warning_message.category,129 warning_message.filename,130 warning_message.lineno,131 warning_message.line,132 )133 return msg134@pytest.hookimpl(hookwrapper=True, tryfirst=True)135def pytest_runtest_protocol(item: Item) -> Generator[None, None, None]:136 with catch_warnings_for_item(137 config=item.config, ihook=item.ihook, when="runtest", item=item138 ):139 yield140@pytest.hookimpl(hookwrapper=True, tryfirst=True)141def pytest_collection(session: Session) -> Generator[None, None, None]:142 config = session.config143 with catch_warnings_for_item(144 config=config, ihook=config.hook, when="collect", item=None145 ):146 yield147@pytest.hookimpl(hookwrapper=True)148def pytest_terminal_summary(149 terminalreporter: TerminalReporter,150) -> Generator[None, None, None]:151 config = terminalreporter.config152 with catch_warnings_for_item(153 config=config, ihook=config.hook, when="config", item=None154 ):155 yield156@pytest.hookimpl(hookwrapper=True)157def pytest_sessionfinish(session: Session) -> Generator[None, None, None]:158 config = session.config159 with catch_warnings_for_item(160 config=config, ihook=config.hook, when="config", item=None161 ):162 yield163def _issue_warning_captured(warning: Warning, hook, stacklevel: int) -> None:164 """165 This function should be used instead of calling ``warnings.warn`` directly when we are in the "configure" stage:166 at this point the actual options might not have been set, so we manually trigger the pytest_warning_recorded167 hook so we can display these warnings in the terminal. This is a hack until we can sort out #2891.168 :param warning: the warning instance.169 :param hook: the hook caller170 :param stacklevel: stacklevel forwarded to warnings.warn171 """172 with warnings.catch_warnings(record=True) as records:173 warnings.simplefilter("always", type(warning))174 warnings.warn(warning, stacklevel=stacklevel)175 frame = sys._getframe(stacklevel - 1)176 location = frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name177 hook.pytest_warning_captured.call_historic(178 kwargs=dict(179 warning_message=records[0], when="config", item=None, location=location180 )181 )182 hook.pytest_warning_recorded.call_historic(183 kwargs=dict(184 warning_message=records[0], when="config", nodeid="", location=location185 )...

Full Screen

Full Screen

Pytest Tutorial

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.

Chapters

  1. What is pytest
  2. Pytest installation: Want to start pytest from scratch? See how to install and configure pytest for Python automation testing.
  3. Run first test with pytest framework: Follow this step-by-step tutorial to write and run your first pytest script.
  4. Parallel testing with pytest: A hands-on guide to parallel testing with pytest to improve the scalability of your test automation.
  5. Generate pytest reports: Reports make it easier to understand the results of pytest-based test runs. Learn how to generate pytest reports.
  6. Pytest Parameterized tests: Create and run your pytest scripts while avoiding code duplication and increasing test coverage with parameterization.
  7. Pytest Fixtures: Check out how to implement pytest fixtures for your end-to-end testing needs.
  8. Execute Multiple Test Cases: Explore different scenarios for running multiple test cases in pytest from a single file.
  9. Stop Test Suite after N Test Failures: See how to stop your test suite after n test failures in pytest using the @pytest.mark.incremental decorator and maxfail command-line option.

YouTube

Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.

https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP

Run Pytest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful