def test_distribution_version():
    """tests the distribution parsing code of the Facts class

    testsets have
    * a name (for output/debugging only)
    * input files that are faked
      * those should be complete and also include "irrelevant" files that might be mistaken as coming from other distributions
      * all files that are not listed here are assumed to not exist at all
    * the output of pythons platform.dist()
    * results for the ansible variables distribution*
    """

    # needs to be in here, because the import fails with python3 still
    import ansible.module_utils.facts as facts

    from ansible.module_utils import basic

    args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
    with swap_stdin_and_argv(stdin_data=args):
        module = basic.AnsibleModule(argument_spec=dict())

        for t in TESTSETS:
            # run individual tests via generator
            # set nicer stdout output for nosetest
            _test_one_distribution.description = "check distribution_version for %s" % t['name']
            yield _test_one_distribution, facts, module, t
예제 #2
0
파일: test_log.py 프로젝트: ernstp/ansible
    def setUp(self):
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
        # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
        self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
        self.stdin_swap.__enter__()

        ansible.module_utils.basic._ANSIBLE_ARGS = None
        self.am = ansible.module_utils.basic.AnsibleModule(
            argument_spec=dict(),
        )
        self.am._name = 'unittest'

        self.has_journal = ansible.module_utils.basic.has_journal
        ansible.module_utils.basic.has_journal = True

        self.module_patcher = None

        # In case systemd-python is not installed
        if not self.has_journal:
            self.module_patcher = patch.dict('sys.modules', {'systemd': MagicMock(), 'systemd.journal': MagicMock()})
            self.module_patcher.start()
            try:
                reload(ansible.module_utils.basic)
            except NameError:
                self._fake_out_reload(ansible.module_utils.basic)
예제 #3
0
    def test_add_host_key(self):

        # Copied
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
        # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually

        with swap_stdin_and_argv(stdin_data=args):
            ansible.module_utils.basic._ANSIBLE_ARGS = None
            self.module = ansible.module_utils.basic.AnsibleModule(argument_spec=dict())

            get_bin_path = Mock()
            get_bin_path.return_value = keyscan_cmd = "/custom/path/ssh-keyscan"
            self.module.get_bin_path = get_bin_path

            run_command = Mock()
            run_command.return_value = (0, "Needs output, otherwise thinks ssh-keyscan timed out'", "")
            self.module.run_command = run_command

            append_to_file = Mock()
            append_to_file.return_value = (None,)
            self.module.append_to_file = append_to_file

            with patch('os.path.isdir', return_value=True):
                with patch('os.path.exists', return_value=True):
                    for u in self.urls:
                        if self.urls[u]['is_ssh_url']:
                            known_hosts.add_host_key(self.module, self.urls[u]['get_fqdn'], port=self.urls[u]['port'])
                            run_command.assert_called_with(keyscan_cmd + self.urls[u]['add_host_key_cmd'])
예제 #4
0
    def test_module_utils_basic_ansible_module_type_check(self):
        from ansible.module_utils import basic

        arg_spec = dict(
            foo = dict(type='float'),
            foo2 = dict(type='float'),
            foo3 = dict(type='float'),
            bar = dict(type='int'),
            bar2 = dict(type='int'),
        )

        # should test ok
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={
            "foo": 123.0, # float
            "foo2": 123, # int
            "foo3": "123", # string
            "bar": 123, # int
            "bar2": "123", # string
        }))

        with swap_stdin_and_argv(stdin_data=args):
            basic._ANSIBLE_ARGS = None
            am = basic.AnsibleModule(
                argument_spec = arg_spec,
                no_log=True,
                check_invalid_arguments=False,
                add_file_common_args=True,
                supports_check_mode=True,
            )

        # fail, because bar does not accept floating point numbers
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={"bar": 123.0}))

        with swap_stdin_and_argv(stdin_data=args):
            basic._ANSIBLE_ARGS = None
            self.assertRaises(
                SystemExit,
                basic.AnsibleModule,
                argument_spec = arg_spec,
                no_log=True,
                check_invalid_arguments=False,
                add_file_common_args=True,
                supports_check_mode=True,
            )
