1
0

test_cli.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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 json
  19. import logging
  20. import pathlib
  21. import subprocess
  22. import typing
  23. import unittest.mock
  24. import _pytest.capture # pylint: disable=import-private-name; typing
  25. import pytest
  26. import switchbot_mqtt
  27. import switchbot_mqtt._cli
  28. # pylint: disable=protected-access; tests
  29. # pylint: disable=too-many-arguments; these are tests, no API
  30. def test_console_entry_point() -> None:
  31. assert subprocess.run(
  32. ["switchbot-mqtt", "--help"], stdout=subprocess.PIPE, check=True
  33. ).stdout.startswith(b"usage: ")
  34. @pytest.mark.parametrize(
  35. (
  36. "argv",
  37. "expected_mqtt_host",
  38. "expected_mqtt_port",
  39. "expected_username",
  40. "expected_password",
  41. "expected_retry_count",
  42. ),
  43. [
  44. (
  45. ["", "--mqtt-host", "mqtt-broker.local"],
  46. "mqtt-broker.local",
  47. 1883,
  48. None,
  49. None,
  50. 3,
  51. ),
  52. (
  53. ["", "--mqtt-host", "mqtt-broker.local", "--mqtt-port", "8883"],
  54. "mqtt-broker.local",
  55. 8883,
  56. None,
  57. None,
  58. 3,
  59. ),
  60. (
  61. ["", "--mqtt-host", "mqtt-broker.local", "--mqtt-username", "me"],
  62. "mqtt-broker.local",
  63. 1883,
  64. "me",
  65. None,
  66. 3,
  67. ),
  68. (
  69. [
  70. "",
  71. "--mqtt-host",
  72. "mqtt-broker.local",
  73. "--mqtt-username",
  74. "me",
  75. "--mqtt-password",
  76. "secret",
  77. "--retries",
  78. "21",
  79. ],
  80. "mqtt-broker.local",
  81. 1883,
  82. "me",
  83. "secret",
  84. 21,
  85. ),
  86. ],
  87. )
  88. def test__main(
  89. argv: typing.List[str],
  90. expected_mqtt_host: str,
  91. expected_mqtt_port: int,
  92. expected_username: str,
  93. expected_password: str,
  94. expected_retry_count: int,
  95. ) -> None:
  96. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  97. "sys.argv", argv
  98. ), pytest.warns(UserWarning, match=r"Please add --mqtt-disable-tls\b"):
  99. switchbot_mqtt._cli._main()
  100. run_mock.assert_called_once_with(
  101. mqtt_host=expected_mqtt_host,
  102. mqtt_port=expected_mqtt_port,
  103. mqtt_disable_tls=True,
  104. mqtt_username=expected_username,
  105. mqtt_password=expected_password,
  106. mqtt_topic_prefix="homeassistant/",
  107. retry_count=expected_retry_count,
  108. device_passwords={},
  109. fetch_device_info=False,
  110. )
  111. @pytest.mark.parametrize(
  112. ("mqtt_password_file_content", "expected_password"),
  113. [
  114. ("secret", "secret"),
  115. ("secret space", "secret space"),
  116. ("secret ", "secret "),
  117. (" secret ", " secret "),
  118. ("secret\n", "secret"),
  119. ("secret\n\n", "secret\n"),
  120. ("secret\r\n", "secret"),
  121. ("secret\n\r\n", "secret\n"),
  122. ("你好\n", "你好"),
  123. ],
  124. )
  125. def test__main_mqtt_password_file(
  126. tmp_path: pathlib.Path, mqtt_password_file_content: str, expected_password: str
  127. ) -> None:
  128. mqtt_password_path = tmp_path.joinpath("mqtt-password")
  129. mqtt_password_path.write_text(mqtt_password_file_content, encoding="utf8")
  130. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  131. "sys.argv",
  132. [
  133. "",
  134. "--mqtt-host",
  135. "localhost",
  136. "--mqtt-username",
  137. "me",
  138. "--mqtt-password-file",
  139. str(mqtt_password_path),
  140. ],
  141. ):
  142. switchbot_mqtt._cli._main()
  143. run_mock.assert_called_once_with(
  144. mqtt_host="localhost",
  145. mqtt_port=1883,
  146. mqtt_disable_tls=True,
  147. mqtt_username="me",
  148. mqtt_password=expected_password,
  149. mqtt_topic_prefix="homeassistant/",
  150. retry_count=3,
  151. device_passwords={},
  152. fetch_device_info=False,
  153. )
  154. def test__main_mqtt_password_file_collision(
  155. capsys: _pytest.capture.CaptureFixture,
  156. ) -> None:
  157. with unittest.mock.patch(
  158. "sys.argv",
  159. [
  160. "",
  161. "--mqtt-host",
  162. "localhost",
  163. "--mqtt-username",
  164. "me",
  165. "--mqtt-password",
  166. "secret",
  167. "--mqtt-password-file",
  168. "/var/lib/secrets/mqtt/password",
  169. ],
  170. ):
  171. with pytest.raises(SystemExit):
  172. switchbot_mqtt._cli._main()
  173. out, err = capsys.readouterr()
  174. assert not out
  175. assert (
  176. "argument --mqtt-password-file: not allowed with argument --mqtt-password\n"
  177. in err
  178. )
  179. @pytest.mark.parametrize(
  180. "device_passwords",
  181. [
  182. {},
  183. {"11:22:33:44:55:66": "password", "aa:bb:cc:dd:ee:ff": "secret"},
  184. ],
  185. )
  186. def test__main_device_password_file(
  187. tmp_path: pathlib.Path, device_passwords: typing.Dict[str, str]
  188. ) -> None:
  189. device_passwords_path = tmp_path.joinpath("passwords.json")
  190. device_passwords_path.write_text(json.dumps(device_passwords), encoding="utf8")
  191. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  192. "sys.argv",
  193. [
  194. "",
  195. "--mqtt-host",
  196. "localhost",
  197. "--device-password-file",
  198. str(device_passwords_path),
  199. ],
  200. ):
  201. switchbot_mqtt._cli._main()
  202. run_mock.assert_called_once_with(
  203. mqtt_host="localhost",
  204. mqtt_port=1883,
  205. mqtt_disable_tls=True,
  206. mqtt_username=None,
  207. mqtt_password=None,
  208. mqtt_topic_prefix="homeassistant/",
  209. retry_count=3,
  210. device_passwords=device_passwords,
  211. fetch_device_info=False,
  212. )
  213. _RUN_DEFAULT_KWARGS: typing.Dict[str, typing.Any] = {
  214. "mqtt_host": "localhost",
  215. "mqtt_port": 1883,
  216. "mqtt_disable_tls": True,
  217. "mqtt_username": None,
  218. "mqtt_password": None,
  219. "mqtt_topic_prefix": "homeassistant/",
  220. "retry_count": 3,
  221. "device_passwords": {},
  222. "fetch_device_info": False,
  223. }
  224. def test__main_mqtt_disable_tls_implicit() -> None:
  225. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  226. "sys.argv", ["", "--mqtt-host", "mqtt.local"]
  227. ), pytest.warns(UserWarning, match=r"Please add --mqtt-disable-tls\b"):
  228. switchbot_mqtt._cli._main()
  229. run_mock.assert_called_once_with(
  230. **{
  231. **_RUN_DEFAULT_KWARGS,
  232. "mqtt_host": "mqtt.local",
  233. "mqtt_disable_tls": True,
  234. "mqtt_port": 1883,
  235. }
  236. )
  237. def test__main_mqtt_enable_tls() -> None:
  238. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  239. "sys.argv", ["", "--mqtt-host", "mqtt.local", "--mqtt-enable-tls"]
  240. ):
  241. switchbot_mqtt._cli._main()
  242. run_mock.assert_called_once_with(
  243. **{
  244. **_RUN_DEFAULT_KWARGS,
  245. "mqtt_host": "mqtt.local",
  246. "mqtt_disable_tls": False,
  247. "mqtt_port": 8883,
  248. }
  249. )
  250. def test__main_mqtt_enable_tls_overwrite_port() -> None:
  251. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  252. "sys.argv",
  253. ["", "--mqtt-host", "mqtt.local", "--mqtt-port", "1883", "--mqtt-enable-tls"],
  254. ):
  255. switchbot_mqtt._cli._main()
  256. run_mock.assert_called_once_with(
  257. **{
  258. **_RUN_DEFAULT_KWARGS,
  259. "mqtt_host": "mqtt.local",
  260. "mqtt_disable_tls": False,
  261. "mqtt_port": 1883,
  262. }
  263. )
  264. def test__main_mqtt_tls_collision(capsys: _pytest.capture.CaptureFixture) -> None:
  265. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  266. "sys.argv",
  267. ["", "--mqtt-host", "mqtt.local", "--mqtt-enable-tls", "--mqtt-disable-tls"],
  268. ), pytest.raises(SystemExit):
  269. switchbot_mqtt._cli._main()
  270. run_mock.assert_not_called()
  271. assert (
  272. "error: argument --mqtt-disable-tls: not allowed with argument --mqtt-enable-tls\n"
  273. in capsys.readouterr()[1]
  274. )
  275. @pytest.mark.parametrize(
  276. ("additional_argv", "expected_topic_prefix"),
  277. [([], "homeassistant/"), (["--mqtt-topic-prefix", ""], "")],
  278. )
  279. def test__main_mqtt_topic_prefix(
  280. additional_argv: typing.List[str], expected_topic_prefix: str
  281. ) -> None:
  282. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  283. "sys.argv", ["", "--mqtt-host", "localhost"] + additional_argv
  284. ):
  285. switchbot_mqtt._cli._main()
  286. run_mock.assert_called_once_with(
  287. **{**_RUN_DEFAULT_KWARGS, "mqtt_topic_prefix": expected_topic_prefix}
  288. )
  289. def test__main_fetch_device_info() -> None:
  290. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  291. "sys.argv",
  292. [
  293. "",
  294. "--mqtt-host",
  295. "localhost",
  296. ],
  297. ):
  298. switchbot_mqtt._cli._main()
  299. run_mock.assert_called_once_with(
  300. **{**_RUN_DEFAULT_KWARGS, "fetch_device_info": False}
  301. )
  302. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  303. "sys.argv",
  304. ["", "--mqtt-host", "localhost", "--fetch-device-info"],
  305. ):
  306. switchbot_mqtt._cli._main()
  307. run_mock.assert_called_once_with(
  308. **{**_RUN_DEFAULT_KWARGS, "fetch_device_info": True}
  309. )
  310. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  311. "sys.argv",
  312. ["", "--mqtt-host", "localhost"],
  313. ), unittest.mock.patch.dict("os.environ", {"FETCH_DEVICE_INFO": "21"}):
  314. switchbot_mqtt._cli._main()
  315. run_mock.assert_called_once_with(
  316. **{**_RUN_DEFAULT_KWARGS, "fetch_device_info": True}
  317. )
  318. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  319. "sys.argv",
  320. ["", "--mqtt-host", "localhost"],
  321. ), unittest.mock.patch.dict("os.environ", {"FETCH_DEVICE_INFO": ""}):
  322. switchbot_mqtt._cli._main()
  323. run_mock.assert_called_once_with(
  324. **{**_RUN_DEFAULT_KWARGS, "fetch_device_info": False}
  325. )
  326. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  327. "sys.argv",
  328. ["", "--mqtt-host", "localhost"],
  329. ), unittest.mock.patch.dict("os.environ", {"FETCH_DEVICE_INFO": " "}):
  330. switchbot_mqtt._cli._main()
  331. run_mock.assert_called_once_with(
  332. **{**_RUN_DEFAULT_KWARGS, "fetch_device_info": True}
  333. )
  334. @pytest.mark.parametrize(
  335. ("additional_argv", "root_log_level", "log_format"),
  336. [
  337. ([], logging.INFO, "%(message)s"),
  338. (
  339. ["--debug"],
  340. logging.DEBUG,
  341. "%(asctime)s:%(levelname)s:%(name)s:%(funcName)s:%(message)s",
  342. ),
  343. ],
  344. )
  345. def test__main_log_config(
  346. additional_argv: typing.List[str], root_log_level: int, log_format: str
  347. ) -> None:
  348. with unittest.mock.patch(
  349. "sys.argv", ["", "--mqtt-host", "localhost"] + additional_argv
  350. ), unittest.mock.patch(
  351. "logging.basicConfig"
  352. ) as logging_basic_config_mock, unittest.mock.patch(
  353. "switchbot_mqtt._run"
  354. ):
  355. switchbot_mqtt._cli._main()
  356. logging_basic_config_mock.assert_called_once_with(
  357. level=root_log_level, format=log_format, datefmt="%Y-%m-%dT%H:%M:%S%z"
  358. )