test_cli.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. retry_count=expected_retry_count,
  106. device_passwords={},
  107. fetch_device_info=False,
  108. )
  109. @pytest.mark.parametrize(
  110. ("mqtt_password_file_content", "expected_password"),
  111. [
  112. ("secret", "secret"),
  113. ("secret space", "secret space"),
  114. ("secret ", "secret "),
  115. (" secret ", " secret "),
  116. ("secret\n", "secret"),
  117. ("secret\n\n", "secret\n"),
  118. ("secret\r\n", "secret"),
  119. ("secret\n\r\n", "secret\n"),
  120. ("你好\n", "你好"),
  121. ],
  122. )
  123. def test__main_mqtt_password_file(
  124. tmp_path: pathlib.Path, mqtt_password_file_content: str, expected_password: str
  125. ) -> None:
  126. mqtt_password_path = tmp_path.joinpath("mqtt-password")
  127. mqtt_password_path.write_text(mqtt_password_file_content, encoding="utf8")
  128. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  129. "sys.argv",
  130. [
  131. "",
  132. "--mqtt-host",
  133. "localhost",
  134. "--mqtt-username",
  135. "me",
  136. "--mqtt-password-file",
  137. str(mqtt_password_path),
  138. ],
  139. ):
  140. switchbot_mqtt._cli._main()
  141. run_mock.assert_called_once_with(
  142. mqtt_host="localhost",
  143. mqtt_port=1883,
  144. mqtt_username="me",
  145. mqtt_password=expected_password,
  146. retry_count=3,
  147. device_passwords={},
  148. fetch_device_info=False,
  149. )
  150. def test__main_mqtt_password_file_collision(
  151. capsys: _pytest.capture.CaptureFixture,
  152. ) -> None:
  153. with unittest.mock.patch(
  154. "sys.argv",
  155. [
  156. "",
  157. "--mqtt-host",
  158. "localhost",
  159. "--mqtt-username",
  160. "me",
  161. "--mqtt-password",
  162. "secret",
  163. "--mqtt-password-file",
  164. "/var/lib/secrets/mqtt/password",
  165. ],
  166. ):
  167. with pytest.raises(SystemExit):
  168. switchbot_mqtt._cli._main()
  169. out, err = capsys.readouterr()
  170. assert not out
  171. assert (
  172. "argument --mqtt-password-file: not allowed with argument --mqtt-password\n"
  173. in err
  174. )
  175. @pytest.mark.parametrize(
  176. "device_passwords",
  177. [
  178. {},
  179. {"11:22:33:44:55:66": "password", "aa:bb:cc:dd:ee:ff": "secret"},
  180. ],
  181. )
  182. def test__main_device_password_file(
  183. tmp_path: pathlib.Path, device_passwords: typing.Dict[str, str]
  184. ) -> None:
  185. device_passwords_path = tmp_path.joinpath("passwords.json")
  186. device_passwords_path.write_text(json.dumps(device_passwords), encoding="utf8")
  187. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  188. "sys.argv",
  189. [
  190. "",
  191. "--mqtt-host",
  192. "localhost",
  193. "--device-password-file",
  194. str(device_passwords_path),
  195. ],
  196. ):
  197. switchbot_mqtt._cli._main()
  198. run_mock.assert_called_once_with(
  199. mqtt_host="localhost",
  200. mqtt_port=1883,
  201. mqtt_username=None,
  202. mqtt_password=None,
  203. retry_count=3,
  204. device_passwords=device_passwords,
  205. fetch_device_info=False,
  206. )
  207. def test__main_fetch_device_info() -> None:
  208. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  209. "sys.argv",
  210. [
  211. "",
  212. "--mqtt-host",
  213. "localhost",
  214. ],
  215. ):
  216. switchbot_mqtt._cli._main()
  217. default_kwargs = dict(
  218. mqtt_host="localhost",
  219. mqtt_port=1883,
  220. mqtt_username=None,
  221. mqtt_password=None,
  222. retry_count=3,
  223. device_passwords={},
  224. )
  225. run_mock.assert_called_once_with(fetch_device_info=False, **default_kwargs)
  226. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  227. "sys.argv",
  228. ["", "--mqtt-host", "localhost", "--fetch-device-info"],
  229. ):
  230. switchbot_mqtt._cli._main()
  231. run_mock.assert_called_once_with(fetch_device_info=True, **default_kwargs)
  232. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  233. "sys.argv",
  234. ["", "--mqtt-host", "localhost"],
  235. ), unittest.mock.patch.dict("os.environ", {"FETCH_DEVICE_INFO": "21"}):
  236. switchbot_mqtt._cli._main()
  237. run_mock.assert_called_once_with(fetch_device_info=True, **default_kwargs)
  238. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  239. "sys.argv",
  240. ["", "--mqtt-host", "localhost"],
  241. ), unittest.mock.patch.dict("os.environ", {"FETCH_DEVICE_INFO": ""}):
  242. switchbot_mqtt._cli._main()
  243. run_mock.assert_called_once_with(fetch_device_info=False, **default_kwargs)
  244. with unittest.mock.patch("switchbot_mqtt._run") as run_mock, unittest.mock.patch(
  245. "sys.argv",
  246. ["", "--mqtt-host", "localhost"],
  247. ), unittest.mock.patch.dict("os.environ", {"FETCH_DEVICE_INFO": " "}):
  248. switchbot_mqtt._cli._main()
  249. run_mock.assert_called_once_with(fetch_device_info=True, **default_kwargs)
  250. @pytest.mark.parametrize(
  251. ("additional_argv", "root_log_level", "log_format"),
  252. [
  253. ([], logging.INFO, "%(message)s"),
  254. (
  255. ["--debug"],
  256. logging.DEBUG,
  257. "%(asctime)s:%(levelname)s:%(name)s:%(funcName)s:%(message)s",
  258. ),
  259. ],
  260. )
  261. def test__main_log_config(
  262. additional_argv: typing.List[str], root_log_level: int, log_format: str
  263. ) -> None:
  264. with unittest.mock.patch(
  265. "sys.argv", ["", "--mqtt-host", "localhost"] + additional_argv
  266. ), unittest.mock.patch(
  267. "logging.basicConfig"
  268. ) as logging_basic_config_mock, unittest.mock.patch(
  269. "switchbot_mqtt._run"
  270. ):
  271. switchbot_mqtt._cli._main()
  272. logging_basic_config_mock.assert_called_once_with(
  273. level=root_log_level, format=log_format, datefmt="%Y-%m-%dT%H:%M:%S%z"
  274. )