test_switchbot_curtain_motor.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. @pytest.mark.parametrize(
  25. "mac_address",
  26. ("aa:bb:cc:dd:ee:ff", "aa:bb:cc:dd:ee:gg"),
  27. )
  28. @pytest.mark.parametrize(
  29. ("position", "expected_payload"), [(0, b"0"), (100, b"100"), (42, b"42")]
  30. )
  31. def test__report_position(
  32. caplog, mac_address: str, position: int, expected_payload: bytes
  33. ):
  34. with unittest.mock.patch(
  35. "switchbot.SwitchbotCurtain.__init__", return_value=None
  36. ) as device_init_mock, caplog.at_level(logging.DEBUG):
  37. actor = switchbot_mqtt._CurtainMotor(mac_address=mac_address)
  38. device_init_mock.assert_called_once_with(
  39. mac=mac_address,
  40. # > The position of the curtain is saved in self._pos with 0 = open and 100 = closed.
  41. # > [...] The parameter 'reverse_mode' reverse these values, [...]
  42. # > The parameter is default set to True so that the definition of position
  43. # > is the same as in Home Assistant.
  44. # https://github.com/Danielhiversen/pySwitchbot/blob/0.10.0/switchbot/__init__.py#L150
  45. reverse_mode=True,
  46. )
  47. with unittest.mock.patch.object(
  48. actor, "_mqtt_publish"
  49. ) as publish_mock, unittest.mock.patch(
  50. "switchbot.SwitchbotCurtain.get_position", return_value=position
  51. ):
  52. actor._report_position(mqtt_client="dummy")
  53. publish_mock.assert_called_once_with(
  54. topic_levels=[
  55. "homeassistant",
  56. "cover",
  57. "switchbot-curtain",
  58. switchbot_mqtt._MQTTTopicPlaceholder.MAC_ADDRESS,
  59. "position",
  60. ],
  61. payload=expected_payload,
  62. mqtt_client="dummy",
  63. )
  64. assert not caplog.record_tuples
  65. @pytest.mark.parametrize("position", ("", 'lambda: print("")'))
  66. def test__report_position_invalid(caplog, position):
  67. with unittest.mock.patch(
  68. "switchbot.SwitchbotCurtain.__init__", return_value=None
  69. ), caplog.at_level(logging.DEBUG):
  70. actor = switchbot_mqtt._CurtainMotor(mac_address="aa:bb:cc:dd:ee:ff")
  71. with unittest.mock.patch.object(
  72. actor, "_mqtt_publish"
  73. ) as publish_mock, unittest.mock.patch(
  74. "switchbot.SwitchbotCurtain.get_position", return_value=position
  75. ), pytest.raises(
  76. ValueError
  77. ):
  78. actor._report_position(mqtt_client="dummy")
  79. publish_mock.assert_not_called()
  80. def test__update_position():
  81. with unittest.mock.patch("switchbot.SwitchbotCurtain.__init__", return_value=None):
  82. actor = switchbot_mqtt._CurtainMotor(mac_address="dummy")
  83. with unittest.mock.patch(
  84. "switchbot.SwitchbotCurtain.update"
  85. ) as update_mock, unittest.mock.patch.object(
  86. actor, "_report_position"
  87. ) as report_position_mock:
  88. actor._update_position(mqtt_client="client")
  89. update_mock.assert_called_once_with()
  90. report_position_mock.assert_called_once_with(mqtt_client="client")
  91. @pytest.mark.parametrize("mac_address", ["aa:bb:cc:dd:ee:ff", "aa:bb:cc:11:22:33"])
  92. @pytest.mark.parametrize(
  93. ("message_payload", "action_name"),
  94. [
  95. (b"open", "switchbot.SwitchbotCurtain.open"),
  96. (b"OPEN", "switchbot.SwitchbotCurtain.open"),
  97. (b"Open", "switchbot.SwitchbotCurtain.open"),
  98. (b"close", "switchbot.SwitchbotCurtain.close"),
  99. (b"CLOSE", "switchbot.SwitchbotCurtain.close"),
  100. (b"Close", "switchbot.SwitchbotCurtain.close"),
  101. (b"stop", "switchbot.SwitchbotCurtain.stop"),
  102. (b"STOP", "switchbot.SwitchbotCurtain.stop"),
  103. (b"Stop", "switchbot.SwitchbotCurtain.stop"),
  104. ],
  105. )
  106. @pytest.mark.parametrize("command_successful", [True, False])
  107. def test_execute_command(
  108. caplog, mac_address, message_payload, action_name, command_successful
  109. ):
  110. with unittest.mock.patch(
  111. "switchbot.SwitchbotCurtain.__init__", return_value=None
  112. ) as device_init_mock:
  113. actor = switchbot_mqtt._CurtainMotor(mac_address=mac_address)
  114. with unittest.mock.patch.object(
  115. actor, "report_state"
  116. ) as report_mock, unittest.mock.patch(
  117. action_name, return_value=command_successful
  118. ) as action_mock, unittest.mock.patch.object(
  119. actor, "_update_position"
  120. ) as update_position_mock, caplog.at_level(
  121. logging.INFO
  122. ):
  123. actor.execute_command(mqtt_client="dummy", mqtt_message_payload=message_payload)
  124. device_init_mock.assert_called_once_with(mac=mac_address, reverse_mode=True)
  125. action_mock.assert_called_once_with()
  126. if command_successful:
  127. assert caplog.record_tuples == [
  128. (
  129. "switchbot_mqtt",
  130. logging.INFO,
  131. "switchbot curtain {} {}".format(
  132. mac_address,
  133. {b"open": "opening", b"close": "closing", b"stop": "stopped"}[
  134. message_payload.lower()
  135. ],
  136. ),
  137. )
  138. ]
  139. report_mock.assert_called_once_with(
  140. mqtt_client="dummy",
  141. # https://www.home-assistant.io/integrations/cover.mqtt/#state_opening
  142. state={b"open": b"opening", b"close": b"closing", b"stop": b""}[
  143. message_payload.lower()
  144. ],
  145. )
  146. else:
  147. assert caplog.record_tuples == [
  148. (
  149. "switchbot_mqtt",
  150. logging.ERROR,
  151. "failed to {} switchbot curtain {}".format(
  152. message_payload.decode().lower(), mac_address
  153. ),
  154. )
  155. ]
  156. report_mock.assert_not_called()
  157. if action_name == "switchbot.SwitchbotCurtain.stop" and command_successful:
  158. update_position_mock.assert_called_once_with(mqtt_client="dummy")
  159. else:
  160. update_position_mock.assert_not_called()
  161. @pytest.mark.parametrize("mac_address", ["aa:bb:cc:dd:ee:ff"])
  162. @pytest.mark.parametrize("message_payload", [b"OEFFNEN", b""])
  163. def test_execute_command_invalid_payload(caplog, mac_address, message_payload):
  164. with unittest.mock.patch(
  165. "switchbot.SwitchbotCurtain"
  166. ) as device_mock, caplog.at_level(logging.INFO):
  167. actor = switchbot_mqtt._CurtainMotor(mac_address=mac_address)
  168. with unittest.mock.patch.object(actor, "report_state") as report_mock:
  169. actor.execute_command(
  170. mqtt_client="dummy", mqtt_message_payload=message_payload
  171. )
  172. device_mock.assert_called_once_with(mac=mac_address, reverse_mode=True)
  173. assert not device_mock().mock_calls # no methods called
  174. report_mock.assert_not_called()
  175. assert caplog.record_tuples == [
  176. (
  177. "switchbot_mqtt",
  178. logging.WARNING,
  179. "unexpected payload {!r} (expected 'OPEN', 'CLOSE', or 'STOP')".format(
  180. message_payload
  181. ),
  182. )
  183. ]
  184. @pytest.mark.parametrize("mac_address", ["aa:bb:cc:dd:ee:ff"])
  185. @pytest.mark.parametrize("message_payload", [b"OPEN", b"CLOSE", b"STOP"])
  186. def test_execute_command_bluetooth_error(caplog, mac_address, message_payload):
  187. """
  188. paho.mqtt.python>=1.5.1 no longer implicitly suppresses exceptions in callbacks.
  189. verify pySwitchbot catches exceptions raised in bluetooth stack.
  190. https://github.com/Danielhiversen/pySwitchbot/blob/0.8.0/switchbot/__init__.py#L48
  191. https://github.com/Danielhiversen/pySwitchbot/blob/0.8.0/switchbot/__init__.py#L94
  192. """
  193. with unittest.mock.patch(
  194. "bluepy.btle.Peripheral",
  195. side_effect=bluepy.btle.BTLEDisconnectError(
  196. "Failed to connect to peripheral {}, addr type: random".format(mac_address)
  197. ),
  198. ), caplog.at_level(logging.ERROR):
  199. switchbot_mqtt._CurtainMotor(mac_address=mac_address).execute_command(
  200. mqtt_client="dummy", mqtt_message_payload=message_payload
  201. )
  202. assert caplog.record_tuples == [
  203. (
  204. "switchbot",
  205. logging.ERROR,
  206. "Switchbot communication failed. Stopping trying.",
  207. ),
  208. (
  209. "switchbot_mqtt",
  210. logging.ERROR,
  211. "failed to {} switchbot curtain {}".format(
  212. message_payload.decode().lower(), mac_address
  213. ),
  214. ),
  215. ]