示例#1
0
def test_build_ignore_files_and_folders(collection_input, monkeypatch):
    input_dir = collection_input[0]

    mock_display = MagicMock()
    monkeypatch.setattr(Display, 'vvv', mock_display)

    git_folder = os.path.join(input_dir, '.git')
    retry_file = os.path.join(input_dir, 'ansible.retry')

    tests_folder = os.path.join(input_dir, 'tests', 'output')
    tests_output_file = os.path.join(tests_folder, 'result.txt')

    os.makedirs(git_folder)
    os.makedirs(tests_folder)

    with open(retry_file, 'w+') as ignore_file:
        ignore_file.write('random')
        ignore_file.flush()

    with open(tests_output_file, 'w+') as tests_file:
        tests_file.write('random')
        tests_file.flush()

    actual = collection._build_files_manifest(to_bytes(input_dir), 'namespace', 'collection', [])

    assert actual['format'] == 1
    for manifest_entry in actual['files']:
        assert manifest_entry['name'] not in ['.git', 'ansible.retry', 'galaxy.yml', 'tests/output', 'tests/output/result.txt']

    expected_msgs = [
        "Skipping '%s/galaxy.yml' for collection build" % to_text(input_dir),
        "Skipping '%s' for collection build" % to_text(retry_file),
        "Skipping '%s' for collection build" % to_text(git_folder),
        "Skipping '%s' for collection build" % to_text(tests_folder),
    ]
    assert mock_display.call_count == 4
    assert mock_display.mock_calls[0][1][0] in expected_msgs
    assert mock_display.mock_calls[1][1][0] in expected_msgs
    assert mock_display.mock_calls[2][1][0] in expected_msgs
    assert mock_display.mock_calls[3][1][0] in expected_msgs
示例#2
0
def test_install_collections_existing_without_force(collection_artifact,
                                                    monkeypatch):
    collection_path, collection_tar = collection_artifact
    temp_path = os.path.split(collection_tar)[0]

    mock_display = MagicMock()
    monkeypatch.setattr(Display, 'display', mock_display)

    # If we don't delete collection_path it will think the original build skeleton is installed so we expect a skip
    collection.install_collections([(
        to_text(collection_tar),
        '*',
        None,
    )], to_text(temp_path), [u'https://galaxy.ansible.com'], True, False,
                                   False, False, False)

    assert os.path.isdir(collection_path)

    actual_files = os.listdir(collection_path)
    actual_files.sort()
    assert actual_files == [
        b'README.md', b'docs', b'galaxy.yml', b'playbooks', b'plugins',
        b'roles', b'runme.sh'
    ]

    # Filter out the progress cursor display calls.
    display_msgs = [
        m[1][0] for m in mock_display.mock_calls
        if 'newline' not in m[2] and len(m[1]) == 1
    ]
    assert len(display_msgs) == 3

    assert display_msgs[0] == "Process install dependency map"
    assert display_msgs[1] == "Starting collection install process"
    assert display_msgs[
        2] == "Skipping 'ansible_namespace.collection' as it is already installed"

    for msg in display_msgs:
        assert 'WARNING' not in msg
示例#3
0
    def test_load_role_with_vars_nested_dirs_combined(self):

        fake_loader = DictDataLoader({
            "/etc/ansible/roles/foo_vars/defaults/main/foo/bar.yml":
            """
            foo: bar
            a: 1
            """,
            "/etc/ansible/roles/foo_vars/defaults/main/bar/foo.yml":
            """
            foo: bam
            b: 2
            """,
        })

        mock_play = MagicMock()
        mock_play.ROLE_CACHE = {}

        i = RoleInclude.load('foo_vars', play=mock_play, loader=fake_loader)
        r = Role.load(i, play=mock_play)

        self.assertEqual(r._default_vars, dict(foo='bar', a=1, b=2))
示例#4
0
 def test_run_setup_csior_enable_case(self,
                                      idrac_connection_lc_attribute_mock,
                                      idrac_default_args,
                                      idrac_file_manager_lc_attribute_mock):
     idrac_default_args.update({
         "share_name": "sharename",
         "share_mnt": "mountname",
         "share_user": "******",
         "share_password": "******",
         "csior": 'Enabled'
     })
     message = "Enabled"
     obj = MagicMock()
     idrac_connection_lc_attribute_mock.config_mgr = obj
     type(obj).enable_csior = Mock(return_value='Enabled')
     idrac_connection_lc_attribute_mock.config_mgr.is_change_applicable.return_value = message
     f_module = self.get_module_mock(params=idrac_default_args,
                                     check_mode=True)
     msg, err = self.module.run_setup_idrac_csior(
         idrac_connection_lc_attribute_mock, f_module)
     assert msg == {'changed': False, 'failed': False, 'msg': 'Enabled'}
     assert err is False
