-
Notifications
You must be signed in to change notification settings - Fork 37
/
test_runner.py
412 lines (339 loc) · 12.5 KB
/
test_runner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#******************************************************************************
# * Copyright (c) 2019, XtremeDV. All rights reserved.
# *
# * Licensed under the Apache License, Version 2.0 (the "License");
# * you may not use this file except in compliance with the License.
# * You may obtain a copy of the License at
# *
# * http://www.apache.org/licenses/LICENSE-2.0
# *
# * Unless required by applicable law or agreed to in writing, software
# * distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
# *
# * Author: Jude Zhang, Email: zhajio.1988@gmail.com
# *******************************************************************************
# Copyright (c) 2014-2018, Lars Asplund lars.anders.asplund@gmail.com
"""
Provided functionality to run a suite of test in a robust way
"""
from __future__ import print_function
import os
from os.path import join, exists, abspath, basename, relpath
import traceback
import threading
import sys
import time
import logging
import string
from contextlib import contextmanager
import ostools
from test_report import PASSED, FAILED, WARNED
from hashing import hash_string
LOGGER = logging.getLogger(__name__)
class TestRunner(object):
"""
Administer the execution of a list of test suites
"""
VERBOSITY_QUIET = 0
VERBOSITY_NORMAL = 1
VERBOSITY_VERBOSE = 2
def __init__(self,
report,
verbosity=VERBOSITY_NORMAL,
num_threads=1,
fail_fast=False,
dont_catch_exceptions=False,
no_color=False):
self._lock = threading.Lock()
self._fail_fast = fail_fast
self._abort = False
self._local = threading.local()
self._report = report
assert verbosity in (self.VERBOSITY_QUIET,
self.VERBOSITY_NORMAL,
self.VERBOSITY_VERBOSE)
self._verbosity = verbosity
self._num_threads = num_threads
self._stdout = sys.stdout
self._stderr = sys.stderr
self._dont_catch_exceptions = dont_catch_exceptions
self._no_color = no_color
ostools.PROGRAM_STATUS.reset()
@property
def _is_verbose(self):
return self._verbosity == self.VERBOSITY_VERBOSE
@property
def _is_quiet(self):
return self._verbosity == self.VERBOSITY_QUIET
def run(self, test_suites):
"""
Run a list of test suites
"""
num_tests = 0
for test_suite in test_suites:
for test_name in test_suite.test_names:
num_tests += 1
if self._is_verbose:
print("Running test: " + test_name)
if self._is_verbose:
print("Running %i tests" % num_tests)
print()
self._report.set_expected_num_tests(num_tests)
scheduler = TestScheduler(test_suites)
threads = []
# Disable continuous output in parallel mode
write_stdout = self._is_verbose and self._num_threads == 1
try:
sys.stdout = ThreadLocalOutput(self._local, self._stdout)
sys.stderr = ThreadLocalOutput(self._local, self._stdout)
fixed_size = 16 * 1024 * 1024 # 16M
threading.stack_size(fixed_size)
# Start P-1 worker threads
for _ in range(self._num_threads - 1):
new_thread = threading.Thread(target=self._run_thread,
args=(write_stdout, scheduler, num_tests, False))
threads.append(new_thread)
new_thread.start()
# Run one worker in main thread such that P=1 is not multithreaded
self._run_thread(write_stdout, scheduler, num_tests, True)
scheduler.wait_for_finish()
except KeyboardInterrupt:
LOGGER.debug("TestRunner: Caught Ctrl-C shutting down")
ostools.PROGRAM_STATUS.shutdown()
raise
finally:
for thread in threads:
thread.join()
threading.stack_size(0)
sys.stdout = self._stdout
sys.stderr = self._stderr
LOGGER.debug("TestRunner: Leaving")
def _run_thread(self, write_stdout, scheduler, num_tests, is_main):
"""
Run worker thread
"""
self._local.output = self._stdout
while True:
test_suite = None
try:
test_suite = scheduler.next()
with self._stdout_lock():
for test_name in test_suite.test_names:
print("Starting %s" % test_name)
#print("Output file: %s" % test_suite.test_result_file)
self._run_test_suite(test_suite,
write_stdout,
num_tests)
except StopIteration:
return
except KeyboardInterrupt:
# Only main thread should handle KeyboardInterrupt
if is_main:
LOGGER.debug("MainWorkerThread: Caught Ctrl-C shutting down")
raise
return
finally:
if test_suite is not None:
scheduler.test_done()
def _add_skipped_tests(self, test_suite, results, start_time, num_tests, output_file_name):
for name in test_suite.test_names:
#TODO: set case not run as failed case
results[name]['status'] = FAILED
self._add_results(test_suite, results, start_time, num_tests, output_file_name)
def _run_test_suite(self,
test_suite,
write_stdout,
num_tests):
"""
Run the actual test suite
"""
#output_file = None
devNull = None
start_time = ostools.get_time()
results = self._fail_suite(test_suite)
try:
if write_stdout:
"""
If write_stdout enable, use stdout, showing log in terminal
"""
#self._local.output = Tee([self._stdout])
self._local.output = self._stdout
else:
"""
Open a dummy file os.devnull for writing log file to it,
not showing log in terminal
If you want to save log in a file, use code below:
>>> output_file = open("xxx.log", "w")
>>> self._local.output = Tee([output_file])
"""
devNull = open(os.devnull, "w")
self._local.output = devNull
#self._local.output = Tee([devNull])
results = test_suite.run()
except KeyboardInterrupt:
self._add_skipped_tests(test_suite, results, start_time, num_tests, test_suite.test_result_file)
raise KeyboardInterrupt
except:
if self._dont_catch_exceptions:
raise
with self._stdout_lock():
traceback.print_exc()
finally:
self._local.output = self._stdout
if devNull != None:
devNull.close()
#for fptr in [output_file]:
# if fptr is None:
# continue
# fptr.flush()
# fptr.close()
any_not_passed = any(value['status'] != PASSED for value in results.values())
with self._stdout_lock():
if (any_not_passed or self._is_verbose) and not self._is_quiet and not write_stdout:
#use stdout, print log file contents in terminal.
self._print_output(test_suite.test_result_file)
self._add_results(test_suite, results, start_time, num_tests, test_suite.test_result_file)
if self._fail_fast and any_not_passed:
self._abort = True
def _print_output(self, output_file_name):
"""
Print contents of output file if it exists
"""
with open(output_file_name, "r") as fh:
for line in fh.readlines():
self._stdout.write(line)
def _add_results(self, test_suite, results, start_time, num_tests, output_file_name):
"""
Add results to test report
"""
runtime = ostools.get_time() - start_time
time_per_test = runtime / len(results)
for test_name in test_suite.test_names:
status = results[test_name]
self._report.add_result(test_name,
status,
time_per_test,
output_file_name)
self._report.print_latest_status(total_tests=num_tests)
print()
@staticmethod
def _fail_suite(test_suite):
""" Return failure for all tests in suite """
results = {}
for test_name in test_suite.test_names:
results[test_name] = {}
results[test_name]['reasonMsg'] = ''
results[test_name]['status'] = FAILED
return results
@contextmanager
def _stdout_lock(self):
"""
Enter this lock when printing to stdout
Ensures no additional output is printed during abort
"""
with self._lock: # pylint: disable=not-context-manager
if self._abort:
raise KeyboardInterrupt
yield
class Tee(object):
"""
Provide a write method which writes to multiple files
like the unix 'tee' command.
"""
def __init__(self, files):
self._files = files
def write(self, txt):
for ofile in self._files:
ofile.write(txt)
def flush(self):
for ofile in self._files:
ofile.flush()
class ThreadLocalOutput(object):
"""
Replacement for stdout/err that separates re-directs
output to a thread local file interface
"""
def __init__(self, local, stdout):
self._local = local
self._stdout = stdout
def write(self, txt):
"""
Write to file object
"""
if hasattr(self._local, "output"):
self._local.output.write(txt)
else:
self._stdout.write(txt)
def flush(self):
"""
Flush file object
"""
if hasattr(self._local, "output"):
self._local.output.flush()
else:
self._stdout.flush()
class TestScheduler(object):
"""
Schedule tests to different treads
"""
def __init__(self, tests):
self._lock = threading.Lock()
self._tests = tests
self._idx = 0
self._num_done = 0
def __iter__(self):
return self
def __next__(self):
"""
Iterator in Python 3
"""
return self.__next__()
def next(self):
"""
Iterator in Python 2
"""
ostools.PROGRAM_STATUS.check_for_shutdown()
with self._lock: # pylint: disable=not-context-manager
if self._idx < len(self._tests):
idx = self._idx
self._idx += 1
return self._tests[idx]
raise StopIteration
def test_done(self):
"""
Signal that a test has been done
"""
with self._lock: # pylint: disable=not-context-manager
self._num_done += 1
def is_finished(self):
with self._lock: # pylint: disable=not-context-manager
return self._num_done >= len(self._tests)
def wait_for_finish(self):
"""
Block until all tests have been done
"""
while not self.is_finished():
time.sleep(0.05)
LEGAL_CHARS = string.printable
ILLEGAL_CHARS = ' <>"|:*%?\\/#&;()'
def _is_legal(char):
"""
Return true if the character is legal to have in a file name
"""
return (char in LEGAL_CHARS) and (char not in ILLEGAL_CHARS)
def create_output_path(output_path, test_suite_name):
"""
Create the full output path of a test case.
Ensure no bad characters and no long path names.
"""
output_path = abspath(output_path)
safe_name = "".join(char if _is_legal(char) else '_' for char in test_suite_name) + "_"
hash_name = hash_string(test_suite_name)
if "YASA_SHORT_TEST_OUTPUT_PATHS" in os.environ:
full_name = hash_name
else:
full_name = safe_name + hash_name
return join(output_path, full_name)