Debian Codegraph @

python/tests/test_output_filter.py

raw
1 #
2 # subunit: extensions to python unittest to get test results from subprocesses.
3 # Copyright (C) 2013 Subunit Contributors
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 import datetime
18 import optparse
19 from contextlib import contextmanager
20 from functools import partial
21 from io import BytesIO, TextIOWrapper
22 from tempfile import NamedTemporaryFile
23
24 from iso8601 import UTC
25
26 from testtools import TestCase
27 from testtools.matchers import Equals, Matcher, MatchesAny, MatchesListwise, Mismatch, raises
28 from testtools.testresult.doubles import StreamResult
29
30 import subunit._output as _o
31 from subunit._output import _ALL_ACTIONS, _FINAL_ACTIONS, generate_stream_results, parse_arguments
32
33
34 class SafeOptionParser(optparse.OptionParser):
35 """An ArgumentParser class that doesn't call sys.exit."""
36
37 def exit(self, status=0, message=""):
38 raise RuntimeError(message)
39
40 def error(self, message):
41 raise RuntimeError(message)
42
43
44 safe_parse_arguments = partial(parse_arguments, ParserClass=SafeOptionParser)
45
46
47 class TestStatusArgParserTests(TestCase):
48 scenarios = [(cmd, dict(command=cmd, option="--" + cmd)) for cmd in _ALL_ACTIONS]
49
50 def test_can_parse_all_commands_with_test_id(self):
51 test_id = self.getUniqueString()
52 args = safe_parse_arguments(args=[self.option, test_id])
53
54 self.assertThat(args.action, Equals(self.command))
55 self.assertThat(args.test_id, Equals(test_id))
56
57 def test_all_commands_parse_file_attachment(self):
58 with NamedTemporaryFile() as tmp_file:
59 args = safe_parse_arguments(args=[self.option, "foo", "--attach-file", tmp_file.name])
60 self.assertThat(args.attach_file.name, Equals(tmp_file.name))
61
62 def test_all_commands_accept_mimetype_argument(self):
63 with NamedTemporaryFile() as tmp_file:
64 args = safe_parse_arguments(
65 args=[self.option, "foo", "--attach-file", tmp_file.name, "--mimetype", "text/plain"]
66 )
67 self.assertThat(args.mimetype, Equals("text/plain"))
68
69 def test_all_commands_accept_file_name_argument(self):
70 with NamedTemporaryFile() as tmp_file:
71 args = safe_parse_arguments(args=[self.option, "foo", "--attach-file", tmp_file.name, "--file-name", "foo"])
72 self.assertThat(args.file_name, Equals("foo"))
73
74 def test_all_commands_accept_tags_argument(self):
75 args = safe_parse_arguments(args=[self.option, "foo", "--tag", "foo", "--tag", "bar", "--tag", "baz"])
76 self.assertThat(args.tags, Equals(["foo", "bar", "baz"]))
77
78 def test_attach_file_with_hyphen_opens_stdin(self):
79 self.patch(_o.sys, "stdin", TextIOWrapper(BytesIO(b"Hello")))
80 args = safe_parse_arguments(args=[self.option, "foo", "--attach-file", "-"])
81
82 self.assertThat(args.attach_file.read(), Equals(b"Hello"))
83
84 def test_attach_file_with_hyphen_sets_filename_to_stdin(self):
85 args = safe_parse_arguments(args=[self.option, "foo", "--attach-file", "-"])
86
87 self.assertThat(args.file_name, Equals("stdin"))
88
89 def test_can_override_stdin_filename(self):
90 args = safe_parse_arguments(args=[self.option, "foo", "--attach-file", "-", "--file-name", "foo"])
91
92 self.assertThat(args.file_name, Equals("foo"))
93
94 def test_requires_test_id(self):
95 def fn():
96 return safe_parse_arguments(args=[self.option])
97
98 self.assertThat(fn, raises(RuntimeError("argument %s: must specify a single TEST_ID." % self.option)))
99
100
101 class ArgParserTests(TestCase):
102 def test_can_parse_attach_file_without_test_id(self):
103 with NamedTemporaryFile() as tmp_file:
104 args = safe_parse_arguments(args=["--attach-file", tmp_file.name])
105 self.assertThat(args.attach_file.name, Equals(tmp_file.name))
106
107 def test_can_run_without_args(self):
108 safe_parse_arguments([])
109
110 def test_cannot_specify_more_than_one_status_command(self):
111 def fn():
112 return safe_parse_arguments(["--fail", "foo", "--skip", "bar"])
113
114 self.assertThat(fn, raises(RuntimeError("argument --skip: Only one status may be specified at once.")))
115
116 def test_cannot_specify_mimetype_without_attach_file(self):
117 def fn():
118 return safe_parse_arguments(["--mimetype", "foo"])
119
120 self.assertThat(fn, raises(RuntimeError("Cannot specify --mimetype without --attach-file")))
121
122 def test_cannot_specify_filename_without_attach_file(self):
123 def fn():
124 return safe_parse_arguments(["--file-name", "foo"])
125
126 self.assertThat(fn, raises(RuntimeError("Cannot specify --file-name without --attach-file")))
127
128 def test_can_specify_tags_without_status_command(self):
129 args = safe_parse_arguments(["--tag", "foo"])
130 self.assertEqual(["foo"], args.tags)
131
132 def test_must_specify_tags_with_tags_options(self):
133 def fn():
134 return safe_parse_arguments(["--fail", "foo", "--tag"])
135
136 self.assertThat(
137 fn,
138 MatchesAny(
139 raises(RuntimeError("--tag option requires 1 argument")),
140 raises(RuntimeError("--tag option requires an argument")),
141 ),
142 )
143
144
145 def get_result_for(commands):
146 """Get a result object from *commands.
147
148 Runs the 'generate_stream_results' function from subunit._output after
149 parsing *commands as if they were specified on the command line. The
150 resulting bytestream is then converted back into a result object and
151 returned.
152 """
153 result = StreamResult()
154 args = safe_parse_arguments(commands)
155 generate_stream_results(args, result)
156 return result
157
158
159 @contextmanager
160 def temp_file_contents(data):
161 """Create a temporary file on disk containing 'data'."""
162 with NamedTemporaryFile() as f:
163 f.write(data)
164 f.seek(0)
165 yield f
166
167
168 class StatusStreamResultTests(TestCase):
169 scenarios = [(s, dict(status=s, option="--" + s)) for s in _ALL_ACTIONS]
170
171 _dummy_timestamp = datetime.datetime(2013, 1, 1, 0, 0, 0, 0, UTC)
172
173 def setUp(self):
174 super().setUp()
175 self.patch(_o, "create_timestamp", lambda: self._dummy_timestamp)
176 self.test_id = self.getUniqueString()
177
178 def test_only_one_packet_is_generated(self):
179 result = get_result_for([self.option, self.test_id])
180 self.assertThat(
181 len(result._events),
182 Equals(3), # startTestRun and stopTestRun are also called, making 3 total.
183 )
184
185 def test_correct_status_is_generated(self):
186 result = get_result_for([self.option, self.test_id])
187
188 self.assertThat(result._events[1], MatchesStatusCall(test_status=self.status))
189
190 def test_all_commands_generate_tags(self):
191 result = get_result_for([self.option, self.test_id, "--tag", "hello", "--tag", "world"])
192 self.assertThat(result._events[1], MatchesStatusCall(test_tags={"hello", "world"}))
193
194 def test_all_commands_generate_timestamp(self):
195 result = get_result_for([self.option, self.test_id])
196
197 self.assertThat(result._events[1], MatchesStatusCall(timestamp=self._dummy_timestamp))
198
199 def test_all_commands_generate_correct_test_id(self):
200 result = get_result_for([self.option, self.test_id])
201
202 self.assertThat(result._events[1], MatchesStatusCall(test_id=self.test_id))
203
204 def test_file_is_sent_in_single_packet(self):
205 with temp_file_contents(b"Hello") as f:
206 result = get_result_for([self.option, self.test_id, "--attach-file", f.name])
207
208 self.assertThat(
209 result._events,
210 MatchesListwise(
211 [
212 MatchesStatusCall(call="startTestRun"),
213 MatchesStatusCall(file_bytes=b"Hello", eof=True),
214 MatchesStatusCall(call="stopTestRun"),
215 ]
216 ),
217 )
218
219 def test_can_read_binary_files(self):
220 with temp_file_contents(b"\xde\xad\xbe\xef") as f:
221 result = get_result_for([self.option, self.test_id, "--attach-file", f.name])
222
223 self.assertThat(
224 result._events,
225 MatchesListwise(
226 [
227 MatchesStatusCall(call="startTestRun"),
228 MatchesStatusCall(file_bytes=b"\xde\xad\xbe\xef", eof=True),
229 MatchesStatusCall(call="stopTestRun"),
230 ]
231 ),
232 )
233
234 def test_can_read_empty_files(self):
235 with temp_file_contents(b"") as f:
236 result = get_result_for([self.option, self.test_id, "--attach-file", f.name])
237
238 self.assertThat(
239 result._events,
240 MatchesListwise(
241 [
242 MatchesStatusCall(call="startTestRun"),
243 MatchesStatusCall(file_bytes=b"", file_name=f.name, eof=True),
244 MatchesStatusCall(call="stopTestRun"),
245 ]
246 ),
247 )
248
249 def test_can_read_stdin(self):
250 self.patch(_o.sys, "stdin", TextIOWrapper(BytesIO(b"\xfe\xed\xfa\xce")))
251 result = get_result_for([self.option, self.test_id, "--attach-file", "-"])
252
253 self.assertThat(
254 result._events,
255 MatchesListwise(
256 [
257 MatchesStatusCall(call="startTestRun"),
258 MatchesStatusCall(file_bytes=b"\xfe\xed\xfa\xce", file_name="stdin", eof=True),
259 MatchesStatusCall(call="stopTestRun"),
260 ]
261 ),
262 )
263
264 def test_file_is_sent_with_test_id(self):
265 with temp_file_contents(b"Hello") as f:
266 result = get_result_for([self.option, self.test_id, "--attach-file", f.name])
267
268 self.assertThat(
269 result._events,
270 MatchesListwise(
271 [
272 MatchesStatusCall(call="startTestRun"),
273 MatchesStatusCall(test_id=self.test_id, file_bytes=b"Hello", eof=True),
274 MatchesStatusCall(call="stopTestRun"),
275 ]
276 ),
277 )
278
279 def test_file_is_sent_with_test_status(self):
280 with temp_file_contents(b"Hello") as f:
281 result = get_result_for([self.option, self.test_id, "--attach-file", f.name])
282
283 self.assertThat(
284 result._events,
285 MatchesListwise(
286 [
287 MatchesStatusCall(call="startTestRun"),
288 MatchesStatusCall(test_status=self.status, file_bytes=b"Hello", eof=True),
289 MatchesStatusCall(call="stopTestRun"),
290 ]
291 ),
292 )
293
294 def test_file_chunk_size_is_honored(self):
295 with temp_file_contents(b"Hello") as f:
296 self.patch(_o, "_CHUNK_SIZE", 1)
297 result = get_result_for([self.option, self.test_id, "--attach-file", f.name])
298
299 self.assertThat(
300 result._events,
301 MatchesListwise(
302 [
303 MatchesStatusCall(call="startTestRun"),
304 MatchesStatusCall(test_id=self.test_id, file_bytes=b"H", eof=False),
305 MatchesStatusCall(test_id=self.test_id, file_bytes=b"e", eof=False),
306 MatchesStatusCall(test_id=self.test_id, file_bytes=b"l", eof=False),
307 MatchesStatusCall(test_id=self.test_id, file_bytes=b"l", eof=False),
308 MatchesStatusCall(test_id=self.test_id, file_bytes=b"o", eof=True),
309 MatchesStatusCall(call="stopTestRun"),
310 ]
311 ),
312 )
313
314 def test_file_mimetype_specified_once_only(self):
315 with temp_file_contents(b"Hi") as f:
316 self.patch(_o, "_CHUNK_SIZE", 1)
317 result = get_result_for(
318 [
319 self.option,
320 self.test_id,
321 "--attach-file",
322 f.name,
323 "--mimetype",
324 "text/plain",
325 ]
326 )
327
328 self.assertThat(
329 result._events,
330 MatchesListwise(
331 [
332 MatchesStatusCall(call="startTestRun"),
333 MatchesStatusCall(test_id=self.test_id, mime_type="text/plain", file_bytes=b"H", eof=False),
334 MatchesStatusCall(test_id=self.test_id, mime_type=None, file_bytes=b"i", eof=True),
335 MatchesStatusCall(call="stopTestRun"),
336 ]
337 ),
338 )
339
340 def test_tags_specified_once_only(self):
341 with temp_file_contents(b"Hi") as f:
342 self.patch(_o, "_CHUNK_SIZE", 1)
343 result = get_result_for(
344 [
345 self.option,
346 self.test_id,
347 "--attach-file",
348 f.name,
349 "--tag",
350 "foo",
351 "--tag",
352 "bar",
353 ]
354 )
355
356 self.assertThat(
357 result._events,
358 MatchesListwise(
359 [
360 MatchesStatusCall(call="startTestRun"),
361 MatchesStatusCall(test_id=self.test_id, test_tags={"foo", "bar"}),
362 MatchesStatusCall(test_id=self.test_id, test_tags=None),
363 MatchesStatusCall(call="stopTestRun"),
364 ]
365 ),
366 )
367
368 def test_timestamp_specified_once_only(self):
369 with temp_file_contents(b"Hi") as f:
370 self.patch(_o, "_CHUNK_SIZE", 1)
371 result = get_result_for(
372 [
373 self.option,
374 self.test_id,
375 "--attach-file",
376 f.name,
377 ]
378 )
379
380 self.assertThat(
381 result._events,
382 MatchesListwise(
383 [
384 MatchesStatusCall(call="startTestRun"),
385 MatchesStatusCall(test_id=self.test_id, timestamp=self._dummy_timestamp),
386 MatchesStatusCall(test_id=self.test_id, timestamp=None),
387 MatchesStatusCall(call="stopTestRun"),
388 ]
389 ),
390 )
391
392 def test_test_status_specified_once_only(self):
393 with temp_file_contents(b"Hi") as f:
394 self.patch(_o, "_CHUNK_SIZE", 1)
395 result = get_result_for(
396 [
397 self.option,
398 self.test_id,
399 "--attach-file",
400 f.name,
401 ]
402 )
403
404 # 'inprogress' status should be on the first packet only, all other
405 # statuses should be on the last packet.
406 if self.status in _FINAL_ACTIONS:
407 first_call = MatchesStatusCall(test_id=self.test_id, test_status=None)
408 last_call = MatchesStatusCall(test_id=self.test_id, test_status=self.status)
409 else:
410 first_call = MatchesStatusCall(test_id=self.test_id, test_status=self.status)
411 last_call = MatchesStatusCall(test_id=self.test_id, test_status=None)
412 self.assertThat(
413 result._events,
414 MatchesListwise(
415 [
416 MatchesStatusCall(call="startTestRun"),
417 first_call,
418 last_call,
419 MatchesStatusCall(call="stopTestRun"),
420 ]
421 ),
422 )
423
424 def test_filename_can_be_overridden(self):
425 with temp_file_contents(b"Hello") as f:
426 specified_file_name = self.getUniqueString()
427 result = get_result_for(
428 [self.option, self.test_id, "--attach-file", f.name, "--file-name", specified_file_name]
429 )
430
431 self.assertThat(
432 result._events,
433 MatchesListwise(
434 [
435 MatchesStatusCall(call="startTestRun"),
436 MatchesStatusCall(file_name=specified_file_name, file_bytes=b"Hello"),
437 MatchesStatusCall(call="stopTestRun"),
438 ]
439 ),
440 )
441
442 def test_file_name_is_used_by_default(self):
443 with temp_file_contents(b"Hello") as f:
444 result = get_result_for([self.option, self.test_id, "--attach-file", f.name])
445
446 self.assertThat(
447 result._events,
448 MatchesListwise(
449 [
450 MatchesStatusCall(call="startTestRun"),
451 MatchesStatusCall(file_name=f.name, file_bytes=b"Hello", eof=True),
452 MatchesStatusCall(call="stopTestRun"),
453 ]
454 ),
455 )
456
457
458 class FileDataTests(TestCase):
459 def test_can_attach_file_without_test_id(self):
460 with temp_file_contents(b"Hello") as f:
461 result = get_result_for(["--attach-file", f.name])
462
463 self.assertThat(
464 result._events,
465 MatchesListwise(
466 [
467 MatchesStatusCall(call="startTestRun"),
468 MatchesStatusCall(test_id=None, file_bytes=b"Hello", eof=True),
469 MatchesStatusCall(call="stopTestRun"),
470 ]
471 ),
472 )
473
474 def test_file_name_is_used_by_default(self):
475 with temp_file_contents(b"Hello") as f:
476 result = get_result_for(["--attach-file", f.name])
477
478 self.assertThat(
479 result._events,
480 MatchesListwise(
481 [
482 MatchesStatusCall(call="startTestRun"),
483 MatchesStatusCall(file_name=f.name, file_bytes=b"Hello", eof=True),
484 MatchesStatusCall(call="stopTestRun"),
485 ]
486 ),
487 )
488
489 def test_filename_can_be_overridden(self):
490 with temp_file_contents(b"Hello") as f:
491 specified_file_name = self.getUniqueString()
492 result = get_result_for(["--attach-file", f.name, "--file-name", specified_file_name])
493
494 self.assertThat(
495 result._events,
496 MatchesListwise(
497 [
498 MatchesStatusCall(call="startTestRun"),
499 MatchesStatusCall(file_name=specified_file_name, file_bytes=b"Hello"),
500 MatchesStatusCall(call="stopTestRun"),
501 ]
502 ),
503 )
504
505 def test_files_have_timestamp(self):
506 _dummy_timestamp = datetime.datetime(2013, 1, 1, 0, 0, 0, 0, UTC)
507 self.patch(_o, "create_timestamp", lambda: _dummy_timestamp)
508
509 with temp_file_contents(b"Hello") as f:
510 self.getUniqueString()
511 result = get_result_for(
512 [
513 "--attach-file",
514 f.name,
515 ]
516 )
517
518 self.assertThat(
519 result._events,
520 MatchesListwise(
521 [
522 MatchesStatusCall(call="startTestRun"),
523 MatchesStatusCall(file_bytes=b"Hello", timestamp=_dummy_timestamp),
524 MatchesStatusCall(call="stopTestRun"),
525 ]
526 ),
527 )
528
529 def test_can_specify_tags_without_test_status(self):
530 result = get_result_for(
531 [
532 "--tag",
533 "foo",
534 ]
535 )
536
537 self.assertThat(
538 result._events,
539 MatchesListwise(
540 [
541 MatchesStatusCall(call="startTestRun"),
542 MatchesStatusCall(test_tags={"foo"}),
543 MatchesStatusCall(call="stopTestRun"),
544 ]
545 ),
546 )
547
548
549 class MatchesStatusCall(Matcher):
550 _position_lookup = {
551 "call": 0,
552 "test_id": 1,
553 "test_status": 2,
554 "test_tags": 3,
555 "runnable": 4,
556 "file_name": 5,
557 "file_bytes": 6,
558 "eof": 7,
559 "mime_type": 8,
560 "route_code": 9,
561 "timestamp": 10,
562 }
563
564 def __init__(self, **kwargs):
565 unknown_kwargs = list(filter(lambda k: k not in self._position_lookup, kwargs))
566 if unknown_kwargs:
567 raise ValueError("Unknown keywords: %s" % ",".join(unknown_kwargs))
568 self._filters = kwargs
569
570 def match(self, call_tuple):
571 for k, v in self._filters.items():
572 try:
573 pos = self._position_lookup[k]
574 if call_tuple[pos] != v:
575 return Mismatch("Value for key is {!r}, not {!r}".format(call_tuple[pos], v))
576 except IndexError:
577 return Mismatch("Key %s is not present." % k)
578
579 def __str__(self):
580 return "<MatchesStatusCall %r>" % self._filters