示例#5
0
    def test_kinit_with_missing_executable_pexpect(self, monkeypatch):
        pexpect = pytest.importorskip("pexpect")

        expected_err = "The command was not found or was not " \
                       "executable: /fake/kinit"
        mock_pexpect = \
            MagicMock(side_effect=pexpect.ExceptionPexpect(expected_err))

        monkeypatch.setattr("pexpect.spawn", mock_pexpect)

        winrm.HAS_PEXPECT = True
        pc = PlayContext()
        new_stdin = StringIO()
        conn = connection_loader.get('winrm', pc, new_stdin)
        options = {"_extras": {}, "ansible_winrm_kinit_cmd": "/fake/kinit"}
        conn.set_options(var_options=options)
        conn._build_winrm_kwargs()

        with pytest.raises(AnsibleConnectionFailure) as err:
            conn._kerb_auth("user@domain", "pass")
        assert str(err.value) == "Kerberos auth failure when calling " \
                                 "kinit cmd '/fake/kinit': %s" % expected_err
示例#6
0
def test_download_file(tmp_path_factory, monkeypatch):
    temp_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections'))

    data = b"\x00\x01\x02\x03"
    sha256_hash = sha256()
    sha256_hash.update(data)

    mock_open = MagicMock()
    mock_open.return_value = BytesIO(data)
    monkeypatch.setattr(collection, 'open_url', mock_open)

    expected = os.path.join(temp_dir, b'file')
    actual = collection._download_file('http://google.com/file', temp_dir,
                                       sha256_hash.hexdigest(), True)

    assert actual.startswith(expected)
    assert os.path.isfile(actual)
    with open(actual, 'rb') as file_obj:
        assert file_obj.read() == data

    assert mock_open.call_count == 1
    assert mock_open.mock_calls[0][1][0] == 'http://google.com/file'
示例#7
0
def test_initialise_galaxy(monkeypatch):
    mock_open = MagicMock()
    mock_open.side_effect = [
        StringIO(u'{"available_versions":{"v1":"v1/"}}'),
        StringIO(u'{"token":"my token"}'),
    ]
    monkeypatch.setattr(galaxy_api, 'open_url', mock_open)

    api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/")
    actual = api.authenticate("github_token")

    assert len(api.available_api_versions) == 2
    assert api.available_api_versions['v1'] == u'v1/'
    assert api.available_api_versions['v2'] == u'v2/'
    assert actual == {u'token': u'my token'}
    assert mock_open.call_count == 2
    assert mock_open.mock_calls[0][1][0] == 'https://galaxy.ansible.com/api/'
    assert 'ansible-galaxy' in mock_open.mock_calls[0][2]['http_agent']
    assert mock_open.mock_calls[1][1][
        0] == 'https://galaxy.ansible.com/api/v1/tokens/'
    assert 'ansible-galaxy' in mock_open.mock_calls[1][2]['http_agent']
    assert mock_open.mock_calls[1][2]['data'] == 'github_token=github_token'
示例#8
0
def test_publish_collection(api_version, collection_url, collection_artifact,
                            monkeypatch):
    api = get_test_galaxy_api("https://galaxy.ansible.com/api/", api_version)

    mock_call = MagicMock()
    mock_call.return_value = {'task': 'http://task.url/'}
    monkeypatch.setattr(api, '_call_galaxy', mock_call)

    actual = api.publish_collection(collection_artifact)
    assert actual == 'http://task.url/'
    assert mock_call.call_count == 1
    assert mock_call.mock_calls[0][1][
        0] == 'https://galaxy.ansible.com/api/%s/%s/' % (api_version,
                                                         collection_url)
    assert mock_call.mock_calls[0][2]['headers']['Content-length'] == len(
        mock_call.mock_calls[0][2]['args'])
    assert mock_call.mock_calls[0][2]['headers']['Content-type'].startswith(
        'multipart/form-data; boundary=--------------------------')
    assert mock_call.mock_calls[0][2]['args'].startswith(
        b'--------------------------')
    assert mock_call.mock_calls[0][2]['method'] == 'POST'
    assert mock_call.mock_calls[0][2]['auth_required'] is True
示例#9
0
    def test_play_with_roles(self):
        fake_loader = DictDataLoader({
            '/etc/assible/roles/foo/tasks.yml':
            """
            - name: role task
              shell: echo "hello world"
            """,
        })

        mock_var_manager = MagicMock()
        mock_var_manager.get_vars.return_value = dict()

        p = Play.load(dict(
            name="test play",
            hosts=['foo'],
            gather_facts=False,
            roles=['foo'],
        ),
                      loader=fake_loader,
                      variable_manager=mock_var_manager)

        blocks = p.compile()
