pytest-regex
pytest-regex is a pytest plugin that allows users to select tests for execution using regular expressions against the full test node ID. It extends pytest's test selection capabilities beyond keyword (`-k`) and marker (`-m`) expressions. The current version is 0.2.0, and it maintains an infrequent release cadence.
Common errors
-
pytest: error: unrecognized arguments: --regex
cause The `pytest-regex` plugin is not installed or not accessible to pytest in your current environment.fixEnsure the plugin is installed using `pip install pytest-regex` within the active virtual environment where you run `pytest`. -
============================= no tests ran in X.YZs =============================
cause The regular expression provided with `--regex` did not match any of the collected test node IDs, or was too restrictive.fixVerify your regex pattern is correct and matches your test node IDs. Use `pytest --collect-only` to inspect the full list of collected test node IDs and refine your regex accordingly. Consider if other filters (`-k`, `-m`) are also contributing to the problem.
Warnings
- gotcha The `--regex` flag matches against the *full test node ID*, which includes the file path, module, class, and function name (e.g., `test_module.py::TestClass::test_method`). Simple patterns like `test_my_func` might not match if the full path isn't considered.
- gotcha pytest-regex functionality is exclusively exposed via command-line arguments (`--regex` and `--regex-file`). There is no public Python API for direct programmatic interaction with the plugin's regex matching logic.
- gotcha When combining `--regex` with other selection options like `-k` (keyword) or `-m` (marker), pytest typically applies all filters. An overly restrictive combination of filters can lead to 'No tests ran'.
Install
-
pip install pytest-regex
Imports
- pytest-regex
This library is a pytest plugin; its functionality is accessed via the `pytest` command-line interface, not through direct Python imports.
Quickstart
import pytest
# test_example.py
def test_add():
assert 1 + 1 == 2
def test_subtract():
assert 2 - 1 == 1
class TestMathOperations:
def test_multiply(self):
assert 2 * 2 == 4
# To run: save the above as 'test_example.py'
# Then run from your terminal:
# pip install pytest pytest-regex
# pytest --regex "test_add"
# pytest --regex "TestMathOperations::test_multiply"
# pytest --regex "^(test_add|test_subtract)$"