Debian Codegraph @

test/units/plugins/action/test_action.py

raw
1 # -*- coding: utf-8 -*-
2 # (c) 2015, Florian Apolloner <[email protected]>
3 #
4 # This file is part of Ansible
5 #
6 # Ansible is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Ansible is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
18
19 from __future__ import annotations
20
21 import os
22 import re
23 from importlib import import_module
24
25
26 import builtins
27 import pytest
28 import shlex
29 import unittest
30
31 from unittest.mock import patch, MagicMock, mock_open
32
33 from ansible import constants as C
34 from ansible.errors import AnsibleError, AnsibleAuthenticationFailure
35 from ansible.module_utils.common.text.converters import to_bytes
36 from ansible._internal._datatag._tags import TrustedAsTemplate
37 from ansible.playbook.play_context import PlayContext
38 from ansible.plugins.action import ActionBase
39 from ansible.plugins.shell import _ShellCommand
40 from ansible.vars.clean import clean_facts
41 from ansible.template import Templar
42 from ansible.plugins import loader
43
44 from units.mock.loader import DictDataLoader
45
46
47 python_module_replacers = br"""
48 #!/usr/bin/python
49
50 #ANSIBLE_VERSION = "<<ANSIBLE_VERSION>>"
51 #MODULE_COMPLEX_ARGS = "<<INCLUDE_ANSIBLE_MODULE_COMPLEX_ARGS>>"
52 #SELINUX_SPECIAL_FS="<<SELINUX_SPECIAL_FILESYSTEMS>>"
53
54 test = u'Toshio \u304f\u3089\u3068\u307f'
55 from ansible.module_utils.basic import *
56 """
57
58 powershell_module_replacers = b"""
59 WINDOWS_ARGS = "<<INCLUDE_ANSIBLE_MODULE_JSON_ARGS>>"
60 # POWERSHELL_COMMON
61 """
62
63
64 def _action_base():
65 fake_loader = DictDataLoader({
66 })
67 mock_module_loader = MagicMock()
68 mock_shared_loader_obj = MagicMock()
69 mock_shared_loader_obj.module_loader = mock_module_loader
70 mock_connection_loader = MagicMock()
71
72 mock_shared_loader_obj.connection_loader = mock_connection_loader
73 mock_connection = MagicMock()
74
75 play_context = MagicMock()
76
77 action_base = DerivedActionBase(task=None,
78 connection=mock_connection,
79 play_context=play_context,
80 loader=fake_loader,
81 templar=None,
82 shared_loader_obj=mock_shared_loader_obj)
83 return action_base
84
85
86 class DerivedActionBase(ActionBase):
87 TRANSFERS_FILES = False
88
89 def run(self, tmp=None, task_vars=None):
90 # We're not testing the plugin run() method, just the helper
91 # methods ActionBase defines
92 return super(DerivedActionBase, self).run(tmp=tmp, task_vars=task_vars)
93
94
95 class TestActionBase(unittest.TestCase):
96
97 def test_action_base_run(self):
98 mock_task = MagicMock()
99 mock_task.action = "foo"
100 mock_task.args = dict(a=1, b=2, c=3)
101
102 mock_connection = MagicMock()
103
104 play_context = PlayContext()
105
106 mock_task.async_val = None
107 action_base = DerivedActionBase(mock_task, mock_connection, play_context, None, None, None)
108 results = action_base.run()
109 self.assertEqual(results, {})
110
111 mock_task.async_val = 0
112 action_base = DerivedActionBase(mock_task, mock_connection, play_context, None, None, None)
113 results = action_base.run()
114 self.assertEqual(results, {})
115
116 @pytest.mark.usefixtures('collection_loader')
117 def test_action_base__configure_module(self):
118 # Pre-populate the ansible.builtin collection
119 # so reading the ansible_builtin_runtime.yml happens
120 # before the mock_open below
121 import_module('ansible_collections.ansible.builtin')
122 fake_loader = DictDataLoader({
123 })
124
125 # create our fake task
126 mock_task = MagicMock()
127 mock_task.action = "copy"
128 mock_task.async_val = 0
129 mock_task.delegate_to = None
130
131 # create a mock connection, so we don't actually try and connect to things
132 mock_connection = MagicMock()
133 mock_connection.become = None
134
135 # create a mock shared loader object
136 def mock_find_plugin_with_context(name, options, collection_list=None):
137 mockctx = MagicMock()
138 if name == 'badmodule':
139 mockctx.resolved = False
140 mockctx.plugin_resolved_path = None
141 elif '.ps1' in options:
142 mockctx.resolved = True
143 mockctx.plugin_resolved_path = '/fake/path/to/%s.ps1' % name
144 else:
145 mockctx.resolved = True
146 mockctx.plugin_resolved_path = '/fake/path/to/%s' % name
147 mockctx.resolved_fqcn = name
148 return mockctx
149
150 mock_module_loader = MagicMock()
151 mock_module_loader.find_plugin_with_context.side_effect = mock_find_plugin_with_context
152
153 # we're using a real play context here
154 play_context = PlayContext()
155
156 # our test class
157 action_base = DerivedActionBase(
158 task=mock_task,
159 connection=mock_connection,
160 play_context=play_context,
161 loader=fake_loader,
162 templar=Templar(loader=fake_loader),
163 )
164
165 original_open = builtins.open
166
167 def custom_open(file, *args, **kwargs):
168 if file.endswith('.lock'):
169 return original_open(file, *args, **kwargs)
170 else:
171 return mock_open(read_data=to_bytes(python_module_replacers.strip(), encoding='utf-8'))(file, *args, **kwargs)
172
173 # test python module formatting
174 with (
175 patch.object(builtins, 'open', custom_open),
176 patch.object(loader, 'module_loader', mock_module_loader)
177 ):
178 with patch.object(os, 'rename'):
179 mock_task.args = dict(a=1, foo='fö〩')
180 mock_connection.module_implementation_preferences = ('',)
181 built_module, path = action_base._configure_module(mock_task.action, mock_task.args,
182 task_vars=dict(ansible_python_interpreter='/usr/bin/python',
183 ansible_playbook_python='/usr/bin/python'))
184 self.assertEqual(built_module.module_style, "new")
185 self.assertEqual(built_module.shebang, u"#!/usr/bin/python")
186
187 # test module not found
188 self.assertRaises(AnsibleError, action_base._configure_module, 'badmodule', mock_task.args, {})
189
190 # test powershell module formatting
191 with (
192 patch.object(builtins, 'open', mock_open(read_data=to_bytes(powershell_module_replacers.strip(), encoding='utf-8'))),
193 patch.object(loader, 'module_loader', mock_module_loader),
194 ):
195 mock_task.action = 'win_copy'
196 mock_task.args = dict(b=2)
197 mock_connection.module_implementation_preferences = ('.ps1',)
198 built_module, path = action_base._configure_module('stat', mock_task.args, {})
199 self.assertEqual(built_module.module_style, "new")
200 self.assertEqual(built_module.shebang, u'#!powershell')
201
202 # test module not found
203 self.assertRaises(AnsibleError, action_base._configure_module, 'badmodule', mock_task.args, {})
204
205 def test_action_base__compute_environment_string(self):
206 fake_loader = DictDataLoader({
207 })
208
209 # create our fake task
210 mock_task = MagicMock()
211 mock_task.action = "copy"
212 mock_task.args = dict(a=1)
213
214 # create a mock connection, so we don't actually try and connect to things
215 def env_prefix(**args):
216 return ' '.join(['%s=%s' % (k, shlex.quote(str(v))) for k, v in args.items()])
217 mock_connection = MagicMock()
218 mock_connection._shell.env_prefix.side_effect = env_prefix
219
220 # we're using a real play context here
221 play_context = PlayContext()
222
223 # and we're using a real templar here too
224 templar = Templar(loader=fake_loader)
225
226 # our test class
227 action_base = DerivedActionBase(
228 task=mock_task,
229 connection=mock_connection,
230 play_context=play_context,
231 loader=fake_loader,
232 templar=templar,
233 shared_loader_obj=None,
234 )
235
236 # test standard environment setup
237 mock_task.environment = [dict(FOO='foo'), None]
238 env_string = action_base._compute_environment_string()
239 self.assertEqual(env_string, "FOO=foo")
240
241 # test where environment is not a list
242 mock_task.environment = dict(FOO='foo')
243 env_string = action_base._compute_environment_string()
244 self.assertEqual(env_string, "FOO=foo")
245
246 # test environment with a variable in it
247 templar.available_variables = dict(the_var='bar')
248 mock_task.environment = [dict(FOO=TrustedAsTemplate().tag('{{the_var}}'))]
249 env_string = action_base._compute_environment_string()
250 self.assertEqual(env_string, "FOO=bar")
251
252 # test with a bad environment set
253 mock_task.environment = dict(FOO='foo')
254 mock_task.environment = ['hi there']
255 self.assertRaises(AnsibleError, action_base._compute_environment_string)
256
257 def test_action_base__early_needs_tmp_path(self):
258 # create our fake task
259 mock_task = MagicMock()
260
261 # create a mock connection, so we don't actually try and connect to things
262 mock_connection = MagicMock()
263
264 # we're using a real play context here
265 play_context = PlayContext()
266
267 # our test class
268 action_base = DerivedActionBase(
269 task=mock_task,
270 connection=mock_connection,
271 play_context=play_context,
272 loader=None,
273 templar=None,
274 shared_loader_obj=None,
275 )
276
277 self.assertFalse(action_base._early_needs_tmp_path())
278
279 action_base.TRANSFERS_FILES = True
280 self.assertTrue(action_base._early_needs_tmp_path())
281
282 def test_action_base__make_tmp_path(self):
283 # create our fake task
284 mock_task = MagicMock()
285
286 def get_shell_opt(opt):
287
288 assert opt == 'admin_users'
289 ret = ['root', 'toor', 'Administrator']
290
291 return ret
292
293 # create a mock connection, so we don't actually try and connect to things
294 mock_connection = MagicMock()
295 mock_connection.transport = 'ssh'
296 mock_connection._shell._mkdtemp2.return_value = _ShellCommand(command='mkdir command')
297 mock_connection._shell.join_path.side_effect = os.path.join
298 mock_connection._shell.get_option = get_shell_opt
299 mock_connection._shell.HOMES_RE = re.compile(r'(\'|\")?(~|\$HOME)(.*)')
300
301 # we're using a real play context here
302 play_context = PlayContext()
303 play_context.become = True
304 play_context.become_user = 'foo'
305
306 mock_task.become = True
307 mock_task.become_user = True
308
309 # our test class
310 action_base = DerivedActionBase(
311 task=mock_task,
312 connection=mock_connection,
313 play_context=play_context,
314 loader=None,
315 templar=None,
316 shared_loader_obj=None,
317 )
318
319 action_base._low_level_execute_command = MagicMock()
320 action_base._low_level_execute_command.return_value = dict(rc=0, stdout='/some/path')
321 self.assertEqual(action_base._make_tmp_path('root'), '/some/path/')
322
323 # empty path fails
324 action_base._low_level_execute_command.return_value = dict(rc=0, stdout='')
325 self.assertRaises(AnsibleError, action_base._make_tmp_path, 'root')
326
327 # authentication failure
328 action_base._low_level_execute_command.return_value = dict(rc=5, stdout='')
329 self.assertRaises(AnsibleError, action_base._make_tmp_path, 'root')
330
331 # ssh error
332 action_base._low_level_execute_command.return_value = dict(rc=255, stdout='', stderr='')
333 self.assertRaises(AnsibleError, action_base._make_tmp_path, 'root')
334 self.assertRaises(AnsibleError, action_base._make_tmp_path, 'root')
335
336 # general error
337 action_base._low_level_execute_command.return_value = dict(rc=1, stdout='some stuff here', stderr='')
338 self.assertRaises(AnsibleError, action_base._make_tmp_path, 'root')
339 action_base._low_level_execute_command.return_value = dict(rc=1, stdout='some stuff here', stderr='No space left on device')
340 self.assertRaises(AnsibleError, action_base._make_tmp_path, 'root')
341
342 def test_action_base__fixup_perms2(self):
343 mock_task = MagicMock()
344 mock_connection = MagicMock()
345 play_context = PlayContext()
346 action_base = DerivedActionBase(
347 task=mock_task,
348 connection=mock_connection,
349 play_context=play_context,
350 loader=None,
351 templar=None,
352 shared_loader_obj=None,
353 )
354 action_base._low_level_execute_command = MagicMock()
355 remote_paths = ['/tmp/foo/bar.txt', '/tmp/baz.txt']
356 remote_user = 'remoteuser1'
357
358 # Used for skipping down to common group dir.
359 CHMOD_ACL_FLAGS = ('+a', 'A+user:remoteuser2:r:allow')
360
361 def runWithNoExpectation(execute=False):
362 return action_base._fixup_perms2(
363 remote_paths,
364 remote_user=remote_user,
365 execute=execute)
366
367 def assertSuccess(execute=False):
368 self.assertEqual(runWithNoExpectation(execute), remote_paths)
369
370 def assertThrowRegex(regex, execute=False):
371 self.assertRaisesRegex(
372 AnsibleError,
373 regex,
374 action_base._fixup_perms2,
375 remote_paths,
376 remote_user=remote_user,
377 execute=execute)
378
379 def get_shell_option_for_arg(args_kv, default):
380 """A helper for get_shell_option. Returns a function that, if
381 called with ``option`` that exists in args_kv, will return the
382 value, else will return ``default`` for every other given arg"""
383 def _helper(option, *args, **kwargs):
384 return args_kv.get(option, default)
385 return _helper
386
387 action_base.get_become_option = MagicMock()
388 action_base.get_become_option.return_value = 'remoteuser2'
389
390 # Step 1: On windows, we just return remote_paths
391 action_base._connection._shell._IS_WINDOWS = True
392 assertSuccess(execute=False)
393 assertSuccess(execute=True)
394
395 # But if we're not on windows....we have more work to do.
396 action_base._connection._shell._IS_WINDOWS = False
397
398 # Step 2: We're /not/ becoming an unprivileged user
399 action_base._remote_chmod = MagicMock()
400 action_base._is_become_unprivileged = MagicMock()
401 action_base._is_become_unprivileged.return_value = False
402 # Two subcases:
403 # - _remote_chmod rc is 0
404 # - _remote-chmod rc is not 0, something failed
405 action_base._remote_chmod.return_value = {
406 'rc': 0,
407 'stdout': 'some stuff here',
408 'stderr': '',
409 }
410 assertSuccess(execute=True)
411
412 # When execute=False, we just get the list back. But add it here for
413 # completion. chmod is never called.
414 assertSuccess()
415
416 action_base._remote_chmod.return_value = {
417 'rc': 1,
418 'stdout': 'some stuff here',
419 'stderr': 'and here',
420 }
421 assertThrowRegex(
422 'Failed to set permissions on remote files',
423 execute=True)
424
425 # Step 3: we are becoming unprivileged
426 action_base._is_become_unprivileged.return_value = True
427
428 # Step 3a: setfacl
429 action_base._remote_set_user_facl = MagicMock()
430 action_base._remote_set_user_facl.return_value = {
431 'rc': 0,
432 'stdout': '',
433 'stderr': '',
434 }
435 assertSuccess()
436
437 # Step 3b: chmod +rwx if we need to
438 # To get here, setfacl failed, so mock it as such.
439 action_base._remote_set_user_facl.return_value = {
440 'rc': 1,
441 'stdout': '',
442 'stderr': '',
443 }
444 action_base._remote_chmod.return_value = {
445 'rc': 1,
446 'stdout': 'some stuff here',
447 'stderr': '',
448 }
449 assertThrowRegex(
450 'Failed to set file mode or acl on remote temporary files',
451 execute=True)
452 action_base._remote_chmod.return_value = {
453 'rc': 0,
454 'stdout': 'some stuff here',
455 'stderr': '',
456 }
457 assertSuccess(execute=True)
458
459 # Step 3c: chown
460 action_base._remote_chown = MagicMock()
461 action_base._remote_chown.return_value = {
462 'rc': 0,
463 'stdout': '',
464 'stderr': '',
465 }
466 assertSuccess()
467 action_base._remote_chown.return_value = {
468 'rc': 1,
469 'stdout': '',
470 'stderr': '',
471 }
472 remote_user = 'root'
473 action_base._get_admin_users = MagicMock()
474 action_base._get_admin_users.return_value = ['root']
475 assertThrowRegex('user would be unable to read the file.')
476 remote_user = 'remoteuser1'
477
478 # Step 3d: chmod +a on osx
479 assertSuccess()
480 action_base._remote_chmod.assert_called_with(
481 ['remoteuser2 allow read'] + remote_paths,
482 '+a')
483
484 # This case can cause Solaris chmod to return 5 which the ssh plugin
485 # treats as failure. To prevent a regression and ensure we still try the
486 # rest of the cases below, we mock the thrown exception here.
487 # This function ensures that only the macOS case (+a) throws this.
488 def raise_if_plus_a(definitely_not_underscore, mode):
489 if mode == '+a':
490 raise AnsibleAuthenticationFailure()
491 return {'rc': 0, 'stdout': '', 'stderr': ''}
492
493 action_base._remote_chmod.side_effect = raise_if_plus_a
494 assertSuccess()
495
496 # Step 3e: chmod A+ on Solaris
497 # We threw AnsibleAuthenticationFailure above, try Solaris fallback.
498 # Based on our lambda above, it should be successful.
499 action_base._remote_chmod.assert_called_with(
500 remote_paths,
501 'A+user:remoteuser2:r:allow')
502 assertSuccess()
503
504 # Step 3f: Common group
505 def rc_1_if_chmod_acl(definitely_not_underscore, mode):
506 rc = 0
507 if mode in CHMOD_ACL_FLAGS:
508 rc = 1
509 return {'rc': rc, 'stdout': '', 'stderr': ''}
510
511 action_base._remote_chmod = MagicMock()
512 action_base._remote_chmod.side_effect = rc_1_if_chmod_acl
513
514 get_shell_option = action_base.get_shell_option
515 action_base.get_shell_option = MagicMock()
516 action_base.get_shell_option.side_effect = get_shell_option_for_arg(
517 {
518 'common_remote_group': 'commongroup',
519 },
520 None)
521 action_base._remote_chgrp = MagicMock()
522 action_base._remote_chgrp.return_value = {
523 'rc': 0,
524 'stdout': '',
525 'stderr': '',
526 }
527 # TODO: Add test to assert warning is shown if
528 # world_readable_temp is set in this case.
529 assertSuccess()
530 action_base._remote_chgrp.assert_called_once_with(
531 remote_paths,
532 'commongroup')
533
534 # Step 4: world-readable tmpdir
535 action_base.get_shell_option.side_effect = get_shell_option_for_arg(
536 {
537 'world_readable_temp': True,
538 'common_remote_group': None,
539 },
540 None)
541 action_base._remote_chmod.return_value = {
542 'rc': 0,
543 'stdout': 'some stuff here',
544 'stderr': '',
545 }
546 assertSuccess()
547 action_base._remote_chmod = MagicMock()
548 action_base._remote_chmod.return_value = {
549 'rc': 1,
550 'stdout': 'some stuff here',
551 'stderr': '',
552 }
553 assertThrowRegex('Failed to set file mode on remote files')
554
555 # Otherwise if we make it here in this state, we hit the catch-all
556 action_base.get_shell_option.side_effect = get_shell_option_for_arg(
557 {},
558 None)
559 assertThrowRegex('on the temporary files Ansible needs to create')
560
561 def test_action_base__remove_tmp_path(self):
562 # create our fake task
563 mock_task = MagicMock()
564
565 # create a mock connection, so we don't actually try and connect to things
566 mock_connection = MagicMock()
567 mock_connection._shell.remove.return_value = 'rm some stuff'
568
569 # we're using a real play context here
570 play_context = PlayContext()
571
572 # our test class
573 action_base = DerivedActionBase(
574 task=mock_task,
575 connection=mock_connection,
576 play_context=play_context,
577 loader=None,
578 templar=None,
579 shared_loader_obj=None,
580 )
581
582 action_base._low_level_execute_command = MagicMock()
583 # these don't really return anything or raise errors, so
584 # we're pretty much calling these for coverage right now
585 action_base._remove_tmp_path('/bad/path/dont/remove')
586 action_base._remove_tmp_path('/good/path/to/ansible-tmp-thing')
587
588 @patch('os.unlink')
589 @patch('os.fdopen')
590 @patch('tempfile.mkstemp')
591 def test_action_base__transfer_data(self, mock_mkstemp, mock_fdopen, mock_unlink):
592 # create our fake task
593 mock_task = MagicMock()
594
595 # create a mock connection, so we don't actually try and connect to things
596 mock_connection = MagicMock()
597 mock_connection.put_file.return_value = None
598
599 # we're using a real play context here
600 play_context = PlayContext()
601
602 # our test class
603 action_base = DerivedActionBase(
604 task=mock_task,
605 connection=mock_connection,
606 play_context=play_context,
607 loader=None,
608 templar=None,
609 shared_loader_obj=None,
610 )
611
612 mock_afd = MagicMock()
613 mock_afile = MagicMock()
614 mock_mkstemp.return_value = (mock_afd, mock_afile)
615
616 mock_unlink.return_value = None
617
618 mock_afo = MagicMock()
619 mock_afo.write.return_value = None
620 mock_afo.flush.return_value = None
621 mock_afo.close.return_value = None
622 mock_fdopen.return_value = mock_afo
623
624 self.assertEqual(action_base._transfer_data('/path/to/remote/file', 'some data'), '/path/to/remote/file')
625 self.assertEqual(action_base._transfer_data('/path/to/remote/file', 'some mixed data: fö〩'), '/path/to/remote/file')
626 self.assertEqual(action_base._transfer_data('/path/to/remote/file', 'some data'.encode()), '/path/to/remote/file')
627 self.assertEqual(action_base._transfer_data('/path/to/remote/file', 'some mixed data: fö〩'.encode()), '/path/to/remote/file')
628
629 mock_afo.write.side_effect = Exception()
630 self.assertRaises(AnsibleError, action_base._transfer_data, '/path/to/remote/file', '')
631
632 with pytest.raises(TypeError):
633 action_base._transfer_data('/path/to/remote/file', dict())
634
635 def test_action_base__execute_remote_stat(self):
636 # create our fake task
637 mock_task = MagicMock()
638
639 # create a mock connection, so we don't actually try and connect to things
640 mock_connection = MagicMock()
641
642 # we're using a real play context here
643 play_context = PlayContext()
644
645 # our test class
646 action_base = DerivedActionBase(
647 task=mock_task,
648 connection=mock_connection,
649 play_context=play_context,
650 loader=None,
651 templar=None,
652 shared_loader_obj=None,
653 )
654
655 action_base._execute_module = MagicMock()
656
657 # test normal case
658 action_base._execute_module.return_value = dict(stat=dict(checksum='1111111111111111111111111111111111', exists=True))
659 res = action_base._execute_remote_stat(path='/path/to/file', all_vars=dict(), follow=False)
660 self.assertEqual(res['checksum'], '1111111111111111111111111111111111')
661
662 # test does not exist
663 action_base._execute_module.return_value = dict(stat=dict(exists=False))
664 res = action_base._execute_remote_stat(path='/path/to/file', all_vars=dict(), follow=False)
665 self.assertFalse(res['exists'])
666 self.assertEqual(res['checksum'], '1')
667
668 # test no checksum in result from _execute_module
669 action_base._execute_module.return_value = dict(stat=dict(exists=True))
670 res = action_base._execute_remote_stat(path='/path/to/file', all_vars=dict(), follow=False)
671 self.assertTrue(res['exists'])
672 self.assertEqual(res['checksum'], '')
673
674 # test stat call failed
675 action_base._execute_module.return_value = dict(failed=True, msg="because I said so")
676 self.assertRaises(AnsibleError, action_base._execute_remote_stat, path='/path/to/file', all_vars=dict(), follow=False)
677
678 def test_action_base_sudo_only_if_user_differs(self):
679 fake_loader = MagicMock()
680 fake_loader.get_basedir.return_value = os.getcwd()
681 play_context = PlayContext()
682
683 action_base = DerivedActionBase(None, None, play_context, fake_loader, None, None)
684 action_base.get_become_option = MagicMock(return_value='root')
685 action_base._get_remote_user = MagicMock(return_value='root')
686
687 action_base._connection = MagicMock(exec_command=MagicMock(return_value=(0, '', '')))
688
689 action_base._connection._shell = shell = MagicMock(append_command=MagicMock(return_value=('JOINED CMD')))
690
691 action_base._connection.become = become = MagicMock()
692 action_base._connection.transport = ''
693 become.build_become_command.return_value = 'foo'
694
695 action_base._low_level_execute_command('ECHO', sudoable=True)
696 become.build_become_command.assert_not_called()
697
698 action_base._get_remote_user.return_value = 'apo'
699 action_base._low_level_execute_command('ECHO', sudoable=True, executable='/bin/csh')
700 become.build_become_command.assert_called_once_with("ECHO", shell)
701
702 become.build_become_command.reset_mock()
703
704 with patch.object(C, 'BECOME_ALLOW_SAME_USER', new=True):
705 action_base._get_remote_user.return_value = 'root'
706 action_base._low_level_execute_command('ECHO SAME', sudoable=True)
707 become.build_become_command.assert_called_once_with("ECHO SAME", shell)
708
709 def test__remote_expand_user_relative_pathing(self):
710 action_base = _action_base()
711 action_base._play_context.remote_addr = 'bar'
712 action_base._connection.get_option.return_value = 'bar'
713 action_base._low_level_execute_command = MagicMock(return_value={'stdout': b'../home/user'})
714 action_base._connection._shell.join_path.return_value = '../home/user/foo'
715 with self.assertRaises(AnsibleError) as cm:
716 action_base._remote_expand_user('~/foo')
717 self.assertEqual(
718 cm.exception.message,
719 "'bar' returned an invalid relative home directory path containing '..'"
720 )
721
722
723 class TestActionBaseCleanReturnedData(unittest.TestCase):
724 def test(self):
725 data = {'ansible_playbook_python': '/usr/bin/python',
726 'ansible_python_interpreter': '/usr/bin/python',
727 'ansible_ssh_some_var': 'whatever',
728 'ansible_ssh_host_key_somehost': 'some key here',
729 'some_other_var': 'foo bar'}
730 data = clean_facts(data)
731 self.assertNotIn('ansible_playbook_python', data)
732 self.assertNotIn('ansible_python_interpreter', data)
733 self.assertIn('ansible_ssh_host_key_somehost', data)
734 self.assertIn('some_other_var', data)
735
736
737 class TestActionBaseParseReturnedData(unittest.TestCase):
738
739 def test_fail_no_json(self):
740 action_base = _action_base()
741 rc = 0
742 stdout = 'foo\nbar\n'
743 err = 'oopsy'
744 returned_data = {'rc': rc,
745 'stdout': stdout,
746 'stdout_lines': stdout.splitlines(),
747 'stderr': err}
748 res = action_base._parse_returned_data(returned_data, 'legacy')
749 self.assertFalse(res.ansible_parsed)
750 self.assertTrue(res.failed)
751 self.assertEqual(res.module_stderr, err)
752
753 def test_json_empty(self):
754 action_base = _action_base()
755 rc = 0
756 stdout = '{}\n'
757 err = ''
758 returned_data = {'rc': rc,
759 'stdout': stdout,
760 'stdout_lines': stdout.splitlines(),
761 'stderr': err}
762 res = action_base._parse_returned_data(returned_data, 'legacy')
763 self.assertEqual(len(res.result_data), 0)
764
765 def test_json_facts(self):
766 action_base = _action_base()
767 rc = 0
768 stdout = '{"ansible_facts": {"foo": "bar", "ansible_blip": "blip_value"}}\n'
769 err = ''
770
771 returned_data = {'rc': rc,
772 'stdout': stdout,
773 'stdout_lines': stdout.splitlines(),
774 'stderr': err}
775 res = action_base._parse_returned_data(returned_data, 'legacy')
776 self.assertTrue(res.ansible_facts)
777 self.assertIn('ansible_blip', res.ansible_facts)