How can I skip all PyTest tests in a directory if a certain condition is met?

I want to configure PyTest (preferably in conftest.py) so that all tests under a specific directory are skipped when a certain condition is true, for example, if an optional dependency is missing.

Is there a way to achieve this globally for the directory instead of marking each test individually

I had a similar case where I wanted to skip all tests in a folder if a dependency wasn’t installed.

What worked for me was using the pytest_ignore_collect hook in conftest.py.

This hook runs before tests are collected, so you can conditionally tell PyTest to skip a whole directory:


# conftest.py
import pytest
import importlib.util
import os

def pytest_ignore_collect(path, config):
    # Check for your condition
    if not importlib.util.find_spec("some_optional_dependency"):
        # Skip tests under a specific folder
        if "tests/optional" in str(path):
            return True
    return False

This way, PyTest simply won’t collect any tests under tests/optional if the dependency is missing. Super clean and no need to mark every test individually.

I used pytest_ignore_collect recently to skip a whole directory when a feature wasn’t available.

You just need to check the path and return True when you want to skip it. For example:

# conftest.py
def pytest_ignore_collect(path, config):
    if "my_special_tests" in str(path):
        # any condition, e.g., environment variable
        if config.getoption("--skip-special"):
            return True
    return False

Then I could run PyTest with --skip-special to skip the directory, or implement any other condition in the hook. Works really nicely for optional features or platform-specific tests.

In one of my projects, we had optional tests that relied on a database container.

Instead of decorating every test with @pytest.mark.skipif, I used pytest_ignore_collect in conftest.py and it made things much simpler:

# conftest.py
import os

def pytest_ignore_collect(path, config):
    # Skip tests if DATABASE_URL not set
    if "integration_tests" in str(path) and "DATABASE_URL" not in os.environ:
        return True
    return False

PyTest just ignores the folder entirely, so you don’t see skipped test output cluttering your CI logs.

From personal experience, this is cleaner than adding skipif on every test in large directories.