xuhdev
xuhdev

Reputation: 9370

PyTest: How to skip all tests under the current directory if a certain condition is satisfied?

Is there a way to tell pytest (preferrably in conftest.py) that all test under that directory should be skipped if a certain condition is satisfied? For example, if some optional depedency is missing, then a test directory should be skipped.

Upvotes: 0

Views: 1127

Answers (1)

gold_cy
gold_cy

Reputation: 14236

You could probably use the pytest_ignore_collect hook. For example let's say you have the directory below.

stackoverflow/
├── mypackage
│   ├── __init__.py
│   └── models.py
├── pytest.ini
└── tests
    ├── __init__.py
    ├── conftest.py
    └── foo
        ├── __init__.py
        └── test_models.py

test_models has two tests in it. When I run it as-is from the root of the repository I get the following.

============================================= test session starts =============================================
platform darwin -- Python 3.9.1, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
rootdir: ***/stackoverflow, configfile: pytest.ini
collected 2 items                                                                                             

tests/foo/test_models.py ..                                                                             [100%]

============================================== 2 passed in 0.02s ==============================================

When we place the following in our conftest.py then no tests end up running.

from pathlib import Path

TO_IGNORE = "tests/foo"

def pytest_ignore_collect(path, config):
    # suppose our condition is some command line argument is passed in
    val = config.getvalue("-k")
    if val == "":
        here = Path.cwd().absolute()
        skip_fd = here / TO_IGNORE
        if skip_fd == path:
            return True

============================================= test session starts =============================================
platform darwin -- Python 3.9.1, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
rootdir: ***/stackoverflow, configfile: pytest.ini
collected 0 items                                                                                             

============================================ no tests ran in 0.01s ============================================

You can make it as granular as you want with the file path depending on the structure of your repository. Just remember, Path.cwd() is wherever you are running pytest from.

Upvotes: 1

Related Questions