1
0

test_cli.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 typing
  20. import unittest.mock
  21. import pytest
  22. import systemctl_mqtt
  23. import systemctl_mqtt._homeassistant
  24. import systemctl_mqtt._utils
  25. # pylint: disable=protected-access,too-many-positional-arguments
  26. @pytest.mark.parametrize(
  27. ("args", "log_level"),
  28. [
  29. ([], logging.INFO),
  30. (["--log-level", "debug"], logging.DEBUG),
  31. (["--log-level", "info"], logging.INFO),
  32. (["--log-level", "warning"], logging.WARNING),
  33. (["--log-level", "error"], logging.ERROR),
  34. (["--log-level", "critical"], logging.CRITICAL),
  35. ],
  36. )
  37. def test__main_log_level(args: typing.List[str], log_level: int) -> None:
  38. with unittest.mock.patch("systemctl_mqtt._run") as run_mock, unittest.mock.patch(
  39. "sys.argv", ["", "--mqtt-host", "mqtt-broker.local"] + args
  40. ):
  41. systemctl_mqtt._main()
  42. run_mock.assert_called_once()
  43. assert logging.root.getEffectiveLevel() == log_level
  44. @pytest.mark.parametrize(
  45. (
  46. "argv",
  47. "expected_mqtt_host",
  48. "expected_mqtt_port",
  49. "expected_mqtt_disable_tls",
  50. "expected_username",
  51. "expected_password",
  52. "expected_topic_prefix",
  53. ),
  54. [
  55. (
  56. ["", "--mqtt-host", "mqtt-broker.local"],
  57. "mqtt-broker.local",
  58. 8883,
  59. False,
  60. None,
  61. None,
  62. None,
  63. ),
  64. (
  65. ["", "--mqtt-host", "mqtt-broker.local", "--mqtt-disable-tls"],
  66. "mqtt-broker.local",
  67. 1883,
  68. True,
  69. None,
  70. None,
  71. None,
  72. ),
  73. (
  74. ["", "--mqtt-host", "mqtt-broker.local", "--mqtt-port", "8883"],
  75. "mqtt-broker.local",
  76. 8883,
  77. False,
  78. None,
  79. None,
  80. None,
  81. ),
  82. (
  83. ["", "--mqtt-host", "mqtt-broker.local", "--mqtt-port", "8884"],
  84. "mqtt-broker.local",
  85. 8884,
  86. False,
  87. None,
  88. None,
  89. None,
  90. ),
  91. (
  92. [
  93. "",
  94. "--mqtt-host",
  95. "mqtt-broker.local",
  96. "--mqtt-port",
  97. "8884",
  98. "--mqtt-disable-tls",
  99. ],
  100. "mqtt-broker.local",
  101. 8884,
  102. True,
  103. None,
  104. None,
  105. None,
  106. ),
  107. (
  108. ["", "--mqtt-host", "mqtt-broker.local", "--mqtt-username", "me"],
  109. "mqtt-broker.local",
  110. 8883,
  111. False,
  112. "me",
  113. None,
  114. None,
  115. ),
  116. (
  117. [
  118. "",
  119. "--mqtt-host",
  120. "mqtt-broker.local",
  121. "--mqtt-username",
  122. "me",
  123. "--mqtt-password",
  124. "secret",
  125. ],
  126. "mqtt-broker.local",
  127. 8883,
  128. False,
  129. "me",
  130. "secret",
  131. None,
  132. ),
  133. (
  134. [
  135. "",
  136. "--mqtt-host",
  137. "mqtt-broker.local",
  138. "--mqtt-topic-prefix",
  139. "system/command",
  140. ],
  141. "mqtt-broker.local",
  142. 8883,
  143. False,
  144. None,
  145. None,
  146. "system/command",
  147. ),
  148. ],
  149. )
  150. def test__main(
  151. argv,
  152. expected_mqtt_host,
  153. expected_mqtt_port,
  154. expected_mqtt_disable_tls,
  155. expected_username,
  156. expected_password,
  157. expected_topic_prefix: typing.Optional[str],
  158. ):
  159. # pylint: disable=too-many-arguments
  160. with unittest.mock.patch("systemctl_mqtt._run") as run_mock, unittest.mock.patch(
  161. "sys.argv", argv
  162. ), unittest.mock.patch(
  163. "systemctl_mqtt._utils.get_hostname", return_value="hostname"
  164. ):
  165. # pylint: disable=protected-access
  166. systemctl_mqtt._main()
  167. run_mock.assert_called_once_with(
  168. mqtt_host=expected_mqtt_host,
  169. mqtt_port=expected_mqtt_port,
  170. mqtt_disable_tls=expected_mqtt_disable_tls,
  171. mqtt_username=expected_username,
  172. mqtt_password=expected_password,
  173. mqtt_topic_prefix=expected_topic_prefix or "systemctl/hostname",
  174. homeassistant_discovery_prefix="homeassistant",
  175. homeassistant_discovery_object_id="systemctl-mqtt-hostname",
  176. poweroff_delay=datetime.timedelta(seconds=4),
  177. monitored_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. )
  225. def test__main_password_file_collision(capsys):
  226. with unittest.mock.patch(
  227. "sys.argv",
  228. [
  229. "",
  230. "--mqtt-host",
  231. "localhost",
  232. "--mqtt-username",
  233. "me",
  234. "--mqtt-password",
  235. "secret",
  236. "--mqtt-password-file",
  237. "/var/lib/secrets/mqtt/password",
  238. ],
  239. ):
  240. with pytest.raises(SystemExit):
  241. # pylint: disable=protected-access
  242. systemctl_mqtt._main()
  243. out, err = capsys.readouterr()
  244. assert not out
  245. assert (
  246. "argument --mqtt-password-file: not allowed with argument --mqtt-password\n"
  247. in err
  248. )
  249. @pytest.mark.parametrize(
  250. ("args", "discovery_prefix"),
  251. [
  252. ([], "homeassistant"),
  253. (["--homeassistant-discovery-prefix", "home/assistant"], "home/assistant"),
  254. ],
  255. )
  256. def test__main_homeassistant_discovery_prefix(args, discovery_prefix):
  257. with unittest.mock.patch("systemctl_mqtt._run") as run_mock, unittest.mock.patch(
  258. "sys.argv", ["", "--mqtt-host", "mqtt-broker.local"] + args
  259. ):
  260. systemctl_mqtt._main()
  261. run_mock.assert_called_once()
  262. assert run_mock.call_args[1]["homeassistant_discovery_prefix"] == discovery_prefix
  263. @pytest.mark.parametrize(
  264. ("args", "object_id"),
  265. [
  266. ([], "systemctl-mqtt-fallback"),
  267. (["--homeassistant-discovery-object-id", "raspberrypi"], "raspberrypi"),
  268. ],
  269. )
  270. def test__main_homeassistant_discovery_object_id(args, object_id):
  271. with unittest.mock.patch("systemctl_mqtt._run") as run_mock, unittest.mock.patch(
  272. "sys.argv", ["", "--mqtt-host", "mqtt-broker.local"] + args
  273. ), unittest.mock.patch(
  274. "systemctl_mqtt._utils.get_hostname", return_value="fallback"
  275. ):
  276. systemctl_mqtt._main()
  277. run_mock.assert_called_once()
  278. assert run_mock.call_args[1]["homeassistant_discovery_object_id"] == object_id
  279. @pytest.mark.parametrize(
  280. "args",
  281. [
  282. ["--homeassistant-discovery-object-id", "no pe"],
  283. ["--homeassistant-discovery-object-id", ""],
  284. ],
  285. )
  286. def test__main_homeassistant_discovery_object_id_invalid(args):
  287. with unittest.mock.patch(
  288. "sys.argv", ["", "--mqtt-host", "mqtt-broker.local"] + args
  289. ):
  290. with pytest.raises(ValueError):
  291. systemctl_mqtt._main()
  292. @pytest.mark.parametrize(
  293. ("args", "poweroff_delay"),
  294. [
  295. ([], datetime.timedelta(seconds=4)),
  296. (["--poweroff-delay-seconds", "42.21"], datetime.timedelta(seconds=42.21)),
  297. (["--poweroff-delay-seconds", "3600"], datetime.timedelta(hours=1)),
  298. ],
  299. )
  300. def test__main_poweroff_delay(args, poweroff_delay):
  301. with unittest.mock.patch("systemctl_mqtt._run") as run_mock, unittest.mock.patch(
  302. "sys.argv", ["", "--mqtt-host", "mqtt-broker.local"] + args
  303. ):
  304. systemctl_mqtt._main()
  305. run_mock.assert_called_once()
  306. assert run_mock.call_args[1]["poweroff_delay"] == poweroff_delay