test_cli.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. controlled_system_unit_names=[],
  179. )
  180. @pytest.mark.parametrize(
  181. ("password_file_content", "expected_password"),
  182. [
  183. ("secret", "secret"),
  184. ("secret space", "secret space"),
  185. ("secret ", "secret "),
  186. (" secret ", " secret "),
  187. ("secret\n", "secret"),
  188. ("secret\n\n", "secret\n"),
  189. ("secret\r\n", "secret"),
  190. ("secret\n\r\n", "secret\n"),
  191. ("你好\n", "你好"),
  192. ],
  193. )
  194. def test__main_password_file(tmpdir, password_file_content, expected_password):
  195. mqtt_password_path = tmpdir.join("mqtt-password")
  196. with mqtt_password_path.open("w") as mqtt_password_file:
  197. mqtt_password_file.write(password_file_content)
  198. with unittest.mock.patch("systemctl_mqtt._run") as run_mock, unittest.mock.patch(
  199. "sys.argv",
  200. [
  201. "",
  202. "--mqtt-host",
  203. "localhost",
  204. "--mqtt-username",
  205. "me",
  206. "--mqtt-password-file",
  207. str(mqtt_password_path),
  208. ],
  209. ), unittest.mock.patch(
  210. "systemctl_mqtt._utils.get_hostname", return_value="hostname"
  211. ):
  212. # pylint: disable=protected-access
  213. systemctl_mqtt._main()
  214. run_mock.assert_called_once_with(
  215. mqtt_host="localhost",
  216. mqtt_port=8883,
  217. mqtt_disable_tls=False,
  218. mqtt_username="me",
  219. mqtt_password=expected_password,
  220. mqtt_topic_prefix="systemctl/hostname",
  221. homeassistant_discovery_prefix="homeassistant",
  222. homeassistant_discovery_object_id="systemctl-mqtt-hostname",
  223. poweroff_delay=datetime.timedelta(seconds=4),
  224. monitored_system_unit_names=[],
  225. controlled_system_unit_names=[],
  226. )
  227. def test__main_password_file_collision(capsys):
  228. with unittest.mock.patch(
  229. "sys.argv",
  230. [
  231. "",
  232. "--mqtt-host",
  233. "localhost",
  234. "--mqtt-username",
  235. "me",
  236. "--mqtt-password",
  237. "secret",
  238. "--mqtt-password-file",
  239. "/var/lib/secrets/mqtt/password",
  240. ],
  241. ):
  242. with pytest.raises(SystemExit):
  243. # pylint: disable=protected-access
  244. systemctl_mqtt._main()
  245. out, err = capsys.readouterr()
  246. assert not out
  247. assert (
  248. "argument --mqtt-password-file: not allowed with argument --mqtt-password\n"
  249. in err
  250. )
  251. @pytest.mark.parametrize(
  252. ("args", "discovery_prefix"),
  253. [
  254. ([], "homeassistant"),
  255. (["--homeassistant-discovery-prefix", "home/assistant"], "home/assistant"),
  256. ],
  257. )
  258. def test__main_homeassistant_discovery_prefix(args, discovery_prefix):
  259. with unittest.mock.patch("systemctl_mqtt._run") as run_mock, unittest.mock.patch(
  260. "sys.argv", ["", "--mqtt-host", "mqtt-broker.local"] + args
  261. ):
  262. systemctl_mqtt._main()
  263. run_mock.assert_called_once()
  264. assert run_mock.call_args[1]["homeassistant_discovery_prefix"] == discovery_prefix
  265. @pytest.mark.parametrize(
  266. ("args", "object_id"),
  267. [
  268. ([], "systemctl-mqtt-fallback"),
  269. (["--homeassistant-discovery-object-id", "raspberrypi"], "raspberrypi"),
  270. ],
  271. )
  272. def test__main_homeassistant_discovery_object_id(args, object_id):
  273. with unittest.mock.patch("systemctl_mqtt._run") as run_mock, unittest.mock.patch(
  274. "sys.argv", ["", "--mqtt-host", "mqtt-broker.local"] + args
  275. ), unittest.mock.patch(
  276. "systemctl_mqtt._utils.get_hostname", return_value="fallback"
  277. ):
  278. systemctl_mqtt._main()
  279. run_mock.assert_called_once()
  280. assert run_mock.call_args[1]["homeassistant_discovery_object_id"] == object_id
  281. @pytest.mark.parametrize(
  282. "args",
  283. [
  284. ["--homeassistant-discovery-object-id", "no pe"],
  285. ["--homeassistant-discovery-object-id", ""],
  286. ],
  287. )
  288. def test__main_homeassistant_discovery_object_id_invalid(args):
  289. with unittest.mock.patch(
  290. "sys.argv", ["", "--mqtt-host", "mqtt-broker.local"] + args
  291. ):
  292. with pytest.raises(ValueError):
  293. systemctl_mqtt._main()
  294. @pytest.mark.parametrize(
  295. ("args", "poweroff_delay"),
  296. [
  297. ([], datetime.timedelta(seconds=4)),
  298. (["--poweroff-delay-seconds", "42.21"], datetime.timedelta(seconds=42.21)),
  299. (["--poweroff-delay-seconds", "3600"], datetime.timedelta(hours=1)),
  300. ],
  301. )
  302. def test__main_poweroff_delay(args, poweroff_delay):
  303. with unittest.mock.patch("systemctl_mqtt._run") as run_mock, unittest.mock.patch(
  304. "sys.argv", ["", "--mqtt-host", "mqtt-broker.local"] + args
  305. ):
  306. systemctl_mqtt._main()
  307. run_mock.assert_called_once()
  308. assert run_mock.call_args[1]["poweroff_delay"] == poweroff_delay