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"""Code for instructing systems under test to block or fail.""" 15 16import abc 17import contextlib 18import threading 19 20import six 21 22 23class Defect(Exception): 24 """Simulates a programming defect raised into in a system under test. 25 26 Use of a standard exception type is too easily misconstrued as an actual 27 defect in either the test infrastructure or the system under test. 28 """ 29 30 31class Control(six.with_metaclass(abc.ABCMeta)): 32 """An object that accepts program control from a system under test. 33 34 Systems under test passed a Control should call its control() method 35 frequently during execution. The control() method may block, raise an 36 exception, or do nothing, all according to the enclosing test's desire for 37 the system under test to simulate hanging, failing, or functioning. 38 """ 39 40 @abc.abstractmethod 41 def control(self): 42 """Potentially does anything.""" 43 raise NotImplementedError() 44 45 46class PauseFailControl(Control): 47 """A Control that can be used to pause or fail code under control. 48 49 This object is only safe for use from two threads: one of the system under 50 test calling control and the other from the test system calling pause, 51 block_until_paused, and fail. 52 """ 53 54 def __init__(self): 55 self._condition = threading.Condition() 56 self._pause = False 57 self._paused = False 58 self._fail = False 59 60 def control(self): 61 with self._condition: 62 if self._fail: 63 raise Defect() 64 65 while self._pause: 66 self._paused = True 67 self._condition.notify_all() 68 self._condition.wait() 69 self._paused = False 70 71 @contextlib.contextmanager 72 def pause(self): 73 """Pauses code under control while controlling code is in context.""" 74 with self._condition: 75 self._pause = True 76 yield 77 with self._condition: 78 self._pause = False 79 self._condition.notify_all() 80 81 def block_until_paused(self): 82 """Blocks controlling code until code under control is paused. 83 84 May only be called within the context of a pause call. 85 """ 86 with self._condition: 87 while not self._paused: 88 self._condition.wait() 89 90 @contextlib.contextmanager 91 def fail(self): 92 """Fails code under control while controlling code is in context.""" 93 with self._condition: 94 self._fail = True 95 yield 96 with self._condition: 97 self._fail = False 98