예제 #5
0
    def run_command_mocked_env(self, mocker):
        self.cmd_out = {
            # os.read() is returning 'bytes', not strings
            sentinel.stdout: BytesIO(),
            sentinel.stderr: BytesIO(),
        }

        def mock_os_read(fd, nbytes):
            return self.cmd_out[fd].read(nbytes)

        def mock_select(rlist, wlist, xlist, timeout=1):
            return (rlist, [], [])

        def mock_os_chdir(path):
            if path == '/inaccessible':
                raise OSError(errno.EPERM, "Permission denied: '/inaccessible'")

        def mock_os_abspath(path):
            if path.startswith('/'):
                return path
            else:
                return self.os.getcwd.return_value + '/' + path

        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
        # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
        self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
        self.stdin_swap.__enter__()

        ansible.module_utils.basic._ANSIBLE_ARGS = None
        self.module = ansible.module_utils.basic.AnsibleModule(argument_spec=dict())
        self.module.fail_json = MagicMock(side_effect=SystemExit)

        self.os = mocker.patch('ansible.module_utils.basic.os')
        self.os.path.expandvars.side_effect = lambda x: x
        self.os.path.expanduser.side_effect = lambda x: x
        self.os.environ = {'PATH': '/bin'}
        self.os.getcwd.return_value = '/home/foo'
        self.os.path.isdir.return_value = True
        self.os.chdir.side_effect = mock_os_chdir
        self.os.read.side_effect = mock_os_read
        self.os.path.abspath.side_effect = mock_os_abspath

        self.subprocess = mocker.patch('ansible.module_utils.basic.subprocess')
        self.cmd = Mock()
        self.cmd.returncode = 0
        self.cmd.stdin = OpenBytesIO()
        self.cmd.stdout.fileno.return_value = sentinel.stdout
        self.cmd.stderr.fileno.return_value = sentinel.stderr
        self.subprocess.Popen.return_value = self.cmd

        self.select = mocker.patch('ansible.module_utils.basic.select')
        self.select.select.side_effect = mock_select
        yield

        # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
        self.stdin_swap.__exit__(None, None, None)
    def setUp(self):
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))
        self.stdin_swap_ctx = swap_stdin_and_argv(stdin_data=args)
        self.stdin_swap_ctx.__enter__()

        # since we can't use context managers and "with" without overriding run(), call them directly
        self.stdout_swap_ctx = swap_stdout()
        self.fake_stream = self.stdout_swap_ctx.__enter__()

        reload(basic)
        self.module = basic.AnsibleModule(argument_spec=dict())
예제 #7
0
    def setUp(self):
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))

        # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
        self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
        self.stdin_swap.__enter__()

        ansible.module_utils.basic._ANSIBLE_ARGS = None
        self.am = ansible.module_utils.basic.AnsibleModule(
            argument_spec = dict(),
        )
예제 #8
0
    def test_module_utils_basic__log_invocation(self):
        with swap_stdin_and_argv(stdin_data=json.dumps(dict(
            ANSIBLE_MODULE_ARGS=dict(foo=False, bar=[1, 2, 3], bam="bam", baz=u'baz')),
        )):
            from ansible.module_utils import basic

            # test basic log invocation
            basic._ANSIBLE_ARGS = None
            am = basic.AnsibleModule(
                argument_spec=dict(
                    foo=dict(default=True, type='bool'),
                    bar=dict(default=[], type='list'),
                    bam=dict(default="bam"),
                    baz=dict(default=u"baz"),
                    password=dict(default=True),
                    no_log=dict(default="you shouldn't see me", no_log=True),
                ),
            )

            am.log = MagicMock()
            am._log_invocation()

            # Message is generated from a dict so it will be in an unknown order.
            # have to check this manually rather than with assert_called_with()
            args = am.log.call_args[0]
            self.assertEqual(len(args), 1)
            message = args[0]

            self.assertEqual(
                len(message),
                len('Invoked with bam=bam bar=[1, 2, 3] foo=False baz=baz no_log=NOT_LOGGING_PARAMETER password=NOT_LOGGING_PASSWORD')
            )
            self.assertTrue(message.startswith('Invoked with '))
            self.assertIn(' bam=bam', message)
            self.assertIn(' bar=[1, 2, 3]', message)
            self.assertIn(' foo=False', message)
            self.assertIn(' baz=baz', message)
            self.assertIn(' no_log=NOT_LOGGING_PARAMETER', message)
            self.assertIn(' password=NOT_LOGGING_PASSWORD', message)

            kwargs = am.log.call_args[1]
            self.assertEqual(
                kwargs,
                dict(log_args={
                    'foo': 'False',
                    'bar': '[1, 2, 3]',
                    'bam': 'bam',
                    'baz': 'baz',
                    'password': '******',
                    'no_log': 'NOT_LOGGING_PARAMETER',
                })
            )
