Matthias Urlichs
Matthias Urlichs

Reputation: 2544

How can I apply a pytest mark to a whole subtree?

pytestmark = pytest.mark.foo applies this mark to all functions+classes in a module.

My problem is that I have a lot of test modules in a directory and want to apply the testmark to all of them.

How? I don't want to change every module's file.

Upvotes: 2

Views: 1419

Answers (1)

hoefling
hoefling

Reputation: 66461

You can attach the common marker programmatically, e.g. in the pytest_collection_modifyitems hookimpl:

import pytest


def pytest_collection_modifyitems(items):
    for item in items:
        item.add_marker(pytest.mark.foo)

If only tests from selected subtrees should be marked, extend the above impl with a test module file check, e.g.

import pathlib
import pytest


# assuming all tests are stored in a `tests` directory
dirs = (pathlib.Path("tests/foo"), pathlib.Path("tests/bar/baz"))

def pytest_collection_modifyitems(config, items):
    for item in items:
        testmod = pathlib.Path(item.fspath)
        if any(config.rootdir / dir in testmod.parents for dir in dirs):
            item.add_marker(pytest.mark.foo)

Upvotes: 4

Related Questions