def test_policy_table(self):
        """Test change policy of a chain"""
        set_module_args({
            'policy': 'ACCEPT',
            'chain': 'INPUT',
        })
        commands_results = [(0, 'Chain INPUT (policy DROP)\n', ''),
                            (0, '', '')]

        with patch.object(basic.AnsibleModule, 'run_command') as run_command:
            run_command.side_effect = commands_results
            with self.assertRaises(AnsibleExitJson) as result:
                iptables.main()
                self.assertTrue(result.exception.args[0]['changed'])

        self.assertEqual(run_command.call_count, 2)
        self.assertEqual(run_command.call_args_list[0][0][0], [
            '/sbin/iptables',
            '-t',
            'filter',
            '-L',
            'INPUT',
        ])
        self.assertEqual(run_command.call_args_list[1][0][0], [
            '/sbin/iptables',
            '-t',
            'filter',
            '-P',
            'INPUT',
            'ACCEPT',
        ])
    def test_insert_rule_with_wait(self):
        """Test flush without parameters"""
        set_module_args({
            'chain': 'OUTPUT',
            'source': '1.2.3.4/32',
            'destination': '7.8.9.10/42',
            'jump': 'ACCEPT',
            'action': 'insert',
            'wait': '10'
        })

        commands_results = [
            (0, '', ''),
        ]

        with patch.object(basic.AnsibleModule, 'run_command') as run_command:
            run_command.side_effect = commands_results
            with self.assertRaises(AnsibleExitJson) as result:
                iptables.main()
                self.assertTrue(result.exception.args[0]['changed'])

        self.assertEqual(run_command.call_count, 1)
        self.assertEqual(run_command.call_args_list[0][0][0], [
            '/sbin/iptables', '-t', 'filter', '-C', 'OUTPUT', '-w', '10', '-s',
            '1.2.3.4/32', '-d', '7.8.9.10/42', '-j', 'ACCEPT'
        ])
