Skip to content

Commit

Permalink
Merge pull request #684 from ag2ai/polish-suppress-in-tests
Browse files Browse the repository at this point in the history
Polish suppress decorator in tests
  • Loading branch information
davorrunje authored Jan 28, 2025
2 parents 101cc53 + 55c6559 commit 267ce37
Showing 1 changed file with 14 additions and 28 deletions.
42 changes: 14 additions & 28 deletions test/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ def credentials_from_test_param(request: pytest.FixtureRequest) -> Credentials:
T = TypeVar("T", bound=Callable[..., Any])


def suppress(exception: type[BaseException], *, retries: Optional[int] = None, timeout: int = 60) -> Callable[[T], T]:
def suppress(exception: type[BaseException], *, retries: int = 0, timeout: int = 60) -> Callable[[T], T]:
"""Suppresses the specified exception and retries the function a specified number of times.
Args:
Expand All @@ -429,58 +429,44 @@ def suppress(exception: type[BaseException], *, retries: Optional[int] = None, t
"""

def decorator(
func: T, exception: type[BaseException] = exception, retries: Optional[int] = retries, timeout: int = timeout
func: T, exception: type[BaseException] = exception, retries: int = retries, timeout: int = timeout
) -> T:
if inspect.iscoroutinefunction(func):

@functools.wraps(func)
async def wrapper(
*args: Any,
exception: type[BaseException] = exception,
retries: Optional[int] = retries,
retries: int = retries,
timeout: int = timeout,
**kwargs: Any,
) -> Any:
if retries is None:
for i in range(retries + 1):
try:
return await func(*args, **kwargs)
except exception:
pytest.xfail(f"Suppressed '{exception}' raised")
raise
else:
for i in range(retries):
try:
return await func(*args, **kwargs)
except exception:
if i >= retries - 1:
pytest.xfail(f"Suppressed '{exception}' raised {i + 1} times")
raise
await asyncio.sleep(timeout)
if i >= retries - 1:
pytest.xfail(f"Suppressed '{exception}' raised {i + 1} times")
raise
await asyncio.sleep(timeout)
else:

@functools.wraps(func)
def wrapper(
*args: Any,
exception: type[BaseException] = exception,
retries: Optional[int] = retries,
retries: int = retries,
timeout: int = timeout,
**kwargs: Any,
) -> Any:
if retries is None:
for i in range(retries + 1):
try:
return func(*args, **kwargs)
except exception:
pytest.xfail(f"Suppressed '{exception}' raised")
raise
else:
for i in range(retries):
try:
return func(*args, **kwargs)
except exception:
if i >= retries - 1:
pytest.xfail(f"Suppressed '{exception}' raised {i + 1} times")
raise
time.sleep(timeout)
if i >= retries - 1:
pytest.xfail(f"Suppressed '{exception}' raised {i + 1} times")
raise
time.sleep(timeout)

return wrapper # type: ignore[return-value]

Expand Down

0 comments on commit 267ce37

Please sign in to comment.