1
0

test_switchbot_curtain_motor.py 13 KB

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