def test_install_collection(collection_artifact, monkeypatch):
    mock_display = MagicMock()
    monkeypatch.setattr(Display, 'display', mock_display)

    collection_tar = collection_artifact[1]
    output_path = os.path.join(os.path.split(collection_tar)[0], b'output')
    collection_path = os.path.join(output_path, b'assible_namespace',
                                   b'collection')
    os.makedirs(os.path.join(collection_path, b'delete_me')
                )  # Create a folder to verify the install cleans out the dir

    temp_path = os.path.join(os.path.split(collection_tar)[0], b'temp')
    os.makedirs(temp_path)

    req = collection.CollectionRequirement.from_tar(collection_tar, True, True)
    req.install(to_text(output_path), temp_path)

    # Ensure the temp directory is empty, nothing is left behind
    assert os.listdir(temp_path) == []

    actual_files = os.listdir(collection_path)
    actual_files.sort()
    assert actual_files == [
        b'FILES.json', b'MANIFEST.json', b'README.md', b'docs', b'playbooks',
        b'plugins', b'roles', b'runme.sh'
    ]

    assert stat.S_IMODE(
        os.stat(os.path.join(collection_path, b'plugins')).st_mode) == 0o0755
    assert stat.S_IMODE(
        os.stat(os.path.join(collection_path, b'README.md')).st_mode) == 0o0644
    assert stat.S_IMODE(
        os.stat(os.path.join(collection_path, b'runme.sh')).st_mode) == 0o0755

    assert mock_display.call_count == 2
    assert mock_display.mock_calls[0][1][0] == "Installing 'assible_namespace.collection:0.1.0' to '%s'" \
        % to_text(collection_path)
    assert mock_display.mock_calls[1][1][
        0] == "assible_namespace.collection (0.1.0) was installed successfully"
示例#11
0
    def test_multiple_failures(self, monkeypatch):
        self.conn.set_option('host_key_checking', False)
        self.conn.set_option('reconnection_retries', 9)

        monkeypatch.setattr('time.sleep', lambda x: None)

        self.mock_popen_res.stdout.read.side_effect = [b""] * 10
        self.mock_popen_res.stderr.read.side_effect = [b""] * 10
        type(self.mock_popen_res).returncode = PropertyMock(side_effect=[255] * 30)

        self.mock_selector.select.side_effect = [
            [(SelectorKey(self.mock_popen_res.stdout, 1001, [EVENT_READ], None), EVENT_READ)],
            [(SelectorKey(self.mock_popen_res.stderr, 1002, [EVENT_READ], None), EVENT_READ)],
            [],
        ] * 10
        self.mock_selector.get_map.side_effect = lambda: True

        self.conn._build_command = MagicMock()
        self.conn._build_command.return_value = 'ssh'

        pytest.raises(AnsibleConnectionFailure, self.conn.exec_command, 'ssh', 'some data')
        assert self.mock_popen.call_count == 10
示例#12
0
def test_verify_file_hash_mismatching_hash(manifest_info):

    data = to_bytes(json.dumps(manifest_info))
    digest = sha256(data).hexdigest()
    different_digest = 'not_{0}'.format(digest)

    namespace = manifest_info['collection_info']['namespace']
    name = manifest_info['collection_info']['name']
    version = manifest_info['collection_info']['version']
    server = 'http://galaxy.ansible.com'

    error_queue = []

    with patch.object(builtins, 'open', mock_open(read_data=data)) as m:
        with patch.object(collection.os.path, 'isfile', MagicMock(return_value=True)) as mock_isfile:
            collection._verify_file_hash(b'path/', 'file', different_digest, error_queue)

            assert mock_isfile.called_once

    assert len(error_queue) == 1
    assert error_queue[0].installed == digest
    assert error_queue[0].expected == different_digest
def test_install_missing_metadata_warning(collection_artifact, monkeypatch):
    collection_path, collection_tar = collection_artifact
    temp_path = os.path.split(collection_tar)[0]

    mock_display = MagicMock()
    monkeypatch.setattr(Display, 'display', mock_display)

    for file in [b'MANIFEST.json', b'galaxy.yml']:
        b_path = os.path.join(collection_path, file)
        if os.path.isfile(b_path):
            os.unlink(b_path)

    collection.install_collections(
        [(to_text(collection_tar), '*', None, None)], to_text(temp_path),
        [u'https://galaxy.assible.com'], True, False, False, False, False)

    display_msgs = [
        m[1][0] for m in mock_display.mock_calls
        if 'newline' not in m[2] and len(m[1]) == 1
    ]

    assert 'WARNING' in display_msgs[0]
