test_switchbot_button_automator.py 7.4 KB

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