|
4 | 4 | from unittest import TestCase, skipIf |
5 | 5 |
|
6 | 6 | from mqlog import MqttHandler |
| 7 | +from tests.utils import AsyncMock, Mock |
7 | 8 |
|
8 | 9 |
|
9 | 10 | class FakeClient: |
10 | 11 | """A fake MQTT client for testing purposes.""" |
11 | 12 |
|
12 | 13 | def __init__(self): |
13 | | - self.calls = [] |
14 | | - |
15 | | - # Store the call like a mock so we can check it later |
16 | | - async def publish(self, topic, payload, qos=0): |
17 | | - self.calls.append((topic, payload, qos)) |
| 14 | + self.publish = AsyncMock() |
18 | 15 |
|
19 | 16 |
|
20 | 17 | class TestMqttHandler(TestCase): |
@@ -50,6 +47,23 @@ def test_flush_full_buffer(self): |
50 | 47 | self.logger.info(f"Test message {i}") |
51 | 48 | self.assertTrue(self.handler.will_flush.is_set()) |
52 | 49 |
|
| 50 | + def test_flush_fail(self): |
| 51 | + """Flushing should log an error if publish fails""" |
| 52 | + self.handler._logger.error = Mock() |
| 53 | + self.client.publish = AsyncMock(side_effect=Exception("Publish failed")) |
| 54 | + asyncio.create_task(self.handler.run()) |
| 55 | + |
| 56 | + async def do_test(logger): |
| 57 | + await asyncio.sleep(0.1) # Allow handler to start |
| 58 | + logger.error("Test message") # should trigger flush |
| 59 | + |
| 60 | + asyncio.run(do_test(self.logger)) |
| 61 | + self.assertTrue(self.handler.will_flush.is_set()) |
| 62 | + self.handler._logger.error.assert_called_with( |
| 63 | + "Failed to publish log message: Publish failed" |
| 64 | + ) |
| 65 | + |
| 66 | + |
53 | 67 | @skipIf(os.getenv("CI"), "Hangs in CI") |
54 | 68 | def test_publish(self): |
55 | 69 | """Flushing should publish messages to MQTT topic""" |
|
0 commit comments