Debian Codegraph @

python/tests/test_junitxml2subunit.py

raw
1 #
2 # subunit: extensions to python unittest to get test results from subprocesses.
3 # Copyright (C) 2026 Jelmer Vernooij <[email protected]>
4 #
5 # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
6 # license at the users choice. A copy of both licenses are available in the
7 # project source as Apache-2.0 and BSD. You may not use this file except in
8 # compliance with one of these two licences.
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # license you chose for the specific language governing permissions and
14 # limitations under that license.
15 #
16
17 """Tests for JUnitXML2SubUnit."""
18
19 import io
20 import os
21 import tempfile
22 from unittest import mock
23
24 from testtools import TestCase
25 from testtools.testresult.doubles import StreamResult
26
27 import subunit
28 from subunit.filter_scripts import junitxml2subunit
29
30
31 def _write(tmpdir, name, content):
32 path = os.path.join(tmpdir, name)
33 with open(path, "w", encoding="utf-8") as fh:
34 fh.write(content)
35 return path
36
37
38 class TestJUnitXML2SubUnit(TestCase):
39 """Behavioural tests for `JUnitXML2SubUnit`.
40
41 Each test writes a synthetic JUnit XML doc to disk, runs the converter,
42 decodes the resulting subunit bytes back into events via
43 `StreamResult`, and asserts on the (test_id, test_status) tuples.
44 """
45
46 def setUp(self):
47 super().setUp()
48 self.tmp = tempfile.mkdtemp(prefix="junitxml2subunit-test-")
49 self.addCleanup(self._rmtree, self.tmp)
50 self.subunit = io.BytesIO()
51
52 def _rmtree(self, path):
53 import shutil
54
55 shutil.rmtree(path, ignore_errors=True)
56
57 def _events(self):
58 self.subunit.seek(0)
59 sink = StreamResult()
60 subunit.ByteStreamToStreamResult(self.subunit).run(sink)
61 return sink._events
62
63 def _statuses(self, events):
64 return [(e[1], e[2]) for e in events if e[0] == "status"]
65
66 def test_passing_testcase(self):
67 path = _write(
68 self.tmp,
69 "TEST-FooTest.xml",
70 """<?xml version="1.0" encoding="UTF-8"?>
71 <testsuite name="com.example.FooTest" tests="1" failures="0" errors="0" skipped="0" time="0.123">
72 <testcase classname="com.example.FooTest" name="testBar" time="0.05"/>
73 </testsuite>
74 """,
75 )
76 rc = subunit.JUnitXML2SubUnit([path], self.subunit)
77 self.assertEqual(0, rc)
78 self.assertEqual(
79 [
80 ("com.example.FooTest::testBar", "inprogress"),
81 ("com.example.FooTest::testBar", "success"),
82 ],
83 self._statuses(self._events()),
84 )
85
86 def test_failure_marks_fail_and_returns_nonzero(self):
87 path = _write(
88 self.tmp,
89 "TEST-FooTest.xml",
90 """<?xml version="1.0" encoding="UTF-8"?>
91 <testsuite name="com.example.FooTest" tests="1" failures="1">
92 <testcase classname="com.example.FooTest" name="testBar" time="0.01">
93 <failure type="java.lang.AssertionError" message="expected x but was y">at line 42</failure>
94 </testcase>
95 </testsuite>
96 """,
97 )
98 rc = subunit.JUnitXML2SubUnit([path], self.subunit)
99 self.assertEqual(1, rc)
100 events = self._events()
101 terminal = [e for e in events if e[0] == "status" and e[1] == "com.example.FooTest::testBar" and e[2] == "fail"]
102 self.assertEqual(1, len(terminal))
103 # The failure detail (type + message + body) is folded into a
104 # single attachment so consumers see everything in one place.
105 ev = terminal[0]
106 self.assertEqual("junit detail", ev[5])
107 # The decoder returns the attachment as a memoryview; coerce to
108 # bytes for substring searching.
109 body = bytes(ev[6])
110 self.assertIn(b"java.lang.AssertionError", body)
111 self.assertIn(b"expected x but was y", body)
112 self.assertIn(b"at line 42", body)
113
114 def test_error_is_treated_as_fail(self):
115 # An <error> in JUnit terms is "an unexpected exception". subunit
116 # has no separate "error" status that maps cleanly, and from a
117 # consumer's perspective both mean "did not pass" — so it lands
118 # on `fail` like a failure does.
119 path = _write(
120 self.tmp,
121 "TEST-FooTest.xml",
122 """<?xml version="1.0"?>
123 <testsuite>
124 <testcase classname="com.example.FooTest" name="testBar">
125 <error type="java.lang.NullPointerException">stack trace</error>
126 </testcase>
127 </testsuite>
128 """,
129 )
130 rc = subunit.JUnitXML2SubUnit([path], self.subunit)
131 self.assertEqual(1, rc)
132 statuses = self._statuses(self._events())
133 self.assertIn(("com.example.FooTest::testBar", "fail"), statuses)
134
135 def test_skipped(self):
136 path = _write(
137 self.tmp,
138 "TEST-FooTest.xml",
139 """<?xml version="1.0"?>
140 <testsuite>
141 <testcase classname="com.example.FooTest" name="testBar">
142 <skipped message="ignored for now"/>
143 </testcase>
144 </testsuite>
145 """,
146 )
147 rc = subunit.JUnitXML2SubUnit([path], self.subunit)
148 self.assertEqual(0, rc)
149 statuses = self._statuses(self._events())
150 self.assertIn(("com.example.FooTest::testBar", "skip"), statuses)
151
152 def test_testsuites_wrapper_is_unwrapped(self):
153 # Some emitters (Gradle, Ant) wrap multiple <testsuite> in a
154 # <testsuites> root; both shapes need to work.
155 path = _write(
156 self.tmp,
157 "report.xml",
158 """<?xml version="1.0"?>
159 <testsuites>
160 <testsuite name="A">
161 <testcase classname="A" name="testOne"/>
162 </testsuite>
163 <testsuite name="B">
164 <testcase classname="B" name="testTwo"/>
165 </testsuite>
166 </testsuites>
167 """,
168 )
169 rc = subunit.JUnitXML2SubUnit([path], self.subunit)
170 self.assertEqual(0, rc)
171 statuses = self._statuses(self._events())
172 self.assertIn(("A::testOne", "success"), statuses)
173 self.assertIn(("B::testTwo", "success"), statuses)
174
175 def test_multiple_files_concatenate(self):
176 a = _write(
177 self.tmp,
178 "TEST-A.xml",
179 """<?xml version="1.0"?>
180 <testsuite>
181 <testcase classname="A" name="testOne"/>
182 </testsuite>
183 """,
184 )
185 b = _write(
186 self.tmp,
187 "TEST-B.xml",
188 """<?xml version="1.0"?>
189 <testsuite>
190 <testcase classname="B" name="testTwo"/>
191 </testsuite>
192 """,
193 )
194 rc = subunit.JUnitXML2SubUnit([a, b], self.subunit)
195 self.assertEqual(0, rc)
196 statuses = self._statuses(self._events())
197 self.assertIn(("A::testOne", "success"), statuses)
198 self.assertIn(("B::testTwo", "success"), statuses)
199
200 def test_missing_classname_falls_back_to_name(self):
201 # `classname` is technically optional; without it the test ID
202 # is just the bare method name rather than emitting "::name".
203 path = _write(
204 self.tmp,
205 "report.xml",
206 """<?xml version="1.0"?>
207 <testsuite>
208 <testcase name="bareName"/>
209 </testsuite>
210 """,
211 )
212 rc = subunit.JUnitXML2SubUnit([path], self.subunit)
213 self.assertEqual(0, rc)
214 statuses = self._statuses(self._events())
215 self.assertIn(("bareName", "success"), statuses)
216
217 def test_unparseable_xml_counts_as_failure(self):
218 # A broken file is loud (stderr warning + non-zero exit) rather
219 # than silently dropping the suite — broken XML in a CI report
220 # almost always means a test runner crash.
221 path = _write(self.tmp, "broken.xml", "<<not really xml>>")
222 with mock.patch("sys.stderr", new=io.StringIO()) as stderr:
223 rc = subunit.JUnitXML2SubUnit([path], self.subunit)
224 self.assertEqual(1, rc)
225 self.assertIn("failed to parse", stderr.getvalue())
226
227 def test_time_attribute_advances_synthetic_clock(self):
228 # Each testcase's `time` attribute should determine the gap
229 # between its inprogress and terminal packets, so the consumer
230 # can recover the duration. Use distinct values per test to
231 # confirm both make it through.
232 path = _write(
233 self.tmp,
234 "report.xml",
235 """<?xml version="1.0"?>
236 <testsuite>
237 <testcase classname="A" name="testOne" time="0.5"/>
238 <testcase classname="A" name="testTwo" time="1.5"/>
239 </testsuite>
240 """,
241 )
242 subunit.JUnitXML2SubUnit([path], self.subunit)
243 events = self._events()
244
245 # Pull the per-test (inprogress, terminal) timestamp pairs. The
246 # ByteStreamToStreamResult emits a "time" event before each
247 # status event when the packet carries a timestamp.
248 # Easier: walk the events and pair them up by test_id.
249 timestamps = {}
250 for e in events:
251 if e[0] != "status":
252 continue
253 test_id = e[1]
254 ts = e[-1]
255 if ts is None:
256 continue
257 timestamps.setdefault(test_id, []).append(ts)
258
259 one = timestamps["A::testOne"]
260 two = timestamps["A::testTwo"]
261 self.assertEqual(2, len(one))
262 self.assertEqual(2, len(two))
263 # testOne spans 0.5s
264 self.assertAlmostEqual(0.5, (one[1] - one[0]).total_seconds(), places=3)
265 # testTwo spans 1.5s
266 self.assertAlmostEqual(1.5, (two[1] - two[0]).total_seconds(), places=3)
267
268
269 class TestCollectFiles(TestCase):
270 """Tests for the `--dir` walking logic in the script entrypoint."""
271
272 def setUp(self):
273 super().setUp()
274 self.tmp = tempfile.mkdtemp(prefix="junitxml2subunit-collect-")
275 self.addCleanup(self._rmtree, self.tmp)
276
277 def _rmtree(self, path):
278 import shutil
279
280 shutil.rmtree(path, ignore_errors=True)
281
282 def test_dir_walks_xml_files_only(self):
283 a = _write(self.tmp, "TEST-A.xml", "")
284 _write(self.tmp, "ignored.txt", "")
285 b = _write(self.tmp, "TEST-B.xml", "")
286 out = junitxml2subunit.collect_files([self.tmp], [])
287 self.assertEqual({a, b}, set(out))
288
289 def test_dir_results_are_sorted_for_deterministic_output(self):
290 # Lexical sort within a directory so the subunit stream is
291 # reproducible across runs (and across filesystems with
292 # different readdir order).
293 b = _write(self.tmp, "TEST-B.xml", "")
294 a = _write(self.tmp, "TEST-A.xml", "")
295 out = junitxml2subunit.collect_files([self.tmp], [])
296 self.assertEqual([a, b], out)
297
298 def test_explicit_files_appended_after_dir_walks(self):
299 a = _write(self.tmp, "TEST-A.xml", "")
300 # Build an explicit file outside the walked dir to confirm it's
301 # appended after the discovered files rather than re-walked.
302 extra_dir = tempfile.mkdtemp(prefix="junitxml2subunit-extra-")
303 self.addCleanup(self._rmtree, extra_dir)
304 explicit = _write(extra_dir, "extra.xml", "")
305 out = junitxml2subunit.collect_files([self.tmp], [explicit])
306 self.assertEqual([a, explicit], out)
307
308 def test_missing_dir_warned_and_skipped(self):
309 with mock.patch("sys.stderr", new=io.StringIO()) as stderr:
310 out = junitxml2subunit.collect_files(["/nonexistent/junit/dir"], [])
311 self.assertEqual([], out)
312 self.assertIn("not a directory", stderr.getvalue())