示例#14
0
    def test_task_executor_run_loop(self):
        items = ['a', 'b', 'c']

        fake_loader = DictDataLoader({})

        mock_host = MagicMock()

        def _copy(exclude_parent=False, exclude_tasks=False):
            new_item = MagicMock()
            return new_item

        mock_task = MagicMock()
        mock_task.copy.side_effect = _copy

        mock_play_context = MagicMock()

        mock_shared_loader = MagicMock()
        mock_queue = MagicMock()

        new_stdin = None
        job_vars = dict()

        te = TaskExecutor(
            host=mock_host,
            task=mock_task,
            job_vars=job_vars,
            play_context=mock_play_context,
            new_stdin=new_stdin,
            loader=fake_loader,
            shared_loader_obj=mock_shared_loader,
            final_q=mock_queue,
        )

        def _execute(variables):
            return dict(item=variables.get('item'))

        te._squash_items = MagicMock(return_value=items)
        te._execute = MagicMock(side_effect=_execute)

        res = te._run_loop(items)
        self.assertEqual(len(res), 3)
示例#15
0
    def test_fetch_file_retries(self, monkeypatch):
        monkeypatch.setattr(C, 'HOST_KEY_CHECKING', False)
        monkeypatch.setattr(C, 'ANSIBLE_SSH_RETRIES', 3)

        monkeypatch.setattr('time.sleep', lambda x: None)
        monkeypatch.setattr('ansible.plugins.connection.ssh.os.path.exists',
                            lambda x: True)

        self.mock_popen_res.stdout.read.side_effect = [
            b"", b"my_stdout\n", b"second_line"
        ]
        self.mock_popen_res.stderr.read.side_effect = [b"", b"my_stderr"]
        type(self.mock_popen_res).returncode = PropertyMock(
            side_effect=[255] * 4 + [0] * 4)

        self.mock_selector.select.side_effect = [
            [(SelectorKey(self.mock_popen_res.stdout, 1001, [EVENT_READ],
                          None), EVENT_READ)],
            [(SelectorKey(self.mock_popen_res.stderr, 1002, [EVENT_READ],
                          None), EVENT_READ)], [],
            [(SelectorKey(self.mock_popen_res.stdout, 1001, [EVENT_READ],
                          None), EVENT_READ)],
            [(SelectorKey(self.mock_popen_res.stdout, 1001, [EVENT_READ],
                          None), EVENT_READ)],
            [(SelectorKey(self.mock_popen_res.stderr, 1002, [EVENT_READ],
                          None), EVENT_READ)], []
        ]
        self.mock_selector.get_map.side_effect = lambda: True

        self.conn._build_command = MagicMock()
        self.conn._build_command.return_value = 'sftp'

        return_code, b_stdout, b_stderr = self.conn.fetch_file(
            '/path/to/in/file', '/path/to/dest/file')
        assert return_code == 0
        assert b_stdout == b"my_stdout\nsecond_line"
        assert b_stderr == b"my_stderr"
        assert self.mock_popen.call_count == 2
def test_build_ignore_older_release_in_root(collection_input, monkeypatch):
    input_dir = collection_input[0]

    mock_display = MagicMock()
    monkeypatch.setattr(Display, 'vvv', mock_display)

    # This is expected to be ignored because it is in the root collection dir.
    release_file = os.path.join(input_dir, 'namespace-collection-0.0.0.tar.gz')

    # This is not expected to be ignored because it is not in the root collection dir.
    fake_release_file = os.path.join(input_dir, 'plugins',
                                     'namespace-collection-0.0.0.tar.gz')

    for filename in [release_file, fake_release_file]:
        with open(filename, 'w+') as file_obj:
            file_obj.write('random')
            file_obj.flush()

    actual = collection._build_files_manifest(to_bytes(input_dir), 'namespace',
                                              'collection', [])
    assert actual['format'] == 1

    plugin_release_found = False
    for manifest_entry in actual['files']:
        assert manifest_entry['name'] != 'namespace-collection-0.0.0.tar.gz'
        if manifest_entry[
                'name'] == 'plugins/namespace-collection-0.0.0.tar.gz':
            plugin_release_found = True

    assert plugin_release_found

    expected_msgs = [
        "Skipping '%s/galaxy.yml' for collection build" % to_text(input_dir),
        "Skipping '%s' for collection build" % to_text(release_file)
    ]
    assert mock_display.call_count == 2
    assert mock_display.mock_calls[0][1][0] in expected_msgs
    assert mock_display.mock_calls[1][1][0] in expected_msgs
