How to Use -k Flag in pytest for Selective Test Execution
The
-k flag in pytest lets you run tests that match a specific keyword expression in their names or test IDs. You can use simple words or logical expressions with and, or, and not to filter which tests to run.Syntax
The basic syntax of the -k flag is:
pytest -k "expression"
Here, expression is a keyword or a logical combination of keywords that match test names or node IDs.
Supported logical operators are and, or, and not. Parentheses can group expressions.
bash
pytest -k "expression"Example
This example shows how to run tests whose names contain the word add or subtract, but not negative.
python
def test_add_positive(): assert 1 + 1 == 2 def test_add_negative(): assert 1 + (-1) == 0 def test_subtract_positive(): assert 2 - 1 == 1 def test_subtract_negative(): assert (-2) - (-1) == -1 # Command to run: # pytest -k "add or subtract and not negative"
Output
============================= test session starts ==============================
collected 4 items
test_example.py .. [100%]
============================== 2 passed in 0.01s ===============================
Common Pitfalls
Common mistakes when using -k include:
- Not quoting the expression, which can cause shell errors.
- Misunderstanding operator precedence:
andhas higher precedence thanor. - Using keywords that do not match any test names, resulting in no tests run.
Always use quotes and parentheses to clarify your intent.
bash
## Wrong usage (no quotes): # pytest -k add or subtract ## Correct usage with quotes and parentheses: # pytest -k "add or subtract" ## To combine with not: # pytest -k "(add or subtract) and not negative"
Quick Reference
| Expression | Description |
|---|---|
| "add" | Run tests with 'add' in their name |
| "add and positive" | Run tests with both 'add' and 'positive' in their names |
| "add or subtract" | Run tests with either 'add' or 'subtract' in their names |
| "not negative" | Run tests that do NOT have 'negative' in their names |
| "(add or subtract) and not negative" | Run tests with 'add' or 'subtract' but exclude those with 'negative' |
Key Takeaways
Use
-k with quoted keyword expressions to select tests by name.Combine keywords with
and, or, and not for precise filtering.Always quote the expression to avoid shell parsing errors.
Use parentheses to control logical operator precedence.
If no tests match the expression, pytest will run zero tests.