Beispiel #1
0
 def test_ios_config_config(self):
     config = 'hostname localhost'
     lines = ['hostname router']
     set_module_args(dict(lines=lines, config=config))
     self.conn.get_diff = MagicMock(
         return_value=self.cliconf_obj.get_diff('\n'.join(lines), config))
     commands = ['hostname router']
     self.execute_module(changed=True, commands=commands)
Beispiel #2
0
    def test_invalid_fetch_conjur_variable(self, mocker):
        for code in [401, 403, 404]:
            mock_response = MagicMock(spec_set=http_client.HTTPResponse)
            try:
                mock_response.getcode.return_value = code
            except Exception:
                # HTTPResponse is a Python 3 only feature. This uses a generic mock for python 2.6
                mock_response = MagicMock()
                mock_response.getcode.return_value = code

            mocker.patch.object(conjur_variable,
                                'open_url',
                                return_value=mock_response)

            with pytest.raises(AnsibleError):
                response = conjur_variable._fetch_conjur_token(
                    'super-secret', 'token', 'http://conjur', 'account')
Beispiel #3
0
 def setUp(self):
     super(TestNiosNetworkViewModule, self).setUp()
     self.module = MagicMock(
         name=
         'ansible_collections.notmintest.not_a_real_collection.plugins.modules.nios_network_view.WapiModule'
     )
     self.module.check_mode = False
     self.module.params = {'provider': None}
     self.mock_wapi = patch(
         'ansible_collections.notmintest.not_a_real_collection.plugins.modules.nios_network_view.WapiModule'
     )
     self.exec_command = self.mock_wapi.start()
     self.mock_wapi_run = patch(
         'ansible_collections.notmintest.not_a_real_collection.plugins.modules.nios_network_view.WapiModule.run'
     )
     self.mock_wapi_run.start()
     self.load_config = self.mock_wapi_run.start()
Beispiel #4
0
def test_simple_auth_with_ldaps(monkeypatch):
    mock_ldap_option = MagicMock()
    monkeypatch.setattr(FakeLdap, "set_option", mock_ldap_option)

    mock_ldap = MagicMock()
    monkeypatch.setattr("ldap.initialize", mock_ldap)

    lookup_loader.get('laps_password').run([], domain="dc01", scheme="ldaps", auth="simple", username="******",
                                           password="******")

    assert mock_ldap_option.mock_calls[0][1] == (FakeLdap.OPT_X_TLS_REQUIRE_CERT, FakeLdap.OPT_X_TLS_DEMAND)

    assert mock_ldap.mock_calls[3][0] == '().bind_s'
    assert mock_ldap.mock_calls[3][1] == (u"user", u"pass")

    assert mock_ldap.mock_calls[4][0] == "().read_rootdse_s"
    assert mock_ldap.mock_calls[4][1] == ()
Beispiel #5
0
    def test_ios_config_replace_block(self):
        lines = ['description test string', 'test string']
        parents = ['interface GigabitEthernet0/0']
        set_module_args(dict(lines=lines, replace='block', parents=parents))

        module = MagicMock()
        module.params = {'lines': lines, 'parents': parents, 'src': None}
        candidate_config = ios_config.get_candidate_config(module)

        self.conn.get_diff = MagicMock(
            return_value=self.cliconf_obj.get_diff(candidate_config,
                                                   self.running_config,
                                                   diff_replace='block',
                                                   path=parents))

        commands = parents + lines
        self.execute_module(changed=True, commands=commands)