예제 #9
0
    def setUp(self):
        args = json.dumps(
            dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))

        # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
        self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
        self.stdin_swap.__enter__()

        self.am = basic.AnsibleModule(argument_spec=dict(), )

        self.has_journal = basic.has_journal
        if self.has_journal:
            # Systems with journal can still test syslog
            basic.has_journal = False
    def test_module_utils_basic__log_invocation(self):
        with swap_stdin_and_argv(stdin_data=json.dumps(
                dict(ANSIBLE_MODULE_ARGS=dict(
                    foo=False, bar=[1, 2, 3], bam="bam", baz=u'baz'),
                     ANSIBLE_MODULE_CONSTANTS=dict()))):
            from ansible.module_utils import basic

            # test basic log invocation
            am = basic.AnsibleModule(argument_spec=dict(
                foo=dict(default=True, type='bool'),
                bar=dict(default=[], type='list'),
                bam=dict(default="bam"),
                baz=dict(default=u"baz"),
                password=dict(default=True),
                no_log=dict(default="you shouldn't see me", no_log=True),
            ), )

            am.log = MagicMock()
            am._log_invocation()

            # Message is generated from a dict so it will be in an unknown order.
            # have to check this manually rather than with assert_called_with()
            args = am.log.call_args[0]
            self.assertEqual(len(args), 1)
            message = args[0]

            self.assertEqual(
                len(message),
                len('Invoked with bam=bam bar=[1, 2, 3] foo=False baz=baz no_log=NOT_LOGGING_PARAMETER password=NOT_LOGGING_PASSWORD'
                    ))
            self.assertTrue(message.startswith('Invoked with '))
            self.assertIn(' bam=bam', message)
            self.assertIn(' bar=[1, 2, 3]', message)
            self.assertIn(' foo=False', message)
            self.assertIn(' baz=baz', message)
            self.assertIn(' no_log=NOT_LOGGING_PARAMETER', message)
            self.assertIn(' password=NOT_LOGGING_PASSWORD', message)

            kwargs = am.log.call_args[1]
            self.assertEqual(
                kwargs,
                dict(
                    log_args={
                        'foo': 'False',
                        'bar': '[1, 2, 3]',
                        'bam': 'bam',
                        'baz': 'baz',
                        'password': '******',
                        'no_log': 'NOT_LOGGING_PARAMETER',
                    }))
예제 #11
0
    def setUp(self):
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))
        # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
        self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
        self.stdin_swap.__enter__()

        reload(basic)
        self.am = basic.AnsibleModule(
            argument_spec = dict(),
        )

        self.has_journal = basic.has_journal
        if self.has_journal:
            # Systems with journal can still test syslog
            basic.has_journal = False
예제 #12
0
    def test_warn(self):
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
        with swap_stdin_and_argv(stdin_data=args):
            with swap_stdout():

                ansible.module_utils.basic._ANSIBLE_ARGS = None
                am = ansible.module_utils.basic.AnsibleModule(
                    argument_spec=dict(),
                )
                am._name = 'unittest'

                am.warn('warning1')

                with self.assertRaises(SystemExit):
                    am.exit_json(warnings=['warning2'])
                self.assertEquals(json.loads(sys.stdout.getvalue())['warnings'], ['warning1', 'warning2'])
