Hone

Lessons · Python · a test function

A test is a function that asserts one fact

A test is a plain function named test_something, with no arguments, that calls your code and asserts what should come back. pytest finds them by name and runs each one.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

A test pins a fact down so it stays true after every change you or anyone else makes. Ten small facts about a function are worth more than one big one, because each failure names exactly what broke.

How to think about it

One fact per test. Name it as the sentence you want to read when it fails: test_empty_basket_totals_zero. Call the code once, assert once, and stop.

Worked example

def total(prices):
The code under test.
    return sum(prices)
def test_total_adds_prices():
A test: named, no arguments, one assert.
    assert total([2, 3]) == 5
def test_empty_basket_totals_zero():
A second fact, a second test.
    assert total([]) == 0
for t in (test_total_adds_prices, test_empty_basket_totals_zero):
pytest would find these by name; here we call them.
    t(); print(t.__name__, 'passed')
test_total_adds_prices passed / test_empty_basket_totals_zero passed

Your turn

Name and write the test for a one-item basket.

def ():
    assert total([9]) == 9

The trap

A test with no assert. It passes whenever the code runs without raising, which proves almost nothing.

Practise a test function on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.