How to Use Pytest for Testing

Step 1: Install pytest

First, you’ll need to install pytest. The easiest way is using pip:

pip install pytest

Step 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.py

Step 3: Write Your Code

In main.py, let’s write a simple function:

# main.py

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

Step 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) == 0

Each test function must start with test_ and use assert to check the result.

Step 5: Run the Tests

In your terminal, run:

pytest

You’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 purpose

Run pytest again:

pytest

Output:

>       assert add(2, 3) == 6
E       assert 5 == 6

This 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_add
pytest -v

Leave a Reply

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