Step 1: Install pytest
First, you’ll need to install pytest. The easiest way is using pip:
pip install pytestStep 2: Set Up Your Project Structure
Here’s a simple layout:
main.py: Your Python code
test_main.py: Your test file (by convention, test files start with test_)
my_project/
├── main.py
├── test_main.pyStep 3: Write Your Code
In main.py, let’s write a simple function:
# main.py
def add(a, b):
return a + bStep 4: Write Your First Test
Create test_main.py:
# test_main.py
from main import add
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0Each test function must start with test_ and use assert to check the result.
Step 5: Run the Tests
In your terminal, run:
pytestYou’ll see output like:
==================== test session starts ====================
collected 1 item
test_main.py . [100%]
===================== 1 passed in 0.01s =====================That dot (.) means your test passed.
Step 6: What Happens If a Test Fails?
Change your test to make it fail:
def test_add():
assert add(2, 3) == 6 # wrong on purposeRun pytest again:
pytestOutput:
> assert add(2, 3) == 6
E assert 5 == 6This shows the actual value (5) and what you expected (6)—super useful for debugging.
Step 7: Clean and Improve
You can run only specific tests:
Or show more detail with:
pytest test_main.py::test_addpytest -v