Beispiel #3
0
    def test_selinux_default_context(self):
        # selinux unavailable
        with patch.object(basic, 'HAVE_SELINUX', False):
            assert no_args_module().selinux_default_context(
                path='/foo/bar') == [None, None, None]

        am = no_args_module(selinux_enabled=True, selinux_mls_enabled=True)
        # matchpathcon success
        with patch('ansible.module_utils.compat.selinux.matchpathcon',
                   return_value=[0, 'unconfined_u:object_r:default_t:s0']):
            assert am.selinux_default_context(path='/foo/bar') == [
                'unconfined_u', 'object_r', 'default_t', 's0'
            ]

        # matchpathcon fail (return initial context value)
        with patch('ansible.module_utils.compat.selinux.matchpathcon',
                   return_value=[-1, '']):
            assert am.selinux_default_context(path='/foo/bar') == [
                None, None, None, None
            ]

        # matchpathcon OSError
        with patch('ansible.module_utils.compat.selinux.matchpathcon',
                   side_effect=OSError):
            assert am.selinux_default_context(path='/foo/bar') == [
                None, None, None, None
            ]
    def test_append_rule(self):
        """Test append a redirection rule"""
        set_module_args({
            'chain': 'PREROUTING',
            'source': '1.2.3.4/32',
            'destination': '7.8.9.10/42',
            'jump': 'REDIRECT',
            'table': 'nat',
            'to_destination': '5.5.5.5/32',
            'protocol': 'udp',
            'destination_port': '22',
            'to_ports': '8600'
        })

        commands_results = [(1, '', ''), (0, '', '')]

        with patch.object(basic.AnsibleModule, 'run_command') as run_command:
            run_command.side_effect = commands_results
            with self.assertRaises(AnsibleExitJson) as result:
                iptables.main()
                self.assertTrue(result.exception.args[0]['changed'])

        self.assertEqual(run_command.call_count, 2)
        self.assertEqual(run_command.call_args_list[0][0][0], [
            '/sbin/iptables', '-t', 'nat', '-C', 'PREROUTING', '-p', 'udp',
            '-s', '1.2.3.4/32', '-d', '7.8.9.10/42', '-j', 'REDIRECT',
            '--to-destination', '5.5.5.5/32', '--destination-port', '22',
            '--to-ports', '8600'
        ])
        self.assertEqual(run_command.call_args_list[1][0][0], [
            '/sbin/iptables', '-t', 'nat', '-A', 'PREROUTING', '-p', 'udp',
            '-s', '1.2.3.4/32', '-d', '7.8.9.10/42', '-j', 'REDIRECT',
            '--to-destination', '5.5.5.5/32', '--destination-port', '22',
            '--to-ports', '8600'
        ])
    def test_jump_tee_gateway(self):
        """ Using gateway when JUMP is set to TEE """
        set_module_args({
            'table': 'mangle',
            'chain': 'PREROUTING',
            'in_interface': 'eth0',
            'protocol': 'udp',
            'match': 'state',
            'jump': 'TEE',
            'ctstate': ['NEW'],
            'destination_port': '9521',
            'gateway': '192.168.10.1',
            'destination': '127.0.0.1'
        })
        commands_results = [
            (0, '', ''),
        ]

        with patch.object(basic.AnsibleModule, 'run_command') as run_command:
            run_command.side_effect = commands_results
            with self.assertRaises(AnsibleExitJson) as result:
                iptables.main()
                self.assertTrue(result.exception.args[0]['changed'])

        self.assertEqual(run_command.call_count, 1)
        self.assertEqual(run_command.call_args_list[0][0][0], [
            '/sbin/iptables', '-t', 'mangle', '-C', 'PREROUTING', '-p', 'udp',
            '-d', '127.0.0.1', '-m', 'state', '-j', 'TEE', '--gateway',
            '192.168.10.1', '-i', 'eth0', '--destination-port', '9521',
            '--state', 'NEW'
        ])
    def test_ensure_backupPlanName_outputs_correctly(self):
        """
        Testing that command is executed with correct args
        :return:
        """
        set_module_args({
            'operation': "Provision",
            'opsName': 'Provision_test',
            'WS': "PLMN-PLMN/MRBTS-746",
            'createBackupPlan': "Yes",
            'backupPlanName': "backupPlanName"
        })

        with patch.object(basic.AnsibleModule, 'run_command') as mock_run_command:
            stdout = 'configuration updated'
            stderr = ''
            return_code = 0
            mock_run_command.return_value = return_code, stdout, stderr  # successful execution

            with self.assertRaises(AnsibleExitJson) as result:
                netact_cm_command.main()
            print(result.exception.args)
            self.assertTrue(result.exception.args[0]['changed'])  # ensure result is changed

        mock_run_command.assert_called_once_with(
            ['/opt/oss/bin/racclimx.sh', '-op', 'Provision', '-opsName', 'Provision_test',
             '-WS', 'PLMN-PLMN/MRBTS-746', '-createBackupPlan', 'true', '-backupPlanName', 'backupPlanName'],
            check_rc=True)
    def test_policy_table_no_change(self):
        """Test don't change policy of a chain if the policy is right"""
        set_module_args({
            'policy': 'ACCEPT',
            'chain': 'INPUT',
        })
        commands_results = [(0, 'Chain INPUT (policy ACCEPT)\n', ''),
                            (0, '', '')]

        with patch.object(basic.AnsibleModule, 'run_command') as run_command:
            run_command.side_effect = commands_results
            with self.assertRaises(AnsibleExitJson) as result:
                iptables.main()
                self.assertFalse(result.exception.args[0]['changed'])

        self.assertEqual(run_command.call_count, 1)
        # import pdb
        # pdb.set_trace()
        self.assertEqual(run_command.call_args_list[0][0][0], [
            '/sbin/iptables',
            '-t',
            'filter',
            '-L',
            'INPUT',
        ])
 def test_create_flexcache_multiplier(self):
     ''' create flexcache with aggregate multiplier'''
     args = {
         'volume': 'volume',
         'size': '90',  # 80MB minimum
         'size_unit': 'mb',  # 80MB minimum
         'vserver': 'ansibleSVM',
         'aggr_list': 'aggr1',
         'origin_volume': 'fc_vol_origin',
         'origin_vserver': 'ansibleSVM',
         'aggr_list_multiplier': '2',
     }
     self.delete_flexcache(args['vserver'], args['volume'])
     args.update(self.args)
     set_module_args(args)
     my_obj = my_module()
     if not self.onbox:
         my_obj.server = MockONTAPConnection()
     with patch.object(my_module,
                       'flexcache_create',
                       wraps=my_obj.flexcache_create) as mock_create:
         with pytest.raises(AnsibleExitJson) as exc:
             my_obj.apply()
         print('Create: ' + repr(exc.value))
         assert exc.value.args[0]['changed']
         mock_create.assert_called_with()
 def test_delete_flexcache_exists_junctionpath_no_force(self):
     ''' delete flexcache '''
     args = {
         'volume': 'volume',
         'vserver': 'ansibleSVM',
         'junction_path': 'jpath',
         'state': 'absent',
         'force_offline': 'true'
     }
     self.create_flexcache(args['vserver'], args['volume'],
                           args['junction_path'])
     args.update(self.args)
     set_module_args(args)
     my_obj = my_module()
     error = '160:Volume volume on Vserver ansibleSVM must be unmounted before being taken offline or restricted.'
     if not self.onbox:
         my_obj.server = MockONTAPConnection('vserver',
                                             'flex',
                                             api_error=error)
     with patch.object(my_module,
                       'flexcache_delete',
                       wraps=my_obj.flexcache_delete) as mock_delete:
         with pytest.raises(AnsibleFailJson) as exc:
             my_obj.apply()
         print('Delete: ' + repr(exc.value))
         msg = 'Error deleting FlexCache : NetApp API failed. Reason - %s' % error
         assert exc.value.args[0]['msg'] == msg
         mock_delete.assert_called_with()
    def test_withwrongargs(self):
        """
        Testing that wrong attribute causing error
        :return:
        """
        set_module_args({
            'operation': "Upload",
            'opsName': 'Uploading_testi',
            'MR': "PLMN-PLMN/MRBTS-746",
            'abc': 'abc'
        })

        with self.assertRaises(AnsibleFailJson):
            with patch.object(basic.AnsibleModule,
                              'run_command') as mock_run_command:
                stdout = 'configuration updated'
                stderr = ''
                return_code = 0
                mock_run_command.return_value = return_code, stdout, stderr  # successful execution

                with self.assertRaises(AnsibleExitJson) as result:
                    netact_cm_command.main()
                self.assertTrue(result.exception.args[0]
                                ['changed'])  # ensure result is changed

            self.assertFalse(True)  # ensure result is changed
