Python for AIPython 3.10+ · Pydantic 2.12
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
33 small wins to finish your pathNext lesson

pytest: checking your code automatically

Every lesson so far checked its code by reading the output. A test does that reading for you, the same way every time, whenever you run it.

Start with categorise from lesson 11, in its own file:

Exampletriage.py
def categorise(text):
    text = text.lower()
    if "charged" in text or "refund" in text:
        return "billing"
    if "parcel" in text or "arrived" in text:
        return "shipping"
    return "other"

Tests go in a file whose name starts with test_:

Exampletest_triage.py
from triage import categorise


def test_charge_is_billing():
    assert categorise("I was charged twice for one order") == "billing"


def test_parcel_is_shipping():
    assert categorise("My parcel has not arrived") == "shipping"


def test_password_is_other():
    assert categorise("How do I change my password?") == "other"

A test is a function whose name starts with test_. assert checks that something is true. If it is, nothing happens; if not, the test fails.

Example
pytest -q

pytest finds every test_ file and function by itself and runs them. -q keeps the report short: one dot per passing test.

Installing it
Inside the project's virtual environment from lesson 29: pip install pytest.

A test that fails

A customer writes I want my money back. That is a billing ticket, so add a test saying so:

Exampleadded to test_triage.py
def test_money_back_is_billing():
    assert categorise("I want my money back") == "billing"
Example
pytest -q

The F marks the failure. pytest shows the assert that failed and both sides of it: categorise returned 'other' where the test wanted 'billing'. The other three still pass.

This is the order to work in. The test describes what should happen, it fails, and then you change triage.py until it passes, knowing the three older tests will tell you if the change broke them.

Try it yourself
  • Add "money back" to the billing check in triage.py and run pytest -q again.
  • Run pytest -v to see every test by name.
  • Break triage.py on purpose, say by returning "Billing" with a capital, and count the failures.

Every expert started right here.