test_switchbot_curtain_motor.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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()._battery_percent = battery_percent
  111. actor._get_device()._pos = position
  112. mqtt_client_mock = unittest.mock.MagicMock()
  113. with unittest.mock.patch("switchbot.SwitchbotCurtain.update") as update_mock:
  114. actor._update_and_report_device_info(
  115. mqtt_client=mqtt_client_mock, report_position=report_position
  116. )
  117. update_mock.assert_called_once_with()
  118. assert mqtt_client_mock.publish.call_count == (1 + report_position)
  119. assert (
  120. unittest.mock.call(
  121. topic="homeassistant/cover/switchbot-curtain/dummy/battery-percentage",
  122. payload=battery_percent_encoded,
  123. retain=True,
  124. )
  125. in mqtt_client_mock.publish.call_args_list
  126. )
  127. if report_position:
  128. assert (
  129. unittest.mock.call(
  130. topic="homeassistant/cover/switchbot-curtain/dummy/position",
  131. payload=position_encoded,
  132. retain=True,
  133. )
  134. in mqtt_client_mock.publish.call_args_list
  135. )
  136. @pytest.mark.parametrize(
  137. "exception",
  138. [
  139. PermissionError("bluepy-helper failed to enable low energy mode..."),
  140. bluepy.btle.BTLEManagementError("test"),
  141. ],
  142. )
  143. def test__update_and_report_device_info_update_error(exception):
  144. actor = _CurtainMotor(mac_address="dummy", retry_count=21, password=None)
  145. mqtt_client_mock = unittest.mock.MagicMock()
  146. with unittest.mock.patch.object(
  147. actor._get_device(), "update", side_effect=exception
  148. ), pytest.raises(type(exception)):
  149. actor._update_and_report_device_info(mqtt_client_mock, report_position=True)
  150. mqtt_client_mock.publish.assert_not_called()
  151. @pytest.mark.parametrize("mac_address", ["aa:bb:cc:dd:ee:ff", "aa:bb:cc:11:22:33"])
  152. @pytest.mark.parametrize("password", ["pa$$word", None])
  153. @pytest.mark.parametrize("retry_count", (2, 3))
  154. @pytest.mark.parametrize(
  155. ("message_payload", "action_name"),
  156. [
  157. (b"open", "switchbot.SwitchbotCurtain.open"),
  158. (b"OPEN", "switchbot.SwitchbotCurtain.open"),
  159. (b"Open", "switchbot.SwitchbotCurtain.open"),
  160. (b"close", "switchbot.SwitchbotCurtain.close"),
  161. (b"CLOSE", "switchbot.SwitchbotCurtain.close"),
  162. (b"Close", "switchbot.SwitchbotCurtain.close"),
  163. (b"stop", "switchbot.SwitchbotCurtain.stop"),
  164. (b"STOP", "switchbot.SwitchbotCurtain.stop"),
  165. (b"Stop", "switchbot.SwitchbotCurtain.stop"),
  166. ],
  167. )
  168. @pytest.mark.parametrize("update_device_info", [True, False])
  169. @pytest.mark.parametrize("command_successful", [True, False])
  170. def test_execute_command(
  171. caplog,
  172. mac_address,
  173. password,
  174. retry_count,
  175. message_payload,
  176. action_name,
  177. update_device_info,
  178. command_successful,
  179. ):
  180. with unittest.mock.patch(
  181. "switchbot.SwitchbotCurtain.__init__", return_value=None
  182. ) as device_init_mock, caplog.at_level(logging.INFO):
  183. actor = _CurtainMotor(
  184. mac_address=mac_address, retry_count=retry_count, password=password
  185. )
  186. with unittest.mock.patch.object(
  187. actor, "report_state"
  188. ) as report_mock, unittest.mock.patch(
  189. action_name, return_value=command_successful
  190. ) as action_mock, unittest.mock.patch.object(
  191. actor, "_update_and_report_device_info"
  192. ) as update_device_info_mock:
  193. actor.execute_command(
  194. mqtt_client="dummy",
  195. mqtt_message_payload=message_payload,
  196. update_device_info=update_device_info,
  197. )
  198. device_init_mock.assert_called_once_with(
  199. mac=mac_address, password=password, retry_count=retry_count, reverse_mode=True
  200. )
  201. action_mock.assert_called_once_with()
  202. if command_successful:
  203. state_str = {b"open": "opening", b"close": "closing", b"stop": "stopped"}[
  204. message_payload.lower()
  205. ]
  206. assert caplog.record_tuples == [
  207. (
  208. "switchbot_mqtt._actors",
  209. logging.INFO,
  210. f"switchbot curtain {mac_address} {state_str}",
  211. )
  212. ]
  213. report_mock.assert_called_once_with(
  214. mqtt_client="dummy",
  215. # https://www.home-assistant.io/integrations/cover.mqtt/#state_opening
  216. state={b"open": b"opening", b"close": b"closing", b"stop": b""}[
  217. message_payload.lower()
  218. ],
  219. )
  220. else:
  221. assert caplog.record_tuples == [
  222. (
  223. "switchbot_mqtt._actors",
  224. logging.ERROR,
  225. f"failed to {message_payload.decode().lower()} switchbot curtain {mac_address}",
  226. )
  227. ]
  228. report_mock.assert_not_called()
  229. if update_device_info and command_successful:
  230. update_device_info_mock.assert_called_once_with(
  231. mqtt_client="dummy",
  232. report_position=(action_name == "switchbot.SwitchbotCurtain.stop"),
  233. )
  234. else:
  235. update_device_info_mock.assert_not_called()
  236. @pytest.mark.parametrize("mac_address", ["aa:bb:cc:dd:ee:ff"])
  237. @pytest.mark.parametrize("password", ["secret"])
  238. @pytest.mark.parametrize("message_payload", [b"OEFFNEN", b""])
  239. def test_execute_command_invalid_payload(
  240. caplog, mac_address, password, message_payload
  241. ):
  242. with unittest.mock.patch(
  243. "switchbot.SwitchbotCurtain"
  244. ) as device_mock, caplog.at_level(logging.INFO):
  245. actor = _CurtainMotor(mac_address=mac_address, retry_count=7, password=password)
  246. with unittest.mock.patch.object(actor, "report_state") as report_mock:
  247. actor.execute_command(
  248. mqtt_client="dummy",
  249. mqtt_message_payload=message_payload,
  250. update_device_info=True,
  251. )
  252. device_mock.assert_called_once_with(
  253. mac=mac_address, password=password, retry_count=7, reverse_mode=True
  254. )
  255. assert not device_mock().mock_calls # no methods called
  256. report_mock.assert_not_called()
  257. assert caplog.record_tuples == [
  258. (
  259. "switchbot_mqtt._actors",
  260. logging.WARNING,
  261. f"unexpected payload {message_payload!r} (expected 'OPEN', 'CLOSE', or 'STOP')",
  262. )
  263. ]
  264. @pytest.mark.parametrize("mac_address", ["aa:bb:cc:dd:ee:ff"])
  265. @pytest.mark.parametrize("message_payload", [b"OPEN", b"CLOSE", b"STOP"])
  266. def test_execute_command_bluetooth_error(caplog, mac_address, message_payload):
  267. """
  268. paho.mqtt.python>=1.5.1 no longer implicitly suppresses exceptions in callbacks.
  269. verify pySwitchbot catches exceptions raised in bluetooth stack.
  270. https://github.com/Danielhiversen/pySwitchbot/blob/0.8.0/switchbot/__init__.py#L48
  271. https://github.com/Danielhiversen/pySwitchbot/blob/0.8.0/switchbot/__init__.py#L94
  272. """
  273. with unittest.mock.patch(
  274. "bluepy.btle.Peripheral",
  275. side_effect=bluepy.btle.BTLEDisconnectError(
  276. f"Failed to connect to peripheral {mac_address}, addr type: random"
  277. ),
  278. ), caplog.at_level(logging.ERROR):
  279. _CurtainMotor(
  280. mac_address=mac_address, retry_count=10, password="secret"
  281. ).execute_command(
  282. mqtt_client="dummy",
  283. mqtt_message_payload=message_payload,
  284. update_device_info=True,
  285. )
  286. assert caplog.record_tuples == [
  287. (
  288. "switchbot",
  289. logging.ERROR,
  290. "Switchbot communication failed. Stopping trying.",
  291. ),
  292. (
  293. "switchbot_mqtt._actors",
  294. logging.ERROR,
  295. f"failed to {message_payload.decode().lower()} switchbot curtain {mac_address}",
  296. ),
  297. ]