Debian Codegraph @

python/tests/test_gojson2subunit.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 GoJSON2SubUnit."""
18
19 import json
20 from io import BytesIO, StringIO
21
22 from testtools import TestCase
23 from testtools.testresult.doubles import StreamResult
24
25 import subunit
26
27 UTF8_TEXT = "text/plain; charset=UTF8"
28
29
30 def _ndjson(*events):
31 """Render an iterable of dicts as one JSON object per line."""
32 return "\n".join(json.dumps(e) for e in events) + "\n"
33
34
35 class TestGoJSON2SubUnit(TestCase):
36 """Behavioural tests for `GoJSON2SubUnit`.
37
38 Each test feeds a synthetic `go test -json` event stream in, decodes
39 the resulting subunit bytes back into events via `StreamResult`, and
40 asserts on the (status, test_id, test_status, ...) tuples.
41 """
42
43 def setUp(self):
44 super().setUp()
45 self.gojson = StringIO()
46 self.subunit = BytesIO()
47
48 def _events(self):
49 self.subunit.seek(0)
50 sink = StreamResult()
51 subunit.ByteStreamToStreamResult(self.subunit).run(sink)
52 return sink._events
53
54 def _statuses(self, events):
55 # Strip the verbose tuple down to (test_id, test_status) for clearer
56 # assertions when timing/file content isn't what's being tested.
57 return [(e[1], e[2]) for e in events if e[0] == "status"]
58
59 def test_pass_emits_inprogress_then_success(self):
60 self.gojson.write(
61 _ndjson(
62 {"Action": "run", "Package": "pkg/a", "Test": "TestFoo"},
63 {"Action": "pass", "Package": "pkg/a", "Test": "TestFoo", "Elapsed": 0.01},
64 )
65 )
66 self.gojson.seek(0)
67 rc = subunit.GoJSON2SubUnit(self.gojson, self.subunit)
68 self.assertEqual(0, rc)
69 self.assertEqual(
70 [("pkg/a.TestFoo", "inprogress"), ("pkg/a.TestFoo", "success")],
71 self._statuses(self._events()),
72 )
73
74 def test_fail_returns_nonzero(self):
75 self.gojson.write(
76 _ndjson(
77 {"Action": "run", "Package": "pkg/a", "Test": "TestBad"},
78 {"Action": "run", "Package": "pkg/a", "Test": "TestGood"},
79 {"Action": "pass", "Package": "pkg/a", "Test": "TestGood", "Elapsed": 0.01},
80 {"Action": "fail", "Package": "pkg/a", "Test": "TestBad", "Elapsed": 0.02},
81 )
82 )
83 self.gojson.seek(0)
84 rc = subunit.GoJSON2SubUnit(self.gojson, self.subunit)
85 self.assertEqual(1, rc)
86 # Each test produces an inprogress packet and a terminal packet;
87 # check the terminal status (last one wins in dict()).
88 statuses = dict(self._statuses(self._events()))
89 self.assertEqual("fail", statuses["pkg/a.TestBad"])
90 self.assertEqual("success", statuses["pkg/a.TestGood"])
91
92 def test_skip_status(self):
93 self.gojson.write(
94 _ndjson(
95 {"Action": "run", "Package": "pkg/a", "Test": "TestSkipped"},
96 {"Action": "skip", "Package": "pkg/a", "Test": "TestSkipped", "Elapsed": 0.0},
97 )
98 )
99 self.gojson.seek(0)
100 rc = subunit.GoJSON2SubUnit(self.gojson, self.subunit)
101 self.assertEqual(0, rc)
102 self.assertIn(("pkg/a.TestSkipped", "skip"), self._statuses(self._events()))
103
104 def test_subtest_keeps_slash_separator(self):
105 # Go subtests are reported as "Parent/Sub"; the resulting test ID
106 # should be "<package>.Parent/Sub" so it round-trips through
107 # `go test -run '^Parent$/^Sub$'`.
108 self.gojson.write(
109 _ndjson(
110 {"Action": "run", "Package": "pkg/a", "Test": "TestParent/sub_one"},
111 {"Action": "pass", "Package": "pkg/a", "Test": "TestParent/sub_one", "Elapsed": 0.01},
112 )
113 )
114 self.gojson.seek(0)
115 subunit.GoJSON2SubUnit(self.gojson, self.subunit)
116 self.assertIn(
117 ("pkg/a.TestParent/sub_one", "success"),
118 self._statuses(self._events()),
119 )
120
121 def test_output_attached_to_terminal_packet(self):
122 self.gojson.write(
123 _ndjson(
124 {"Action": "run", "Package": "pkg/a", "Test": "TestNoisy"},
125 {"Action": "output", "Package": "pkg/a", "Test": "TestNoisy", "Output": "hello\n"},
126 {"Action": "output", "Package": "pkg/a", "Test": "TestNoisy", "Output": "world\n"},
127 {"Action": "fail", "Package": "pkg/a", "Test": "TestNoisy", "Elapsed": 0.01},
128 )
129 )
130 self.gojson.seek(0)
131 subunit.GoJSON2SubUnit(self.gojson, self.subunit)
132 events = self._events()
133 # Find the terminal packet for TestNoisy and confirm both lines
134 # were folded into one attachment.
135 terminal = [e for e in events if e[0] == "status" and e[1] == "pkg/a.TestNoisy" and e[2] == "fail"]
136 self.assertEqual(1, len(terminal))
137 # Tuple shape from StreamResult:
138 # ("status", test_id, test_status, test_tags, runnable, file_name,
139 # file_bytes, eof, mime_type, route_code, timestamp)
140 ev = terminal[0]
141 self.assertEqual("go test output", ev[5])
142 self.assertEqual(b"hello\nworld\n", ev[6])
143 self.assertEqual(UTF8_TEXT, ev[8])
144
145 def test_package_level_build_failure_synthesises_test(self):
146 # When `go test` can't build a package it emits a `fail` event with
147 # no `Test` field, preceded by `output` events scoped to the package.
148 self.gojson.write(
149 _ndjson(
150 {"Action": "output", "Package": "pkg/broken", "Output": "./x.go:1:1: syntax error\n"},
151 {"Action": "fail", "Package": "pkg/broken", "Elapsed": 0.0},
152 )
153 )
154 self.gojson.seek(0)
155 rc = subunit.GoJSON2SubUnit(self.gojson, self.subunit)
156 self.assertEqual(1, rc)
157 events = self._events()
158 terminal = [e for e in events if e[0] == "status" and e[1] == "pkg/broken [build]" and e[2] == "fail"]
159 self.assertEqual(1, len(terminal))
160 self.assertEqual(b"./x.go:1:1: syntax error\n", terminal[0][6])
161
162 def test_garbage_lines_are_skipped(self):
163 # `go test -json` occasionally interleaves a non-JSON banner on
164 # certain failure paths; a junk line shouldn't abort the stream.
165 self.gojson.write("not json at all\n")
166 self.gojson.write(
167 _ndjson(
168 {"Action": "run", "Package": "pkg/a", "Test": "TestFoo"},
169 {"Action": "pass", "Package": "pkg/a", "Test": "TestFoo", "Elapsed": 0.0},
170 )
171 )
172 self.gojson.seek(0)
173 rc = subunit.GoJSON2SubUnit(self.gojson, self.subunit)
174 self.assertEqual(0, rc)
175 self.assertIn(("pkg/a.TestFoo", "success"), self._statuses(self._events()))
176
177 def test_blank_lines_are_skipped(self):
178 self.gojson.write("\n\n")
179 self.gojson.write(_ndjson({"Action": "run", "Package": "pkg/a", "Test": "TestFoo"}))
180 self.gojson.write("\n")
181 self.gojson.write(_ndjson({"Action": "pass", "Package": "pkg/a", "Test": "TestFoo", "Elapsed": 0.0}))
182 self.gojson.seek(0)
183 rc = subunit.GoJSON2SubUnit(self.gojson, self.subunit)
184 self.assertEqual(0, rc)
185 self.assertIn(("pkg/a.TestFoo", "success"), self._statuses(self._events()))
186
187 def test_unfinished_test_at_eof_is_failed(self):
188 # A test that started but never reached a terminal action — the
189 # runner died mid-test. Surface as a failure rather than dropping it.
190 self.gojson.write(
191 _ndjson(
192 {"Action": "run", "Package": "pkg/a", "Test": "TestStuck"},
193 {"Action": "output", "Package": "pkg/a", "Test": "TestStuck", "Output": "panic\n"},
194 )
195 )
196 self.gojson.seek(0)
197 rc = subunit.GoJSON2SubUnit(self.gojson, self.subunit)
198 self.assertEqual(1, rc)
199 events = self._events()
200 terminal = [e for e in events if e[0] == "status" and e[1] == "pkg/a.TestStuck" and e[2] == "fail"]
201 self.assertEqual(1, len(terminal))
202 self.assertEqual(b"panic\n", terminal[0][6])
203
204 def test_timestamp_is_propagated(self):
205 # The `Time` on each event should land on the matching subunit packet.
206 self.gojson.write(
207 _ndjson(
208 {
209 "Time": "2026-01-02T03:04:05.000000Z",
210 "Action": "run",
211 "Package": "pkg/a",
212 "Test": "TestTimed",
213 },
214 {
215 "Time": "2026-01-02T03:04:06.000000Z",
216 "Action": "pass",
217 "Package": "pkg/a",
218 "Test": "TestTimed",
219 "Elapsed": 1.0,
220 },
221 )
222 )
223 self.gojson.seek(0)
224 subunit.GoJSON2SubUnit(self.gojson, self.subunit)
225 # The terminal packet's timestamp (last tuple element) must be set,
226 # which gives consumers a basis for computing duration.
227 terminal = [e for e in self._events() if e[0] == "status" and e[1] == "pkg/a.TestTimed" and e[2] == "success"]
228 self.assertEqual(1, len(terminal))
229 self.assertIsNotNone(terminal[0][-1])