| 1 |
"""Default driver for run tests (run-*.test). |
| 2 |
|
| 3 |
This imports the 'native' module (containing the compiled test cases) |
| 4 |
and calls each function starting with test_, and reports any |
| 5 |
exceptions as failures. |
| 6 |
|
| 7 |
Test cases can provide a custom driver.py that overrides this file. |
| 8 |
""" |
| 9 |
|
| 10 |
import sys |
| 11 |
import native |
| 12 |
import asyncio |
| 13 |
import inspect |
| 14 |
|
| 15 |
evloop = asyncio.new_event_loop() |
| 16 |
|
| 17 |
failures = [] |
| 18 |
tests_run = 0 |
| 19 |
|
| 20 |
for name in dir(native): |
| 21 |
if name.startswith('test_'): |
| 22 |
test_func = getattr(native, name) |
| 23 |
tests_run += 1 |
| 24 |
try: |
| 25 |
if inspect.iscoroutinefunction(test_func): |
| 26 |
evloop.run_until_complete(test_func()) |
| 27 |
else: |
| 28 |
test_func() |
| 29 |
except Exception as e: |
| 30 |
failures.append((name, sys.exc_info())) |
| 31 |
|
| 32 |
if failures: |
| 33 |
from traceback import print_exception, format_tb |
| 34 |
import re |
| 35 |
|
| 36 |
def extract_line(tb): |
| 37 |
formatted = '\n'.join(format_tb(tb)) |
| 38 |
m = re.search('File "(native|driver).py", line ([0-9]+), in (test_|<module>)', formatted) |
| 39 |
if m is None: |
| 40 |
return "0" |
| 41 |
return m.group(1) |
| 42 |
|
| 43 |
# Sort failures by line number of test function. |
| 44 |
failures = sorted(failures, key=lambda e: extract_line(e[1][2])) |
| 45 |
|
| 46 |
# If there are multiple failures, print stack traces of all but the final failure. |
| 47 |
for name, e in failures[:-1]: |
| 48 |
print(f'<< {name} >>') |
| 49 |
sys.stdout.flush() |
| 50 |
print_exception(*e) |
| 51 |
print() |
| 52 |
sys.stdout.flush() |
| 53 |
|
| 54 |
# Raise exception for the last failure. Test runner will show the traceback. |
| 55 |
print(f'<< {failures[-1][0]} >>') |
| 56 |
sys.stdout.flush() |
| 57 |
raise failures[-1][1][1] |
| 58 |
|
| 59 |
assert tests_run > 0, 'Default test driver did not find any functions prefixed "test_" to run.' |