Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

python - 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.

question from:https://stackoverflow.com/questions/65905429/how-can-i-apply-a-pytest-mark-to-a-whole-subtree

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...