Debian Codegraph @

test/units/playbook/test_play.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible 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 # (at your option) any later version.
9 #
10 # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import annotations
19
20 import pytest
21
22 from ansible.errors import AnsibleAssertionError, AnsibleParserError
23 from ansible.playbook.block import Block
24 from ansible.playbook.play import Play
25 from ansible.playbook.role import Role
26 from ansible.playbook.task import Task
27
28 from units.mock.loader import DictDataLoader
29
30
31 def test_play_with_hosts_string():
32 p = Play.load({'hosts': 'foo'})
33
34 assert p.get_name() == 'foo'
35
36
37 def test_basic_play():
38 p = Play.load(dict(
39 name="test play",
40 hosts=['foo'],
41 gather_facts=False,
42 connection='local',
43 remote_user="root",
44 become=True,
45 become_user="testing",
46 ))
47
48 assert p.name == 'test play'
49 assert p.hosts == ['foo']
50 assert p.connection == 'local'
51
52
53 def test_play_with_remote_user():
54 p = Play.load(dict(
55 name="test play",
56 hosts=['foo'],
57 user="testing",
58 gather_facts=False,
59 ))
60
61 assert p.remote_user == "testing"
62
63
64 def test_play_with_user_conflict():
65 play_data = dict(
66 name="test play",
67 hosts=['foo'],
68 user="testing",
69 remote_user="testing",
70 )
71
72 with pytest.raises(AnsibleParserError):
73 Play.load(play_data)
74
75
76 def test_play_with_bad_ds_type():
77 play_data = []
78 with pytest.raises(AnsibleAssertionError, match=r"while preprocessing data \(\[\]\), ds should be a dict but was a <(?:class|type) 'list'>"):
79 Play.load(play_data)
80
81
82 def test_play_with_tasks():
83 p = Play.load(dict(
84 name="test play",
85 hosts=['foo'],
86 gather_facts=False,
87 tasks=[dict(action='shell echo "hello world"')],
88 ))
89
90 assert len(p.tasks) == 1
91 assert isinstance(p.tasks[0], Block)
92 assert p.tasks[0].has_tasks() is True
93
94
95 def test_play_with_handlers():
96 p = Play.load(dict(
97 name="test play",
98 hosts=['foo'],
99 gather_facts=False,
100 handlers=[dict(action='shell echo "hello world"')],
101 ))
102
103 assert len(p.handlers) >= 1
104 assert len(p.get_handlers()) >= 1
105 assert isinstance(p.handlers[0], Block)
106 assert p.handlers[0].has_tasks() is True
107
108
109 def test_play_with_pre_tasks():
110 p = Play.load(dict(
111 name="test play",
112 hosts=['foo'],
113 gather_facts=False,
114 pre_tasks=[dict(action='shell echo "hello world"')],
115 ))
116
117 assert len(p.pre_tasks) >= 1
118 assert isinstance(p.pre_tasks[0], Block)
119 assert p.pre_tasks[0].has_tasks() is True
120
121 assert len(p.get_tasks()) >= 1
122 assert isinstance(p.get_tasks()[0][0], Task)
123 assert p.get_tasks()[0][0].action == 'shell'
124
125
126 def test_play_with_post_tasks():
127 p = Play.load(dict(
128 name="test play",
129 hosts=['foo'],
130 gather_facts=False,
131 post_tasks=[dict(action='shell echo "hello world"')],
132 ))
133
134 assert len(p.post_tasks) >= 1
135 assert isinstance(p.post_tasks[0], Block)
136 assert p.post_tasks[0].has_tasks() is True
137
138
139 def test_play_with_roles(mocker):
140 mocker.patch('ansible.playbook.role.definition.RoleDefinition._load_role_path', return_value=('foo', '/etc/ansible/roles/foo'))
141 fake_loader = DictDataLoader({
142 '/etc/ansible/roles/foo/tasks.yml': """
143 - name: role task
144 shell: echo "hello world"
145 """,
146 })
147
148 mock_var_manager = mocker.MagicMock()
149 mock_var_manager.get_vars.return_value = {}
150
151 p = Play.load(dict(
152 name="test play",
153 hosts=['foo'],
154 gather_facts=False,
155 roles=['foo'],
156 ), loader=fake_loader, variable_manager=mock_var_manager)
157
158 blocks = p.compile()
159 assert len(blocks) > 1
160 assert all(isinstance(block, Block) for block in blocks)
161 assert isinstance(p.get_roles()[0], Role)
162
163
164 def test_play_compile():
165 p = Play.load(dict(
166 name="test play",
167 hosts=['foo'],
168 gather_facts=False,
169 tasks=[dict(action='shell echo "hello world"')],
170 ))
171
172 blocks = p.compile()
173
174 # with a single block, there will still be three
175 # implicit meta flush_handler blocks inserted
176 assert len(blocks) == 4
177
178
179 @pytest.mark.parametrize(
180 'value, expected',
181 (
182 ('my_vars.yml', ['my_vars.yml']),
183 (['my_vars.yml'], ['my_vars.yml']),
184 (['my_vars1.yml', 'my_vars2.yml'], ['my_vars1.yml', 'my_vars2.yml']),
185 (None, []),
186 )
187 )
188 def test_play_with_vars_files(value, expected):
189 play = Play.load({
190 'name': 'Play with vars_files',
191 'hosts': ['testhost1'],
192 'vars_files': value,
193 })
194
195 assert play.vars_files == value
196 assert play.get_vars_files() == expected
197
198
199 @pytest.mark.parametrize('value', ([], tuple(), set(), {}, '', None, False, 0))
200 def test_play_empty_hosts(value):
201 with pytest.raises(AnsibleParserError, match='Hosts list cannot be empty'):
202 Play.load({'hosts': value})
203
204
205 @pytest.mark.parametrize('value', ([None], (None,), ['one', None]))
206 def test_play_none_hosts(value):
207 with pytest.raises(AnsibleParserError, match="Hosts list cannot contain values of 'None'"):
208 Play.load({'hosts': value})
209
210
211 @pytest.mark.parametrize(
212 'value',
213 (
214 {'one': None},
215 {'one': 'two'},
216 True,
217 1,
218 1.75,
219 )
220 )
221 def test_play_invalid_hosts_sequence(value):
222 with pytest.raises(AnsibleParserError, match='Hosts list must be a sequence or string'):
223 Play.load({'hosts': value})
224
225
226 @pytest.mark.parametrize(
227 'value',
228 (
229 [[1, 'two']],
230 [{'one': None}],
231 [set((None, 'one'))],
232 ['one', 'two', {'three': None}],
233 ['one', 'two', {'three': 'four'}],
234 )
235 )
236 def test_play_invalid_hosts_value(value):
237 with pytest.raises(AnsibleParserError, match='Hosts list contains an invalid host value'):
238 Play.load({'hosts': value})
239
240
241 def test_play_with_vars():
242 play = Play.load({}, vars={'var1': 'val1'})
243
244 assert play.get_name() == ''
245 assert play.vars == {'var1': 'val1'}
246 assert play.get_vars() == {'var1': 'val1'}
247
248
249 def test_play_no_name_hosts_sequence():
250 play = Play.load({'hosts': ['host1', 'host2']})
251
252 assert play.get_name() == 'host1,host2'
253
254
255 def test_play_hosts_template_expression():
256 play = Play.load({'hosts': "{{ target_hosts }}"})
257
258 assert play.get_name() == '{{ target_hosts }}'
259
260
261 @pytest.mark.parametrize(
262 'call',
263 (
264 '_load_tasks',
265 '_load_pre_tasks',
266 '_load_post_tasks',
267 '_load_handlers',
268 '_load_roles',
269 )
270 )
271 def test_bad_blocks_roles(mocker, call):
272 mocker.patch('ansible.playbook.play.load_list_of_blocks', side_effect=AssertionError('Raised intentionally'))
273 mocker.patch('ansible.playbook.play.load_list_of_roles', side_effect=AssertionError('Raised intentionally'))
274
275 play = Play.load({})
276 with pytest.raises(AnsibleParserError, match='A malformed (block|(role declaration)) was encountered'):
277 getattr(play, call)('', None)