### Example of Ignored Setup File Source: https://docs.pytest.org/en/stable/example/pythoncollection.html This file is designed to raise an exception if imported, and is typically ignored during test collection. ```python # content of setup.py 0 / 0 # will raise exception if imported ``` -------------------------------- ### FDCaptureBase Start Method Source: https://docs.pytest.org/en/stable/_modules/_pytest/capture.html Starts capturing I/O on the target file descriptor, redirecting it to the temporary file. ```python def start(self) -> None: """Start capturing on targetfd using memorized tmpfile.""" self._assert_state("start", ("initialized",)) os.dup2(self.tmpfile.fileno(), self.targetfd) self.syscapture.start() self._state = "started" ``` -------------------------------- ### Install Tox for Running Tests Source: https://docs.pytest.org/en/stable/contributing.html Install the tox tool, which is used to automate the setup of virtual environments and run tests for Pytest. ```bash $ pip install tox ``` -------------------------------- ### FunctionDefinition Class setup Method Source: https://docs.pytest.org/en/stable/reference/reference.html The setup method in FunctionDefinition also executes the underlying test function. ```python setup() ``` -------------------------------- ### Drop to PDB at Test Start Source: https://docs.pytest.org/en/stable/how-to/failures.html Use the `--trace` command-line option to enter the pdb prompt at the beginning of every test. This is useful for debugging test setup or initial execution flow. ```bash pytest --trace ``` -------------------------------- ### Example of testing against an installed package version Source: https://docs.pytest.org/en/stable/explanation/pythonpath.html When using '--import-mode=append', tests can run against an installed version of a package. This is contrasted with 'prepend' mode, which might pick up a local version. ```python testing/__init__.py testing/test_pkg_under_test.py pkg_under_test/ ``` -------------------------------- ### Copying and Running Example Tests with pytester Source: https://docs.pytest.org/en/stable/how-to/writing_plugins.html Demonstrates copying an example test file into the `pytester` environment and running it. This is useful for testing complex plugins or abstracting logic. ```python # content of test_example.py def test_plugin(pytester): pytester.copy_example("test_example.py") pytester.runpytest("-k", "test_example") def test_example(): pass ``` -------------------------------- ### Fixture Setup Execution Source: https://docs.pytest.org/en/stable/_modules/_pytest/fixtures.html Executes the setup for a fixture, resolving arguments and calling the fixture function. Handles potential skips or errors during execution. ```python def pytest_fixture_setup( fixturedef: FixtureDef[FixtureValue], request: SubRequest ) -> FixtureValue: """Execution of fixture setup.""" kwargs = {} for argname in fixturedef.argnames: kwargs[argname] = request.getfixturevalue(argname) fixturefunc = resolve_fixture_function(fixturedef, request) my_cache_key = fixturedef.cache_key(request) if inspect.isasyncgenfunction(fixturefunc) or inspect.iscoroutinefunction( fixturefunc ): auto_str = " with autouse=True" if fixturedef._autouse else "" fail( f"{request.node.name!r} requested an async fixture {request.fixturename!r}{auto_str}, " "with no plugin or hook that handled it. This is an error, as pytest does not natively support it.\n" "See: https://docs.pytest.org/en/stable/deprecations.html#sync-test-depending-on-async-fixture", pytrace=False, ) try: result = call_fixture_func(fixturefunc, request, kwargs) except TEST_OUTCOME as e: if isinstance(e, skip.Exception): # The test requested a fixture which caused a skip. # Don't show the fixture as the skip location, as then the user # wouldn't know which test skipped. e._use_item_location = True fixturedef.cached_result = (None, my_cache_key, (e, e.__traceback__)) raise fixturedef.cached_result = (result, my_cache_key, None) return result ``` -------------------------------- ### Parametrized Fixtures with Different Scopes Source: https://docs.pytest.org/en/stable/how-to/fixtures.html This example demonstrates how to use parametrized fixtures with module and function scopes. It includes print statements to visualize the setup and teardown flow of fixtures during test execution. ```python import pytest @pytest.fixture(scope="module", params=["mod1", "mod2"]) def modarg(request): param = request.param print(" SETUP modarg", param) yield param print(" TEARDOWN modarg", param) @pytest.fixture(scope="function", params=[1, 2]) def otherarg(request): param = request.param print(" SETUP otherarg", param) yield param print(" TEARDOWN otherarg", param) def test_0(otherarg): print(" RUN test0 with otherarg", otherarg) def test_1(modarg): print(" RUN test1 with modarg", modarg) def test_2(otherarg, modarg): print(f" RUN test2 with otherarg {otherarg} and modarg {modarg}") ``` -------------------------------- ### Example Test File for Custom Naming Source: https://docs.pytest.org/en/stable/example/pythoncollection.html An example Python file demonstrating custom naming conventions for test classes and methods. ```python # content of check_myapp.py class CheckMyApp: def simple_check(self): pass def complex_check(self): pass ``` -------------------------------- ### Pytest Function Setup Source: https://docs.pytest.org/en/stable/_modules/_pytest/python.html Performs the setup for a Pytest function, including filling fixtures. ```python def setup(self) -> None: self._request._fillfixtures() ``` -------------------------------- ### Install Pytest using easy_install Source: https://docs.pytest.org/en/stable/announce/release-2.0.0.html Install or upgrade Pytest to the latest version using easy_install. ```bash easy_install -U pytest ``` -------------------------------- ### Copy Example File/Directory with Pytest Pytester Source: https://docs.pytest.org/en/stable/_modules/_pytest/pytester.html Copies a file or directory from the project's example directory into the test directory. Raises a ValueError if pytester_example_dir is not set. Raises LookupError if the example is not found. ```python pytester.copy_example("my_file.py") ``` -------------------------------- ### Install Project in Development Mode Source: https://docs.pytest.org/en/stable/how-to/existingtestsuite.html Use this command to install your project in development mode, allowing for live code edits while running tests. This is typically done in the repository's root directory after navigating into it. ```bash cd pip install -e . # Environment dependent alternatives include # 'python setup.py develop' and 'conda develop' ``` -------------------------------- ### Set Up Virtual Environment and Editable Install Source: https://docs.pytest.org/en/stable/contributing.html Create a Python virtual environment and install Pytest in editable mode with the 'dev' extra. This allows direct editing of files and running pytest normally. ```bash $ python3 -m venv .venv $ source .venv/bin/activate # Linux $ .venv/Scripts/activate.bat # Windows $ pip install -e ".[dev]" ``` -------------------------------- ### Install pytest 7.0.0rc1 Source: https://docs.pytest.org/en/stable/announce/release-7.0.0rc1.html Use this command to install the prerelease version of pytest. This is not intended for production use. ```bash pip install pytest==7.0.0rc1 ``` -------------------------------- ### SysCaptureBase Start and Done Operations Source: https://docs.pytest.org/en/stable/_modules/_pytest/capture.html Methods to start and finalize the capture process, managing the redirection of system streams. ```python def start(self) -> None: self._assert_state("start", ("initialized",)) setattr(sys, self.name, self.tmpfile) self._state = "started" def done(self) -> None: self._assert_state("done", ("initialized", "started", "suspended", "done")) if self._state == "done": return setattr(sys, self.name, self._old) del self._old self.tmpfile.close() self._state = "done" ``` -------------------------------- ### Log Test Start with Path Info Source: https://docs.pytest.org/en/stable/_modules/_pytest/terminal.html Logs the start of a test item, including file path and line number if configured. Ensures the path is displayed before the test begins. ```python def pytest_runtest_logstart( self, nodeid: str, location: tuple[str, int | None, str] ) -> None: fspath, lineno, domain = location # Ensure that the path is printed before the # 1st test of a module starts running. if self.showlongtestinfo: line = self._locationline(nodeid, fspath, lineno, domain) self.write_ensure_prefix(line, "") self.flush() elif self.showfspath: self.write_fspath_result(nodeid, "") self.flush() ``` -------------------------------- ### Configuring pytester Example Directory Source: https://docs.pytest.org/en/stable/how-to/writing_plugins.html Sets the `pytester_example_dir` in `pytest.toml` to specify the location of example files for `pytester.copy_example`. This is necessary for abstracting test logic. ```toml # content of pytest.toml [pytest] pytester_example_dir = "." ``` -------------------------------- ### Install argcomplete Source: https://docs.pytest.org/en/stable/how-to/bash-completion.html Install the argcomplete library using pip. Ensure you are using a version compatible with pytest's requirements. ```bash sudo pip install 'argcomplete>=0.5.7' ``` -------------------------------- ### pytest_runtest_setup Source: https://docs.pytest.org/en/stable/_modules/_pytest/hookspec.html Hook called to perform the setup phase for a test item. The default implementation handles fixture resolution and item-specific setup procedures. ```APIDOC ## pytest_runtest_setup(item: Item) -> None ### Description Called to perform the setup phase for a test item. The default implementation handles fixture resolution and item-specific setup. ### Parameters * **item** (Item) - The test item requiring setup. ``` -------------------------------- ### Build Documentation Locally Source: https://docs.pytest.org/en/stable/contributing.html Use this command to build the documentation locally. The output will be available in the specified directory. ```bash $ tox -e docs ``` -------------------------------- ### Pytest Session Start Fixture Manager Initialization Source: https://docs.pytest.org/en/stable/_modules/_pytest/fixtures.html Initializes the fixture manager when a pytest session starts. This is a core setup step for fixture handling. ```python def pytest_sessionstart(session: Session) -> None: session._fixturemanager = FixtureManager(session) ``` -------------------------------- ### Get Relative Line Number Source: https://docs.pytest.org/en/stable/_modules/_pytest/_code/code.html Calculates the relative line number of the traceback entry with respect to the start of the code block. ```python return self.lineno - self.frame.code.firstlineno ``` -------------------------------- ### Run tests matching 'http' or 'quick' Source: https://docs.pytest.org/en/stable/example/markers.html Combine keywords using 'or' with the -k option to select tests matching either keyword. This example runs tests related to 'http' or 'quick'. ```bash $ pytest -k "http or quick" -v =========================== test session starts ============================ platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python cachedir: .pytest_cache rootdir: /home/sweet/project collecting ... collected 4 items / 2 deselected / 2 selected test_server.py::test_send_http PASSED [ 50%] test_server.py::test_something_quick PASSED [100%] ===================== 2 passed, 2 deselected in 0.12s ====================== ``` -------------------------------- ### Get Code Object First Line Number Source: https://docs.pytest.org/en/stable/_modules/_pytest/_code/code.html Retrieve the starting line number of the code object, adjusted to be zero-based. ```python code_wrapper.firstlineno ``` -------------------------------- ### LogCaptureFixture Get Records Method Source: https://docs.pytest.org/en/stable/_modules/_pytest/logging.html Retrieves captured log records for a specific test phase (setup, call, or teardown). ```python @property def get_records( self, when: Literal["setup", "call", "teardown"] ) -> list[logging.LogRecord]: """Get the logging records for one of the possible test phases. :param when: Which test phase to obtain the records from. Valid values are: "setup", "call" and "teardown". :returns: The list of captured records at the given stage. .. versionadded:: 3.4 """ return self._item.stash[caplog_records_key].get(when, []) ``` -------------------------------- ### Package Initialization and Setup Source: https://docs.pytest.org/en/stable/_modules/_pytest/python.html Initializes a Python package collector and calls setup_module if available in the __init__.py. It also registers a finalizer for teardown_module. ```python init_mod = importtestmodule(self.path / "__init__.py", self.config) # Not using fixtures to call setup_module here because autouse fixtures # from packages are not called automatically (#4085). setup_module = _get_first_non_fixture_func( init_mod, ("setUpModule", "setup_module") ) if setup_module is not None: _call_with_optional_argument(setup_module, init_mod) teardown_module = _get_first_non_fixture_func( init_mod, ("tearDownModule", "teardown_module") ) if teardown_module is not None: func = partial(_call_with_optional_argument, teardown_module, init_mod) self.addfinalizer(func) ``` -------------------------------- ### Example pytest command with arguments Source: https://docs.pytest.org/en/stable/reference/customize.html When arguments are provided, pytest determines the common ancestor directory for these paths to start its search for configuration files. ```bash pytest path/to/testdir path/other/ ``` -------------------------------- ### Example conftest.py in tests/ Source: https://docs.pytest.org/en/stable/reference/fixtures.html Defines a simple fixture named 'order' in the top-level tests directory. ```python import pytest @pytest.fixture def order(): return [] ``` -------------------------------- ### Dynamically Getting Fixture Value Source: https://docs.pytest.org/en/stable/_modules/_pytest/fixtures.html Dynamically run and retrieve the value of a named fixture. Recommended to use during setup or run phase, avoid teardown. ```python def getfixturevalue(self, argname: str) -> Any: """Dynamically run a named fixture function. Declaring fixtures via function argument is recommended where possible. But if you can only decide whether to use another fixture at test setup time, you may use this function to retrieve it inside a fixture or test function body. This method can be used during the test setup phase or the test run phase. Avoid using it during the teardown phase. .. versionchanged:: 9.1 Calling ``request.getfixturevalue()`` during teardown to request a fixture that was not already requested :ref:`is deprecated `. :param argname: The fixture name. :raises pytest.FixtureLookupError: If the given fixture could not be found. """ # Note that in addition to the use case described in the docstring, # getfixturevalue() is also called by pytest itself during item and fixture # setup to evaluate the fixtures that are requested statically # (using function parameters, autouse, etc). pass ``` -------------------------------- ### Example Test File with Platform Markers Source: https://docs.pytest.org/en/stable/example/markers.html This test file demonstrates how to apply platform-specific markers to tests. It includes tests for 'darwin', 'linux', 'win32', and a test that runs everywhere. ```python # content of test_plat.py import pytest @pytest.mark.darwin def test_if_apple_is_evil(): pass @pytest.mark.linux def test_if_linux_works(): pass @pytest.mark.win32 def test_if_win32_crashes(): pass def test_runs_everywhere(): pass ``` -------------------------------- ### Initialize SetupState for Pytest Session Source: https://docs.pytest.org/en/stable/_modules/_pytest/runner.html Initializes the _setupstate attribute on the pytest session object at the start of a test session. This is used to manage setup and teardown exactness. ```python def pytest_sessionstart(session: Session) -> None: session._setupstate = SetupState() ``` -------------------------------- ### Get Column Number (Python 3.11+) Source: https://docs.pytest.org/en/stable/_modules/_pytest/_code/code.html Retrieves the starting byte offset (column number) of the expression in the traceback entry. Only available on Python 3.11 and later. ```python return self.get_python_framesummary().colno ``` -------------------------------- ### Test File Example 2 Source: https://docs.pytest.org/en/stable/example/customdirectory.html Another simple test file that will be collected if listed in the `manifest.json`. ```python from __future__ import annotations def test_2(): pass ``` -------------------------------- ### Pytest Indirect Parametrization Example Source: https://docs.pytest.org/en/stable/example/parametrize.html Demonstrates indirect parametrization where a fixture receives values before passing them to a test. Use this when fixture setup is expensive and should run at test time. ```python import pytest @pytest.fixture def fixt(request): return request.param * 3 @pytest.mark.parametrize("fixt", ["a", "b"], indirect=True) def test_indirect(fixt): assert len(fixt) == 3 ``` -------------------------------- ### Support for setUpModule/tearDownModule Source: https://docs.pytest.org/en/stable/announce/release-2.4.0.html Adds support for detecting and executing `setUpModule` and `tearDownModule` functions, enabling module-level setup and teardown logic. ```python def setUpModule(): # Module setup code pass def tearDownModule(): # Module teardown code pass ``` -------------------------------- ### Getting Fixture Closure Source: https://docs.pytest.org/en/stable/_modules/_pytest/fixtures.html Collects the closure of all fixtures, starting with a given set of initial fixture names. It also returns a mapping from argument names to their corresponding fixture definitions. ```python def getfixtureclosure( self, parentnode: nodes.Node, initialnames: tuple[str, ...], ignore_args: AbstractSet[str], ) -> tuple[list[str], dict[str, Sequence[FixtureDef[Any]]]]: # Collect the closure of all fixtures, starting with the given # fixturenames as the initial set. As we have to visit all # factory definitions anyway, we also return an arg2fixturedefs # mapping so that the caller can reuse it and does not have # to re-discover fixturedefs again for each fixturename # (discovering matching fixtures for a given name/node is expensive). arg2fixturedefs: dict[str, Sequence[FixtureDef[Any]]] = {} ``` -------------------------------- ### Entry Point for Showing Fixtures Source: https://docs.pytest.org/en/stable/_modules/_pytest/fixtures.html This function serves as the main entry point for the 'showfixtures' command, wrapping the session execution. ```python def showfixtures(config: Config) -> int | ExitCode: from _pytest.main import wrap_session return wrap_session(config, _showfixtures_main) ``` -------------------------------- ### Manual Execution of Basic Fixture Example Source: https://docs.pytest.org/en/stable/how-to/fixtures.html Illustrates the manual, step-by-step execution of the 'fruit_bowl' fixture and the 'test_fruit_salad' function, mimicking pytest's behavior. ```python def fruit_bowl(): return [Fruit("apple"), Fruit("banana")] def test_fruit_salad(fruit_bowl): # Act fruit_salad = FruitSalad(*fruit_bowl) # Assert assert all(fruit.cubed for fruit in fruit_salad.fruit) # Arrange bowl = fruit_bowl() test_fruit_salad(fruit_bowl=bowl) ``` -------------------------------- ### copy_example Source: https://docs.pytest.org/en/stable/_modules/_pytest/pytester.html Copy file from project's directory into the testdir. Allows copying example files or directories into the test environment. ```APIDOC ## copy_example ### Description Copies a file or directory from the project's example directory into the current test directory managed by pytester. It can copy a specific file/directory by name, or attempt to find an example corresponding to the current test function. ### Parameters * `name` (str | None, optional): The name of the file or directory to copy from the example directory. If None, it tries to find an example based on the test function name. ### Returns * `Path`: Path to the copied file or directory within the test directory. ### Raises * `ValueError`: If `pytester_example_dir` is not set in the pytest configuration. * `LookupError`: If the specified example file/directory cannot be found. ``` -------------------------------- ### Using a pytest fixture to mock requests.get Source: https://docs.pytest.org/en/stable/monkeypatch.html This example demonstrates how to create a pytest fixture that mocks `requests.get`. The fixture applies the monkeypatch, and tests can then use this fixture to ensure `requests.get` is mocked without repeating the setup code. ```python import pytest import requests # app.py that includes the get_json() function import app # custom class to be the mock return value of requests.get() class MockResponse: @staticmethod def json(): return {"mock_key": "mock_response"} # monkeypatched requests.get moved to a fixture @pytest.fixture def mock_response(monkeypatch): """Requests.get() mocked to return {'mock_key':'mock_response'}.""" def mock_get(*args, **kwargs): return MockResponse() monkeypatch.setattr(requests, "get", mock_get) # notice our test uses the custom fixture instead of monkeypatch directly def test_get_json(mock_response): result = app.get_json("https://fakeurl") assert result["mock_key"] == "mock_response" ``` -------------------------------- ### Test File Example 1 Source: https://docs.pytest.org/en/stable/example/customdirectory.html A simple test file that will be collected if listed in the `manifest.json`. ```python from __future__ import annotations def test_1(): pass ``` -------------------------------- ### Install and Install Pre-commit Hook Source: https://docs.pytest.org/en/stable/contributing.html Install the pre-commit tool and its hook for the Pytest repository. This tool automatically runs code style and formatting checks before each commit. ```bash $ pip install --user pre-commit $ pre-commit install ``` -------------------------------- ### Pytest Runtest Setup Hook Source: https://docs.pytest.org/en/stable/_modules/_pytest/hookspec.html Called to execute the setup phase for a test item. The default implementation handles fixture resolution and item-specific setup procedures. ```python def pytest_runtest_setup(item: Item) -> None: """Called to perform the setup phase for a test item. The default implementation runs ``setup()`` on ``item`` and all of its parents (which haven't been setup yet). This includes obtaining the values of fixtures required by the item (which haven't been obtained yet). :param item: The item. Use in conftest plugins ======================= Any conftest file can implement this hook. For a given item, only conftest files in the item's directory and its parent directories are consulted. """ pass ``` -------------------------------- ### Using capfdbinary to Capture Binary Output Source: https://docs.pytest.org/en/stable/reference/reference.html Example of using the 'capfdbinary' fixture to capture binary output from system commands and assert its content. ```python def test_system_echo(capfdbinary): os.system('echo "hello"') captured = capfdbinary.readouterr() assert captured.out == b"hello\n" ``` -------------------------------- ### Pytest Runtest Setup Hook Source: https://docs.pytest.org/en/stable/_modules/_pytest/runner.html Pytest hook for the setup phase of a test item. It updates the internal test state and calls the setup state manager. ```python def pytest_runtest_setup(item: Item) -> None: _update_current_test_var(item, "setup") item.session._setupstate.setup(item) ``` -------------------------------- ### Manual Execution of Chained Fixture Example Source: https://docs.pytest.org/en/stable/how-to/fixtures.html Demonstrates the manual execution flow for fixtures that depend on each other, showing how 'first_entry' is used to create 'order', which is then passed to the test. ```python def first_entry(): return "a" def order(first_entry): return [first_entry] def test_string(order): # Act order.append("b") # Assert assert order == ["a", "b"] entry = first_entry() the_list = order(first_entry=entry) test_string(order=the_list) ``` -------------------------------- ### Get Pytest Help Source: https://docs.pytest.org/en/stable/reference/customize.html Prints command line options and configuration file settings. ```bash pytest -h # prints options _and_ config file settings ``` -------------------------------- ### Install or Upgrade Pytest Source: https://docs.pytest.org/en/stable/announce/release-2.0.1.html Use pip or easy_install to install or upgrade to the latest version of pytest. ```bash pip install -U pytest # or easy_install -U pytest ``` -------------------------------- ### Command Line Parsing Source: https://docs.pytest.org/en/stable/_modules/_pytest/config.html Parses command-line arguments and handles initial setup. Includes special handling for `--version` and `--help` when `UsageError` occurs during parsing. ```python def pytest_cmdline_parse( self, pluginmanager: PytestPluginManager, args: list[str] ) -> Config: try: self.parse(args) except UsageError: # Handle "--version --version" and "--help" here in a minimal fashion. # This gets done via helpconfig normally, but its # pytest_cmdline_main is not called in case of errors. if getattr(self.option, "version", False) or "--version" in args: from _pytest.helpconfig import show_version_verbose # Note that "--version" (single argument) is handled early by `Config.main()`, so the only # way we are reaching this point is via "--version --version". show_version_verbose(self) elif ( getattr(self.option, "help", False) or "--help" in args or "-h" in args ): self._parser.optparser.print_help() sys.stdout.write( "\nNOTE: displaying only minimal help due to UsageError.\n\n" ) raise return self ``` -------------------------------- ### Install Pytest using pip Source: https://docs.pytest.org/en/stable/announce/release-2.0.0.html Install or upgrade Pytest to the latest version using pip. ```bash pip install -U pytest ``` -------------------------------- ### Autouse Fixture Execution Order Example Source: https://docs.pytest.org/en/stable/reference/fixtures.html Demonstrates how an autouse fixture 'c' and its dependencies 'b' and 'a' are executed before other fixtures like 'd', 'e', 'f', and 'g' in a test file. ```python from __future__ import annotations import pytest @pytest.fixture def order(): return [] @pytest.fixture def a(order): order.append("a") @pytest.fixture def b(a, order): order.append("b") @pytest.fixture(autouse=True) def c(b, order): order.append("c") @pytest.fixture def d(b, order): order.append("d") @pytest.fixture def e(d, order): order.append("e") @pytest.fixture def f(e, order): order.append("f") @pytest.fixture def g(f, c, order): order.append("g") def test_order_and_g(g, order): assert order == ["a", "b", "c", "d", "e", "f", "g"] ``` -------------------------------- ### Plugin Fixture Example (hello) Source: https://docs.pytest.org/en/stable/how-to/writing_plugins.html Defines a pytest fixture `hello` and handles command-line options for a greeting plugin. This code demonstrates how a plugin might provide functionality. ```python import pytest def pytest_addoption(parser): group = parser.getgroup("helloworld") group.addoption( "--name", action="store", dest="name", default="World", help='Default "name" for hello().', ) @pytest.fixture def hello(request): name = request.config.getoption("name") def _hello(name=None): if not name: name = request.config.getoption("name") return f"Hello {name}!" return _hello ``` -------------------------------- ### Collection Start Hook Source: https://docs.pytest.org/en/stable/_modules/_pytest/hookspec.html This hook is called when a collector starts collecting. It is useful for performing actions before collection begins. ```python def pytest_collectstart(collector: Collector) -> None: """Collector starts collecting. :param collector: The collector. """ pass ``` -------------------------------- ### Fixture Initialization Source: https://docs.pytest.org/en/stable/_modules/_pytest/fixtures.html Initializes a fixture with request details, including configuration, scope, and node. ```python def __init__(self, request: FixtureRequest) -> None: super().__init__( config=request.config, baseid=NOTSET, argname="request", func=lambda: request, scope=Scope.Function, params=None, node=request.node, _ispytest=True, ) self.cached_result = (request, [0], None) ``` -------------------------------- ### Example of using capsys fixture Source: https://docs.pytest.org/en/stable/_modules/_pytest/capture.html Demonstrates how to use the capsys fixture to capture and assert printed output to stdout. ```python def test_output(capsys): print("hello") captured = capsys.readouterr() assert captured.out == "hello\n" ``` -------------------------------- ### Website Login Fixture Setup Source: https://docs.pytest.org/en/stable/how-to/fixtures.html This set of fixtures demonstrates a safe structure for testing a website login. It includes fixtures for an admin client, user creation, a Selenium WebDriver instance, login functionality, and the landing page. ```python from uuid import uuid4 from urllib.parse import urljoin from selenium.webdriver import Chrome import pytest from src.utils.pages import LoginPage, LandingPage from src.utils import AdminApiClient from src.utils.data_types import User @pytest.fixture def admin_client(base_url, admin_credentials): return AdminApiClient(base_url, **admin_credentials) @pytest.fixture def user(admin_client): _user = User(name="Susan", username=f"testuser-{uuid4()}", password="P4$$word") admin_client.create_user(_user) yield _user admin_client.delete_user(_user) @pytest.fixture def driver(): _driver = Chrome() yield _driver _driver.quit() @pytest.fixture def login(driver, base_url, user): driver.get(urljoin(base_url, "/login")) page = LoginPage(driver) page.login(user) @pytest.fixture def landing_page(driver, login): return LandingPage(driver) def test_name_on_landing_page_after_login(landing_page, user): assert landing_page.header == f"Welcome, {user.name}!" ``` -------------------------------- ### Pytest Test Log Start Hook Source: https://docs.pytest.org/en/stable/_modules/_pytest/logging.html Resets and sets the 'start' when for the CLI log handler before a test begins. ```python @hookimpl def pytest_runtest_logstart(self) -> None: self.log_cli_handler.reset() self.log_cli_handler.set_when("start") ``` -------------------------------- ### SysCaptureBase Initialization and State Management Source: https://docs.pytest.org/en/stable/_modules/_pytest/capture.html Handles initialization and state management for system-level capture, including redirection of standard streams. ```python class SysCaptureBase(CaptureBase[AnyStr]): def __init__( self, fd: int, tmpfile: TextIO | None = None, *, tee: bool = False ) -> None: name = patchsysdict[fd] self._old: TextIO = getattr(sys, name) self.name = name if tmpfile is None: if name == "stdin": tmpfile = DontReadFromInput() else: tmpfile = CaptureIO() if not tee else TeeCaptureIO(self._old) self.tmpfile = tmpfile self._state = "initialized" ``` -------------------------------- ### Fixture Order by Scope Source: https://docs.pytest.org/en/stable/reference/fixtures.html Demonstrates how fixtures with different scopes (session, package, module, class, function) are executed in order of their scope, from broadest to narrowest. This example requires all fixtures to be defined. ```python from __future__ import annotations import pytest @pytest.fixture(scope="session") def order(): return [] @pytest.fixture def func(order): order.append("function") @pytest.fixture(scope="class") def cls(order): order.append("class") @pytest.fixture(scope="module") def mod(order): order.append("module") @pytest.fixture(scope="package") def pack(order): order.append("package") @pytest.fixture(scope="session") def sess(order): order.append("session") class TestClass: def test_order(self, func, cls, mod, pack, sess, order): assert order == ["session", "package", "module", "class", "function"] ``` -------------------------------- ### Install LegacyTmpdirPlugin Source: https://docs.pytest.org/en/stable/_modules/_pytest/legacypath.html Installs the LegacyTmpdirPlugin if the 'tmpdir' plugin is already present. This ensures backward compatibility for temporary directory handling. ```python if config.pluginmanager.has_plugin("tmpdir"): mp = MonkeyPatch() config.add_cleanup(mp.undo) try: tmp_path_factory = config._tmp_path_factory # type: ignore[attr-defined] except AttributeError: pass else: _tmpdirhandler = TempdirFactory(tmp_path_factory, _ispytest=True) mp.setattr(config, "_tmpdirhandler", _tmpdirhandler, raising=False) config.pluginmanager.register(LegacyTmpdirPlugin, "legacypath-tmpdir") ``` -------------------------------- ### Check Pytest Version Source: https://docs.pytest.org/en/stable/getting-started.html Verify the installed pytest version. This helps confirm the installation was successful and identify the version for compatibility checks. ```bash $ pytest --version pytest 9.1.1 ``` -------------------------------- ### pytest_fixture_setup Source: https://docs.pytest.org/en/stable/_modules/_pytest/hookspec.html Perform fixture setup execution. Stops at the first non-None result. ```APIDOC ## pytest_fixture_setup ### Description Perform fixture setup execution. Stops at first non-None result, see :ref:`firstresult`. .. note:: If the fixture function returns None, other implementations of this hook function will continue to be called, according to the behavior of the :ref:`firstresult` option. ### Parameters #### Path Parameters - **fixturedef** (FixtureDef[Any]) - The fixture definition object. - **request** (SubRequest) - The fixture request object. ### Returns - **object | None** - The return value of the call to the fixture function. ``` -------------------------------- ### Class Level Setup/Teardown Source: https://docs.pytest.org/en/stable/how-to/xunit_setup.html Implement these methods for setup and teardown at the class level, before and after all test methods of the class are called. The `cls` parameter is used. ```python @classmethod def setup_class(cls): """setup any state specific to the execution of the given class (which usually contains tests). """ @classmethod def teardown_class(cls): """teardown any state that was previously setup with a call to setup_class. """ ```