Pytest 101


`pip install pytest
`


Organize your project a bit like this:

my_project/
├── app/
│   └── calculator.py
├── tests/
│   └── test_calculator.py
└── requirements.txt
  • Code lives in app/
  • Tests live in tests/
  • Files that start with test_ or end with _test.py get picked up automatically
  • Functions inside those files that start with test_ are test functions

What are we testing

In app/calculator.py:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

Write the tests

Create a new file: tests/test_calculator.py

from app.calculator import add, subtract

def test_add():
    assert add(2, 3) == 5

def test_subtract():
    assert subtract(10, 4) == 6



Run the Tests

pytest
============================= test session starts ==============================
collected 2 items

tests/test_calculator.py ..                                           [100%]

============================== 2 passed in 0.01s ===============================

pytest -v will give you more info

Leave a Reply

Your email address will not be published. Required fields are marked *