test_switchbot_button_automator.py 8.3 KB

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