test_switchbot_curtain_motor.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. @pytest.mark.parametrize("mac_address", ["aa:bb:cc:dd:ee:ff", "aa:bb:cc:11:22:33"])
  81. @pytest.mark.parametrize(
  82. ("message_payload", "action_name"),
  83. [
  84. (b"open", "switchbot.SwitchbotCurtain.open"),
  85. (b"OPEN", "switchbot.SwitchbotCurtain.open"),
  86. (b"Open", "switchbot.SwitchbotCurtain.open"),
  87. (b"close", "switchbot.SwitchbotCurtain.close"),
  88. (b"CLOSE", "switchbot.SwitchbotCurtain.close"),
  89. (b"Close", "switchbot.SwitchbotCurtain.close"),
  90. (b"stop", "switchbot.SwitchbotCurtain.stop"),
  91. (b"STOP", "switchbot.SwitchbotCurtain.stop"),
  92. (b"Stop", "switchbot.SwitchbotCurtain.stop"),
  93. ],
  94. )
  95. @pytest.mark.parametrize("command_successful", [True, False])
  96. def test_execute_command(
  97. caplog, mac_address, message_payload, action_name, command_successful
  98. ):
  99. with unittest.mock.patch(
  100. "switchbot.SwitchbotCurtain.__init__", return_value=None
  101. ) as device_init_mock, caplog.at_level(logging.INFO):
  102. actor = switchbot_mqtt._CurtainMotor(mac_address=mac_address)
  103. with unittest.mock.patch.object(
  104. actor, "report_state"
  105. ) as report_mock, unittest.mock.patch(
  106. action_name, return_value=command_successful
  107. ) as action_mock:
  108. actor.execute_command(
  109. mqtt_client="dummy", mqtt_message_payload=message_payload
  110. )
  111. device_init_mock.assert_called_once_with(mac=mac_address, reverse_mode=True)
  112. action_mock.assert_called_once_with()
  113. if command_successful:
  114. assert caplog.record_tuples == [
  115. (
  116. "switchbot_mqtt",
  117. logging.INFO,
  118. "switchbot curtain {} {}".format(
  119. mac_address,
  120. {b"open": "opening", b"close": "closing", b"stop": "stopped"}[
  121. message_payload.lower()
  122. ],
  123. ),
  124. )
  125. ]
  126. report_mock.assert_called_once_with(
  127. mqtt_client="dummy",
  128. # https://www.home-assistant.io/integrations/cover.mqtt/#state_opening
  129. state={b"open": b"opening", b"close": b"closing", b"stop": b""}[
  130. message_payload.lower()
  131. ],
  132. )
  133. else:
  134. assert caplog.record_tuples == [
  135. (
  136. "switchbot_mqtt",
  137. logging.ERROR,
  138. "failed to {} switchbot curtain {}".format(
  139. message_payload.decode().lower(), mac_address
  140. ),
  141. )
  142. ]
  143. report_mock.assert_not_called()
  144. @pytest.mark.parametrize("mac_address", ["aa:bb:cc:dd:ee:ff"])
  145. @pytest.mark.parametrize("message_payload", [b"OEFFNEN", b""])
  146. def test_execute_command_invalid_payload(caplog, mac_address, message_payload):
  147. with unittest.mock.patch(
  148. "switchbot.SwitchbotCurtain"
  149. ) as device_mock, caplog.at_level(logging.INFO):
  150. actor = switchbot_mqtt._CurtainMotor(mac_address=mac_address)
  151. with unittest.mock.patch.object(actor, "report_state") as report_mock:
  152. actor.execute_command(
  153. mqtt_client="dummy", mqtt_message_payload=message_payload
  154. )
  155. device_mock.assert_called_once_with(mac=mac_address, reverse_mode=True)
  156. assert not device_mock().mock_calls # no methods called
  157. report_mock.assert_not_called()
  158. assert caplog.record_tuples == [
  159. (
  160. "switchbot_mqtt",
  161. logging.WARNING,
  162. "unexpected payload {!r} (expected 'OPEN', 'CLOSE', or 'STOP')".format(
  163. message_payload
  164. ),
  165. )
  166. ]
  167. @pytest.mark.parametrize("mac_address", ["aa:bb:cc:dd:ee:ff"])
  168. @pytest.mark.parametrize("message_payload", [b"OPEN", b"CLOSE", b"STOP"])
  169. def test_execute_command_bluetooth_error(caplog, mac_address, message_payload):
  170. """
  171. paho.mqtt.python>=1.5.1 no longer implicitly suppresses exceptions in callbacks.
  172. verify pySwitchbot catches exceptions raised in bluetooth stack.
  173. https://github.com/Danielhiversen/pySwitchbot/blob/0.8.0/switchbot/__init__.py#L48
  174. https://github.com/Danielhiversen/pySwitchbot/blob/0.8.0/switchbot/__init__.py#L94
  175. """
  176. with unittest.mock.patch(
  177. "bluepy.btle.Peripheral",
  178. side_effect=bluepy.btle.BTLEDisconnectError(
  179. "Failed to connect to peripheral {}, addr type: random".format(mac_address)
  180. ),
  181. ), caplog.at_level(logging.ERROR):
  182. switchbot_mqtt._CurtainMotor(mac_address=mac_address).execute_command(
  183. mqtt_client="dummy", mqtt_message_payload=message_payload
  184. )
  185. assert caplog.record_tuples == [
  186. (
  187. "switchbot",
  188. logging.ERROR,
  189. "Switchbot communication failed. Stopping trying.",
  190. ),
  191. (
  192. "switchbot_mqtt",
  193. logging.ERROR,
  194. "failed to {} switchbot curtain {}".format(
  195. message_payload.decode().lower(), mac_address
  196. ),
  197. ),
  198. ]