test_mqtt.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. # systemctl-mqtt - MQTT client triggering & reporting shutdown on systemd-based systems
  2. #
  3. # Copyright (C) 2020 Fabian Peter Hammerle <fabian@hammerle.me>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. import logging
  18. import threading
  19. import time
  20. import unittest.mock
  21. import dbus
  22. import paho.mqtt.client
  23. import pytest
  24. from paho.mqtt.client import MQTTMessage
  25. import systemctl_mqtt
  26. # pylint: disable=protected-access
  27. @pytest.mark.parametrize("mqtt_host", ["mqtt-broker.local"])
  28. @pytest.mark.parametrize("mqtt_port", [1833])
  29. @pytest.mark.parametrize("mqtt_topic_prefix", ["systemctl/host", "system/command"])
  30. @pytest.mark.parametrize("homeassistant_discovery_prefix", ["homeassistant"])
  31. @pytest.mark.parametrize("homeassistant_node_id", ["host", "node"])
  32. def test__run(
  33. caplog,
  34. mqtt_host,
  35. mqtt_port,
  36. mqtt_topic_prefix,
  37. homeassistant_discovery_prefix,
  38. homeassistant_node_id,
  39. ):
  40. # pylint: disable=too-many-locals,too-many-arguments
  41. caplog.set_level(logging.DEBUG)
  42. with unittest.mock.patch(
  43. "socket.create_connection"
  44. ) as create_socket_mock, unittest.mock.patch(
  45. "ssl.SSLContext.wrap_socket", autospec=True,
  46. ) as ssl_wrap_socket_mock, unittest.mock.patch(
  47. "paho.mqtt.client.Client.loop_forever", autospec=True,
  48. ) as mqtt_loop_forever_mock, unittest.mock.patch(
  49. "gi.repository.GLib.MainLoop.run"
  50. ) as glib_loop_mock, unittest.mock.patch(
  51. "systemctl_mqtt._get_login_manager"
  52. ) as get_login_manager_mock:
  53. ssl_wrap_socket_mock.return_value.send = len
  54. get_login_manager_mock.return_value.Get.return_value = dbus.Boolean(False)
  55. systemctl_mqtt._run(
  56. mqtt_host=mqtt_host,
  57. mqtt_port=mqtt_port,
  58. mqtt_username=None,
  59. mqtt_password=None,
  60. mqtt_topic_prefix=mqtt_topic_prefix,
  61. homeassistant_discovery_prefix=homeassistant_discovery_prefix,
  62. homeassistant_node_id=homeassistant_node_id,
  63. )
  64. assert caplog.records[0].levelno == logging.INFO
  65. assert caplog.records[0].message == "connecting to MQTT broker {}:{}".format(
  66. mqtt_host, mqtt_port
  67. )
  68. # correct remote?
  69. assert create_socket_mock.call_count == 1
  70. create_socket_args, _ = create_socket_mock.call_args
  71. assert create_socket_args[0] == (mqtt_host, mqtt_port)
  72. # ssl enabled?
  73. assert ssl_wrap_socket_mock.call_count == 1
  74. ssl_context = ssl_wrap_socket_mock.call_args[0][0] # self
  75. assert ssl_context.check_hostname is True
  76. assert ssl_wrap_socket_mock.call_args[1]["server_hostname"] == mqtt_host
  77. # loop started?
  78. while threading.active_count() > 1:
  79. time.sleep(0.01)
  80. assert mqtt_loop_forever_mock.call_count == 1
  81. (mqtt_client,) = mqtt_loop_forever_mock.call_args[0]
  82. assert mqtt_client._tls_insecure is False
  83. # credentials
  84. assert mqtt_client._username is None
  85. assert mqtt_client._password is None
  86. # connect callback
  87. caplog.clear()
  88. mqtt_client.socket().getpeername.return_value = (mqtt_host, mqtt_port)
  89. with unittest.mock.patch(
  90. "paho.mqtt.client.Client.subscribe"
  91. ) as mqtt_subscribe_mock:
  92. mqtt_client.on_connect(mqtt_client, mqtt_client._userdata, {}, 0)
  93. state = mqtt_client._userdata
  94. assert (
  95. state._login_manager.connect_to_signal.call_args[1]["signal_name"]
  96. == "PrepareForShutdown"
  97. )
  98. mqtt_subscribe_mock.assert_called_once_with(mqtt_topic_prefix + "/poweroff")
  99. assert mqtt_client.on_message is None
  100. assert ( # pylint: disable=comparison-with-callable
  101. mqtt_client._on_message_filtered[mqtt_topic_prefix + "/poweroff"]
  102. == systemctl_mqtt._MQTT_TOPIC_SUFFIX_ACTION_MAPPING[
  103. "poweroff"
  104. ].mqtt_message_callback
  105. )
  106. assert caplog.records[0].levelno == logging.DEBUG
  107. assert caplog.records[0].message == "connected to MQTT broker {}:{}".format(
  108. mqtt_host, mqtt_port
  109. )
  110. assert caplog.records[1].levelno == logging.DEBUG
  111. assert caplog.records[1].message == "acquired shutdown inhibitor lock"
  112. assert caplog.records[2].levelno == logging.INFO
  113. assert caplog.records[2].message == "publishing 'false' on {}".format(
  114. mqtt_topic_prefix + "/preparing-for-shutdown"
  115. )
  116. assert caplog.records[3].levelno == logging.DEBUG
  117. assert (
  118. caplog.records[3].message
  119. == "publishing home assistant config on "
  120. + homeassistant_discovery_prefix
  121. + "/binary_sensor/"
  122. + homeassistant_node_id
  123. + "/preparing-for-shutdown/config"
  124. )
  125. assert caplog.records[4].levelno == logging.INFO
  126. assert caplog.records[4].message == "subscribing to {}".format(
  127. mqtt_topic_prefix + "/poweroff"
  128. )
  129. assert caplog.records[5].levelno == logging.DEBUG
  130. assert caplog.records[5].message == "registered MQTT callback for topic {}".format(
  131. mqtt_topic_prefix + "/poweroff"
  132. ) + " triggering {}".format(
  133. systemctl_mqtt._MQTT_TOPIC_SUFFIX_ACTION_MAPPING["poweroff"].action
  134. )
  135. # dbus loop started?
  136. glib_loop_mock.assert_called_once_with()
  137. # waited for mqtt loop to stop?
  138. assert mqtt_client._thread_terminate
  139. assert mqtt_client._thread is None
  140. @pytest.mark.parametrize("mqtt_host", ["mqtt-broker.local"])
  141. @pytest.mark.parametrize("mqtt_port", [1833])
  142. @pytest.mark.parametrize("mqtt_username", ["me"])
  143. @pytest.mark.parametrize("mqtt_password", [None, "secret"])
  144. @pytest.mark.parametrize("mqtt_topic_prefix", ["systemctl/host"])
  145. def test__run_authentication(
  146. mqtt_host, mqtt_port, mqtt_username, mqtt_password, mqtt_topic_prefix
  147. ):
  148. with unittest.mock.patch("socket.create_connection"), unittest.mock.patch(
  149. "ssl.SSLContext.wrap_socket"
  150. ) as ssl_wrap_socket_mock, unittest.mock.patch(
  151. "paho.mqtt.client.Client.loop_forever", autospec=True,
  152. ) as mqtt_loop_forever_mock, unittest.mock.patch(
  153. "gi.repository.GLib.MainLoop.run"
  154. ), unittest.mock.patch(
  155. "systemctl_mqtt._get_login_manager"
  156. ):
  157. ssl_wrap_socket_mock.return_value.send = len
  158. systemctl_mqtt._run(
  159. mqtt_host=mqtt_host,
  160. mqtt_port=mqtt_port,
  161. mqtt_username=mqtt_username,
  162. mqtt_password=mqtt_password,
  163. mqtt_topic_prefix=mqtt_topic_prefix,
  164. homeassistant_discovery_prefix="discovery-prefix",
  165. homeassistant_node_id="node-id",
  166. )
  167. assert mqtt_loop_forever_mock.call_count == 1
  168. (mqtt_client,) = mqtt_loop_forever_mock.call_args[0]
  169. assert mqtt_client._username.decode() == mqtt_username
  170. if mqtt_password:
  171. assert mqtt_client._password.decode() == mqtt_password
  172. else:
  173. assert mqtt_client._password is None
  174. def _initialize_mqtt_client(
  175. mqtt_host, mqtt_port, mqtt_topic_prefix
  176. ) -> paho.mqtt.client.Client:
  177. with unittest.mock.patch("socket.create_connection"), unittest.mock.patch(
  178. "ssl.SSLContext.wrap_socket",
  179. ) as ssl_wrap_socket_mock, unittest.mock.patch(
  180. "paho.mqtt.client.Client.loop_forever", autospec=True,
  181. ) as mqtt_loop_forever_mock, unittest.mock.patch(
  182. "gi.repository.GLib.MainLoop.run"
  183. ), unittest.mock.patch(
  184. "systemctl_mqtt._get_login_manager"
  185. ) as get_login_manager_mock:
  186. ssl_wrap_socket_mock.return_value.send = len
  187. get_login_manager_mock.return_value.Get.return_value = dbus.Boolean(False)
  188. systemctl_mqtt._run(
  189. mqtt_host=mqtt_host,
  190. mqtt_port=mqtt_port,
  191. mqtt_username=None,
  192. mqtt_password=None,
  193. mqtt_topic_prefix=mqtt_topic_prefix,
  194. homeassistant_discovery_prefix="discovery-prefix",
  195. homeassistant_node_id="node-id",
  196. )
  197. while threading.active_count() > 1:
  198. time.sleep(0.01)
  199. assert mqtt_loop_forever_mock.call_count == 1
  200. (mqtt_client,) = mqtt_loop_forever_mock.call_args[0]
  201. mqtt_client.socket().getpeername.return_value = (mqtt_host, mqtt_port)
  202. mqtt_client.on_connect(mqtt_client, mqtt_client._userdata, {}, 0)
  203. return mqtt_client
  204. @pytest.mark.parametrize("mqtt_host", ["mqtt-broker.local"])
  205. @pytest.mark.parametrize("mqtt_port", [1833])
  206. @pytest.mark.parametrize("mqtt_topic_prefix", ["systemctl/host", "system/command"])
  207. def test__client_handle_message(caplog, mqtt_host, mqtt_port, mqtt_topic_prefix):
  208. mqtt_client = _initialize_mqtt_client(
  209. mqtt_host=mqtt_host, mqtt_port=mqtt_port, mqtt_topic_prefix=mqtt_topic_prefix
  210. )
  211. caplog.clear()
  212. caplog.set_level(logging.DEBUG)
  213. poweroff_message = MQTTMessage(topic=mqtt_topic_prefix.encode() + b"/poweroff")
  214. with unittest.mock.patch.object(
  215. systemctl_mqtt._MQTT_TOPIC_SUFFIX_ACTION_MAPPING["poweroff"], "action",
  216. ) as poweroff_action_mock:
  217. mqtt_client._handle_on_message(poweroff_message)
  218. poweroff_action_mock.assert_called_once_with()
  219. assert all(r.levelno == logging.DEBUG for r in caplog.records)
  220. assert caplog.records[0].message == "received topic={} payload=b''".format(
  221. poweroff_message.topic
  222. )
  223. assert caplog.records[1].message.startswith("executing action poweroff")
  224. assert caplog.records[2].message.startswith("completed action poweroff")
  225. @pytest.mark.parametrize("mqtt_host", ["mqtt-broker.local"])
  226. @pytest.mark.parametrize("mqtt_port", [1833])
  227. @pytest.mark.parametrize("mqtt_password", ["secret"])
  228. def test__run_authentication_missing_username(mqtt_host, mqtt_port, mqtt_password):
  229. with unittest.mock.patch("paho.mqtt.client.Client"), unittest.mock.patch(
  230. "systemctl_mqtt._get_login_manager"
  231. ):
  232. with pytest.raises(ValueError):
  233. systemctl_mqtt._run(
  234. mqtt_host=mqtt_host,
  235. mqtt_port=mqtt_port,
  236. mqtt_username=None,
  237. mqtt_password=mqtt_password,
  238. mqtt_topic_prefix="prefix",
  239. homeassistant_discovery_prefix="discovery-prefix",
  240. homeassistant_node_id="node-id",
  241. )
  242. @pytest.mark.parametrize("mqtt_topic", ["system/command/poweroff"])
  243. @pytest.mark.parametrize("payload", [b"", b"junk"])
  244. def test_mqtt_message_callback_poweroff(caplog, mqtt_topic: str, payload: bytes):
  245. message = MQTTMessage(topic=mqtt_topic.encode())
  246. message.payload = payload
  247. with unittest.mock.patch.object(
  248. systemctl_mqtt._MQTT_TOPIC_SUFFIX_ACTION_MAPPING["poweroff"], "action",
  249. ) as action_mock, caplog.at_level(logging.DEBUG):
  250. systemctl_mqtt._MQTT_TOPIC_SUFFIX_ACTION_MAPPING[
  251. "poweroff"
  252. ].mqtt_message_callback(
  253. None, None, message # type: ignore
  254. )
  255. action_mock.assert_called_once_with()
  256. assert len(caplog.records) == 3
  257. assert caplog.records[0].levelno == logging.DEBUG
  258. assert caplog.records[0].message == (
  259. "received topic={} payload={!r}".format(mqtt_topic, payload)
  260. )
  261. assert caplog.records[1].levelno == logging.DEBUG
  262. assert caplog.records[1].message.startswith(
  263. "executing action {} ({!r})".format("poweroff", action_mock)
  264. )
  265. assert caplog.records[2].levelno == logging.DEBUG
  266. assert caplog.records[2].message.startswith(
  267. "completed action {} ({!r})".format("poweroff", action_mock)
  268. )
  269. @pytest.mark.parametrize("mqtt_topic", ["system/command/poweroff"])
  270. @pytest.mark.parametrize("payload", [b"", b"junk"])
  271. def test_mqtt_message_callback_poweroff_retained(
  272. caplog, mqtt_topic: str, payload: bytes
  273. ):
  274. message = MQTTMessage(topic=mqtt_topic.encode())
  275. message.payload = payload
  276. message.retain = True
  277. with unittest.mock.patch.object(
  278. systemctl_mqtt._MQTT_TOPIC_SUFFIX_ACTION_MAPPING["poweroff"], "action",
  279. ) as action_mock, caplog.at_level(logging.DEBUG):
  280. systemctl_mqtt._MQTT_TOPIC_SUFFIX_ACTION_MAPPING[
  281. "poweroff"
  282. ].mqtt_message_callback(
  283. None, None, message # type: ignore
  284. )
  285. action_mock.assert_not_called()
  286. assert len(caplog.records) == 2
  287. assert caplog.records[0].levelno == logging.DEBUG
  288. assert caplog.records[0].message == (
  289. "received topic={} payload={!r}".format(mqtt_topic, payload)
  290. )
  291. assert caplog.records[1].levelno == logging.INFO
  292. assert caplog.records[1].message == "ignoring retained message"