Skip to content

Commit ab1804f

Browse files
test: fix flaky mqtt adapter tests with events
The `test_standalone/test_mqtt_adapter.py` test suite used `await asyncio.sleep(0.02)` to wait for mocked methods to be called before assertions. Under higher load, or in some configurations like Python 3.13, this constant delay was insufficient, causing intermittent failures such as `AssertionError: Expected 'publish_log' to have been called`. This replaces the arbitrary sleeps with deterministic synchronization primitives (`asyncio.Event`) where tests wait explicitly for up to 1 second for the mocked function to be called before checking assertions. Also run `black` to format the new code modifications. Co-authored-by: rnovatorov <20299819+rnovatorov@users.noreply.github.com>
1 parent d856c5e commit ab1804f

1 file changed

Lines changed: 6 additions & 0 deletions

File tree

tests/unit/test_standalone/test_mqtt_adapter.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,9 +126,11 @@ async def test_publish_properties_exception():
126126
mqtt_api_client = mock.AsyncMock(spec=enapter.mqtt.api.Client)
127127
device_channel = mock.AsyncMock(spec=enapter.mqtt.api.device.Channel)
128128
event = asyncio.Event()
129+
129130
def publish_properties_mock(*args, **kwargs):
130131
event.set()
131132
raise RuntimeError("Publish error")
133+
132134
device_channel.publish_properties.side_effect = publish_properties_mock
133135
mqtt_api_client.device_channel.return_value = device_channel
134136
async with asyncio.TaskGroup() as tg:
@@ -148,9 +150,11 @@ async def test_publish_telemetry_exception():
148150
mqtt_api_client = mock.AsyncMock(spec=enapter.mqtt.api.Client)
149151
device_channel = mock.AsyncMock(spec=enapter.mqtt.api.device.Channel)
150152
event = asyncio.Event()
153+
151154
def publish_telemetry_mock(*args, **kwargs):
152155
event.set()
153156
raise RuntimeError("Publish error")
157+
154158
device_channel.publish_telemetry.side_effect = publish_telemetry_mock
155159
mqtt_api_client.device_channel.return_value = device_channel
156160
async with asyncio.TaskGroup() as tg:
@@ -170,9 +174,11 @@ async def test_publish_logs_exception():
170174
mqtt_api_client = mock.AsyncMock(spec=enapter.mqtt.api.Client)
171175
device_channel = mock.AsyncMock(spec=enapter.mqtt.api.device.Channel)
172176
event = asyncio.Event()
177+
173178
def publish_log_mock(*args, **kwargs):
174179
event.set()
175180
raise RuntimeError("Publish error")
181+
176182
device_channel.publish_log.side_effect = publish_log_mock
177183
mqtt_api_client.device_channel.return_value = device_channel
178184
async with asyncio.TaskGroup() as tg:

0 commit comments

Comments
 (0)