test_state_dbus.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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.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. )
  38. get_login_manager_mock.return_value.Inhibit.return_value = (lock_fd,)
  39. state.acquire_shutdown_lock()
  40. state._login_manager.Inhibit.assert_called_once_with(
  41. what="shutdown",
  42. who="systemctl-mqtt",
  43. why="Report shutdown via MQTT",
  44. mode="delay",
  45. )
  46. assert state._shutdown_lock == lock_fd
  47. lock_fd.close.assert_not_called()
  48. state.release_shutdown_lock()
  49. lock_fd.close.assert_called_once_with()
  50. @pytest.mark.parametrize("active", [True, False])
  51. def test_publish_preparing_for_shutdown(active: bool) -> None:
  52. login_manager_mock = unittest.mock.MagicMock()
  53. login_manager_mock.Get.return_value = (("b", active),)[:]
  54. with unittest.mock.patch(
  55. "systemctl_mqtt._dbus.get_login_manager_proxy", return_value=login_manager_mock
  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. )
  63. assert state._login_manager == login_manager_mock
  64. mqtt_client_mock = unittest.mock.MagicMock()
  65. state.publish_preparing_for_shutdown(mqtt_client=mqtt_client_mock)
  66. login_manager_mock.Get.assert_called_once_with("PreparingForShutdown")
  67. mqtt_client_mock.publish.assert_called_once_with(
  68. topic="any/preparing-for-shutdown",
  69. payload="true" if active else "false",
  70. retain=True,
  71. )
  72. class DBusErrorResponseMock(jeepney.wrappers.DBusErrorResponse):
  73. # pylint: disable=missing-class-docstring,super-init-not-called
  74. def __init__(self, name: str, data: typing.Any):
  75. self.name = name
  76. self.data = data
  77. def test_publish_preparing_for_shutdown_get_fail(caplog):
  78. login_manager_mock = unittest.mock.MagicMock()
  79. login_manager_mock.Get.side_effect = DBusErrorResponseMock("error", ("mocked",))
  80. with unittest.mock.patch(
  81. "systemctl_mqtt._dbus.get_login_manager_proxy", return_value=login_manager_mock
  82. ):
  83. state = systemctl_mqtt._State(
  84. mqtt_topic_prefix="any",
  85. homeassistant_discovery_prefix=None,
  86. homeassistant_discovery_object_id=None,
  87. poweroff_delay=datetime.timedelta(),
  88. )
  89. mqtt_client_mock = unittest.mock.MagicMock()
  90. state.publish_preparing_for_shutdown(mqtt_client=None)
  91. mqtt_client_mock.publish.assert_not_called()
  92. assert len(caplog.records) == 1
  93. assert caplog.records[0].levelno == logging.ERROR
  94. assert (
  95. caplog.records[0].message
  96. == "failed to read logind's PreparingForShutdown property: [error] ('mocked',)"
  97. )
  98. @pytest.mark.parametrize("topic_prefix", ["systemctl/hostname", "hostname/systemctl"])
  99. @pytest.mark.parametrize("discovery_prefix", ["homeassistant", "home/assistant"])
  100. @pytest.mark.parametrize("object_id", ["raspberrypi", "debian21"])
  101. @pytest.mark.parametrize("hostname", ["hostname", "host-name"])
  102. def test_publish_homeassistant_device_config(
  103. topic_prefix, discovery_prefix, object_id, hostname
  104. ):
  105. with unittest.mock.patch("jeepney.io.blocking.open_dbus_connection"):
  106. state = systemctl_mqtt._State(
  107. mqtt_topic_prefix=topic_prefix,
  108. homeassistant_discovery_prefix=discovery_prefix,
  109. homeassistant_discovery_object_id=object_id,
  110. poweroff_delay=datetime.timedelta(),
  111. )
  112. mqtt_client = unittest.mock.MagicMock()
  113. with unittest.mock.patch(
  114. "systemctl_mqtt._utils.get_hostname", return_value=hostname
  115. ):
  116. state.publish_homeassistant_device_config(mqtt_client=mqtt_client)
  117. mqtt_client.publish.assert_called_once()
  118. publish_args, publish_kwargs = mqtt_client.publish.call_args
  119. assert not publish_args
  120. assert not publish_kwargs["retain"]
  121. assert (
  122. publish_kwargs["topic"] == discovery_prefix + "/device/" + object_id + "/config"
  123. )
  124. config = json.loads(publish_kwargs["payload"])
  125. assert re.match(r"\d+\.\d+\.", config["origin"].pop("sw_version"))
  126. assert config == {
  127. "origin": {
  128. "name": "systemctl-mqtt",
  129. "support_url": "https://github.com/fphammerle/systemctl-mqtt",
  130. },
  131. "device": {"identifiers": [hostname], "name": hostname},
  132. "components": {
  133. "logind/preparing-for-shutdown": {
  134. "unique_id": f"systemctl-mqtt-{hostname}-logind-preparing-for-shutdown",
  135. "object_id": f"{hostname}_logind_preparing_for_shutdown",
  136. "name": "preparing for shutdown",
  137. "platform": "binary_sensor",
  138. "state_topic": topic_prefix + "/preparing-for-shutdown",
  139. "payload_on": "true",
  140. "payload_off": "false",
  141. },
  142. "logind/poweroff": {
  143. "unique_id": f"systemctl-mqtt-{hostname}-logind-poweroff",
  144. "object_id": f"{hostname}_logind_poweroff",
  145. "name": "poweroff",
  146. "platform": "button",
  147. "command_topic": f"{topic_prefix}/poweroff",
  148. },
  149. "logind/lock-all-sessions": {
  150. "unique_id": f"systemctl-mqtt-{hostname}-logind-lock-all-sessions",
  151. "object_id": f"{hostname}_logind_lock_all_sessions",
  152. "name": "lock all sessions",
  153. "platform": "button",
  154. "command_topic": f"{topic_prefix}/lock-all-sessions",
  155. },
  156. },
  157. }