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:
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_:
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.
pytest -qpytest finds every test_ file and function by itself and runs them. -q keeps the report short: one dot per passing test.
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:
def test_money_back_is_billing():
assert categorise("I want my money back") == "billing"pytest -qThe 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.
- Add
"money back"to the billing check intriage.pyand runpytest -qagain. - Run
pytest -vto see every test by name. - Break
triage.pyon purpose, say by returning"Billing"with a capital, and count the failures.
Every expert started right here.