示例#17
0
def test_build_requirement_from_name_second_server(galaxy_server, monkeypatch):
    json_str = artifact_versions_json('namespace', 'collection',
                                      ['1.0.1', '1.0.2', '1.0.3'],
                                      galaxy_server.api_server)
    mock_open = MagicMock()
    mock_open.side_effect = (urllib_error.HTTPError(
        'https://galaxy.server.com', 404, 'msg', {}, None), StringIO(json_str))

    monkeypatch.setattr(collection, 'open_url', mock_open)

    broken_server = copy.copy(galaxy_server)
    broken_server.api_server = 'https://broken.com/'
    actual = collection.CollectionRequirement.from_name(
        'namespace.collection', [broken_server, galaxy_server], '>1.0.1',
        False, True)

    assert actual.namespace == u'namespace'
    assert actual.name == u'collection'
    assert actual.b_path is None
    assert actual.api == galaxy_server
    assert actual.skip is False
    assert actual.versions == set([u'1.0.2', u'1.0.3'])
    assert actual.latest_version == u'1.0.3'
    assert actual.dependencies is None

    assert mock_open.call_count == 2
    assert mock_open.mock_calls[0][1][
        0] == u"https://broken.com/api/v2/collections/namespace/collection/versions/"
    assert mock_open.mock_calls[0][2] == {
        'validate_certs': True,
        "headers": {}
    }
    assert mock_open.mock_calls[1][1][0] == u"%s/api/v2/collections/namespace/collection/versions/" \
        % galaxy_server.api_server
    assert mock_open.mock_calls[1][2] == {
        'validate_certs': True,
        "headers": {}
    }
示例#18
0
    def test_module_utils_basic_ansible_module_set_group_if_different(self):
        from ansible.module_utils import basic
        basic._ANSIBLE_ARGS = None

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

        self.assertEqual(am.set_group_if_different('/path/to/file', None, True), True)
        self.assertEqual(am.set_group_if_different('/path/to/file', None, False), False)

        am.user_and_group = MagicMock(return_value=(500, 500))

        with patch('os.lchown', return_value=None) as m:
            self.assertEqual(am.set_group_if_different('/path/to/file', 0, False), True)
            m.assert_called_with(b'/path/to/file', -1, 0)

            def _mock_getgrnam(*args, **kwargs):
                mock_gr = MagicMock()
                mock_gr.gr_gid = 0
                return mock_gr

            m.reset_mock()
            with patch('grp.getgrnam', side_effect=_mock_getgrnam):
                self.assertEqual(am.set_group_if_different('/path/to/file', 'root', False), True)
                m.assert_called_with(b'/path/to/file', -1, 0)

            with patch('grp.getgrnam', side_effect=KeyError):
                self.assertRaises(SystemExit, am.set_group_if_different, '/path/to/file', 'root', False)

            m.reset_mock()
            am.check_mode = True
            self.assertEqual(am.set_group_if_different('/path/to/file', 0, False), True)
            self.assertEqual(m.called, False)
            am.check_mode = False

        with patch('os.lchown', side_effect=OSError) as m:
            self.assertRaises(SystemExit, am.set_group_if_different, '/path/to/file', 'root', False)
def test_build_requirement_from_name_single_version(galaxy_server,
                                                    monkeypatch):
    mock_get_info = MagicMock()
    mock_get_info.return_value = api.CollectionVersionMetadata(
        'namespace', 'collection', '2.0.0', None, None, {})
    monkeypatch.setattr(galaxy_server, 'get_collection_version_metadata',
                        mock_get_info)

    actual = collection.CollectionRequirement.from_name(
        'namespace.collection', [galaxy_server], '2.0.0', True, True)

    assert actual.namespace == u'namespace'
    assert actual.name == u'collection'
    assert actual.b_path is None
    assert actual.api == galaxy_server
    assert actual.skip is False
    assert actual.versions == set([u'2.0.0'])
    assert actual.latest_version == u'2.0.0'
    assert actual.dependencies == {}

    assert mock_get_info.call_count == 1
    assert mock_get_info.mock_calls[0][1] == ('namespace', 'collection',
                                              '2.0.0')
