Labs ICT
โญ Pro Login

SubTest for Parameterized Testing

Running multiple test cases with subtests

SubTest for Parameterized Testing

self.subTest() allows you to run multiple test cases within a single test method. If one subtest fails, the others still continue running, giving you a complete picture of what works and what doesn't.

Basic Usage

import unittest

class TestMath(unittest.TestCase):
    def test_addition(self):
        test_cases = [
            (1, 1, 2),
            (2, 3, 5),
            (-1, 1, 0),
            (0, 0, 0),
        ]
        for a, b, expected in test_cases:
            with self.subTest(a=a, b=b, expected=expected):
                self.assertEqual(a + b, expected)

Without SubTest

# Without subTest, test stops at first failure:
def test_without_subtest(self):
    self.assertEqual(1 + 1, 2)  # passes
    self.assertEqual(1 + 1, 3)  # FAILS โ€” stops here
    self.assertEqual(1 + 1, 4)  # never runs

# With subTest, all cases run even if some fail:
def test_with_subtest(self):
    self.assertEqual(1 + 1, 2)  # passes
    with self.subTest():         # FAILS but continues
        self.assertEqual(1 + 1, 3)
    with self.subTest():         # still runs
        self.assertEqual(1 + 1, 4)

Named SubTests

def test_user_permissions(self):
    users = ["admin", "editor", "viewer"]
    permissions = {
        "admin": ["read", "write", "delete"],
        "editor": ["read", "write"],
        "viewer": ["read"],
    }
    for user in users:
        for perm in permissions[user]:
            with self.subTest(user=user, permission=perm):
                self.assertTrue(has_permission(user, perm))

Key Takeaway

Use self.subTest() to run multiple parameterized cases in one test method. Each subtest runs independently โ€” failures in one don't stop the others from executing.

๐Ÿงช Quick Quiz

With subtests, what does self.subTest() do?