test_cli.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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
  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_username=expected_username,
  104. mqtt_password=expected_password,
  105. mqtt_disable_tls=True,
  106. retry_count=expected_retry_count,
  107. device_passwords={},
  108. fetch_device_info=False,
  109. )
  110. @pytest.mark.parametrize(
  111. ("mqtt_password_file_content", "expected_password"),
  112. [
  113. ("secret", "secret"),
  114. ("secret space", "secret space"),
  115. ("secret ", "secret "),
  116. (" secret ", " secret "),
  117. ("secret\n", "secret"),
  118. ("secret\n\n", "secret\n"),
  119. ("secret\r\n", "secret"),
  120. ("secret\n\r\n", "secret\n"),
  121. ("你好\n", "你好"),
  122. ],
  123. )
  124. def test__main_mqtt_password_file(
  125. tmp_path: pathlib.Path, mqtt_password_file_content: str, expected_password: str
  126. ) -> None:
  127. mqtt_password_path = tmp_path.joinpath("mqtt-password")
  128. mqtt_password_path.write_text(mqtt_password_file_content, encoding="utf8")
  129. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  130. "sys.argv",
  131. [
  132. "",
  133. "--mqtt-host",
  134. "localhost",
  135. "--mqtt-username",
  136. "me",
  137. "--mqtt-password-file",
  138. str(mqtt_password_path),
  139. ],
  140. ):
  141. switchbot_mqtt._cli._main()
  142. run_mock.assert_called_once_with(
  143. mqtt_host="localhost",
  144. mqtt_port=1883,
  145. mqtt_username="me",
  146. mqtt_password=expected_password,
  147. mqtt_disable_tls=True,
  148. retry_count=3,
  149. device_passwords={},
  150. fetch_device_info=False,
  151. )
  152. def test__main_mqtt_password_file_collision(
  153. capsys: _pytest.capture.CaptureFixture,
  154. ) -> None:
  155. with unittest.mock.patch(
  156. "sys.argv",
  157. [
  158. "",
  159. "--mqtt-host",
  160. "localhost",
  161. "--mqtt-username",
  162. "me",
  163. "--mqtt-password",
  164. "secret",
  165. "--mqtt-password-file",
  166. "/var/lib/secrets/mqtt/password",
  167. ],
  168. ):
  169. with pytest.raises(SystemExit):
  170. switchbot_mqtt._cli._main()
  171. out, err = capsys.readouterr()
  172. assert not out
  173. assert (
  174. "argument --mqtt-password-file: not allowed with argument --mqtt-password\n"
  175. in err
  176. )
  177. @pytest.mark.parametrize(
  178. "device_passwords",
  179. [
  180. {},
  181. {"11:22:33:44:55:66": "password", "aa:bb:cc:dd:ee:ff": "secret"},
  182. ],
  183. )
  184. def test__main_device_password_file(
  185. tmp_path: pathlib.Path, device_passwords: typing.Dict[str, str]
  186. ) -> None:
  187. device_passwords_path = tmp_path.joinpath("passwords.json")
  188. device_passwords_path.write_text(json.dumps(device_passwords), encoding="utf8")
  189. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  190. "sys.argv",
  191. [
  192. "",
  193. "--mqtt-host",
  194. "localhost",
  195. "--device-password-file",
  196. str(device_passwords_path),
  197. ],
  198. ):
  199. switchbot_mqtt._cli._main()
  200. run_mock.assert_called_once_with(
  201. mqtt_host="localhost",
  202. mqtt_port=1883,
  203. mqtt_username=None,
  204. mqtt_password=None,
  205. mqtt_disable_tls=True,
  206. retry_count=3,
  207. device_passwords=device_passwords,
  208. fetch_device_info=False,
  209. )
  210. _RUN_DEFAULT_KWARGS: typing.Dict[str, typing.Any] = {
  211. "mqtt_port": 1883,
  212. "mqtt_username": None,
  213. "mqtt_password": None,
  214. "mqtt_disable_tls": False,
  215. "retry_count": 3,
  216. "device_passwords": {},
  217. "fetch_device_info": False,
  218. }
  219. def test__main_mqtt_disable_tls_implicit() -> None:
  220. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  221. "sys.argv", ["", "--mqtt-host", "mqtt.local"]
  222. ), pytest.warns(UserWarning, match=r"Please add --mqtt-disable-tls\b"):
  223. switchbot_mqtt._cli._main()
  224. run_mock.assert_called_once_with(
  225. **{
  226. **_RUN_DEFAULT_KWARGS,
  227. "mqtt_host": "mqtt.local",
  228. "mqtt_disable_tls": True,
  229. "mqtt_port": 1883,
  230. }
  231. )
  232. def test__main_mqtt_enable_tls() -> None:
  233. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  234. "sys.argv", ["", "--mqtt-host", "mqtt.local", "--mqtt-enable-tls"]
  235. ):
  236. switchbot_mqtt._cli._main()
  237. run_mock.assert_called_once_with(
  238. **{**_RUN_DEFAULT_KWARGS, "mqtt_host": "mqtt.local", "mqtt_port": 8883}
  239. )
  240. def test__main_mqtt_enable_tls_overwrite_port() -> None:
  241. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  242. "sys.argv",
  243. ["", "--mqtt-host", "mqtt.local", "--mqtt-port", "1883", "--mqtt-enable-tls"],
  244. ):
  245. switchbot_mqtt._cli._main()
  246. run_mock.assert_called_once_with(
  247. **{**_RUN_DEFAULT_KWARGS, "mqtt_host": "mqtt.local", "mqtt_port": 1883}
  248. )
  249. def test__main_mqtt_tls_collision(capsys: _pytest.capture.CaptureFixture) -> None:
  250. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  251. "sys.argv",
  252. ["", "--mqtt-host", "mqtt.local", "--mqtt-enable-tls", "--mqtt-disable-tls"],
  253. ), pytest.raises(SystemExit):
  254. switchbot_mqtt._cli._main()
  255. run_mock.assert_not_called()
  256. assert (
  257. "error: argument --mqtt-disable-tls: not allowed with argument --mqtt-enable-tls\n"
  258. in capsys.readouterr()[1]
  259. )
  260. def test__main_fetch_device_info() -> None:
  261. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  262. "sys.argv",
  263. [
  264. "",
  265. "--mqtt-host",
  266. "localhost",
  267. ],
  268. ):
  269. switchbot_mqtt._cli._main()
  270. default_kwargs = dict(
  271. mqtt_host="localhost",
  272. mqtt_port=1883,
  273. mqtt_username=None,
  274. mqtt_password=None,
  275. mqtt_disable_tls=True,
  276. retry_count=3,
  277. device_passwords={},
  278. )
  279. run_mock.assert_called_once_with(fetch_device_info=False, **default_kwargs)
  280. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  281. "sys.argv",
  282. ["", "--mqtt-host", "localhost", "--fetch-device-info"],
  283. ):
  284. switchbot_mqtt._cli._main()
  285. run_mock.assert_called_once_with(fetch_device_info=True, **default_kwargs)
  286. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  287. "sys.argv",
  288. ["", "--mqtt-host", "localhost"],
  289. ), unittest.mock.patch.dict("os.environ", {"FETCH_DEVICE_INFO": "21"}):
  290. switchbot_mqtt._cli._main()
  291. run_mock.assert_called_once_with(fetch_device_info=True, **default_kwargs)
  292. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  293. "sys.argv",
  294. ["", "--mqtt-host", "localhost"],
  295. ), unittest.mock.patch.dict("os.environ", {"FETCH_DEVICE_INFO": ""}):
  296. switchbot_mqtt._cli._main()
  297. run_mock.assert_called_once_with(fetch_device_info=False, **default_kwargs)
  298. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  299. "sys.argv",
  300. ["", "--mqtt-host", "localhost"],
  301. ), unittest.mock.patch.dict("os.environ", {"FETCH_DEVICE_INFO": " "}):
  302. switchbot_mqtt._cli._main()
  303. run_mock.assert_called_once_with(fetch_device_info=True, **default_kwargs)
  304. @pytest.mark.parametrize(
  305. ("additional_argv", "root_log_level", "log_format"),
  306. [
  307. ([], logging.INFO, "%(message)s"),
  308. (
  309. ["--debug"],
  310. logging.DEBUG,
  311. "%(asctime)s:%(levelname)s:%(name)s:%(funcName)s:%(message)s",
  312. ),
  313. ],
  314. )
  315. def test__main_log_config(
  316. additional_argv: typing.List[str], root_log_level: int, log_format: str
  317. ) -> None:
  318. with unittest.mock.patch(
  319. "sys.argv", ["", "--mqtt-host", "localhost"] + additional_argv
  320. ), unittest.mock.patch(
  321. "logging.basicConfig"
  322. ) as logging_basic_config_mock, unittest.mock.patch(
  323. "switchbot_mqtt._run"
  324. ):
  325. switchbot_mqtt._cli._main()
  326. logging_basic_config_mock.assert_called_once_with(
  327. level=root_log_level, format=log_format, datefmt="%Y-%m-%dT%H:%M:%S%z"
  328. )