Grouping related tests helps keep your tests organized and easy to find. It makes running and understanding tests simpler.
0
0
Grouping related tests in PyTest
Introduction
When you have many tests for different parts of your app and want to keep them separate.
When you want to run only a specific set of tests related to one feature.
When you want to share setup or cleanup code for a group of tests.
When you want to improve test reports by grouping results logically.
Syntax
PyTest
import pytest @pytest.mark.group_name def test_example(): assert True # Or use classes to group tests class TestGroupName: def test_one(self): assert True def test_two(self): assert True
You can use @pytest.mark to tag tests with a group name.
Using classes groups tests inside one container without needing extra decorators.
Examples
Here, both tests are marked with 'login' to group them.
PyTest
import pytest @pytest.mark.login def test_login_success(): assert True @pytest.mark.login def test_login_failure(): assert False
Tests inside the class
TestMathOperations are grouped together.PyTest
class TestMathOperations: def test_add(self): assert 1 + 1 == 2 def test_subtract(self): assert 2 - 1 == 1
Sample Program
This example shows two ways to group tests: using @pytest.mark and using classes.
Tests marked with 'calculator' belong to one group, and string tests are grouped in a class.
PyTest
import pytest @pytest.mark.calculator def test_multiply(): assert 3 * 3 == 9 @pytest.mark.calculator def test_divide(): assert 10 / 2 == 5 class TestStringMethods: def test_upper(self): assert 'hello'.upper() == 'HELLO' def test_isupper(self): assert 'HELLO'.isupper() is True
OutputSuccess
Important Notes
Use descriptive group names to make tests easy to find.
You can run tests by group using pytest -m group_name.
Classes group tests logically and can share setup code with setup_method.
Summary
Grouping tests keeps your test suite organized and easier to manage.
Use @pytest.mark or classes to group related tests.
Running tests by group helps focus on specific features or fixes.