Beispiel #6
0
    def test_update_cs_policy_when_cs_policy_differs(self):
        self.set_module_state('present')
        from ansible_collections.notmintest.not_a_real_collection.plugins.modules import netscaler_cs_policy
        cs_policy_mock = MagicMock()
        attrs = {
            'diff_object.return_value': {},
        }
        cs_policy_mock.configure_mock(**attrs)

        m = MagicMock(return_value=cs_policy_mock)
        policy_exists_mock = Mock(side_effect=[True, True])
        policy_identical_mock = Mock(side_effect=[False, True])

        with patch.multiple(
                'ansible_collections.notmintest.not_a_real_collection.plugins.modules.netscaler_cs_policy',
                ConfigProxy=m,
                policy_exists=policy_exists_mock,
                policy_identical=policy_identical_mock,
                ensure_feature_is_enabled=Mock(),
                nitro_exception=self.MockException,
        ):
            self.module = netscaler_cs_policy
            result = self.exited()
            cs_policy_mock.assert_has_calls([call.update()])
            self.assertTrue(result['changed'], msg='Change not recorded')
    def test_update_servicegroup_when_servicegroup_differs(self):
        self.set_module_state('present')
        from ansible_collections.notmintest.not_a_real_collection.plugins.modules 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=[True, True])
        servicegroup_identical_mock = Mock(side_effect=[False, True])
        monitor_bindings_identical_mock = Mock(side_effect=[True, True])

        with patch.multiple(
            'ansible_collections.notmintest.not_a_real_collection.plugins.modules.netscaler_servicegroup',
            ConfigProxy=m,
            servicegroup_exists=servicegroup_exists_mock,
            servicegroup_identical=servicegroup_identical_mock,
            monitor_bindings_identical=monitor_bindings_identical_mock,
            servicemembers_identical=Mock(side_effect=[True, True]),
            do_state_change=Mock(return_value=Mock(errorcode=0)),
            nitro_exception=self.MockException,
        ):
            self.module = netscaler_servicegroup
            result = self.exited()
            servicegroup_proxy_mock.assert_has_calls([call.update()])
            self.assertTrue(result['changed'], msg='Change not recorded')
 def test_junos_ping_failure_stats(self):
     '''Test for asserting stats when ping fails'''
     set_module_args(dict(count=4, dest="10.10.10.20"))
     self.conn.get = MagicMock(return_value=load_fixture(
         'junos_ping_ping_10.10.10.20_count_4', content='str'))
     result = self.execute_module(failed=True)
     self.assertEqual(result['packet_loss'], '100%')
     self.assertEqual(result['packets_rx'], 0)
     self.assertEqual(result['packets_tx'], 4)
Beispiel #9
0
    def test_iosxr_config_match_exact(self):
        lines = [
            'ip address 1.2.3.4 255.255.255.0', 'description test string',
            'shutdown'
        ]
        parents = ['interface GigabitEthernet0/0']
        set_module_args(dict(lines=lines, parents=parents, match='exact'))
        commands = parents + lines
        module = MagicMock()
        module.params = {'lines': lines, 'parents': parents, 'src': None}
        candidate_config = iosxr_config.get_candidate(module)
        self.conn.get_diff = MagicMock(
            return_value=self.cliconf_obj.get_diff(candidate_config,
                                                   self.running_config,
                                                   diff_match='exact',
                                                   path=parents))

        self.execute_module(changed=True, commands=commands, sort=False)
Beispiel #10
0
def test_sasl_bind_ldap_error(monkeypatch):
    mock_ldap = MagicMock()
    mock_ldap.return_value.sasl_gssapi_bind_s.side_effect = FakeLDAPError("fake error")
    monkeypatch.setattr("ldap.initialize", mock_ldap)

    with pytest.raises(AnsibleLookupError) as err:
        lookup_loader.get('laps_password').run([], domain="dc01")

    assert str(err.value) == "Failed to do a sasl bind against LDAP host 'ldap://dc01:389': fake error"
Beispiel #11
0
def test_start_tls_ldap_error(monkeypatch):
    mock_ldap = MagicMock()
    mock_ldap.return_value.start_tls_s.side_effect = FakeLDAPError("fake error")
    monkeypatch.setattr("ldap.initialize", mock_ldap)

    with pytest.raises(AnsibleLookupError) as err:
        lookup_loader.get('laps_password').run([], domain="dc01", start_tls=True)

    assert str(err.value) == "Failed to send StartTLS to LDAP host 'ldap://dc01:389': fake error"
Beispiel #12
0
def test_uri_options(monkeypatch, kwargs, expected):
    mock_ldap = MagicMock()
    monkeypatch.setattr("ldap.initialize", mock_ldap)

    lookup_loader.get('laps_password').run([], **kwargs)

    assert mock_ldap.call_count == 1
    assert mock_ldap.call_args[0] == (expected,)
    assert mock_ldap.call_args[1] == {"bytes_mode": False}