예제 #13
0
    def test_warn(self):
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
        with swap_stdin_and_argv(stdin_data=args):
            with swap_stdout():

                ansible.module_utils.basic._ANSIBLE_ARGS = None
                am = ansible.module_utils.basic.AnsibleModule(
                    argument_spec = dict(),
                )
                am._name = 'unittest'

                am.warn('warning1')

                with self.assertRaises(SystemExit):
                    am.exit_json(warnings=['warning2'])
                self.assertEquals(json.loads(sys.stdout.getvalue())['warnings'], ['warning1', 'warning2'])
예제 #14
0
파일: test_log.py 프로젝트: ernstp/ansible
    def setUp(self):
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
        # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
        self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
        self.stdin_swap.__enter__()

        ansible.module_utils.basic._ANSIBLE_ARGS = None
        self.am = ansible.module_utils.basic.AnsibleModule(
            argument_spec=dict(),
        )
        self.am._name = 'unittest'

        self.has_journal = ansible.module_utils.basic.has_journal
        if self.has_journal:
            # Systems with journal can still test syslog
            ansible.module_utils.basic.has_journal = False
예제 #15
0
    def test_deprecate_without_list(self):
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
        with swap_stdin_and_argv(stdin_data=args):
            with swap_stdout():

                ansible.module_utils.basic._ANSIBLE_ARGS = None
                am = ansible.module_utils.basic.AnsibleModule(
                    argument_spec=dict(),
                )
                am._name = 'unittest'

                with self.assertRaises(SystemExit):
                    am.exit_json(deprecations='Simple deprecation warning')
                output = json.loads(sys.stdout.getvalue())
                self.assertTrue('warnings' not in output or output['warnings'] == [])
                self.assertEquals(output['deprecations'], [
                    {u'msg': u'Simple deprecation warning', u'version': None},
                ])
예제 #16
0
    def test_deprecate_without_list(self):
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
        with swap_stdin_and_argv(stdin_data=args):
            with swap_stdout():

                ansible.module_utils.basic._ANSIBLE_ARGS = None
                am = ansible.module_utils.basic.AnsibleModule(
                    argument_spec = dict(),
                )
                am._name = 'unittest'

                with self.assertRaises(SystemExit):
                    am.exit_json(deprecations='Simple deprecation warning')
                output = json.loads(sys.stdout.getvalue())
                self.assertTrue('warnings' not in output or output['warnings'] == [])
                self.assertEquals(output['deprecations'], [
                    {u'msg': u'Simple deprecation warning', u'version': None},
                ])
예제 #17
0
    def test_module_utils_basic_ansible_module_is_special_selinux_path(self):
        from ansible.module_utils import basic

        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={'_ansible_selinux_special_fs': "nfs,nfsd,foos",
                                                    '_ansible_remote_tmp': "/tmp",
                                                    '_ansible_keep_remote_files': False}))

        with swap_stdin_and_argv(stdin_data=args):
            basic._ANSIBLE_ARGS = None
            am = basic.AnsibleModule(
                argument_spec=dict(),
            )

            def _mock_find_mount_point(path):
                if path.startswith('/some/path'):
                    return '/some/path'
                elif path.startswith('/weird/random/fstype'):
                    return '/weird/random/fstype'
                return '/'

            am.find_mount_point = MagicMock(side_effect=_mock_find_mount_point)
            am.selinux_context = MagicMock(return_value=['foo_u', 'foo_r', 'foo_t', 's0'])

            m = mock_open()
            m.side_effect = OSError

            with patch.object(builtins, 'open', m, create=True):
                self.assertEqual(am.is_special_selinux_path('/some/path/that/should/be/nfs'), (False, None))

            mount_data = [
                '/dev/disk1 / ext4 rw,seclabel,relatime,data=ordered 0 0\n',
                '1.1.1.1:/path/to/nfs /some/path nfs ro 0 0\n',
                'whatever /weird/random/fstype foos rw 0 0\n',
            ]

            # mock_open has a broken readlines() implementation apparently...
            # this should work by default but doesn't, so we fix it
            m = mock_open(read_data=''.join(mount_data))
            m.return_value.readlines.return_value = mount_data

            with patch.object(builtins, 'open', m, create=True):
                self.assertEqual(am.is_special_selinux_path('/some/random/path'), (False, None))
                self.assertEqual(am.is_special_selinux_path('/some/path/that/should/be/nfs'), (True, ['foo_u', 'foo_r', 'foo_t', 's0']))
                self.assertEqual(am.is_special_selinux_path('/weird/random/fstype/path'), (True, ['foo_u', 'foo_r', 'foo_t', 's0']))
