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.ansible.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]
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
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_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
def test_action_base_run(self): mock_task = MagicMock() mock_task.action = "foo" mock_task.args = dict(a=1, b=2, c=3) mock_connection = MagicMock() play_context = PlayContext() mock_task.async_val = None action_base = DerivedActionBase(mock_task, mock_connection, play_context, None, None, None) results = action_base.run() self.assertEqual(results, dict()) mock_task.async_val = 0 action_base = DerivedActionBase(mock_task, mock_connection, play_context, None, None, None) results = action_base.run() self.assertEqual(results, {})
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
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
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'ansible_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 'ansible_namespace.collection:0.1.0' to '%s'" \ % to_text(collection_path) assert mock_display.mock_calls[1][1][ 0] == "ansible_namespace.collection (0.1.0) was installed successfully"
def test_get_collection_version_metadata_no_version(api_version, token_type, version, token_ins, monkeypatch): api = get_test_galaxy_api('https://galaxy.server.com/api/', api_version, token_ins=token_ins) if token_ins: mock_token_get = MagicMock() mock_token_get.return_value = 'my token' monkeypatch.setattr(token_ins, 'get', mock_token_get) mock_open = MagicMock() mock_open.side_effect = [ StringIO(to_text(json.dumps({ 'download_url': 'https://downloadme.com', 'artifact': { 'sha256': 'ac47b6fac117d7c171812750dacda655b04533cf56b31080b82d1c0db3c9d80f', }, 'namespace': { 'name': 'namespace', }, 'collection': { 'name': 'collection', }, 'version': version, 'metadata': { 'dependencies': {}, } }))), ] monkeypatch.setattr(galaxy_api, 'open_url', mock_open) actual = api.get_collection_version_metadata('namespace', 'collection', version) assert isinstance(actual, CollectionVersionMetadata) assert actual.namespace == u'namespace' assert actual.name == u'collection' assert actual.download_url == u'https://downloadme.com' assert actual.artifact_sha256 == u'ac47b6fac117d7c171812750dacda655b04533cf56b31080b82d1c0db3c9d80f' assert actual.version == version assert actual.dependencies == {} assert mock_open.call_count == 1 assert mock_open.mock_calls[0][1][0] == '%s%s/collections/namespace/collection/versions/%s' \ % (api.api_server, api_version, version) # v2 calls dont need auth, so no authz header or token_type if token_type: assert mock_open.mock_calls[0][2]['headers']['Authorization'] == '%s my token' % token_type
def test_build_requirement_from_name_missing(galaxy_server, monkeypatch): mock_open = MagicMock() mock_open.side_effect = urllib_error.HTTPError('https://galaxy.server.com', 404, 'msg', {}, None) monkeypatch.setattr(collection, 'open_url', mock_open) mock_avail_ver = MagicMock() mock_avail_ver.return_value = {'v2': '/api/v2'} monkeypatch.setattr(collection, 'get_available_api_versions', mock_avail_ver) expected = "Failed to find collection namespace.collection:*" with pytest.raises(AnsibleError, match=expected): collection.CollectionRequirement.from_name( 'namespace.collection', [galaxy_server, galaxy_server], '*', False, True)
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)
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
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_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_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)
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
def test_wait_import_task_timeout(api_version, token_type, monkeypatch): api = get_test_galaxy_api('https://galaxy.server.com', api_version) import_uri = 'https://galaxy.server.com/api/%s/task/1234' % api_version def return_response(*args, **kwargs): return StringIO(u'{"state":"waiting"}') mock_open = MagicMock() mock_open.side_effect = return_response monkeypatch.setattr(galaxy_api, 'open_url', mock_open) mock_display = MagicMock() monkeypatch.setattr(Display, 'display', mock_display) mock_vvv = MagicMock() monkeypatch.setattr(Display, 'vvv', mock_vvv) monkeypatch.setattr(time, 'sleep', MagicMock()) expected = "Timeout while waiting for the Galaxy import process to finish, check progress at '%s'" % import_uri with pytest.raises(AnsibleError, match=expected): api.wait_import_task(import_uri, 1) assert mock_open.call_count > 1 assert mock_open.mock_calls[0][1][0] == import_uri assert mock_open.mock_calls[0][2]['headers'][ 'Authorization'] == '%s my token' % token_type assert mock_open.mock_calls[1][1][0] == import_uri assert mock_open.mock_calls[1][2]['headers'][ 'Authorization'] == '%s my token' % token_type assert mock_display.call_count == 1 assert mock_display.mock_calls[0][1][ 0] == 'Waiting until Galaxy import task %s has completed' % import_uri expected_wait_msg = 'Galaxy import process has a status of waiting, wait {0} seconds before trying again' assert mock_vvv.call_count > 9 # 1st is opening Galaxy token file. assert mock_vvv.mock_calls[1][1][0] == expected_wait_msg.format(2) assert mock_vvv.mock_calls[2][1][0] == expected_wait_msg.format(3) assert mock_vvv.mock_calls[3][1][0] == expected_wait_msg.format(4) assert mock_vvv.mock_calls[4][1][0] == expected_wait_msg.format(6) assert mock_vvv.mock_calls[5][1][0] == expected_wait_msg.format(10) assert mock_vvv.mock_calls[6][1][0] == expected_wait_msg.format(15) assert mock_vvv.mock_calls[7][1][0] == expected_wait_msg.format(22) assert mock_vvv.mock_calls[8][1][0] == expected_wait_msg.format(30)
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 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_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)
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 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': []})
def test_create_non_existing_service(self): self.set_module_state('present') from ansible.modules.network.netscaler import netscaler_service service_proxy_mock = MagicMock() attrs = { 'diff_object.return_value': {}, } service_proxy_mock.configure_mock(**attrs) m = MagicMock(return_value=service_proxy_mock) service_exists_mock = Mock(side_effect=[False, True]) with patch.multiple( 'ansible.modules.network.netscaler.netscaler_service', ConfigProxy=m, service_exists=service_exists_mock, do_state_change=Mock(return_value=Mock(errorcode=0)), ): self.module = netscaler_service result = self.exited() service_proxy_mock.assert_has_calls([call.add()]) self.assertTrue(result['changed'], msg='Change not recorded')
def test_absent_operation_no_change(self): self.set_module_state('absent') from ansible.modules.network.netscaler import netscaler_servicegroup servicegroup_proxy_mock = MagicMock() attrs = { 'diff_object.return_value': {}, } servicegroup_proxy_mock.configure_mock(**attrs) m = MagicMock(return_value=servicegroup_proxy_mock) servicegroup_exists_mock = Mock(side_effect=[False, False]) with patch.multiple( 'ansible.modules.network.netscaler.netscaler_servicegroup', ConfigProxy=m, servicegroup_exists=servicegroup_exists_mock, ): self.module = netscaler_servicegroup result = self.exited() servicegroup_proxy_mock.assert_not_called() self.assertFalse(result['changed'], msg='Changed status not set correctly')
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_path_no_version(collection_artifact, monkeypatch): manifest_path = os.path.join(collection_artifact[0], b'MANIFEST.json') manifest_value = json.dumps({ 'collection_info': { 'namespace': 'namespace', 'name': 'name', 'version': '', 'dependencies': {} } }) with open(manifest_path, 'wb') as manifest_obj: manifest_obj.write(to_bytes(manifest_value)) mock_display = MagicMock() monkeypatch.setattr(Display, 'display', mock_display) actual = collection.CollectionRequirement.from_path( collection_artifact[0], True) # While the folder name suggests a different collection, we treat MANIFEST.json as the source of truth. assert actual.namespace == u'namespace' assert actual.name == u'name' assert actual.b_path == collection_artifact[0] assert actual.api is None assert actual.skip is True assert actual.versions == set(['*']) assert actual.latest_version == u'*' assert actual.dependencies == {} assert mock_display.call_count == 1 actual_warn = ' '.join(mock_display.mock_calls[0][1][0].split('\n')) expected_warn = "Collection at '%s' does not have a valid version set, falling back to '*'. Found version: ''" \ % to_text(collection_artifact[0]) assert expected_warn in actual_warn
def test_incorrect_password(self, monkeypatch): self.conn.set_option('host_key_checking', False) self.conn.set_option('reconnection_retries', 5) monkeypatch.setattr('time.sleep', lambda x: None) self.mock_popen_res.stdout.read.side_effect = [b''] self.mock_popen_res.stderr.read.side_effect = [b'Permission denied, please try again.\r\n'] type(self.mock_popen_res).returncode = PropertyMock(side_effect=[5] * 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)], [], ] self.mock_selector.get_map.side_effect = lambda: True self.conn._build_command = MagicMock() self.conn._build_command.return_value = [b'sshpass', b'-d41', b'ssh', b'-C'] exception_info = pytest.raises(AnsibleAuthenticationFailure, self.conn.exec_command, 'sshpass', 'some data') assert exception_info.value.message == ('Invalid/incorrect username/password. Skipping remaining 5 retries to prevent account lockout: ' 'Permission denied, please try again.') assert self.mock_popen.call_count == 1
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_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' ] # 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] ] assert len(display_msgs) == 4 # Msg1 is the warning about not MANIFEST.json, cannot really check message as it has line breaks which varies based # on the path size assert display_msgs[1] == "Process install dependency map" assert display_msgs[2] == "Starting collection install process" assert display_msgs[ 3] == "Skipping 'ansible_namespace.collection' as it is already installed"
def test_initialise_automation_hub(monkeypatch): mock_open = MagicMock() mock_open.side_effect = [ StringIO(u'{"available_versions":{"v2": "v2/", "v3":"v3/"}}'), ] monkeypatch.setattr(galaxy_api, 'open_url', mock_open) token = KeycloakToken(auth_url='https://api.test/') mock_token_get = MagicMock() mock_token_get.return_value = 'my_token' monkeypatch.setattr(token, 'get', mock_token_get) api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/", token=token) assert len(api.available_api_versions) == 2 assert api.available_api_versions['v2'] == u'v2/' assert api.available_api_versions['v3'] == u'v3/' assert mock_open.mock_calls[0][1][0] == 'https://galaxy.ansible.com/api/' assert mock_open.mock_calls[0][2]['headers'] == {'Authorization': 'Bearer my_token'}