Beispiel #11
0
    def test_content_written(self):

        with patch.object(builtins, 'open', mock_open()) as m:
            password._write_password_file(b'/this/is/a/test/caf\xc3\xa9', u'Testing Café')

            m.assert_called_once_with(b'/this/is/a/test/caf\xc3\xa9', 'wb')
            m().write.assert_called_once_with(u'Testing Café\n'.encode('utf-8'))
Beispiel #12
0
    def test_destination_ports(self):
        """ Test multiport module usage with multiple ports """
        set_module_args({
            'chain': 'INPUT',
            'protocol': 'tcp',
            'in_interface': 'eth0',
            'source': '192.168.0.1/32',
            'destination_ports': ['80', '443', '8081:8085'],
            'jump': 'ACCEPT',
            'comment': 'this is a comment',
        })
        commands_results = [
            (0, '', ''),
        ]

        with patch.object(basic.AnsibleModule, 'run_command') as run_command:
            run_command.side_effect = commands_results
            with self.assertRaises(AnsibleExitJson) as result:
                iptables.main()
                self.assertTrue(result.exception.args[0]['changed'])

        self.assertEqual(run_command.call_count, 1)
        self.assertEqual(run_command.call_args_list[0][0][0], [
            '/sbin/iptables', '-t', 'filter', '-C', 'INPUT', '-p', 'tcp', '-s',
            '192.168.0.1/32', '-j', 'ACCEPT', '-m', 'multiport', '--dports',
            '80,443,8081:8085', '-i', 'eth0', '-m', 'comment', '--comment',
            'this is a comment'
        ])
Beispiel #13
0
    def test_comment_position_at_end(self):
        """Test flush without parameters"""
        set_module_args({
            'chain': 'INPUT',
            'jump': 'ACCEPT',
            'action': 'insert',
            'ctstate': ['NEW'],
            'comment': 'this is a comment',
            '_ansible_check_mode': True,
        })

        commands_results = [
            (0, '', ''),
        ]

        with patch.object(basic.AnsibleModule, 'run_command') as run_command:
            run_command.side_effect = commands_results
            with self.assertRaises(AnsibleExitJson) as result:
                iptables.main()
                self.assertTrue(result.exception.args[0]['changed'])

        self.assertEqual(run_command.call_count, 1)
        self.assertEqual(run_command.call_args_list[0][0][0], [
            '/sbin/iptables', '-t', 'filter', '-C', 'INPUT', '-j', 'ACCEPT',
            '-m', 'conntrack', '--ctstate', 'NEW', '-m', 'comment',
            '--comment', 'this is a comment'
        ])
        self.assertEqual(run_command.call_args[0][0][14], 'this is a comment')
