From 55665c95f8572ee526fba7d3f3f41ef23d301245 Mon Sep 17 00:00:00 2001 From: Stefan Allius Date: Sun, 18 May 2025 23:53:12 +0200 Subject: [PATCH] test dispatcher exceptions --- app/src/mqtt.py | 3 ++- app/tests/test_mqtt.py | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/app/src/mqtt.py b/app/src/mqtt.py index bc0d3a3..886b264 100755 --- a/app/src/mqtt.py +++ b/app/src/mqtt.py @@ -148,7 +148,8 @@ class Mqtt(metaclass=Singleton): f' {status}') if status == 'online': self.ha_restarts += 1 - await self.__cb_mqtt_is_up() + if self.__cb_mqtt_is_up: + await self.__cb_mqtt_is_up() async def _out_coeff(self, message): payload = message.payload.decode("UTF-8") diff --git a/app/tests/test_mqtt.py b/app/tests/test_mqtt.py index ab3fa3a..945ba5e 100755 --- a/app/tests/test_mqtt.py +++ b/app/tests/test_mqtt.py @@ -255,6 +255,10 @@ async def test_msg_dispatch(config_mqtt_conn, spy_modbus_cmd): spy = spy_modbus_cmd try: m = Mqtt(None) + msg = aiomqtt.Message(topic= 'homeassistant/status', payload= b'online', qos= 0, retain = False, mid= 0, properties= None) + await m.dispatch_msg(msg) + assert m.ha_restarts == 1 + msg = aiomqtt.Message(topic= 'tsun/inv_1/rated_load', payload= b'2', qos= 0, retain = False, mid= 0, properties= None) await m.dispatch_msg(msg) spy.assert_awaited_once_with(Modbus.WRITE_SINGLE_REG, 0x2008, 2, logging.INFO) @@ -279,6 +283,23 @@ async def test_msg_dispatch(config_mqtt_conn, spy_modbus_cmd): await m.dispatch_msg(msg) spy.assert_awaited_once_with(Modbus.READ_INPUTS, 0x3000, 10, logging.INFO) + # test dispatching with empty mapping table + m.topic_defs.clear() + spy.reset_mock() + msg = aiomqtt.Message(topic= 'tsun/inv_1/modbus_read_inputs', payload= b'0x3000, 10', qos= 0, retain = False, mid= 0, properties= None) + await m.dispatch_msg(msg) + spy.assert_not_called() + + # test dispatching with incomplete mapping table - invalid fnc defined + m.topic_defs.append( + {'prefix': 'entity_prefix', 'topic': '/+/dcu_power', + 'full_topic': 'entity_prefix/+/dcu_power', 'fnc': 'invalid'} + ) + spy.reset_mock() + msg = aiomqtt.Message(topic= 'tsun/inv_1/modbus_read_inputs', payload= b'0x3000, 10', qos= 0, retain = False, mid= 0, properties= None) + await m.dispatch_msg(msg) + spy.assert_not_called() + finally: await m.close()