How to Use pytest in Python: Simple Guide with Examples
To use
pytest in Python, write test functions starting with test_ in files named test_*.py. Run tests by executing pytest in the terminal, and pytest will find and run all tests automatically.Syntax
Pytest looks for test files named test_*.py or *_test.py. Inside these files, test functions must start with test_. Use assert statements to check expected results.
Run tests by typing pytest in your terminal inside the project folder.
python
def test_example(): assert 1 + 1 == 2
Example
This example shows a simple test function that checks if adding two numbers works correctly. Running pytest will find this test and show if it passes.
python
def add(a, b): return a + b def test_add(): assert add(2, 3) == 5 assert add(-1, 1) == 0 assert add(0, 0) == 0
Output
============================= test session starts ==============================
collected 1 item
test_sample.py . [100%]
============================== 1 passed in 0.01s ===============================
Common Pitfalls
Common mistakes include:
- Not naming test files or functions correctly (must start with
test_). - Using
printinstead ofassertfor checks. - Running
python file.pyinstead ofpytestto run tests.
Always use assert to verify conditions and run tests with the pytest command.
python
def add(a, b): return a + b # Wrong: function name does not start with test_ def check_add(): assert add(2, 3) == 5 # Right: def test_add(): assert add(2, 3) == 5
Quick Reference
- Test file names: start with
test_or end with_test.py - Test function names: start with
test_ - Assertions: use
assertto check results - Run tests: type
pytestin terminal - Install pytest: use
pip install pytestif not installed
Key Takeaways
Name test files and functions starting with 'test_' for pytest to find them.
Use assert statements inside test functions to check expected results.
Run tests by typing 'pytest' in your terminal inside the project folder.
Avoid using print statements for testing; rely on assert for automatic checks.
Install pytest with 'pip install pytest' before running tests if needed.