Specify Which Pytest Tests to Run from a File

How do I select which pytest tests to run from a file?

For example, a file foo.txt containing a list of tests to be executed:

tests_directory/foo.py::test_001
tests_directory/bar.py::test_some_other_test

Similarly,

  • Is there a way to select multiple tests, having no common pattern in test name, from different directories with pytest? pytest -k <pattern> allows a single pattern. One option is to have a pytest.mark against each test, but my requirement is to run different combination of tests from different files.
  • Is there a way to specify multiple patterns and a test file name for each pattern?
  • Is there a way to specify the exact test paths in a file and feed that file as an input to pytest?
  • Is there a hook function that can be utilized for this purpose?
1

11 Answers

You can use -k option to run test cases with different patterns:

py.test tests_directory/foo.py tests_directory/bar.py -k 'test_001 or test_some_other_test'

This will run test cases with name test_001 and test_some_other_test deselecting the rest of the test cases.

Note: This will select any test case starting with test_001 or test_some_other_test. For example, if you have test case test_0012 it will also be selected.

5

Specifying tests / selecting tests

Pytest supports several ways to run and select tests from the command-line.

Run tests in a module

pytest test_mod.py

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.