Adding custom pytest marker to skip test based on input

Viewed 235

I would like to add a custom pytest marker which skips a test whenever a specific file is found in the directory:

@pytest.mark.file_exists("my_file.txt")
def test_mytest():
    assert True

I want test_mytest to execute only when "my_file.txt" is in the root directory. The documentation specifies how to register a custom marker, but not how to define its behavior. How would I define the behavior of file_exists ? Any help is appreciated.

1 Answers

The logic must be implemented in pytest_runtest_setup, you must also declare for example in pytest_configure. For more information check https://docs.pytest.org/en/stable/how-to/mark.html:

conftest.py

from pathlib import Path

import pytest


def pytest_configure(config):
    config.addinivalue_line("markers", "file_exists(filename): description")


def pytest_runtest_setup(item):
    filenames = [mark.args[0] for mark in item.iter_markers(name="file_exists")]
    package_dir = Path(__file__).parent

    for filename in filenames:
        path = package_dir / filename
        if not path.is_file():
            pytest.skip("test requires {!r}".format(filename))
            return
Related