blob: 88715df0dc833db68af0c8855d204a75a95810f0 [file] [log] [blame]
Todd Fiala68615ce2015-09-15 21:38:04 +00001"""
2 The LLVM Compiler Infrastructure
3
4This file is distributed under the University of Illinois Open Source
5License. See LICENSE.TXT for details.
6
7Provides classes used by the test results reporting infrastructure
8within the LLDB test suite.
9"""
10
11import argparse
12import cPickle
13import inspect
14import os
Todd Fiala33896a92015-09-18 21:01:13 +000015import pprint
Todd Fiala8effde42015-09-18 16:00:52 +000016import re
Todd Fiala68615ce2015-09-15 21:38:04 +000017import sys
18import threading
19import time
Todd Fialae7e911f2015-09-18 07:08:09 +000020import traceback
Todd Fiala68615ce2015-09-15 21:38:04 +000021import xml.sax.saxutils
22
23
24class EventBuilder(object):
25 """Helper class to build test result event dictionaries."""
Todd Fiala33896a92015-09-18 21:01:13 +000026
27 BASE_DICTIONARY = None
28
Todd Fiala68615ce2015-09-15 21:38:04 +000029 @staticmethod
30 def _get_test_name_info(test):
31 """Returns (test-class-name, test-method-name) from a test case instance.
32
33 @param test a unittest.TestCase instance.
34
35 @return tuple containing (test class name, test method name)
36 """
37 test_class_components = test.id().split(".")
38 test_class_name = ".".join(test_class_components[:-1])
39 test_name = test_class_components[-1]
40 return (test_class_name, test_name)
41
42 @staticmethod
Todd Fialae83f1402015-09-18 22:45:31 +000043 def bare_event(event_type):
44 """Creates an event with default additions, event type and timestamp.
45
46 @param event_type the value set for the "event" key, used
47 to distinguish events.
48
49 @returns an event dictionary with all default additions, the "event"
50 key set to the passed in event_type, and the event_time value set to
51 time.time().
52 """
53 if EventBuilder.BASE_DICTIONARY is not None:
54 # Start with a copy of the "always include" entries.
55 event = dict(EventBuilder.BASE_DICTIONARY)
56 else:
57 event = {}
58
59 event.update({
60 "event": event_type,
61 "event_time": time.time()
62 })
63 return event
64
65 @staticmethod
Todd Fiala68615ce2015-09-15 21:38:04 +000066 def _event_dictionary_common(test, event_type):
67 """Returns an event dictionary setup with values for the given event type.
68
69 @param test the unittest.TestCase instance
70
71 @param event_type the name of the event type (string).
72
73 @return event dictionary with common event fields set.
74 """
75 test_class_name, test_name = EventBuilder._get_test_name_info(test)
Todd Fiala33896a92015-09-18 21:01:13 +000076
Todd Fialae83f1402015-09-18 22:45:31 +000077 event = EventBuilder.bare_event(event_type)
78 event.update({
Todd Fiala68615ce2015-09-15 21:38:04 +000079 "test_class": test_class_name,
80 "test_name": test_name,
Todd Fialaf77f8ae2015-09-18 22:57:04 +000081 "test_filename": inspect.getfile(test.__class__)
Todd Fiala33896a92015-09-18 21:01:13 +000082 })
Todd Fialae83f1402015-09-18 22:45:31 +000083 return event
Todd Fiala68615ce2015-09-15 21:38:04 +000084
85 @staticmethod
86 def _error_tuple_class(error_tuple):
87 """Returns the unittest error tuple's error class as a string.
88
89 @param error_tuple the error tuple provided by the test framework.
90
91 @return the error type (typically an exception) raised by the
92 test framework.
93 """
94 type_var = error_tuple[0]
95 module = inspect.getmodule(type_var)
96 if module:
97 return "{}.{}".format(module.__name__, type_var.__name__)
98 else:
99 return type_var.__name__
100
101 @staticmethod
102 def _error_tuple_message(error_tuple):
103 """Returns the unittest error tuple's error message.
104
105 @param error_tuple the error tuple provided by the test framework.
106
107 @return the error message provided by the test framework.
108 """
109 return str(error_tuple[1])
110
111 @staticmethod
Todd Fialae7e911f2015-09-18 07:08:09 +0000112 def _error_tuple_traceback(error_tuple):
113 """Returns the unittest error tuple's error message.
114
115 @param error_tuple the error tuple provided by the test framework.
116
117 @return the error message provided by the test framework.
118 """
119 return error_tuple[2]
120
121 @staticmethod
Todd Fiala68615ce2015-09-15 21:38:04 +0000122 def _event_dictionary_test_result(test, status):
123 """Returns an event dictionary with common test result fields set.
124
125 @param test a unittest.TestCase instance.
126
127 @param status the status/result of the test
128 (e.g. "success", "failure", etc.)
129
130 @return the event dictionary
131 """
132 event = EventBuilder._event_dictionary_common(test, "test_result")
133 event["status"] = status
134 return event
135
136 @staticmethod
137 def _event_dictionary_issue(test, status, error_tuple):
138 """Returns an event dictionary with common issue-containing test result
139 fields set.
140
141 @param test a unittest.TestCase instance.
142
143 @param status the status/result of the test
144 (e.g. "success", "failure", etc.)
145
146 @param error_tuple the error tuple as reported by the test runner.
147 This is of the form (type<error>, error).
148
149 @return the event dictionary
150 """
151 event = EventBuilder._event_dictionary_test_result(test, status)
152 event["issue_class"] = EventBuilder._error_tuple_class(error_tuple)
153 event["issue_message"] = EventBuilder._error_tuple_message(error_tuple)
Todd Fiala33896a92015-09-18 21:01:13 +0000154 backtrace = EventBuilder._error_tuple_traceback(error_tuple)
155 if backtrace is not None:
156 event["issue_backtrace"] = traceback.format_tb(backtrace)
Todd Fiala68615ce2015-09-15 21:38:04 +0000157 return event
158
159 @staticmethod
160 def event_for_start(test):
161 """Returns an event dictionary for the test start event.
162
163 @param test a unittest.TestCase instance.
164
165 @return the event dictionary
166 """
167 return EventBuilder._event_dictionary_common(test, "test_start")
168
169 @staticmethod
170 def event_for_success(test):
171 """Returns an event dictionary for a successful test.
172
173 @param test a unittest.TestCase instance.
174
175 @return the event dictionary
176 """
177 return EventBuilder._event_dictionary_test_result(test, "success")
178
179 @staticmethod
180 def event_for_unexpected_success(test, bugnumber):
181 """Returns an event dictionary for a test that succeeded but was
182 expected to fail.
183
184 @param test a unittest.TestCase instance.
185
186 @param bugnumber the issue identifier for the bug tracking the
187 fix request for the test expected to fail (but is in fact
188 passing here).
189
190 @return the event dictionary
191
192 """
193 event = EventBuilder._event_dictionary_test_result(
194 test, "unexpected_success")
195 if bugnumber:
196 event["bugnumber"] = str(bugnumber)
197 return event
198
199 @staticmethod
200 def event_for_failure(test, error_tuple):
201 """Returns an event dictionary for a test that failed.
202
203 @param test a unittest.TestCase instance.
204
205 @param error_tuple the error tuple as reported by the test runner.
206 This is of the form (type<error>, error).
207
208 @return the event dictionary
209 """
210 return EventBuilder._event_dictionary_issue(
211 test, "failure", error_tuple)
212
213 @staticmethod
214 def event_for_expected_failure(test, error_tuple, bugnumber):
215 """Returns an event dictionary for a test that failed as expected.
216
217 @param test a unittest.TestCase instance.
218
219 @param error_tuple the error tuple as reported by the test runner.
220 This is of the form (type<error>, error).
221
222 @param bugnumber the issue identifier for the bug tracking the
223 fix request for the test expected to fail.
224
225 @return the event dictionary
226
227 """
228 event = EventBuilder._event_dictionary_issue(
229 test, "expected_failure", error_tuple)
230 if bugnumber:
231 event["bugnumber"] = str(bugnumber)
232 return event
233
234 @staticmethod
235 def event_for_skip(test, reason):
236 """Returns an event dictionary for a test that was skipped.
237
238 @param test a unittest.TestCase instance.
239
240 @param reason the reason why the test is being skipped.
241
242 @return the event dictionary
243 """
244 event = EventBuilder._event_dictionary_test_result(test, "skip")
245 event["skip_reason"] = reason
246 return event
247
248 @staticmethod
249 def event_for_error(test, error_tuple):
250 """Returns an event dictionary for a test that hit a test execution error.
251
252 @param test a unittest.TestCase instance.
253
254 @param error_tuple the error tuple as reported by the test runner.
255 This is of the form (type<error>, error).
256
257 @return the event dictionary
258 """
259 return EventBuilder._event_dictionary_issue(test, "error", error_tuple)
260
261 @staticmethod
262 def event_for_cleanup_error(test, error_tuple):
263 """Returns an event dictionary for a test that hit a test execution error
264 during the test cleanup phase.
265
266 @param test a unittest.TestCase instance.
267
268 @param error_tuple the error tuple as reported by the test runner.
269 This is of the form (type<error>, error).
270
271 @return the event dictionary
272 """
273 event = EventBuilder._event_dictionary_issue(
274 test, "error", error_tuple)
275 event["issue_phase"] = "cleanup"
276 return event
277
Todd Fiala33896a92015-09-18 21:01:13 +0000278 @staticmethod
279 def add_entries_to_all_events(entries_dict):
280 """Specifies a dictionary of entries to add to all test events.
281
282 This provides a mechanism for, say, a parallel test runner to
283 indicate to each inferior dotest.py that it should add a
284 worker index to each.
285
286 Calling this method replaces all previous entries added
287 by a prior call to this.
288
289 Event build methods will overwrite any entries that collide.
290 Thus, the passed in dictionary is the base, which gets merged
291 over by event building when keys collide.
292
293 @param entries_dict a dictionary containing key and value
294 pairs that should be merged into all events created by the
295 event generator. May be None to clear out any extra entries.
296 """
297 EventBuilder.BASE_DICTIONARY = dict(entries_dict)
298
Todd Fiala68615ce2015-09-15 21:38:04 +0000299
300class ResultsFormatter(object):
Todd Fiala33896a92015-09-18 21:01:13 +0000301
Todd Fiala68615ce2015-09-15 21:38:04 +0000302 """Provides interface to formatting test results out to a file-like object.
303
304 This class allows the LLDB test framework's raw test-realted
305 events to be processed and formatted in any manner desired.
306 Test events are represented by python dictionaries, formatted
307 as in the EventBuilder class above.
308
309 ResultFormatter instances are given a file-like object in which
310 to write their results.
311
312 ResultFormatter lifetime looks like the following:
313
314 # The result formatter is created.
315 # The argparse options dictionary is generated from calling
316 # the SomeResultFormatter.arg_parser() with the options data
317 # passed to dotest.py via the "--results-formatter-options"
318 # argument. See the help on that for syntactic requirements
319 # on getting that parsed correctly.
320 formatter = SomeResultFormatter(file_like_object, argpared_options_dict)
321
322 # Single call to session start, before parsing any events.
323 formatter.begin_session()
324
Todd Fialae83f1402015-09-18 22:45:31 +0000325 formatter.handle_event({"event":"initialize",...})
326
Todd Fiala68615ce2015-09-15 21:38:04 +0000327 # Zero or more calls specified for events recorded during the test session.
328 # The parallel test runner manages getting results from all the inferior
329 # dotest processes, so from a new format perspective, don't worry about
330 # that. The formatter will be presented with a single stream of events
331 # sandwiched between a single begin_session()/end_session() pair in the
332 # parallel test runner process/thread.
333 for event in zero_or_more_test_events():
Todd Fialae83f1402015-09-18 22:45:31 +0000334 formatter.handle_event(event)
Todd Fiala68615ce2015-09-15 21:38:04 +0000335
Todd Fialae83f1402015-09-18 22:45:31 +0000336 # Single call to terminate/wrap-up. Formatters that need all the
337 # data before they can print a correct result (e.g. xUnit/JUnit),
338 # this is where the final report can be generated.
339 formatter.handle_event({"event":"terminate",...})
Todd Fiala68615ce2015-09-15 21:38:04 +0000340
341 It is not the formatter's responsibility to close the file_like_object.
342 (i.e. do not close it).
343
344 The lldb test framework passes these test events in real time, so they
345 arrive as they come in.
346
347 In the case of the parallel test runner, the dotest inferiors
348 add a 'pid' field to the dictionary that indicates which inferior
349 pid generated the event.
350
351 Note more events may be added in the future to support richer test
352 reporting functionality. One example: creating a true flaky test
353 result category so that unexpected successes really mean the test
354 is marked incorrectly (either should be marked flaky, or is indeed
355 passing consistently now and should have the xfail marker
356 removed). In this case, a flaky_success and flaky_fail event
357 likely will be added to capture these and support reporting things
358 like percentages of flaky test passing so we can see if we're
359 making some things worse/better with regards to failure rates.
360
361 Another example: announcing all the test methods that are planned
362 to be run, so we can better support redo operations of various kinds
363 (redo all non-run tests, redo non-run tests except the one that
364 was running [perhaps crashed], etc.)
365
366 Implementers are expected to override all the public methods
367 provided in this class. See each method's docstring to see
368 expectations about when the call should be chained.
369
370 """
371
372 @classmethod
373 def arg_parser(cls):
374 """@return arg parser used to parse formatter-specific options."""
375 parser = argparse.ArgumentParser(
376 description='{} options'.format(cls.__name__),
377 usage=('dotest.py --results-formatter-options='
378 '"--option1 value1 [--option2 value2 [...]]"'))
379 return parser
380
381 def __init__(self, out_file, options):
382 super(ResultsFormatter, self).__init__()
383 self.out_file = out_file
384 self.options = options
Greg Clayton1827fc22015-09-19 00:39:09 +0000385 self.using_terminal = False
Todd Fiala68615ce2015-09-15 21:38:04 +0000386 if not self.out_file:
387 raise Exception("ResultsFormatter created with no file object")
388 self.start_time_by_test = {}
Todd Fialade9a44e2015-09-22 00:15:50 +0000389 self.terminate_called = False
Todd Fiala68615ce2015-09-15 21:38:04 +0000390
391 # Lock that we use while mutating inner state, like the
392 # total test count and the elements. We minimize how
393 # long we hold the lock just to keep inner state safe, not
394 # entirely consistent from the outside.
395 self.lock = threading.Lock()
396
Todd Fialae83f1402015-09-18 22:45:31 +0000397 def handle_event(self, test_event):
398 """Handles the test event for collection into the formatter output.
Todd Fiala68615ce2015-09-15 21:38:04 +0000399
400 Derived classes may override this but should call down to this
401 implementation first.
402
403 @param test_event the test event as formatted by one of the
404 event_for_* calls.
405 """
Todd Fialade9a44e2015-09-22 00:15:50 +0000406 # Keep track of whether terminate was received. We do this so
407 # that a process can call the 'terminate' event on its own, to
408 # close down a formatter at the appropriate time. Then the
409 # atexit() cleanup can call the "terminate if it hasn't been
410 # called yet".
411 if test_event is not None:
412 if test_event.get("event", "") == "terminate":
413 self.terminate_called = True
Todd Fiala68615ce2015-09-15 21:38:04 +0000414
415 def track_start_time(self, test_class, test_name, start_time):
416 """Tracks the start time of a test so elapsed time can be computed.
417
418 This alleviates the need for test results to be processed serially
419 by test. It will save the start time for the test so that
420 elapsed_time_for_test() can compute the elapsed time properly.
421 """
422 if test_class is None or test_name is None:
423 return
424
425 test_key = "{}.{}".format(test_class, test_name)
426 with self.lock:
427 self.start_time_by_test[test_key] = start_time
428
429 def elapsed_time_for_test(self, test_class, test_name, end_time):
430 """Returns the elapsed time for a test.
431
432 This function can only be called once per test and requires that
433 the track_start_time() method be called sometime prior to calling
434 this method.
435 """
436 if test_class is None or test_name is None:
437 return -2.0
438
439 test_key = "{}.{}".format(test_class, test_name)
440 with self.lock:
441 if test_key not in self.start_time_by_test:
442 return -1.0
443 else:
444 start_time = self.start_time_by_test[test_key]
445 del self.start_time_by_test[test_key]
446 return end_time - start_time
447
Greg Clayton1827fc22015-09-19 00:39:09 +0000448 def is_using_terminal(self):
Todd Fialade9a44e2015-09-22 00:15:50 +0000449 """Returns True if this results formatter is using the terminal and
450 output should be avoided."""
Greg Clayton1827fc22015-09-19 00:39:09 +0000451 return self.using_terminal
Todd Fiala68615ce2015-09-15 21:38:04 +0000452
Todd Fialade9a44e2015-09-22 00:15:50 +0000453 def send_terminate_as_needed(self):
454 """Sends the terminate event if it hasn't been received yet."""
455 if not self.terminate_called:
456 terminate_event = EventBuilder.bare_event("terminate")
457 self.handle_event(terminate_event)
458
Todd Fiala132c2c42015-09-22 06:32:50 +0000459
Todd Fiala68615ce2015-09-15 21:38:04 +0000460class XunitFormatter(ResultsFormatter):
461 """Provides xUnit-style formatted output.
462 """
463
464 # Result mapping arguments
465 RM_IGNORE = 'ignore'
466 RM_SUCCESS = 'success'
467 RM_FAILURE = 'failure'
468 RM_PASSTHRU = 'passthru'
469
470 @staticmethod
Todd Fiala8effde42015-09-18 16:00:52 +0000471 def _build_illegal_xml_regex():
Todd Fiala33896a92015-09-18 21:01:13 +0000472 """Contructs a regex to match all illegal xml characters.
473
474 Expects to be used against a unicode string."""
Todd Fiala8effde42015-09-18 16:00:52 +0000475 # Construct the range pairs of invalid unicode chareacters.
476 illegal_chars_u = [
477 (0x00, 0x08), (0x0B, 0x0C), (0x0E, 0x1F), (0x7F, 0x84),
478 (0x86, 0x9F), (0xFDD0, 0xFDDF), (0xFFFE, 0xFFFF)]
479
480 # For wide builds, we have more.
481 if sys.maxunicode >= 0x10000:
482 illegal_chars_u.extend(
483 [(0x1FFFE, 0x1FFFF), (0x2FFFE, 0x2FFFF), (0x3FFFE, 0x3FFFF),
484 (0x4FFFE, 0x4FFFF), (0x5FFFE, 0x5FFFF), (0x6FFFE, 0x6FFFF),
485 (0x7FFFE, 0x7FFFF), (0x8FFFE, 0x8FFFF), (0x9FFFE, 0x9FFFF),
486 (0xAFFFE, 0xAFFFF), (0xBFFFE, 0xBFFFF), (0xCFFFE, 0xCFFFF),
487 (0xDFFFE, 0xDFFFF), (0xEFFFE, 0xEFFFF), (0xFFFFE, 0xFFFFF),
488 (0x10FFFE, 0x10FFFF)])
489
490 # Build up an array of range expressions.
491 illegal_ranges = [
492 "%s-%s" % (unichr(low), unichr(high))
493 for (low, high) in illegal_chars_u]
494
495 # Compile the regex
496 return re.compile(u'[%s]' % u''.join(illegal_ranges))
497
498 @staticmethod
Todd Fiala68615ce2015-09-15 21:38:04 +0000499 def _quote_attribute(text):
500 """Returns the given text in a manner safe for usage in an XML attribute.
501
502 @param text the text that should appear within an XML attribute.
503 @return the attribute-escaped version of the input text.
504 """
505 return xml.sax.saxutils.quoteattr(text)
506
Todd Fiala8effde42015-09-18 16:00:52 +0000507 def _replace_invalid_xml(self, str_or_unicode):
Todd Fiala33896a92015-09-18 21:01:13 +0000508 """Replaces invalid XML characters with a '?'.
509
510 @param str_or_unicode a string to replace invalid XML
511 characters within. Can be unicode or not. If not unicode,
512 assumes it is a byte string in utf-8 encoding.
513
514 @returns a utf-8-encoded byte string with invalid
515 XML replaced with '?'.
516 """
Todd Fiala8effde42015-09-18 16:00:52 +0000517 # Get the content into unicode
518 if isinstance(str_or_unicode, str):
519 unicode_content = str_or_unicode.decode('utf-8')
520 else:
521 unicode_content = str_or_unicode
522 return self.invalid_xml_re.sub(u'?', unicode_content).encode('utf-8')
523
Todd Fiala68615ce2015-09-15 21:38:04 +0000524 @classmethod
525 def arg_parser(cls):
526 """@return arg parser used to parse formatter-specific options."""
527 parser = super(XunitFormatter, cls).arg_parser()
528
529 # These are valid choices for results mapping.
530 results_mapping_choices = [
531 XunitFormatter.RM_IGNORE,
532 XunitFormatter.RM_SUCCESS,
533 XunitFormatter.RM_FAILURE,
534 XunitFormatter.RM_PASSTHRU]
535 parser.add_argument(
Todd Fiala33896a92015-09-18 21:01:13 +0000536 "--assert-on-unknown-events",
537 action="store_true",
538 help=('cause unknown test events to generate '
539 'a python assert. Default is to ignore.'))
540 parser.add_argument(
Todd Fialaea736242015-09-23 15:21:28 +0000541 "--ignore-skip-name",
542 "-n",
543 metavar='PATTERN',
544 action="append",
545 dest='ignore_skip_name_patterns',
546 help=('a python regex pattern, where '
Todd Fiala132c2c42015-09-22 06:32:50 +0000547 'any skipped test with a test method name where regex '
548 'matches (via search) will be ignored for xUnit test '
Todd Fialaea736242015-09-23 15:21:28 +0000549 'result purposes. Can be specified multiple times.'))
Todd Fiala132c2c42015-09-22 06:32:50 +0000550 parser.add_argument(
Todd Fialaea736242015-09-23 15:21:28 +0000551 "--ignore-skip-reason",
552 "-r",
553 metavar='PATTERN',
554 action="append",
555 dest='ignore_skip_reason_patterns',
556 help=('a python regex pattern, where '
Todd Fiala132c2c42015-09-22 06:32:50 +0000557 'any skipped test with a skip reason where the regex '
558 'matches (via search) will be ignored for xUnit test '
Todd Fialaea736242015-09-23 15:21:28 +0000559 'result purposes. Can be specified multiple times.'))
Todd Fiala132c2c42015-09-22 06:32:50 +0000560 parser.add_argument(
Todd Fiala68615ce2015-09-15 21:38:04 +0000561 "--xpass", action="store", choices=results_mapping_choices,
562 default=XunitFormatter.RM_FAILURE,
563 help=('specify mapping from unexpected success to jUnit/xUnit '
564 'result type'))
565 parser.add_argument(
566 "--xfail", action="store", choices=results_mapping_choices,
567 default=XunitFormatter.RM_IGNORE,
568 help=('specify mapping from expected failure to jUnit/xUnit '
569 'result type'))
570 return parser
571
Todd Fiala132c2c42015-09-22 06:32:50 +0000572 @staticmethod
Todd Fialaea736242015-09-23 15:21:28 +0000573 def _build_regex_list_from_patterns(patterns):
Todd Fiala132c2c42015-09-22 06:32:50 +0000574 """Builds a list of compiled regexes from option value.
575
576 @param option string containing a comma-separated list of regex
577 patterns. Zero-length or None will produce an empty regex list.
578
579 @return list of compiled regular expressions, empty if no
580 patterns provided.
581 """
582 regex_list = []
Todd Fialaea736242015-09-23 15:21:28 +0000583 if patterns is not None:
584 for pattern in patterns:
Todd Fiala132c2c42015-09-22 06:32:50 +0000585 regex_list.append(re.compile(pattern))
586 return regex_list
587
Todd Fiala68615ce2015-09-15 21:38:04 +0000588 def __init__(self, out_file, options):
589 """Initializes the XunitFormatter instance.
590 @param out_file file-like object where formatted output is written.
591 @param options_dict specifies a dictionary of options for the
592 formatter.
593 """
594 # Initialize the parent
595 super(XunitFormatter, self).__init__(out_file, options)
596 self.text_encoding = "UTF-8"
Todd Fiala8effde42015-09-18 16:00:52 +0000597 self.invalid_xml_re = XunitFormatter._build_illegal_xml_regex()
Todd Fiala68615ce2015-09-15 21:38:04 +0000598 self.total_test_count = 0
Todd Fiala132c2c42015-09-22 06:32:50 +0000599 self.ignore_skip_name_regexes = (
Todd Fialaea736242015-09-23 15:21:28 +0000600 XunitFormatter._build_regex_list_from_patterns(
601 options.ignore_skip_name_patterns))
Todd Fiala132c2c42015-09-22 06:32:50 +0000602 self.ignore_skip_reason_regexes = (
Todd Fialaea736242015-09-23 15:21:28 +0000603 XunitFormatter._build_regex_list_from_patterns(
604 options.ignore_skip_reason_patterns))
Todd Fiala68615ce2015-09-15 21:38:04 +0000605
606 self.elements = {
607 "successes": [],
608 "errors": [],
609 "failures": [],
610 "skips": [],
611 "unexpected_successes": [],
612 "expected_failures": [],
613 "all": []
614 }
615
616 self.status_handlers = {
617 "success": self._handle_success,
618 "failure": self._handle_failure,
619 "error": self._handle_error,
620 "skip": self._handle_skip,
621 "expected_failure": self._handle_expected_failure,
622 "unexpected_success": self._handle_unexpected_success
623 }
624
Todd Fialae83f1402015-09-18 22:45:31 +0000625 def handle_event(self, test_event):
626 super(XunitFormatter, self).handle_event(test_event)
Todd Fiala68615ce2015-09-15 21:38:04 +0000627
628 event_type = test_event["event"]
629 if event_type is None:
630 return
631
Todd Fialae83f1402015-09-18 22:45:31 +0000632 if event_type == "terminate":
633 self._finish_output()
634 elif event_type == "test_start":
Todd Fiala68615ce2015-09-15 21:38:04 +0000635 self.track_start_time(
636 test_event["test_class"],
637 test_event["test_name"],
638 test_event["event_time"])
639 elif event_type == "test_result":
640 self._process_test_result(test_event)
641 else:
Todd Fiala33896a92015-09-18 21:01:13 +0000642 # This is an unknown event.
643 if self.options.assert_on_unknown_events:
644 raise Exception("unknown event type {} from {}\n".format(
645 event_type, test_event))
Todd Fiala68615ce2015-09-15 21:38:04 +0000646
647 def _handle_success(self, test_event):
648 """Handles a test success.
649 @param test_event the test event to handle.
650 """
651 result = self._common_add_testcase_entry(test_event)
652 with self.lock:
653 self.elements["successes"].append(result)
654
655 def _handle_failure(self, test_event):
656 """Handles a test failure.
657 @param test_event the test event to handle.
658 """
Todd Fiala8effde42015-09-18 16:00:52 +0000659 message = self._replace_invalid_xml(test_event["issue_message"])
660 backtrace = self._replace_invalid_xml(
661 "".join(test_event.get("issue_backtrace", [])))
Todd Fialae7e911f2015-09-18 07:08:09 +0000662
Todd Fiala68615ce2015-09-15 21:38:04 +0000663 result = self._common_add_testcase_entry(
664 test_event,
Todd Fiala8effde42015-09-18 16:00:52 +0000665 inner_content=(
666 '<failure type={} message={}><![CDATA[{}]]></failure>'.format(
667 XunitFormatter._quote_attribute(test_event["issue_class"]),
668 XunitFormatter._quote_attribute(message),
669 backtrace)
Todd Fialae7e911f2015-09-18 07:08:09 +0000670 ))
Todd Fiala68615ce2015-09-15 21:38:04 +0000671 with self.lock:
672 self.elements["failures"].append(result)
673
674 def _handle_error(self, test_event):
675 """Handles a test error.
676 @param test_event the test event to handle.
677 """
Todd Fiala8effde42015-09-18 16:00:52 +0000678 message = self._replace_invalid_xml(test_event["issue_message"])
679 backtrace = self._replace_invalid_xml(
680 "".join(test_event.get("issue_backtrace", [])))
Todd Fialae7e911f2015-09-18 07:08:09 +0000681
Todd Fiala68615ce2015-09-15 21:38:04 +0000682 result = self._common_add_testcase_entry(
683 test_event,
Todd Fiala8effde42015-09-18 16:00:52 +0000684 inner_content=(
685 '<error type={} message={}><![CDATA[{}]]></error>'.format(
686 XunitFormatter._quote_attribute(test_event["issue_class"]),
687 XunitFormatter._quote_attribute(message),
688 backtrace)
Todd Fialae7e911f2015-09-18 07:08:09 +0000689 ))
Todd Fiala68615ce2015-09-15 21:38:04 +0000690 with self.lock:
691 self.elements["errors"].append(result)
692
Todd Fiala132c2c42015-09-22 06:32:50 +0000693 @staticmethod
694 def _ignore_based_on_regex_list(test_event, test_key, regex_list):
695 """Returns whether to ignore a test event based on patterns.
696
697 @param test_event the test event dictionary to check.
698 @param test_key the key within the dictionary to check.
699 @param regex_list a list of zero or more regexes. May contain
700 zero or more compiled regexes.
701
702 @return True if any o the regex list match based on the
703 re.search() method; false otherwise.
704 """
705 for regex in regex_list:
706 match = regex.search(test_event.get(test_key, ''))
707 if match:
708 return True
709 return False
710
Todd Fiala68615ce2015-09-15 21:38:04 +0000711 def _handle_skip(self, test_event):
712 """Handles a skipped test.
713 @param test_event the test event to handle.
714 """
Todd Fiala132c2c42015-09-22 06:32:50 +0000715
716 # Are we ignoring this test based on test name?
717 if XunitFormatter._ignore_based_on_regex_list(
718 test_event, 'test_name', self.ignore_skip_name_regexes):
719 return
720
721 # Are we ignoring this test based on skip reason?
722 if XunitFormatter._ignore_based_on_regex_list(
723 test_event, 'skip_reason', self.ignore_skip_reason_regexes):
724 return
725
726 # We're not ignoring this test. Process the skip.
Todd Fiala8effde42015-09-18 16:00:52 +0000727 reason = self._replace_invalid_xml(test_event.get("skip_reason", ""))
Todd Fiala68615ce2015-09-15 21:38:04 +0000728 result = self._common_add_testcase_entry(
729 test_event,
730 inner_content='<skipped message={} />'.format(
Todd Fiala8effde42015-09-18 16:00:52 +0000731 XunitFormatter._quote_attribute(reason)))
Todd Fiala68615ce2015-09-15 21:38:04 +0000732 with self.lock:
733 self.elements["skips"].append(result)
734
735 def _handle_expected_failure(self, test_event):
736 """Handles a test that failed as expected.
737 @param test_event the test event to handle.
738 """
739 if self.options.xfail == XunitFormatter.RM_PASSTHRU:
740 # This is not a natively-supported junit/xunit
741 # testcase mode, so it might fail a validating
742 # test results viewer.
743 if "bugnumber" in test_event:
744 bug_id_attribute = 'bug-id={} '.format(
745 XunitFormatter._quote_attribute(test_event["bugnumber"]))
746 else:
747 bug_id_attribute = ''
748
749 result = self._common_add_testcase_entry(
750 test_event,
751 inner_content=(
752 '<expected-failure {}type={} message={} />'.format(
753 bug_id_attribute,
754 XunitFormatter._quote_attribute(
755 test_event["issue_class"]),
756 XunitFormatter._quote_attribute(
757 test_event["issue_message"]))
758 ))
759 with self.lock:
760 self.elements["expected_failures"].append(result)
761 elif self.options.xfail == XunitFormatter.RM_SUCCESS:
762 result = self._common_add_testcase_entry(test_event)
763 with self.lock:
764 self.elements["successes"].append(result)
765 elif self.options.xfail == XunitFormatter.RM_FAILURE:
766 result = self._common_add_testcase_entry(
767 test_event,
768 inner_content='<failure type={} message={} />'.format(
769 XunitFormatter._quote_attribute(test_event["issue_class"]),
770 XunitFormatter._quote_attribute(
771 test_event["issue_message"])))
772 with self.lock:
773 self.elements["failures"].append(result)
774 elif self.options.xfail == XunitFormatter.RM_IGNORE:
775 pass
776 else:
777 raise Exception(
778 "unknown xfail option: {}".format(self.options.xfail))
779
780 def _handle_unexpected_success(self, test_event):
781 """Handles a test that passed but was expected to fail.
782 @param test_event the test event to handle.
783 """
784 if self.options.xpass == XunitFormatter.RM_PASSTHRU:
785 # This is not a natively-supported junit/xunit
786 # testcase mode, so it might fail a validating
787 # test results viewer.
788 result = self._common_add_testcase_entry(
789 test_event,
790 inner_content=("<unexpected-success />"))
791 with self.lock:
792 self.elements["unexpected_successes"].append(result)
793 elif self.options.xpass == XunitFormatter.RM_SUCCESS:
794 # Treat the xpass as a success.
795 result = self._common_add_testcase_entry(test_event)
796 with self.lock:
797 self.elements["successes"].append(result)
798 elif self.options.xpass == XunitFormatter.RM_FAILURE:
799 # Treat the xpass as a failure.
800 if "bugnumber" in test_event:
801 message = "unexpected success (bug_id:{})".format(
802 test_event["bugnumber"])
803 else:
804 message = "unexpected success (bug_id:none)"
805 result = self._common_add_testcase_entry(
806 test_event,
807 inner_content='<failure type={} message={} />'.format(
808 XunitFormatter._quote_attribute("unexpected_success"),
809 XunitFormatter._quote_attribute(message)))
810 with self.lock:
811 self.elements["failures"].append(result)
812 elif self.options.xpass == XunitFormatter.RM_IGNORE:
813 # Ignore the xpass result as far as xUnit reporting goes.
814 pass
815 else:
816 raise Exception("unknown xpass option: {}".format(
817 self.options.xpass))
818
819 def _process_test_result(self, test_event):
820 """Processes the test_event known to be a test result.
821
822 This categorizes the event appropriately and stores the data needed
823 to generate the final xUnit report. This method skips events that
824 cannot be represented in xUnit output.
825 """
826 if "status" not in test_event:
827 raise Exception("test event dictionary missing 'status' key")
828
829 status = test_event["status"]
830 if status not in self.status_handlers:
831 raise Exception("test event status '{}' unsupported".format(
832 status))
833
834 # Call the status handler for the test result.
835 self.status_handlers[status](test_event)
836
837 def _common_add_testcase_entry(self, test_event, inner_content=None):
838 """Registers a testcase result, and returns the text created.
839
840 The caller is expected to manage failure/skip/success counts
841 in some kind of appropriate way. This call simply constructs
842 the XML and appends the returned result to the self.all_results
843 list.
844
845 @param test_event the test event dictionary.
846
847 @param inner_content if specified, gets included in the <testcase>
848 inner section, at the point before stdout and stderr would be
849 included. This is where a <failure/>, <skipped/>, <error/>, etc.
850 could go.
851
852 @return the text of the xml testcase element.
853 """
854
855 # Get elapsed time.
856 test_class = test_event["test_class"]
857 test_name = test_event["test_name"]
858 event_time = test_event["event_time"]
859 time_taken = self.elapsed_time_for_test(
860 test_class, test_name, event_time)
861
862 # Plumb in stdout/stderr once we shift over to only test results.
863 test_stdout = ''
864 test_stderr = ''
865
866 # Formulate the output xml.
867 if not inner_content:
868 inner_content = ""
869 result = (
870 '<testcase classname="{}" name="{}" time="{:.3f}">'
871 '{}{}{}</testcase>'.format(
872 test_class,
873 test_name,
874 time_taken,
875 inner_content,
876 test_stdout,
877 test_stderr))
878
879 # Save the result, update total test count.
880 with self.lock:
881 self.total_test_count += 1
882 self.elements["all"].append(result)
883
884 return result
885
Todd Fialae83f1402015-09-18 22:45:31 +0000886 def _finish_output_no_lock(self):
Todd Fiala68615ce2015-09-15 21:38:04 +0000887 """Flushes out the report of test executions to form valid xml output.
888
889 xUnit output is in XML. The reporting system cannot complete the
890 formatting of the output without knowing when there is no more input.
891 This call addresses notifcation of the completed test run and thus is
892 when we can finish off the report output.
893 """
894
895 # Figure out the counts line for the testsuite. If we have
896 # been counting either unexpected successes or expected
897 # failures, we'll output those in the counts, at the risk of
898 # being invalidated by a validating test results viewer.
899 # These aren't counted by default so they won't show up unless
900 # the user specified a formatter option to include them.
901 xfail_count = len(self.elements["expected_failures"])
902 xpass_count = len(self.elements["unexpected_successes"])
903 if xfail_count > 0 or xpass_count > 0:
904 extra_testsuite_attributes = (
905 ' expected-failures="{}"'
906 ' unexpected-successes="{}"'.format(xfail_count, xpass_count))
907 else:
908 extra_testsuite_attributes = ""
909
910 # Output the header.
911 self.out_file.write(
912 '<?xml version="1.0" encoding="{}"?>\n'
Todd Fiala038bf832015-09-18 01:43:08 +0000913 '<testsuites>'
Todd Fiala68615ce2015-09-15 21:38:04 +0000914 '<testsuite name="{}" tests="{}" errors="{}" failures="{}" '
915 'skip="{}"{}>\n'.format(
916 self.text_encoding,
917 "LLDB test suite",
918 self.total_test_count,
919 len(self.elements["errors"]),
920 len(self.elements["failures"]),
921 len(self.elements["skips"]),
922 extra_testsuite_attributes))
923
924 # Output each of the test result entries.
925 for result in self.elements["all"]:
926 self.out_file.write(result + '\n')
927
928 # Close off the test suite.
Todd Fiala038bf832015-09-18 01:43:08 +0000929 self.out_file.write('</testsuite></testsuites>\n')
Todd Fiala68615ce2015-09-15 21:38:04 +0000930
Todd Fialae83f1402015-09-18 22:45:31 +0000931 def _finish_output(self):
Todd Fiala132c2c42015-09-22 06:32:50 +0000932 """Finish writing output as all incoming events have arrived."""
Todd Fiala68615ce2015-09-15 21:38:04 +0000933 with self.lock:
Todd Fialae83f1402015-09-18 22:45:31 +0000934 self._finish_output_no_lock()
Todd Fiala68615ce2015-09-15 21:38:04 +0000935
936
937class RawPickledFormatter(ResultsFormatter):
938 """Formats events as a pickled stream.
939
940 The parallel test runner has inferiors pickle their results and send them
941 over a socket back to the parallel test. The parallel test runner then
942 aggregates them into the final results formatter (e.g. xUnit).
943 """
944
945 @classmethod
946 def arg_parser(cls):
947 """@return arg parser used to parse formatter-specific options."""
948 parser = super(RawPickledFormatter, cls).arg_parser()
949 return parser
950
951 def __init__(self, out_file, options):
952 super(RawPickledFormatter, self).__init__(out_file, options)
953 self.pid = os.getpid()
954
Todd Fialae83f1402015-09-18 22:45:31 +0000955 def handle_event(self, test_event):
956 super(RawPickledFormatter, self).handle_event(test_event)
Todd Fiala68615ce2015-09-15 21:38:04 +0000957
Todd Fialae83f1402015-09-18 22:45:31 +0000958 # Convert initialize/terminate events into job_begin/job_end events.
959 event_type = test_event["event"]
960 if event_type is None:
961 return
962
963 if event_type == "initialize":
964 test_event["event"] = "job_begin"
965 elif event_type == "terminate":
966 test_event["event"] = "job_end"
967
968 # Tack on the pid.
969 test_event["pid"] = self.pid
Todd Fiala68615ce2015-09-15 21:38:04 +0000970
Todd Fiala68615ce2015-09-15 21:38:04 +0000971 # Send it as {serialized_length_of_serialized_bytes}#{serialized_bytes}
972 pickled_message = cPickle.dumps(test_event)
973 self.out_file.send(
974 "{}#{}".format(len(pickled_message), pickled_message))
975
Todd Fiala33896a92015-09-18 21:01:13 +0000976
977class DumpFormatter(ResultsFormatter):
978 """Formats events to the file as their raw python dictionary format."""
979
Todd Fialae83f1402015-09-18 22:45:31 +0000980 def handle_event(self, test_event):
981 super(DumpFormatter, self).handle_event(test_event)
Todd Fiala33896a92015-09-18 21:01:13 +0000982 self.out_file.write("\n" + pprint.pformat(test_event) + "\n")