Skip to content

Commit

Permalink
fix: Release lock in aenter on initial connection failure (#245); Close
Browse files Browse the repository at this point in the history
  • Loading branch information
vvanglro authored Aug 23, 2023
1 parent 40d4f56 commit 1f0f0b3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
6 changes: 5 additions & 1 deletion aiomqtt/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1039,7 +1039,11 @@ async def __aenter__(self) -> Client:
msg = "Does not support reentrant"
raise MqttReentrantError(msg)
await self._lock.acquire()
await self.connect()
try:
await self.connect()
except Exception:
self._lock.release()
raise
return self

async def __aexit__(
Expand Down
10 changes: 9 additions & 1 deletion tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from anyio.abc import TaskStatus

from aiomqtt import Client, ProtocolVersion, TLSParameters, Topic, Wildcard, Will
from aiomqtt.error import MqttReentrantError
from aiomqtt.error import MqttError, MqttReentrantError
from aiomqtt.types import PayloadType

pytestmark = pytest.mark.anyio
Expand Down Expand Up @@ -536,3 +536,11 @@ async def test_client_connecting_disconnected_done() -> None:
client._disconnected.set_result(None)
await client.connect()
await client.disconnect()


@pytest.mark.network
async def test_client_aenter_connect_error_lock_release() -> None:
client = Client(hostname="aenter_connect_error_lock_release")
with pytest.raises(MqttError):
await client.__aenter__()
assert not client._lock.locked()

0 comments on commit 1f0f0b3

Please sign in to comment.