test_mqtt.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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 pytest
  23. from paho.mqtt.client import MQTT_ERR_QUEUE_SIZE, MQTT_ERR_SUCCESS, MQTTMessage, Client
  24. import switchbot_mqtt
  25. import switchbot_mqtt._actors
  26. from switchbot_mqtt._actors import _ButtonAutomator, _CurtainMotor
  27. from switchbot_mqtt._actors._base import _MQTTCallbackUserdata, _MQTTControlledActor
  28. from switchbot_mqtt._utils import _MQTTTopicLevel, _MQTTTopicPlaceholder
  29. # pylint: disable=protected-access
  30. # pylint: disable=too-many-arguments; these are tests, no API
  31. @pytest.mark.parametrize("mqtt_host", ["mqtt-broker.local"])
  32. @pytest.mark.parametrize("mqtt_port", [1833])
  33. @pytest.mark.parametrize("retry_count", [3, 21])
  34. @pytest.mark.parametrize(
  35. "device_passwords",
  36. [{}, {"11:22:33:44:55:66": "password", "aa:bb:cc:dd:ee:ff": "secret"}],
  37. )
  38. @pytest.mark.parametrize("fetch_device_info", [True, False])
  39. def test__run(
  40. caplog: _pytest.logging.LogCaptureFixture,
  41. mqtt_host: str,
  42. mqtt_port: int,
  43. retry_count: int,
  44. device_passwords: typing.Dict[str, str],
  45. fetch_device_info: bool,
  46. ) -> None:
  47. with unittest.mock.patch(
  48. "paho.mqtt.client.Client"
  49. ) as mqtt_client_mock, caplog.at_level(logging.DEBUG):
  50. switchbot_mqtt._run(
  51. mqtt_host=mqtt_host,
  52. mqtt_port=mqtt_port,
  53. mqtt_username=None,
  54. mqtt_password=None,
  55. mqtt_disable_tls=False,
  56. retry_count=retry_count,
  57. device_passwords=device_passwords,
  58. fetch_device_info=fetch_device_info,
  59. )
  60. mqtt_client_mock.assert_called_once()
  61. assert not mqtt_client_mock.call_args[0]
  62. assert set(mqtt_client_mock.call_args[1].keys()) == {"userdata"}
  63. userdata = mqtt_client_mock.call_args[1]["userdata"]
  64. assert userdata == _MQTTCallbackUserdata(
  65. retry_count=retry_count,
  66. device_passwords=device_passwords,
  67. fetch_device_info=fetch_device_info,
  68. )
  69. assert not mqtt_client_mock().username_pw_set.called
  70. mqtt_client_mock().tls_set.assert_called_once_with(ca_certs=None)
  71. mqtt_client_mock().connect.assert_called_once_with(host=mqtt_host, port=mqtt_port)
  72. mqtt_client_mock().socket().getpeername.return_value = (mqtt_host, mqtt_port)
  73. with caplog.at_level(logging.DEBUG):
  74. mqtt_client_mock().on_connect(mqtt_client_mock(), userdata, {}, 0)
  75. subscribe_mock = mqtt_client_mock().subscribe
  76. assert subscribe_mock.call_count == (5 if fetch_device_info else 3)
  77. for topic in [
  78. "homeassistant/switch/switchbot/+/set",
  79. "homeassistant/cover/switchbot-curtain/+/set",
  80. "homeassistant/cover/switchbot-curtain/+/position/set-percent",
  81. ]:
  82. assert unittest.mock.call(topic) in subscribe_mock.call_args_list
  83. for topic in [
  84. "homeassistant/switch/switchbot/+/request-device-info",
  85. "homeassistant/cover/switchbot-curtain/+/request-device-info",
  86. ]:
  87. assert (
  88. unittest.mock.call(topic) in subscribe_mock.call_args_list
  89. ) == fetch_device_info
  90. callbacks = {
  91. c[1]["sub"]: c[1]["callback"]
  92. for c in mqtt_client_mock().message_callback_add.call_args_list
  93. }
  94. assert ( # pylint: disable=comparison-with-callable; intended
  95. callbacks["homeassistant/cover/switchbot-curtain/+/position/set-percent"]
  96. == _CurtainMotor._mqtt_set_position_callback
  97. )
  98. mqtt_client_mock().loop_forever.assert_called_once_with()
  99. assert caplog.record_tuples[:2] == [
  100. (
  101. "switchbot_mqtt",
  102. logging.INFO,
  103. f"connecting to MQTT broker {mqtt_host}:{mqtt_port} (TLS enabled)",
  104. ),
  105. (
  106. "switchbot_mqtt",
  107. logging.DEBUG,
  108. f"connected to MQTT broker {mqtt_host}:{mqtt_port}",
  109. ),
  110. ]
  111. assert len(caplog.record_tuples) == (7 if fetch_device_info else 5)
  112. assert (
  113. "switchbot_mqtt._actors._base",
  114. logging.INFO,
  115. "subscribing to MQTT topic 'homeassistant/switch/switchbot/+/set'",
  116. ) in caplog.record_tuples
  117. assert (
  118. "switchbot_mqtt._actors._base",
  119. logging.INFO,
  120. "subscribing to MQTT topic 'homeassistant/cover/switchbot-curtain/+/set'",
  121. ) in caplog.record_tuples
  122. @pytest.mark.parametrize("mqtt_disable_tls", [True, False])
  123. def test__run_tls(
  124. caplog: _pytest.logging.LogCaptureFixture, mqtt_disable_tls: bool
  125. ) -> None:
  126. with unittest.mock.patch(
  127. "paho.mqtt.client.Client"
  128. ) as mqtt_client_mock, caplog.at_level(logging.INFO):
  129. switchbot_mqtt._run(
  130. mqtt_host="mqtt.local",
  131. mqtt_port=1234,
  132. mqtt_username=None,
  133. mqtt_password=None,
  134. mqtt_disable_tls=mqtt_disable_tls,
  135. retry_count=21,
  136. device_passwords={},
  137. fetch_device_info=True,
  138. )
  139. if mqtt_disable_tls:
  140. mqtt_client_mock().tls_set.assert_not_called()
  141. else:
  142. mqtt_client_mock().tls_set.assert_called_once_with(ca_certs=None)
  143. if mqtt_disable_tls:
  144. assert caplog.record_tuples[0][2].endswith(" (TLS disabled)")
  145. else:
  146. assert caplog.record_tuples[0][2].endswith(" (TLS enabled)")
  147. @pytest.mark.parametrize("mqtt_host", ["mqtt-broker.local"])
  148. @pytest.mark.parametrize("mqtt_port", [1833])
  149. @pytest.mark.parametrize("mqtt_username", ["me"])
  150. @pytest.mark.parametrize("mqtt_password", [None, "secret"])
  151. def test__run_authentication(
  152. mqtt_host: str,
  153. mqtt_port: int,
  154. mqtt_username: str,
  155. mqtt_password: typing.Optional[str],
  156. ) -> None:
  157. with unittest.mock.patch("paho.mqtt.client.Client") as mqtt_client_mock:
  158. switchbot_mqtt._run(
  159. mqtt_host=mqtt_host,
  160. mqtt_port=mqtt_port,
  161. mqtt_username=mqtt_username,
  162. mqtt_password=mqtt_password,
  163. mqtt_disable_tls=True,
  164. retry_count=7,
  165. device_passwords={},
  166. fetch_device_info=True,
  167. )
  168. mqtt_client_mock.assert_called_once_with(
  169. userdata=_MQTTCallbackUserdata(
  170. retry_count=7, device_passwords={}, fetch_device_info=True
  171. )
  172. )
  173. mqtt_client_mock().username_pw_set.assert_called_once_with(
  174. username=mqtt_username, password=mqtt_password
  175. )
  176. @pytest.mark.parametrize("mqtt_host", ["mqtt-broker.local"])
  177. @pytest.mark.parametrize("mqtt_port", [1833])
  178. @pytest.mark.parametrize("mqtt_password", ["secret"])
  179. def test__run_authentication_missing_username(
  180. mqtt_host: str, mqtt_port: int, mqtt_password: str
  181. ) -> None:
  182. with unittest.mock.patch("paho.mqtt.client.Client"):
  183. with pytest.raises(ValueError):
  184. switchbot_mqtt._run(
  185. mqtt_host=mqtt_host,
  186. mqtt_port=mqtt_port,
  187. mqtt_username=None,
  188. mqtt_password=mqtt_password,
  189. mqtt_disable_tls=True,
  190. retry_count=3,
  191. device_passwords={},
  192. fetch_device_info=True,
  193. )
  194. def _mock_actor_class(
  195. *,
  196. command_topic_levels: typing.Tuple[_MQTTTopicLevel, ...] = NotImplemented,
  197. request_info_levels: typing.Tuple[_MQTTTopicLevel, ...] = NotImplemented,
  198. ) -> typing.Type:
  199. class _ActorMock(_MQTTControlledActor):
  200. MQTT_COMMAND_TOPIC_LEVELS = command_topic_levels
  201. _MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS = request_info_levels
  202. def __init__(
  203. self, mac_address: str, retry_count: int, password: typing.Optional[str]
  204. ) -> None:
  205. super().__init__(
  206. mac_address=mac_address, retry_count=retry_count, password=password
  207. )
  208. def execute_command(
  209. self,
  210. mqtt_message_payload: bytes,
  211. mqtt_client: Client,
  212. update_device_info: bool,
  213. ) -> None:
  214. pass
  215. def _get_device(self) -> None:
  216. return None
  217. return _ActorMock
  218. @pytest.mark.parametrize(
  219. ("topic_levels", "topic", "expected_mac_address"),
  220. [
  221. (
  222. switchbot_mqtt._actors._ButtonAutomator._MQTT_UPDATE_DEVICE_INFO_TOPIC_LEVELS,
  223. b"homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/request-device-info",
  224. "aa:bb:cc:dd:ee:ff",
  225. ),
  226. ],
  227. )
  228. @pytest.mark.parametrize("payload", [b"", b"whatever"])
  229. def test__mqtt_update_device_info_callback(
  230. caplog: _pytest.logging.LogCaptureFixture,
  231. topic_levels: typing.Tuple[_MQTTTopicLevel, ...],
  232. topic: bytes,
  233. expected_mac_address: str,
  234. payload: bytes,
  235. ) -> None:
  236. ActorMock = _mock_actor_class(request_info_levels=topic_levels)
  237. message = MQTTMessage(topic=topic)
  238. message.payload = payload
  239. callback_userdata = _MQTTCallbackUserdata(
  240. retry_count=21, # tested in test__mqtt_command_callback
  241. device_passwords={},
  242. fetch_device_info=True,
  243. )
  244. with unittest.mock.patch.object(
  245. ActorMock, "__init__", return_value=None
  246. ) as init_mock, unittest.mock.patch.object(
  247. ActorMock, "_update_and_report_device_info"
  248. ) as update_mock, caplog.at_level(
  249. logging.DEBUG
  250. ):
  251. ActorMock._mqtt_update_device_info_callback(
  252. "client_dummy", callback_userdata, message
  253. )
  254. init_mock.assert_called_once_with(
  255. mac_address=expected_mac_address, retry_count=21, password=None
  256. )
  257. update_mock.assert_called_once_with("client_dummy")
  258. assert caplog.record_tuples == [
  259. (
  260. "switchbot_mqtt._actors._base",
  261. logging.DEBUG,
  262. f"received topic={topic.decode()} payload={payload!r}",
  263. )
  264. ]
  265. def test__mqtt_update_device_info_callback_ignore_retained(
  266. caplog: _pytest.logging.LogCaptureFixture,
  267. ) -> None:
  268. ActorMock = _mock_actor_class(
  269. request_info_levels=(_MQTTTopicPlaceholder.MAC_ADDRESS, "request")
  270. )
  271. message = MQTTMessage(topic=b"aa:bb:cc:dd:ee:ff/request")
  272. message.payload = b""
  273. message.retain = True
  274. with unittest.mock.patch.object(
  275. ActorMock, "__init__", return_value=None
  276. ) as init_mock, unittest.mock.patch.object(
  277. ActorMock, "execute_command"
  278. ) as execute_command_mock, caplog.at_level(
  279. logging.DEBUG
  280. ):
  281. ActorMock._mqtt_update_device_info_callback(
  282. "client_dummy",
  283. _MQTTCallbackUserdata(
  284. retry_count=21, device_passwords={}, fetch_device_info=True
  285. ),
  286. message,
  287. )
  288. init_mock.assert_not_called()
  289. execute_command_mock.assert_not_called()
  290. assert caplog.record_tuples == [
  291. (
  292. "switchbot_mqtt._actors._base",
  293. logging.DEBUG,
  294. "received topic=aa:bb:cc:dd:ee:ff/request payload=b''",
  295. ),
  296. ("switchbot_mqtt._actors._base", logging.INFO, "ignoring retained message"),
  297. ]
  298. @pytest.mark.parametrize(
  299. ("command_topic_levels", "topic", "payload", "expected_mac_address"),
  300. [
  301. (
  302. _ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS,
  303. b"homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/set",
  304. b"ON",
  305. "aa:bb:cc:dd:ee:ff",
  306. ),
  307. (
  308. _ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS,
  309. b"homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/set",
  310. b"OFF",
  311. "aa:bb:cc:dd:ee:ff",
  312. ),
  313. (
  314. _ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS,
  315. b"homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/set",
  316. b"on",
  317. "aa:bb:cc:dd:ee:ff",
  318. ),
  319. (
  320. _ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS,
  321. b"homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/set",
  322. b"off",
  323. "aa:bb:cc:dd:ee:ff",
  324. ),
  325. (
  326. _ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS,
  327. b"homeassistant/switch/switchbot/aa:01:23:45:67:89/set",
  328. b"ON",
  329. "aa:01:23:45:67:89",
  330. ),
  331. (
  332. ["switchbot", _MQTTTopicPlaceholder.MAC_ADDRESS],
  333. b"switchbot/aa:01:23:45:67:89",
  334. b"ON",
  335. "aa:01:23:45:67:89",
  336. ),
  337. (
  338. _CurtainMotor.MQTT_COMMAND_TOPIC_LEVELS,
  339. b"homeassistant/cover/switchbot-curtain/aa:01:23:45:67:89/set",
  340. b"OPEN",
  341. "aa:01:23:45:67:89",
  342. ),
  343. ],
  344. )
  345. @pytest.mark.parametrize("retry_count", (3, 42))
  346. @pytest.mark.parametrize("fetch_device_info", [True, False])
  347. def test__mqtt_command_callback(
  348. caplog: _pytest.logging.LogCaptureFixture,
  349. command_topic_levels: typing.Tuple[_MQTTTopicLevel, ...],
  350. topic: bytes,
  351. payload: bytes,
  352. expected_mac_address: str,
  353. retry_count: int,
  354. fetch_device_info: bool,
  355. ) -> None:
  356. ActorMock = _mock_actor_class(command_topic_levels=command_topic_levels)
  357. message = MQTTMessage(topic=topic)
  358. message.payload = payload
  359. callback_userdata = _MQTTCallbackUserdata(
  360. retry_count=retry_count,
  361. device_passwords={},
  362. fetch_device_info=fetch_device_info,
  363. )
  364. with unittest.mock.patch.object(
  365. ActorMock, "__init__", return_value=None
  366. ) as init_mock, unittest.mock.patch.object(
  367. ActorMock, "execute_command"
  368. ) as execute_command_mock, caplog.at_level(
  369. logging.DEBUG
  370. ):
  371. ActorMock._mqtt_command_callback("client_dummy", callback_userdata, message)
  372. init_mock.assert_called_once_with(
  373. mac_address=expected_mac_address, retry_count=retry_count, password=None
  374. )
  375. execute_command_mock.assert_called_once_with(
  376. mqtt_client="client_dummy",
  377. mqtt_message_payload=payload,
  378. update_device_info=fetch_device_info,
  379. )
  380. assert caplog.record_tuples == [
  381. (
  382. "switchbot_mqtt._actors._base",
  383. logging.DEBUG,
  384. f"received topic={topic.decode()} payload={payload!r}",
  385. )
  386. ]
  387. @pytest.mark.parametrize(
  388. ("mac_address", "expected_password"),
  389. [
  390. ("11:22:33:44:55:66", None),
  391. ("aa:bb:cc:dd:ee:ff", "secret"),
  392. ("11:22:33:dd:ee:ff", "äöü"),
  393. ],
  394. )
  395. def test__mqtt_command_callback_password(
  396. mac_address: str, expected_password: typing.Optional[str]
  397. ) -> None:
  398. ActorMock = _mock_actor_class(
  399. command_topic_levels=("switchbot", _MQTTTopicPlaceholder.MAC_ADDRESS)
  400. )
  401. message = MQTTMessage(topic=b"switchbot/" + mac_address.encode())
  402. message.payload = b"whatever"
  403. callback_userdata = _MQTTCallbackUserdata(
  404. retry_count=3,
  405. device_passwords={
  406. "11:22:33:44:55:77": "test",
  407. "aa:bb:cc:dd:ee:ff": "secret",
  408. "11:22:33:dd:ee:ff": "äöü",
  409. },
  410. fetch_device_info=True,
  411. )
  412. with unittest.mock.patch.object(
  413. ActorMock, "__init__", return_value=None
  414. ) as init_mock, unittest.mock.patch.object(
  415. ActorMock, "execute_command"
  416. ) as execute_command_mock:
  417. ActorMock._mqtt_command_callback("client_dummy", callback_userdata, message)
  418. init_mock.assert_called_once_with(
  419. mac_address=mac_address, retry_count=3, password=expected_password
  420. )
  421. execute_command_mock.assert_called_once_with(
  422. mqtt_client="client_dummy",
  423. mqtt_message_payload=b"whatever",
  424. update_device_info=True,
  425. )
  426. @pytest.mark.parametrize(
  427. ("topic", "payload"),
  428. [
  429. (b"homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff", b"on"),
  430. (b"homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/change", b"ON"),
  431. (b"homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/set/suffix", b"ON"),
  432. ],
  433. )
  434. def test__mqtt_command_callback_unexpected_topic(
  435. caplog: _pytest.logging.LogCaptureFixture, topic: bytes, payload: bytes
  436. ) -> None:
  437. ActorMock = _mock_actor_class(
  438. command_topic_levels=_ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS
  439. )
  440. message = MQTTMessage(topic=topic)
  441. message.payload = payload
  442. with unittest.mock.patch.object(
  443. ActorMock, "__init__", return_value=None
  444. ) as init_mock, unittest.mock.patch.object(
  445. ActorMock, "execute_command"
  446. ) as execute_command_mock, caplog.at_level(
  447. logging.DEBUG
  448. ):
  449. ActorMock._mqtt_command_callback(
  450. "client_dummy",
  451. _MQTTCallbackUserdata(
  452. retry_count=3, device_passwords={}, fetch_device_info=True
  453. ),
  454. message,
  455. )
  456. init_mock.assert_not_called()
  457. execute_command_mock.assert_not_called()
  458. assert caplog.record_tuples == [
  459. (
  460. "switchbot_mqtt._actors._base",
  461. logging.DEBUG,
  462. f"received topic={topic.decode()} payload={payload!r}",
  463. ),
  464. (
  465. "switchbot_mqtt._actors._base",
  466. logging.WARNING,
  467. f"unexpected topic {topic.decode()}",
  468. ),
  469. ]
  470. @pytest.mark.parametrize(("mac_address", "payload"), [("aa:01:23:4E:RR:OR", b"ON")])
  471. def test__mqtt_command_callback_invalid_mac_address(
  472. caplog: _pytest.logging.LogCaptureFixture, mac_address: str, payload: bytes
  473. ) -> None:
  474. ActorMock = _mock_actor_class(
  475. command_topic_levels=_ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS
  476. )
  477. topic = f"homeassistant/switch/switchbot/{mac_address}/set".encode()
  478. message = MQTTMessage(topic=topic)
  479. message.payload = payload
  480. with unittest.mock.patch.object(
  481. ActorMock, "__init__", return_value=None
  482. ) as init_mock, unittest.mock.patch.object(
  483. ActorMock, "execute_command"
  484. ) as execute_command_mock, caplog.at_level(
  485. logging.DEBUG
  486. ):
  487. ActorMock._mqtt_command_callback(
  488. "client_dummy",
  489. _MQTTCallbackUserdata(
  490. retry_count=3, device_passwords={}, fetch_device_info=True
  491. ),
  492. message,
  493. )
  494. init_mock.assert_not_called()
  495. execute_command_mock.assert_not_called()
  496. assert caplog.record_tuples == [
  497. (
  498. "switchbot_mqtt._actors._base",
  499. logging.DEBUG,
  500. f"received topic={topic.decode()} payload={payload!r}",
  501. ),
  502. (
  503. "switchbot_mqtt._actors._base",
  504. logging.WARNING,
  505. f"invalid mac address {mac_address}",
  506. ),
  507. ]
  508. @pytest.mark.parametrize(
  509. ("topic", "payload"),
  510. [(b"homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/set", b"ON")],
  511. )
  512. def test__mqtt_command_callback_ignore_retained(
  513. caplog: _pytest.logging.LogCaptureFixture, topic: bytes, payload: bytes
  514. ) -> None:
  515. ActorMock = _mock_actor_class(
  516. command_topic_levels=_ButtonAutomator.MQTT_COMMAND_TOPIC_LEVELS
  517. )
  518. message = MQTTMessage(topic=topic)
  519. message.payload = payload
  520. message.retain = True
  521. with unittest.mock.patch.object(
  522. ActorMock, "__init__", return_value=None
  523. ) as init_mock, unittest.mock.patch.object(
  524. ActorMock, "execute_command"
  525. ) as execute_command_mock, caplog.at_level(
  526. logging.DEBUG
  527. ):
  528. ActorMock._mqtt_command_callback(
  529. "client_dummy",
  530. _MQTTCallbackUserdata(
  531. retry_count=4, device_passwords={}, fetch_device_info=True
  532. ),
  533. message,
  534. )
  535. init_mock.assert_not_called()
  536. execute_command_mock.assert_not_called()
  537. assert caplog.record_tuples == [
  538. (
  539. "switchbot_mqtt._actors._base",
  540. logging.DEBUG,
  541. f"received topic={topic.decode()} payload={payload!r}",
  542. ),
  543. ("switchbot_mqtt._actors._base", logging.INFO, "ignoring retained message"),
  544. ]
  545. @pytest.mark.parametrize(
  546. ("state_topic_levels", "mac_address", "expected_topic"),
  547. # https://www.home-assistant.io/docs/mqtt/discovery/#switches
  548. [
  549. (
  550. _ButtonAutomator.MQTT_STATE_TOPIC_LEVELS,
  551. "aa:bb:cc:dd:ee:ff",
  552. "homeassistant/switch/switchbot/aa:bb:cc:dd:ee:ff/state",
  553. ),
  554. (
  555. ["switchbot", _MQTTTopicPlaceholder.MAC_ADDRESS, "state"],
  556. "aa:bb:cc:dd:ee:gg",
  557. "switchbot/aa:bb:cc:dd:ee:gg/state",
  558. ),
  559. ],
  560. )
  561. @pytest.mark.parametrize("state", [b"ON", b"CLOSE"])
  562. @pytest.mark.parametrize("return_code", [MQTT_ERR_SUCCESS, MQTT_ERR_QUEUE_SIZE])
  563. def test__report_state(
  564. caplog: _pytest.logging.LogCaptureFixture,
  565. state_topic_levels: typing.Tuple[_MQTTTopicLevel, ...],
  566. mac_address: str,
  567. expected_topic: str,
  568. state: bytes,
  569. return_code: int,
  570. ) -> None:
  571. # pylint: disable=too-many-arguments
  572. class _ActorMock(_MQTTControlledActor):
  573. MQTT_STATE_TOPIC_LEVELS = state_topic_levels
  574. def __init__(
  575. self, mac_address: str, retry_count: int, password: typing.Optional[str]
  576. ) -> None:
  577. super().__init__(
  578. mac_address=mac_address, retry_count=retry_count, password=password
  579. )
  580. def execute_command(
  581. self,
  582. mqtt_message_payload: bytes,
  583. mqtt_client: Client,
  584. update_device_info: bool,
  585. ) -> None:
  586. pass
  587. def _get_device(self) -> None:
  588. return None
  589. mqtt_client_mock = unittest.mock.MagicMock()
  590. mqtt_client_mock.publish.return_value.rc = return_code
  591. with caplog.at_level(logging.DEBUG):
  592. actor = _ActorMock(mac_address=mac_address, retry_count=3, password=None)
  593. actor.report_state(state=state, mqtt_client=mqtt_client_mock)
  594. mqtt_client_mock.publish.assert_called_once_with(
  595. topic=expected_topic, payload=state, retain=True
  596. )
  597. assert caplog.record_tuples[0] == (
  598. "switchbot_mqtt._actors._base",
  599. logging.DEBUG,
  600. f"publishing topic={expected_topic} payload={state!r}",
  601. )
  602. if return_code == MQTT_ERR_SUCCESS:
  603. assert not caplog.records[1:]
  604. else:
  605. assert caplog.record_tuples[1:] == [
  606. (
  607. "switchbot_mqtt._actors._base",
  608. logging.ERROR,
  609. f"Failed to publish MQTT message on topic {expected_topic} (rc={return_code})",
  610. )
  611. ]