test_mqtt.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. # systemctl-mqtt - MQTT client triggering 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 paho.mqtt.client
  22. import pytest
  23. from paho.mqtt.client import MQTTMessage
  24. import systemctl_mqtt
  25. # pylint: disable=protected-access
  26. @pytest.mark.parametrize("mqtt_host", ["mqtt-broker.local"])
  27. @pytest.mark.parametrize("mqtt_port", [1833])
  28. @pytest.mark.parametrize("mqtt_topic_prefix", ["systemctl/host", "system/command"])
  29. def test__run(caplog, mqtt_host, mqtt_port, mqtt_topic_prefix):
  30. caplog.set_level(logging.DEBUG)
  31. with unittest.mock.patch(
  32. "socket.create_connection"
  33. ) as create_socket_mock, unittest.mock.patch(
  34. "ssl.SSLContext.wrap_socket", autospec=True,
  35. ) as ssl_wrap_socket_mock, unittest.mock.patch(
  36. "paho.mqtt.client.Client.loop_forever", autospec=True,
  37. ) as mqtt_loop_forever_mock, unittest.mock.patch(
  38. "gi.repository.GLib.MainLoop.run"
  39. ) as glib_loop_mock:
  40. ssl_wrap_socket_mock.return_value.send = len
  41. systemctl_mqtt._run(
  42. mqtt_host=mqtt_host,
  43. mqtt_port=mqtt_port,
  44. mqtt_username=None,
  45. mqtt_password=None,
  46. mqtt_topic_prefix=mqtt_topic_prefix,
  47. )
  48. assert caplog.records[0].levelno == logging.INFO
  49. assert caplog.records[0].message == "connecting to MQTT broker {}:{}".format(
  50. mqtt_host, mqtt_port
  51. )
  52. # correct remote?
  53. assert create_socket_mock.call_count == 1
  54. create_socket_args, _ = create_socket_mock.call_args
  55. assert create_socket_args[0] == (mqtt_host, mqtt_port)
  56. # ssl enabled?
  57. assert ssl_wrap_socket_mock.call_count == 1
  58. ssl_context = ssl_wrap_socket_mock.call_args[0][0] # self
  59. assert ssl_context.check_hostname is True
  60. assert ssl_wrap_socket_mock.call_args[1]["server_hostname"] == mqtt_host
  61. # loop started?
  62. while threading.active_count() > 1:
  63. time.sleep(0.01)
  64. assert mqtt_loop_forever_mock.call_count == 1
  65. (mqtt_client,) = mqtt_loop_forever_mock.call_args[0]
  66. assert mqtt_client._tls_insecure is False
  67. # credentials
  68. assert mqtt_client._username is None
  69. assert mqtt_client._password is None
  70. # connect callback
  71. caplog.clear()
  72. mqtt_client.socket().getpeername.return_value = (mqtt_host, mqtt_port)
  73. with unittest.mock.patch(
  74. "paho.mqtt.client.Client.subscribe"
  75. ) as mqtt_subscribe_mock, unittest.mock.patch.object(
  76. mqtt_client._userdata, "acquire_shutdown_lock"
  77. ) as acquire_shutdown_lock_mock:
  78. mqtt_client.on_connect(mqtt_client, mqtt_client._userdata, {}, 0)
  79. acquire_shutdown_lock_mock.assert_called_once_with()
  80. mqtt_subscribe_mock.assert_called_once_with(mqtt_topic_prefix + "/poweroff")
  81. assert mqtt_client.on_message is None
  82. assert ( # pylint: disable=comparison-with-callable
  83. mqtt_client._on_message_filtered[mqtt_topic_prefix + "/poweroff"]
  84. == systemctl_mqtt._MQTT_TOPIC_SUFFIX_ACTION_MAPPING[
  85. "poweroff"
  86. ].mqtt_message_callback
  87. )
  88. assert caplog.records[0].levelno == logging.DEBUG
  89. assert caplog.records[0].message == "connected to MQTT broker {}:{}".format(
  90. mqtt_host, mqtt_port
  91. )
  92. assert caplog.records[1].levelno == logging.INFO
  93. assert caplog.records[1].message == "subscribing to {}".format(
  94. mqtt_topic_prefix + "/poweroff"
  95. )
  96. assert caplog.records[2].levelno == logging.DEBUG
  97. assert caplog.records[2].message == "registered MQTT callback for topic {}".format(
  98. mqtt_topic_prefix + "/poweroff"
  99. ) + " triggering {}".format(
  100. systemctl_mqtt._MQTT_TOPIC_SUFFIX_ACTION_MAPPING["poweroff"].action
  101. )
  102. # dbus loop started?
  103. glib_loop_mock.assert_called_once_with()
  104. # waited for mqtt loop to stop?
  105. assert mqtt_client._thread_terminate
  106. assert mqtt_client._thread is None
  107. @pytest.mark.parametrize("mqtt_host", ["mqtt-broker.local"])
  108. @pytest.mark.parametrize("mqtt_port", [1833])
  109. @pytest.mark.parametrize("mqtt_username", ["me"])
  110. @pytest.mark.parametrize("mqtt_password", [None, "secret"])
  111. @pytest.mark.parametrize("mqtt_topic_prefix", ["systemctl/host"])
  112. def test__run_authentication(
  113. mqtt_host, mqtt_port, mqtt_username, mqtt_password, mqtt_topic_prefix
  114. ):
  115. with unittest.mock.patch("socket.create_connection"), unittest.mock.patch(
  116. "ssl.SSLContext.wrap_socket"
  117. ) as ssl_wrap_socket_mock, unittest.mock.patch(
  118. "paho.mqtt.client.Client.loop_forever", autospec=True,
  119. ) as mqtt_loop_forever_mock, unittest.mock.patch(
  120. "gi.repository.GLib.MainLoop.run"
  121. ):
  122. ssl_wrap_socket_mock.return_value.send = len
  123. systemctl_mqtt._run(
  124. mqtt_host=mqtt_host,
  125. mqtt_port=mqtt_port,
  126. mqtt_username=mqtt_username,
  127. mqtt_password=mqtt_password,
  128. mqtt_topic_prefix=mqtt_topic_prefix,
  129. )
  130. assert mqtt_loop_forever_mock.call_count == 1
  131. (mqtt_client,) = mqtt_loop_forever_mock.call_args[0]
  132. assert mqtt_client._username.decode() == mqtt_username
  133. if mqtt_password:
  134. assert mqtt_client._password.decode() == mqtt_password
  135. else:
  136. assert mqtt_client._password is None
  137. def _initialize_mqtt_client(
  138. mqtt_host, mqtt_port, mqtt_topic_prefix
  139. ) -> paho.mqtt.client.Client:
  140. with unittest.mock.patch("socket.create_connection"), unittest.mock.patch(
  141. "ssl.SSLContext.wrap_socket",
  142. ) as ssl_wrap_socket_mock, unittest.mock.patch(
  143. "paho.mqtt.client.Client.loop_forever", autospec=True,
  144. ) as mqtt_loop_forever_mock, unittest.mock.patch(
  145. "gi.repository.GLib.MainLoop.run"
  146. ):
  147. ssl_wrap_socket_mock.return_value.send = len
  148. systemctl_mqtt._run(
  149. mqtt_host=mqtt_host,
  150. mqtt_port=mqtt_port,
  151. mqtt_username=None,
  152. mqtt_password=None,
  153. mqtt_topic_prefix=mqtt_topic_prefix,
  154. )
  155. while threading.active_count() > 1:
  156. time.sleep(0.01)
  157. assert mqtt_loop_forever_mock.call_count == 1
  158. (mqtt_client,) = mqtt_loop_forever_mock.call_args[0]
  159. mqtt_client.socket().getpeername.return_value = (mqtt_host, mqtt_port)
  160. mqtt_client.on_connect(mqtt_client, mqtt_client._userdata, {}, 0)
  161. return mqtt_client
  162. @pytest.mark.parametrize("mqtt_host", ["mqtt-broker.local"])
  163. @pytest.mark.parametrize("mqtt_port", [1833])
  164. @pytest.mark.parametrize("mqtt_topic_prefix", ["systemctl/host", "system/command"])
  165. def test__client_handle_message(caplog, mqtt_host, mqtt_port, mqtt_topic_prefix):
  166. mqtt_client = _initialize_mqtt_client(
  167. mqtt_host=mqtt_host, mqtt_port=mqtt_port, mqtt_topic_prefix=mqtt_topic_prefix
  168. )
  169. caplog.clear()
  170. caplog.set_level(logging.DEBUG)
  171. poweroff_message = MQTTMessage(topic=mqtt_topic_prefix.encode() + b"/poweroff")
  172. with unittest.mock.patch.object(
  173. systemctl_mqtt._MQTT_TOPIC_SUFFIX_ACTION_MAPPING["poweroff"], "action",
  174. ) as poweroff_action_mock:
  175. mqtt_client._handle_on_message(poweroff_message)
  176. poweroff_action_mock.assert_called_once_with()
  177. assert all(r.levelno == logging.DEBUG for r in caplog.records)
  178. assert caplog.records[0].message == "received topic={} payload=b''".format(
  179. poweroff_message.topic
  180. )
  181. assert caplog.records[1].message.startswith("executing action poweroff")
  182. assert caplog.records[2].message.startswith("completed action poweroff")
  183. @pytest.mark.parametrize("mqtt_host", ["mqtt-broker.local"])
  184. @pytest.mark.parametrize("mqtt_port", [1833])
  185. @pytest.mark.parametrize("mqtt_password", ["secret"])
  186. def test__run_authentication_missing_username(mqtt_host, mqtt_port, mqtt_password):
  187. with unittest.mock.patch("paho.mqtt.client.Client"):
  188. with pytest.raises(ValueError):
  189. systemctl_mqtt._run(
  190. mqtt_host=mqtt_host,
  191. mqtt_port=mqtt_port,
  192. mqtt_username=None,
  193. mqtt_password=mqtt_password,
  194. mqtt_topic_prefix="prefix",
  195. )
  196. @pytest.mark.parametrize("mqtt_topic", ["system/command/poweroff"])
  197. @pytest.mark.parametrize("payload", [b"", b"junk"])
  198. def test_mqtt_message_callback_poweroff(caplog, mqtt_topic: str, payload: bytes):
  199. message = MQTTMessage(topic=mqtt_topic.encode())
  200. message.payload = payload
  201. with unittest.mock.patch.object(
  202. systemctl_mqtt._MQTT_TOPIC_SUFFIX_ACTION_MAPPING["poweroff"], "action",
  203. ) as action_mock, caplog.at_level(logging.DEBUG):
  204. systemctl_mqtt._MQTT_TOPIC_SUFFIX_ACTION_MAPPING[
  205. "poweroff"
  206. ].mqtt_message_callback(
  207. None, None, message # type: ignore
  208. )
  209. action_mock.assert_called_once_with()
  210. assert len(caplog.records) == 3
  211. assert caplog.records[0].levelno == logging.DEBUG
  212. assert caplog.records[0].message == (
  213. "received topic={} payload={!r}".format(mqtt_topic, payload)
  214. )
  215. assert caplog.records[1].levelno == logging.DEBUG
  216. assert caplog.records[1].message.startswith(
  217. "executing action {} ({!r})".format("poweroff", action_mock)
  218. )
  219. assert caplog.records[2].levelno == logging.DEBUG
  220. assert caplog.records[2].message.startswith(
  221. "completed action {} ({!r})".format("poweroff", action_mock)
  222. )
  223. @pytest.mark.parametrize("mqtt_topic", ["system/command/poweroff"])
  224. @pytest.mark.parametrize("payload", [b"", b"junk"])
  225. def test_mqtt_message_callback_poweroff_retained(
  226. caplog, mqtt_topic: str, payload: bytes
  227. ):
  228. message = MQTTMessage(topic=mqtt_topic.encode())
  229. message.payload = payload
  230. message.retain = True
  231. with unittest.mock.patch.object(
  232. systemctl_mqtt._MQTT_TOPIC_SUFFIX_ACTION_MAPPING["poweroff"], "action",
  233. ) as action_mock, caplog.at_level(logging.DEBUG):
  234. systemctl_mqtt._MQTT_TOPIC_SUFFIX_ACTION_MAPPING[
  235. "poweroff"
  236. ].mqtt_message_callback(
  237. None, None, message # type: ignore
  238. )
  239. action_mock.assert_not_called()
  240. assert len(caplog.records) == 2
  241. assert caplog.records[0].levelno == logging.DEBUG
  242. assert caplog.records[0].message == (
  243. "received topic={} payload={!r}".format(mqtt_topic, payload)
  244. )
  245. assert caplog.records[1].levelno == logging.INFO
  246. assert caplog.records[1].message == "ignoring retained message"
  247. def test_shutdown_lock():
  248. settings = systemctl_mqtt._Settings(mqtt_topic_prefix="any")
  249. lock_fd = unittest.mock.MagicMock()
  250. with unittest.mock.patch(
  251. "systemctl_mqtt._get_login_manager"
  252. ) as get_login_manager_mock:
  253. get_login_manager_mock.return_value.Inhibit.return_value = lock_fd
  254. settings.acquire_shutdown_lock()
  255. get_login_manager_mock.return_value.Inhibit.assert_called_once_with(
  256. "shutdown", "systemctl-mqtt", "Report shutdown via MQTT", "delay",
  257. )
  258. assert settings._shutdown_lock == lock_fd
  259. # https://dbus.freedesktop.org/doc/dbus-python/dbus.types.html#dbus.types.UnixFd.take
  260. lock_fd.take.return_value = "fdnum"
  261. with unittest.mock.patch("os.close") as close_mock:
  262. settings.release_shutdown_lock()
  263. close_mock.assert_called_once_with("fdnum")