Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Tests and Assertions

Organizing Tests with Classes

Learn when to group pytest tests in classes, how each test gets a fresh instance, how setup_method and teardown_method work, and why fixtures usually beat them.

A growing test file soon holds dozens of functions. You want to see at a glance which tests belong together: all the tests for Cart.add, all the tests for validation, all the tests for the "empty cart" situation. pytest lets you group tests in a class whose name starts with Test. Unlike unittest, the class does not inherit from anything; it is just a namespace.

This lesson explains the grouping rules, one rule that surprises almost everyone (every test gets a new instance of the class), and when to prefer plain functions.

Grouping with a class

Python A test class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The node ids now contain the class name (test_cart.py::TestCartAdding::test_add_one_item), so you can run a whole group with pytest test_cart.py::TestCartAdding or with -k Adding.

Rules to remember:

  • The class name must start with Test (capital T).
  • The class must not define __init__. pytest creates the instance itself and would have no way to pass arguments.
  • Methods start with test and take self as usual.
  • No base class is required.

Every test gets a fresh instance

This is the surprise. In unittest and in other languages you might expect an attribute set in one test to still be there in the next. In pytest it is not. For each test method, pytest creates a new instance of the class:

Python Fresh instance per test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Both tests pass because self.counter += 1 creates an instance attribute on a brand-new object each time, leaving the class attribute at 0. This design keeps tests independent. If you need to share mutable data across tests on purpose, you almost certainly want a fixture with a wider scope instead.

A mutable class attribute (a list or dict defined directly in the class body) is shared by all instances, so tests can leak state into each other. Create such objects inside a method or a fixture.

setup_method and teardown_method

If every test in the class needs the same starting object, you can write special methods that pytest calls around each test:

Python setup_method and teardown_method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The -rP option shows the captured output of passing tests: for each test, the text printed during setup and teardown appears in its own section, and the hooks run once per test. The related hooks are:

Method Runs
setup_method(self, method) / teardown_method around every test method
setup_class(cls) / teardown_class once per class (use @classmethod)
setup_module(module) / teardown_module once per file
setup_function(function) / teardown_function around every plain function in a module

These are xunit-style hooks, kept for people coming from other frameworks. They work, but pytest's own fixtures are more flexible, as the next chapter shows.

Classes and marks

A mark on a class applies to every test in it, which is a neat way to configure a group:

Python
import pytest

@pytest.mark.slow
class TestBigImport:
    def test_one(self): ...
    def test_two(self): ...

You will meet marks in the last lesson of this chapter. Fixtures can apply to a class too, with @pytest.mark.usefixtures("name").

Inheritance in test classes

A test class may inherit from a plain base class to reuse tests or helpers. Tests defined in the base are collected in each subclass (when the base name does not start with Test, it is not collected on its own):

Python Reusing tests through a base class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same behavior checks run against two implementations. This "contract test" pattern is great for interfaces with several implementations. Use it sparingly; deep inheritance makes tests hard to read.

Class or plain functions?

Use a class when Use plain functions when
tests clearly cluster around one object or feature tests are independent and few
you want to apply one mark to a group each test needs a different setup
you want a shared base with contract tests you prefer flat, simple files

Many pytest users write mostly functions and add a class only to group. Do not use a class "because Java does". Both styles are equal in the eyes of pytest, and you can mix them in a file.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which class will pytest collect?

    The class name must start with Test and it must not define init. No base class is required.
  2. 2. Test A sets self.value = 5. Does test B in the same class see it?

    Each test method runs on a fresh instance, which keeps tests independent.
  3. 3. What does setup_method(self, method) do?

    setup_method is called before each test method; teardown_method after it.
  4. 4. How can you run only the tests of class TestCartAdding in test_cart.py?

    A node id can end at the class: file::Class selects all of its tests.

Summary

  • A class named Test... without __init__ groups related tests; no base class is needed.
  • Each test method runs on a new instance, so instance state does not leak between tests.
  • setup_method and friends exist for xunit-style setup, but fixtures are the more powerful tool.
  • Marks on a class apply to all its tests; base classes can share contract tests.
  • Plain functions are just as valid. Use classes to group, not by habit.

Next: Fixtures Basics