예제 #18
0
    def test_module_utils_basic_ansible_module_is_special_selinux_path(self):
        from ansible.module_utils import basic
        reload(basic)

        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={"SELINUX_SPECIAL_FS": "nfs,nfsd,foos"}))

        with swap_stdin_and_argv(stdin_data=args):

            am = basic.AnsibleModule(
                argument_spec = dict(),
            )
            print(am.constants)

            def _mock_find_mount_point(path):
                if path.startswith('/some/path'):
                    return '/some/path'
                elif path.startswith('/weird/random/fstype'):
                    return '/weird/random/fstype'
                return '/'

            am.find_mount_point = MagicMock(side_effect=_mock_find_mount_point)
            am.selinux_context = MagicMock(return_value=['foo_u', 'foo_r', 'foo_t', 's0'])

            m = mock_open()
            m.side_effect = OSError

            with patch.object(builtins, 'open', m, create=True):
                self.assertEqual(am.is_special_selinux_path('/some/path/that/should/be/nfs'), (False, None))

            mount_data = [
                '/dev/disk1 / ext4 rw,seclabel,relatime,data=ordered 0 0\n',
                '1.1.1.1:/path/to/nfs /some/path nfs ro 0 0\n',
                'whatever /weird/random/fstype foos rw 0 0\n',
            ]

            # mock_open has a broken readlines() implementation apparently...
            # this should work by default but doesn't, so we fix it
            m = mock_open(read_data=''.join(mount_data))
            m.return_value.readlines.return_value = mount_data

            with patch.object(builtins, 'open', m, create=True):
                self.assertEqual(am.is_special_selinux_path('/some/random/path'), (False, None))
                self.assertEqual(am.is_special_selinux_path('/some/path/that/should/be/nfs'), (True, ['foo_u', 'foo_r', 'foo_t', 's0']))
                self.assertEqual(am.is_special_selinux_path('/weird/random/fstype/path'), (True, ['foo_u', 'foo_r', 'foo_t', 's0']))
예제 #19
0
    def test_module_utils_basic_safe_eval(self):
        from ansible.module_utils import basic

        args = json.dumps(
            dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))

        with swap_stdin_and_argv(stdin_data=args):
            reload(basic)
            am = basic.AnsibleModule(argument_spec=dict(), )

            # test some basic usage
            # string (and with exceptions included), integer, bool
            self.assertEqual(am.safe_eval("'a'"), 'a')
            self.assertEqual(am.safe_eval("'a'", include_exceptions=True),
                             ('a', None))
            self.assertEqual(am.safe_eval("1"), 1)
            self.assertEqual(am.safe_eval("True"), True)
            self.assertEqual(am.safe_eval("False"), False)
            self.assertEqual(am.safe_eval("{}"), {})
            # not passing in a string to convert
            self.assertEqual(am.safe_eval({'a': 1}), {'a': 1})
            self.assertEqual(am.safe_eval({'a': 1}, include_exceptions=True),
                             ({
                                 'a': 1
                             }, None))
            # invalid literal eval
            self.assertEqual(am.safe_eval("a=1"), "a=1")
            res = am.safe_eval("a=1", include_exceptions=True)
            self.assertEqual(res[0], "a=1")
            self.assertEqual(type(res[1]), SyntaxError)
            self.assertEqual(am.safe_eval("a.foo()"), "a.foo()")
            res = am.safe_eval("a.foo()", include_exceptions=True)
            self.assertEqual(res[0], "a.foo()")
            self.assertEqual(res[1], None)
            self.assertEqual(am.safe_eval("import foo"), "import foo")
            res = am.safe_eval("import foo", include_exceptions=True)
            self.assertEqual(res[0], "import foo")
            self.assertEqual(res[1], None)
            self.assertEqual(am.safe_eval("__import__('foo')"),
                             "__import__('foo')")
            res = am.safe_eval("__import__('foo')", include_exceptions=True)
            self.assertEqual(res[0], "__import__('foo')")
            self.assertEqual(type(res[1]), ValueError)
