blob: 00b7d0bb12e85d6f33c4a6f3fbe53c269cf681c3 [file] [log] [blame]
Brad Bishopc342db32019-05-15 21:57:59 -04001#
Brad Bishop6e60e8b2018-02-01 10:27:11 -05002# Copyright (C) 2016 Intel Corporation
Brad Bishopc342db32019-05-15 21:57:59 -04003#
4# SPDX-License-Identifier: MIT
5#
Brad Bishop6e60e8b2018-02-01 10:27:11 -05006
7import os
8import time
9import unittest
10import logging
Brad Bishopd7bf8c12018-02-25 22:55:05 -050011import re
Brad Bishopf86d0552018-12-04 14:18:15 -080012import json
Brad Bishopc342db32019-05-15 21:57:59 -040013import sys
Brad Bishop6e60e8b2018-02-01 10:27:11 -050014
Brad Bishopf86d0552018-12-04 14:18:15 -080015from unittest import TextTestResult as _TestResult
16from unittest import TextTestRunner as _TestRunner
Brad Bishop6e60e8b2018-02-01 10:27:11 -050017
18class OEStreamLogger(object):
19 def __init__(self, logger):
20 self.logger = logger
21 self.buffer = ""
22
23 def write(self, msg):
24 if len(msg) > 1 and msg[0] != '\n':
Brad Bishopd7bf8c12018-02-25 22:55:05 -050025 if '...' in msg:
26 self.buffer += msg
27 elif self.buffer:
28 self.buffer += msg
29 self.logger.log(logging.INFO, self.buffer)
30 self.buffer = ""
31 else:
32 self.logger.log(logging.INFO, msg)
Brad Bishop6e60e8b2018-02-01 10:27:11 -050033
34 def flush(self):
35 for handler in self.logger.handlers:
36 handler.flush()
37
38class OETestResult(_TestResult):
39 def __init__(self, tc, *args, **kwargs):
40 super(OETestResult, self).__init__(*args, **kwargs)
41
Brad Bishopf86d0552018-12-04 14:18:15 -080042 self.successes = []
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080043 self.starttime = {}
44 self.endtime = {}
45 self.progressinfo = {}
Brad Bishop79641f22019-09-10 07:20:22 -040046 self.extraresults = {}
Brad Bishopf86d0552018-12-04 14:18:15 -080047
48 # Inject into tc so that TestDepends decorator can see results
49 tc.results = self
50
Brad Bishop6e60e8b2018-02-01 10:27:11 -050051 self.tc = tc
52
Brad Bishopc342db32019-05-15 21:57:59 -040053 # stdout and stderr for each test case
54 self.logged_output = {}
55
Brad Bishopd7bf8c12018-02-25 22:55:05 -050056 def startTest(self, test):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080057 # May have been set by concurrencytest
58 if test.id() not in self.starttime:
59 self.starttime[test.id()] = time.time()
Brad Bishopd7bf8c12018-02-25 22:55:05 -050060 super(OETestResult, self).startTest(test)
61
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080062 def stopTest(self, test):
63 self.endtime[test.id()] = time.time()
Brad Bishopc342db32019-05-15 21:57:59 -040064 if self.buffer:
65 self.logged_output[test.id()] = (
66 sys.stdout.getvalue(), sys.stderr.getvalue())
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080067 super(OETestResult, self).stopTest(test)
68 if test.id() in self.progressinfo:
69 self.tc.logger.info(self.progressinfo[test.id()])
70
71 # Print the errors/failures early to aid/speed debugging, its a pain
72 # to wait until selftest finishes to see them.
73 for t in ['failures', 'errors', 'skipped', 'expectedFailures']:
74 for (scase, msg) in getattr(self, t):
75 if test.id() == scase.id():
76 self.tc.logger.info(str(msg))
77 break
78
Brad Bishopd7bf8c12018-02-25 22:55:05 -050079 def logSummary(self, component, context_msg=''):
80 elapsed_time = self.tc._run_end_time - self.tc._run_start_time
81 self.tc.logger.info("SUMMARY:")
82 self.tc.logger.info("%s (%s) - Ran %d test%s in %.3fs" % (component,
83 context_msg, self.testsRun, self.testsRun != 1 and "s" or "",
84 elapsed_time))
85
86 if self.wasSuccessful():
87 msg = "%s - OK - All required tests passed" % component
88 else:
89 msg = "%s - FAIL - Required tests failed" % component
Brad Bishopf86d0552018-12-04 14:18:15 -080090 msg += " (successes=%d, skipped=%d, failures=%d, errors=%d)" % (len(self.successes), len(self.skipped), len(self.failures), len(self.errors))
Brad Bishopd7bf8c12018-02-25 22:55:05 -050091 self.tc.logger.info(msg)
92
Brad Bishopf86d0552018-12-04 14:18:15 -080093 def _getTestResultDetails(self, case):
94 result_types = {'failures': 'FAILED', 'errors': 'ERROR', 'skipped': 'SKIPPED',
Brad Bishopc342db32019-05-15 21:57:59 -040095 'expectedFailures': 'EXPECTEDFAIL', 'successes': 'PASSED',
96 'unexpectedSuccesses' : 'PASSED'}
Brad Bishopd7bf8c12018-02-25 22:55:05 -050097
Brad Bishopf86d0552018-12-04 14:18:15 -080098 for rtype in result_types:
99 found = False
Brad Bishopc342db32019-05-15 21:57:59 -0400100 for resultclass in getattr(self, rtype):
101 # unexpectedSuccesses are just lists, not lists of tuples
102 if isinstance(resultclass, tuple):
103 scase, msg = resultclass
104 else:
105 scase, msg = resultclass, None
Brad Bishopf86d0552018-12-04 14:18:15 -0800106 if case.id() == scase.id():
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500107 found = True
108 break
Brad Bishopf86d0552018-12-04 14:18:15 -0800109 scase_str = str(scase.id())
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500110
Brad Bishopf86d0552018-12-04 14:18:15 -0800111 # When fails at module or class level the class name is passed as string
112 # so figure out to see if match
Brad Bishopc342db32019-05-15 21:57:59 -0400113 m = re.search(r"^setUpModule \((?P<module_name>.*)\).*$", scase_str)
Brad Bishopf86d0552018-12-04 14:18:15 -0800114 if m:
115 if case.__class__.__module__ == m.group('module_name'):
116 found = True
117 break
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500118
Brad Bishopc342db32019-05-15 21:57:59 -0400119 m = re.search(r"^setUpClass \((?P<class_name>.*)\).*$", scase_str)
Brad Bishopf86d0552018-12-04 14:18:15 -0800120 if m:
121 class_name = "%s.%s" % (case.__class__.__module__,
122 case.__class__.__name__)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500123
Brad Bishopf86d0552018-12-04 14:18:15 -0800124 if class_name == m.group('class_name'):
125 found = True
126 break
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500127
Brad Bishopf86d0552018-12-04 14:18:15 -0800128 if found:
129 return result_types[rtype], msg
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500130
Brad Bishopf86d0552018-12-04 14:18:15 -0800131 return 'UNKNOWN', None
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500132
Brad Bishop79641f22019-09-10 07:20:22 -0400133 def extractExtraResults(self, test, details = None):
134 extraresults = None
135 if details is not None and "extraresults" in details:
136 extraresults = details.get("extraresults", {})
137 elif hasattr(test, "extraresults"):
138 extraresults = test.extraresults
139
140 if extraresults is not None:
141 for k, v in extraresults.items():
142 # handle updating already existing entries (e.g. ptestresults.sections)
143 if k in self.extraresults:
144 self.extraresults[k].update(v)
145 else:
146 self.extraresults[k] = v
147
148 def addError(self, test, *args, details = None):
149 self.extractExtraResults(test, details = details)
150 return super(OETestResult, self).addError(test, *args)
151
152 def addFailure(self, test, *args, details = None):
153 self.extractExtraResults(test, details = details)
154 return super(OETestResult, self).addFailure(test, *args)
155
156 def addSuccess(self, test, details = None):
Brad Bishopf86d0552018-12-04 14:18:15 -0800157 #Added so we can keep track of successes too
158 self.successes.append((test, None))
Brad Bishop79641f22019-09-10 07:20:22 -0400159 self.extractExtraResults(test, details = details)
160 return super(OETestResult, self).addSuccess(test)
161
162 def addExpectedFailure(self, test, *args, details = None):
163 self.extractExtraResults(test, details = details)
164 return super(OETestResult, self).addExpectedFailure(test, *args)
165
166 def addUnexpectedSuccess(self, test, details = None):
167 self.extractExtraResults(test, details = details)
168 return super(OETestResult, self).addUnexpectedSuccess(test)
Brad Bishopf86d0552018-12-04 14:18:15 -0800169
Brad Bishopc342db32019-05-15 21:57:59 -0400170 def logDetails(self, json_file_dir=None, configuration=None, result_id=None,
171 dump_streams=False):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500172 self.tc.logger.info("RESULTS:")
Brad Bishopf86d0552018-12-04 14:18:15 -0800173
Brad Bishop79641f22019-09-10 07:20:22 -0400174 result = self.extraresults
Brad Bishopf86d0552018-12-04 14:18:15 -0800175 logs = {}
176 if hasattr(self.tc, "extraresults"):
Brad Bishop79641f22019-09-10 07:20:22 -0400177 result.update(self.tc.extraresults)
Brad Bishopf86d0552018-12-04 14:18:15 -0800178
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500179 for case_name in self.tc._registry['cases']:
180 case = self.tc._registry['cases'][case_name]
181
Brad Bishopf86d0552018-12-04 14:18:15 -0800182 (status, log) = self._getTestResultDetails(case)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500183
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800184 t = ""
Andrew Geissler1e34c2d2020-05-29 16:02:59 -0500185 duration = 0
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800186 if case.id() in self.starttime and case.id() in self.endtime:
Andrew Geissler1e34c2d2020-05-29 16:02:59 -0500187 duration = self.endtime[case.id()] - self.starttime[case.id()]
188 t = " (" + "{0:.2f}".format(duration) + "s)"
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800189
Brad Bishopf86d0552018-12-04 14:18:15 -0800190 if status not in logs:
191 logs[status] = []
Brad Bishopc342db32019-05-15 21:57:59 -0400192 logs[status].append("RESULTS - %s: %s%s" % (case.id(), status, t))
193 report = {'status': status}
Brad Bishopf86d0552018-12-04 14:18:15 -0800194 if log:
Brad Bishopc342db32019-05-15 21:57:59 -0400195 report['log'] = log
Andrew Geissler1e34c2d2020-05-29 16:02:59 -0500196 if duration:
197 report['duration'] = duration
Brad Bishopc342db32019-05-15 21:57:59 -0400198 if dump_streams and case.id() in self.logged_output:
199 (stdout, stderr) = self.logged_output[case.id()]
200 report['stdout'] = stdout
201 report['stderr'] = stderr
202 result[case.id()] = report
Brad Bishopf86d0552018-12-04 14:18:15 -0800203
204 for i in ['PASSED', 'SKIPPED', 'EXPECTEDFAIL', 'ERROR', 'FAILED', 'UNKNOWN']:
205 if i not in logs:
206 continue
207 for l in logs[i]:
208 self.tc.logger.info(l)
209
210 if json_file_dir:
211 tresultjsonhelper = OETestResultJSONHelper()
212 tresultjsonhelper.dump_testresult_file(json_file_dir, configuration, result_id, result)
213
214 def wasSuccessful(self):
215 # Override as we unexpected successes aren't failures for us
216 return (len(self.failures) == len(self.errors) == 0)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500217
218class OEListTestsResult(object):
219 def wasSuccessful(self):
220 return True
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500221
222class OETestRunner(_TestRunner):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500223 streamLoggerClass = OEStreamLogger
224
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500225 def __init__(self, tc, *args, **kwargs):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500226 kwargs['stream'] = self.streamLoggerClass(tc.logger)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500227 super(OETestRunner, self).__init__(*args, **kwargs)
228 self.tc = tc
229 self.resultclass = OETestResult
230
Brad Bishopf86d0552018-12-04 14:18:15 -0800231 def _makeResult(self):
232 return self.resultclass(self.tc, self.stream, self.descriptions,
233 self.verbosity)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500234
235 def _walk_suite(self, suite, func):
236 for obj in suite:
237 if isinstance(obj, unittest.suite.TestSuite):
238 if len(obj._tests):
239 self._walk_suite(obj, func)
240 elif isinstance(obj, unittest.case.TestCase):
241 func(self.tc.logger, obj)
242 self._walked_cases = self._walked_cases + 1
243
244 def _list_tests_name(self, suite):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500245 self._walked_cases = 0
246
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500247 def _list_cases(logger, case):
Brad Bishop79641f22019-09-10 07:20:22 -0400248 oetags = []
249 if hasattr(case, '__oeqa_testtags'):
250 oetags = getattr(case, '__oeqa_testtags')
251 if oetags:
252 logger.info("%s (%s)" % (case.id(), ",".join(oetags)))
253 else:
254 logger.info("%s" % (case.id()))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500255
256 self.tc.logger.info("Listing all available tests:")
257 self._walked_cases = 0
Brad Bishop79641f22019-09-10 07:20:22 -0400258 self.tc.logger.info("test (tags)")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500259 self.tc.logger.info("-" * 80)
260 self._walk_suite(suite, _list_cases)
261 self.tc.logger.info("-" * 80)
262 self.tc.logger.info("Total found:\t%s" % self._walked_cases)
263
264 def _list_tests_class(self, suite):
265 self._walked_cases = 0
266
267 curr = {}
268 def _list_classes(logger, case):
269 if not 'module' in curr or curr['module'] != case.__module__:
270 curr['module'] = case.__module__
271 logger.info(curr['module'])
272
273 if not 'class' in curr or curr['class'] != \
274 case.__class__.__name__:
275 curr['class'] = case.__class__.__name__
276 logger.info(" -- %s" % curr['class'])
277
278 logger.info(" -- -- %s" % case._testMethodName)
279
280 self.tc.logger.info("Listing all available test classes:")
281 self._walk_suite(suite, _list_classes)
282
283 def _list_tests_module(self, suite):
284 self._walked_cases = 0
285
286 listed = []
287 def _list_modules(logger, case):
288 if not case.__module__ in listed:
289 if case.__module__.startswith('_'):
290 logger.info("%s (hidden)" % case.__module__)
291 else:
292 logger.info(case.__module__)
293 listed.append(case.__module__)
294
295 self.tc.logger.info("Listing all available test modules:")
296 self._walk_suite(suite, _list_modules)
297
298 def list_tests(self, suite, display_type):
299 if display_type == 'name':
300 self._list_tests_name(suite)
301 elif display_type == 'class':
302 self._list_tests_class(suite)
303 elif display_type == 'module':
304 self._list_tests_module(suite)
305
306 return OEListTestsResult()
Brad Bishopf86d0552018-12-04 14:18:15 -0800307
308class OETestResultJSONHelper(object):
309
310 testresult_filename = 'testresults.json'
311
312 def _get_existing_testresults_if_available(self, write_dir):
313 testresults = {}
314 file = os.path.join(write_dir, self.testresult_filename)
315 if os.path.exists(file):
316 with open(file, "r") as f:
317 testresults = json.load(f)
318 return testresults
319
320 def _write_file(self, write_dir, file_name, file_content):
321 file_path = os.path.join(write_dir, file_name)
322 with open(file_path, 'w') as the_file:
323 the_file.write(file_content)
324
325 def dump_testresult_file(self, write_dir, configuration, result_id, test_result):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500326 try:
327 import bb
328 has_bb = True
329 bb.utils.mkdirhier(write_dir)
330 lf = bb.utils.lockfile(os.path.join(write_dir, 'jsontestresult.lock'))
331 except ImportError:
332 has_bb = False
333 os.makedirs(write_dir, exist_ok=True)
Brad Bishopf86d0552018-12-04 14:18:15 -0800334 test_results = self._get_existing_testresults_if_available(write_dir)
335 test_results[result_id] = {'configuration': configuration, 'result': test_result}
336 json_testresults = json.dumps(test_results, sort_keys=True, indent=4)
337 self._write_file(write_dir, self.testresult_filename, json_testresults)
Andrew Geissler82c905d2020-04-13 13:39:40 -0500338 if has_bb:
339 bb.utils.unlockfile(lf)