test_switchbot_curtain_motor.py 14 KB

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