Course contentsShow
← Python
Lesson 755 of 1,06012. Testing and DebuggingFree lesson

Organizing Test Suites with Classes and Markers

Group related tests into classes and apply custom markers to categorize and selectively run specific subsets of your overall test suite.

In this lesson, you will learn how to structure your growing test suite using Python classes and categorize specific groups of tests using custom markers.

Organizing Tests with Classes

As your project grows, your test_ files can quickly become cluttered with dozens of independent functions. To keep things clean, you can group related tests inside a class. In pytest, any class name starting with Test will be automatically discovered, and every method inside that starts with test_ will be treated as an individual test case.

class TestUserAccount:
    def test_login(self):
        assert True
        
    def test_logout(self):
        assert True

This structure makes it easier to share pytest fixtures across related tests and provides a logical hierarchy for your test suite.

Categorizing with Markers

Sometimes you want to run only a subset of your tests—for example, skipping slow integration tests while keeping fast unit tests running during development. You can achieve this using pytest markers.

First, you "tag" a test or a whole class using the @pytest.mark decorator:

import pytest

@pytest.mark.slow
def test_heavy_computation():
    # This might take 30 seconds
    assert True

To run only the tests marked as "slow," you execute pytest from your terminal with the -m flag: pytest -m slow

Conversely, you can exclude specific markers using not: pytest -m "not slow"

Markers are particularly powerful because you can apply them to an entire class, instantly tagging every test method inside it with that single category. This allows you to manage large suites by defining "smoke tests," "integration tests," or "database tests" without renaming files or moving functions around.

By combining classes for organization and markers for selection, you maintain a professional, high-performance test suite that scales alongside your application code.

Key Takeaway: Use classes to group related tests for better readability, and apply custom markers to create flexible execution subsets within your test suite.