test_switchbot_button_automator.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. # switchbot-mqtt - MQTT client controlling SwitchBot button & curtain automators,
  2. # compatible with home-assistant.io's MQTT Switch & Cover platform
  3. #
  4. # Copyright (C) 2020 Fabian Peter Hammerle <fabian@hammerle.me>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. # pylint: disable=protected-access
  19. # pylint: disable=too-many-arguments; these are tests, no API
  20. # pylint: disable=duplicate-code; similarities with tests for curtain motor
  21. import logging
  22. import typing
  23. import unittest.mock
  24. import _pytest.logging # pylint: disable=import-private-name; typing
  25. import pytest
  26. # pylint: disable=import-private-name; internal
  27. from switchbot_mqtt._actors import _ButtonAutomator
  28. # pylint: disable=too-many-positional-arguments; tests
  29. @pytest.mark.parametrize("prefix", ["homeassistant/", "prefix-", ""])
  30. @pytest.mark.parametrize("mac_address", ["{MAC_ADDRESS}", "aa:bb:cc:dd:ee:ff"])
  31. def test_get_mqtt_battery_percentage_topic(prefix: str, mac_address: str) -> None:
  32. assert (
  33. _ButtonAutomator.get_mqtt_battery_percentage_topic(
  34. prefix=prefix, mac_address=mac_address
  35. )
  36. == f"{prefix}switch/switchbot/{mac_address}/battery-percentage"
  37. )
  38. @pytest.mark.asyncio
  39. @pytest.mark.parametrize("topic_prefix", ["homeassistant/", "prefix-", ""])
  40. @pytest.mark.parametrize(("battery_percent", "battery_percent_encoded"), [(42, b"42")])
  41. async def test__update_and_report_device_info(
  42. topic_prefix: str, battery_percent: int, battery_percent_encoded: bytes
  43. ) -> None:
  44. device = unittest.mock.Mock()
  45. device.address = "dummy"
  46. with unittest.mock.patch("switchbot.Switchbot.__init__", return_value=None):
  47. actor = _ButtonAutomator(device=device, retry_count=21, password=None)
  48. actor._get_device().get_basic_info = unittest.mock.AsyncMock(
  49. return_value={"battery": battery_percent}
  50. )
  51. mqtt_client_mock = unittest.mock.AsyncMock()
  52. await actor._update_and_report_device_info(
  53. mqtt_client=mqtt_client_mock, mqtt_topic_prefix=topic_prefix
  54. )
  55. mqtt_client_mock.publish.assert_awaited_once_with(
  56. topic=f"{topic_prefix}switch/switchbot/dummy/battery-percentage",
  57. payload=battery_percent_encoded,
  58. retain=True,
  59. )
  60. @pytest.mark.asyncio
  61. @pytest.mark.parametrize("topic_prefix", ["homeassistant/"])
  62. @pytest.mark.parametrize("mac_address", ["aa:bb:cc:dd:ee:ff", "aa:bb:cc:11:22:33"])
  63. @pytest.mark.parametrize("password", (None, "secret"))
  64. @pytest.mark.parametrize("retry_count", (3, 21))
  65. @pytest.mark.parametrize(
  66. ("message_payload", "action_name"),
  67. [
  68. (b"on", "switchbot.Switchbot.turn_on"),
  69. (b"ON", "switchbot.Switchbot.turn_on"),
  70. (b"On", "switchbot.Switchbot.turn_on"),
  71. (b"off", "switchbot.Switchbot.turn_off"),
  72. (b"OFF", "switchbot.Switchbot.turn_off"),
  73. (b"Off", "switchbot.Switchbot.turn_off"),
  74. ],
  75. )
  76. @pytest.mark.parametrize("update_device_info", [True, False])
  77. @pytest.mark.parametrize("command_successful", [True, False])
  78. async def test_execute_command(
  79. caplog: _pytest.logging.LogCaptureFixture,
  80. topic_prefix: str,
  81. mac_address: str,
  82. password: typing.Optional[str],
  83. retry_count: int,
  84. message_payload: bytes,
  85. action_name: str,
  86. update_device_info: bool,
  87. command_successful: bool,
  88. ) -> None:
  89. # pylint: disable=too-many-locals
  90. device = unittest.mock.Mock()
  91. device.address = mac_address
  92. with unittest.mock.patch(
  93. "switchbot.Switchbot.__init__", return_value=None
  94. ) as device_init_mock, caplog.at_level(logging.INFO):
  95. actor = _ButtonAutomator(
  96. device=device, retry_count=retry_count, password=password
  97. )
  98. mqtt_client = unittest.mock.Mock()
  99. with unittest.mock.patch.object(
  100. actor, "report_state"
  101. ) as report_mock, unittest.mock.patch(
  102. action_name, return_value=command_successful
  103. ) as action_mock, unittest.mock.patch.object(
  104. actor, "_update_and_report_device_info"
  105. ) as update_device_info_mock:
  106. await actor.execute_command(
  107. mqtt_client=mqtt_client,
  108. mqtt_message_payload=message_payload,
  109. update_device_info=update_device_info,
  110. mqtt_topic_prefix=topic_prefix,
  111. )
  112. device_init_mock.assert_called_once_with(
  113. device=device, password=password, retry_count=retry_count
  114. )
  115. action_mock.assert_awaited_once_with()
  116. if command_successful:
  117. assert caplog.record_tuples == [
  118. (
  119. "switchbot_mqtt._actors",
  120. logging.INFO,
  121. f"switchbot {mac_address} turned {message_payload.decode().lower()}",
  122. )
  123. ]
  124. report_mock.assert_awaited_once_with(
  125. mqtt_client=mqtt_client,
  126. mqtt_topic_prefix=topic_prefix,
  127. state=message_payload.upper(),
  128. )
  129. assert update_device_info_mock.await_count == (1 if update_device_info else 0)
  130. else:
  131. assert caplog.record_tuples == [
  132. (
  133. "switchbot_mqtt._actors",
  134. logging.ERROR,
  135. f"failed to turn {message_payload.decode().lower()} switchbot {mac_address}",
  136. )
  137. ]
  138. report_mock.assert_not_called()
  139. update_device_info_mock.assert_not_called()
  140. @pytest.mark.asyncio
  141. @pytest.mark.parametrize("mac_address", ["aa:bb:cc:dd:ee:ff"])
  142. @pytest.mark.parametrize("message_payload", [b"EIN", b""])
  143. async def test_execute_command_invalid_payload(
  144. caplog: _pytest.logging.LogCaptureFixture, mac_address: str, message_payload: bytes
  145. ) -> None:
  146. device = unittest.mock.Mock()
  147. device.address = mac_address
  148. with unittest.mock.patch("switchbot.Switchbot") as device_mock, caplog.at_level(
  149. logging.INFO
  150. ):
  151. actor = _ButtonAutomator(device=device, retry_count=21, password=None)
  152. with unittest.mock.patch.object(actor, "report_state") as report_mock:
  153. await actor.execute_command(
  154. mqtt_client=unittest.mock.Mock(),
  155. mqtt_message_payload=message_payload,
  156. update_device_info=True,
  157. mqtt_topic_prefix="dummy",
  158. )
  159. device_mock.assert_called_once_with(device=device, retry_count=21, password=None)
  160. assert not device_mock().mock_calls # no methods called
  161. report_mock.assert_not_called()
  162. assert caplog.record_tuples == [
  163. (
  164. "switchbot_mqtt._actors",
  165. logging.WARNING,
  166. f"unexpected payload {message_payload!r} (expected 'ON' or 'OFF')",
  167. )
  168. ]