Question
Answer and Explanation
Pytest is a powerful testing framework for Python. Running specific tests is a common task, and pytest provides several ways to achieve this. Here’s how you can run specific tests with pytest:
1. Running a Test by Node ID
- Each test function in Pytest has a unique "Node ID" which includes the file path, module name, and test function name. To run a specific test using its node ID, you can use the -k
flag followed by a pattern.
- Example:
If your test function is located in tests/test_example.py
and looks like this:
def test_add_numbers():
assert 2 + 2 == 4
You can run it using:
pytest -k "test_add_numbers" tests/test_example.py
This will run tests that contain "test_add_numbers" in their node ID.
2. Running Tests by Matching Function Names:
- The -k
option can also be used to match test function names more flexibly. For example, to run all tests that contain the word "add", you could use:
pytest -k "add"
- This will run all tests with "add" anywhere in their test function names or node ID.
3. Running Tests within a Specific File:
- To run all tests in a single file, simply provide the file path to pytest:
pytest tests/test_example.py
- This will run every test function within tests/test_example.py
.
4. Running Tests within a Class:
- If your tests are organized within a class, the -k
option allows you to target specific methods. For a file tests/test_class.py
with a test class like this:
class TestClass:
def test_method_a(self):
assert 1 == 1
def test_method_b(self):
assert 2 == 2
- You can run the test_method_a with:
pytest -k "test_method_a" tests/test_class.py
5. Running Tests based on Markers:
- Pytest allows you to use markers to categorize tests, and you can use -m
flag to run tests with specific markers:
- Suppose you have a marker @pytest.mark.slow
, you could run only those tests with:
pytest -m slow
By using these techniques, you can selectively run specific tests in your test suites, saving time and focusing on the relevant parts of your code. Remember to choose the method that best suits your needs based on your project’s organization and the specific tests you need to execute.