Debian Codegraph @

test/units/plugins/action/test_reboot.py

raw
1 # Copyright (c) 2022 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3 """Tests for the reboot action plugin."""
4 from __future__ import annotations
5
6 import os
7
8 import pytest
9
10 from ansible.errors import AnsibleConnectionFailure
11 from ansible.playbook.task import Task
12 from ansible.plugins.action.reboot import ActionModule as RebootAction
13 from ansible.plugins.loader import connection_loader
14
15
16 @pytest.fixture
17 def task_args(request):
18 """Return playbook task args."""
19 return getattr(request, 'param', {})
20
21
22 @pytest.fixture
23 def module_task(mocker, task_args):
24 """Construct a task object."""
25 task = mocker.MagicMock(Task)
26 task.action = 'reboot'
27 task.args = task_args
28 task.async_val = False
29 task.check_mode = False
30 task.diff = False
31 return task
32
33
34 @pytest.fixture
35 def play_context(mocker):
36 """Construct a play context."""
37 ctx = mocker.MagicMock()
38 ctx.check_mode = False
39 ctx.shell = 'sh'
40 return ctx
41
42
43 @pytest.fixture
44 def action_plugin(play_context, module_task):
45 """Initialize an action plugin."""
46 connection = connection_loader.get('local', play_context, os.devnull)
47 loader = None
48 templar = None
49 shared_loader_obj = None
50
51 return RebootAction(
52 module_task,
53 connection,
54 play_context,
55 loader,
56 templar,
57 shared_loader_obj,
58 )
59
60
61 _SENTINEL_REBOOT_COMMAND = '/reboot-command-mock --arg'
62 _SENTINEL_SHORT_REBOOT_COMMAND = '/reboot-command-mock'
63 _SENTINEL_TEST_COMMAND = 'cmd-stub'
64
65
66 @pytest.mark.parametrize(
67 'task_args',
68 (
69 {
70 'reboot_timeout': 5,
71 'reboot_command': _SENTINEL_REBOOT_COMMAND,
72 'test_command': _SENTINEL_TEST_COMMAND,
73 },
74 {
75 'reboot_timeout': 5,
76 'reboot_command': _SENTINEL_SHORT_REBOOT_COMMAND,
77 'test_command': _SENTINEL_TEST_COMMAND,
78 },
79 ),
80 ids=('reboot command with spaces', 'reboot command without spaces'),
81 indirect=('task_args', ),
82 )
83 def test_reboot_command(action_plugin, mocker, monkeypatch, task_args):
84 """Check that the reboot command gets called and reboot verified."""
85 def _patched_low_level_execute_command(cmd, *args, **kwargs):
86 return {
87 _SENTINEL_TEST_COMMAND: {
88 'rc': 0,
89 'stderr': '<test command stub-stderr>',
90 'stdout': '<test command stub-stdout>',
91 },
92 _SENTINEL_REBOOT_COMMAND: {
93 'rc': 0,
94 'stderr': '<reboot command stub-stderr>',
95 'stdout': '<reboot command stub-stdout>',
96 },
97 f'{_SENTINEL_SHORT_REBOOT_COMMAND} ': { # no args is concatenated
98 'rc': 0,
99 'stderr': '<short reboot command stub-stderr>',
100 'stdout': '<short reboot command stub-stdout>',
101 },
102 }[cmd]
103
104 monkeypatch.setattr(
105 action_plugin,
106 '_low_level_execute_command',
107 _patched_low_level_execute_command,
108 )
109
110 action_plugin._connection = mocker.Mock()
111
112 monkeypatch.setattr(action_plugin, 'check_boot_time', lambda *_a, **_kw: 5)
113 monkeypatch.setattr(action_plugin, 'get_distribution', mocker.MagicMock())
114 monkeypatch.setattr(action_plugin, 'get_system_boot_time', lambda d: 0)
115
116 low_level_cmd_spy = mocker.spy(action_plugin, '_low_level_execute_command')
117
118 action_result = action_plugin.run()
119
120 assert low_level_cmd_spy.called
121
122 expected_reboot_command = (
123 task_args['reboot_command'] if ' ' in task_args['reboot_command']
124 else f'{task_args["reboot_command"] !s} '
125 )
126 low_level_cmd_spy.assert_any_call(expected_reboot_command, sudoable=True)
127 low_level_cmd_spy.assert_any_call(task_args['test_command'], sudoable=True)
128
129 assert low_level_cmd_spy.call_count == 2
130 assert low_level_cmd_spy.spy_return == {
131 'rc': 0,
132 'stderr': '<test command stub-stderr>',
133 'stdout': '<test command stub-stdout>',
134 }
135 assert low_level_cmd_spy.spy_exception is None
136
137 assert 'failed' not in action_result
138 assert action_result == {'rebooted': True, 'changed': True, 'elapsed': 0}
139
140
141 @pytest.mark.parametrize(
142 'task_args',
143 (
144 {
145 'reboot_timeout': 5,
146 'reboot_command': _SENTINEL_REBOOT_COMMAND,
147 'test_command': _SENTINEL_TEST_COMMAND,
148 },
149 ),
150 ids=('reboot command with spaces', ),
151 indirect=('task_args', ),
152 )
153 def test_reboot_command_connection_fail(action_plugin, mocker, monkeypatch, task_args):
154 """Check that the reboot command gets called and reboot verified."""
155 def _patched_low_level_execute_command(cmd, *args, **kwargs):
156 if cmd == _SENTINEL_REBOOT_COMMAND:
157 raise AnsibleConnectionFailure('Fake connection drop')
158 return {
159 _SENTINEL_TEST_COMMAND: {
160 'rc': 0,
161 'stderr': '<test command stub-stderr>',
162 'stdout': '<test command stub-stdout>',
163 },
164 }[cmd]
165
166 monkeypatch.setattr(
167 action_plugin,
168 '_low_level_execute_command',
169 _patched_low_level_execute_command,
170 )
171
172 action_plugin._connection = mocker.Mock()
173
174 monkeypatch.setattr(action_plugin, 'check_boot_time', lambda *_a, **_kw: 5)
175 monkeypatch.setattr(action_plugin, 'get_distribution', mocker.MagicMock())
176 monkeypatch.setattr(action_plugin, 'get_system_boot_time', lambda d: 0)
177
178 low_level_cmd_spy = mocker.spy(action_plugin, '_low_level_execute_command')
179
180 action_result = action_plugin.run()
181
182 assert low_level_cmd_spy.called
183
184 low_level_cmd_spy.assert_any_call(
185 task_args['reboot_command'], sudoable=True,
186 )
187 low_level_cmd_spy.assert_any_call(task_args['test_command'], sudoable=True)
188
189 assert low_level_cmd_spy.call_count == 2
190 assert low_level_cmd_spy.spy_return == {
191 'rc': 0,
192 'stderr': '<test command stub-stderr>',
193 'stdout': '<test command stub-stdout>',
194 }
195
196 assert 'failed' not in action_result
197 assert action_result == {'rebooted': True, 'changed': True, 'elapsed': 0}
198
199
200 def test_reboot_connection_local(action_plugin, module_task):
201 """Verify that using local connection doesn't let reboot happen."""
202 expected_message = ' '.join(
203 (
204 'Running', module_task.action,
205 'with local connection would reboot the control node.',
206 ),
207 )
208 expected_action_result = {
209 'changed': False,
210 'elapsed': 0,
211 'failed': True,
212 'msg': expected_message,
213 'rebooted': False,
214 }
215
216 action_result = action_plugin.run()
217
218 assert action_result == expected_action_result