test_state_dbus.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 datetime
  18. import json
  19. import logging
  20. import re
  21. import typing
  22. import unittest.mock
  23. import jeepney.wrappers
  24. import pytest
  25. import systemctl_mqtt
  26. # pylint: disable=protected-access
  27. def test_shutdown_lock():
  28. lock_fd = unittest.mock.MagicMock(spec=jeepney.fds.FileDescriptor)
  29. with unittest.mock.patch(
  30. "systemctl_mqtt._dbus.login_manager.get_login_manager_proxy"
  31. ) as get_login_manager_mock:
  32. state = systemctl_mqtt._State(
  33. mqtt_topic_prefix="any",
  34. homeassistant_discovery_prefix=None,
  35. homeassistant_discovery_object_id=None,
  36. poweroff_delay=datetime.timedelta(),
  37. monitored_system_unit_names=[],
  38. )
  39. get_login_manager_mock.return_value.Inhibit.return_value = (lock_fd,)
  40. state.acquire_shutdown_lock()
  41. state._login_manager.Inhibit.assert_called_once_with(
  42. what="shutdown",
  43. who="systemctl-mqtt",
  44. why="Report shutdown via MQTT",
  45. mode="delay",
  46. )
  47. assert state._shutdown_lock == lock_fd
  48. lock_fd.close.assert_not_called()
  49. state.release_shutdown_lock()
  50. lock_fd.close.assert_called_once_with()
  51. @pytest.mark.asyncio
  52. @pytest.mark.parametrize("active", [True, False])
  53. async def test_preparing_for_shutdown_handler(active: bool) -> None:
  54. with unittest.mock.patch(
  55. "systemctl_mqtt._dbus.login_manager.get_login_manager_proxy"
  56. ):
  57. state = systemctl_mqtt._State(
  58. mqtt_topic_prefix="any",
  59. homeassistant_discovery_prefix="pre/fix",
  60. homeassistant_discovery_object_id="obj",
  61. poweroff_delay=datetime.timedelta(),
  62. monitored_system_unit_names=[],
  63. )
  64. mqtt_client_mock = unittest.mock.MagicMock()
  65. with unittest.mock.patch.object(
  66. state, "_publish_preparing_for_shutdown"
  67. ) as publish_mock, unittest.mock.patch.object(
  68. state, "acquire_shutdown_lock"
  69. ) as acquire_lock_mock, unittest.mock.patch.object(
  70. state, "release_shutdown_lock"
  71. ) as release_lock_mock:
  72. await state.preparing_for_shutdown_handler(
  73. active=active, mqtt_client=mqtt_client_mock
  74. )
  75. publish_mock.assert_awaited_once_with(mqtt_client=mqtt_client_mock, active=active)
  76. if active:
  77. acquire_lock_mock.assert_not_called()
  78. release_lock_mock.assert_called_once_with()
  79. else:
  80. acquire_lock_mock.assert_called_once_with()
  81. release_lock_mock.assert_not_called()
  82. @pytest.mark.asyncio
  83. @pytest.mark.parametrize("active", [True, False])
  84. async def test_publish_preparing_for_shutdown(active: bool) -> None:
  85. login_manager_mock = unittest.mock.MagicMock()
  86. login_manager_mock.Get.return_value = (("b", active),)[:]
  87. with unittest.mock.patch(
  88. "systemctl_mqtt._dbus.login_manager.get_login_manager_proxy",
  89. return_value=login_manager_mock,
  90. ):
  91. state = systemctl_mqtt._State(
  92. mqtt_topic_prefix="any",
  93. homeassistant_discovery_prefix="pre/fix",
  94. homeassistant_discovery_object_id="obj",
  95. poweroff_delay=datetime.timedelta(),
  96. monitored_system_unit_names=[],
  97. )
  98. assert state._login_manager == login_manager_mock
  99. mqtt_client_mock = unittest.mock.AsyncMock()
  100. await state.publish_preparing_for_shutdown(mqtt_client=mqtt_client_mock)
  101. login_manager_mock.Get.assert_called_once_with("PreparingForShutdown")
  102. mqtt_client_mock.publish.assert_awaited_once_with(
  103. topic="any/preparing-for-shutdown",
  104. payload="true" if active else "false",
  105. retain=False,
  106. )
  107. class DBusErrorResponseMock(jeepney.wrappers.DBusErrorResponse):
  108. # pylint: disable=missing-class-docstring,super-init-not-called
  109. def __init__(self, name: str, data: typing.Any):
  110. self.name = name
  111. self.data = data
  112. @pytest.mark.asyncio
  113. async def test_publish_preparing_for_shutdown_get_fail(caplog):
  114. login_manager_mock = unittest.mock.MagicMock()
  115. login_manager_mock.Get.side_effect = DBusErrorResponseMock("error", ("mocked",))
  116. with unittest.mock.patch(
  117. "systemctl_mqtt._dbus.login_manager.get_login_manager_proxy",
  118. return_value=login_manager_mock,
  119. ):
  120. state = systemctl_mqtt._State(
  121. mqtt_topic_prefix="any",
  122. homeassistant_discovery_prefix=None,
  123. homeassistant_discovery_object_id=None,
  124. poweroff_delay=datetime.timedelta(),
  125. monitored_system_unit_names=[],
  126. )
  127. mqtt_client_mock = unittest.mock.MagicMock()
  128. await state.publish_preparing_for_shutdown(mqtt_client=None)
  129. mqtt_client_mock.publish.assert_not_called()
  130. assert len(caplog.records) == 1
  131. assert caplog.records[0].levelno == logging.ERROR
  132. assert (
  133. caplog.records[0].message
  134. == "failed to read logind's PreparingForShutdown property: [error] ('mocked',)"
  135. )
  136. @pytest.mark.asyncio
  137. @pytest.mark.parametrize("topic_prefix", ["systemctl/hostname", "hostname/systemctl"])
  138. @pytest.mark.parametrize("discovery_prefix", ["homeassistant", "home/assistant"])
  139. @pytest.mark.parametrize("object_id", ["raspberrypi", "debian21"])
  140. @pytest.mark.parametrize("hostname", ["hostname", "host-name"])
  141. @pytest.mark.parametrize(
  142. "monitored_system_unit_names", [[], ["foo.service", "bar.service"]]
  143. )
  144. async def test_publish_homeassistant_device_config(
  145. topic_prefix: str,
  146. discovery_prefix: str,
  147. object_id: str,
  148. hostname: str,
  149. monitored_system_unit_names: typing.List[str],
  150. ) -> None:
  151. with unittest.mock.patch("jeepney.io.blocking.open_dbus_connection"):
  152. state = systemctl_mqtt._State(
  153. mqtt_topic_prefix=topic_prefix,
  154. homeassistant_discovery_prefix=discovery_prefix,
  155. homeassistant_discovery_object_id=object_id,
  156. poweroff_delay=datetime.timedelta(),
  157. monitored_system_unit_names=monitored_system_unit_names,
  158. )
  159. assert state.monitored_system_unit_names == monitored_system_unit_names
  160. mqtt_client = unittest.mock.AsyncMock()
  161. with unittest.mock.patch(
  162. "systemctl_mqtt._utils.get_hostname", return_value=hostname
  163. ):
  164. await state.publish_homeassistant_device_config(mqtt_client=mqtt_client)
  165. mqtt_client.publish.assert_called_once()
  166. publish_args, publish_kwargs = mqtt_client.publish.call_args
  167. assert not publish_args
  168. assert not publish_kwargs["retain"]
  169. assert (
  170. publish_kwargs["topic"] == discovery_prefix + "/device/" + object_id + "/config"
  171. )
  172. config = json.loads(publish_kwargs["payload"])
  173. assert re.match(r"\d+\.\d+\.", config["origin"].pop("sw_version"))
  174. assert config == {
  175. "origin": {
  176. "name": "systemctl-mqtt",
  177. "support_url": "https://github.com/fphammerle/systemctl-mqtt",
  178. },
  179. "device": {"identifiers": [hostname], "name": hostname},
  180. "availability": {"topic": topic_prefix + "/status"},
  181. "components": {
  182. "logind/preparing-for-shutdown": {
  183. "unique_id": f"systemctl-mqtt-{hostname}-logind-preparing-for-shutdown",
  184. "object_id": f"{hostname}_logind_preparing_for_shutdown",
  185. "name": "preparing for shutdown",
  186. "platform": "binary_sensor",
  187. "state_topic": topic_prefix + "/preparing-for-shutdown",
  188. "payload_on": "true",
  189. "payload_off": "false",
  190. },
  191. "logind/poweroff": {
  192. "unique_id": f"systemctl-mqtt-{hostname}-logind-poweroff",
  193. "object_id": f"{hostname}_logind_poweroff",
  194. "name": "poweroff",
  195. "platform": "button",
  196. "command_topic": f"{topic_prefix}/poweroff",
  197. },
  198. "logind/lock-all-sessions": {
  199. "unique_id": f"systemctl-mqtt-{hostname}-logind-lock-all-sessions",
  200. "object_id": f"{hostname}_logind_lock_all_sessions",
  201. "name": "lock all sessions",
  202. "platform": "button",
  203. "command_topic": f"{topic_prefix}/lock-all-sessions",
  204. },
  205. "logind/suspend": {
  206. "unique_id": f"systemctl-mqtt-{hostname}-logind-suspend",
  207. "object_id": f"{hostname}_logind_suspend",
  208. "name": "suspend",
  209. "platform": "button",
  210. "command_topic": f"{topic_prefix}/suspend",
  211. },
  212. }
  213. | {
  214. f"unit/system/{n}/active-state": {
  215. "unique_id": f"systemctl-mqtt-{hostname}-unit-system-{n}-active-state",
  216. "object_id": f"{hostname}_unit_system_{n}_active_state",
  217. "name": f"{n} active state",
  218. "platform": "sensor",
  219. "state_topic": f"{topic_prefix}/unit/system/{n}/active-state",
  220. }
  221. for n in monitored_system_unit_names
  222. },
  223. }