21

We use pytest to test our project and have enabled --doctest-modules by default to collect all of our doctests from across the project.

However there is one wsgi.py which may not be imported during test collection, but I cant get pytest to ignore it.

I tried putting it in the collect_ignore list in conftest.py but apparently the doctest module does not use this list.

The only thing that does work is putting the whole directory of wsgi.py into norecursedirs in the pytest config file, but this obviously hides the whole directory, which I don't want.

Is there a way to make the doctest module ignore just a certain file?

1

2 Answers 2

9

As MasterAndrey has mentioned, pytest_ignore_collect should do the trick. Important to note that you should put conftest.py to root folder (the one you run tests from).
Example:

import sys

def pytest_ignore_collect(path):
    if sys.version_info[0] > 2:
        if str(path).endswith("__py2.py"):
            return True
    else:
        if str(path).endswith("__py3.py"):
            return True

Since pytest v4.3.0 there is also --ignore-glob flag which allows to ignore by pattern. Example: pytest --doctest-modules --ignore-glob="*__py3.py" dir/

Sign up to request clarification or add additional context in comments.

3 Comments

The crucial part for me was to put this pytest_ignore_collect hook in a conftest.py in the root of the project. We had a conftest.py in our tests directory with several settings, and placing the hook there did not work.
hmmm ... this just gives me a whole load of E KeyError: '--doctest-modules'
In the current version (pytest==8.3.2), the path positional argument is deprecated in favor of collection_path.
6

You can use hook to conditionally exclude some folders from test discovery. https://docs.pytest.org/en/latest/writing_plugins.html

def pytest_ignore_collect(path, config):
    """ return True to prevent considering this path for collection.
    This hook is consulted for all files and directories prior to calling
    more specific hooks.
    """

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.