Skip to content

Commit d4a6af3

Browse files
authored
Merge pull request #630 from CyrilRoelandteNovance/fix-subtest-testtools-testcase
Add subTest support for testtools.TestCase
2 parents 5c1785c + f662ae4 commit d4a6af3

3 files changed

Lines changed: 215 additions & 0 deletions

File tree

‎tests/test_testcase.py‎

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2343,6 +2343,150 @@ def test_other_attribute(self):
23432343
self.assertRaises(AttributeError, getattr, orig, "thing")
23442344

23452345

2346+
class TestSubTest(TestCase):
2347+
"""Tests for testtools.TestCase.subTest support."""
2348+
2349+
run_test_with = FullStackRunTest
2350+
2351+
def _run_case(self, case):
2352+
result = ExtendedTestResult()
2353+
case.run(result)
2354+
return result
2355+
2356+
def test_passing_subtests(self):
2357+
class Case(TestCase):
2358+
def test_it(self):
2359+
for i in (0, 2, 4):
2360+
with self.subTest(i=i):
2361+
self.assertEqual(i % 2, 0)
2362+
2363+
result = self._run_case(Case("test_it"))
2364+
self.assertIn("addSuccess", [e[0] for e in result._events])
2365+
self.assertEqual([], result.failures)
2366+
2367+
def test_single_failure(self):
2368+
class Case(TestCase):
2369+
def test_it(self):
2370+
for i in (0, 1, 2):
2371+
with self.subTest(i=i):
2372+
self.assertEqual(i % 2, 0)
2373+
2374+
result = self._run_case(Case("test_it"))
2375+
self.assertNotIn("addSuccess", [e[0] for e in result._events])
2376+
self.assertEqual(1, len(result.failures))
2377+
subtest = result.failures[0][0]
2378+
self.assertIn("(i=1)", str(subtest))
2379+
2380+
def test_multiple_failures(self):
2381+
class Case(TestCase):
2382+
def test_it(self):
2383+
for i in range(4):
2384+
with self.subTest(i=i):
2385+
self.assertEqual(i % 2, 0)
2386+
2387+
result = self._run_case(Case("test_it"))
2388+
self.assertEqual(2, len(result.failures))
2389+
descriptions = [str(f[0]) for f in result.failures]
2390+
self.assertTrue(
2391+
any("(i=1)" in d for d in descriptions),
2392+
f"Expected a failure for (i=1), got {descriptions}",
2393+
)
2394+
self.assertTrue(
2395+
any("(i=3)" in d for d in descriptions),
2396+
f"Expected a failure for (i=3), got {descriptions}",
2397+
)
2398+
2399+
def test_failure_continues_loop(self):
2400+
class Case(TestCase):
2401+
def __init__(self, *args, **kwargs):
2402+
super().__init__(*args, **kwargs)
2403+
self.iterations = []
2404+
2405+
def test_it(self):
2406+
for i in range(4):
2407+
with self.subTest(i=i):
2408+
self.iterations.append(i)
2409+
self.assertEqual(i % 2, 0)
2410+
2411+
case = Case("test_it")
2412+
self._run_case(case)
2413+
self.assertEqual([0, 1, 2, 3], case.iterations)
2414+
2415+
def test_with_msg(self):
2416+
class Case(TestCase):
2417+
def test_it(self):
2418+
with self.subTest(msg="my label", x=42):
2419+
self.fail("boom")
2420+
2421+
result = self._run_case(Case("test_it"))
2422+
self.assertEqual(1, len(result.failures))
2423+
description = str(result.failures[0][0])
2424+
self.assertIn("[my label]", description)
2425+
self.assertIn("(x=42)", description)
2426+
2427+
def test_multiple_params(self):
2428+
class Case(TestCase):
2429+
def test_it(self):
2430+
with self.subTest(a=1, b="two"):
2431+
self.fail("boom")
2432+
2433+
result = self._run_case(Case("test_it"))
2434+
self.assertEqual(1, len(result.failures))
2435+
description = str(result.failures[0][0])
2436+
self.assertIn("a=1", description)
2437+
self.assertIn("b='two'", description)
2438+
2439+
def test_no_params(self):
2440+
class Case(TestCase):
2441+
def test_it(self):
2442+
with self.subTest():
2443+
self.fail("boom")
2444+
2445+
result = self._run_case(Case("test_it"))
2446+
self.assertEqual(1, len(result.failures))
2447+
description = str(result.failures[0][0])
2448+
self.assertIn("(<subtest>)", description)
2449+
2450+
def test_nested_subtests(self):
2451+
class Case(TestCase):
2452+
def test_it(self):
2453+
for a in (1, 2):
2454+
with self.subTest(a=a):
2455+
for b in (3, 4):
2456+
with self.subTest(b=b):
2457+
self.assertEqual(a, b)
2458+
2459+
result = self._run_case(Case("test_it"))
2460+
self.assertEqual(4, len(result.failures))
2461+
descriptions = [str(f[0]) for f in result.failures]
2462+
self.assertTrue(
2463+
any("a=1" in d and "b=3" in d for d in descriptions),
2464+
f"Expected a failure with both a=1 and b=3, got {descriptions}",
2465+
)
2466+
self.assertTrue(
2467+
any("a=2" in d and "b=4" in d for d in descriptions),
2468+
f"Expected a failure with both a=2 and b=4, got {descriptions}",
2469+
)
2470+
2471+
def test_skip_inside_subtest(self):
2472+
class Case(TestCase):
2473+
def __init__(self, *args, **kwargs):
2474+
super().__init__(*args, **kwargs)
2475+
self.reached = []
2476+
2477+
def test_it(self):
2478+
for i in range(3):
2479+
with self.subTest(i=i):
2480+
if i == 1:
2481+
self.skipTest("skip this one")
2482+
self.reached.append(i)
2483+
2484+
case = Case("test_it")
2485+
self._run_case(case)
2486+
self.assertEqual([0, 2], case.reached)
2487+
self.assertEqual(1, len(case._subtest_skips))
2488+
2489+
23462490
def test_suite():
23472491
from unittest import TestLoader
23482492

