test_switchbot_button_automator.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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
  25. import bluepy.btle
  26. import pytest
  27. from switchbot_mqtt._actors import _ButtonAutomator
  28. @pytest.mark.parametrize("prefix", ["homeassistant/", "prefix-", ""])
  29. @pytest.mark.parametrize("mac_address", ["{MAC_ADDRESS}", "aa:bb:cc:dd:ee:ff"])
  30. def test_get_mqtt_battery_percentage_topic(prefix: str, mac_address: str) -> None:
  31. assert (
  32. _ButtonAutomator.get_mqtt_battery_percentage_topic(
  33. prefix=prefix, mac_address=mac_address
  34. )
  35. == f"{prefix}switch/switchbot/{mac_address}/battery-percentage"
  36. )
  37. @pytest.mark.parametrize("topic_prefix", ["homeassistant/", "prefix-", ""])
  38. @pytest.mark.parametrize(("battery_percent", "battery_percent_encoded"), [(42, b"42")])
  39. def test__update_and_report_device_info(
  40. topic_prefix: str, battery_percent: int, battery_percent_encoded: bytes
  41. ) -> None:
  42. with unittest.mock.patch("switchbot.SwitchbotCurtain.__init__", return_value=None):
  43. actor = _ButtonAutomator(mac_address="dummy", retry_count=21, password=None)
  44. actor._get_device()._switchbot_device_data = {"data": {"battery": battery_percent}}
  45. mqtt_client_mock = unittest.mock.MagicMock()
  46. with unittest.mock.patch("switchbot.Switchbot.update") as update_mock:
  47. actor._update_and_report_device_info(
  48. mqtt_client=mqtt_client_mock, mqtt_topic_prefix=topic_prefix
  49. )
  50. update_mock.assert_called_once_with()
  51. mqtt_client_mock.publish.assert_called_once_with(
  52. topic=f"{topic_prefix}switch/switchbot/dummy/battery-percentage",
  53. payload=battery_percent_encoded,
  54. retain=True,
  55. )
  56. @pytest.mark.parametrize("topic_prefix", ["homeassistant/"])
  57. @pytest.mark.parametrize("mac_address", ["aa:bb:cc:dd:ee:ff", "aa:bb:cc:11:22:33"])
  58. @pytest.mark.parametrize("password", (None, "secret"))
  59. @pytest.mark.parametrize("retry_count", (3, 21))
  60. @pytest.mark.parametrize(
  61. ("message_payload", "action_name"),
  62. [
  63. (b"on", "switchbot.Switchbot.turn_on"),
  64. (b"ON", "switchbot.Switchbot.turn_on"),
  65. (b"On", "switchbot.Switchbot.turn_on"),
  66. (b"off", "switchbot.Switchbot.turn_off"),
  67. (b"OFF", "switchbot.Switchbot.turn_off"),
  68. (b"Off", "switchbot.Switchbot.turn_off"),
  69. ],
  70. )
  71. @pytest.mark.parametrize("update_device_info", [True, False])
  72. @pytest.mark.parametrize("command_successful", [True, False])
  73. def test_execute_command(
  74. caplog: _pytest.logging.LogCaptureFixture,
  75. topic_prefix: str,
  76. mac_address: str,
  77. password: typing.Optional[str],
  78. retry_count: int,
  79. message_payload: bytes,
  80. action_name: str,
  81. update_device_info: bool,
  82. command_successful: bool,
  83. ) -> None:
  84. with unittest.mock.patch(
  85. "switchbot.Switchbot.__init__", return_value=None
  86. ) as device_init_mock, caplog.at_level(logging.INFO):
  87. actor = _ButtonAutomator(
  88. mac_address=mac_address, retry_count=retry_count, password=password
  89. )
  90. with unittest.mock.patch.object(
  91. actor, "report_state"
  92. ) as report_mock, unittest.mock.patch(
  93. action_name, return_value=command_successful
  94. ) as action_mock, unittest.mock.patch.object(
  95. actor, "_update_and_report_device_info"
  96. ) as update_device_info_mock:
  97. actor.execute_command(
  98. mqtt_client="dummy",
  99. mqtt_message_payload=message_payload,
  100. update_device_info=update_device_info,
  101. mqtt_topic_prefix=topic_prefix,
  102. )
  103. device_init_mock.assert_called_once_with(
  104. mac=mac_address, password=password, retry_count=retry_count
  105. )
  106. action_mock.assert_called_once_with()
  107. if command_successful:
  108. assert caplog.record_tuples == [
  109. (
  110. "switchbot_mqtt._actors",
  111. logging.INFO,
  112. f"switchbot {mac_address} turned {message_payload.decode().lower()}",
  113. )
  114. ]
  115. report_mock.assert_called_once_with(
  116. mqtt_client="dummy",
  117. mqtt_topic_prefix=topic_prefix,
  118. state=message_payload.upper(),
  119. )
  120. assert update_device_info_mock.call_count == (1 if update_device_info else 0)
  121. else:
  122. assert caplog.record_tuples == [
  123. (
  124. "switchbot_mqtt._actors",
  125. logging.ERROR,
  126. f"failed to turn {message_payload.decode().lower()} switchbot {mac_address}",
  127. )
  128. ]
  129. report_mock.assert_not_called()
  130. update_device_info_mock.assert_not_called()
  131. @pytest.mark.parametrize("mac_address", ["aa:bb:cc:dd:ee:ff"])
  132. @pytest.mark.parametrize("message_payload", [b"EIN", b""])
  133. def test_execute_command_invalid_payload(
  134. caplog: _pytest.logging.LogCaptureFixture, mac_address: str, message_payload: bytes
  135. ) -> None:
  136. with unittest.mock.patch("switchbot.Switchbot") as device_mock, caplog.at_level(
  137. logging.INFO
  138. ):
  139. actor = _ButtonAutomator(mac_address=mac_address, retry_count=21, password=None)
  140. with unittest.mock.patch.object(actor, "report_state") as report_mock:
  141. actor.execute_command(
  142. mqtt_client="dummy",
  143. mqtt_message_payload=message_payload,
  144. update_device_info=True,
  145. mqtt_topic_prefix="dummy",
  146. )
  147. device_mock.assert_called_once_with(mac=mac_address, retry_count=21, password=None)
  148. assert not device_mock().mock_calls # no methods called
  149. report_mock.assert_not_called()
  150. assert caplog.record_tuples == [
  151. (
  152. "switchbot_mqtt._actors",
  153. logging.WARNING,
  154. f"unexpected payload {message_payload!r} (expected 'ON' or 'OFF')",
  155. )
  156. ]
  157. @pytest.mark.parametrize("mac_address", ["aa:bb:cc:dd:ee:ff"])
  158. @pytest.mark.parametrize("message_payload", [b"ON", b"OFF"])
  159. def test_execute_command_bluetooth_error(
  160. caplog: _pytest.logging.LogCaptureFixture, mac_address: str, message_payload: bytes
  161. ) -> None:
  162. """
  163. paho.mqtt.python>=1.5.1 no longer implicitly suppresses exceptions in callbacks.
  164. verify pySwitchbot catches exceptions raised in bluetooth stack.
  165. https://github.com/Danielhiversen/pySwitchbot/blob/0.8.0/switchbot/__init__.py#L48
  166. https://github.com/Danielhiversen/pySwitchbot/blob/0.8.0/switchbot/__init__.py#L94
  167. """
  168. with unittest.mock.patch(
  169. "bluepy.btle.Peripheral",
  170. side_effect=bluepy.btle.BTLEDisconnectError(
  171. f"Failed to connect to peripheral {mac_address}, addr type: random"
  172. ),
  173. ), caplog.at_level(logging.ERROR):
  174. _ButtonAutomator(
  175. mac_address=mac_address, retry_count=0, password=None
  176. ).execute_command(
  177. mqtt_client="dummy",
  178. mqtt_message_payload=message_payload,
  179. update_device_info=True,
  180. mqtt_topic_prefix="dummy",
  181. )
  182. assert len(caplog.records) == 2
  183. assert caplog.records[0].name == "switchbot"
  184. assert caplog.records[0].levelno == logging.ERROR
  185. assert caplog.records[0].msg.startswith(
  186. # pySwitchbot<0.11 had '.' suffix
  187. "Switchbot communication failed. Stopping trying",
  188. )
  189. assert caplog.record_tuples[1] == (
  190. "switchbot_mqtt._actors",
  191. logging.ERROR,
  192. f"failed to turn {message_payload.decode().lower()} switchbot {mac_address}",
  193. )