Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 1 | """ |
| 2 | The LLVM Compiler Infrastructure |
| 3 | |
| 4 | This file is distributed under the University of Illinois Open Source |
| 5 | License. See LICENSE.TXT for details. |
| 6 | |
| 7 | Provides classes used by the test results reporting infrastructure |
| 8 | within the LLDB test suite. |
| 9 | """ |
| 10 | |
| 11 | import argparse |
| 12 | import cPickle |
| 13 | import inspect |
| 14 | import os |
Todd Fiala | 33896a9 | 2015-09-18 21:01:13 +0000 | [diff] [blame] | 15 | import pprint |
Todd Fiala | 8effde4 | 2015-09-18 16:00:52 +0000 | [diff] [blame] | 16 | import re |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 17 | import sys |
| 18 | import threading |
| 19 | import time |
Todd Fiala | e7e911f | 2015-09-18 07:08:09 +0000 | [diff] [blame] | 20 | import traceback |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 21 | import xml.sax.saxutils |
| 22 | |
| 23 | |
| 24 | class EventBuilder(object): |
| 25 | """Helper class to build test result event dictionaries.""" |
Todd Fiala | 33896a9 | 2015-09-18 21:01:13 +0000 | [diff] [blame] | 26 | |
| 27 | BASE_DICTIONARY = None |
| 28 | |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 29 | @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 Fiala | e83f140 | 2015-09-18 22:45:31 +0000 | [diff] [blame] | 43 | 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 Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 66 | 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 Fiala | 33896a9 | 2015-09-18 21:01:13 +0000 | [diff] [blame] | 76 | |
Todd Fiala | e83f140 | 2015-09-18 22:45:31 +0000 | [diff] [blame] | 77 | event = EventBuilder.bare_event(event_type) |
| 78 | event.update({ |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 79 | "test_class": test_class_name, |
| 80 | "test_name": test_name, |
Todd Fiala | f77f8ae | 2015-09-18 22:57:04 +0000 | [diff] [blame^] | 81 | "test_filename": inspect.getfile(test.__class__) |
Todd Fiala | 33896a9 | 2015-09-18 21:01:13 +0000 | [diff] [blame] | 82 | }) |
Todd Fiala | e83f140 | 2015-09-18 22:45:31 +0000 | [diff] [blame] | 83 | return event |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 84 | |
| 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 Fiala | e7e911f | 2015-09-18 07:08:09 +0000 | [diff] [blame] | 112 | 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 Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 122 | 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 Fiala | 33896a9 | 2015-09-18 21:01:13 +0000 | [diff] [blame] | 154 | backtrace = EventBuilder._error_tuple_traceback(error_tuple) |
| 155 | if backtrace is not None: |
| 156 | event["issue_backtrace"] = traceback.format_tb(backtrace) |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 157 | 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 Fiala | 33896a9 | 2015-09-18 21:01:13 +0000 | [diff] [blame] | 278 | @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 Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 299 | |
| 300 | class ResultsFormatter(object): |
Todd Fiala | 33896a9 | 2015-09-18 21:01:13 +0000 | [diff] [blame] | 301 | |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 302 | """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 Fiala | e83f140 | 2015-09-18 22:45:31 +0000 | [diff] [blame] | 325 | formatter.handle_event({"event":"initialize",...}) |
| 326 | |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 327 | # 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 Fiala | e83f140 | 2015-09-18 22:45:31 +0000 | [diff] [blame] | 334 | formatter.handle_event(event) |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 335 | |
Todd Fiala | e83f140 | 2015-09-18 22:45:31 +0000 | [diff] [blame] | 336 | # 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 Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 340 | |
| 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 |
| 385 | if not self.out_file: |
| 386 | raise Exception("ResultsFormatter created with no file object") |
| 387 | self.start_time_by_test = {} |
| 388 | |
| 389 | # Lock that we use while mutating inner state, like the |
| 390 | # total test count and the elements. We minimize how |
| 391 | # long we hold the lock just to keep inner state safe, not |
| 392 | # entirely consistent from the outside. |
| 393 | self.lock = threading.Lock() |
| 394 | |
Todd Fiala | e83f140 | 2015-09-18 22:45:31 +0000 | [diff] [blame] | 395 | def handle_event(self, test_event): |
| 396 | """Handles the test event for collection into the formatter output. |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 397 | |
| 398 | Derived classes may override this but should call down to this |
| 399 | implementation first. |
| 400 | |
| 401 | @param test_event the test event as formatted by one of the |
| 402 | event_for_* calls. |
| 403 | """ |
| 404 | pass |
| 405 | |
| 406 | def track_start_time(self, test_class, test_name, start_time): |
| 407 | """Tracks the start time of a test so elapsed time can be computed. |
| 408 | |
| 409 | This alleviates the need for test results to be processed serially |
| 410 | by test. It will save the start time for the test so that |
| 411 | elapsed_time_for_test() can compute the elapsed time properly. |
| 412 | """ |
| 413 | if test_class is None or test_name is None: |
| 414 | return |
| 415 | |
| 416 | test_key = "{}.{}".format(test_class, test_name) |
| 417 | with self.lock: |
| 418 | self.start_time_by_test[test_key] = start_time |
| 419 | |
| 420 | def elapsed_time_for_test(self, test_class, test_name, end_time): |
| 421 | """Returns the elapsed time for a test. |
| 422 | |
| 423 | This function can only be called once per test and requires that |
| 424 | the track_start_time() method be called sometime prior to calling |
| 425 | this method. |
| 426 | """ |
| 427 | if test_class is None or test_name is None: |
| 428 | return -2.0 |
| 429 | |
| 430 | test_key = "{}.{}".format(test_class, test_name) |
| 431 | with self.lock: |
| 432 | if test_key not in self.start_time_by_test: |
| 433 | return -1.0 |
| 434 | else: |
| 435 | start_time = self.start_time_by_test[test_key] |
| 436 | del self.start_time_by_test[test_key] |
| 437 | return end_time - start_time |
| 438 | |
| 439 | |
| 440 | class XunitFormatter(ResultsFormatter): |
| 441 | """Provides xUnit-style formatted output. |
| 442 | """ |
| 443 | |
| 444 | # Result mapping arguments |
| 445 | RM_IGNORE = 'ignore' |
| 446 | RM_SUCCESS = 'success' |
| 447 | RM_FAILURE = 'failure' |
| 448 | RM_PASSTHRU = 'passthru' |
| 449 | |
| 450 | @staticmethod |
Todd Fiala | 8effde4 | 2015-09-18 16:00:52 +0000 | [diff] [blame] | 451 | def _build_illegal_xml_regex(): |
Todd Fiala | 33896a9 | 2015-09-18 21:01:13 +0000 | [diff] [blame] | 452 | """Contructs a regex to match all illegal xml characters. |
| 453 | |
| 454 | Expects to be used against a unicode string.""" |
Todd Fiala | 8effde4 | 2015-09-18 16:00:52 +0000 | [diff] [blame] | 455 | # Construct the range pairs of invalid unicode chareacters. |
| 456 | illegal_chars_u = [ |
| 457 | (0x00, 0x08), (0x0B, 0x0C), (0x0E, 0x1F), (0x7F, 0x84), |
| 458 | (0x86, 0x9F), (0xFDD0, 0xFDDF), (0xFFFE, 0xFFFF)] |
| 459 | |
| 460 | # For wide builds, we have more. |
| 461 | if sys.maxunicode >= 0x10000: |
| 462 | illegal_chars_u.extend( |
| 463 | [(0x1FFFE, 0x1FFFF), (0x2FFFE, 0x2FFFF), (0x3FFFE, 0x3FFFF), |
| 464 | (0x4FFFE, 0x4FFFF), (0x5FFFE, 0x5FFFF), (0x6FFFE, 0x6FFFF), |
| 465 | (0x7FFFE, 0x7FFFF), (0x8FFFE, 0x8FFFF), (0x9FFFE, 0x9FFFF), |
| 466 | (0xAFFFE, 0xAFFFF), (0xBFFFE, 0xBFFFF), (0xCFFFE, 0xCFFFF), |
| 467 | (0xDFFFE, 0xDFFFF), (0xEFFFE, 0xEFFFF), (0xFFFFE, 0xFFFFF), |
| 468 | (0x10FFFE, 0x10FFFF)]) |
| 469 | |
| 470 | # Build up an array of range expressions. |
| 471 | illegal_ranges = [ |
| 472 | "%s-%s" % (unichr(low), unichr(high)) |
| 473 | for (low, high) in illegal_chars_u] |
| 474 | |
| 475 | # Compile the regex |
| 476 | return re.compile(u'[%s]' % u''.join(illegal_ranges)) |
| 477 | |
| 478 | @staticmethod |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 479 | def _quote_attribute(text): |
| 480 | """Returns the given text in a manner safe for usage in an XML attribute. |
| 481 | |
| 482 | @param text the text that should appear within an XML attribute. |
| 483 | @return the attribute-escaped version of the input text. |
| 484 | """ |
| 485 | return xml.sax.saxutils.quoteattr(text) |
| 486 | |
Todd Fiala | 8effde4 | 2015-09-18 16:00:52 +0000 | [diff] [blame] | 487 | def _replace_invalid_xml(self, str_or_unicode): |
Todd Fiala | 33896a9 | 2015-09-18 21:01:13 +0000 | [diff] [blame] | 488 | """Replaces invalid XML characters with a '?'. |
| 489 | |
| 490 | @param str_or_unicode a string to replace invalid XML |
| 491 | characters within. Can be unicode or not. If not unicode, |
| 492 | assumes it is a byte string in utf-8 encoding. |
| 493 | |
| 494 | @returns a utf-8-encoded byte string with invalid |
| 495 | XML replaced with '?'. |
| 496 | """ |
Todd Fiala | 8effde4 | 2015-09-18 16:00:52 +0000 | [diff] [blame] | 497 | # Get the content into unicode |
| 498 | if isinstance(str_or_unicode, str): |
| 499 | unicode_content = str_or_unicode.decode('utf-8') |
| 500 | else: |
| 501 | unicode_content = str_or_unicode |
| 502 | return self.invalid_xml_re.sub(u'?', unicode_content).encode('utf-8') |
| 503 | |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 504 | @classmethod |
| 505 | def arg_parser(cls): |
| 506 | """@return arg parser used to parse formatter-specific options.""" |
| 507 | parser = super(XunitFormatter, cls).arg_parser() |
| 508 | |
| 509 | # These are valid choices for results mapping. |
| 510 | results_mapping_choices = [ |
| 511 | XunitFormatter.RM_IGNORE, |
| 512 | XunitFormatter.RM_SUCCESS, |
| 513 | XunitFormatter.RM_FAILURE, |
| 514 | XunitFormatter.RM_PASSTHRU] |
| 515 | parser.add_argument( |
Todd Fiala | 33896a9 | 2015-09-18 21:01:13 +0000 | [diff] [blame] | 516 | "--assert-on-unknown-events", |
| 517 | action="store_true", |
| 518 | help=('cause unknown test events to generate ' |
| 519 | 'a python assert. Default is to ignore.')) |
| 520 | parser.add_argument( |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 521 | "--xpass", action="store", choices=results_mapping_choices, |
| 522 | default=XunitFormatter.RM_FAILURE, |
| 523 | help=('specify mapping from unexpected success to jUnit/xUnit ' |
| 524 | 'result type')) |
| 525 | parser.add_argument( |
| 526 | "--xfail", action="store", choices=results_mapping_choices, |
| 527 | default=XunitFormatter.RM_IGNORE, |
| 528 | help=('specify mapping from expected failure to jUnit/xUnit ' |
| 529 | 'result type')) |
| 530 | return parser |
| 531 | |
| 532 | def __init__(self, out_file, options): |
| 533 | """Initializes the XunitFormatter instance. |
| 534 | @param out_file file-like object where formatted output is written. |
| 535 | @param options_dict specifies a dictionary of options for the |
| 536 | formatter. |
| 537 | """ |
| 538 | # Initialize the parent |
| 539 | super(XunitFormatter, self).__init__(out_file, options) |
| 540 | self.text_encoding = "UTF-8" |
Todd Fiala | 8effde4 | 2015-09-18 16:00:52 +0000 | [diff] [blame] | 541 | self.invalid_xml_re = XunitFormatter._build_illegal_xml_regex() |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 542 | |
| 543 | self.total_test_count = 0 |
| 544 | |
| 545 | self.elements = { |
| 546 | "successes": [], |
| 547 | "errors": [], |
| 548 | "failures": [], |
| 549 | "skips": [], |
| 550 | "unexpected_successes": [], |
| 551 | "expected_failures": [], |
| 552 | "all": [] |
| 553 | } |
| 554 | |
| 555 | self.status_handlers = { |
| 556 | "success": self._handle_success, |
| 557 | "failure": self._handle_failure, |
| 558 | "error": self._handle_error, |
| 559 | "skip": self._handle_skip, |
| 560 | "expected_failure": self._handle_expected_failure, |
| 561 | "unexpected_success": self._handle_unexpected_success |
| 562 | } |
| 563 | |
Todd Fiala | e83f140 | 2015-09-18 22:45:31 +0000 | [diff] [blame] | 564 | def handle_event(self, test_event): |
| 565 | super(XunitFormatter, self).handle_event(test_event) |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 566 | |
| 567 | event_type = test_event["event"] |
| 568 | if event_type is None: |
| 569 | return |
| 570 | |
Todd Fiala | e83f140 | 2015-09-18 22:45:31 +0000 | [diff] [blame] | 571 | if event_type == "terminate": |
| 572 | self._finish_output() |
| 573 | elif event_type == "test_start": |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 574 | self.track_start_time( |
| 575 | test_event["test_class"], |
| 576 | test_event["test_name"], |
| 577 | test_event["event_time"]) |
| 578 | elif event_type == "test_result": |
| 579 | self._process_test_result(test_event) |
| 580 | else: |
Todd Fiala | 33896a9 | 2015-09-18 21:01:13 +0000 | [diff] [blame] | 581 | # This is an unknown event. |
| 582 | if self.options.assert_on_unknown_events: |
| 583 | raise Exception("unknown event type {} from {}\n".format( |
| 584 | event_type, test_event)) |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 585 | |
| 586 | def _handle_success(self, test_event): |
| 587 | """Handles a test success. |
| 588 | @param test_event the test event to handle. |
| 589 | """ |
| 590 | result = self._common_add_testcase_entry(test_event) |
| 591 | with self.lock: |
| 592 | self.elements["successes"].append(result) |
| 593 | |
| 594 | def _handle_failure(self, test_event): |
| 595 | """Handles a test failure. |
| 596 | @param test_event the test event to handle. |
| 597 | """ |
Todd Fiala | 8effde4 | 2015-09-18 16:00:52 +0000 | [diff] [blame] | 598 | message = self._replace_invalid_xml(test_event["issue_message"]) |
| 599 | backtrace = self._replace_invalid_xml( |
| 600 | "".join(test_event.get("issue_backtrace", []))) |
Todd Fiala | e7e911f | 2015-09-18 07:08:09 +0000 | [diff] [blame] | 601 | |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 602 | result = self._common_add_testcase_entry( |
| 603 | test_event, |
Todd Fiala | 8effde4 | 2015-09-18 16:00:52 +0000 | [diff] [blame] | 604 | inner_content=( |
| 605 | '<failure type={} message={}><![CDATA[{}]]></failure>'.format( |
| 606 | XunitFormatter._quote_attribute(test_event["issue_class"]), |
| 607 | XunitFormatter._quote_attribute(message), |
| 608 | backtrace) |
Todd Fiala | e7e911f | 2015-09-18 07:08:09 +0000 | [diff] [blame] | 609 | )) |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 610 | with self.lock: |
| 611 | self.elements["failures"].append(result) |
| 612 | |
| 613 | def _handle_error(self, test_event): |
| 614 | """Handles a test error. |
| 615 | @param test_event the test event to handle. |
| 616 | """ |
Todd Fiala | 8effde4 | 2015-09-18 16:00:52 +0000 | [diff] [blame] | 617 | message = self._replace_invalid_xml(test_event["issue_message"]) |
| 618 | backtrace = self._replace_invalid_xml( |
| 619 | "".join(test_event.get("issue_backtrace", []))) |
Todd Fiala | e7e911f | 2015-09-18 07:08:09 +0000 | [diff] [blame] | 620 | |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 621 | result = self._common_add_testcase_entry( |
| 622 | test_event, |
Todd Fiala | 8effde4 | 2015-09-18 16:00:52 +0000 | [diff] [blame] | 623 | inner_content=( |
| 624 | '<error type={} message={}><![CDATA[{}]]></error>'.format( |
| 625 | XunitFormatter._quote_attribute(test_event["issue_class"]), |
| 626 | XunitFormatter._quote_attribute(message), |
| 627 | backtrace) |
Todd Fiala | e7e911f | 2015-09-18 07:08:09 +0000 | [diff] [blame] | 628 | )) |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 629 | with self.lock: |
| 630 | self.elements["errors"].append(result) |
| 631 | |
| 632 | def _handle_skip(self, test_event): |
| 633 | """Handles a skipped test. |
| 634 | @param test_event the test event to handle. |
| 635 | """ |
Todd Fiala | 8effde4 | 2015-09-18 16:00:52 +0000 | [diff] [blame] | 636 | reason = self._replace_invalid_xml(test_event.get("skip_reason", "")) |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 637 | result = self._common_add_testcase_entry( |
| 638 | test_event, |
| 639 | inner_content='<skipped message={} />'.format( |
Todd Fiala | 8effde4 | 2015-09-18 16:00:52 +0000 | [diff] [blame] | 640 | XunitFormatter._quote_attribute(reason))) |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 641 | with self.lock: |
| 642 | self.elements["skips"].append(result) |
| 643 | |
| 644 | def _handle_expected_failure(self, test_event): |
| 645 | """Handles a test that failed as expected. |
| 646 | @param test_event the test event to handle. |
| 647 | """ |
| 648 | if self.options.xfail == XunitFormatter.RM_PASSTHRU: |
| 649 | # This is not a natively-supported junit/xunit |
| 650 | # testcase mode, so it might fail a validating |
| 651 | # test results viewer. |
| 652 | if "bugnumber" in test_event: |
| 653 | bug_id_attribute = 'bug-id={} '.format( |
| 654 | XunitFormatter._quote_attribute(test_event["bugnumber"])) |
| 655 | else: |
| 656 | bug_id_attribute = '' |
| 657 | |
| 658 | result = self._common_add_testcase_entry( |
| 659 | test_event, |
| 660 | inner_content=( |
| 661 | '<expected-failure {}type={} message={} />'.format( |
| 662 | bug_id_attribute, |
| 663 | XunitFormatter._quote_attribute( |
| 664 | test_event["issue_class"]), |
| 665 | XunitFormatter._quote_attribute( |
| 666 | test_event["issue_message"])) |
| 667 | )) |
| 668 | with self.lock: |
| 669 | self.elements["expected_failures"].append(result) |
| 670 | elif self.options.xfail == XunitFormatter.RM_SUCCESS: |
| 671 | result = self._common_add_testcase_entry(test_event) |
| 672 | with self.lock: |
| 673 | self.elements["successes"].append(result) |
| 674 | elif self.options.xfail == XunitFormatter.RM_FAILURE: |
| 675 | result = self._common_add_testcase_entry( |
| 676 | test_event, |
| 677 | inner_content='<failure type={} message={} />'.format( |
| 678 | XunitFormatter._quote_attribute(test_event["issue_class"]), |
| 679 | XunitFormatter._quote_attribute( |
| 680 | test_event["issue_message"]))) |
| 681 | with self.lock: |
| 682 | self.elements["failures"].append(result) |
| 683 | elif self.options.xfail == XunitFormatter.RM_IGNORE: |
| 684 | pass |
| 685 | else: |
| 686 | raise Exception( |
| 687 | "unknown xfail option: {}".format(self.options.xfail)) |
| 688 | |
| 689 | def _handle_unexpected_success(self, test_event): |
| 690 | """Handles a test that passed but was expected to fail. |
| 691 | @param test_event the test event to handle. |
| 692 | """ |
| 693 | if self.options.xpass == XunitFormatter.RM_PASSTHRU: |
| 694 | # This is not a natively-supported junit/xunit |
| 695 | # testcase mode, so it might fail a validating |
| 696 | # test results viewer. |
| 697 | result = self._common_add_testcase_entry( |
| 698 | test_event, |
| 699 | inner_content=("<unexpected-success />")) |
| 700 | with self.lock: |
| 701 | self.elements["unexpected_successes"].append(result) |
| 702 | elif self.options.xpass == XunitFormatter.RM_SUCCESS: |
| 703 | # Treat the xpass as a success. |
| 704 | result = self._common_add_testcase_entry(test_event) |
| 705 | with self.lock: |
| 706 | self.elements["successes"].append(result) |
| 707 | elif self.options.xpass == XunitFormatter.RM_FAILURE: |
| 708 | # Treat the xpass as a failure. |
| 709 | if "bugnumber" in test_event: |
| 710 | message = "unexpected success (bug_id:{})".format( |
| 711 | test_event["bugnumber"]) |
| 712 | else: |
| 713 | message = "unexpected success (bug_id:none)" |
| 714 | result = self._common_add_testcase_entry( |
| 715 | test_event, |
| 716 | inner_content='<failure type={} message={} />'.format( |
| 717 | XunitFormatter._quote_attribute("unexpected_success"), |
| 718 | XunitFormatter._quote_attribute(message))) |
| 719 | with self.lock: |
| 720 | self.elements["failures"].append(result) |
| 721 | elif self.options.xpass == XunitFormatter.RM_IGNORE: |
| 722 | # Ignore the xpass result as far as xUnit reporting goes. |
| 723 | pass |
| 724 | else: |
| 725 | raise Exception("unknown xpass option: {}".format( |
| 726 | self.options.xpass)) |
| 727 | |
| 728 | def _process_test_result(self, test_event): |
| 729 | """Processes the test_event known to be a test result. |
| 730 | |
| 731 | This categorizes the event appropriately and stores the data needed |
| 732 | to generate the final xUnit report. This method skips events that |
| 733 | cannot be represented in xUnit output. |
| 734 | """ |
| 735 | if "status" not in test_event: |
| 736 | raise Exception("test event dictionary missing 'status' key") |
| 737 | |
| 738 | status = test_event["status"] |
| 739 | if status not in self.status_handlers: |
| 740 | raise Exception("test event status '{}' unsupported".format( |
| 741 | status)) |
| 742 | |
| 743 | # Call the status handler for the test result. |
| 744 | self.status_handlers[status](test_event) |
| 745 | |
| 746 | def _common_add_testcase_entry(self, test_event, inner_content=None): |
| 747 | """Registers a testcase result, and returns the text created. |
| 748 | |
| 749 | The caller is expected to manage failure/skip/success counts |
| 750 | in some kind of appropriate way. This call simply constructs |
| 751 | the XML and appends the returned result to the self.all_results |
| 752 | list. |
| 753 | |
| 754 | @param test_event the test event dictionary. |
| 755 | |
| 756 | @param inner_content if specified, gets included in the <testcase> |
| 757 | inner section, at the point before stdout and stderr would be |
| 758 | included. This is where a <failure/>, <skipped/>, <error/>, etc. |
| 759 | could go. |
| 760 | |
| 761 | @return the text of the xml testcase element. |
| 762 | """ |
| 763 | |
| 764 | # Get elapsed time. |
| 765 | test_class = test_event["test_class"] |
| 766 | test_name = test_event["test_name"] |
| 767 | event_time = test_event["event_time"] |
| 768 | time_taken = self.elapsed_time_for_test( |
| 769 | test_class, test_name, event_time) |
| 770 | |
| 771 | # Plumb in stdout/stderr once we shift over to only test results. |
| 772 | test_stdout = '' |
| 773 | test_stderr = '' |
| 774 | |
| 775 | # Formulate the output xml. |
| 776 | if not inner_content: |
| 777 | inner_content = "" |
| 778 | result = ( |
| 779 | '<testcase classname="{}" name="{}" time="{:.3f}">' |
| 780 | '{}{}{}</testcase>'.format( |
| 781 | test_class, |
| 782 | test_name, |
| 783 | time_taken, |
| 784 | inner_content, |
| 785 | test_stdout, |
| 786 | test_stderr)) |
| 787 | |
| 788 | # Save the result, update total test count. |
| 789 | with self.lock: |
| 790 | self.total_test_count += 1 |
| 791 | self.elements["all"].append(result) |
| 792 | |
| 793 | return result |
| 794 | |
Todd Fiala | e83f140 | 2015-09-18 22:45:31 +0000 | [diff] [blame] | 795 | def _finish_output_no_lock(self): |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 796 | """Flushes out the report of test executions to form valid xml output. |
| 797 | |
| 798 | xUnit output is in XML. The reporting system cannot complete the |
| 799 | formatting of the output without knowing when there is no more input. |
| 800 | This call addresses notifcation of the completed test run and thus is |
| 801 | when we can finish off the report output. |
| 802 | """ |
| 803 | |
| 804 | # Figure out the counts line for the testsuite. If we have |
| 805 | # been counting either unexpected successes or expected |
| 806 | # failures, we'll output those in the counts, at the risk of |
| 807 | # being invalidated by a validating test results viewer. |
| 808 | # These aren't counted by default so they won't show up unless |
| 809 | # the user specified a formatter option to include them. |
| 810 | xfail_count = len(self.elements["expected_failures"]) |
| 811 | xpass_count = len(self.elements["unexpected_successes"]) |
| 812 | if xfail_count > 0 or xpass_count > 0: |
| 813 | extra_testsuite_attributes = ( |
| 814 | ' expected-failures="{}"' |
| 815 | ' unexpected-successes="{}"'.format(xfail_count, xpass_count)) |
| 816 | else: |
| 817 | extra_testsuite_attributes = "" |
| 818 | |
| 819 | # Output the header. |
| 820 | self.out_file.write( |
| 821 | '<?xml version="1.0" encoding="{}"?>\n' |
Todd Fiala | 038bf83 | 2015-09-18 01:43:08 +0000 | [diff] [blame] | 822 | '<testsuites>' |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 823 | '<testsuite name="{}" tests="{}" errors="{}" failures="{}" ' |
| 824 | 'skip="{}"{}>\n'.format( |
| 825 | self.text_encoding, |
| 826 | "LLDB test suite", |
| 827 | self.total_test_count, |
| 828 | len(self.elements["errors"]), |
| 829 | len(self.elements["failures"]), |
| 830 | len(self.elements["skips"]), |
| 831 | extra_testsuite_attributes)) |
| 832 | |
| 833 | # Output each of the test result entries. |
| 834 | for result in self.elements["all"]: |
| 835 | self.out_file.write(result + '\n') |
| 836 | |
| 837 | # Close off the test suite. |
Todd Fiala | 038bf83 | 2015-09-18 01:43:08 +0000 | [diff] [blame] | 838 | self.out_file.write('</testsuite></testsuites>\n') |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 839 | |
Todd Fiala | e83f140 | 2015-09-18 22:45:31 +0000 | [diff] [blame] | 840 | def _finish_output(self): |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 841 | with self.lock: |
Todd Fiala | e83f140 | 2015-09-18 22:45:31 +0000 | [diff] [blame] | 842 | self._finish_output_no_lock() |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 843 | |
| 844 | |
| 845 | class RawPickledFormatter(ResultsFormatter): |
| 846 | """Formats events as a pickled stream. |
| 847 | |
| 848 | The parallel test runner has inferiors pickle their results and send them |
| 849 | over a socket back to the parallel test. The parallel test runner then |
| 850 | aggregates them into the final results formatter (e.g. xUnit). |
| 851 | """ |
| 852 | |
| 853 | @classmethod |
| 854 | def arg_parser(cls): |
| 855 | """@return arg parser used to parse formatter-specific options.""" |
| 856 | parser = super(RawPickledFormatter, cls).arg_parser() |
| 857 | return parser |
| 858 | |
| 859 | def __init__(self, out_file, options): |
| 860 | super(RawPickledFormatter, self).__init__(out_file, options) |
| 861 | self.pid = os.getpid() |
| 862 | |
Todd Fiala | e83f140 | 2015-09-18 22:45:31 +0000 | [diff] [blame] | 863 | def handle_event(self, test_event): |
| 864 | super(RawPickledFormatter, self).handle_event(test_event) |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 865 | |
Todd Fiala | e83f140 | 2015-09-18 22:45:31 +0000 | [diff] [blame] | 866 | # Convert initialize/terminate events into job_begin/job_end events. |
| 867 | event_type = test_event["event"] |
| 868 | if event_type is None: |
| 869 | return |
| 870 | |
| 871 | if event_type == "initialize": |
| 872 | test_event["event"] = "job_begin" |
| 873 | elif event_type == "terminate": |
| 874 | test_event["event"] = "job_end" |
| 875 | |
| 876 | # Tack on the pid. |
| 877 | test_event["pid"] = self.pid |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 878 | |
Todd Fiala | 68615ce | 2015-09-15 21:38:04 +0000 | [diff] [blame] | 879 | # Send it as {serialized_length_of_serialized_bytes}#{serialized_bytes} |
| 880 | pickled_message = cPickle.dumps(test_event) |
| 881 | self.out_file.send( |
| 882 | "{}#{}".format(len(pickled_message), pickled_message)) |
| 883 | |
Todd Fiala | 33896a9 | 2015-09-18 21:01:13 +0000 | [diff] [blame] | 884 | |
| 885 | class DumpFormatter(ResultsFormatter): |
| 886 | """Formats events to the file as their raw python dictionary format.""" |
| 887 | |
Todd Fiala | e83f140 | 2015-09-18 22:45:31 +0000 | [diff] [blame] | 888 | def handle_event(self, test_event): |
| 889 | super(DumpFormatter, self).handle_event(test_event) |
Todd Fiala | 33896a9 | 2015-09-18 21:01:13 +0000 | [diff] [blame] | 890 | self.out_file.write("\n" + pprint.pformat(test_event) + "\n") |