‎testtools/runtest.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,15 @@ def _run_core(self) -> None:
184184
if getattr(self.case, "force_failure", None):
185185
self._run_user(_raise_force_fail_error)
186186
failed = True
187+
for subtest, err in getattr(self.case, "_subtest_failures", ()):
188+
add_subtest = getattr(self.result, "addSubTest", None)
189+
if add_subtest is not None:
190+
add_subtest(self.case, subtest, err)
191+
else:
192+
self.result.addFailure(self.case, err)
193+
failed = True
194+
for subtest, reason in getattr(self.case, "_subtest_skips", ()):
195+
self.result.addSkip(subtest, reason=reason)
187196
if not failed:
188197
self.result.addSuccess(
189198
self.case, details=self.case.getDetails()

‎testtools/testcase.py‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"unique_text_generator",
1616
]
1717

18+
import contextlib
1819
import copy
1920
import datetime
2021
import functools
@@ -99,6 +100,44 @@ class _ExpectedFailure(Exception):
99100
"""
100101

101102

103+
_subtest_msg_sentinel = object()
104+
105+
106+
class SubTest(unittest.TestCase):
107+
"""Describes a single subTest iteration for failure reporting.
108+
109+
Carries the message and parameters passed to ``subTest`` so that
110+
result objects can label each failure with its subTest context.
111+
"""
112+
113+
def __init__(
114+
self, test_case: "TestCase", msg: object, params: dict[str, Any]
115+
) -> None:
116+
super().__init__()
117+
self.test_case = test_case
118+
self.failureException = test_case.failureException
119+
self._msg = msg
120+
self._params = params
121+
122+
def _subDescription(self) -> str:
123+
parts: list[str] = []
124+
if self._msg is not _subtest_msg_sentinel:
125+
parts.append(f"[{self._msg}]")
126+
if self._params:
127+
params_desc = ", ".join(f"{k}={v!r}" for k, v in self._params.items())
128+
parts.append(f"({params_desc})")
129+
return " ".join(parts) or "(<subtest>)"
130+
131+
def id(self) -> str:
132+
return f"{self.test_case.id()} {self._subDescription()}"
133+
134+
def shortDescription(self) -> str | None:
135+
return self.test_case.shortDescription()
136+
137+
def __str__(self) -> str:
138+
return self.id()
139+
140+
102141
# TypeVar for decorators
103142
_P = ParamSpec("_P")
104143
_R = TypeVar("_R")
@@ -378,6 +417,9 @@ def _reset(self) -> None:
378417
# force_failure is set by expectThat() on mismatch; must be
379418
# cleared so re-runs of the same test can succeed.
380419
self.force_failure: bool | None = None
420+
self._subtest_failures: list[tuple[SubTest, ExcInfo]] = []
421+
self._subtest_skips: list[tuple[SubTest, str]] = []
422+
self._subtest_params: dict[str, Any] = {}
381423

382424
def __eq__(self, other: object) -> bool:
383425
eq = getattr(unittest.TestCase, "__eq__", None)
@@ -887,6 +929,26 @@ def _report_traceback(
887929
),
888930
)
889931

932+
@contextlib.contextmanager
933+
def subTest(
934+
self, msg: object = _subtest_msg_sentinel, **params: Any
935+
) -> Iterator[None]:
936+
"""Return a context manager for a subTest."""
937+
merged_params = {**self._subtest_params, **params}
938+
subtest = SubTest(self, msg, merged_params)
939+
old_params, self._subtest_params = self._subtest_params, merged_params
940+
try:
941+
yield
942+
except SkipTest as e:
943+
reason = str(e)
944+
self._subtest_skips.append((subtest, reason))
945+
except Exception:
946+
# Inside except block, exc_info() is guaranteed to have non-None values
947+
exc_info = sys.exc_info()
948+
self._subtest_failures.append((subtest, exc_info)) # type: ignore[arg-type]
949+
finally:
950+
self._subtest_params = old_params
951+
890952
@staticmethod
891953
def _report_unexpected_success(
892954
self: "TestCase", result: TestResult, err: BaseException

0 commit comments

Comments
 (0)