예제 #20
0
    def test_exit_json_removes_values(self):
        self.maxDiff = None
        for args, return_val, expected in self.dataset:
            params = dict(ANSIBLE_MODULE_ARGS=args)
            params = json.dumps(params)

            with swap_stdin_and_argv(stdin_data=params):
                with swap_stdout():
                    basic._ANSIBLE_ARGS = None
                    module = basic.AnsibleModule(
                        argument_spec=dict(
                            username=dict(),
                            password=dict(no_log=True),
                            token=dict(no_log=True),
                        ),
                    )
                    with self.assertRaises(SystemExit) as ctx:
                        self.assertEquals(module.exit_json(**return_val), expected)
                    self.assertEquals(json.loads(sys.stdout.getvalue()), expected)
예제 #21
0
    def test_exit_json_removes_values(self):
        self.maxDiff = None
        for args, return_val, expected in self.dataset:
            params = dict(ANSIBLE_MODULE_ARGS=args, ANSIBLE_MODULE_CONSTANTS={})
            params = json.dumps(params)

            with swap_stdin_and_argv(stdin_data=params):
                reload(basic)
                with swap_stdout():
                    module = basic.AnsibleModule(
                        argument_spec = dict(
                            username=dict(),
                            password=dict(no_log=True),
                            token=dict(no_log=True),
                            ),
                        )
                    with self.assertRaises(SystemExit) as ctx:
                        self.assertEquals(module.exit_json(**return_val), expected)
                    self.assertEquals(json.loads(sys.stdout.getvalue()), expected)
예제 #22
0
 def test_fail_json_removes_values(self):
     self.maxDiff = None
     for args, return_val, expected in self.dataset:
         expected = copy.deepcopy(expected)
         expected['failed'] = True
         params = dict(ANSIBLE_MODULE_ARGS=args)
         params = json.dumps(params)
         with swap_stdin_and_argv(stdin_data=params):
             with swap_stdout():
                 basic._ANSIBLE_ARGS = None
                 module = basic.AnsibleModule(
                     argument_spec=dict(
                         username=dict(),
                         password=dict(no_log=True),
                         token=dict(no_log=True),
                     ),
                 )
                 with self.assertRaises(SystemExit) as ctx:
                     self.assertEquals(module.fail_json(**return_val), expected)
                 self.assertEquals(json.loads(sys.stdout.getvalue()), expected)
예제 #23
0
def test_distribution_version(testcase):
    """tests the distribution parsing code of the Facts class

    testsets have
    * a name (for output/debugging only)
    * input files that are faked
      * those should be complete and also include "irrelevant" files that might be mistaken as coming from other distributions
      * all files that are not listed here are assumed to not exist at all
    * the output of pythons platform.dist()
    * results for the ansible variables distribution* and os_family
    """

    from ansible.module_utils import basic

    args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
    with swap_stdin_and_argv(stdin_data=args):
        basic._ANSIBLE_ARGS = None
        module = basic.AnsibleModule(argument_spec=dict())

        _test_one_distribution(facts, module, testcase)
예제 #24
0
def test_distribution_version(testcase):
    """tests the distribution parsing code of the Facts class

    testsets have
    * a name (for output/debugging only)
    * input files that are faked
      * those should be complete and also include "irrelevant" files that might be mistaken as coming from other distributions
      * all files that are not listed here are assumed to not exist at all
    * the output of pythons platform.dist()
    * results for the ansible variables distribution* and os_family
    """

    from ansible.module_utils import basic

    args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
    with swap_stdin_and_argv(stdin_data=args):
        basic._ANSIBLE_ARGS = None
        module = basic.AnsibleModule(argument_spec=dict())

        _test_one_distribution(module, testcase)
