Python · Advanced level

Advanced level · Module 2: Testing and Code Quality · Lesson 1 of 4

Unit Testing with pytest

Write small automated tests that check functions and classes every time code changes.

In this lesson you will

  • Write and run pytest tests
  • Test normal, edge and error cases

Key concepts

unit testassertpytest.raisesfixture

The lesson

A unit test is a small function that checks one behaviour of your code automatically. pytest finds files named test_*.py, runs every function starting with test_, and reports which pass and fail.

Tests use plain assert statements: assert account.balance == 500. To test that an error is raised, use with pytest.raises(ValueError):.

Automated tests let you change code with confidence. Run them after every change; a failing test points straight to what broke.

Step by step

  1. Install pytest in your venv.
  2. Create test_bank.py and write a test for deposit().
  3. Add tests for overdrafts, zero amounts and statements.
  4. Run pytest and fix anything that fails.

Practice activity

Write at least eight tests for your BankAccount class, including overdraft attempts and zero amounts.

Expected result: A passing suite of eight or more meaningful tests.

Check your understanding

  1. Why test edge cases such as zero and empty input?

    Show answer

    Bugs cluster at boundaries; normal cases often pass while edges fail.

Further learning

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.