Beispiel #13
0
    def test_valid_fetch_conjur_variable(self, mocker):
        mock_response = MagicMock(spec_set=http_client.HTTPResponse)
        try:
            mock_response.getcode.return_value = 200
        except Exception:
            # HTTPResponse is a Python 3 only feature. This uses a generic mock for python 2.6
            mock_response = MagicMock()
            mock_response.getcode.return_value = 200

        mock_response.read.return_value = 'foo-bar'
        mocker.patch.object(conjur_variable,
                            'open_url',
                            return_value=mock_response)

        response = conjur_variable._fetch_conjur_token('super-secret', 'token',
                                                       'http://conjur',
                                                       'account')
        assert response == 'foo-bar'
    def test_icx_config_match_exact(self):
        lines = [
            'speed-duplex 10-full', 'port-name test-interface-4', 'disable'
        ]
        parents = ['interface ethernet 1/1/4']
        set_module_args(dict(lines=lines, parents=parents, match='exact'))

        module = MagicMock()
        module.params = {'lines': lines, 'parents': parents, 'src': None}
        candidate_config = icx_config.get_candidate_config(module)
        self.conn.get_diff = MagicMock(
            return_value=self.cliconf_obj.get_diff(candidate_config,
                                                   self.running_config,
                                                   diff_match='exact',
                                                   path=parents))

        commands = parents + lines
        self.execute_module(changed=True, commands=commands, sort=False)
Beispiel #15
0
    def test_apply_config_add_event(self):
        api_config = {
            'Id': 'test-id',
            'LambdaFunctionArn': 'test-arn',
            'Events': ['s3:ObjectRemoved:*'],
            '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': 'test-arn',
                'lambda_version': 1,
                'events': ['s3:ObjectRemoved:*', 's3:ObjectCreated:*'],
                'prefix': '',
                'suffix': ''
            })
        bucket.apply_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': [{
                    'Id':
                    'test-id',
                    'LambdaFunctionArn':
                    'test-arn:1',
                    'Events': ['s3:ObjectCreated:*', 's3:ObjectRemoved:*'],
                    'Filter': {
                        'Key': {
                            'FilterRules': [{
                                'Name': 'Prefix',
                                'Value': ''
                            }, {
                                'Name': 'Suffix',
                                'Value': ''
                            }]
                        }
                    }
                }]
            })
 def test_voss_config_before_after_no_change(self):
     lines = ['prompt "VSP300"']
     set_module_args(
         dict(lines=lines,
              before=['test1', 'test2'],
              after=['test3', 'test4']))
     self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff(
         '\n'.join(lines), self.running_config))
     self.execute_module()
Beispiel #17
0
 def test_ios_config_src(self):
     src = load_fixture('ios_config_src.cfg')
     set_module_args(dict(src=src))
     self.conn.get_diff = MagicMock(
         return_value=self.cliconf_obj.get_diff(src, self.running_config))
     commands = [
         'hostname foo', 'interface GigabitEthernet0/0', 'no ip address'
     ]
     self.execute_module(changed=True, commands=commands)
Beispiel #18
0
 def test_current_config_empty(self):
     client = MagicMock()
     client.get_bucket_notification_configuration.return_value = {
         'LambdaFunctionConfigurations': []
     }
     bucket = AmazonBucket(client, 'test-bucket')
     current = bucket.current_config('test-id')
     assert current is None
     assert client.get_bucket_notification_configuration.call_count == 1
Beispiel #19
0
def test_sasl_bind_ldap_no_mechs_error(monkeypatch):
    mock_ldap = MagicMock()
    mock_ldap.return_value.sasl_gssapi_bind_s.side_effect = FakeLDAPAuthUnknownError("no mechs")
    monkeypatch.setattr("ldap.initialize", mock_ldap)

    with pytest.raises(AnsibleLookupError) as err:
        lookup_loader.get('laps_password').run([], domain="dc01")

    assert str(err.value) == "Failed to do a sasl bind against LDAP host 'ldap://dc01:389', the GSSAPI mech is " \
                             "not installed: no mechs"
def test_lookup_multiple_obj(dummy_credentials):
    avi_lookup = lookup_loader.get('avi')
    avi_mock = MagicMock()
    avi_mock.return_value.get.return_value.json.return_value = data[
        "mock_multiple_obj"]
    with patch.object(avi, 'ApiSession', avi_mock):
        retval = avi_lookup.run([], {},
                                avi_credentials=dummy_credentials,
                                obj_type="network")
        assert retval == data["mock_multiple_obj"]["results"]
    def setUp(self):
        super(TestJunosPingModule, self).setUp()

        self.mock_get_connection = patch(
            'ansible_collections.notmintest.not_a_real_collection.plugins.modules.junos_ping.get_connection'
        )
        self.get_connection = self.mock_get_connection.start()

        self.conn = self.get_connection()
        self.conn.get = MagicMock()