예제 #25
0
 def test_fail_json_removes_values(self):
     self.maxDiff = None
     for args, return_val, expected in self.dataset:
         expected = copy.deepcopy(expected)
         del expected['changed']
         expected['failed'] = True
         params = dict(ANSIBLE_MODULE_ARGS=args,
                       ANSIBLE_MODULE_CONSTANTS={})
         params = json.dumps(params)
         with swap_stdin_and_argv(stdin_data=params):
             with swap_stdout():
                 module = basic.AnsibleModule(argument_spec=dict(
                     username=dict(),
                     password=dict(no_log=True),
                     token=dict(no_log=True),
                 ), )
                 with self.assertRaises(SystemExit) as ctx:
                     self.assertEquals(module.fail_json(**return_val),
                                       expected)
                 self.assertEquals(json.loads(sys.stdout.getvalue()),
                                   expected)
예제 #26
0
    def test_module_utils_basic_safe_eval(self):
        from ansible.module_utils import basic

        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))

        with swap_stdin_and_argv(stdin_data=args):
            reload(basic)
            am = basic.AnsibleModule(
                argument_spec=dict(),
            )

            # test some basic usage
            # string (and with exceptions included), integer, bool
            self.assertEqual(am.safe_eval("'a'"), 'a')
            self.assertEqual(am.safe_eval("'a'", include_exceptions=True), ('a', None))
            self.assertEqual(am.safe_eval("1"), 1)
            self.assertEqual(am.safe_eval("True"), True)
            self.assertEqual(am.safe_eval("False"), False)
            self.assertEqual(am.safe_eval("{}"), {})
            # not passing in a string to convert
            self.assertEqual(am.safe_eval({'a':1}), {'a':1})
            self.assertEqual(am.safe_eval({'a':1}, include_exceptions=True), ({'a':1}, None))
            # invalid literal eval
            self.assertEqual(am.safe_eval("a=1"), "a=1")
            res = am.safe_eval("a=1", include_exceptions=True)
            self.assertEqual(res[0], "a=1")
            self.assertEqual(type(res[1]), SyntaxError)
            self.assertEqual(am.safe_eval("a.foo()"), "a.foo()")
            res = am.safe_eval("a.foo()", include_exceptions=True)
            self.assertEqual(res[0], "a.foo()")
            self.assertEqual(res[1], None)
            self.assertEqual(am.safe_eval("import foo"), "import foo")
            res = am.safe_eval("import foo", include_exceptions=True)
            self.assertEqual(res[0], "import foo")
            self.assertEqual(res[1], None)
            self.assertEqual(am.safe_eval("__import__('foo')"), "__import__('foo')")
            res = am.safe_eval("__import__('foo')", include_exceptions=True)
            self.assertEqual(res[0], "__import__('foo')")
            self.assertEqual(type(res[1]), ValueError)
예제 #27
0
def test_distribution_version():
    """tests the distribution parsing code of the Facts class

    testsets have
    * a name (for output/debugging only)
    * input files that are faked
      * those should be complete and also include "irrelevant" files that might be mistaken as coming from other distributions
      * all files that are not listed here are assumed to not exist at all
    * the output of pythons platform.dist()
    * results for the ansible variables distribution*
    """

    from ansible.module_utils import basic

    args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
    with swap_stdin_and_argv(stdin_data=args):
        module = basic.AnsibleModule(argument_spec=dict())

        for t in TESTSETS:
            # run individual tests via generator
            # set nicer stdout output for nosetest
            _test_one_distribution.description = "check distribution_version for %s" % t['name']
            yield _test_one_distribution, facts, module, t
예제 #28
0
 def setUp(self):
     args = json.dumps(
         dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))
     # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
     self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
     self.stdin_swap.__enter__()