Beispiel #14
0
    def setUp(self):
        super(TestOnyxOspfModule, self).setUp()
        self._ospf_exists = True
        self.mock_get_config = patch.object(
            onyx_ospf.OnyxOspfModule,
            "_get_ospf_config")
        self.get_config = self.mock_get_config.start()

        self.mock_get_interfaces_config = patch.object(
            onyx_ospf.OnyxOspfModule,
            "_get_ospf_interfaces_config")
        self.get_interfaces_config = self.mock_get_interfaces_config.start()

        self.mock_load_config = patch(
            'ansible.module_utils.network.onyx.onyx.load_config')
        self.load_config = self.mock_load_config.start()
Beispiel #15
0
def test_update_lambda_if_added_environment_variable():

    set_module_args(module_args_with_environment)
    (boto3_conn_double,
     lambda_client_double) = make_mock_connection(base_lambda_config)

    with patch.object(lda, 'boto3_conn', boto3_conn_double):
        try:
            lda.main()
        except SystemExit:
            pass

    # guard against calling other than for a lambda connection (e.g. IAM)
    assert (len(boto3_conn_double.mock_calls) >
            0), "boto connections never used"
    assert (len(boto3_conn_double.mock_calls) <
            2), "multiple boto connections used unexpectedly"
    assert(len(lambda_client_double.update_function_configuration.mock_calls) > 0), \
        "failed to update lambda function when configuration changed"
    assert(len(lambda_client_double.update_function_configuration.mock_calls) < 2), \
        "lambda function update called multiple times when only one time should be needed"
    assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \
        "updated lambda code when no change should have happened"

    (update_args, update_kwargs
     ) = lambda_client_double.update_function_configuration.call_args
    assert (
        len(update_kwargs) > 0
    ), "expected update configuration called with keyword args, none found"
    assert update_kwargs['Environment'][
        'Variables'] == module_args_with_environment['environment_variables']
 def test_delete_flexcache_exists_junctionpath_with_force(self):
     ''' delete flexcache '''
     args = {
         'volume': 'volume',
         'vserver': 'ansibleSVM',
         'junction_path': 'jpath',
         'state': 'absent',
         'force_offline': 'true',
         'force_unmount': 'true'
     }
     self.create_flexcache(args['vserver'], args['volume'],
                           args['junction_path'])
     args.update(self.args)
     set_module_args(args)
     my_obj = my_module()
     if not self.onbox:
         my_obj.server = MockONTAPConnection('vserver', 'flex')
     with patch.object(my_module,
                       'flexcache_delete',
                       wraps=my_obj.flexcache_delete) as mock_delete:
         with pytest.raises(AnsibleExitJson) as exc:
             my_obj.apply()
         print('Delete: ' + repr(exc.value))
         assert exc.value.args[0]['changed']
         mock_delete.assert_called_with()
