test_switchbot_curtain_motor.py 10 KB

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