示例#20
0
    def test_task_executor_get_handler_normal(self):
        te = TaskExecutor(
            host=MagicMock(),
            task=MagicMock(),
            job_vars={},
            play_context=MagicMock(),
            new_stdin=None,
            loader=DictDataLoader({}),
            shared_loader_obj=MagicMock(),
            final_q=MagicMock(),
        )

        action_loader = te._shared_loader_obj.action_loader
        action_loader.has_plugin.return_value = False
        action_loader.get.return_value = mock.sentinel.handler
        action_loader.__contains__.return_value = False

        mock_connection = MagicMock()
        mock_templar = MagicMock()
        action = 'namespace.prefix_suffix'
        module_prefix = action.split('_')[0]
        te._task.action = action
        handler = te._get_action_handler(mock_connection, mock_templar)

        self.assertIs(mock.sentinel.handler, handler)

        action_loader.has_plugin.assert_has_calls([
            mock.call(action, collection_list=te._task.collections),
            mock.call(module_prefix, collection_list=te._task.collections)
        ])

        action_loader.get.assert_called_once_with(
            'assible.legacy.normal',
            task=te._task,
            connection=mock_connection,
            play_context=te._play_context,
            loader=te._loader,
            templar=mock_templar,
            shared_loader_obj=te._shared_loader_obj,
            collection_list=None)
示例#21
0
    def test_kinit_success_subprocess(self, monkeypatch, options, expected):
        def mock_communicate(input=None, timeout=None):
            return b"", b""

        mock_popen = MagicMock()
        mock_popen.return_value.communicate = mock_communicate
        mock_popen.return_value.returncode = 0
        monkeypatch.setattr("subprocess.Popen", mock_popen)

        winrm.HAS_PEXPECT = False
        pc = PlayContext()
        new_stdin = StringIO()
        conn = connection_loader.get('winrm', pc, new_stdin)
        conn.set_options(var_options=options)
        conn._build_winrm_kwargs()

        conn._kerb_auth("user@domain", "pass")
        mock_calls = mock_popen.mock_calls
        assert len(mock_calls) == 1
        assert mock_calls[0][1] == expected
        actual_env = mock_calls[0][2]['env']
        assert list(actual_env.keys()) == ['KRB5CCNAME']
        assert actual_env['KRB5CCNAME'].startswith("FILE:/")
 def test_run_import_server_config_profile_runtimeerror_case(
         self, idrac_connection_server_configure_profile_mock,
         idrac_default_args, idrac_file_manager_server_config_profile_mock):
     idrac_default_args.update({
         "share_name": "sharename",
         "share_user": "******",
         "share_password": "******",
         "command": "export",
         "job_wait": True,
         "scp_components": "IDRAC",
         "scp_file": "scp_file.xml",
         "end_host_power_state": "On",
         "shutdown_type": "Graceful"
     })
     message = {"Status": "Failed"}
     f_module = self.get_module_mock(params=idrac_default_args)
     obj = MagicMock()
     idrac_connection_server_configure_profile_mock.config_mgr = obj
     obj.scp_import = Mock(return_value=message)
     with pytest.raises(Exception) as ex:
         self.module.run_import_server_config_profile(
             idrac_connection_server_configure_profile_mock, f_module)
     assert "Failed to import scp." == str(ex.value)
示例#23
0
def test_world_writable_cache(cache_dir, monkeypatch):
    mock_warning = MagicMock()
    monkeypatch.setattr(Display, 'warning', mock_warning)

    cache_file = os.path.join(cache_dir, 'api.json')
    with open(cache_file, mode='w') as fd:
        fd.write('{"version": 2}')
        os.chmod(cache_file, 0o666)

    api = GalaxyAPI(None,
                    "test",
                    'https://galaxy.ansible.com/',
                    no_cache=False)
    assert api._cache is None

    with open(cache_file) as fd:
        actual_cache = fd.read()
    assert actual_cache == '{"version": 2}'
    assert stat.S_IMODE(os.stat(cache_file).st_mode) == 0o666

    assert mock_warning.call_count == 1
    assert mock_warning.call_args[0][0] == \
        'Galaxy cache has world writable access (%s), ignoring it as a cache source.' % cache_file
