Labs ICT
Pro Login

Writing Your First Test

Create and run your very first pytest test case.

Your First Test

Let us write and run a real test. Create a file called test_math.py in your project:

# test_math.py

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

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

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

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

def test_add_negative():
    assert add(-1, -1) == -2

Running the Test

Open your terminal and run:

pytest test_math.py -v

You should see output similar to this:

test_math.py::test_add PASSED                         [ 33%]
test_math.py::test_subtract PASSED                    [ 66%]
test_math.py::test_add_negative PASSED                [100%]

============================== 3 passed in 0.02s ===============================

The -v flag makes the output verbose, showing the name of each test and its result.

What Happens When a Test Fails?

Let us see what a failure looks like. Change one test to fail intentionally:

def test_add_wrong():
    assert add(2, 3) == 6  # This will fail!

Run it and you will get a detailed failure report:

def test_add_wrong():
>       assert add(2, 3) == 6
E       assert 5 == 6
E        +  where 5 = add(2, 3)

test_math.py:12: AssertionError

pytest shows you the exact line that failed, the expression that was evaluated, and the actual values involved. This makes debugging much easier.