Learn with diagrams, code, systems and practical examples.
Testing Python Code
Write small tests that protect behavior and make refactoring safer.
Tests help you know whether code still behaves correctly after changes.
Start with the idea
A useful test arranges input, performs an action, and checks an expected result. Start with pure functions because they are easy to test deterministically.
Small working example
Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5 A useful test arranges input, performs an action, and checks an expected result. Start with pure functions because they are easy to test deterministically.
- Tests protect behavior.
- Assertions express expected results.
- Small deterministic units are easiest to test.
The example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.
Common beginner mistake
Writing tests that only exercise implementation details instead of observable behavior.
Assert the contract the caller depends on, including important edge cases.
Quick recap
- Tests protect behavior.
- Assertions express expected results.
- Small deterministic units are easiest to test.
Try it yourself
These are deliberately small. If you can complete them without copying the example, you are ready to continue.
- Test a function with normal input.
- Add one edge-case test.