示例#24
0
def test_get_password_multiple_results(laps_password):
    mock_conn = MagicMock()
    mock_conn.search_s.return_value = [
        ("CN=server,OU=Workstations,DC=domain,DC=local", {
            "ms-Mcs-AdmPwd": ["pass"],
            "distinguishedName":
            ["CN=server,OU=Workstations,DC=domain,DC=local"]
        }),
        ("CN=server,OU=Servers,DC=domain,DC=local", {
            "ms-Mcs-AdmPwd": ["pass"],
            "distinguishedName": ["CN=server,OU=Servers,DC=domain,DC=local"]
        }),
        (None, [
            "ldap://ForestDnsZones.domain.com/DC=ForestDnsZones,DC=domain,DC=com"
        ]),
        (None, [
            "ldap://DomainDnsZones.domain.com/DC=DomainDnsZones,DC=domain,DC=com"
        ]),
        (None, ["ldap://domain.com/CN=Configuration,DC=domain,DC=com"]),
    ]

    with pytest.raises(AnsibleLookupError) as err:
        laps_password.get_laps_password(mock_conn, "server",
                                        "DC=domain,DC=local")
    assert str(err.value) == \
        "Found too many results for the server 'server' in the base 'DC=domain,DC=local'. Specify a more explicit " \
        "search base for the server required. Found servers 'CN=server,OU=Workstations,DC=domain,DC=local', " \
        "'CN=server,OU=Servers,DC=domain,DC=local'"

    assert len(mock_conn.method_calls) == 1
    assert mock_conn.method_calls[0][0] == "search_s"
    assert mock_conn.method_calls[0][1] == (
        "DC=domain,DC=local", FakeLdap.SCOPE_SUBTREE,
        "(&(objectClass=computer)(CN=server))")
    assert mock_conn.method_calls[0][2] == {
        "attrlist": ["distinguishedName", "ms-Mcs-AdmPwd"]
    }
    def setUpClass(cls):
        class MockException(Exception):
            pass

        cls.MockException = MockException

        m = MagicMock()
        nssrc_modules_mock = {
            'nssrc.com.citrix.netscaler.nitro.resource.config.gslb':
            m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice':
            m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice.gslbservice':
            m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice_lbmonitor_binding':
            m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice_lbmonitor_binding.gslbservice_lbmonitor_binding':
            m,

            # The following are needed because of monkey_patch_nitro_api()
            'nssrc.com.citrix.netscaler.nitro.resource.base':
            m,
            'nssrc.com.citrix.netscaler.nitro.resource.base.Json':
            m,
            'nssrc.com.citrix.netscaler.nitro.resource.base.Json.Json':
            m,
            'nssrc.com.citrix.netscaler.nitro.util':
            m,
            'nssrc.com.citrix.netscaler.nitro.util.nitro_util':
            m,
            'nssrc.com.citrix.netscaler.nitro.util.nitro_util.nitro_util':
            m,
        }

        cls.nitro_specific_patcher = patch.dict(sys.modules,
                                                nssrc_modules_mock)
        cls.nitro_base_patcher = nitro_base_patcher
 def test_delete_config(self):
     api_config = {
         'Id': 'test-id',
         'LambdaFunctionArn': 'test-arn',
         'Events': [],
         'Filter': {
             'Key': {
                 'FilterRules': [{
                     'Name': 'Prefix',
                     'Value': ''
                 }, {
                     'Name': 'Suffix',
                     'Value': ''
                 }]
             }
         }
     }
     client = MagicMock()
     client.get_bucket_notification_configuration.return_value = {
         'LambdaFunctionConfigurations': [api_config]
     }
     bucket = AmazonBucket(client, 'test-bucket')
     config = Config.from_params(
         **{
             'event_name': 'test-id',
             'lambda_function_arn': 'lambda_arn',
             'lambda_version': 1,
             'events': [],
             'prefix': '',
             'suffix': ''
         })
     bucket.delete_config(config)
     assert client.get_bucket_notification_configuration.call_count == 1
     assert client.put_bucket_notification_configuration.call_count == 1
     client.put_bucket_notification_configuration.assert_called_with(
         Bucket='test-bucket',
         NotificationConfiguration={'LambdaFunctionConfigurations': []})
示例#27
0
def test_install_collection_with_circular_dependency(collection_artifact,
                                                     monkeypatch):
    collection_path, collection_tar = collection_artifact
    temp_path = os.path.split(collection_tar)[0]
    shutil.rmtree(collection_path)

    mock_display = MagicMock()
    monkeypatch.setattr(Display, 'display', mock_display)

    collection.install_collections([(
        to_text(collection_tar),
        '*',
        None,
    )], to_text(temp_path), [u'https://galaxy.ansible.com'], True, False,
                                   False, False, False)

    assert os.path.isdir(collection_path)

    actual_files = os.listdir(collection_path)
    actual_files.sort()
    assert actual_files == [
        b'FILES.json', b'MANIFEST.json', b'README.md', b'docs', b'playbooks',
        b'plugins', b'roles'
    ]

    with open(os.path.join(collection_path, b'MANIFEST.json'),
              'rb') as manifest_obj:
        actual_manifest = json.loads(to_text(manifest_obj.read()))

    assert actual_manifest['collection_info'][
        'namespace'] == 'ansible_namespace'
    assert actual_manifest['collection_info']['name'] == 'collection'
    assert actual_manifest['collection_info']['version'] == '0.1.0'

    assert mock_display.call_count == 1
    assert mock_display.mock_calls[0][1][0] == "Installing 'ansible_namespace.collection:0.1.0' to '%s'" \
        % to_text(collection_path)
