test_cli.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. ):
  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. def test__main_fetch_device_info() -> None:
  211. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  212. "sys.argv",
  213. [
  214. "",
  215. "--mqtt-host",
  216. "localhost",
  217. ],
  218. ):
  219. switchbot_mqtt._cli._main()
  220. default_kwargs = dict(
  221. mqtt_host="localhost",
  222. mqtt_port=1883,
  223. mqtt_username=None,
  224. mqtt_password=None,
  225. mqtt_disable_tls=True,
  226. retry_count=3,
  227. device_passwords={},
  228. )
  229. run_mock.assert_called_once_with(fetch_device_info=False, **default_kwargs)
  230. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  231. "sys.argv",
  232. ["", "--mqtt-host", "localhost", "--fetch-device-info"],
  233. ):
  234. switchbot_mqtt._cli._main()
  235. run_mock.assert_called_once_with(fetch_device_info=True, **default_kwargs)
  236. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  237. "sys.argv",
  238. ["", "--mqtt-host", "localhost"],
  239. ), unittest.mock.patch.dict("os.environ", {"FETCH_DEVICE_INFO": "21"}):
  240. switchbot_mqtt._cli._main()
  241. run_mock.assert_called_once_with(fetch_device_info=True, **default_kwargs)
  242. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  243. "sys.argv",
  244. ["", "--mqtt-host", "localhost"],
  245. ), unittest.mock.patch.dict("os.environ", {"FETCH_DEVICE_INFO": ""}):
  246. switchbot_mqtt._cli._main()
  247. run_mock.assert_called_once_with(fetch_device_info=False, **default_kwargs)
  248. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  249. "sys.argv",
  250. ["", "--mqtt-host", "localhost"],
  251. ), unittest.mock.patch.dict("os.environ", {"FETCH_DEVICE_INFO": " "}):
  252. switchbot_mqtt._cli._main()
  253. run_mock.assert_called_once_with(fetch_device_info=True, **default_kwargs)
  254. @pytest.mark.parametrize(
  255. ("additional_argv", "root_log_level", "log_format"),
  256. [
  257. ([], logging.INFO, "%(message)s"),
  258. (
  259. ["--debug"],
  260. logging.DEBUG,
  261. "%(asctime)s:%(levelname)s:%(name)s:%(funcName)s:%(message)s",
  262. ),
  263. ],
  264. )
  265. def test__main_log_config(
  266. additional_argv: typing.List[str], root_log_level: int, log_format: str
  267. ) -> None:
  268. with unittest.mock.patch(
  269. "sys.argv", ["", "--mqtt-host", "localhost"] + additional_argv
  270. ), unittest.mock.patch(
  271. "logging.basicConfig"
  272. ) as logging_basic_config_mock, unittest.mock.patch(
  273. "switchbot_mqtt._run"
  274. ):
  275. switchbot_mqtt._cli._main()
  276. logging_basic_config_mock.assert_called_once_with(
  277. level=root_log_level, format=log_format, datefmt="%Y-%m-%dT%H:%M:%S%z"
  278. )