How to Run pytest: Simple Commands and Examples
To run tests with
pytest, open your terminal and type pytest in the directory containing your test files. You can also specify a test file or folder like pytest test_example.py to run specific tests.Syntax
The basic command to run pytest is pytest. You can add options or specify files/folders:
pytest: Runs all tests in the current directory and subdirectories.pytest test_file.py: Runs tests in a specific file.pytest -v: Runs tests with detailed output.pytest -k 'expression': Runs tests matching the expression.
bash
pytest [options] [file_or_dir]
Example
This example shows a simple test file and how to run it with pytest.
python
def test_addition(): assert 2 + 3 == 5 def test_subtraction(): assert 5 - 2 == 3
Output
============================= test session starts ==============================
collected 2 items
test_example.py .. [100%]
============================== 2 passed in 0.01s ===============================
Common Pitfalls
Common mistakes when running pytest include:
- Running pytest in the wrong directory where tests are not found.
- Not naming test files or functions correctly (they must start with
test_). - Using incorrect command syntax or missing the
-voption for detailed output.
python
## Wrong: test file named example.py (no 'test_' prefix) # pytest will not find tests here def test_sample(): assert True ## Right: test file named test_example.py # pytest will discover this file and run tests def test_sample(): assert True
Quick Reference
| Command | Description |
|---|---|
| pytest | Run all tests in current directory and subdirectories |
| pytest test_file.py | Run tests in a specific file |
| pytest -v | Run tests with detailed output |
| pytest -k 'expr' | Run tests matching expression |
| pytest --maxfail=1 | Stop after first failure |
Key Takeaways
Run pytest by typing
pytest in the terminal inside your test folder.Test files and functions must start with
test_ for pytest to find them.Use
pytest -v for more detailed test results.Specify test files or folders to run specific tests.
Check your current directory if pytest does not find any tests.