示例#28
0
def test_build_requirement_from_name_multiple_versions_one_match(
        galaxy_server, monkeypatch):
    json_str1 = artifact_versions_json('namespace', 'collection',
                                       ['2.0.0', '2.0.1', '2.0.2'],
                                       galaxy_server.api_server)
    json_str2 = artifact_json('namespace', 'collection', '2.0.1', {},
                              galaxy_server.api_server)
    mock_open = MagicMock()
    mock_open.side_effect = (StringIO(json_str1), StringIO(json_str2))

    monkeypatch.setattr(collection, 'open_url', mock_open)

    actual = collection.CollectionRequirement.from_name(
        'namespace.collection', [galaxy_server], '>=2.0.1,<2.0.2', True, True)

    assert actual.namespace == u'namespace'
    assert actual.name == u'collection'
    assert actual.b_path is None
    assert actual.api == galaxy_server
    assert actual.skip is False
    assert actual.versions == set([u'2.0.1'])
    assert actual.latest_version == u'2.0.1'
    assert actual.dependencies == {}

    assert mock_open.call_count == 2
    assert mock_open.mock_calls[0][1][0] == u"%s/api/v2/collections/namespace/collection/versions/" \
        % galaxy_server.api_server
    assert mock_open.mock_calls[0][2] == {
        'validate_certs': True,
        "headers": {}
    }
    assert mock_open.mock_calls[1][1][0] == u"%s/api/v2/collections/namespace/collection/versions/2.0.1/" \
        % galaxy_server.api_server
    assert mock_open.mock_calls[1][2] == {
        'validate_certs': True,
        "headers": {}
    }
示例#29
0
    def _setup(self):
        # This is not a very good mixin, lots of side effects
        self.fake_loader = DictDataLoader({'include_test.yml': "",
                                           'other_include_test.yml': ""})
        self.mock_tqm = MagicMock(name='MockTaskQueueManager')

        self.mock_play = MagicMock(name='MockPlay')
        self.mock_play._attributes = []
        self.mock_play.collections = None

        self.mock_iterator = MagicMock(name='MockIterator')
        self.mock_iterator._play = self.mock_play

        self.mock_inventory = MagicMock(name='MockInventory')
        self.mock_inventory._hosts_cache = dict()

        def _get_host(host_name):
            return None

        self.mock_inventory.get_host.side_effect = _get_host
        # TODO: can we use a real VariableManager?
        self.mock_variable_manager = MagicMock(name='MockVariableManager')
        self.mock_variable_manager.get_vars.return_value = dict()

        self.mock_block = MagicMock(name='MockBlock')

        # On macOS /etc is actually /private/etc, tests fail when performing literal /etc checks
        self.fake_role_loader = DictDataLoader({os.path.join(os.path.realpath("/etc"), "ansible/roles/bogus_role/tasks/main.yml"): """
                                                - shell: echo 'hello world'
                                                """})

        self._test_data_path = os.path.dirname(__file__)
        self.fake_include_loader = DictDataLoader({"/dev/null/includes/test_include.yml": """
                                                   - include: other_test_include.yml
                                                   - shell: echo 'hello world'
                                                   """,
                                                   "/dev/null/includes/static_test_include.yml": """
                                                   - include: other_test_include.yml
                                                   - shell: echo 'hello static world'
                                                   """,
                                                   "/dev/null/includes/other_test_include.yml": """
                                                   - debug:
                                                       msg: other_test_include_debug
                                                   """})
def test_build_requirement_from_name_multiple_version_results(
        galaxy_server, monkeypatch):
    mock_get_versions = MagicMock()
    mock_get_versions.return_value = [
        '2.0.0', '2.0.1', '2.0.2', '2.0.3', '2.0.4', '2.0.5'
    ]
    monkeypatch.setattr(galaxy_server, 'get_collection_versions',
                        mock_get_versions)

    actual = collection.CollectionRequirement.from_name(
        'namespace.collection', [galaxy_server], '!=2.0.2', True, True)

    assert actual.namespace == u'namespace'
    assert actual.name == u'collection'
    assert actual.b_path is None
    assert actual.api == galaxy_server
    assert actual.skip is False
    assert actual.versions == set(
        [u'2.0.0', u'2.0.1', u'2.0.3', u'2.0.4', u'2.0.5'])
    assert actual.latest_version == u'2.0.5'
    assert actual.dependencies == {}

    assert mock_get_versions.call_count == 1
    assert mock_get_versions.mock_calls[0][1] == ('namespace', 'collection')