blob: f35d34c9d03e6094e28e41d8ba38ad78785e787e [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
Zachary Turner35d017f2015-10-23 17:04:29 +000011from __future__ import print_function
12
Zachary Turner814236d2015-10-21 17:48:52 +000013import lldb_shared
14
Todd Fiala68615ce2015-09-15 21:38:04 +000015import argparse
Todd Fiala68615ce2015-09-15 21:38:04 +000016import inspect
17import os
Todd Fiala33896a92015-09-18 21:01:13 +000018import pprint
Todd Fiala8effde42015-09-18 16:00:52 +000019import re
Todd Fiala68615ce2015-09-15 21:38:04 +000020import sys
21import threading
22import time
Todd Fialae7e911f2015-09-18 07:08:09 +000023import traceback
Todd Fiala68615ce2015-09-15 21:38:04 +000024import xml.sax.saxutils
25
Zachary Turner814236d2015-10-21 17:48:52 +000026from six.moves import cPickle
27
Todd Fiala68615ce2015-09-15 21:38:04 +000028
29class EventBuilder(object):
30 """Helper class to build test result event dictionaries."""
Todd Fiala33896a92015-09-18 21:01:13 +000031
32 BASE_DICTIONARY = None
33
Todd Fiala68615ce2015-09-15 21:38:04 +000034 @staticmethod
35 def _get_test_name_info(test):
36 """Returns (test-class-name, test-method-name) from a test case instance.
37
38 @param test a unittest.TestCase instance.
39
40 @return tuple containing (test class name, test method name)
41 """
42 test_class_components = test.id().split(".")
43 test_class_name = ".".join(test_class_components[:-1])
44 test_name = test_class_components[-1]
45 return (test_class_name, test_name)
46
47 @staticmethod
Todd Fialae83f1402015-09-18 22:45:31 +000048 def bare_event(event_type):
49 """Creates an event with default additions, event type and timestamp.
50
51 @param event_type the value set for the "event" key, used
52 to distinguish events.
53
54 @returns an event dictionary with all default additions, the "event"
55 key set to the passed in event_type, and the event_time value set to
56 time.time().
57 """
58 if EventBuilder.BASE_DICTIONARY is not None:
59 # Start with a copy of the "always include" entries.
60 event = dict(EventBuilder.BASE_DICTIONARY)
61 else:
62 event = {}
63
64 event.update({
65 "event": event_type,
66 "event_time": time.time()
67 })
68 return event
69
70 @staticmethod
Todd Fiala68615ce2015-09-15 21:38:04 +000071 def _event_dictionary_common(test, event_type):
72 """Returns an event dictionary setup with values for the given event type.
73
74 @param test the unittest.TestCase instance
75
76 @param event_type the name of the event type (string).
77
78 @return event dictionary with common event fields set.
79 """
80 test_class_name, test_name = EventBuilder._get_test_name_info(test)
Todd Fiala33896a92015-09-18 21:01:13 +000081
Todd Fialae83f1402015-09-18 22:45:31 +000082 event = EventBuilder.bare_event(event_type)
83 event.update({
Todd Fiala68615ce2015-09-15 21:38:04 +000084 "test_class": test_class_name,
85 "test_name": test_name,
Todd Fialaf77f8ae2015-09-18 22:57:04 +000086 "test_filename": inspect.getfile(test.__class__)
Todd Fiala33896a92015-09-18 21:01:13 +000087 })
Todd Fialae83f1402015-09-18 22:45:31 +000088 return event
Todd Fiala68615ce2015-09-15 21:38:04 +000089
90 @staticmethod
91 def _error_tuple_class(error_tuple):
92 """Returns the unittest error tuple's error class as a string.
93
94 @param error_tuple the error tuple provided by the test framework.
95
96 @return the error type (typically an exception) raised by the
97 test framework.
98 """
99 type_var = error_tuple[0]
100 module = inspect.getmodule(type_var)
101 if module:
102 return "{}.{}".format(module.__name__, type_var.__name__)
103 else:
104 return type_var.__name__
105
106 @staticmethod
107 def _error_tuple_message(error_tuple):
108 """Returns the unittest error tuple's error message.
109
110 @param error_tuple the error tuple provided by the test framework.
111
112 @return the error message provided by the test framework.
113 """
114 return str(error_tuple[1])
115
116 @staticmethod
Todd Fialae7e911f2015-09-18 07:08:09 +0000117 def _error_tuple_traceback(error_tuple):
118 """Returns the unittest error tuple's error message.
119
120 @param error_tuple the error tuple provided by the test framework.
121
122 @return the error message provided by the test framework.
123 """
124 return error_tuple[2]
125
126 @staticmethod
Todd Fiala68615ce2015-09-15 21:38:04 +0000127 def _event_dictionary_test_result(test, status):
128 """Returns an event dictionary with common test result fields set.
129
130 @param test a unittest.TestCase instance.
131
132 @param status the status/result of the test
133 (e.g. "success", "failure", etc.)
134
135 @return the event dictionary
136 """
137 event = EventBuilder._event_dictionary_common(test, "test_result")
138 event["status"] = status
139 return event
140
141 @staticmethod
142 def _event_dictionary_issue(test, status, error_tuple):
143 """Returns an event dictionary with common issue-containing test result
144 fields set.
145
146 @param test a unittest.TestCase instance.
147
148 @param status the status/result of the test
149 (e.g. "success", "failure", etc.)
150
151 @param error_tuple the error tuple as reported by the test runner.
152 This is of the form (type<error>, error).
153
154 @return the event dictionary
155 """
156 event = EventBuilder._event_dictionary_test_result(test, status)
157 event["issue_class"] = EventBuilder._error_tuple_class(error_tuple)
158 event["issue_message"] = EventBuilder._error_tuple_message(error_tuple)
Todd Fiala33896a92015-09-18 21:01:13 +0000159 backtrace = EventBuilder._error_tuple_traceback(error_tuple)
160 if backtrace is not None:
161 event["issue_backtrace"] = traceback.format_tb(backtrace)
Todd Fiala68615ce2015-09-15 21:38:04 +0000162 return event
163
164 @staticmethod
165 def event_for_start(test):
166 """Returns an event dictionary for the test start event.
167
168 @param test a unittest.TestCase instance.
169
170 @return the event dictionary
171 """
172 return EventBuilder._event_dictionary_common(test, "test_start")
173
174 @staticmethod
175 def event_for_success(test):
176 """Returns an event dictionary for a successful test.
177
178 @param test a unittest.TestCase instance.
179
180 @return the event dictionary
181 """
182 return EventBuilder._event_dictionary_test_result(test, "success")
183
184 @staticmethod
185 def event_for_unexpected_success(test, bugnumber):
186 """Returns an event dictionary for a test that succeeded but was
187 expected to fail.
188
189 @param test a unittest.TestCase instance.
190
191 @param bugnumber the issue identifier for the bug tracking the
192 fix request for the test expected to fail (but is in fact
193 passing here).
194
195 @return the event dictionary
196
197 """
198 event = EventBuilder._event_dictionary_test_result(
199 test, "unexpected_success")
200 if bugnumber:
201 event["bugnumber"] = str(bugnumber)
202 return event
203
204 @staticmethod
205 def event_for_failure(test, error_tuple):
206 """Returns an event dictionary for a test that failed.
207
208 @param test a unittest.TestCase instance.
209
210 @param error_tuple the error tuple as reported by the test runner.
211 This is of the form (type<error>, error).
212
213 @return the event dictionary
214 """
215 return EventBuilder._event_dictionary_issue(
216 test, "failure", error_tuple)
217
218 @staticmethod
219 def event_for_expected_failure(test, error_tuple, bugnumber):
220 """Returns an event dictionary for a test that failed as expected.
221
222 @param test a unittest.TestCase instance.
223
224 @param error_tuple the error tuple as reported by the test runner.
225 This is of the form (type<error>, error).
226
227 @param bugnumber the issue identifier for the bug tracking the
228 fix request for the test expected to fail.
229
230 @return the event dictionary
231
232 """
233 event = EventBuilder._event_dictionary_issue(
234 test, "expected_failure", error_tuple)
235 if bugnumber:
236 event["bugnumber"] = str(bugnumber)
237 return event
238
239 @staticmethod
240 def event_for_skip(test, reason):
241 """Returns an event dictionary for a test that was skipped.
242
243 @param test a unittest.TestCase instance.
244
245 @param reason the reason why the test is being skipped.
246
247 @return the event dictionary
248 """
249 event = EventBuilder._event_dictionary_test_result(test, "skip")
250 event["skip_reason"] = reason
251 return event
252
253 @staticmethod
254 def event_for_error(test, error_tuple):
255 """Returns an event dictionary for a test that hit a test execution error.
256
257 @param test a unittest.TestCase instance.
258
259 @param error_tuple the error tuple as reported by the test runner.
260 This is of the form (type<error>, error).
261
262 @return the event dictionary
263 """
264 return EventBuilder._event_dictionary_issue(test, "error", error_tuple)
265
266 @staticmethod
267 def event_for_cleanup_error(test, error_tuple):
268 """Returns an event dictionary for a test that hit a test execution error
269 during the test cleanup phase.
270
271 @param test a unittest.TestCase instance.
272
273 @param error_tuple the error tuple as reported by the test runner.
274 This is of the form (type<error>, error).
275
276 @return the event dictionary
277 """
278 event = EventBuilder._event_dictionary_issue(
279 test, "error", error_tuple)
280 event["issue_phase"] = "cleanup"
281 return event
282
Todd Fiala33896a92015-09-18 21:01:13 +0000283 @staticmethod
284 def add_entries_to_all_events(entries_dict):
285 """Specifies a dictionary of entries to add to all test events.
286
287 This provides a mechanism for, say, a parallel test runner to
288 indicate to each inferior dotest.py that it should add a
289 worker index to each.
290
291 Calling this method replaces all previous entries added
292 by a prior call to this.
293
294 Event build methods will overwrite any entries that collide.
295 Thus, the passed in dictionary is the base, which gets merged
296 over by event building when keys collide.
297
298 @param entries_dict a dictionary containing key and value
299 pairs that should be merged into all events created by the
300 event generator. May be None to clear out any extra entries.
301 """
302 EventBuilder.BASE_DICTIONARY = dict(entries_dict)
303
Todd Fiala68615ce2015-09-15 21:38:04 +0000304
305class ResultsFormatter(object):
Todd Fiala33896a92015-09-18 21:01:13 +0000306
Todd Fiala68615ce2015-09-15 21:38:04 +0000307 """Provides interface to formatting test results out to a file-like object.
308
309 This class allows the LLDB test framework's raw test-realted
310 events to be processed and formatted in any manner desired.
311 Test events are represented by python dictionaries, formatted
312 as in the EventBuilder class above.
313
314 ResultFormatter instances are given a file-like object in which
315 to write their results.
316
317 ResultFormatter lifetime looks like the following:
318
319 # The result formatter is created.
320 # The argparse options dictionary is generated from calling
321 # the SomeResultFormatter.arg_parser() with the options data
322 # passed to dotest.py via the "--results-formatter-options"
323 # argument. See the help on that for syntactic requirements
324 # on getting that parsed correctly.
325 formatter = SomeResultFormatter(file_like_object, argpared_options_dict)
326
327 # Single call to session start, before parsing any events.
328 formatter.begin_session()
329
Todd Fialae83f1402015-09-18 22:45:31 +0000330 formatter.handle_event({"event":"initialize",...})
331
Todd Fiala68615ce2015-09-15 21:38:04 +0000332 # Zero or more calls specified for events recorded during the test session.
333 # The parallel test runner manages getting results from all the inferior
334 # dotest processes, so from a new format perspective, don't worry about
335 # that. The formatter will be presented with a single stream of events
336 # sandwiched between a single begin_session()/end_session() pair in the
337 # parallel test runner process/thread.
338 for event in zero_or_more_test_events():
Todd Fialae83f1402015-09-18 22:45:31 +0000339 formatter.handle_event(event)
Todd Fiala68615ce2015-09-15 21:38:04 +0000340
Todd Fialae83f1402015-09-18 22:45:31 +0000341 # Single call to terminate/wrap-up. Formatters that need all the
342 # data before they can print a correct result (e.g. xUnit/JUnit),
343 # this is where the final report can be generated.
344 formatter.handle_event({"event":"terminate",...})
Todd Fiala68615ce2015-09-15 21:38:04 +0000345
346 It is not the formatter's responsibility to close the file_like_object.
347 (i.e. do not close it).
348
349 The lldb test framework passes these test events in real time, so they
350 arrive as they come in.
351
352 In the case of the parallel test runner, the dotest inferiors
353 add a 'pid' field to the dictionary that indicates which inferior
354 pid generated the event.
355
356 Note more events may be added in the future to support richer test
357 reporting functionality. One example: creating a true flaky test
358 result category so that unexpected successes really mean the test
359 is marked incorrectly (either should be marked flaky, or is indeed
360 passing consistently now and should have the xfail marker
361 removed). In this case, a flaky_success and flaky_fail event
362 likely will be added to capture these and support reporting things
363 like percentages of flaky test passing so we can see if we're
364 making some things worse/better with regards to failure rates.
365
366 Another example: announcing all the test methods that are planned
367 to be run, so we can better support redo operations of various kinds
368 (redo all non-run tests, redo non-run tests except the one that
369 was running [perhaps crashed], etc.)
370
371 Implementers are expected to override all the public methods
372 provided in this class. See each method's docstring to see
373 expectations about when the call should be chained.
374
375 """
376
377 @classmethod
378 def arg_parser(cls):
379 """@return arg parser used to parse formatter-specific options."""
380 parser = argparse.ArgumentParser(
381 description='{} options'.format(cls.__name__),
382 usage=('dotest.py --results-formatter-options='
383 '"--option1 value1 [--option2 value2 [...]]"'))
384 return parser
385
386 def __init__(self, out_file, options):
387 super(ResultsFormatter, self).__init__()
388 self.out_file = out_file
389 self.options = options
Greg Clayton1827fc22015-09-19 00:39:09 +0000390 self.using_terminal = False
Todd Fiala68615ce2015-09-15 21:38:04 +0000391 if not self.out_file:
392 raise Exception("ResultsFormatter created with no file object")
393 self.start_time_by_test = {}
Todd Fialade9a44e2015-09-22 00:15:50 +0000394 self.terminate_called = False
Todd Fiala68615ce2015-09-15 21:38:04 +0000395
396 # Lock that we use while mutating inner state, like the
397 # total test count and the elements. We minimize how
398 # long we hold the lock just to keep inner state safe, not
399 # entirely consistent from the outside.
400 self.lock = threading.Lock()
401
Todd Fialae83f1402015-09-18 22:45:31 +0000402 def handle_event(self, test_event):
403 """Handles the test event for collection into the formatter output.
Todd Fiala68615ce2015-09-15 21:38:04 +0000404
405 Derived classes may override this but should call down to this
406 implementation first.
407
408 @param test_event the test event as formatted by one of the
409 event_for_* calls.
410 """
Todd Fialade9a44e2015-09-22 00:15:50 +0000411 # Keep track of whether terminate was received. We do this so
412 # that a process can call the 'terminate' event on its own, to
413 # close down a formatter at the appropriate time. Then the
414 # atexit() cleanup can call the "terminate if it hasn't been
415 # called yet".
416 if test_event is not None:
417 if test_event.get("event", "") == "terminate":
418 self.terminate_called = True
Todd Fiala68615ce2015-09-15 21:38:04 +0000419
420 def track_start_time(self, test_class, test_name, start_time):
421 """Tracks the start time of a test so elapsed time can be computed.
422
423 This alleviates the need for test results to be processed serially
424 by test. It will save the start time for the test so that
425 elapsed_time_for_test() can compute the elapsed time properly.
426 """
427 if test_class is None or test_name is None:
428 return
429
430 test_key = "{}.{}".format(test_class, test_name)
431 with self.lock:
432 self.start_time_by_test[test_key] = start_time
433
434 def elapsed_time_for_test(self, test_class, test_name, end_time):
435 """Returns the elapsed time for a test.
436
437 This function can only be called once per test and requires that
438 the track_start_time() method be called sometime prior to calling
439 this method.
440 """
441 if test_class is None or test_name is None:
442 return -2.0
443
444 test_key = "{}.{}".format(test_class, test_name)
445 with self.lock:
446 if test_key not in self.start_time_by_test:
447 return -1.0
448 else:
449 start_time = self.start_time_by_test[test_key]
450 del self.start_time_by_test[test_key]
451 return end_time - start_time
452
Greg Clayton1827fc22015-09-19 00:39:09 +0000453 def is_using_terminal(self):
Todd Fialade9a44e2015-09-22 00:15:50 +0000454 """Returns True if this results formatter is using the terminal and
455 output should be avoided."""
Greg Clayton1827fc22015-09-19 00:39:09 +0000456 return self.using_terminal
Todd Fiala68615ce2015-09-15 21:38:04 +0000457
Todd Fialade9a44e2015-09-22 00:15:50 +0000458 def send_terminate_as_needed(self):
459 """Sends the terminate event if it hasn't been received yet."""
460 if not self.terminate_called:
461 terminate_event = EventBuilder.bare_event("terminate")
462 self.handle_event(terminate_event)
463
Todd Fiala132c2c42015-09-22 06:32:50 +0000464
Todd Fiala68615ce2015-09-15 21:38:04 +0000465class XunitFormatter(ResultsFormatter):
466 """Provides xUnit-style formatted output.
467 """
468
469 # Result mapping arguments
470 RM_IGNORE = 'ignore'
471 RM_SUCCESS = 'success'
472 RM_FAILURE = 'failure'
473 RM_PASSTHRU = 'passthru'
474
475 @staticmethod
Todd Fiala8effde42015-09-18 16:00:52 +0000476 def _build_illegal_xml_regex():
Todd Fiala33896a92015-09-18 21:01:13 +0000477 """Contructs a regex to match all illegal xml characters.
478
479 Expects to be used against a unicode string."""
Todd Fiala8effde42015-09-18 16:00:52 +0000480 # Construct the range pairs of invalid unicode chareacters.
481 illegal_chars_u = [
482 (0x00, 0x08), (0x0B, 0x0C), (0x0E, 0x1F), (0x7F, 0x84),
483 (0x86, 0x9F), (0xFDD0, 0xFDDF), (0xFFFE, 0xFFFF)]
484
485 # For wide builds, we have more.
486 if sys.maxunicode >= 0x10000:
487 illegal_chars_u.extend(
488 [(0x1FFFE, 0x1FFFF), (0x2FFFE, 0x2FFFF), (0x3FFFE, 0x3FFFF),
489 (0x4FFFE, 0x4FFFF), (0x5FFFE, 0x5FFFF), (0x6FFFE, 0x6FFFF),
490 (0x7FFFE, 0x7FFFF), (0x8FFFE, 0x8FFFF), (0x9FFFE, 0x9FFFF),
491 (0xAFFFE, 0xAFFFF), (0xBFFFE, 0xBFFFF), (0xCFFFE, 0xCFFFF),
492 (0xDFFFE, 0xDFFFF), (0xEFFFE, 0xEFFFF), (0xFFFFE, 0xFFFFF),
493 (0x10FFFE, 0x10FFFF)])
494
495 # Build up an array of range expressions.
496 illegal_ranges = [
497 "%s-%s" % (unichr(low), unichr(high))
498 for (low, high) in illegal_chars_u]
499
500 # Compile the regex
501 return re.compile(u'[%s]' % u''.join(illegal_ranges))
502
503 @staticmethod
Todd Fiala68615ce2015-09-15 21:38:04 +0000504 def _quote_attribute(text):
505 """Returns the given text in a manner safe for usage in an XML attribute.
506
507 @param text the text that should appear within an XML attribute.
508 @return the attribute-escaped version of the input text.
509 """
510 return xml.sax.saxutils.quoteattr(text)
511
Todd Fiala8effde42015-09-18 16:00:52 +0000512 def _replace_invalid_xml(self, str_or_unicode):
Todd Fiala33896a92015-09-18 21:01:13 +0000513 """Replaces invalid XML characters with a '?'.
514
515 @param str_or_unicode a string to replace invalid XML
516 characters within. Can be unicode or not. If not unicode,
517 assumes it is a byte string in utf-8 encoding.
518
519 @returns a utf-8-encoded byte string with invalid
520 XML replaced with '?'.
521 """
Todd Fiala8effde42015-09-18 16:00:52 +0000522 # Get the content into unicode
523 if isinstance(str_or_unicode, str):
524 unicode_content = str_or_unicode.decode('utf-8')
525 else:
526 unicode_content = str_or_unicode
527 return self.invalid_xml_re.sub(u'?', unicode_content).encode('utf-8')
528
Todd Fiala68615ce2015-09-15 21:38:04 +0000529 @classmethod
530 def arg_parser(cls):
531 """@return arg parser used to parse formatter-specific options."""
532 parser = super(XunitFormatter, cls).arg_parser()
533
534 # These are valid choices for results mapping.
535 results_mapping_choices = [
536 XunitFormatter.RM_IGNORE,
537 XunitFormatter.RM_SUCCESS,
538 XunitFormatter.RM_FAILURE,
539 XunitFormatter.RM_PASSTHRU]
540 parser.add_argument(
Todd Fiala33896a92015-09-18 21:01:13 +0000541 "--assert-on-unknown-events",
542 action="store_true",
543 help=('cause unknown test events to generate '
544 'a python assert. Default is to ignore.'))
545 parser.add_argument(
Todd Fialaea736242015-09-23 15:21:28 +0000546 "--ignore-skip-name",
547 "-n",
548 metavar='PATTERN',
549 action="append",
550 dest='ignore_skip_name_patterns',
551 help=('a python regex pattern, where '
Todd Fiala132c2c42015-09-22 06:32:50 +0000552 'any skipped test with a test method name where regex '
553 'matches (via search) will be ignored for xUnit test '
Todd Fialaea736242015-09-23 15:21:28 +0000554 'result purposes. Can be specified multiple times.'))
Todd Fiala132c2c42015-09-22 06:32:50 +0000555 parser.add_argument(
Todd Fialaea736242015-09-23 15:21:28 +0000556 "--ignore-skip-reason",
557 "-r",
558 metavar='PATTERN',
559 action="append",
560 dest='ignore_skip_reason_patterns',
561 help=('a python regex pattern, where '
Todd Fiala132c2c42015-09-22 06:32:50 +0000562 'any skipped test with a skip reason where the regex '
563 'matches (via search) will be ignored for xUnit test '
Todd Fialaea736242015-09-23 15:21:28 +0000564 'result purposes. Can be specified multiple times.'))
Todd Fiala132c2c42015-09-22 06:32:50 +0000565 parser.add_argument(
Todd Fiala68615ce2015-09-15 21:38:04 +0000566 "--xpass", action="store", choices=results_mapping_choices,
567 default=XunitFormatter.RM_FAILURE,
568 help=('specify mapping from unexpected success to jUnit/xUnit '
569 'result type'))
570 parser.add_argument(
571 "--xfail", action="store", choices=results_mapping_choices,
572 default=XunitFormatter.RM_IGNORE,
573 help=('specify mapping from expected failure to jUnit/xUnit '
574 'result type'))
575 return parser
576
Todd Fiala132c2c42015-09-22 06:32:50 +0000577 @staticmethod
Todd Fialaea736242015-09-23 15:21:28 +0000578 def _build_regex_list_from_patterns(patterns):
Todd Fiala132c2c42015-09-22 06:32:50 +0000579 """Builds a list of compiled regexes from option value.
580
581 @param option string containing a comma-separated list of regex
582 patterns. Zero-length or None will produce an empty regex list.
583
584 @return list of compiled regular expressions, empty if no
585 patterns provided.
586 """
587 regex_list = []
Todd Fialaea736242015-09-23 15:21:28 +0000588 if patterns is not None:
589 for pattern in patterns:
Todd Fiala132c2c42015-09-22 06:32:50 +0000590 regex_list.append(re.compile(pattern))
591 return regex_list
592
Todd Fiala68615ce2015-09-15 21:38:04 +0000593 def __init__(self, out_file, options):
594 """Initializes the XunitFormatter instance.
595 @param out_file file-like object where formatted output is written.
596 @param options_dict specifies a dictionary of options for the
597 formatter.
598 """
599 # Initialize the parent
600 super(XunitFormatter, self).__init__(out_file, options)
601 self.text_encoding = "UTF-8"
Todd Fiala8effde42015-09-18 16:00:52 +0000602 self.invalid_xml_re = XunitFormatter._build_illegal_xml_regex()
Todd Fiala68615ce2015-09-15 21:38:04 +0000603 self.total_test_count = 0
Todd Fiala132c2c42015-09-22 06:32:50 +0000604 self.ignore_skip_name_regexes = (
Todd Fialaea736242015-09-23 15:21:28 +0000605 XunitFormatter._build_regex_list_from_patterns(
606 options.ignore_skip_name_patterns))
Todd Fiala132c2c42015-09-22 06:32:50 +0000607 self.ignore_skip_reason_regexes = (
Todd Fialaea736242015-09-23 15:21:28 +0000608 XunitFormatter._build_regex_list_from_patterns(
609 options.ignore_skip_reason_patterns))
Todd Fiala68615ce2015-09-15 21:38:04 +0000610
611 self.elements = {
612 "successes": [],
613 "errors": [],
614 "failures": [],
615 "skips": [],
616 "unexpected_successes": [],
617 "expected_failures": [],
618 "all": []
619 }
620
621 self.status_handlers = {
622 "success": self._handle_success,
623 "failure": self._handle_failure,
624 "error": self._handle_error,
625 "skip": self._handle_skip,
626 "expected_failure": self._handle_expected_failure,
627 "unexpected_success": self._handle_unexpected_success
628 }
629
Todd Fialae83f1402015-09-18 22:45:31 +0000630 def handle_event(self, test_event):
631 super(XunitFormatter, self).handle_event(test_event)
Todd Fiala68615ce2015-09-15 21:38:04 +0000632
633 event_type = test_event["event"]
634 if event_type is None:
635 return
636
Todd Fialae83f1402015-09-18 22:45:31 +0000637 if event_type == "terminate":
638 self._finish_output()
639 elif event_type == "test_start":
Todd Fiala68615ce2015-09-15 21:38:04 +0000640 self.track_start_time(
641 test_event["test_class"],
642 test_event["test_name"],
643 test_event["event_time"])
644 elif event_type == "test_result":
645 self._process_test_result(test_event)
646 else:
Todd Fiala33896a92015-09-18 21:01:13 +0000647 # This is an unknown event.
648 if self.options.assert_on_unknown_events:
649 raise Exception("unknown event type {} from {}\n".format(
650 event_type, test_event))
Todd Fiala68615ce2015-09-15 21:38:04 +0000651
652 def _handle_success(self, test_event):
653 """Handles a test success.
654 @param test_event the test event to handle.
655 """
656 result = self._common_add_testcase_entry(test_event)
657 with self.lock:
658 self.elements["successes"].append(result)
659
660 def _handle_failure(self, test_event):
661 """Handles a test failure.
662 @param test_event the test event to handle.
663 """
Todd Fiala8effde42015-09-18 16:00:52 +0000664 message = self._replace_invalid_xml(test_event["issue_message"])
665 backtrace = self._replace_invalid_xml(
666 "".join(test_event.get("issue_backtrace", [])))
Todd Fialae7e911f2015-09-18 07:08:09 +0000667
Todd Fiala68615ce2015-09-15 21:38:04 +0000668 result = self._common_add_testcase_entry(
669 test_event,
Todd Fiala8effde42015-09-18 16:00:52 +0000670 inner_content=(
671 '<failure type={} message={}><![CDATA[{}]]></failure>'.format(
672 XunitFormatter._quote_attribute(test_event["issue_class"]),
673 XunitFormatter._quote_attribute(message),
674 backtrace)
Todd Fialae7e911f2015-09-18 07:08:09 +0000675 ))
Todd Fiala68615ce2015-09-15 21:38:04 +0000676 with self.lock:
677 self.elements["failures"].append(result)
678
679 def _handle_error(self, test_event):
680 """Handles a test error.
681 @param test_event the test event to handle.
682 """
Todd Fiala8effde42015-09-18 16:00:52 +0000683 message = self._replace_invalid_xml(test_event["issue_message"])
684 backtrace = self._replace_invalid_xml(
685 "".join(test_event.get("issue_backtrace", [])))
Todd Fialae7e911f2015-09-18 07:08:09 +0000686
Todd Fiala68615ce2015-09-15 21:38:04 +0000687 result = self._common_add_testcase_entry(
688 test_event,
Todd Fiala8effde42015-09-18 16:00:52 +0000689 inner_content=(
690 '<error type={} message={}><![CDATA[{}]]></error>'.format(
691 XunitFormatter._quote_attribute(test_event["issue_class"]),
692 XunitFormatter._quote_attribute(message),
693 backtrace)
Todd Fialae7e911f2015-09-18 07:08:09 +0000694 ))
Todd Fiala68615ce2015-09-15 21:38:04 +0000695 with self.lock:
696 self.elements["errors"].append(result)
697
Todd Fiala132c2c42015-09-22 06:32:50 +0000698 @staticmethod
699 def _ignore_based_on_regex_list(test_event, test_key, regex_list):
700 """Returns whether to ignore a test event based on patterns.
701
702 @param test_event the test event dictionary to check.
703 @param test_key the key within the dictionary to check.
704 @param regex_list a list of zero or more regexes. May contain
705 zero or more compiled regexes.
706
707 @return True if any o the regex list match based on the
708 re.search() method; false otherwise.
709 """
710 for regex in regex_list:
711 match = regex.search(test_event.get(test_key, ''))
712 if match:
713 return True
714 return False
715
Todd Fiala68615ce2015-09-15 21:38:04 +0000716 def _handle_skip(self, test_event):
717 """Handles a skipped test.
718 @param test_event the test event to handle.
719 """
Todd Fiala132c2c42015-09-22 06:32:50 +0000720
721 # Are we ignoring this test based on test name?
722 if XunitFormatter._ignore_based_on_regex_list(
723 test_event, 'test_name', self.ignore_skip_name_regexes):
724 return
725
726 # Are we ignoring this test based on skip reason?
727 if XunitFormatter._ignore_based_on_regex_list(
728 test_event, 'skip_reason', self.ignore_skip_reason_regexes):
729 return
730
731 # We're not ignoring this test. Process the skip.
Todd Fiala8effde42015-09-18 16:00:52 +0000732 reason = self._replace_invalid_xml(test_event.get("skip_reason", ""))
Todd Fiala68615ce2015-09-15 21:38:04 +0000733 result = self._common_add_testcase_entry(
734 test_event,
735 inner_content='<skipped message={} />'.format(
Todd Fiala8effde42015-09-18 16:00:52 +0000736 XunitFormatter._quote_attribute(reason)))
Todd Fiala68615ce2015-09-15 21:38:04 +0000737 with self.lock:
738 self.elements["skips"].append(result)
739
740 def _handle_expected_failure(self, test_event):
741 """Handles a test that failed as expected.
742 @param test_event the test event to handle.
743 """
744 if self.options.xfail == XunitFormatter.RM_PASSTHRU:
745 # This is not a natively-supported junit/xunit
746 # testcase mode, so it might fail a validating
747 # test results viewer.
748 if "bugnumber" in test_event:
749 bug_id_attribute = 'bug-id={} '.format(
750 XunitFormatter._quote_attribute(test_event["bugnumber"]))
751 else:
752 bug_id_attribute = ''
753
754 result = self._common_add_testcase_entry(
755 test_event,
756 inner_content=(
757 '<expected-failure {}type={} message={} />'.format(
758 bug_id_attribute,
759 XunitFormatter._quote_attribute(
760 test_event["issue_class"]),
761 XunitFormatter._quote_attribute(
762 test_event["issue_message"]))
763 ))
764 with self.lock:
765 self.elements["expected_failures"].append(result)
766 elif self.options.xfail == XunitFormatter.RM_SUCCESS:
767 result = self._common_add_testcase_entry(test_event)
768 with self.lock:
769 self.elements["successes"].append(result)
770 elif self.options.xfail == XunitFormatter.RM_FAILURE:
771 result = self._common_add_testcase_entry(
772 test_event,
773 inner_content='<failure type={} message={} />'.format(
774 XunitFormatter._quote_attribute(test_event["issue_class"]),
775 XunitFormatter._quote_attribute(
776 test_event["issue_message"])))
777 with self.lock:
778 self.elements["failures"].append(result)
779 elif self.options.xfail == XunitFormatter.RM_IGNORE:
780 pass
781 else:
782 raise Exception(
783 "unknown xfail option: {}".format(self.options.xfail))
784
785 def _handle_unexpected_success(self, test_event):
786 """Handles a test that passed but was expected to fail.
787 @param test_event the test event to handle.
788 """
789 if self.options.xpass == XunitFormatter.RM_PASSTHRU:
790 # This is not a natively-supported junit/xunit
791 # testcase mode, so it might fail a validating
792 # test results viewer.
793 result = self._common_add_testcase_entry(
794 test_event,
795 inner_content=("<unexpected-success />"))
796 with self.lock:
797 self.elements["unexpected_successes"].append(result)
798 elif self.options.xpass == XunitFormatter.RM_SUCCESS:
799 # Treat the xpass as a success.
800 result = self._common_add_testcase_entry(test_event)
801 with self.lock:
802 self.elements["successes"].append(result)
803 elif self.options.xpass == XunitFormatter.RM_FAILURE:
804 # Treat the xpass as a failure.
805 if "bugnumber" in test_event:
806 message = "unexpected success (bug_id:{})".format(
807 test_event["bugnumber"])
808 else:
809 message = "unexpected success (bug_id:none)"
810 result = self._common_add_testcase_entry(
811 test_event,
812 inner_content='<failure type={} message={} />'.format(
813 XunitFormatter._quote_attribute("unexpected_success"),
814 XunitFormatter._quote_attribute(message)))
815 with self.lock:
816 self.elements["failures"].append(result)
817 elif self.options.xpass == XunitFormatter.RM_IGNORE:
818 # Ignore the xpass result as far as xUnit reporting goes.
819 pass
820 else:
821 raise Exception("unknown xpass option: {}".format(
822 self.options.xpass))
823
824 def _process_test_result(self, test_event):
825 """Processes the test_event known to be a test result.
826
827 This categorizes the event appropriately and stores the data needed
828 to generate the final xUnit report. This method skips events that
829 cannot be represented in xUnit output.
830 """
831 if "status" not in test_event:
832 raise Exception("test event dictionary missing 'status' key")
833
834 status = test_event["status"]
835 if status not in self.status_handlers:
836 raise Exception("test event status '{}' unsupported".format(
837 status))
838
839 # Call the status handler for the test result.
840 self.status_handlers[status](test_event)
841
842 def _common_add_testcase_entry(self, test_event, inner_content=None):
843 """Registers a testcase result, and returns the text created.
844
845 The caller is expected to manage failure/skip/success counts
846 in some kind of appropriate way. This call simply constructs
847 the XML and appends the returned result to the self.all_results
848 list.
849
850 @param test_event the test event dictionary.
851
852 @param inner_content if specified, gets included in the <testcase>
853 inner section, at the point before stdout and stderr would be
854 included. This is where a <failure/>, <skipped/>, <error/>, etc.
855 could go.
856
857 @return the text of the xml testcase element.
858 """
859
860 # Get elapsed time.
861 test_class = test_event["test_class"]
862 test_name = test_event["test_name"]
863 event_time = test_event["event_time"]
864 time_taken = self.elapsed_time_for_test(
865 test_class, test_name, event_time)
866
867 # Plumb in stdout/stderr once we shift over to only test results.
868 test_stdout = ''
869 test_stderr = ''
870
871 # Formulate the output xml.
872 if not inner_content:
873 inner_content = ""
874 result = (
875 '<testcase classname="{}" name="{}" time="{:.3f}">'
876 '{}{}{}</testcase>'.format(
877 test_class,
878 test_name,
879 time_taken,
880 inner_content,
881 test_stdout,
882 test_stderr))
883
884 # Save the result, update total test count.
885 with self.lock:
886 self.total_test_count += 1
887 self.elements["all"].append(result)
888
889 return result
890
Todd Fialae83f1402015-09-18 22:45:31 +0000891 def _finish_output_no_lock(self):
Todd Fiala68615ce2015-09-15 21:38:04 +0000892 """Flushes out the report of test executions to form valid xml output.
893
894 xUnit output is in XML. The reporting system cannot complete the
895 formatting of the output without knowing when there is no more input.
896 This call addresses notifcation of the completed test run and thus is
897 when we can finish off the report output.
898 """
899
900 # Figure out the counts line for the testsuite. If we have
901 # been counting either unexpected successes or expected
902 # failures, we'll output those in the counts, at the risk of
903 # being invalidated by a validating test results viewer.
904 # These aren't counted by default so they won't show up unless
905 # the user specified a formatter option to include them.
906 xfail_count = len(self.elements["expected_failures"])
907 xpass_count = len(self.elements["unexpected_successes"])
908 if xfail_count > 0 or xpass_count > 0:
909 extra_testsuite_attributes = (
910 ' expected-failures="{}"'
911 ' unexpected-successes="{}"'.format(xfail_count, xpass_count))
912 else:
913 extra_testsuite_attributes = ""
914
915 # Output the header.
916 self.out_file.write(
917 '<?xml version="1.0" encoding="{}"?>\n'
Todd Fiala038bf832015-09-18 01:43:08 +0000918 '<testsuites>'
Todd Fiala68615ce2015-09-15 21:38:04 +0000919 '<testsuite name="{}" tests="{}" errors="{}" failures="{}" '
920 'skip="{}"{}>\n'.format(
921 self.text_encoding,
922 "LLDB test suite",
923 self.total_test_count,
924 len(self.elements["errors"]),
925 len(self.elements["failures"]),
926 len(self.elements["skips"]),
927 extra_testsuite_attributes))
928
929 # Output each of the test result entries.
930 for result in self.elements["all"]:
931 self.out_file.write(result + '\n')
932
933 # Close off the test suite.
Todd Fiala038bf832015-09-18 01:43:08 +0000934 self.out_file.write('</testsuite></testsuites>\n')
Todd Fiala68615ce2015-09-15 21:38:04 +0000935
Todd Fialae83f1402015-09-18 22:45:31 +0000936 def _finish_output(self):
Todd Fiala132c2c42015-09-22 06:32:50 +0000937 """Finish writing output as all incoming events have arrived."""
Todd Fiala68615ce2015-09-15 21:38:04 +0000938 with self.lock:
Todd Fialae83f1402015-09-18 22:45:31 +0000939 self._finish_output_no_lock()
Todd Fiala68615ce2015-09-15 21:38:04 +0000940
941
942class RawPickledFormatter(ResultsFormatter):
943 """Formats events as a pickled stream.
944
945 The parallel test runner has inferiors pickle their results and send them
946 over a socket back to the parallel test. The parallel test runner then
947 aggregates them into the final results formatter (e.g. xUnit).
948 """
949
950 @classmethod
951 def arg_parser(cls):
952 """@return arg parser used to parse formatter-specific options."""
953 parser = super(RawPickledFormatter, cls).arg_parser()
954 return parser
955
956 def __init__(self, out_file, options):
957 super(RawPickledFormatter, self).__init__(out_file, options)
958 self.pid = os.getpid()
959
Todd Fialae83f1402015-09-18 22:45:31 +0000960 def handle_event(self, test_event):
961 super(RawPickledFormatter, self).handle_event(test_event)
Todd Fiala68615ce2015-09-15 21:38:04 +0000962
Todd Fialae83f1402015-09-18 22:45:31 +0000963 # Convert initialize/terminate events into job_begin/job_end events.
964 event_type = test_event["event"]
965 if event_type is None:
966 return
967
968 if event_type == "initialize":
969 test_event["event"] = "job_begin"
970 elif event_type == "terminate":
971 test_event["event"] = "job_end"
972
973 # Tack on the pid.
974 test_event["pid"] = self.pid
Todd Fiala68615ce2015-09-15 21:38:04 +0000975
Todd Fiala68615ce2015-09-15 21:38:04 +0000976 # Send it as {serialized_length_of_serialized_bytes}#{serialized_bytes}
977 pickled_message = cPickle.dumps(test_event)
978 self.out_file.send(
979 "{}#{}".format(len(pickled_message), pickled_message))
980
Todd Fiala33896a92015-09-18 21:01:13 +0000981
982class DumpFormatter(ResultsFormatter):
983 """Formats events to the file as their raw python dictionary format."""
984
Todd Fialae83f1402015-09-18 22:45:31 +0000985 def handle_event(self, test_event):
986 super(DumpFormatter, self).handle_event(test_event)
Todd Fiala33896a92015-09-18 21:01:13 +0000987 self.out_file.write("\n" + pprint.pformat(test_event) + "\n")