test_switchbot_button_automator.py 8.5 KB

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