diff --git a/tests/test_ibkr.py b/tests/test_ibkr.py index 12890d0..33efbde 100644 --- a/tests/test_ibkr.py +++ b/tests/test_ibkr.py @@ -1,18 +1,28 @@ -from ib_insync import IB import pytest +from ib_insync import IB + +MAX_ATTEMPTS = 3 + + +class IBKRConnectionError(RuntimeError): + """Raised when the IB Gateway API does not accept a connection.""" @pytest.mark.asyncio async def test_ib_connection(): - attempts = 0 ib = IB() - while not ib.isConnected(): - if attempts >= 3: - raise Exception("Failed to connect to IBKR after 3 attempts") + last_error: OSError | None = None + for _ in range(MAX_ATTEMPTS): + if ib.isConnected(): + break try: await ib.connectAsync("localhost", 8888, clientId=0) - except Exception: - pass - attempts += 1 + except OSError as exc: + last_error = exc + + if not ib.isConnected(): + raise IBKRConnectionError( + f"Failed to connect to IBKR after {MAX_ATTEMPTS} attempts" + ) from last_error ib.disconnect()