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 def __init__(self, stub, test_cases, hist, exception_queue, stop_event): 37 super(TestRunner, self).__init__() 38 self._exception_queue = exception_queue 39 self._stop_event = stop_event 40 self._stub = stub 41 self._test_cases = _weighted_test_case_generator(test_cases) 42 self._histogram = hist 43 44 def run(self): 45 while not self._stop_event.is_set(): 46 try: 47 test_case = next(self._test_cases) 48 start_time = time.time() 49 test_case.test_interoperability(self._stub, None) 50 end_time = time.time() 51 self._histogram.add((end_time - start_time) * 1e9) 52 except Exception as e: # pylint: disable=broad-except 53 traceback.print_exc() 54 self._exception_queue.put( 55 Exception( 56 "An exception occurred during test {}".format( 57 test_case 58 ), 59 e, 60 ) 61 ) 62