test_state_dbus.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # systemctl-mqtt - MQTT client triggering 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 unittest.mock
  18. import pytest
  19. import systemctl_mqtt
  20. # pylint: disable=protected-access
  21. def test_shutdown_lock():
  22. lock_fd = unittest.mock.MagicMock()
  23. with unittest.mock.patch("systemctl_mqtt._get_login_manager"):
  24. state = systemctl_mqtt._State(mqtt_topic_prefix="any")
  25. state._login_manager.Inhibit.return_value = lock_fd
  26. state.acquire_shutdown_lock()
  27. state._login_manager.Inhibit.assert_called_once_with(
  28. "shutdown", "systemctl-mqtt", "Report shutdown via MQTT", "delay",
  29. )
  30. assert state._shutdown_lock == lock_fd
  31. # https://dbus.freedesktop.org/doc/dbus-python/dbus.types.html#dbus.types.UnixFd.take
  32. lock_fd.take.return_value = "fdnum"
  33. with unittest.mock.patch("os.close") as close_mock:
  34. state.release_shutdown_lock()
  35. close_mock.assert_called_once_with("fdnum")
  36. @pytest.mark.parametrize("active", [True, False])
  37. def test_prepare_for_shutdown_handler(active):
  38. with unittest.mock.patch("systemctl_mqtt._get_login_manager"):
  39. state = systemctl_mqtt._State(mqtt_topic_prefix="any")
  40. # pylint: disable=no-member,comparison-with-callable
  41. connect_to_signal_kwargs = state._login_manager.connect_to_signal.call_args[1]
  42. assert connect_to_signal_kwargs["signal_name"] == "PrepareForShutdown"
  43. handler_function = connect_to_signal_kwargs["handler_function"]
  44. assert handler_function == state.prepare_for_shutdown_handler
  45. with unittest.mock.patch.object(
  46. state, "acquire_shutdown_lock"
  47. ) as acquire_lock_mock, unittest.mock.patch.object(
  48. state, "release_shutdown_lock"
  49. ) as release_lock_mock:
  50. handler_function(active)
  51. if active:
  52. acquire_lock_mock.assert_not_called()
  53. release_lock_mock.assert_called_once_with()
  54. else:
  55. acquire_lock_mock.assert_called_once_with()
  56. release_lock_mock.assert_not_called()