Beispiel #22
0
    def setUp(self):
        super(TestJunosScpModule, self).setUp()
        self.mock_get_device = patch('ansible_collections.notmintest.not_a_real_collection.plugins.modules.junos_scp.get_device')
        self.get_device = self.mock_get_device.start()

        self.mock_scp = patch('ansible_collections.notmintest.not_a_real_collection.plugins.modules.junos_scp.SCP')
        self.scp = self.mock_scp.start()

        self.scp_mock = MagicMock()
        self.scp().__enter__.return_value = self.scp_mock
Beispiel #23
0
def test_simple_bind_ldap_error(monkeypatch):
    mock_ldap = MagicMock()
    mock_ldap.return_value.bind_s.side_effect = FakeLDAPError("fake error")
    monkeypatch.setattr("ldap.initialize", mock_ldap)

    with pytest.raises(AnsibleLookupError) as err:
        lookup_loader.get('laps_password').run([], domain="dc01", auth="simple", username="******", password="******",
                                               allow_plaintext=True)

    assert str(err.value) == "Failed to simple bind against LDAP host 'ldap://dc01:389': fake error"
    def test_cli_config_backup_returns__backup__(self, run_mock):
        self.conn.get_capabilities = MagicMock(return_value='{}')

        args = dict(backup=True)
        set_module_args(args)

        run_mock.return_value = {}

        result = self.execute_module()
        self.assertIn('__backup__', result)
def test_manage_state_removes_unwanted_permissions():
    lambda_client_double = MagicMock()
    # Policy actually: present  Requested State: not present  Should: remove
    lambda_client_double.get_policy.return_value = fake_policy_return
    fake_module_params = copy.deepcopy(fake_module_params_absent)
    module_double.params = fake_module_params
    lambda_policy.manage_state(module_double, lambda_client_double)
    assert lambda_client_double.get_policy.call_count > 0
    lambda_client_double.add_permission.assert_not_called()
    assert lambda_client_double.remove_permission.call_count > 0
def test_manage_state_updates_nonmatching_permissions():
    lambda_client_double = MagicMock()
    # Policy actually: present   Requested State: present  Should: do nothing
    lambda_client_double.get_policy.return_value = fake_policy_return
    fake_module_params = copy.deepcopy(fake_module_params_different)
    module_double.params = fake_module_params
    lambda_policy.manage_state(module_double, lambda_client_double)
    assert lambda_client_double.get_policy.call_count > 0
    assert lambda_client_double.add_permission.call_count > 0
    assert lambda_client_double.remove_permission.call_count > 0
 def test_voss_config_src(self):
     src = load_fixture('voss_config_src.cfg')
     set_module_args(dict(src=src))
     self.conn.get_diff = MagicMock(
         return_value=self.cliconf_obj.get_diff(src, self.running_config))
     commands = [
         'prompt "VSP8K"', 'interface GigabitEthernet 1/1', 'name "UNUSED"',
         'exit'
     ]
     self.execute_module(changed=True, commands=commands)
 def test_voss_config_src_ipv6(self):
     src = load_fixture('voss_config_ipv6.cfg')
     set_module_args(dict(src=src))
     self.conn.get_diff = MagicMock(
         return_value=self.cliconf_obj.get_diff(src, self.running_config))
     commands = [
         'interface loopback 1', 'ip address 1 2.2.2.2/255.255.255.255',
         'ipv6 interface address 2011:0:0:0:0:0:0:2/128', 'exit'
     ]
     self.execute_module(changed=True, commands=commands)
def test_manage_state_leaves_already_removed_permissions():
    lambda_client_double = MagicMock()
    # Policy actually: absent   Requested State: absent  Should: do nothing
    lambda_client_double.get_policy.side_effect = ClientError(
        error_response, operation_name)
    fake_module_params = copy.deepcopy(fake_module_params_absent)
    module_double.params = fake_module_params
    lambda_policy.manage_state(module_double, lambda_client_double)
    assert lambda_client_double.get_policy.call_count > 0
    lambda_client_double.add_permission.assert_not_called()
    lambda_client_double.remove_permission.assert_not_called()
Beispiel #30
0
    def test_eos_config_lines(self):
        lines = ['hostname switch01', 'ip domain-name eng.ansible.com']
        args = dict(lines=lines)
        set_module_args(args)
        self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff(
            '\n'.join(lines), self.running_config))
        result = self.execute_module(changed=True)
        config = ['hostname switch01']

        self.assertEqual(sorted(config), sorted(result['commands']),
                         result['commands'])