test_switchbot_curtain_motor.py 13 KB

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