Beispiel #17
0
    def test_action_base_sudo_only_if_user_differs(self):
        fake_loader = MagicMock()
        fake_loader.get_basedir.return_value = os.getcwd()
        play_context = PlayContext()

        action_base = DerivedActionBase(None, None, play_context, fake_loader,
                                        None, None)
        action_base.get_become_option = MagicMock(return_value='root')
        action_base._get_remote_user = MagicMock(return_value='root')

        action_base._connection = MagicMock(exec_command=MagicMock(
            return_value=(0, '', '')))

        action_base._connection._shell = shell = MagicMock(
            append_command=MagicMock(return_value=('JOINED CMD')))

        action_base._connection.become = become = MagicMock()
        become.build_become_command.return_value = 'foo'

        action_base._low_level_execute_command('ECHO', sudoable=True)
        become.build_become_command.assert_not_called()

        action_base._get_remote_user.return_value = 'apo'
        action_base._low_level_execute_command('ECHO',
                                               sudoable=True,
                                               executable='/bin/csh')
        become.build_become_command.assert_called_once_with("ECHO", shell)

        become.build_become_command.reset_mock()

        with patch.object(C, 'BECOME_ALLOW_SAME_USER', new=True):
            action_base._get_remote_user.return_value = 'root'
            action_base._low_level_execute_command('ECHO SAME', sudoable=True)
            become.build_become_command.assert_called_once_with(
                "ECHO SAME", shell)
 def test_create_flexcache_size_error(self):
     ''' create flexcache '''
     args = {
         'volume': 'volume_err',
         'size': '50',  # 80MB minimum
         'size_unit': 'mb',  # 80MB minimum
         'vserver': 'ansibleSVM',
         'aggr_list': 'aggr1',
         'origin_volume': 'fc_vol_origin',
         'origin_vserver': 'ansibleSVM',
     }
     args.update(self.args)
     set_module_args(args)
     my_obj = my_module()
     error = 'Size "50MB" ("52428800B") is too small.  Minimum size is "80MB" ("83886080B"). '
     if not self.onbox:
         my_obj.server = MockONTAPConnection(job_error=error)
     with patch.object(my_module,
                       'flexcache_create',
                       wraps=my_obj.flexcache_create) as mock_create:
         with pytest.raises(AnsibleFailJson) as exc:
             my_obj.apply()
         print('Create: ' + repr(exc.value))
         msg = 'Error when creating flexcache: %s' % error
         assert exc.value.args[0]['msg'] == msg
         mock_create.assert_called_with()
    def test_ensure_command_called(self):
        """
        Testing that command is executed with correct args
        :return:
        """
        set_module_args({
            'operation': "Upload",
            'opsName': 'Uploading_testi',
            'DN': "PLMN-PLMN/MRBTS-746",
        })

        with patch.object(basic.AnsibleModule, 'run_command') as mock_run_command:
            stdout = 'configuration updated'
            stderr = ''
            return_code = 0
            mock_run_command.return_value = return_code, stdout, stderr  # successful execution

            with self.assertRaises(AnsibleExitJson) as result:
                netact_cm_command.main()
            print(result.exception.args)
            self.assertTrue(result.exception.args[0]['changed'])  # ensure result is changed

        mock_run_command.assert_called_once_with(
            ['/opt/oss/bin/racclimx.sh', '-op', 'Upload', '-opsName', 'Uploading_testi',
             '-DN', 'PLMN-PLMN/MRBTS-746'],
            check_rc=True)
 def test_create_flexcache_time_out(self, mock_sleep):
     ''' create flexcache '''
     args = {
         'volume': 'volume_err',
         'size': '50',  # 80MB minimum
         'size_unit': 'mb',  # 80MB minimum
         'vserver': 'ansibleSVM',
         'aggr_list': 'aggr1',
         'origin_volume': 'fc_vol_origin',
         'origin_vserver': 'ansibleSVM',
         'time_out': '2'
     }
     args.update(self.args)
     set_module_args(args)
     my_obj = my_module()
     if not self.onbox:
         my_obj.server = MockONTAPConnection(job_error='time_out')
     with patch.object(my_module,
                       'flexcache_create',
                       wraps=my_obj.flexcache_create) as mock_create:
         with pytest.raises(AnsibleFailJson) as exc:
             my_obj.apply()
         print('Create: ' + repr(exc.value))
         msg = 'Error when creating flexcache: job completion exceeded expected timer of: %s seconds' \
             % args['time_out']
         assert exc.value.args[0]['msg'] == msg
         mock_create.assert_called_with()
    def test_policy_table_changed_false(self):
        """Test flush without parameters and change == false"""
        set_module_args({
            'policy': 'ACCEPT',
            'chain': 'INPUT',
            '_ansible_check_mode': True,
        })
        commands_results = [
            (0, 'Chain INPUT (policy DROP)\n', ''),
        ]

        with patch.object(basic.AnsibleModule, 'run_command') as run_command:
            run_command.side_effect = commands_results
            with self.assertRaises(AnsibleExitJson) as result:
                iptables.main()
                self.assertTrue(result.exception.args[0]['changed'])

        self.assertEqual(run_command.call_count, 1)
        # import pdb
        # pdb.set_trace()
        self.assertEqual(run_command.call_args_list[0][0][0], [
            '/sbin/iptables',
            '-t',
            'filter',
            '-L',
            'INPUT',
        ])
