1# Copyright 2016 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"""Thread that sends random weighted requests on a TestService stub.""" 15 16import random 17import threading 18import time 19import traceback 20 21 22def _weighted_test_case_generator(weighted_cases): 23 weight_sum = sum(weighted_cases.itervalues()) 24 25 while True: 26 val = random.uniform(0, weight_sum) 27 partial_sum = 0 28 for case in weighted_cases: 29 partial_sum += weighted_cases[case] 30 if val <= partial_sum: 31 yield case 32 break 33 34 35class TestRunner(threading.Thread): 36 37 def __init__(self, stub, test_cases, hist, exception_queue, stop_event): 38 super(TestRunner, self).__init__() 39 self._exception_queue = exception_queue 40 self._stop_event = stop_event 41 self._stub = stub 42 self._test_cases = _weighted_test_case_generator(test_cases) 43 self._histogram = hist 44 45 def run(self): 46 while not self._stop_event.is_set(): 47 try: 48 test_case = next(self._test_cases) 49 start_time = time.time() 50 test_case.test_interoperability(self._stub, None) 51 end_time = time.time() 52 self._histogram.add((end_time - start_time) * 1e9) 53 except Exception as e: # pylint: disable=broad-except 54 traceback.print_exc() 55 self._exception_queue.put( 56 Exception("An exception occurred during test {}" 57 .format(test_case), e)) 58