self.subTest is a part of Django's
TestCase class and is used as follows:
def test_a_view(self): response = self.client.get(url) with self.subTest("Response status code"): self.assertEqual(response.status_code, 200) with self.subTest("Response content"): # Assertions about the content
In addition to the obvious boon to readability, this allows more granularity in test success/failure. Consider the version of the above test that does not use
def test_a_view(self): response = self.client.get(url) self.assertEqual(response.status_code, 200) # Assertions about the content
If this second test fails, you do not immediately know whether the problem is in the response status code or the response content. You have to read the test logs to check. You could address this by writing a separate unit test for content and status code, but that adds a lot of boilerplate and potentially slows down your tests by having to run
setUp multiple times, etc.
By contrast, when the version using
subTest fails, you get something like this:
It is obvious at a glance which portion of the test has failed, no splitting into multiple tests required.