test_cli.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. # systemctl-mqtt - MQTT client triggering & reporting shutdown on systemd-based systems
  2. #
  3. # Copyright (C) 2020 Fabian Peter Hammerle <fabian@hammerle.me>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. import datetime
  18. import logging
  19. import unittest.mock
  20. import pytest
  21. import systemctl_mqtt
  22. import systemctl_mqtt._homeassistant
  23. import systemctl_mqtt._utils
  24. # pylint: disable=protected-access,too-many-positional-arguments
  25. @pytest.mark.parametrize(
  26. ("args", "log_level"),
  27. [
  28. ([], logging.INFO),
  29. (["--log-level", "debug"], logging.DEBUG),
  30. (["--log-level", "info"], logging.INFO),
  31. (["--log-level", "warning"], logging.WARNING),
  32. (["--log-level", "error"], logging.ERROR),
  33. (["--log-level", "critical"], logging.CRITICAL),
  34. ],
  35. )
  36. def test__main_log_level(args: list[str], log_level: int) -> None:
  37. with unittest.mock.patch("systemctl_mqtt._run") as run_mock, unittest.mock.patch(
  38. "sys.argv", ["", "--mqtt-host", "mqtt-broker.local"] + args
  39. ):
  40. systemctl_mqtt._main()
  41. run_mock.assert_called_once()
  42. assert logging.root.getEffectiveLevel() == log_level
  43. @pytest.mark.parametrize(
  44. (
  45. "argv",
  46. "expected_mqtt_host",
  47. "expected_mqtt_port",
  48. "expected_mqtt_disable_tls",
  49. "expected_username",
  50. "expected_password",
  51. "expected_topic_prefix",
  52. ),
  53. [
  54. (
  55. ["", "--mqtt-host", "mqtt-broker.local"],
  56. "mqtt-broker.local",
  57. 8883,
  58. False,
  59. None,
  60. None,
  61. None,
  62. ),
  63. (
  64. ["", "--mqtt-host", "mqtt-broker.local", "--mqtt-disable-tls"],
  65. "mqtt-broker.local",
  66. 1883,
  67. True,
  68. None,
  69. None,
  70. None,
  71. ),
  72. (
  73. ["", "--mqtt-host", "mqtt-broker.local", "--mqtt-port", "8883"],
  74. "mqtt-broker.local",
  75. 8883,
  76. False,
  77. None,
  78. None,
  79. None,
  80. ),
  81. (
  82. ["", "--mqtt-host", "mqtt-broker.local", "--mqtt-port", "8884"],
  83. "mqtt-broker.local",
  84. 8884,
  85. False,
  86. None,
  87. None,
  88. None,
  89. ),
  90. (
  91. [
  92. "",
  93. "--mqtt-host",
  94. "mqtt-broker.local",
  95. "--mqtt-port",
  96. "8884",
  97. "--mqtt-disable-tls",
  98. ],
  99. "mqtt-broker.local",
  100. 8884,
  101. True,
  102. None,
  103. None,
  104. None,
  105. ),
  106. (
  107. ["", "--mqtt-host", "mqtt-broker.local", "--mqtt-username", "me"],
  108. "mqtt-broker.local",
  109. 8883,
  110. False,
  111. "me",
  112. None,
  113. None,
  114. ),
  115. (
  116. [
  117. "",
  118. "--mqtt-host",
  119. "mqtt-broker.local",
  120. "--mqtt-username",
  121. "me",
  122. "--mqtt-password",
  123. "secret",
  124. ],
  125. "mqtt-broker.local",
  126. 8883,
  127. False,
  128. "me",
  129. "secret",
  130. None,
  131. ),
  132. (
  133. [
  134. "",
  135. "--mqtt-host",
  136. "mqtt-broker.local",
  137. "--mqtt-topic-prefix",
  138. "system/command",
  139. ],
  140. "mqtt-broker.local",
  141. 8883,
  142. False,
  143. None,
  144. None,
  145. "system/command",
  146. ),
  147. ],
  148. )
  149. def test__main(
  150. argv,
  151. expected_mqtt_host,
  152. expected_mqtt_port,
  153. expected_mqtt_disable_tls,
  154. expected_username,
  155. expected_password,
  156. expected_topic_prefix: str | None,
  157. ):
  158. # pylint: disable=too-many-arguments
  159. with unittest.mock.patch("systemctl_mqtt._run") as run_mock, unittest.mock.patch(
  160. "sys.argv", argv
  161. ), unittest.mock.patch(
  162. "systemctl_mqtt._utils.get_hostname", return_value="hostname"
  163. ):
  164. # pylint: disable=protected-access
  165. systemctl_mqtt._main()
  166. run_mock.assert_called_once_with(
  167. mqtt_host=expected_mqtt_host,
  168. mqtt_port=expected_mqtt_port,
  169. mqtt_disable_tls=expected_mqtt_disable_tls,
  170. mqtt_username=expected_username,
  171. mqtt_password=expected_password,
  172. mqtt_topic_prefix=expected_topic_prefix or "systemctl/hostname",
  173. homeassistant_discovery_prefix="homeassistant",
  174. homeassistant_discovery_object_id="systemctl-mqtt-hostname",
  175. poweroff_delay=datetime.timedelta(seconds=4),
  176. monitored_system_unit_names=[],
  177. controlled_system_unit_names=[],
  178. )
  179. @pytest.mark.parametrize(
  180. ("password_file_content", "expected_password"),
  181. [
  182. ("secret", "secret"),
  183. ("secret space", "secret space"),
  184. ("secret ", "secret "),
  185. (" secret ", " secret "),
  186. ("secret\n", "secret"),
  187. ("secret\n\n", "secret\n"),
  188. ("secret\r\n", "secret"),
  189. ("secret\n\r\n", "secret\n"),
  190. ("你好\n", "你好"),
  191. ],
  192. )
  193. def test__main_password_file(tmpdir, password_file_content, expected_password):
  194. mqtt_password_path = tmpdir.join("mqtt-password")
  195. with mqtt_password_path.open("w") as mqtt_password_file:
  196. mqtt_password_file.write(password_file_content)
  197. with unittest.mock.patch("systemctl_mqtt._run") as run_mock, unittest.mock.patch(
  198. "sys.argv",
  199. [
  200. "",
  201. "--mqtt-host",
  202. "localhost",
  203. "--mqtt-username",
  204. "me",
  205. "--mqtt-password-file",
  206. str(mqtt_password_path),
  207. ],
  208. ), unittest.mock.patch(
  209. "systemctl_mqtt._utils.get_hostname", return_value="hostname"
  210. ):
  211. # pylint: disable=protected-access
  212. systemctl_mqtt._main()
  213. run_mock.assert_called_once_with(
  214. mqtt_host="localhost",
  215. mqtt_port=8883,
  216. mqtt_disable_tls=False,
  217. mqtt_username="me",
  218. mqtt_password=expected_password,
  219. mqtt_topic_prefix="systemctl/hostname",
  220. homeassistant_discovery_prefix="homeassistant",
  221. homeassistant_discovery_object_id="systemctl-mqtt-hostname",
  222. poweroff_delay=datetime.timedelta(seconds=4),
  223. monitored_system_unit_names=[],
  224. controlled_system_unit_names=[],
  225. )
  226. def test__main_password_file_collision(capsys):
  227. with unittest.mock.patch(
  228. "sys.argv",
  229. [
  230. "",
  231. "--mqtt-host",
  232. "localhost",
  233. "--mqtt-username",
  234. "me",
  235. "--mqtt-password",
  236. "secret",
  237. "--mqtt-password-file",
  238. "/var/lib/secrets/mqtt/password",
  239. ],
  240. ):
  241. with pytest.raises(SystemExit):
  242. # pylint: disable=protected-access
  243. systemctl_mqtt._main()
  244. out, err = capsys.readouterr()
  245. assert not out
  246. assert (
  247. "argument --mqtt-password-file: not allowed with argument --mqtt-password\n"
  248. in err
  249. )
  250. @pytest.mark.parametrize(
  251. ("args", "discovery_prefix"),
  252. [
  253. ([], "homeassistant"),
  254. (["--homeassistant-discovery-prefix", "home/assistant"], "home/assistant"),
  255. ],
  256. )
  257. def test__main_homeassistant_discovery_prefix(args, discovery_prefix):
  258. with unittest.mock.patch("systemctl_mqtt._run") as run_mock, unittest.mock.patch(
  259. "sys.argv", ["", "--mqtt-host", "mqtt-broker.local"] + args
  260. ):
  261. systemctl_mqtt._main()
  262. run_mock.assert_called_once()
  263. assert run_mock.call_args[1]["homeassistant_discovery_prefix"] == discovery_prefix
  264. @pytest.mark.parametrize(
  265. ("args", "object_id"),
  266. [
  267. ([], "systemctl-mqtt-fallback"),
  268. (["--homeassistant-discovery-object-id", "raspberrypi"], "raspberrypi"),
  269. ],
  270. )
  271. def test__main_homeassistant_discovery_object_id(args, object_id):
  272. with unittest.mock.patch("systemctl_mqtt._run") as run_mock, unittest.mock.patch(
  273. "sys.argv", ["", "--mqtt-host", "mqtt-broker.local"] + args
  274. ), unittest.mock.patch(
  275. "systemctl_mqtt._utils.get_hostname", return_value="fallback"
  276. ):
  277. systemctl_mqtt._main()
  278. run_mock.assert_called_once()
  279. assert run_mock.call_args[1]["homeassistant_discovery_object_id"] == object_id
  280. @pytest.mark.parametrize(
  281. "args",
  282. [
  283. ["--homeassistant-discovery-object-id", "no pe"],
  284. ["--homeassistant-discovery-object-id", ""],
  285. ],
  286. )
  287. def test__main_homeassistant_discovery_object_id_invalid(args):
  288. with unittest.mock.patch(
  289. "sys.argv", ["", "--mqtt-host", "mqtt-broker.local"] + args
  290. ):
  291. with pytest.raises(ValueError):
  292. systemctl_mqtt._main()
  293. @pytest.mark.parametrize(
  294. ("args", "poweroff_delay"),
  295. [
  296. ([], datetime.timedelta(seconds=4)),
  297. (["--poweroff-delay-seconds", "42.21"], datetime.timedelta(seconds=42.21)),
  298. (["--poweroff-delay-seconds", "3600"], datetime.timedelta(hours=1)),
  299. ],
  300. )
  301. def test__main_poweroff_delay(args, poweroff_delay):
  302. with unittest.mock.patch("systemctl_mqtt._run") as run_mock, unittest.mock.patch(
  303. "sys.argv", ["", "--mqtt-host", "mqtt-broker.local"] + args
  304. ):
  305. systemctl_mqtt._main()
  306. run_mock.assert_called_once()
  307. assert run_mock.call_args[1]["poweroff_delay"] == poweroff_delay