예제 #29
0
    def test_module_utils_basic_ansible_module_creation(self):
        from ansible.module_utils import basic

        am = basic.AnsibleModule(argument_spec=dict(), )

        arg_spec = dict(
            foo=dict(required=True),
            bar=dict(),
            bam=dict(),
            baz=dict(),
        )
        mut_ex = (('bar', 'bam'), )
        req_to = (('bam', 'baz'), )

        # should test ok
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={"foo": "hello"}))

        with swap_stdin_and_argv(stdin_data=args):
            basic._ANSIBLE_ARGS = None
            am = basic.AnsibleModule(
                argument_spec=arg_spec,
                mutually_exclusive=mut_ex,
                required_together=req_to,
                no_log=True,
                check_invalid_arguments=False,
                add_file_common_args=True,
                supports_check_mode=True,
            )

        # FIXME: add asserts here to verify the basic config

        # fail, because a required param was not specified
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))

        with swap_stdin_and_argv(stdin_data=args):
            basic._ANSIBLE_ARGS = None
            self.assertRaises(
                SystemExit,
                basic.AnsibleModule,
                argument_spec=arg_spec,
                mutually_exclusive=mut_ex,
                required_together=req_to,
                no_log=True,
                check_invalid_arguments=False,
                add_file_common_args=True,
                supports_check_mode=True,
            )

        # fail because of mutually exclusive parameters
        args = json.dumps(
            dict(ANSIBLE_MODULE_ARGS={
                "foo": "hello",
                "bar": "bad",
                "bam": "bad"
            }))

        with swap_stdin_and_argv(stdin_data=args):
            basic._ANSIBLE_ARGS = None
            self.assertRaises(
                SystemExit,
                basic.AnsibleModule,
                argument_spec=arg_spec,
                mutually_exclusive=mut_ex,
                required_together=req_to,
                no_log=True,
                check_invalid_arguments=False,
                add_file_common_args=True,
                supports_check_mode=True,
            )

        # fail because a param required due to another param was not specified
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={"bam": "bad"}))

        with swap_stdin_and_argv(stdin_data=args):
            basic._ANSIBLE_ARGS = None
            self.assertRaises(
                SystemExit,
                basic.AnsibleModule,
                argument_spec=arg_spec,
                mutually_exclusive=mut_ex,
                required_together=req_to,
                no_log=True,
                check_invalid_arguments=False,
                add_file_common_args=True,
                supports_check_mode=True,
            )
예제 #30
0
    def test_module_utils_basic_ansible_module_creation(self):
        from ansible.module_utils import basic

        am = basic.AnsibleModule(
            argument_spec=dict(),
        )

        arg_spec = dict(
            foo = dict(required=True),
            bar = dict(),
            bam = dict(),
            baz = dict(),
        )
        mut_ex = (('bar', 'bam'),)
        req_to = (('bam', 'baz'),)

        # should test ok
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={"foo": "hello"}, ANSIBLE_MODULE_CONSTANTS={}))

        with swap_stdin_and_argv(stdin_data=args):
            reload(basic)
            am = basic.AnsibleModule(
                argument_spec = arg_spec,
                mutually_exclusive = mut_ex,
                required_together = req_to,
                no_log=True,
                check_invalid_arguments=False,
                add_file_common_args=True,
                supports_check_mode=True,
            )

        # FIXME: add asserts here to verify the basic config

        # fail, because a required param was not specified
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))

        with swap_stdin_and_argv(stdin_data=args):
            reload(basic)
            self.assertRaises(
                SystemExit,
                basic.AnsibleModule,
                argument_spec = arg_spec,
                mutually_exclusive = mut_ex,
                required_together = req_to,
                no_log=True,
                check_invalid_arguments=False,
                add_file_common_args=True,
                supports_check_mode=True,
            )

        # fail because of mutually exclusive parameters
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={"foo":"hello", "bar": "bad", "bam": "bad"}, ANSIBLE_MODULE_CONSTANTS={}))

        with swap_stdin_and_argv(stdin_data=args):
            self.assertRaises(
                SystemExit,
                basic.AnsibleModule,
                argument_spec = arg_spec,
                mutually_exclusive = mut_ex,
                required_together = req_to,
                no_log=True,
                check_invalid_arguments=False,
                add_file_common_args=True,
                supports_check_mode=True,
            )

        # fail because a param required due to another param was not specified
        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={"bam": "bad"}, ANSIBLE_MODULE_CONSTANTS={}))

        with swap_stdin_and_argv(stdin_data=args):
            self.assertRaises(
                SystemExit,
                basic.AnsibleModule,
                argument_spec = arg_spec,
                mutually_exclusive = mut_ex,
                required_together = req_to,
                no_log=True,
                check_invalid_arguments=False,
                add_file_common_args=True,
                supports_check_mode=True,
            )
예제 #31
0
 def setUp(self):
     args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))
     # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
     self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
     self.stdin_swap.__enter__()