Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions NEWS
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ Changes and improvements to testtools_, grouped by release.
NEXT
~~~~

Bug fixes
---------

* Emit a final failure status for ``testtools.TestCase`` subtest failures
reported through ``ExtendedToStreamDecorator``. Previously, these tests
remained in progress in subunit streams, causing runners such as stestr
to report an unfinished test instead of counting a failure.

2.9.2
~~~~~

Expand Down
62 changes: 62 additions & 0 deletions tests/test_testcase.py
Original file line number Diff line number Diff line change
Expand Up @@ -2664,6 +2664,68 @@ def test_it(self):
decorator.stopTestRun()
self.assertEqual(1, summary.testsRun)
self.assertEqual(False, summary.wasSuccessful())
self.assertEqual(1, len(summary.errors))
self.assertIn("boom", summary.errors[0][1])

def test_stream_result_reports_multiple_subtest_errors(self):
class Case(TestCase):
def test_it(self):
for i in range(2):
with self.subTest(i=i):
raise RuntimeError(f"boom {i}")

case = Case("test_it")
summary = StreamSummary()
decorator = ExtendedToStreamDecorator(summary)
decorator.startTestRun()
case.run(decorator)
decorator.stopTestRun()

self.assertEqual(1, summary.testsRun)
self.assertEqual(1, len(summary.errors))
self.assertEqual(case.id(), summary.errors[0][0].id())
self.assertIn("boom 0", summary.errors[0][1])
self.assertIn("boom 1", summary.errors[0][1])

def test_stream_result_subtest_and_parent_failure_count_once(self):
class Case(TestCase):
def test_it(self):
with self.subTest(i=1):
self.fail("subtest failed")
self.fail("parent failed")

summary = StreamSummary()
decorator = ExtendedToStreamDecorator(summary)
decorator.startTestRun()
Case("test_it").run(decorator)
decorator.stopTestRun()

self.assertEqual(1, summary.testsRun)
self.assertEqual(1, len(summary.errors))
self.assertIn("subtest failed", summary.errors[0][1])
self.assertIn("parent failed", summary.errors[0][1])

def test_stream_result_does_not_fail_following_test(self):
class Case(TestCase):
def test_fail(self):
with self.subTest(i=1):
self.fail("boom")

def test_pass(self):
with self.subTest(i=1):
pass

summary = StreamSummary()
decorator = ExtendedToStreamDecorator(summary)
decorator.startTestRun()
Case("test_fail").run(decorator)
Case("test_pass").run(decorator)
decorator.stopTestRun()

self.assertEqual(2, summary.testsRun)
self.assertEqual(1, len(summary.errors))
self.assertEqual(Case("test_fail").id(), summary.errors[0][0].id())
self.assertIn("boom", summary.errors[0][1])

def test_stream_result_counts_one_test_for_skip(self):
class Case(TestCase):
Expand Down
89 changes: 65 additions & 24 deletions tests/test_testresult.py
Original file line number Diff line number Diff line change
Expand Up @@ -1364,20 +1364,60 @@ def _subDescription(self):
self.assertEqual(event1.test_id, test_id)
self.assertEqual(event1.test_status, "inprogress")

# The traceback attachment for the subtest
event2 = events[2]
assert isinstance(event2, _StatusEvent)
self.assertEqual(event2.test_id, test_id)
self.assertEqual(event2.file_name, "traceback (i=1)")
self.assertIn(b"AssertionError: subtest failed", event2.file_bytes)
# The traceback attachment may span several stream events.
attachments = events[2:-2]
for event in attachments:
self.assertEqual(event.test_id, test_id)
self.assertEqual(event.file_name, "traceback (i=1)")
self.assertIn(
b"AssertionError: subtest failed",
b"".join(event.file_bytes for event in attachments),
)
self.assertTrue(attachments[-1].eof)

# The final fail status
event3 = events[3]
assert isinstance(event3, _StatusEvent)
self.assertEqual(event3.test_id, test_id)
self.assertEqual(event3.test_status, "fail")
self.assertEqual(events[-2].test_id, test_id)
self.assertEqual(events[-2].test_status, "fail")
self.assertEqual(events[-1], ("stopTestRun",))

def test_testtools_subtest_failure_emits_parent_status(self):
events_during_subtests = []

class Case(TestCase):
def test_it(self):
for i in range(2):
with self.subTest(i=i):
self.addDetail("clue", text_content(f"clue {i}"))
self.fail("boom")
events_during_subtests.append(list(log._events))

case = Case("test_it")
log = LoggingStreamResult()
result = ExtendedToStreamDecorator(log)
result.startTestRun()
case.run(result)
result.stopTestRun()

self.assertEqual(events[4], ("stopTestRun",))
self.assertEqual(
[(case.id(), "inprogress"), (case.id(), "fail")],
[
(event.test_id, event.test_status)
for event in log._events
if event[0] == "status" and event.test_status is not None
],
)

# Details are buffered until the parent finishes, not emitted twice.
self.assertEqual([2, 2], [len(e) for e in events_during_subtests])
for i in range(2):
self.assertEqual(
f"clue {i}".encode(),
b"".join(
event.file_bytes
for event in log._events
if event[0] == "status" and event.file_name == f"clue (i={i})"
),
)

def test_subtest_success_no_events(self):
# Test that successful subtests don't generate events
Expand Down Expand Up @@ -1464,21 +1504,22 @@ def _subDescription(self):
assert isinstance(event1, _StatusEvent)
self.assertEqual(event1.test_status, "inprogress")