def test_finder_setup():
    # ensure scalar path is listified
    f = _AssibleCollectionFinder(paths='/bogus/bogus')
    assert isinstance(f._n_collection_paths, list)

    # ensure sys.path paths that have an assible_collections dir are added to the end of the collections paths
    with patch.object(sys, 'path', [
            '/bogus', default_test_collection_paths[1], '/morebogus',
            default_test_collection_paths[0]
    ]):
        f = _AssibleCollectionFinder(paths=['/explicit', '/other'])
        assert f._n_collection_paths == [
            '/explicit', '/other', default_test_collection_paths[1],
            default_test_collection_paths[0]
        ]

    configured_paths = ['/bogus']
    playbook_paths = ['/playbookdir']
    f = _AssibleCollectionFinder(paths=configured_paths)
    assert f._n_collection_paths == configured_paths
    f.set_playbook_paths(playbook_paths)
    assert f._n_collection_paths == extend_paths(
        playbook_paths, 'collections') + configured_paths

    # ensure scalar playbook_paths gets listified
    f.set_playbook_paths(playbook_paths[0])
    assert f._n_collection_paths == extend_paths(
        playbook_paths, 'collections') + configured_paths
    def test_insert_jump_reject_with_reject(self):
        """ Using reject_with with a previously defined jump: REJECT results in two Jump statements #18988 """
        set_module_args({
            'chain': 'INPUT',
            'protocol': 'tcp',
            'jump': 'REJECT',
            'reject_with': 'tcp-reset',
            'ip_version': 'ipv4',
        })
        commands_results = [
            (0, '', ''),
        ]

        with patch.object(basic.AnsibleModule, 'run_command') as run_command:
            run_command.side_effect = commands_results
            with self.assertRaises(AnsibleExitJson) as result:
                iptables.main()
                self.assertTrue(result.exception.args[0]['changed'])

        self.assertEqual(run_command.call_count, 1)
        self.assertEqual(run_command.call_args_list[0][0][0], [
            '/sbin/iptables',
            '-t',
            'filter',
            '-C',
            'INPUT',
            '-p',
            'tcp',
            '-j',
            'REJECT',
            '--reject-with',
            'tcp-reset',
        ])
Beispiel #24
0
    def test_selinux_context(self):
        # selinux unavailable
        with patch.object(basic, 'HAVE_SELINUX', False):
            assert no_args_module().selinux_context(path='/foo/bar') == [
                None, None, None
            ]

        am = no_args_module(selinux_enabled=True, selinux_mls_enabled=True)
        # lgetfilecon_raw passthru
        with patch('ansible.module_utils.compat.selinux.lgetfilecon_raw',
                   return_value=[0, 'unconfined_u:object_r:default_t:s0']):
            assert am.selinux_context(path='/foo/bar') == [
                'unconfined_u', 'object_r', 'default_t', 's0'
            ]

        # lgetfilecon_raw returned a failure
        with patch('ansible.module_utils.compat.selinux.lgetfilecon_raw',
                   return_value=[-1, '']):
            assert am.selinux_context(path='/foo/bar') == [
                None, None, None, None
            ]

        # lgetfilecon_raw OSError (should bomb the module)
        with patch('ansible.module_utils.compat.selinux.lgetfilecon_raw',
                   side_effect=OSError(errno.ENOENT, 'NotFound')):
            with pytest.raises(SystemExit):
                am.selinux_context(path='/foo/bar')

        with patch('ansible.module_utils.compat.selinux.lgetfilecon_raw',
                   side_effect=OSError()):
            with pytest.raises(SystemExit):
                am.selinux_context(path='/foo/bar')
    def test_log_level(self):
        """ Test various ways of log level flag """

        log_levels = [
            '0', '1', '2', '3', '4', '5', '6', '7', 'emerg', 'alert', 'crit',
            'error', 'warning', 'notice', 'info', 'debug'
        ]

        for log_lvl in log_levels:
            set_module_args({
                'chain': 'INPUT',
                'jump': 'LOG',
                'log_level': log_lvl,
                'source': '1.2.3.4/32',
                'log_prefix': '** DROP-this_ip **'
            })
            commands_results = [
                (0, '', ''),
            ]

            with patch.object(basic.AnsibleModule,
                              'run_command') as run_command:
                run_command.side_effect = commands_results
                with self.assertRaises(AnsibleExitJson) as result:
                    iptables.main()
                    self.assertTrue(result.exception.args[0]['changed'])

                self.assertEqual(run_command.call_count, 1)
                self.assertEqual(run_command.call_args_list[0][0][0], [
                    '/sbin/iptables', '-t', 'filter', '-C', 'INPUT', '-s',
                    '1.2.3.4/32', '-j', 'LOG', '--log-prefix',
                    '** DROP-this_ip **', '--log-level', log_lvl
                ])
