# Your First Tests with pytest

A test is a small function that runs your code on an example and makes sure the answer is right, and pytest finds every test, runs it, and shows exactly what came back when one fails.

Journeyman · Python · Updated November 19, 2026

By Gregor Dzierzon

## After this lesson you can

- Write test functions with assert that check what a function returns, and run them with python -m pytest
- Read a failing test's report to tell what came back from what was expected, and write a test first and watch it fail

## Key takeaways

- A test is a function whose name starts with test_, in a file whose name starts with test_, and assert inside it makes sure a condition is true.
- python -m pytest finds every test and runs it, printing a dot for each test that passes and an F for each one that fails.
- A failing test's report points at the line that failed and shows what came back next to what the test expected.
- Writing the test first and watching it fail proves the test can catch the problem before you write the code that solves it.

Every time you change a program, something that worked yesterday can quietly stop working: a price rounds the wrong way, a discount stops applying. A test is a few lines of code that check your code for you, in a second, as often as you like. Graders run tests on homework, and teams run them before any change goes live.

The example is Crafty Corner, an online craft shop: shipping costs $5.99, and orders of $50 or more ship free.

## Checking by hand doesn't last

Here is Crafty Corner's shipping rule as a function, checked the way most people start, by printing a couple of answers and reading them:

```python
def shipping_cost(order_total):
    if order_total >= 50:
        return 0
    return 5.99


print(shipping_cost(32.00))
print(shipping_cost(64.00))
```

```text
5.99
0
```

Both look right, so you delete the prints and move on. A month later someone edits the rule, and nobody checks again: nobody remembers which answers to look for.

A smoke alarm doesn't wait for you to sniff the air: set up once, it stays quiet while all is well and sounds the moment something's wrong. Tests are smoke alarms for code: the examples you checked by hand, written down once as code, so a computer can check every one of them each time anything changes.

## A test is a function that makes sure

Python developers run their tests with **pytest**, a free package. Install it into your project's virtual environment with `pip install pytest` (*Virtual Environments and pip* shows how). Then keep the code and its tests in two files side by side. The code goes in `shipping.py`:

```python
def shipping_cost(order_total):
    """Crafty Corner's shipping: free for orders of $50 or more, $5.99 below that."""
    if order_total >= 50:
        return 0
    return 5.99
```

The tests go in `test_shipping.py`. Its first line brings the function in from `shipping.py`, so the tests can call it:

```python
from shipping import shipping_cost


def test_small_order_pays_shipping():
    assert shipping_cost(32.00) == 5.99


def test_order_of_50_ships_free():
    assert shipping_cost(50.00) == 0
```

pytest goes by names: it reads files whose names start with `test_`, and runs every function in them whose name starts with `test_`. These tests take no parameters and return nothing: their work is the `assert` line. `assert` is read "make sure that": `assert shipping_cost(32.00) == 5.99` says "make sure that the shipping cost of a $32 order is equal to 5.99". When the condition is true, nothing happens and the test **passes**. When it's false, the test **fails**.

Most tests follow three steps, called **arrange, act, assert**: set up the example, call the code, make sure of the answer. Short tests do all three in one line; a longer one can give each its own:

```python
def test_two_items_over_50_ship_free():
    order_total = 22.50 + 31.00          # arrange: the example's values
    cost = shipping_cost(order_total)    # act: call the code
    assert cost == 0                     # assert: make sure of the answer
```

## Running pytest

In the terminal, in the project's folder, with the virtual environment on:

```bash
python -m pytest
```

```text
============================= test session starts ==============================
platform win32 -- Python 3.14.4, pytest-9.2.0, pluggy-1.7.0
rootdir: C:\Users\Sam\python-course\crafty-corner
collected 2 items

test_shipping.py ..                                                      [100%]

============================== 2 passed in 0.07s ===============================
```

pytest found 2 tests (*collected 2 items*) and printed a dot for each one that passed. The last line is the verdict: *2 passed*. Your own run names your Python's version on its second line.

## When a test fails

Now someone changes the rule's first line to `if order_total > 50:`, so an order of exactly $50 pays shipping. The tests don't need changing. Run them again; after the same first four lines, pytest prints:

