1# Copyright (C) 2024 The Android Open Source Project 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 15import time 16from typing import Callable 17 18 19class UnexpectedBehaviorError(Exception): 20 """Raised when there is an unexpected behavior during applying a procedure.""" 21 22class UnexpectedExceptionError(Exception): 23 """Raised when there is an unexpected exception throws during applying a procedure""" 24 25def expect_with_retry( 26 predicate: Callable[[], bool], 27 retry_action: Callable[[], None] = None, 28 max_retries: int = 10, 29 retry_interval_sec: int = 1, 30) -> None: 31 """Executes a predicate and retries if it doesn't return True.""" 32 33 for retry in range(max_retries): 34 if predicate(): 35 return None 36 else: 37 if retry == max_retries - 1: 38 break 39 if retry_action: 40 retry_action() 41 time.sleep(retry_interval_sec) 42 43 raise UnexpectedBehaviorError( 44 "Predicate didn't become true after " + str(max_retries) + " retries." 45 ) 46 47def expect_throws(runnable: callable, exception_class) -> None: 48 try: 49 runnable() 50 raise UnexpectedBehaviorError("Expected an exception, but none was thrown") 51 except exception_class: 52 pass 53 except UnexpectedBehaviorError as e: 54 raise e 55 except Exception as e: 56 raise UnexpectedExceptionError( 57 f"Expected exception of type {exception_class.__name__}, " 58 f"but got {type(e).__name__}: {e}" 59 )