Beispiel #26
0
def test_update_lambda_if_code_changed():

    set_module_args(base_module_args)
    (boto3_conn_double,
     lambda_client_double) = make_mock_connection(code_change_lambda_config)

    with patch.object(lda, 'boto3_conn', boto3_conn_double):
        try:
            lda.main()
        except SystemExit:
            pass

    # guard against calling other than for a lambda connection (e.g. IAM)
    assert (len(boto3_conn_double.mock_calls) >
            0), "boto connections never used"
    assert (len(boto3_conn_double.mock_calls) <
            2), "multiple boto connections used unexpectedly"
    assert(len(lambda_client_double.update_function_configuration.mock_calls) == 0), \
        "unexpectedly updatede lambda configuration when only code changed"
    assert(len(lambda_client_double.update_function_configuration.mock_calls) < 2), \
        "lambda function update called multiple times when only one time should be needed"
    assert(len(lambda_client_double.update_function_code.mock_calls) > 1), \
        "failed to update lambda function when code changed"
    # 3 because after uploading we call into the return from mock to try to find what function version
    # was returned so the MagicMock actually sees two calls for one update.
    assert(len(lambda_client_double.update_function_code.mock_calls) < 3), \
        "lambda function code update called multiple times when only one time should be needed"
Beispiel #27
0
 def setUp(self):
     """Setup."""
     super(TestIcinga2Feature, self).setUp()
     self.module = icinga2_feature
     self.mock_get_bin_path = patch.object(basic.AnsibleModule, 'get_bin_path', get_bin_path)
     self.mock_get_bin_path.start()
     self.addCleanup(self.mock_get_bin_path.stop)  # ensure that the patching is 'undone'
Beispiel #28
0
    def test_remove_rule_check_mode(self):
        """Test flush without parameters check mode"""
        set_module_args({
            'chain': 'PREROUTING',
            'source': '1.2.3.4/32',
            'destination': '7.8.9.10/42',
            'jump': 'SNAT',
            'table': 'nat',
            'to_source': '5.5.5.5/32',
            'protocol': 'udp',
            'source_port': '22',
            'to_ports': '8600',
            'state': 'absent',
            'in_interface': 'eth0',
            'out_interface': 'eth1',
            'comment': 'this is a comment',
            '_ansible_check_mode': True,
        })

        commands_results = [
            (0, '', ''),
        ]

        with patch.object(basic.AnsibleModule, 'run_command') as run_command:
            run_command.side_effect = commands_results
            with self.assertRaises(AnsibleExitJson) as result:
                iptables.main()
                self.assertTrue(result.exception.args[0]['changed'])

        self.assertEqual(run_command.call_count, 1)
        self.assertEqual(run_command.call_args_list[0][0][0], [
            '/sbin/iptables',
            '-t',
            'nat',
            '-C',
            'PREROUTING',
            '-p',
            'udp',
            '-s',
            '1.2.3.4/32',
            '-d',
            '7.8.9.10/42',
            '-j',
            'SNAT',
            '--to-source',
            '5.5.5.5/32',
            '-i',
            'eth0',
            '-o',
            'eth1',
            '--source-port',
            '22',
            '--to-ports',
            '8600',
            '-m',
            'comment',
            '--comment',
            'this is a comment'
        ])
Beispiel #29
0
 def test_read_file_not_executable(self, mock_popen):
     self._mock_popen(mock_popen)
     secret = vault.ScriptVaultSecret()
     with patch.object(secret, 'loader') as mock_loader:
         mock_loader.is_executable = MagicMock(return_value=False)
         self.assertRaisesRegexp(
             vault.AnsibleVaultError,
             'The vault password script .* was not executable', secret.load)
Beispiel #30
0
 def test_read_file_empty(self, mock_popen):
     self._mock_popen(mock_popen, stdout=b'')
     secret = vault.ScriptVaultSecret()
     with patch.object(secret, 'loader') as mock_loader:
         mock_loader.is_executable = MagicMock(return_value=True)
         self.assertRaisesRegexp(
             vault.AnsibleVaultPasswordError,
             'Invalid vault password was provided from script', secret.load)