```text
test_shipping.py .F                                                      [100%]

=================================== FAILURES ===================================
_________________________ test_order_of_50_ships_free __________________________

    def test_order_of_50_ships_free():
>       assert shipping_cost(50.00) == 0
E       assert 5.99 == 0
E        +  where 5.99 = shipping_cost(50.0)

test_shipping.py:9: AssertionError
=========================== short test summary info ============================
FAILED test_shipping.py::test_order_of_50_ships_free - assert 5.99 == 0
========================= 1 failed, 1 passed in 2.05s ==========================
```

Read it from the top. The `F` says the second test failed. Under its name, `>` points at the line that failed, and each line starting with `E` (for error) explains why: `assert 5.99 == 0` puts what came back on the left and what the test expected on the right, and `where 5.99 = shipping_cost(50.0)` says which call gave the 5.99. `test_shipping.py:9` is the file and line number.

So which is wrong, the code or the test? Work the example out by hand from the rule: $50 ships free, so 0 is right, and the code is the part to fix. When the test's expected value is the mistake, you fix the test instead.

## Write the test first

Crafty Corner adds rush delivery: $12 more on any order. Before changing `shipping_cost`, write the test that says what it should do, and add it to `test_shipping.py`:

```python
def test_rush_adds_12_to_a_free_order():
    assert shipping_cost(64.00, rush=True) == 12
```

Run pytest, and this is the end of what it prints:

```text
E       TypeError: shipping_cost() got an unexpected keyword argument 'rush'

test_shipping.py:13: TypeError
=========================== short test summary info ============================
FAILED test_shipping.py::test_rush_adds_12_to_a_free_order - TypeError: shipp...
========================= 1 failed, 2 passed in 2.03s ==========================
```

It fails for the right reason: `shipping_cost` doesn't know about rush yet. That failure is the proof that the test can catch a missing rush fee. Now write the code: give `shipping_cost` a `rush=False` parameter and add 12 when it's `True`. Run pytest again, and the last line says *3 passed*. In your textbook this is called **test-driven development**: red (a failing test), green (the code that passes it), then tidy up with the tests still passing.

## Do it: write two tests for the coupon

Crafty Corner's coupon takes $5 off any order of $40 or more. The function `discounted` already works. Your tests will catch anyone who breaks it later.

- `discounted(total)`: in the code box, ready to use. It returns an order's total after the coupon. Don't change it.

**Your job:** below `discounted`, write two test functions, each with one `assert`:

- `test_45_gets_5_off`: makes sure that `discounted(45)` is equal to `40`.
- `test_30_pays_full_price`: makes sure that `discounted(30)` is equal to `30`.

Worked through: a $45 order is at least $40, so the coupon takes $5 off, and 45 − 5 = 40. The test's line is `assert discounted(45) == 40`.

The box runs your two tests three times. On the working `discounted`, both must pass. Then on two broken copies, where at least one of them must fail: a copy that never takes $5 off, and a copy that takes $5 off every order, even a $30 one. A broken copy that gets past every test is a bug that would reach real customers.

Practiced live on the lesson page: write the Python right there and check it.

## Check yourself

2 questions to try on the lesson page.

## So what

A test turns "I checked it once" into "it's checked every time", and a failing test tells you exactly what came back, so a broken rule is found in seconds instead of by a customer.

## Key terms

- [pytest](https://www.ask-codey.com/glossary/pytest)
- [assert](https://www.ask-codey.com/glossary/assert)
- [Arrange, Act, Assert](https://www.ask-codey.com/glossary/arrange-act-assert)
- [Passing and Failing Tests](https://www.ask-codey.com/glossary/passing-and-failing-tests)
- [Test-Driven Development](https://www.ask-codey.com/glossary/test-driven-development)

## Related

- [Testing Edge Cases and Errors](https://www.ask-codey.com/lessons/python-testing-edge-cases-and-errors)
- [Fixtures and Temporary Files](https://www.ask-codey.com/lessons/python-testing-fixtures-and-tmp-path)

Source: https://www.ask-codey.com/lessons/python-testing-first-tests
