test_switchbot_curtain_motor.py 13 KB

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