test_switchbot_curtain_motor.py 12 KB

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