Debian Codegraph @

test/units/module_utils/basic/test_argument_spec.py

raw
1 # -*- coding: utf-8 -*-
2 # (c) 2012-2014, Michael DeHaan <[email protected]>
3 # (c) 2016 Toshio Kuratomi <[email protected]>
4 # Copyright: Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import annotations
8
9 import json
10 import os
11 import typing as t
12
13 import pytest
14
15 from unittest.mock import MagicMock
16 from ansible.module_utils import basic
17 from ansible.module_utils.api import basic_auth_argument_spec, rate_limit_argument_spec, retry_argument_spec
18 from ansible.module_utils.common.warnings import get_deprecation_messages, get_warning_messages
19 import builtins
20
21
22 pytestmark = pytest.mark.usefixtures("module_env_mocker")
23
24 MOCK_VALIDATOR_FAIL = MagicMock(side_effect=TypeError("bad conversion"))
25 # Data is argspec, argument, expected
26 VALID_SPECS = (
27 # Simple type=int
28 ({'arg': {'type': 'int'}}, {'arg': 42}, 42),
29 # Simple type=int with a large value (will be of type long under Python 2)
30 ({'arg': {'type': 'int'}}, {'arg': 18765432109876543210}, 18765432109876543210),
31 # Simple type=list, elements=int
32 ({'arg': {'type': 'list', 'elements': 'int'}}, {'arg': [42, 32]}, [42, 32]),
33 # Type=int with conversion from string
34 ({'arg': {'type': 'int'}}, {'arg': '42'}, 42),
35 # Type=list elements=int with conversion from string
36 ({'arg': {'type': 'list', 'elements': 'int'}}, {'arg': ['42', '32']}, [42, 32]),
37 # Simple type=float
38 ({'arg': {'type': 'float'}}, {'arg': 42.0}, 42.0),
39 # Simple type=list, elements=float
40 ({'arg': {'type': 'list', 'elements': 'float'}}, {'arg': [42.1, 32.2]}, [42.1, 32.2]),
41 # Type=float conversion from int
42 ({'arg': {'type': 'float'}}, {'arg': 42}, 42.0),
43 # type=list, elements=float conversion from int
44 ({'arg': {'type': 'list', 'elements': 'float'}}, {'arg': [42, 32]}, [42.0, 32.0]),
45 # Type=float conversion from string
46 ({'arg': {'type': 'float'}}, {'arg': '42.0'}, 42.0),
47 # type=list, elements=float conversion from string
48 ({'arg': {'type': 'list', 'elements': 'float'}}, {'arg': ['42.1', '32.2']}, [42.1, 32.2]),
49 # Type=float conversion from string without decimal point
50 ({'arg': {'type': 'float'}}, {'arg': '42'}, 42.0),
51 # Type=list elements=float conversion from string without decimal point
52 ({'arg': {'type': 'list', 'elements': 'float'}}, {'arg': ['42', '32.2']}, [42.0, 32.2]),
53 # Simple type=bool
54 ({'arg': {'type': 'bool'}}, {'arg': True}, True),
55 # Simple type=list elements=bool
56 ({'arg': {'type': 'list', 'elements': 'bool'}}, {'arg': [True, 'true', 1, 'yes', False, 'false', 'no', 0]},
57 [True, True, True, True, False, False, False, False]),
58 # Type=int with conversion from string
59 ({'arg': {'type': 'bool'}}, {'arg': 'yes'}, True),
60 # Type=str converts to string
61 ({'arg': {'type': 'str'}}, {'arg': 42}, '42'),
62 # Type=list elements=str simple converts to string
63 ({'arg': {'type': 'list', 'elements': 'str'}}, {'arg': ['42', '32']}, ['42', '32']),
64 # Type is implicit, converts to string
65 ({'arg': {'type': 'str'}}, {'arg': 42}, '42'),
66 # Type=list elements=str implicit converts to string
67 ({'arg': {'type': 'list', 'elements': 'str'}}, {'arg': [42, 32]}, ['42', '32']),
68 # parameter is required
69 ({'arg': {'required': True}}, {'arg': 42}, '42'),
70 # ignored unknown parameters
71 ({'arg': {'type': 'int'}}, {'arg': 1, 'invalid': True, '_ansible_ignore_unknown_opts': True}, 1),
72 )
73
74 INVALID_SPECS: tuple[tuple[dict[str, t.Any], dict[str, t.Any], str], ...] = (
75 # Type is int; unable to convert this string
76 ({'arg': {'type': 'int'}}, {'arg': "wolf"}, "is of type str and we were unable to convert to int"),
77 # Type is list elements is int; unable to convert this string
78 ({'arg': {'type': 'list', 'elements': 'int'}}, {'arg': [1, "bad"]}, "is of type str and we were unable to convert to int"),
79 # Type is int; unable to convert float
80 ({'arg': {'type': 'int'}}, {'arg': 42.1}, "is of type float and we were unable to convert to int:"),
81 # Type is list, elements is int; unable to convert float
82 ({'arg': {'type': 'list', 'elements': 'int'}}, {'arg': [42.1, 32, 2]}, "is of type float and we were unable to convert to int:"),
83 # type is a callable that fails to convert
84 ({'arg': {'type': MOCK_VALIDATOR_FAIL}}, {'arg': "bad"}, "bad conversion"),
85 # type is a list, elements is callable that fails to convert
86 ({'arg': {'type': 'list', 'elements': MOCK_VALIDATOR_FAIL}}, {'arg': [1, "bad"]}, "bad conversion"),
87 # unknown parameter
88 ({'arg': {'type': 'int'}}, {'other': 'bad', '_ansible_module_name': 'ansible_unittest'},
89 'Unsupported parameters for (ansible_unittest) module: other. Supported parameters include: arg.'),
90 ({'arg': {'type': 'int', 'aliases': ['argument']}}, {'other': 'bad', '_ansible_module_name': 'ansible_unittest'},
91 'Unsupported parameters for (ansible_unittest) module: other. Supported parameters include: arg (argument).'),
92 # parameter is required
93 ({'arg': {'required': True}}, {}, 'missing required arguments: arg'),
94 )
95
96 BASIC_AUTH_VALID_ARGS = [
97 {'api_username': 'user1', 'api_password': 'password1', 'api_url': 'http://example.com', 'validate_certs': False},
98 {'api_username': 'user1', 'api_password': 'password1', 'api_url': 'http://example.com', 'validate_certs': True},
99 ]
100
101 RATE_LIMIT_VALID_ARGS = [
102 {'rate': 1, 'rate_limit': 1},
103 {'rate': '1', 'rate_limit': 1},
104 {'rate': 1, 'rate_limit': '1'},
105 {'rate': '1', 'rate_limit': '1'},
106 ]
107
108 RETRY_VALID_ARGS = [
109 {'retries': 1, 'retry_pause': 1.5},
110 {'retries': '1', 'retry_pause': '1.5'},
111 {'retries': 1, 'retry_pause': '1.5'},
112 {'retries': '1', 'retry_pause': 1.5},
113 ]
114
115
116 @pytest.fixture
117 def complex_argspec():
118 arg_spec = dict(
119 foo=dict(required=True, aliases=['dup']),
120 bar=dict(),
121 bam=dict(),
122 bing=dict(),
123 bang=dict(),
124 bong=dict(),
125 baz=dict(fallback=(basic.env_fallback, ['BAZ'])),
126 bar1=dict(type='bool'),
127 bar3=dict(type='list', elements='path'),
128 bar_str=dict(type='list', elements=str),
129 zardoz=dict(choices=['one', 'two']),
130 zardoz2=dict(type='list', choices=['one', 'two', 'three']),
131 zardoz3=dict(type='str', aliases=['zodraz'], deprecated_aliases=[dict(name='zodraz', version='9.99')]),
132 )
133 mut_ex = (('bar', 'bam'), ('bing', 'bang', 'bong'))
134 req_to = (('bam', 'baz'),)
135
136 kwargs = dict(
137 argument_spec=arg_spec,
138 mutually_exclusive=mut_ex,
139 required_together=req_to,
140 no_log=True,
141 add_file_common_args=True,
142 supports_check_mode=True,
143 )
144 return kwargs
145
146
147 @pytest.fixture
148 def options_argspec_list():
149 options_spec = dict(
150 foo=dict(required=True, aliases=['dup']),
151 bar=dict(),
152 bar1=dict(type='list', elements='str'),
153 bar2=dict(type='list', elements='int'),
154 bar3=dict(type='list', elements='float'),
155 bar4=dict(type='list', elements='path'),
156 bam=dict(),
157 baz=dict(fallback=(basic.env_fallback, ['BAZ'])),
158 bam1=dict(),
159 bam2=dict(default='test'),
160 bam3=dict(type='bool'),
161 bam4=dict(type='str'),
162 )
163
164 arg_spec = dict(
165 foobar=dict(
166 type='list',
167 elements='dict',
168 options=options_spec,
169 mutually_exclusive=[
170 ['bam', 'bam1'],
171 ],
172 required_if=[
173 ['foo', 'hello', ['bam']],
174 ['foo', 'bam2', ['bam2']]
175 ],
176 required_one_of=[
177 ['bar', 'bam']
178 ],
179 required_together=[
180 ['bam1', 'baz']
181 ],
182 required_by={
183 'bam4': ('bam1', 'bam3'),
184 },
185 )
186 )
187
188 kwargs = dict(
189 argument_spec=arg_spec,
190 no_log=True,
191 add_file_common_args=True,
192 supports_check_mode=True
193 )
194 return kwargs
195
196
197 @pytest.fixture
198 def options_argspec_dict(options_argspec_list):
199 # should test ok, for options in dict format.
200 kwargs = options_argspec_list
201 kwargs['argument_spec']['foobar']['type'] = 'dict'
202 kwargs['argument_spec']['foobar']['elements'] = None
203
204 return kwargs
205
206
207 #
208 # Tests for one aspect of arg_spec
209 #
210
211 @pytest.mark.parametrize('argspec, expected, stdin', [(s[0], s[2], s[1]) for s in VALID_SPECS],
212 indirect=['stdin'])
213 def test_validator_basic_types(argspec, expected, stdin):
214
215 am = basic.AnsibleModule(argspec)
216
217 if 'type' in argspec['arg']:
218 if argspec['arg']['type'] == 'int':
219 type_ = int
220 else:
221 type_ = getattr(builtins, argspec['arg']['type'])
222 else:
223 type_ = str
224
225 assert isinstance(am.params['arg'], type_)
226 assert am.params['arg'] == expected
227
228
229 @pytest.mark.parametrize('stdin', [{'arg': 42}, {'arg': 18765432109876543210}], indirect=['stdin'])
230 def test_validator_function(mocker, stdin):
231 # Type is a callable
232 MOCK_VALIDATOR_SUCCESS = mocker.MagicMock(return_value=27)
233 argspec = {'arg': {'type': MOCK_VALIDATOR_SUCCESS}}
234 am = basic.AnsibleModule(argspec)
235
236 assert isinstance(am.params['arg'], int)
237 assert am.params['arg'] == 27
238
239
240 @pytest.mark.parametrize('stdin', BASIC_AUTH_VALID_ARGS, indirect=['stdin'])
241 def test_validate_basic_auth_arg(mocker, stdin):
242 kwargs = dict(
243 argument_spec=basic_auth_argument_spec()
244 )
245 am = basic.AnsibleModule(**kwargs)
246 assert isinstance(am.params['api_username'], str)
247 assert isinstance(am.params['api_password'], str)
248 assert isinstance(am.params['api_url'], str)
249 assert isinstance(am.params['validate_certs'], bool)
250
251
252 @pytest.mark.parametrize('stdin', RATE_LIMIT_VALID_ARGS, indirect=['stdin'])
253 def test_validate_rate_limit_argument_spec(mocker, stdin):
254 kwargs = dict(
255 argument_spec=rate_limit_argument_spec()
256 )
257 am = basic.AnsibleModule(**kwargs)
258 assert isinstance(am.params['rate'], int)
259 assert isinstance(am.params['rate_limit'], int)
260
261
262 @pytest.mark.parametrize('stdin', RETRY_VALID_ARGS, indirect=['stdin'])
263 def test_validate_retry_argument_spec(mocker, stdin):
264 kwargs = dict(
265 argument_spec=retry_argument_spec()
266 )
267 am = basic.AnsibleModule(**kwargs)
268 assert isinstance(am.params['retries'], int)
269 assert isinstance(am.params['retry_pause'], float)
270
271
272 @pytest.mark.parametrize('stdin', [{'arg': '123'}, {'arg': 123}], indirect=['stdin'])
273 def test_validator_string_type(mocker, stdin):
274 # Custom callable that is 'str'
275 argspec = {'arg': {'type': str}}
276 am = basic.AnsibleModule(argspec)
277
278 assert isinstance(am.params['arg'], str)
279 assert am.params['arg'] == '123'
280
281
282 @pytest.mark.parametrize('argspec, expected, stdin', [(s[0], s[2], s[1]) for s in INVALID_SPECS],
283 indirect=['stdin'])
284 def test_validator_fail(stdin, capfd, argspec, expected):
285 with pytest.raises(SystemExit):
286 basic.AnsibleModule(argument_spec=argspec)
287
288 out, err = capfd.readouterr()
289 assert not err
290 assert expected in json.loads(out)['msg']
291 assert json.loads(out)['failed']
292
293
294 class TestComplexArgSpecs:
295 """Test with a more complex arg_spec"""
296
297 @pytest.mark.parametrize('stdin', [{'foo': 'hello'}, {'dup': 'hello'}], indirect=['stdin'])
298 def test_complex_required(self, stdin, complex_argspec):
299 """Test that the complex argspec works if we give it its required param as either the canonical or aliased name"""
300 am = basic.AnsibleModule(**complex_argspec)
301 assert isinstance(am.params['foo'], str)
302 assert am.params['foo'] == 'hello'
303
304 @pytest.mark.parametrize('stdin', [{'foo': 'hello1', 'dup': 'hello2'}], indirect=['stdin'])
305 def test_complex_duplicate_warning(self, stdin, complex_argspec):
306 """Test that the complex argspec issues a warning if we specify an option both with its canonical name and its alias"""
307 am = basic.AnsibleModule(**complex_argspec)
308 assert isinstance(am.params['foo'], str)
309 assert 'Both option foo and its alias dup are set.' in get_warning_messages()
310 assert am.params['foo'] == 'hello2'
311
312 @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'bam': 'test'}], indirect=['stdin'])
313 def test_complex_type_fallback(self, mocker, stdin, complex_argspec):
314 """Test that the complex argspec works if we get a required parameter via fallback"""
315 environ = os.environ.copy()
316 environ['BAZ'] = 'test data'
317 mocker.patch('ansible.module_utils.basic.os.environ', environ)
318
319 am = basic.AnsibleModule(**complex_argspec)
320
321 assert isinstance(am.params['baz'], str)
322 assert am.params['baz'] == 'test data'
323
324 @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'bar': 'bad', 'bam': 'bad2', 'bing': 'a', 'bang': 'b', 'bong': 'c'}], indirect=['stdin'])
325 def test_fail_mutually_exclusive(self, capfd, stdin, complex_argspec):
326 """Fail because of mutually exclusive parameters"""
327 with pytest.raises(SystemExit):
328 am = basic.AnsibleModule(**complex_argspec)
329
330 out, err = capfd.readouterr()
331 results = json.loads(out)
332
333 assert results['failed']
334 assert results['msg'] == "parameters are mutually exclusive: bar|bam, bing|bang|bong"
335
336 @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'bam': 'bad2'}], indirect=['stdin'])
337 def test_fail_required_together(self, capfd, stdin, complex_argspec):
338 """Fail because only one of a required_together pair of parameters was specified"""
339 with pytest.raises(SystemExit):
340 am = basic.AnsibleModule(**complex_argspec)
341
342 out, err = capfd.readouterr()
343 results = json.loads(out)
344
345 assert results['failed']
346 assert results['msg'] == "parameters are required together: bam, baz"
347
348 @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'bar': 'hi'}], indirect=['stdin'])
349 def test_fail_required_together_and_default(self, capfd, stdin, complex_argspec):
350 """Fail because one of a required_together pair of parameters has a default and the other was not specified"""
351 complex_argspec['argument_spec']['baz'] = {'default': 42}
352 with pytest.raises(SystemExit):
353 am = basic.AnsibleModule(**complex_argspec)
354
355 out, err = capfd.readouterr()
356 results = json.loads(out)
357
358 assert results['failed']
359 assert results['msg'] == "parameters are required together: bam, baz"
360
361 @pytest.mark.parametrize('stdin', [{'foo': 'hello'}], indirect=['stdin'])
362 def test_fail_required_together_and_fallback(self, capfd, mocker, stdin, complex_argspec):
363 """Fail because one of a required_together pair of parameters has a fallback and the other was not specified"""
364 environ = os.environ.copy()
365 environ['BAZ'] = 'test data'
366 mocker.patch('ansible.module_utils.basic.os.environ', environ)
367
368 with pytest.raises(SystemExit):
369 am = basic.AnsibleModule(**complex_argspec)
370
371 out, err = capfd.readouterr()
372 results = json.loads(out)
373
374 assert results['failed']
375 assert results['msg'] == "parameters are required together: bam, baz"
376
377 @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'zardoz2': ['one', 'four', 'five']}], indirect=['stdin'])
378 def test_fail_list_with_choices(self, capfd, mocker, stdin, complex_argspec):
379 """Fail because one of the items is not in the choice"""
380 with pytest.raises(SystemExit):
381 basic.AnsibleModule(**complex_argspec)
382
383 out, err = capfd.readouterr()
384 results = json.loads(out)
385
386 assert results['failed']
387 assert results['msg'] == "value of zardoz2 must be one or more of: one, two, three. Got no match for: four, five"
388
389 @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'zardoz2': ['one', 'three']}], indirect=['stdin'])
390 def test_list_with_choices(self, capfd, mocker, stdin, complex_argspec):
391 """Test choices with list"""
392 am = basic.AnsibleModule(**complex_argspec)
393 assert isinstance(am.params['zardoz2'], list)
394 assert am.params['zardoz2'] == ['one', 'three']
395
396 @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'bar3': ['~/test', 'test/']}], indirect=['stdin'])
397 def test_list_with_elements_path(self, capfd, mocker, stdin, complex_argspec):
398 """Test choices with list"""
399 am = basic.AnsibleModule(**complex_argspec)
400 assert isinstance(am.params['bar3'], list)
401 assert am.params['bar3'][0].startswith('/')
402 assert am.params['bar3'][1] == 'test/'
403
404 @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'zodraz': 'one'}], indirect=['stdin'])
405 def test_deprecated_alias(self, capfd, mocker, stdin, complex_argspec):
406 """Test a deprecated alias"""
407 am = basic.AnsibleModule(**complex_argspec)
408
409 assert "Alias 'zodraz' is deprecated." in get_deprecation_messages()[0]['msg']
410 assert get_deprecation_messages()[0]['version'] == '9.99'
411
412 @pytest.mark.parametrize('stdin', [{'foo': 'hello', 'bar_str': [867, '5309']}], indirect=['stdin'])
413 def test_list_with_elements_callable_str(self, capfd, mocker, stdin, complex_argspec):
414 """Test choices with list"""
415 am = basic.AnsibleModule(**complex_argspec)
416 assert isinstance(am.params['bar_str'], list)
417 assert isinstance(am.params['bar_str'][0], str)
418 assert isinstance(am.params['bar_str'][1], str)
419 assert am.params['bar_str'][0] == '867'
420 assert am.params['bar_str'][1] == '5309'
421
422
423 class TestComplexOptions:
424 """Test arg spec options"""
425
426 # (Parameters, expected value of module.params['foobar'])
427 OPTIONS_PARAMS_LIST = (
428 ({'foobar': [{"foo": "hello", "bam": "good"}, {"foo": "test", "bar": "good"}]},
429 [{'foo': 'hello', 'bam': 'good', 'bam2': 'test', 'bar': None, 'baz': None, 'bam1': None, 'bam3': None, 'bam4': None,
430 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None},
431 {'foo': 'test', 'bam': None, 'bam2': 'test', 'bar': 'good', 'baz': None, 'bam1': None, 'bam3': None, 'bam4': None,
432 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None}]
433 ),
434 # Alias for required param
435 ({'foobar': [{"dup": "test", "bar": "good"}]},
436 [{'foo': 'test', 'dup': 'test', 'bam': None, 'bam2': 'test', 'bar': 'good', 'baz': None, 'bam1': None, 'bam3': None, 'bam4': None,
437 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None}]
438 ),
439 # Required_if utilizing default value of the requirement
440 ({'foobar': [{"foo": "bam2", "bar": "required_one_of"}]},
441 [{'bam': None, 'bam1': None, 'bam2': 'test', 'bam3': None, 'bam4': None, 'bar': 'required_one_of', 'baz': None, 'foo': 'bam2',
442 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None}]
443 ),
444 # Check that a bool option is converted
445 ({"foobar": [{"foo": "required", "bam": "good", "bam3": "yes"}]},
446 [{'bam': 'good', 'bam1': None, 'bam2': 'test', 'bam3': True, 'bam4': None, 'bar': None, 'baz': None, 'foo': 'required',
447 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None}]
448 ),
449 # Check required_by options
450 ({"foobar": [{"foo": "required", "bar": "good", "baz": "good", "bam4": "required_by", "bam1": "ok", "bam3": "yes"}]},
451 [{'bar': 'good', 'baz': 'good', 'bam1': 'ok', 'bam2': 'test', 'bam3': True, 'bam4': 'required_by', 'bam': None, 'foo': 'required',
452 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None}]
453 ),
454 # Check for elements in sub-options
455 ({"foobar": [{"foo": "good", "bam": "required_one_of", "bar1": [1, "good", "yes"], "bar2": ['1', 1], "bar3": ['1.3', 1.3, 1]}]},
456 [{'foo': 'good', 'bam1': None, 'bam2': 'test', 'bam3': None, 'bam4': None, 'bar': None, 'baz': None, 'bam': 'required_one_of',
457 'bar1': ["1", "good", "yes"], 'bar2': [1, 1], 'bar3': [1.3, 1.3, 1.0], 'bar4': None}]
458 ),
459 )
460
461 # (Parameters, expected value of module.params['foobar'])
462 OPTIONS_PARAMS_DICT = (
463 ({'foobar': {"foo": "hello", "bam": "good"}},
464 {'foo': 'hello', 'bam': 'good', 'bam2': 'test', 'bar': None, 'baz': None, 'bam1': None, 'bam3': None, 'bam4': None,
465 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None}
466 ),
467 # Alias for required param
468 ({'foobar': {"dup": "test", "bar": "good"}},
469 {'foo': 'test', 'dup': 'test', 'bam': None, 'bam2': 'test', 'bar': 'good', 'baz': None, 'bam1': None, 'bam3': None, 'bam4': None,
470 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None}
471 ),
472 # Required_if utilizing default value of the requirement
473 ({'foobar': {"foo": "bam2", "bar": "required_one_of"}},
474 {'bam': None, 'bam1': None, 'bam2': 'test', 'bam3': None, 'bam4': None, 'bar': 'required_one_of', 'baz': None, 'foo': 'bam2',
475 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None}
476 ),
477 # Check that a bool option is converted
478 ({"foobar": {"foo": "required", "bam": "good", "bam3": "yes"}},
479 {'bam': 'good', 'bam1': None, 'bam2': 'test', 'bam3': True, 'bam4': None, 'bar': None, 'baz': None, 'foo': 'required',
480 'bar1': None, 'bar2': None, 'bar3': None, 'bar4': None}
481 ),
482 # Check required_by options
483 ({"foobar": {"foo": "required", "bar": "good", "baz": "good", "bam4": "required_by", "bam1": "ok", "bam3": "yes"}},
484 {'bar': 'good', 'baz': 'good', 'bam1': 'ok', 'bam2': 'test', 'bam3': True, 'bam4': 'required_by', 'bam': None,
485 'foo': 'required', 'bar1': None, 'bar3': None, 'bar2': None, 'bar4': None}
486 ),
487 # Check for elements in sub-options
488 ({"foobar": {"foo": "good", "bam": "required_one_of", "bar1": [1, "good", "yes"],
489 "bar2": ['1', 1], "bar3": ['1.3', 1.3, 1]}},
490 {'foo': 'good', 'bam1': None, 'bam2': 'test', 'bam3': None, 'bam4': None, 'bar': None,
491 'baz': None, 'bam': 'required_one_of',
492 'bar1': ["1", "good", "yes"], 'bar2': [1, 1], 'bar3': [1.3, 1.3, 1.0], 'bar4': None}
493 ),
494 )
495
496 # (Parameters, failure message)
497 FAILING_PARAMS_LIST: tuple[tuple[dict[str, list[dict[str, t.Any]]], str], ...] = (
498 # Missing required option
499 ({'foobar': [{}]}, 'missing required arguments: foo found in foobar'),
500 # Invalid option
501 ({'foobar': [{"foo": "hello", "bam": "good", "invalid": "bad"}]}, 'module: foobar.invalid. Supported parameters include'),
502 # Mutually exclusive options found
503 ({'foobar': [{"foo": "test", "bam": "bad", "bam1": "bad", "baz": "req_to"}]},
504 'parameters are mutually exclusive: bam|bam1 found in foobar'),
505 # required_if fails
506 ({'foobar': [{"foo": "hello", "bar": "bad"}]},
507 'foo is hello but all of the following are missing: bam found in foobar'),
508 # Missing required_one_of option
509 ({'foobar': [{"foo": "test"}]},
510 'one of the following is required: bar, bam found in foobar'),
511 # Missing required_together option
512 ({'foobar': [{"foo": "test", "bar": "required_one_of", "bam1": "bad"}]},
513 'parameters are required together: bam1, baz found in foobar'),
514 # Missing required_by options
515 ({'foobar': [{"foo": "test", "bar": "required_one_of", "bam4": "required_by"}]},
516 "missing parameter(s) required by 'bam4': bam1, bam3"),
517 )
518
519 # (Parameters, failure message)
520 FAILING_PARAMS_DICT: tuple[tuple[dict[str, dict[str, t.Any]], str], ...] = (
521 # Missing required option
522 ({'foobar': {}}, 'missing required arguments: foo found in foobar'),
523 # Invalid option
524 ({'foobar': {"foo": "hello", "bam": "good", "invalid": "bad"}},
525 'module: foobar.invalid. Supported parameters include'),
526 # Mutually exclusive options found
527 ({'foobar': {"foo": "test", "bam": "bad", "bam1": "bad", "baz": "req_to"}},
528 'parameters are mutually exclusive: bam|bam1 found in foobar'),
529 # required_if fails
530 ({'foobar': {"foo": "hello", "bar": "bad"}},
531 'foo is hello but all of the following are missing: bam found in foobar'),
532 # Missing required_one_of option
533 ({'foobar': {"foo": "test"}},
534 'one of the following is required: bar, bam found in foobar'),
535 # Missing required_together option
536 ({'foobar': {"foo": "test", "bar": "required_one_of", "bam1": "bad"}},
537 'parameters are required together: bam1, baz found in foobar'),
538 # Missing required_by options
539 ({'foobar': {"foo": "test", "bar": "required_one_of", "bam4": "required_by"}},
540 "missing parameter(s) required by 'bam4': bam1, bam3"),
541 )
542
543 @pytest.mark.parametrize('stdin, expected', OPTIONS_PARAMS_DICT, indirect=['stdin'])
544 def test_options_type_dict(self, stdin, options_argspec_dict, expected):
545 """Test that a basic creation with required and required_if works"""
546 # should test ok, tests basic foo requirement and required_if
547 am = basic.AnsibleModule(**options_argspec_dict)
548
549 assert isinstance(am.params['foobar'], dict)
550 assert am.params['foobar'] == expected
551
552 @pytest.mark.parametrize('stdin, expected', OPTIONS_PARAMS_LIST, indirect=['stdin'])
553 def test_options_type_list(self, stdin, options_argspec_list, expected):
554 """Test that a basic creation with required and required_if works"""
555 # should test ok, tests basic foo requirement and required_if
556 am = basic.AnsibleModule(**options_argspec_list)
557
558 assert isinstance(am.params['foobar'], list)
559 assert am.params['foobar'] == expected
560
561 @pytest.mark.parametrize('stdin, expected', FAILING_PARAMS_DICT, indirect=['stdin'])
562 def test_fail_validate_options_dict(self, capfd, stdin, options_argspec_dict, expected):
563 """Fail because one of a required_together pair of parameters has a default and the other was not specified"""
564 with pytest.raises(SystemExit):
565 am = basic.AnsibleModule(**options_argspec_dict)
566
567 out, err = capfd.readouterr()
568 results = json.loads(out)
569
570 assert results['failed']
571 assert expected in results['msg']
572
573 @pytest.mark.parametrize('stdin, expected', FAILING_PARAMS_LIST, indirect=['stdin'])
574 def test_fail_validate_options_list(self, capfd, stdin, options_argspec_list, expected):
575 """Fail because one of a required_together pair of parameters has a default and the other was not specified"""
576 with pytest.raises(SystemExit):
577 am = basic.AnsibleModule(**options_argspec_list)
578
579 out, err = capfd.readouterr()
580 results = json.loads(out)
581
582 assert results['failed']
583 assert expected in results['msg']
584
585 @pytest.mark.parametrize('stdin', [{'foobar': {'foo': 'required', 'bam1': 'test', 'bar': 'case'}}], indirect=['stdin'])
586 def test_fallback_in_option(self, mocker, stdin, options_argspec_dict):
587 """Test that the complex argspec works if we get a required parameter via fallback"""
588 environ = os.environ.copy()
589 environ['BAZ'] = 'test data'
590 mocker.patch('ansible.module_utils.basic.os.environ', environ)
591
592 am = basic.AnsibleModule(**options_argspec_dict)
593
594 assert isinstance(am.params['foobar']['baz'], str)
595 assert am.params['foobar']['baz'] == 'test data'
596
597 @pytest.mark.parametrize('stdin',
598 [{'foobar': {'foo': 'required', 'bam1': 'test', 'baz': 'data', 'bar': 'case', 'bar4': '~/test'}}],
599 indirect=['stdin'])
600 def test_elements_path_in_option(self, mocker, stdin, options_argspec_dict):
601 """Test that the complex argspec works with elements path type"""
602
603 am = basic.AnsibleModule(**options_argspec_dict)
604
605 assert isinstance(am.params['foobar']['bar4'][0], str)
606 assert am.params['foobar']['bar4'][0].startswith('/')
607
608 @pytest.mark.parametrize('stdin,spec,expected', [
609 ({},
610 {'one': {'type': 'dict', 'apply_defaults': True, 'options': {'two': {'default': True, 'type': 'bool'}}}},
611 {'two': True}),
612 ({},
613 {'one': {'type': 'dict', 'options': {'two': {'default': True, 'type': 'bool'}}}},
614 None),
615 ], indirect=['stdin'])
616 def test_subspec_not_required_defaults(self, stdin, spec, expected):
617 # Check that top level not required, processed subspec defaults
618 am = basic.AnsibleModule(spec)
619 assert am.params['one'] == expected
620
621
622 class TestLoadFileCommonArguments:
623 @pytest.mark.parametrize('stdin', [{}], indirect=['stdin'])
624 def test_smoketest_load_file_common_args(self, am):
625 """With no file arguments, an empty dict is returned"""
626 am.selinux_mls_enabled = MagicMock()
627 am.selinux_mls_enabled.return_value = True
628 am.selinux_default_context = MagicMock()
629 am.selinux_default_context.return_value = 'unconfined_u:object_r:default_t:s0'.split(':', 3)
630
631 assert am.load_file_common_arguments(params={}) == {}
632
633 @pytest.mark.parametrize('stdin', [{}], indirect=['stdin'])
634 def test_load_file_common_args(self, am, mocker):
635 am.selinux_mls_enabled = MagicMock()
636 am.selinux_mls_enabled.return_value = True
637 am.selinux_default_context = MagicMock()
638 am.selinux_default_context.return_value = 'unconfined_u:object_r:default_t:s0'.split(':', 3)
639
640 base_params = dict(
641 path='/path/to/file',
642 mode=0o600,
643 owner='root',
644 group='root',
645 seuser='_default',
646 serole='_default',
647 setype='_default',
648 selevel='_default',
649 )
650
651 extended_params = base_params.copy()
652 extended_params.update(dict(
653 follow=True,
654 foo='bar',
655 ))
656
657 final_params = base_params.copy()
658 final_params.update(dict(
659 path='/path/to/real_file',
660 secontext=['unconfined_u', 'object_r', 'default_t', 's0'],
661 attributes=None,
662 ))
663
664 # with the proper params specified, the returned dictionary should represent
665 # only those params which have something to do with the file arguments, excluding
666 # other params and updated as required with proper values which may have been
667 # massaged by the method
668 mocker.patch('os.path.islink', return_value=True)
669 mocker.patch('os.path.realpath', return_value='/path/to/real_file')
670
671 res = am.load_file_common_arguments(params=extended_params)
672
673 assert res == final_params
674
675
676 @pytest.mark.parametrize("stdin", [{"arg_pass": "testing"}], indirect=["stdin"])
677 def test_no_log_none(stdin, capfd):
678 """Allow Ansible to make the decision by matching the argument name
679 against PASSWORD_MATCH."""
680 arg_spec = {
681 "arg_pass": {}
682 }
683 am = basic.AnsibleModule(arg_spec)
684 # Omitting no_log is only picked up by _log_invocation, so the value never
685 # makes it into am.no_log_values. Instead we can check for the warning
686 # emitted by am._log_invocation.
687 assert len(get_warning_messages()) > 0
688
689
690 @pytest.mark.parametrize("stdin", [{"pass": "testing"}], indirect=["stdin"])
691 def test_no_log_alias(stdin, capfd):
692 """Given module parameters that use an alias for a parameter that matches
693 PASSWORD_MATCH and has no_log=True set, a warning should not be issued.
694 """
695 arg_spec = {
696 "other_pass": {"no_log": True, "aliases": ["pass"]},
697 }
698 am = basic.AnsibleModule(arg_spec)
699
700 assert len(get_warning_messages()) == 0