| 1 |
# Copyright 2015 gRPC authors. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
from __future__ import absolute_import |
| 16 |
|
| 17 |
import collections |
| 18 |
import io |
| 19 |
import os |
| 20 |
import select |
| 21 |
import signal |
| 22 |
import sys |
| 23 |
import tempfile |
| 24 |
import threading |
| 25 |
import time |
| 26 |
import unittest |
| 27 |
import uuid |
| 28 |
|
| 29 |
from tests import _loader |
| 30 |
from tests import _result |
| 31 |
|
| 32 |
|
| 33 |
class CaptureFile(object): |
| 34 |
"""A context-managed file to redirect output to a byte array. |
| 35 |
|
| 36 |
Use by invoking `start` (`__enter__`) and at some point invoking `stop` |
| 37 |
(`__exit__`). At any point after the initial call to `start` call `output` to |
| 38 |
get the current redirected output. Note that we don't currently use file |
| 39 |
locking, so calling `output` between calls to `start` and `stop` may muddle |
| 40 |
the result (you should only be doing this during a Python-handled interrupt as |
| 41 |
a last ditch effort to provide output to the user). |
| 42 |
|
| 43 |
Attributes: |
| 44 |
_redirected_fd (int): File descriptor of file to redirect writes from. |
| 45 |
_saved_fd (int): A copy of the original value of the redirected file |
| 46 |
descriptor. |
| 47 |
_into_file (TemporaryFile or None): File to which writes are redirected. |
| 48 |
Only non-None when self is started. |
| 49 |
""" |
| 50 |
|
| 51 |
def __init__(self, fd): |
| 52 |
self._redirected_fd = fd |
| 53 |
self._saved_fd = os.dup(self._redirected_fd) |
| 54 |
self._into_file = None |
| 55 |
|
| 56 |
def output(self): |
| 57 |
"""Get all output from the redirected-to file if it exists.""" |
| 58 |
if self._into_file: |
| 59 |
self._into_file.seek(0) |
| 60 |
return bytes(self._into_file.read()) |
| 61 |
else: |
| 62 |
return bytes() |
| 63 |
|
| 64 |
def start(self): |
| 65 |
"""Start redirection of writes to the file descriptor.""" |
| 66 |
self._into_file = tempfile.TemporaryFile() |
| 67 |
os.dup2(self._into_file.fileno(), self._redirected_fd) |
| 68 |
|
| 69 |
def stop(self): |
| 70 |
"""Stop redirection of writes to the file descriptor.""" |
| 71 |
# n.b. this dup2 call auto-closes self._redirected_fd |
| 72 |
os.dup2(self._saved_fd, self._redirected_fd) |
| 73 |
|
| 74 |
def write_bypass(self, value): |
| 75 |
"""Bypass the redirection and write directly to the original file. |
| 76 |
|
| 77 |
Arguments: |
| 78 |
value (str): What to write to the original file. |
| 79 |
""" |
| 80 |
if not isinstance(value, bytes): |
| 81 |
value = value.encode('ascii') |
| 82 |
if self._saved_fd is None: |
| 83 |
os.write(self._redirect_fd, value) |
| 84 |
else: |
| 85 |
os.write(self._saved_fd, value) |
| 86 |
|
| 87 |
def __enter__(self): |
| 88 |
self.start() |
| 89 |
return self |
| 90 |
|
| 91 |
def __exit__(self, type, value, traceback): |
| 92 |
self.stop() |
| 93 |
|
| 94 |
def close(self): |
| 95 |
"""Close any resources used by self not closed by stop().""" |
| 96 |
os.close(self._saved_fd) |
| 97 |
|
| 98 |
|
| 99 |
class AugmentedCase(collections.namedtuple('AugmentedCase', ['case', 'id'])): |
| 100 |
"""A test case with a guaranteed unique externally specified identifier. |
| 101 |
|
| 102 |
Attributes: |
| 103 |
case (unittest.TestCase): TestCase we're decorating with an additional |
| 104 |
identifier. |
| 105 |
id (object): Any identifier that may be considered 'unique' for testing |
| 106 |
purposes. |
| 107 |
""" |
| 108 |
|
| 109 |
def __new__(cls, case, id=None): |
| 110 |
if id is None: |
| 111 |
id = uuid.uuid4() |
| 112 |
return super(cls, AugmentedCase).__new__(cls, case, id) |
| 113 |
|
| 114 |
|
| 115 |
# NOTE(lidiz) This complex wrapper is not triggering setUpClass nor |
| 116 |
# tearDownClass. Do not use those methods, or fix this wrapper! |
| 117 |
class Runner(object): |
| 118 |
|
| 119 |
def __init__(self, dedicated_threads=False): |
| 120 |
"""Constructs the Runner object. |
| 121 |
|
| 122 |
Args: |
| 123 |
dedicated_threads: A bool indicates whether to spawn each unit test |
| 124 |
in separate thread or not. |
| 125 |
""" |
| 126 |
self._skipped_tests = [] |
| 127 |
self._dedicated_threads = dedicated_threads |
| 128 |
|
| 129 |
def skip_tests(self, tests): |
| 130 |
self._skipped_tests = tests |
| 131 |
|
| 132 |
def run(self, suite): |
| 133 |
"""See setuptools' test_runner setup argument for information.""" |
| 134 |
# only run test cases with id starting with given prefix |
| 135 |
testcase_filter = os.getenv('GRPC_PYTHON_TESTRUNNER_FILTER') |
| 136 |
filtered_cases = [] |
| 137 |
for case in _loader.iterate_suite_cases(suite): |
| 138 |
if not testcase_filter or case.id().startswith(testcase_filter): |
| 139 |
filtered_cases.append(case) |
| 140 |
|
| 141 |
# Ensure that every test case has no collision with any other test case in |
| 142 |
# the augmented results. |
| 143 |
augmented_cases = [ |
| 144 |
AugmentedCase(case, uuid.uuid4()) for case in filtered_cases |
| 145 |
] |
| 146 |
case_id_by_case = dict((augmented_case.case, augmented_case.id) |
| 147 |
for augmented_case in augmented_cases) |
| 148 |
result_out = io.StringIO() |
| 149 |
result = _result.TerminalResult( |
| 150 |
result_out, id_map=lambda case: case_id_by_case[case]) |
| 151 |
stdout_pipe = CaptureFile(sys.stdout.fileno()) |
| 152 |
stderr_pipe = CaptureFile(sys.stderr.fileno()) |
| 153 |
kill_flag = [False] |
| 154 |
|
| 155 |
def sigint_handler(signal_number, frame): |
| 156 |
if signal_number == signal.SIGINT: |
| 157 |
kill_flag[0] = True # Python 2.7 not having 'local'... :-( |
| 158 |
signal.signal(signal_number, signal.SIG_DFL) |
| 159 |
|
| 160 |
def fault_handler(signal_number, frame): |
| 161 |
stdout_pipe.write_bypass( |
| 162 |
'Received fault signal {}\nstdout:\n{}\n\nstderr:{}\n'.format( |
| 163 |
signal_number, stdout_pipe.output(), stderr_pipe.output())) |
| 164 |
os._exit(1) |
| 165 |
|
| 166 |
def check_kill_self(): |
| 167 |
if kill_flag[0]: |
| 168 |
stdout_pipe.write_bypass('Stopping tests short...') |
| 169 |
result.stopTestRun() |
| 170 |
stdout_pipe.write_bypass(result_out.getvalue()) |
| 171 |
stdout_pipe.write_bypass('\ninterrupted stdout:\n{}\n'.format( |
| 172 |
stdout_pipe.output().decode())) |
| 173 |
stderr_pipe.write_bypass('\ninterrupted stderr:\n{}\n'.format( |
| 174 |
stderr_pipe.output().decode())) |
| 175 |
os._exit(1) |
| 176 |
|
| 177 |
def try_set_handler(name, handler): |
| 178 |
try: |
| 179 |
signal.signal(getattr(signal, name), handler) |
| 180 |
except AttributeError: |
| 181 |
pass |
| 182 |
|
| 183 |
try_set_handler('SIGINT', sigint_handler) |
| 184 |
try_set_handler('SIGBUS', fault_handler) |
| 185 |
try_set_handler('SIGABRT', fault_handler) |
| 186 |
try_set_handler('SIGFPE', fault_handler) |
| 187 |
try_set_handler('SIGILL', fault_handler) |
| 188 |
# Sometimes output will lag after a test has successfully finished; we |
| 189 |
# ignore such writes to our pipes. |
| 190 |
try_set_handler('SIGPIPE', signal.SIG_IGN) |
| 191 |
|
| 192 |
# Run the tests |
| 193 |
result.startTestRun() |
| 194 |
for augmented_case in augmented_cases: |
| 195 |
for skipped_test in self._skipped_tests: |
| 196 |
if skipped_test in augmented_case.case.id(): |
| 197 |
break |
| 198 |
else: |
| 199 |
sys.stdout.write('Running {}\n'.format( |
| 200 |
augmented_case.case.id())) |
| 201 |
sys.stdout.flush() |
| 202 |
if self._dedicated_threads: |
| 203 |
# (Deprecated) Spawns dedicated thread for each test case. |
| 204 |
case_thread = threading.Thread( |
| 205 |
target=augmented_case.case.run, args=(result,)) |
| 206 |
try: |
| 207 |
with stdout_pipe, stderr_pipe: |
| 208 |
case_thread.start() |
| 209 |
# If the thread is exited unexpected, stop testing. |
| 210 |
while case_thread.is_alive(): |
| 211 |
check_kill_self() |
| 212 |
time.sleep(0) |
| 213 |
case_thread.join() |
| 214 |
except: # pylint: disable=try-except-raise |
| 215 |
# re-raise the exception after forcing the with-block to end |
| 216 |
raise |
| 217 |
# Records the result of the test case run. |
| 218 |
result.set_output(augmented_case.case, stdout_pipe.output(), |
| 219 |
stderr_pipe.output()) |
| 220 |
sys.stdout.write(result_out.getvalue()) |
| 221 |
sys.stdout.flush() |
| 222 |
result_out.truncate(0) |
| 223 |
check_kill_self() |
| 224 |
else: |
| 225 |
# Donates current thread to test case execution. |
| 226 |
augmented_case.case.run(result) |
| 227 |
result.stopTestRun() |
| 228 |
stdout_pipe.close() |
| 229 |
stderr_pipe.close() |
| 230 |
|
| 231 |
# Report results |
| 232 |
sys.stdout.write(result_out.getvalue()) |
| 233 |
sys.stdout.flush() |
| 234 |
signal.signal(signal.SIGINT, signal.SIG_DFL) |
| 235 |
with open('report.xml', 'wb') as report_xml_file: |
| 236 |
_result.jenkins_junit_xml(result).write(report_xml_file) |
| 237 |
return result |