test_mqtt.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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 socket
  20. import ssl
  21. import typing
  22. import unittest.mock
  23. import _pytest.logging # pylint: disable=import-private-name; typing
  24. import pytest
  25. import aiomqtt
  26. import bleak
  27. import bleak.backends.device
  28. from paho.mqtt.client import MQTT_ERR_NO_CONN
  29. # pylint: disable=import-private-name; internal
  30. import switchbot_mqtt
  31. import switchbot_mqtt._actors
  32. from switchbot_mqtt._actors import _ButtonAutomator, _CurtainMotor
  33. from switchbot_mqtt._actors.base import _MQTTControlledActor
  34. from switchbot_mqtt._utils import _MQTTTopicLevel, _MQTTTopicPlaceholder
  35. # pylint: disable=protected-access
  36. # pylint: disable=too-many-arguments; these are tests, no API
  37. @pytest.mark.asyncio
  38. async def test__listen(caplog: _pytest.logging.LogCaptureFixture) -> None:
  39. mqtt_client = unittest.mock.AsyncMock()
  40. messages_mock = unittest.mock.AsyncMock()
  41. async def _msg_iter() -> typing.AsyncIterator[aiomqtt.Message]:
  42. for topic, payload in [
  43. ("/foo", b"foo1"),
  44. ("/baz/21/bar", b"42/2"),
  45. ("/baz/bar", b"nope"),
  46. ("/foo", b"foo2"),
  47. ]:
  48. yield aiomqtt.Message(
  49. topic=topic,
  50. payload=payload,
  51. qos=0,
  52. retain=False,
  53. mid=0,
  54. properties=None,
  55. )
  56. messages_mock.__aenter__.return_value.__aiter__.side_effect = _msg_iter
  57. mqtt_client.messages = lambda: messages_mock
  58. callback_foo = unittest.mock.AsyncMock()
  59. callback_bar = unittest.mock.AsyncMock()
  60. with caplog.at_level(logging.DEBUG):
  61. await switchbot_mqtt._listen(
  62. mqtt_client=mqtt_client,
  63. topic_callbacks=(("/foo", callback_foo), ("/baz/+/bar", callback_bar)),
  64. mqtt_topic_prefix="whatever/",
  65. retry_count=3,
  66. device_passwords={},
  67. fetch_device_info=False,
  68. )
  69. mqtt_client.publish.assert_awaited_once_with(
  70. topic="whatever/switchbot-mqtt/status", payload="online", retain=True
  71. )
  72. messages_mock.__aenter__.assert_awaited_once_with()
  73. assert callback_foo.await_count == 2
  74. assert not callback_foo.await_args_list[0].args
  75. kwargs = callback_foo.await_args_list[0].kwargs
  76. assert kwargs["message"].topic.value == "/foo"
  77. assert kwargs["message"].payload == b"foo1"
  78. del kwargs["message"] # type: ignore
  79. assert kwargs == {
  80. "mqtt_client": mqtt_client,
  81. "mqtt_topic_prefix": "whatever/",
  82. "retry_count": 3,
  83. "device_passwords": {},
  84. "fetch_device_info": False,
  85. }
  86. assert callback_foo.await_args_list[1].kwargs["message"].payload == b"foo2"
  87. assert callback_bar.await_count == 1
  88. assert (
  89. callback_bar.await_args_list[0].kwargs["message"].topic.value == "/baz/21/bar"
  90. )
  91. assert callback_bar.await_args_list[0].kwargs["message"].payload == b"42/2"
  92. @pytest.mark.parametrize(
  93. ("socket_family", "peername", "peername_log"),
  94. [
  95. (socket.AF_INET, ("mqtt-broker.local", 1883), "mqtt-broker.local:1883"),
  96. # https://github.com/fphammerle/switchbot-mqtt/issues/42#issuecomment-1173909335
  97. (socket.AF_INET6, ("::1", 1883, 0, 0), "[::1]:1883"),
  98. ],
  99. )
  100. def test__log_mqtt_connected(
  101. caplog: _pytest.logging.LogCaptureFixture,
  102. socket_family: int, # socket.AddressFamily,
  103. peername: typing.Tuple[typing.Union[str, int]],
  104. peername_log: str,
  105. ) -> None:
  106. mqtt_client = unittest.mock.MagicMock()
  107. mqtt_client._client.socket().family = socket_family
  108. mqtt_client._client.socket().getpeername.return_value = peername
  109. with caplog.at_level(logging.INFO):
  110. switchbot_mqtt._log_mqtt_connected(mqtt_client)
  111. assert not caplog.records
  112. with caplog.at_level(logging.DEBUG):
  113. switchbot_mqtt._log_mqtt_connected(mqtt_client)
  114. assert caplog.record_tuples[0] == (
  115. "switchbot_mqtt",
  116. logging.DEBUG,
  117. f"connected to MQTT broker {peername_log}",
  118. )
  119. @pytest.mark.asyncio()
  120. @pytest.mark.parametrize("mqtt_host", ["mqtt-broker.local"])
  121. @pytest.mark.parametrize("mqtt_port", [1234])
  122. @pytest.mark.parametrize("retry_count", [3, 21])
  123. @pytest.mark.parametrize(
  124. "device_passwords",
  125. [{}, {"11:22:33:44:55:66": "password", "aa:bb:cc:dd:ee:ff": "secret"}],
  126. )
  127. @pytest.mark.parametrize("fetch_device_info", [True, False])
  128. async def test__run(
  129. caplog: _pytest.logging.LogCaptureFixture,
  130. mqtt_host: str,
  131. mqtt_port: int,
  132. retry_count: int,
  133. device_passwords: typing.Dict[str, str],
  134. fetch_device_info: bool,
  135. ) -> None:
  136. with unittest.mock.patch("aiomqtt.Client") as mqtt_client_mock, unittest.mock.patch(
  137. "switchbot_mqtt._log_mqtt_connected"
  138. ) as log_connected_mock, unittest.mock.patch(
  139. "switchbot_mqtt._listen"
  140. ) as listen_mock, caplog.at_level(
  141. logging.DEBUG
  142. ):
  143. await switchbot_mqtt._run(
  144. mqtt_host=mqtt_host,
  145. mqtt_port=mqtt_port,
  146. mqtt_disable_tls=False,
  147. mqtt_username=None,
  148. mqtt_password=None,
  149. mqtt_topic_prefix="home/",
  150. retry_count=retry_count,
  151. device_passwords=device_passwords,
  152. fetch_device_info=fetch_device_info,
  153. )
  154. mqtt_client_mock.assert_called_once()
  155. assert not mqtt_client_mock.call_args.args
  156. init_kwargs = mqtt_client_mock.call_args.kwargs
  157. assert isinstance(init_kwargs.pop("tls_context"), ssl.SSLContext)
  158. assert init_kwargs.pop("will") == aiomqtt.Will(
  159. topic="home/switchbot-mqtt/status",
  160. payload="offline",
  161. qos=0,
  162. retain=True,
  163. properties=None,
  164. )
  165. assert init_kwargs == {
  166. "hostname": mqtt_host,
  167. "port": mqtt_port,
  168. "username": None,
  169. "password": None,
  170. }
  171. log_connected_mock.assert_called_once()
  172. subscribe_mock = mqtt_client_mock().__aenter__.return_value.subscribe
  173. assert subscribe_mock.await_count == (5 if fetch_device_info else 3)
  174. subscribe_mock.assert_has_awaits(
  175. (
  176. unittest.mock.call(topic)
  177. for topic in [
  178. "home/switch/switchbot/+/set",
  179. "home/cover/switchbot-curtain/+/set",
  180. "home/cover/switchbot-curtain/+/position/set-percent",
  181. ]
  182. ),
  183. any_order=True,
  184. )
  185. if fetch_device_info:
  186. subscribe_mock.assert_has_awaits(
  187. (
  188. unittest.mock.call("home/switch/switchbot/+/request-device-info"),
  189. unittest.mock.call(
  190. "home/cover/switchbot-curtain/+/request-device-info"
  191. ),
  192. ),
  193. any_order=True,
  194. )
  195. listen_mock.assert_awaited_once()
  196. assert listen_mock.await_args is not None # for mypy
  197. assert not listen_mock.await_args.args
  198. listen_kwargs = listen_mock.await_args.kwargs
  199. assert (
  200. listen_kwargs.pop("mqtt_client") # type: ignore
  201. == mqtt_client_mock().__aenter__.return_value
  202. )
  203. topic_callbacks = listen_kwargs.pop("topic_callbacks") # type: ignore
  204. assert len(topic_callbacks) == (5 if fetch_device_info else 3)
  205. assert (
  206. "home/switch/switchbot/+/set",
  207. switchbot_mqtt._actors._ButtonAutomator._mqtt_command_callback,
  208. ) in topic_callbacks
  209. assert (
  210. "home/cover/switchbot-curtain/+/set",
  211. switchbot_mqtt._actors._CurtainMotor._mqtt_command_callback,
  212. ) in topic_callbacks
  213. assert (
  214. "home/cover/switchbot-curtain/+/position/set-percent",
  215. switchbot_mqtt._actors._CurtainMotor._mqtt_set_position_callback,
  216. ) in topic_callbacks
  217. if fetch_device_info:
  218. assert (
  219. "home/switch/switchbot/+/request-device-info",
  220. switchbot_mqtt._actors._ButtonAutomator._mqtt_update_device_info_callback,
  221. ) in topic_callbacks
  222. assert (
  223. "home/cover/switchbot-curtain/+/request-device-info",
  224. switchbot_mqtt._actors._CurtainMotor._mqtt_update_device_info_callback,
  225. ) in topic_callbacks
  226. assert listen_kwargs == {
  227. "device_passwords": device_passwords,
  228. "fetch_device_info": fetch_device_info,
  229. "mqtt_topic_prefix": "home/",
  230. "retry_count": retry_count,
  231. }
  232. assert caplog.record_tuples[0] == (
  233. "switchbot_mqtt",
  234. logging.INFO,
  235. f"connecting to MQTT broker {mqtt_host}:{mqtt_port} (TLS enabled)",
  236. )
  237. assert len(caplog.record_tuples) == (5 if fetch_device_info else 3) + 1
  238. assert (
  239. "switchbot_mqtt._actors.base",
  240. logging.INFO,
  241. "subscribing to MQTT topic 'home/switch/switchbot/+/set'",
  242. ) in caplog.record_tuples
  243. assert (
  244. "switchbot_mqtt._actors.base",
  245. logging.INFO,
  246. "subscribing to MQTT topic 'home/cover/switchbot-curtain/+/set'",
  247. ) in caplog.record_tuples
  248. @pytest.mark.asyncio
  249. @pytest.mark.parametrize("mqtt_disable_tls", [True, False])
  250. async def test__run_tls(
  251. caplog: _pytest.logging.LogCaptureFixture, mqtt_disable_tls: bool
  252. ) -> None:
  253. with unittest.mock.patch("aiomqtt.Client") as mqtt_client_mock, unittest.mock.patch(
  254. "switchbot_mqtt._listen"
  255. ), caplog.at_level(logging.INFO):
  256. await switchbot_mqtt._run(
  257. mqtt_host="mqtt.local",
  258. mqtt_port=1234,
  259. mqtt_disable_tls=mqtt_disable_tls,
  260. mqtt_username=None,
  261. mqtt_password=None,
  262. mqtt_topic_prefix="prfx",
  263. retry_count=21,
  264. device_passwords={},
  265. fetch_device_info=True,
  266. )
  267. mqtt_client_mock.assert_called_once()
  268. assert not mqtt_client_mock.call_args.args
  269. kwargs = mqtt_client_mock.call_args.kwargs
  270. if mqtt_disable_tls:
  271. assert kwargs["tls_context"] is None
  272. assert caplog.record_tuples[0][2].endswith(" (TLS disabled)")
  273. else:
  274. assert isinstance(kwargs["tls_context"], ssl.SSLContext)
  275. assert caplog.record_tuples[0][2].endswith(" (TLS enabled)")
  276. @pytest.mark.asyncio
  277. @pytest.mark.parametrize("mqtt_host", ["mqtt-broker.local"])
  278. @pytest.mark.parametrize("mqtt_port", [1833])
  279. @pytest.mark.parametrize("mqtt_username", ["me"])
  280. @pytest.mark.parametrize("mqtt_password", [None, "secret"])
  281. async def test__run_authentication(
  282. mqtt_host: str,
  283. mqtt_port: int,
  284. mqtt_username: str,
  285. mqtt_password: typing.Optional[str],
  286. ) -> None:
  287. with unittest.mock.patch("aiomqtt.Client") as mqtt_client_mock, unittest.mock.patch(
  288. "switchbot_mqtt._listen"
  289. ):
  290. await switchbot_mqtt._run(
  291. mqtt_host=mqtt_host,
  292. mqtt_port=mqtt_port,
  293. mqtt_disable_tls=True,
  294. mqtt_username=mqtt_username,
  295. mqtt_password=mqtt_password,
  296. mqtt_topic_prefix="prfx",
  297. retry_count=7,
  298. device_passwords={},
  299. fetch_device_info=True,
  300. )
  301. mqtt_client_mock.assert_called_once()
  302. assert not mqtt_client_mock.call_args.args
  303. kwargs = mqtt_client_mock.call_args.kwargs
  304. assert kwargs["username"] == mqtt_username
  305. assert kwargs["password"] == mqtt_password
  306. @pytest.mark.asyncio
  307. @pytest.mark.parametrize("mqtt_host", ["mqtt-broker.local"])
  308. @pytest.mark.parametrize("mqtt_port", [1833])
  309. @pytest.mark.parametrize("mqtt_password", ["secret"])
  310. async def test__run_authentication_missing_username(
  311. mqtt_host: str, mqtt_port: int, mqtt_password: str
  312. ) -> None:
  313. with pytest.raises(ValueError, match=r"^Missing MQTT username$"):
  314. await switchbot_mqtt._run(
  315. mqtt_host=mqtt_host,
  316. mqtt_port=mqtt_port,
  317. mqtt_disable_tls=True,
  318. mqtt_username=None,
  319. mqtt_password=mqtt_password,
  320. mqtt_topic_prefix="whatever",
  321. retry_count=3,
  322. device_passwords={},
  323. fetch_device_info=True,
  324. )
  325. def _mock_actor_class(
  326. *,
  327. command_topic_levels: typing.Tuple[_MQTTTopicLevel, ...] = NotImplemented,
  328. request_info_levels: typing.Tuple[_MQTTTopicLevel, ...] = NotImplemented,
  329. ) -> typing.Type:
  330. class _ActorMock(_MQTTControlledActor):
  331. MQTT_COMMAND_TOPIC_LEVELS = command_topic_levels
  332. _MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS = request_info_levels
  333. def __init__(
  334. self,
  335. device: bleak.backends.device.BLEDevice,
  336. retry_count: int,
  337. password: typing.Optional[str],
  338. ) -> None:
  339. super().__init__(device=device, retry_count=retry_count, password=password)
  340. async def execute_command(
  341. self,
  342. *,
  343. mqtt_message_payload: bytes,
  344. mqtt_client: aiomqtt.Client,
  345. update_device_info: bool,
  346. mqtt_topic_prefix: str,
  347. ) -> None:
  348. pass
  349. def _get_device(self) -> None:
  350. return None
  351. return _ActorMock
  352. @pytest.mark.asyncio
  353. @pytest.mark.parametrize(
  354. ("topic_levels", "topic", "expected_mac_address"),
  355. [
  356. (
  357. switchbot_mqtt._actors._ButtonAutomator._MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS,
  358. "prfx/switch/switchbot/aa:bb:cc:dd:ee:ff/request-device-info",
  359. "aa:bb:cc:dd:ee:ff",
  360. ),
  361. ],
  362. )
  363. @pytest.mark.parametrize("payload", [b"", b"whatever"])
  364. async def test__mqtt_update_device_info_callback(
  365. caplog: _pytest.logging.LogCaptureFixture,
  366. topic_levels: typing.Tuple[_MQTTTopicLevel, ...],
  367. topic: str,
  368. expected_mac_address: str,
  369. payload: bytes,
  370. ) -> None:
  371. ActorMock = _mock_actor_class(request_info_levels=topic_levels)
  372. message = aiomqtt.Message(
  373. topic=topic, payload=payload, qos=0, retain=False, mid=0, properties=None
  374. )
  375. device = unittest.mock.Mock()
  376. with unittest.mock.patch.object(
  377. bleak.BleakScanner, "find_device_by_address", return_value=device
  378. ) as find_device_mock, unittest.mock.patch.object(
  379. ActorMock, "__init__", return_value=None
  380. ) as init_mock, unittest.mock.patch.object(
  381. ActorMock, "_update_and_report_device_info"
  382. ) as update_mock, caplog.at_level(
  383. logging.DEBUG
  384. ):
  385. await ActorMock._mqtt_update_device_info_callback(
  386. mqtt_client="client_dummy",
  387. message=message,
  388. mqtt_topic_prefix="prfx/",
  389. retry_count=21, # tested in test__mqtt_command_callback
  390. device_passwords={},
  391. fetch_device_info=True,
  392. )
  393. find_device_mock.assert_awaited_once_with(expected_mac_address)
  394. init_mock.assert_called_once_with(device=device, retry_count=21, password=None)
  395. update_mock.assert_called_once_with(
  396. mqtt_client="client_dummy", mqtt_topic_prefix="prfx/"
  397. )
  398. assert caplog.record_tuples == [
  399. (
  400. "switchbot_mqtt._actors.base",
  401. logging.DEBUG,
  402. f"received topic={topic} payload={payload!r}",
  403. )
  404. ]
  405. @pytest.mark.asyncio
  406. async def test__mqtt_update_device_info_callback_ignore_retained(
  407. caplog: _pytest.logging.LogCaptureFixture,
  408. ) -> None:
  409. ActorMock = _mock_actor_class(
  410. request_info_levels=(_MQTTTopicPlaceholder.MAC_ADDRESS, "request")
  411. )
  412. message = aiomqtt.Message(
  413. topic="aa:bb:cc:dd:ee:ff/request",
  414. payload=b"",
  415. qos=0,
  416. retain=True,
  417. mid=0,
  418. properties=None,
  419. )
  420. with unittest.mock.patch.object(
  421. ActorMock, "__init__", return_value=None
  422. ) as init_mock, unittest.mock.patch.object(
  423. ActorMock, "execute_command"
  424. ) as execute_command_mock, caplog.at_level(
  425. logging.DEBUG
  426. ):
  427. await ActorMock._mqtt_update_device_info_callback(
  428. mqtt_client="client_dummy",
  429. message=message,
  430. mqtt_topic_prefix="ignored",
  431. retry_count=21,
  432. device_passwords={},
  433. fetch_device_info=True,
  434. )
  435. init_mock.assert_not_called()
  436. execute_command_mock.assert_not_called()
  437. execute_command_mock.assert_not_awaited()
  438. assert caplog.record_tuples == [
  439. (
  440. "switchbot_mqtt._actors.base",
  441. logging.DEBUG,
  442. "received topic=aa:bb:cc:dd:ee:ff/request payload=b''",
  443. ),
  444. ("switchbot_mqtt._actors.base", logging.INFO, "ignoring retained message"),
  445. ]
  446. @pytest.mark.asyncio
  447. @pytest.mark.parametrize(
  448. (
  449. "topic_prefix",
  450. "command_topic_levels",
  451. "topic",
  452. "payload",
  453. "expected_mac_address",
  454. ),
  455. [
  456. (
  457. "homeassistant/",
  458. _ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS,
  459. "homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/set",
  460. b"ON",
  461. "aa:bb:cc:dd:ee:ff",
  462. ),
  463. (
  464. "homeassistant/",
  465. _ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS,
  466. "homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/set",
  467. b"OFF",
  468. "aa:bb:cc:dd:ee:ff",
  469. ),
  470. (
  471. "homeassistant/",
  472. _ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS,
  473. "homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/set",
  474. b"on",
  475. "aa:bb:cc:dd:ee:ff",
  476. ),
  477. (
  478. "homeassistant/",
  479. _ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS,
  480. "homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/set",
  481. b"off",
  482. "aa:bb:cc:dd:ee:ff",
  483. ),
  484. (
  485. "prefix-",
  486. _ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS,
  487. "prefix-switch/switchbot/aa:01:23:45:67:89/set",
  488. b"ON",
  489. "aa:01:23:45:67:89",
  490. ),
  491. (
  492. "",
  493. ["switchbot", _MQTTTopicPlaceholder.MAC_ADDRESS],
  494. "switchbot/aa:01:23:45:67:89",
  495. b"ON",
  496. "aa:01:23:45:67:89",
  497. ),
  498. (
  499. "homeassistant/",
  500. _CurtainMotor.MQTT_COMMAND_TOPIC_LEVELS,
  501. "homeassistant/cover/switchbot-curtain/aa:01:23:45:67:89/set",
  502. b"OPEN",
  503. "aa:01:23:45:67:89",
  504. ),
  505. ],
  506. )
  507. @pytest.mark.parametrize("retry_count", (3, 42))
  508. @pytest.mark.parametrize("fetch_device_info", [True, False])
  509. async def test__mqtt_command_callback(
  510. caplog: _pytest.logging.LogCaptureFixture,
  511. topic_prefix: str,
  512. command_topic_levels: typing.Tuple[_MQTTTopicLevel, ...],
  513. topic: str,
  514. payload: bytes,
  515. expected_mac_address: str,
  516. retry_count: int,
  517. fetch_device_info: bool,
  518. ) -> None:
  519. ActorMock = _mock_actor_class(command_topic_levels=command_topic_levels)
  520. message = aiomqtt.Message(
  521. topic=topic, payload=payload, qos=0, retain=False, mid=0, properties=None
  522. )
  523. device = unittest.mock.Mock()
  524. device.address = expected_mac_address
  525. with unittest.mock.patch.object(
  526. bleak.BleakScanner, "find_device_by_address", return_value=device
  527. ) as find_device_mock, unittest.mock.patch.object(
  528. ActorMock, "__init__", return_value=None
  529. ) as init_mock, unittest.mock.patch.object(
  530. ActorMock, "execute_command"
  531. ) as execute_command_mock, caplog.at_level(
  532. logging.DEBUG
  533. ):
  534. await ActorMock._mqtt_command_callback(
  535. mqtt_client="client_dummy",
  536. message=message,
  537. retry_count=retry_count,
  538. device_passwords={},
  539. fetch_device_info=fetch_device_info,
  540. mqtt_topic_prefix=topic_prefix,
  541. )
  542. find_device_mock.assert_awaited_once_with(expected_mac_address)
  543. init_mock.assert_called_once_with(
  544. device=device, retry_count=retry_count, password=None
  545. )
  546. execute_command_mock.assert_awaited_once_with(
  547. mqtt_client="client_dummy",
  548. mqtt_message_payload=payload,
  549. update_device_info=fetch_device_info,
  550. mqtt_topic_prefix=topic_prefix,
  551. )
  552. assert caplog.record_tuples == [
  553. (
  554. "switchbot_mqtt._actors.base",
  555. logging.DEBUG,
  556. f"received topic={topic} payload={payload!r}",
  557. )
  558. ]
  559. @pytest.mark.asyncio
  560. @pytest.mark.parametrize(
  561. ("mac_address", "expected_password"),
  562. [
  563. ("11:22:33:44:55:66", None),
  564. ("aa:bb:cc:dd:ee:ff", "secret"),
  565. ("11:22:33:dd:ee:ff", "äöü"),
  566. ],
  567. )
  568. async def test__mqtt_command_callback_password(
  569. mac_address: str, expected_password: typing.Optional[str]
  570. ) -> None:
  571. ActorMock = _mock_actor_class(
  572. command_topic_levels=("switchbot", _MQTTTopicPlaceholder.MAC_ADDRESS)
  573. )
  574. message = aiomqtt.Message(
  575. topic="prefix-switchbot/" + mac_address,
  576. payload=b"whatever",
  577. qos=0,
  578. retain=False,
  579. mid=0,
  580. properties=None,
  581. )
  582. device = unittest.mock.Mock()
  583. device.address = mac_address
  584. with unittest.mock.patch.object(
  585. bleak.BleakScanner, "find_device_by_address", return_value=device
  586. ) as find_device_mock, unittest.mock.patch.object(
  587. ActorMock, "__init__", return_value=None
  588. ) as init_mock, unittest.mock.patch.object(
  589. ActorMock, "execute_command"
  590. ) as execute_command_mock:
  591. await ActorMock._mqtt_command_callback(
  592. mqtt_client="client_dummy",
  593. message=message,
  594. retry_count=3,
  595. device_passwords={
  596. "11:22:33:44:55:77": "test",
  597. "aa:bb:cc:dd:ee:ff": "secret",
  598. "11:22:33:dd:ee:ff": "äöü",
  599. },
  600. fetch_device_info=True,
  601. mqtt_topic_prefix="prefix-",
  602. )
  603. find_device_mock.assert_awaited_once_with(mac_address)
  604. init_mock.assert_called_once_with(
  605. device=device, retry_count=3, password=expected_password
  606. )
  607. execute_command_mock.assert_awaited_once_with(
  608. mqtt_client="client_dummy",
  609. mqtt_message_payload=b"whatever",
  610. update_device_info=True,
  611. mqtt_topic_prefix="prefix-",
  612. )
  613. @pytest.mark.asyncio
  614. @pytest.mark.parametrize(
  615. ("topic", "payload"),
  616. [
  617. ("homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff", b"on"),
  618. ("homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/change", b"ON"),
  619. ("homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/set/suffix", b"ON"),
  620. ],
  621. )
  622. async def test__mqtt_command_callback_unexpected_topic(
  623. caplog: _pytest.logging.LogCaptureFixture, topic: str, payload: bytes
  624. ) -> None:
  625. ActorMock = _mock_actor_class(
  626. command_topic_levels=_ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS
  627. )
  628. message = aiomqtt.Message(
  629. topic=topic, payload=payload, qos=0, retain=False, mid=0, properties=None
  630. )
  631. with unittest.mock.patch.object(
  632. ActorMock, "__init__", return_value=None
  633. ) as init_mock, unittest.mock.patch.object(
  634. ActorMock, "execute_command"
  635. ) as execute_command_mock, caplog.at_level(
  636. logging.DEBUG
  637. ):
  638. await ActorMock._mqtt_command_callback(
  639. mqtt_client="client_dummy",
  640. message=message,
  641. retry_count=3,
  642. device_passwords={},
  643. fetch_device_info=True,
  644. mqtt_topic_prefix="homeassistant/",
  645. )
  646. init_mock.assert_not_called()
  647. execute_command_mock.assert_not_called()
  648. execute_command_mock.assert_not_awaited()
  649. assert caplog.record_tuples == [
  650. (
  651. "switchbot_mqtt._actors.base",
  652. logging.DEBUG,
  653. f"received topic={topic} payload={payload!r}",
  654. ),
  655. (
  656. "switchbot_mqtt._actors.base",
  657. logging.WARNING,
  658. f"unexpected topic {topic}",
  659. ),
  660. ]
  661. @pytest.mark.asyncio
  662. @pytest.mark.parametrize(("mac_address", "payload"), [("aa:01:23:4E:RR:OR", b"ON")])
  663. async def test__mqtt_command_callback_invalid_mac_address(
  664. caplog: _pytest.logging.LogCaptureFixture, mac_address: str, payload: bytes
  665. ) -> None:
  666. ActorMock = _mock_actor_class(
  667. command_topic_levels=_ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS
  668. )
  669. topic = f"mqttprefix-switch/switchbot/{mac_address}/set"
  670. message = aiomqtt.Message(
  671. topic=topic, payload=payload, qos=0, retain=False, mid=0, properties=None
  672. )
  673. with unittest.mock.patch.object(
  674. ActorMock, "__init__", return_value=None
  675. ) as init_mock, unittest.mock.patch.object(
  676. ActorMock, "execute_command"
  677. ) as execute_command_mock, caplog.at_level(
  678. logging.DEBUG
  679. ):
  680. await ActorMock._mqtt_command_callback(
  681. mqtt_client="client_dummy",
  682. message=message,
  683. retry_count=3,
  684. device_passwords={},
  685. fetch_device_info=True,
  686. mqtt_topic_prefix="mqttprefix-",
  687. )
  688. init_mock.assert_not_called()
  689. execute_command_mock.assert_not_called()
  690. assert caplog.record_tuples == [
  691. (
  692. "switchbot_mqtt._actors.base",
  693. logging.DEBUG,
  694. f"received topic={topic} payload={payload!r}",
  695. ),
  696. (
  697. "switchbot_mqtt._actors.base",
  698. logging.WARNING,
  699. f"invalid mac address {mac_address}",
  700. ),
  701. ]
  702. @pytest.mark.asyncio
  703. @pytest.mark.parametrize("mac_address", ["00:11:22:33:44:55", "aa:bb:cc:dd:ee:ff"])
  704. @pytest.mark.parametrize("payload", [b"ON"])
  705. async def test__mqtt_command_callback_device_not_found(
  706. caplog: _pytest.logging.LogCaptureFixture, mac_address: str, payload: bytes
  707. ) -> None:
  708. ActorMock = _mock_actor_class(
  709. command_topic_levels=_ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS
  710. )
  711. topic = f"prefix/switch/switchbot/{mac_address}/set"
  712. message = aiomqtt.Message(
  713. topic=topic, payload=payload, qos=0, retain=False, mid=0, properties=None
  714. )
  715. with unittest.mock.patch.object(
  716. bleak.BleakScanner, "find_device_by_address", return_value=None
  717. ), unittest.mock.patch.object(
  718. ActorMock, "__init__", return_value=None
  719. ) as init_mock, unittest.mock.patch.object(
  720. ActorMock, "execute_command"
  721. ) as execute_command_mock, caplog.at_level(
  722. logging.DEBUG
  723. ):
  724. await ActorMock._mqtt_command_callback(
  725. mqtt_client="client_dummy",
  726. message=message,
  727. retry_count=3,
  728. device_passwords={},
  729. fetch_device_info=True,
  730. mqtt_topic_prefix="prefix/",
  731. )
  732. init_mock.assert_not_called()
  733. execute_command_mock.assert_not_called()
  734. assert caplog.record_tuples == [
  735. (
  736. "switchbot_mqtt._actors.base",
  737. logging.DEBUG,
  738. f"received topic={topic} payload={payload!r}",
  739. ),
  740. (
  741. "switchbot_mqtt._actors.base",
  742. logging.ERROR,
  743. f"failed to find bluetooth low energy device with mac address {mac_address}",
  744. ),
  745. ]
  746. @pytest.mark.asyncio
  747. @pytest.mark.parametrize(
  748. ("topic", "payload"),
  749. [("homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/set", b"ON")],
  750. )
  751. async def test__mqtt_command_callback_ignore_retained(
  752. caplog: _pytest.logging.LogCaptureFixture, topic: str, payload: bytes
  753. ) -> None:
  754. ActorMock = _mock_actor_class(
  755. command_topic_levels=_ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS
  756. )
  757. message = aiomqtt.Message(
  758. topic=topic, payload=payload, qos=0, retain=True, mid=0, properties=None
  759. )
  760. with unittest.mock.patch.object(
  761. ActorMock, "__init__", return_value=None
  762. ) as init_mock, unittest.mock.patch.object(
  763. ActorMock, "execute_command"
  764. ) as execute_command_mock, caplog.at_level(
  765. logging.DEBUG
  766. ):
  767. await ActorMock._mqtt_command_callback(
  768. mqtt_client="client_dummy",
  769. message=message,
  770. retry_count=4,
  771. device_passwords={},
  772. fetch_device_info=True,
  773. mqtt_topic_prefix="homeassistant/",
  774. )
  775. init_mock.assert_not_called()
  776. execute_command_mock.assert_not_called()
  777. execute_command_mock.assert_not_awaited()
  778. assert caplog.record_tuples == [
  779. (
  780. "switchbot_mqtt._actors.base",
  781. logging.DEBUG,
  782. f"received topic={topic} payload={payload!r}",
  783. ),
  784. ("switchbot_mqtt._actors.base", logging.INFO, "ignoring retained message"),
  785. ]
  786. @pytest.mark.asyncio
  787. @pytest.mark.parametrize(
  788. ("topic_prefix", "state_topic_levels", "mac_address", "expected_topic"),
  789. # https://www.home-assistant.io/docs/mqtt/discovery/#switches
  790. [
  791. (
  792. "homeassistant/",
  793. _ButtonAutomator.MQTT_STATE_TOPIC_LEVELS,
  794. "aa:bb:cc:dd:ee:ff",
  795. "homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/state",
  796. ),
  797. (
  798. "",
  799. ["switchbot", _MQTTTopicPlaceholder.MAC_ADDRESS, "state"],
  800. "aa:bb:cc:dd:ee:gg",
  801. "switchbot/aa:bb:cc:dd:ee:gg/state",
  802. ),
  803. ],
  804. )
  805. @pytest.mark.parametrize("state", [b"ON", b"CLOSE"])
  806. @pytest.mark.parametrize("mqtt_publish_fails", [False, True])
  807. async def test__report_state(
  808. caplog: _pytest.logging.LogCaptureFixture,
  809. topic_prefix: str,
  810. state_topic_levels: typing.Tuple[_MQTTTopicLevel, ...],
  811. mac_address: str,
  812. expected_topic: str,
  813. state: bytes,
  814. mqtt_publish_fails: bool,
  815. ) -> None:
  816. # pylint: disable=too-many-arguments
  817. class _ActorMock(_MQTTControlledActor):
  818. MQTT_STATE_TOPIC_LEVELS = state_topic_levels
  819. def __init__(
  820. self,
  821. device: bleak.backends.device.BLEDevice,
  822. retry_count: int,
  823. password: typing.Optional[str],
  824. ) -> None:
  825. super().__init__(device=device, retry_count=retry_count, password=password)
  826. async def execute_command(
  827. self,
  828. *,
  829. mqtt_message_payload: bytes,
  830. mqtt_client: aiomqtt.Client,
  831. update_device_info: bool,
  832. mqtt_topic_prefix: str,
  833. ) -> None:
  834. pass
  835. def _get_device(self) -> None:
  836. return None
  837. mqtt_client_mock = unittest.mock.AsyncMock()
  838. if mqtt_publish_fails:
  839. # https://github.com/sbtinstruments/aiomqtt/blob/v1.2.1/aiomqtt/client.py#L678
  840. mqtt_client_mock.publish.side_effect = aiomqtt.MqttCodeError(
  841. MQTT_ERR_NO_CONN, "Could not publish message"
  842. )
  843. device = unittest.mock.Mock()
  844. device.address = mac_address
  845. with caplog.at_level(logging.DEBUG):
  846. actor = _ActorMock(device=device, retry_count=3, password=None)
  847. await actor.report_state(
  848. state=state, mqtt_client=mqtt_client_mock, mqtt_topic_prefix=topic_prefix
  849. )
  850. mqtt_client_mock.publish.assert_awaited_once_with(
  851. topic=expected_topic, payload=state, retain=True
  852. )
  853. assert caplog.record_tuples[0] == (
  854. "switchbot_mqtt._actors.base",
  855. logging.DEBUG,
  856. f"publishing topic={expected_topic} payload={state!r}",
  857. )
  858. if not mqtt_publish_fails:
  859. assert not caplog.records[1:]
  860. else:
  861. assert caplog.record_tuples[1:] == [
  862. (
  863. "switchbot_mqtt._actors.base",
  864. logging.ERROR,
  865. f"Failed to publish MQTT message on topic {expected_topic}:"
  866. " aiomqtt.MqttCodeError [code:4] The client is not currently connected.",
  867. )
  868. ]