Controller/tests/test_systimecfg.py

104 lines
3.3 KiB
Python

# coding=utf-8
import subprocess
from unittest import mock
import pytest
from datetime import datetime
from tests import fixtures
from tsgrain_controller import systimecfg
@pytest.mark.parametrize('cmd_str, raise_err', [
(f"{fixtures.CMD_SET_DATE} -s '2022-01-18 18:29:14'", False),
(f"{fixtures.CMD_ERR} -s '2022-01-18 18:29:14'", True),
])
def test_run_cmd(cmd_str: str, raise_err: bool):
if raise_err:
with pytest.raises(systimecfg.ErrorTimeConfig):
systimecfg._run_cmd(cmd_str)
else:
systimecfg._run_cmd(cmd_str)
def test_get_system_timezone(mocker):
mock_res = mock.Mock()
mock_res.stdout = 'Europe/Berlin'
cmd_run_mock: mock.MagicMock = mocker.patch('subprocess.run',
return_value=mock_res)
tz = systimecfg.get_system_timezone()
assert tz == 'Europe/Berlin'
cmd_parts = ['cat', '/etc/timezone']
cmd_run_mock.assert_called_once_with(cmd_parts,
check=True,
universal_newlines=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
def test_get_system_timezone_err(mocker):
mock_res = mock.Mock()
mock_res.stdout = 'Europe Berlin'
mocker.patch('subprocess.run', return_value=mock_res)
with pytest.raises(systimecfg.ErrorInvalidTimezone):
systimecfg.get_system_timezone()
def test_set_system_datetime(mocker):
cmd_run_mock: mock.MagicMock = mocker.patch('subprocess.run')
date_time = datetime(2021, 12, 25, 16, 30, 14)
cmd_tmpl = "date -s '%Y-%m-%d %H:%M:%S'"
systimecfg.set_system_datetime(date_time, cmd_tmpl)
cmd_parts = ['date', '-s', '2021-12-25 16:30:14']
cmd_run_mock.assert_called_once_with(cmd_parts,
check=True,
universal_newlines=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
def test_set_system_timezone(mocker):
cmd_run_mock: mock.MagicMock = mocker.patch('subprocess.run')
tz = 'Europe/Berlin'
cmd_tmpl = "timedatectl set-timezone {TZ}"
systimecfg.set_system_timezone(tz, cmd_tmpl)
cmd_parts = ['timedatectl', 'set-timezone', 'Europe/Berlin']
cmd_run_mock.assert_called_once_with(cmd_parts,
check=True,
universal_newlines=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
def test_set_system_timezone_invalid(mocker):
cmd_run_mock: mock.MagicMock = mocker.patch('subprocess.run')
tz = 'Europe + Berlin'
cmd_tmpl = "timedatectl set-timezone {TZ}"
with pytest.raises(systimecfg.ErrorInvalidTimezone):
systimecfg.set_system_timezone(tz, cmd_tmpl)
cmd_run_mock.assert_not_called()
def test_set_system_tmpl_invalid(mocker):
cmd_run_mock: mock.MagicMock = mocker.patch('subprocess.run')
tz = 'Europe/Berlin'
cmd_tmpl = "timedatectl set-timezone"
with pytest.raises(systimecfg.ErrorInvalidCmdTemplate):
systimecfg.set_system_timezone(tz, cmd_tmpl)
cmd_run_mock.assert_not_called()