test_switchbot_curtain_motor.py 10 KB

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