test_switchbot_button_automator.py 7.6 KB

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