Skip to content

Unit Testing with pytest

Beginning of the lesson

Unit Testing with pytest

Prove your code works -- automatically, every time you change it

Big Idea: A unit test is a small piece of code that runs one function and checks that it returns what you expect. pytest collects all your tests, runs them in a second, and tells you exactly which ones failed -- so a bug you introduce today cannot quietly ship tomorrow.
By the end you will be able to:
  • explain why automated tests matter,
  • write test functions and assert what you expect,
  • run the suite with the pytest command and read its report,
  • share setup with fixtures,
  • check that errors are raised with pytest.raises, and cover many cases with parametrize.

1. Why testing matters

You already test your code -- by running it and looking at the output. The problem is that manual checking does not scale. A real program has dozens of functions, and every change can quietly break something you fixed last week. Automated tests turn "let me eyeball it" into a button you press: the machine re-checks every rule in under a second.

Think of tests as a safety net for a trapeze artist. The net does not do the tricks for you, but it lets you attempt bold changes -- refactor a function, rename a variable, speed something up -- knowing that if you fall, the net catches you immediately instead of a user discovering the bug in production.

Good tests give you three concrete wins:

  • Confidence to change code. Green tests mean your edit did not break the parts you already trusted.
  • Living documentation. A test named test_withdraw_too_much shows exactly how a function is meant to behave.
  • Faster debugging. A failing test points at one function, not the whole program.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers