How to test single file under pytest

PythonPytest

Python Problem Overview


How do you test a single file in pytest? I could only find ignore options and no "test this file only" option in the docs.

Preferably this would work on the command line instead of setup.cfg, as I would like to run different file tests in the ide. The entire suite takes too long.

Python Solutions


Solution 1 - Python

simply run pytest with the path to the file

something like

pytest tests/test_file.py

Use the :: syntax to run a specific test in the test file:

pytest test_mod.py::test_func

Here test_func can be a test method or a class (e.g.: pytest test_mod.py::TestClass).

For more ways and details, see "Specifying which tests to run" in the docs.

Solution 2 - Python

This is pretty simple:

$ pytest -v /path/to/test_file.py

The -v flag is to increase verbosity. If you want to run a specific test within that file:

$ pytest -v /path/to/test_file.py::test_name

If you want to run test which names follow a patter you can use:

$ pytest -v -k "pattern_one or pattern_two" /path/to/test_file.py

You also have the option of marking tests, so you can use the -m flag to run a subset of marked tests.

test_file.py

def test_number_one():
    """Docstring"""
    assert 1 == 1


@pytest.mark.run_these_please
def test_number_two():
    """Docstring"""
    assert [1] == [1]

To run test marked with run_these_please:

$ pytest -v -m run_these_please /path/to/test_file.py

Solution 3 - Python

This worked for me:

python -m pytest -k some_test_file.py

This works for individual test functions too:

python -m pytest -k test_about_something

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsimonzackView Question on Stackoverflow
Solution 1 - PythonBryantView Answer on Stackoverflow
Solution 2 - PythonlmiguelvargasfView Answer on Stackoverflow
Solution 3 - PythonJonDoe297View Answer on Stackoverflow