Running Tests with pytest
Once you’ve written your test functions, the next step is to run them and verify that your code behaves as expected. This section explains how to use the pytest command, interpret the output, and specify specific files or directories to test.
Running Tests with the pytest
Command
To run tests, use the pytest
command in your terminal or command prompt. By default, pytest discovers and runs all test files and functions in the current directory and its subdirectories.
Basic Command
Run the command:
pytest
This will:
- Automatically find files named
test_*.py
or*_test.py
. - Execute all functions within those files that start with
test_
.
Example
Assume you have the following test file:
File: test_math.py
def test_addition():
assert 2 + 2 == 4
def test_subtraction():
assert 5 - 3 == 2
Run pytest:
pytest
Output:
================== test session starts ==================
collected 2 items
test_math.py .. [100%]
================== 2 passed in 0.01s ==================
Understanding Test Output
pytest provides detailed output to help you understand the status of your tests.
Key Components of Output
- Test Collection: Shows how many test cases were discovered (e.g.,
collected 2 items
). - Test Results:
.
(dot): Test passed.F
: Test failed.E
: Error occurred during the test.
- Summary: Provides a breakdown of passed, failed, and skipped tests.
Example: Failing Test Output
If a test fails, pytest provides detailed information to help debug.
File: test_math.py
def test_failure():
assert 2 + 2 == 5 # This will fail
Run pytest:
pytest
Output:
================== test session starts ==================
collected 1 item
test_math.py F [100%]
================== FAILURES ==================
____________________ test_failure _____________________
def test_failure():
> assert 2 + 2 == 5
E assert 4 == 5
test_math.py:2: AssertionError
- Failure Location: Shows the file name and line number where the test failed.
- Assertion Details: Explains the mismatch (
4 == 5
).
Specifying Test Files or Directories
Sometimes, you might want to run tests in a specific file or folder rather than all tests in the project.
Running a Specific Test File
Use the filename as an argument:
pytest test_math.py
This runs all tests in test_math.py
.
Running Tests in a Directory
Provide the directory name:
pytest tests/
This runs all tests in the tests/
directory and its subdirectories.
Running a Specific Test Function
Use the file name followed by ::
and the function name:
pytest test_math.py::test_addition
This runs only the test_addition
function in test_math.py
.
Summary
- Use
pytest
to discover and run tests automatically. - Interpret test output to identify passed, failed, and error cases.
- Specify files, directories, or individual test functions for targeted testing.
This foundational understanding will help you efficiently run tests as you continue exploring pytest!