### Deferring expensive resource setup for parametrized tests Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/example/parametrize.rst Example demonstrating how to defer the setup of expensive resources, like database connections, until the actual test is run, using fixtures and indirect parametrization. ```python # content of test_backends.py import pytest def test_db_initialized(db): # a dummy test if db.__class__.__name__ == "DB2": pytest.fail("deliberately failing for demo purposes") ``` ```python # content of conftest.py import pytest def pytest_generate_tests(metafunc): if "db" in metafunc.fixturenames: metafunc.parametrize("db", ["d1", "d2"], indirect=True) class DB1: "one database object" class DB2: "alternative database object" @pytest.fixture def db(request): if request.param == "d1": return DB1() elif request.param == "d2": return DB2() else: raise ValueError("invalid internal test config") ``` -------------------------------- ### Display pytest version, fixtures, and help Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/how-to/usage.rst Shows how to get information about the pytest installation, available fixtures, and command-line options. ```bash pytest --version # shows where pytest was imported from ``` ```bash pytest --fixtures # show available builtin function arguments ``` ```bash pytest -h | --help # show help on command line and config file options ``` -------------------------------- ### Pytest setup and teardown methods Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/deprecations.rst Example of using setup_method and teardown_method for resource management in Pytest classes. ```python class Test: def setup_method(self): self.resource = make_resource() def teardown_method(self): self.resource.close() def test_foo(self): ... def test_bar(self): ... ``` -------------------------------- ### Show Fixture Setup During Test Execution Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/reference/reference.rst Display detailed information about the setup process of fixtures as tests are being executed. This provides insight into fixture instantiation and teardown. ```bash pytest --setup-show ``` -------------------------------- ### Deprecated: Nose 'setup' and 'teardown' methods Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/deprecations.rst This example shows the use of 'setup' and 'teardown' methods, which are part of Pytest's nose support and are deprecated. Native pytest uses 'setup_method' and 'teardown_method'. ```python class Test: def setup(self): self.resource = make_resource() def teardown(self): self.resource.close() def test_foo(self): ... def test_bar(self): ... ``` -------------------------------- ### Setup Fixtures Only Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/reference/reference.rst Execute only the setup phase for fixtures without running the actual tests. This is useful for verifying fixture configurations and dependencies. ```bash pytest --setup-only ``` -------------------------------- ### Install tox for running tests Source: https://github.com/pytest-dev/pytest/blob/main/CONTRIBUTING.rst Install tox, a command-line tool for automating testing and package building. Tox will automatically set up virtual environments for running tests. ```bash $ pip install tox ``` -------------------------------- ### Parametrized Fixtures with Different Scopes Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/how-to/fixtures.rst Demonstrates how pytest manages setup and teardown for fixtures with different scopes (module and function) when they are parametrized. This example shows the order of execution and resource management. ```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}") ``` -------------------------------- ### Modern Fixture Setup/Teardown Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/deprecations.rst Demonstrates the current standard fixture mechanism for setup and teardown using yield. ```python @pytest.fixture(scope="module") def db_session(): session = Session.create() yield session session.close() ``` -------------------------------- ### Example test file test_first.py Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/example/customdirectory.rst A simple test module that will be collected based on the manifest.json configuration. ```python def test_1(): pass ``` -------------------------------- ### Use yaml.safe_load in Example Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/changelog.rst Shows the use of yaml.safe_load in an example, promoting safer YAML parsing practices. This is a recommended change for security. ```python fix issue307 - use yaml.safe_load in example, thanks Mark Eichin. ``` -------------------------------- ### Example test file test_second.py Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/example/customdirectory.rst A simple test module that will be collected based on the manifest.json configuration. ```python def test_2(): pass ``` -------------------------------- ### Install and set up pre-commit hooks for pytest Source: https://github.com/pytest-dev/pytest/blob/main/CONTRIBUTING.rst Install the pre-commit framework and set up its hooks in your local pytest repository. This ensures consistent code style and formatting on commit. ```bash $ pip install --user pre-commit ``` ```bash $ pre-commit install ``` -------------------------------- ### Install package in editable mode Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/explanation/goodpractices.rst Use pip to install the package so that source code changes are immediately reflected during testing. ```bash pip install -e . ``` -------------------------------- ### Install argcomplete via pip Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/how-to/bash-completion.rst Installs the argcomplete package with a minimum version requirement of 0.5.7. ```bash sudo pip install 'argcomplete>=0.5.7' ``` -------------------------------- ### Autouse Fixture for Automatic Test Setup Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/how-to/fixtures.rst Shows how to define an autouse fixture using `autouse=True`. Autouse fixtures are automatically requested by all tests in their scope, simplifying setup for common requirements. ```python # contents of test_append.py import pytest @pytest.fixture def first_entry(): return "a" @pytest.fixture def order(first_entry): return [] @pytest.fixture(autouse=True) def append_first(order, first_entry): return order.append(first_entry) def test_string_only(order, first_entry): assert order == [first_entry] def test_string_and_int(order, first_entry): order.append(2) assert order == [first_entry, 2] ``` -------------------------------- ### Using --sw-skip argument Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/changelog.rst Example of using the --sw-skip argument as a shorthand for --stepwise-skip. ```bash pytest --sw-skip ``` -------------------------------- ### Inspect fixture execution order using --setup-plan Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/reference/fixtures.rst Use the --setup-plan flag to see the order in which fixtures will execute for a specific test or scope. Add the -v flag to include fixtures starting with an underscore. ```bash pytest --setup-plan test_something.py ``` -------------------------------- ### Configure pytester_example_dir in pytest.toml Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/how-to/writing_plugins.rst Set the pytester_example_dir configuration option to specify the directory where pytester should look for example files to copy. ```toml # content of pytest.toml [pytest] pytester_example_dir = "." ``` -------------------------------- ### Install Project in Development Mode Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/how-to/existingtestsuite.rst Set up a symlink to your code in site-packages to run tests against local code without reinstalling. Run this in your project root after cloning the repository. ```bash cd pip install -e . # Environment dependent alternatives include # 'python setup.py develop' and 'conda develop' ``` -------------------------------- ### Capture and display warnings Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/how-to/capture-warnings.rst This example demonstrates how pytest automatically captures warnings during test execution and displays them at the end of the session. No special setup is required. ```python import warnings def api_v1(): warnings.warn(UserWarning("api v1, should use functions from v2")) return 1 def test_one(): assert api_v1() == 1 ``` -------------------------------- ### Declaring a Custom Hook Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/how-to/writing_hook_functions.rst Hooks are declared as do-nothing functions starting with 'pytest_'. This example shows a basic hook declaration with a docstring explaining its purpose. ```python def pytest_my_hook(config): """ Receives the pytest config and does things with it """ ``` -------------------------------- ### Command-Line Option Precedence Example Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/example/simple.rst Illustrates how command-line options are combined from configuration files, environment variables, and direct command-line arguments. Note that later options can override earlier ones. ```text $PYTEST_ADDOPTS ``` ```bash pytest -m slow ``` ```bash pytest -ra -q -v -m slow ``` -------------------------------- ### Example Tests Using Fixture for Report Access Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/example/simple.rst These tests are designed to showcase how the 'something' fixture can react to different test outcomes, including setup failures and call failures. ```python # content of test_module.py import pytest @pytest.fixture def other(): assert 0 def test_setup_fails(something, other): pass def test_call_fails(something): assert 0 def test_fail2(): assert 0 ``` -------------------------------- ### Example plugin with custom option and fixture Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/how-to/writing_plugins.rst A sample plugin implementation that adds a command-line option and a fixture that uses that option. ```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 ``` -------------------------------- ### Example pytest module with print statements for debugging Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/how-to/capture-stdout-stderr.rst This Python module demonstrates how print statements within test functions or setup functions are captured by pytest. The output is shown for failing tests. ```python # content of test_module.py def setup_function(function): print("setting up", function) def test_func1(): assert True def test_func2(): assert False ``` -------------------------------- ### Create a test file for CI demonstration Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/explanation/ci.rst A sample test file that fails with a long message to demonstrate output truncation behavior. ```python # content of test_ci.py import pytest def test_db_initialized(): pytest.fail( "deliberately failing for demo purpose, Lorem ipsum dolor sit amet, " "consectetur adipiscing elit. Cras facilisis, massa in suscipit " "dignissim, mauris lacus molestie nisi, quis varius metus nulla ut ipsum." ) ``` -------------------------------- ### Skip test with version condition Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/changelog.rst Use a string expression for skipif/xfail to provide meaningful information about skipping conditions. This example skips a test if the module's version string does not start with '1'. ```python import pytest import mymodule @pytest.mark.skipif("mymodule.__version__[0] == \"1\"") def test_function(): pass ``` -------------------------------- ### Sharing Mocked Responses with a Pytest Fixture Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/how-to/monkeypatch.rst This example shows how to encapsulate the monkeypatching logic for 'requests.get' into a pytest fixture. This allows tests to simply request the fixture, making the setup cleaner and reusable across multiple tests. ```python # contents of test_app.py, a simple test for our API retrieval 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" ``` -------------------------------- ### Install and Uninstall pytest Plugins with pip Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/how-to/plugins.rst Use pip to install or uninstall pytest plugins. Installed plugins are automatically discovered and integrated by pytest. ```bash pip install pytest-NAME pip uninstall pytest-NAME ``` -------------------------------- ### Install or Upgrade pytest with pip or easy_install Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/announce/release-2.1.1.rst Install or upgrade the pytest testing tool using either pip or easy_install. The '-U' flag ensures an upgrade if already installed. ```bash pip install -U pytest # or ``` ```bash easy_install -U pytest ``` -------------------------------- ### Example Failing Tests Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/example/simple.rst These are example tests that are designed to fail, demonstrating the behavior of the pytest_runtest_makereport hook. ```python # content of test_module.py def test_fail1(tmp_path): assert 0 def test_fail2(): assert 0 ``` -------------------------------- ### Install or upgrade pytest Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/announce/release-2.0.0.rst Use these commands to install or upgrade pytest to the latest version using pip or easy_install. ```bash pip install -U pytest ``` ```bash easy_install -U pytest ``` -------------------------------- ### Configure pytest using pytest.ini Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/reference/customize.rst This example shows how to set `minversion`, `addopts`, and `testpaths` in a `pytest.ini` or `.pytest.ini` file. These files take precedence over `pyproject.toml`, `tox.ini`, and `setup.cfg`. ```ini # pytest.ini or .pytest.ini [pytest] minversion = 6.0 addopts = -ra -q testpaths = tests integration ``` -------------------------------- ### Configure pytest using pytest.toml Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/reference/customize.rst This example shows how to set `minversion`, `addopts`, and `testpaths` in a `pytest.toml` or `.pytest.toml` file. These files take precedence over other configuration files. ```toml # pytest.toml or .pytest.toml [pytest] minversion = "9.0" addopts = ["-ra", "-q"] testpaths = [ "tests", "integration", ] ``` -------------------------------- ### Original code with default configuration dictionary Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/how-to/monkeypatch.rst This is the example code that uses a default configuration dictionary to create a connection string. It demonstrates how to handle default values. ```python # contents of app.py to generate a simple connection string DEFAULT_CONFIG = {"user": "user1", "database": "db1"} def create_connection_string(config=None): """Creates a connection string from input or defaults.""" config = config or DEFAULT_CONFIG return f"User Id={config['user']}; Location={config['database']};" ``` -------------------------------- ### Build documentation locally with tox Source: https://github.com/pytest-dev/pytest/blob/main/CONTRIBUTING.rst Use this command to generate the HTML documentation. The output will be located in the doc/en/_build/html directory. ```bash $ tox -e docs ``` -------------------------------- ### Use pytester.copy_example in test function Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/how-to/writing_plugins.rst Copy an example test file and run pytest on it using pytester.copy_example and pytester.runpytest. Requires pytester_example_dir to be configured. ```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 ``` -------------------------------- ### Getting Limited Object Representation Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/changelog.rst Exposes the internal py.io.saferepr() method to get a limited representation string of an object, useful for debugging and logging. ```python import py long_string = "a" * 100 print(py.io.saferepr(long_string)) ``` -------------------------------- ### Integrate Nose Setup/Teardown with Setupstate Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/changelog.rst Describes the integration of nose setup/teardown with setupstate to prevent unnecessary teardown calls. This ensures correct resource management. ```python Issue 265 - integrate nose setup/teardown with setupstate so it doesn't try to teardown if it did not setup ``` -------------------------------- ### Drop to pdb at test start with pytest Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/how-to/failures.rst Use --trace to invoke the Python debugger at the start of every test, allowing inspection before execution begins. ```bash pytest --trace ``` -------------------------------- ### Set up virtual environment and run pytest directly Source: https://github.com/pytest-dev/pytest/blob/main/CONTRIBUTING.rst Create and activate a Python virtual environment, then install pytest with development dependencies in editable mode. This allows running pytest directly without tox. ```bash $ python3 -m venv .venv ``` ```bash $ source .venv/bin/activate ``` ```bash $ .venv/Scripts/activate.bat ``` ```bash $ pip install -e ".[dev]" ``` ```bash $ pytest testing/test_config.py ``` -------------------------------- ### Pytest Command Line Execution Examples Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/example/parametrize.rst Demonstrates running pytest with and without the `--all` flag to observe the effect on test execution and output. ```pytest $ pytest -q test_compute.py .. [100%] 2 passed in 0.12s ``` ```pytest $ pytest -q --all ....F [100%] ================================= FAILURES ================================= _____________________________ test_compute[4] ______________________________ param1 = 4 def test_compute(param1): > assert param1 < 4 E assert 4 < 4 test_compute.py:4: AssertionError ========================= short test summary info ========================== FAILED test_compute.py::test_compute[4] - assert 4 < 4 1 failed, 4 passed in 0.12s ``` -------------------------------- ### Alternative to --lf -x for Stopping at First Failure Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/changelog.rst Introduces the '--sw' and '--stepwise' command-line options as alternatives to '--lf -x'. These options stop at the first failure but resume the next test invocation from that point. ```text --sw --stepwise ``` -------------------------------- ### Start Interactive Debugger on Errors Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/reference/reference.rst Automatically start the interactive Python debugger (PDB) when a test encounters an error or a KeyboardInterrupt occurs. This allows for in-depth debugging of failures. ```bash pytest --pdb ``` -------------------------------- ### Python Test Collection Example Source: https://github.com/pytest-dev/pytest/blob/main/doc/en/reference/reference.rst Illustrates a Python code structure where a class is defined in one file and imported into a test file. This example helps understand the behavior of 'collect_imported_tests'. ```python # contents of src/domain.py class Testament: ... # contents of tests/test_testament.py from domain import Testament def test_testament(): ... ```