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
|
#!/usr/bin/env python3
"""
A smart, fast test runner. Used in a git pre-commit hook.
"""
import logging
import os
import re
import subprocess
import threading
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
from overrides import overrides
import ansi
import bootstrap
import config
import exec_utils
import file_utils
import parallelize as par
import smart_future
import text_utils
import thread_utils
logger = logging.getLogger(__name__)
args = config.add_commandline_args(f'({__file__})', 'Args related to __file__')
args.add_argument('--unittests', '-u', action='store_true', help='Run unittests.')
args.add_argument('--doctests', '-d', action='store_true', help='Run doctests.')
args.add_argument('--integration', '-i', action='store_true', help='Run integration tests.')
args.add_argument(
'--coverage', '-c', action='store_true', help='Run tests and capture code coverage data'
)
HOME = os.environ['HOME']
@dataclass
class TestingParameters:
halt_on_error: bool
"""Should we stop as soon as one error has occurred?"""
halt_event: threading.Event
"""An event that, when set, indicates to stop ASAP."""
@dataclass
class TestResults:
name: str
"""The name of this test / set of tests."""
tests_executed: List[str]
"""Tests that were executed."""
tests_succeeded: List[str]
"""Tests that succeeded."""
tests_failed: List[str]
"""Tests that failed."""
tests_timed_out: List[str]
"""Tests that timed out."""
def __add__(self, other):
self.tests_executed.extend(other.tests_executed)
self.tests_succeeded.extend(other.tests_succeeded)
self.tests_failed.extend(other.tests_failed)
self.tests_timed_out.extend(other.tests_timed_out)
return self
__radd__ = __add__
def __repr__(self) -> str:
out = f'{self.name}: '
out += f'{ansi.fg("green")}'
out += f'{len(self.tests_succeeded)}/{len(self.tests_executed)} passed'
out += f'{ansi.reset()}.\n'
if len(self.tests_failed) > 0:
out += f' ..{ansi.fg("red")}'
out += f'{len(self.tests_failed)} tests failed'
out += f'{ansi.reset()}:\n'
for test in self.tests_failed:
out += f' {test}\n'
out += '\n'
if len(self.tests_timed_out) > 0:
out += f' ..{ansi.fg("yellow")}'
out += f'{len(self.tests_timed_out)} tests timed out'
out += f'{ansi.reset()}:\n'
for test in self.tests_failed:
out += f' {test}\n'
out += '\n'
return out
class TestRunner(ABC, thread_utils.ThreadWithReturnValue):
"""A Base class for something that runs a test."""
def __init__(self, params: TestingParameters):
"""Create a TestRunner.
Args:
params: Test running paramters.
"""
super().__init__(self, target=self.begin, args=[params])
self.params = params
self.test_results = TestResults(
name=self.get_name(),
tests_executed=[],
tests_succeeded=[],
tests_failed=[],
tests_timed_out=[],
)
@abstractmethod
def get_name(self) -> str:
"""The name of this test collection."""
pass
@abstractmethod
def begin(self, params: TestingParameters) -> TestResults:
"""Start execution."""
pass
class TemplatedTestRunner(TestRunner, ABC):
"""A TestRunner that has a recipe for executing the tests."""
@abstractmethod
def identify_tests(self) -> List[str]:
"""Return a list of tests that should be executed."""
pass
@abstractmethod
def run_test(self, test: Any) -> TestResults:
"""Run a single test and return its TestResults."""
pass
def check_for_abort(self):
"""Periodically caled to check to see if we need to stop."""
if self.params.halt_event.is_set():
logger.debug('Thread %s saw halt event; exiting.', self.get_name())
raise Exception("Kill myself!")
if self.params.halt_on_error:
if len(self.test_results.tests_failed) > 0:
logger.error('Thread %s saw abnormal results; exiting.', self.get_name())
raise Exception("Kill myself!")
def status_report(self, started: int, result: TestResults):
"""Periodically called to report current status."""
finished = (
len(self.test_results.tests_succeeded)
+ len(self.test_results.tests_failed)
+ len(self.test_results.tests_timed_out)
)
running = started - finished
finished_percent = finished / started * 100.0
logging.info(
'%s: %d/%d in flight; %d/%d finished (%.1f%%).',
self.get_name(),
running,
started,
finished,
started,
finished_percent,
)
def persist_output(self, test_name: str, message: str, output: str) -> None:
"""Called to save the output of a test run."""
basename = file_utils.without_path(test_name)
dest = f'{basename}-output.txt'
with open(f'./test_output/{dest}', 'w') as wf:
print(message, file=wf)
print('-' * len(message), file=wf)
wf.write(output)
def execute_commandline(
self,
test_name: str,
cmdline: str,
*,
timeout: float = 120.0,
) -> TestResults:
"""Execute a particular commandline to run a test."""
try:
logger.debug('%s: Running %s (%s)', self.get_name(), test_name, cmdline)
output = exec_utils.cmd(
cmdline,
timeout_seconds=timeout,
)
self.persist_output(test_name, f'{test_name} ({cmdline}) succeeded.', output)
logger.debug('%s (%s) succeeded', test_name, cmdline)
return TestResults(test_name, [test_name], [test_name], [], [])
except subprocess.TimeoutExpired as e:
msg = f'{self.get_name()}: {test_name} ({cmdline}) timed out after {e.timeout:.1f} seconds.'
logger.error(msg)
logger.debug(
'%s: %s output when it timed out: %s', self.get_name(), test_name, e.output
)
self.persist_output(test_name, msg, e.output.decode('utf-8'))
return TestResults(
test_name,
[test_name],
[],
[],
[test_name],
)
except subprocess.CalledProcessError as e:
msg = f'{self.get_name()}: {test_name} ({cmdline}) failed; exit code {e.returncode}'
logger.error(msg)
logger.debug('%s: %s output when it failed: %s', self.get_name(), test_name, e.output)
self.persist_output(test_name, msg, e.output.decide('utf-8'))
return TestResults(
test_name,
[test_name],
[],
[test_name],
[],
)
@overrides
def begin(self, params: TestingParameters) -> TestResults:
logger.debug('Thread %s started.', self.get_name())
interesting_tests = self.identify_tests()
running: List[Any] = []
for test in interesting_tests:
running.append(self.run_test(test))
started = len(running)
for future in smart_future.wait_any(running):
self.check_for_abort()
result = future._resolve()
self.status_report(started, result)
logger.debug('Test %s finished.', result.name)
self.test_results += result
logger.debug('Thread %s finished.', self.get_name())
return self.test_results
class UnittestTestRunner(TemplatedTestRunner):
"""Run all known Unittests."""
@overrides
def get_name(self) -> str:
return "Unittests"
@overrides
def identify_tests(self) -> List[str]:
return list(file_utils.expand_globs('*_test.py'))
@par.parallelize
def run_test(self, test: Any) -> TestResults:
if config.config['coverage']:
cmdline = f'coverage run --source {HOME}/lib {test} --unittests_ignore_perf'
else:
cmdline = test
return self.execute_commandline(test, cmdline)
class DoctestTestRunner(TemplatedTestRunner):
"""Run all known Doctests."""
@overrides
def get_name(self) -> str:
return "Doctests"
@overrides
def identify_tests(self) -> List[str]:
ret = []
out = exec_utils.cmd('grep -lR "^ *import doctest" /home/scott/lib/python_modules/*')
for line in out.split('\n'):
if re.match(r'.*\.py$', line):
if 'run_tests.py' not in line:
ret.append(line)
return ret
@par.parallelize
def run_test(self, test: Any) -> TestResults:
if config.config['coverage']:
cmdline = f'coverage run --source {HOME}/lib {test} 2>&1'
else:
cmdline = f'python3 {test}'
return self.execute_commandline(test, cmdline)
class IntegrationTestRunner(TemplatedTestRunner):
"""Run all know Integration tests."""
@overrides
def get_name(self) -> str:
return "Integration Tests"
@overrides
def identify_tests(self) -> List[str]:
return list(file_utils.expand_globs('*_itest.py'))
@par.parallelize
def run_test(self, test: Any) -> TestResults:
if config.config['coverage']:
cmdline = f'coverage run --source {HOME}/lib {test}'
else:
cmdline = test
return self.execute_commandline(test, cmdline)
def test_results_report(results: Dict[str, TestResults]) -> int:
"""Give a final report about the tests that were run."""
total_problems = 0
for result in results.values():
print(result, end='')
total_problems += len(result.tests_failed)
total_problems += len(result.tests_timed_out)
if total_problems > 0:
print('Reminder: look in ./test_output to view test output logs')
return total_problems
def code_coverage_report():
"""Give a final code coverage report."""
text_utils.header('Code Coverage')
exec_utils.cmd('coverage combine .coverage*')
out = exec_utils.cmd('coverage report --omit=config-3.8.py,*_test.py,*_itest.py --sort=-cover')
print(out)
print(
"""
To recall this report w/o re-running the tests:
$ coverage report --omit=config-3.8.py,*_test.py,*_itest.py --sort=-cover
...from the 'tests' directory. Note that subsequent calls to
run_tests.py with --coverage will klobber previous results. See:
https://coverage.readthedocs.io/en/6.2/
"""
)
@bootstrap.initialize
def main() -> Optional[int]:
saw_flag = False
halt_event = threading.Event()
threads: List[TestRunner] = []
halt_event.clear()
params = TestingParameters(
halt_on_error=True,
halt_event=halt_event,
)
if config.config['coverage']:
logger.debug('Clearing existing coverage data via "coverage erase".')
exec_utils.cmd('coverage erase')
if config.config['unittests']:
saw_flag = True
threads.append(UnittestTestRunner(params))
if config.config['doctests']:
saw_flag = True
threads.append(DoctestTestRunner(params))
if config.config['integration']:
saw_flag = True
threads.append(IntegrationTestRunner(params))
if not saw_flag:
config.print_usage()
print('ERROR: one of --unittests, --doctests or --integration is required.')
return 1
for thread in threads:
thread.start()
results: Dict[str, TestResults] = {}
while len(results) != len(threads):
for thread in threads:
if not thread.is_alive():
tid = thread.name
if tid not in results:
result = thread.join()
if result:
results[tid] = result
if len(result.tests_failed) > 0:
logger.error(
'Thread %s returned abnormal results; killing the others.', tid
)
halt_event.set()
time.sleep(1.0)
if config.config['coverage']:
code_coverage_report()
total_problems = test_results_report(results)
return total_problems
if __name__ == '__main__':
main()
|