diff --git a/src/bluetooth_adapters/dbus.py b/src/bluetooth_adapters/dbus.py index cf89a63..7c857e8 100644 --- a/src/bluetooth_adapters/dbus.py +++ b/src/bluetooth_adapters/dbus.py @@ -78,6 +78,17 @@ async def _get_dbus_managed_objects() -> dict[str, Any]: "DBus connection broken: %s; try restarting " "`bluetooth` and `dbus`", ex ) return {} + except ConnectionRefusedError as ex: + if is_docker_env(): + _LOGGER.debug( + "DBus connection refused: %s; try restarting " + "`bluetooth`, `dbus`, and finally the docker container", + ex, + ) + _LOGGER.debug( + "DBus connection refused: %s; try restarting " "`bluetooth` and `dbus`", ex + ) + return {} msg = Message( destination="org.bluez", path="/", diff --git a/tests/test_init.py b/tests/test_init.py index 42ddb3f..b27d299 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -26,6 +26,36 @@ def __init__(self, *args, **kwargs): assert await get_bluetooth_adapters() == [] +@pytest.mark.asyncio +async def test_get_bluetooth_adapters_connection_refused(): + """Test get_bluetooth_adapters with connection refused.""" + + class MockMessageBus: + def __init__(self, *args, **kwargs): + raise ConnectionRefusedError + + with patch("bluetooth_adapters.dbus.MessageBus", MockMessageBus): + assert await get_bluetooth_adapters() == [] + + +@pytest.mark.asyncio +async def test_get_bluetooth_adapters_connect_refused_docker(): + class MockMessageBus: + def __init__(self, *args, **kwargs): + pass + + async def connect(self): + raise ConnectionRefusedError + + async def call(self): + return None + + with patch("bluetooth_adapters.dbus.MessageBus", MockMessageBus), patch( + "bluetooth_adapters.dbus.is_docker_env", return_value=True + ): + assert await get_bluetooth_adapters() == [] + + @pytest.mark.asyncio async def test_get_bluetooth_adapters_connect_fails(): class MockMessageBus: