test_switchbot_button_automator.py 7.3 KB

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