test_switchbot_button_automator.py 8.1 KB

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