test_switchbot_curtain_motor.py 13 KB

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