Skip to content

15. Distinguishing test iterations using subtests

NaveenS edited this page Aug 13, 2019 · 1 revision

When there are very small differences among your tests, for instance some parameters, unittest allows to distinguish them inside the body of a test method using the subTest() context manager

subTest(msg=None, **params)

Return a context manager which executes the enclosed code block as a subtest. msg and params are optional, arbitrary values which are displayed whenever a subtest fails, allowing you to identify them clearly.

A test case can contain any number of subtest declarations, and they can be arbitrarily nested.

import unittest

class DivisibleTest(unittest.TestCase):

    def test_Divisible_By_13(self):
        """
        Test the numbers divisible by 13 in range 481 to 485
        """
        for i in range(481,485):
            with self.subTest(i=i):
                print(i)
                self.assertEqual(i % 13, 0)
Clone this wiki locally