# Two traceback attachments
event2 = events[2]
assert isinstance(event2, _StatusEvent)
self.assertEqual(event2.file_name, "traceback (i=1)")
self.assertIn(b"subtest 1 failed", event2.file_bytes)
event3 = events[3]
assert isinstance(event3, _StatusEvent)
self.assertEqual(event3.file_name, "traceback (i=2)")
self.assertIn(b"subtest 2 failed", event3.file_bytes)
# Two traceback attachments, possibly split across stream events.
for i in (1, 2):
attachments = [
event
for event in events[2:-2]
if event.file_name == f"traceback (i={i})"
]
self.assertIn(
f"subtest {i} failed".encode(),
b"".join(event.file_bytes for event in attachments),
)
self.assertTrue(attachments[-1].eof)

# Final fail status
event4 = events[4]
assert isinstance(event4, _StatusEvent)
self.assertEqual(event4.test_status, "fail")
self.assertEqual(events[5], ("stopTestRun",))
self.assertEqual(events[-2].test_status, "fail")
self.assertEqual(events[-1], ("stopTestRun",))


class TestResourcedToStreamDecorator(TestCase):
Expand Down
96 changes: 45 additions & 51 deletions testtools/testresult/real.py
Original file line number Diff line number Diff line change
Expand Up @@ -2224,7 +2224,7 @@ def __init__(self, decorated: StreamResult) -> None:
self._started = False
self._tags: TagContext | None = None
self.__now: datetime.datetime | None = None
self._subtest_failures: list[tuple[unittest.TestCase, OptExcInfo]] = []
self._subtest_failures: list[DetailsDict] = []

def _get_failfast(self) -> bool:
return len(self.targets) == 2
Expand Down Expand Up @@ -2254,32 +2254,7 @@ def stopTest(self, test: unittest.TestCase) -> None:
# for the parent test. When all subtests pass, unittest calls
# addSuccess for the parent, so we don't need to emit a status here.
if self._subtest_failures:
test_id = test.id()
now = self._now()
# Emit traceback for each failed subtest as a file attachment
for subtest, err in self._subtest_failures:
# Use subtest description to create unique attachment name
subtest_desc = subtest._subDescription() # type: ignore[attr-defined]
attachment_name = f"traceback {subtest_desc}"
content = TracebackContent(err, subtest)
mime_type = repr(content.content_type)
file_bytes = b"".join(content.iter_bytes())
self.status(
file_name=attachment_name,
file_bytes=file_bytes,
eof=True,
mime_type=mime_type,
test_id=test_id,
timestamp=now,
)
# Emit final fail status for the parent test
self.status(
test_id=test_id,
test_status="fail",
test_tags=self.current_tags,
timestamp=now,
)
# Clear subtest tracking
self._convert(test, None, {}, "fail")
self._subtest_failures = []

def addError(
Expand Down Expand Up @@ -2321,34 +2296,20 @@ def _convert(
details = {
f"{name} {label}": detail for name, detail in (details or {}).items()
}
if status == "fail":
self._subtest_failures.append(details)
return
if status not in ("skip", "xfail"):
status = None # type: ignore[assignment]
else:
test_id = test.id()
if status == "fail":
# Flush buffered subtest details before completing the parent.
for subtest_details in self._subtest_failures:
self._emit_details(test_id, subtest_details, now)
self._subtest_failures = []
if details is not None:
for name, content in details.items():
mime_type = repr(content.content_type)
file_bytes = None
for next_bytes in content.iter_bytes():
if file_bytes is not None:
self.status(
file_name=name,
file_bytes=file_bytes,
mime_type=mime_type,
test_id=test_id,
timestamp=now,
)
file_bytes = next_bytes
if file_bytes is None:
file_bytes = b""
self.status(
file_name=name,
file_bytes=file_bytes,
eof=True,
mime_type=mime_type,
test_id=test_id,
timestamp=now,
)
self._emit_details(test_id, details, now)
if reason is not None:
self.status(
file_name="reason",
Expand All @@ -2366,6 +2327,36 @@ def _convert(
timestamp=now,
)

def _emit_details(
self,
test_id: str,
details: DetailsDict,
timestamp: datetime.datetime,
) -> None:
for name, content in details.items():
mime_type = repr(content.content_type)
file_bytes = None
for next_bytes in content.iter_bytes():
if file_bytes is not None:
self.status(
file_name=name,
file_bytes=file_bytes,
mime_type=mime_type,
test_id=test_id,
timestamp=timestamp,
)
file_bytes = next_bytes
if file_bytes is None:
file_bytes = b""
self.status(
file_name=name,
file_bytes=file_bytes,
eof=True,
mime_type=mime_type,
test_id=test_id,
timestamp=timestamp,
)

def addExpectedFailure(
self,
test: unittest.TestCase,
Expand Down Expand Up @@ -2411,7 +2402,10 @@ def addSubTest(
"""
# Collect failures to report when the parent test completes
if err is not None:
self._subtest_failures.append((subtest, err))
label = subtest._subDescription() # type: ignore[attr-defined]
self._subtest_failures.append(
{f"traceback {label}": TracebackContent(err, subtest)}
)

def _check_args(self, err: OptExcInfo | None, details: DetailsDict | None) -> None:
param_count = 0
Expand Down