Esempio n. 1
0
    def test_activate_import_from_template(self, *args):
        set_module_args(dict(
            name='fake_policy',
            template='OWA Exchange 2007 (https)',
            state='present',
            active='yes',
            server='localhost',
            password='******',
            user='******',
        ))

        current = V1Parameters(params=load_fixture('load_asm_policy_inactive.json'))
        module = AnsibleModule(
            argument_spec=self.spec.argument_spec,
            supports_check_mode=self.spec.supports_check_mode
        )

        v1 = V1Manager(module=module)
        v1.exists = Mock(return_value=False)
        v1.import_to_device = Mock(return_value=True)
        v1.wait_for_task = Mock(side_effect=[True, True])
        v1.read_current_from_device = Mock(return_value=current)
        v1.apply_on_device = Mock(return_value=True)
        v1.create_from_template_on_device = Mock(return_value=True)
        v1._file_is_missing = Mock(return_value=False)

        # Override methods to force specific logic in the module to happen
        mm = ModuleManager(module=module)
        mm.version_is_less_than_13 = Mock(return_value=False)
        mm.get_manager = Mock(return_value=v1)

        results = mm.exec_module()

        assert results['changed'] is True
        assert results['name'] == 'fake_policy'
        assert results['template'] == 'OWA Exchange 2007 (https)'
        assert results['active'] is True
Esempio n. 2
0
    def test_absent_cs_action_failed_delete(self):
        set_module_args(
            dict(
                nitro_user='******',
                nitro_pass='******',
                nsip='1.1.1.1',
                state='absent',
            ))
        from ansible.modules.network.netscaler import netscaler_cs_action

        client_mock = Mock()

        m = Mock(return_value=client_mock)

        server_proxy_attrs = {
            'diff_object.return_value': {},
        }
        cs_action_proxy_mock = Mock()
        cs_action_proxy_mock.configure_mock(**server_proxy_attrs)
        config_proxy_mock = Mock(return_value=cs_action_proxy_mock)

        with patch.multiple(
                'ansible.modules.network.netscaler.netscaler_cs_action',
                nitro_exception=self.MockException,
                get_nitro_client=m,
                diff_list=Mock(return_value={}),
                get_immutables_intersection=Mock(return_value=[]),
                action_exists=Mock(side_effect=[True, True]),
                action_identical=Mock(side_effect=[False, False]),
                ensure_feature_is_enabled=Mock(return_value=True),
                ConfigProxy=config_proxy_mock,
        ):
            self.module = netscaler_cs_action
            result = self.failed()
            self.assertEqual(result['msg'],
                             'Content switching action still exists')
            self.assertTrue(result['failed'])
Esempio n. 3
0
    def test_present_gslb_site_failed_update(self):
        set_module_args(
            dict(
                nitro_user='******',
                nitro_pass='******',
                nsip='1.1.1.1',
                state='present',
            ))
        from ansible.modules.network.netscaler import netscaler_gslb_site

        client_mock = Mock()

        m = Mock(return_value=client_mock)

        glsb_site_proxy_attrs = {
            'diff_object.return_value': {},
        }
        gslb_site_proxy_mock = Mock()
        gslb_site_proxy_mock.configure_mock(**glsb_site_proxy_attrs)
        config_proxy_mock = Mock(return_value=gslb_site_proxy_mock)

        with patch.multiple(
                'ansible.modules.network.netscaler.netscaler_gslb_site',
                nitro_exception=self.MockException,
                get_nitro_client=m,
                diff_list=Mock(return_value={}),
                get_immutables_intersection=Mock(return_value=[]),
                gslb_site_exists=Mock(side_effect=[True, True]),
                gslb_site_identical=Mock(side_effect=[False, False]),
                ensure_feature_is_enabled=Mock(),
                ConfigProxy=config_proxy_mock,
        ):
            self.module = netscaler_gslb_site
            result = self.failed()
            self.assertEqual(result['msg'],
                             'GSLB site differs from configured')
            self.assertTrue(result['failed'])
Esempio n. 4
0
    def test_run_single_command(self, *args):
        set_module_args(
            dict(commands=["tmsh show sys version"],
                 server='localhost',
                 user='******',
                 password='******'))

        module = AnsibleModule(
            argument_spec=self.spec.argument_spec,
            supports_check_mode=self.spec.supports_check_mode)
        mm = ModuleManager(module=module)

        # Override methods to force specific logic in the module to happen
        mm.execute_on_device = Mock(return_value='foo')

        results = mm.exec_module()

        assert results['changed'] is True
Esempio n. 5
0
    def setUp(self):

        self.cmd_out = {
            # os.read() is returning 'bytes', not strings
            sentinel.stdout: BytesIO(),
            sentinel.stderr: BytesIO(),
        }

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

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

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

        basic.MODULE_COMPLEX_ARGS = '{}'
        basic.MODULE_CONSTANTS = '{}'
        self.module = AnsibleModule(argument_spec=dict())
        self.module.fail_json = MagicMock(side_effect=SystemExit)

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

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

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

        self.addCleanup(patch.stopall)
Esempio n. 6
0
    def test_module_utils_basic_ansible_module_set_context_if_different(self):
        from ansible.module_utils import basic
        basic._ANSIBLE_ARGS = None

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

        basic.HAVE_SELINUX = False

        am.selinux_enabled = MagicMock(return_value=False)
        self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True), True)
        self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), False)

        basic.HAVE_SELINUX = True

        am.selinux_enabled = MagicMock(return_value=True)
        am.selinux_context = MagicMock(return_value=['bar_u', 'bar_r', None, None])
        am.is_special_selinux_path = MagicMock(return_value=(False, None))

        basic.selinux = Mock()
        with patch.dict('sys.modules', {'selinux': basic.selinux}):
            with patch('selinux.lsetfilecon', return_value=0) as m:
                self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True)
                m.assert_called_with(b'/path/to/file', 'foo_u:foo_r:foo_t:s0')
                m.reset_mock()
                am.check_mode = True
                self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True)
                self.assertEqual(m.called, False)
                am.check_mode = False

            with patch('selinux.lsetfilecon', return_value=1) as m:
                self.assertRaises(SystemExit, am.set_context_if_different, '/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True)

            with patch('selinux.lsetfilecon', side_effect=OSError) as m:
                self.assertRaises(SystemExit, am.set_context_if_different, '/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True)

            am.is_special_selinux_path = MagicMock(return_value=(True, ['sp_u', 'sp_r', 'sp_t', 's0']))
            
            with patch('selinux.lsetfilecon', return_value=0) as m:
                self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True)
                m.assert_called_with(b'/path/to/file', 'sp_u:sp_r:sp_t:s0')

        delattr(basic, 'selinux')
Esempio n. 7
0
    def test_get_image_and_hotfixes_no_filter(self, *args):
        set_module_args(
            dict(server='localhost',
                 password='******',
                 user='******',
                 include=['image', 'hotfix']))

        module = AnsibleModule(
            argument_spec=self.spec.argument_spec,
            supports_check_mode=self.spec.supports_check_mode)

        mm = ModuleManager(module=module)
        mm.exit_json = Mock(return_value=False)
        results = mm.exec_module()

        assert results['changed'] is True
        assert len(results['images']) == 8
        assert len(results['hotfixes']) == 5
        assert 'volumes' not in results.keys()
Esempio n. 8
0
    def test_module_utils_basic_ansible_module_selinux_mls_enabled(self):
        from ansible.module_utils import basic
        basic._ANSIBLE_ARGS = None

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

        basic.HAVE_SELINUX = False
        self.assertEqual(am.selinux_mls_enabled(), False)

        basic.HAVE_SELINUX = True
        basic.selinux = Mock()
        with patch.dict('sys.modules', {'selinux': basic.selinux}):
            with patch('selinux.is_selinux_mls_enabled', return_value=0):
                self.assertEqual(am.selinux_mls_enabled(), False)
            with patch('selinux.is_selinux_mls_enabled', return_value=1):
                self.assertEqual(am.selinux_mls_enabled(), True)
        delattr(basic, 'selinux')
 def test_main_no_switch_configlet(self, mock_module, mock_connect,
                                   mock_info, mock_comp, mock_server_conf,
                                   mock_exception):
     ''' Test main fails if switch has no configlet for Ansible to edit.
     '''
     mock_module_object = Mock()
     mock_module_object.params = dict(action='add', switch_name='eos')
     mock_module_object.fail_json.side_effect = SystemExit('Exiting')
     mock_module.return_value = mock_module_object
     mock_connect.return_value = 'Client'
     mock_info.return_value = 'Info'
     mock_server_conf.return_value = None
     self.assertRaises(SystemExit, cv_server_provision.main)
     self.assertEqual(mock_connect.call_count, 1)
     self.assertEqual(mock_info.call_count, 1)
     self.assertEqual(mock_comp.call_count, 1)
     self.assertEqual(mock_server_conf.call_count, 1)
     mock_module_object.fail_json.assert_called_with(
         msg='Switch eos has no configurable server ports.')
    def test_graceful_nitro_exception_operation_absent(self):
        self.set_module_state('absent')
        from ansible.modules.network.netscaler import netscaler_servicegroup

        class MockException(Exception):
            def __init__(self, *args, **kwargs):
                self.errorcode = 0
                self.message = ''

        m = Mock(side_effect=MockException)
        with patch.multiple(
                'ansible.modules.network.netscaler.netscaler_servicegroup',
                servicegroup_exists=m,
                nitro_exception=MockException):
            self.module = netscaler_servicegroup
            result = self.failed()
            self.assertTrue(
                result['msg'].startswith('nitro exception'),
                msg='Nitro exception not caught on operation absent')
Esempio n. 11
0
    def test_delete_iapp_template_idempotent(self, *args):
        set_module_args(
            dict(content=load_fixture('basic-iapp.tmpl'),
                 password='******',
                 server='localhost',
                 user='******',
                 state='absent'))

        module = AnsibleModule(
            argument_spec=self.spec.argument_spec,
            supports_check_mode=self.spec.supports_check_mode)
        mm = ModuleManager(module=module)

        # Override methods to force specific logic in the module to happen
        mm.exists = Mock(side_effect=[False, False])

        results = mm.exec_module()

        assert results['changed'] is False
    def test_create(self, *args):
        set_module_args(
            dict(backup='yes',
                 create_on_missing='yes',
                 dest='/tmp/foo.ucs',
                 force='yes',
                 fail_on_missing='no',
                 src='remote.ucs',
                 password='******',
                 server='localhost',
                 user='******'))

        module = AnsibleModule(
            argument_spec=self.spec.argument_spec,
            supports_check_mode=self.spec.supports_check_mode)

        # Override methods to force specific logic in the module to happen
        m1 = V1Manager(module=module)
        m1.exists = Mock(return_value=False)
        m1.create_on_device = Mock(return_value=True)
        m1._get_backup_file = Mock(return_value='/tmp/foo.backup')
        m1.download_from_device = Mock(return_value=True)
        m1._set_checksum = Mock(return_value=12345)
        m1._set_md5sum = Mock(return_value=54321)

        mm = ModuleManager(module=module)
        mm.get_manager = Mock(return_value=m1)
        mm.is_version_v1 = Mock(return_value=True)

        p1 = patch('os.path.exists', return_value=True)
        p1.start()
        p2 = patch('os.path.isdir', return_value=False)
        p2.start()

        results = mm.exec_module()

        p1.stop()
        p2.stop()

        assert results['changed'] is True
    def test_get_volumes_no_filter(self, *args):
        set_module_args(
            dict(server='localhost',
                 password='******',
                 user='******',
                 include='volume'))

        client = AnsibleF5Client(
            argument_spec=self.spec.argument_spec,
            supports_check_mode=self.spec.supports_check_mode,
            f5_product_name=self.spec.f5_product_name)

        mm = ModuleManager(client)
        mm.exit_json = Mock(return_value=False)
        results = mm.exec_module()

        assert results['changed'] is True
        assert 'images' not in results.keys()
        assert 'hotfixes' not in results.keys()
        assert len(results['volumes']) == 4
Esempio n. 14
0
    def test_ensure_feature_is_enabled_nitro_exception_caught(self):
        set_module_args(
            dict(
                nitro_user='******',
                nitro_pass='******',
                nsip='192.0.2.1',
                state='present',
                save_config=False,
            ))
        from ansible.modules.network.netscaler import netscaler_lb_monitor

        client_mock = Mock()

        lb_monitor_proxy_mock = Mock(diff_object=Mock(return_value={}))
        errorcode = 10
        message = 'mock error'

        class MockException(Exception):
            def __init__(self):
                self.errorcode = errorcode
                self.message = message

        feature_mock = Mock(side_effect=MockException)

        with patch.multiple(
                'ansible.modules.network.netscaler.netscaler_lb_monitor',
                get_nitro_client=Mock(return_value=client_mock),
                lbmonitor_exists=Mock(side_effect=[True, True]),
                lbmonitor_identical=Mock(side_effect=[True, True]),
                ConfigProxy=Mock(return_value=lb_monitor_proxy_mock),
                ensure_feature_is_enabled=feature_mock,
                nitro_exception=MockException,
        ):
            self.module = netscaler_lb_monitor
            result = self.failed()
            expected_msg = 'nitro exception errorcode=%s, message=%s' % (
                errorcode, message)
            self.assertEqual(result['msg'], expected_msg,
                             'Failed to handle nitro exception')
Esempio n. 15
0
    def test_create(self, *args):
        set_module_args(
            dict(server='lb.mydomain.com',
                 user='******',
                 password='******',
                 name='GTM_Server',
                 datacenter='/Common/New York',
                 server_type='bigip',
                 link_discovery='disabled',
                 virtual_server_discovery='disabled',
                 devices=[
                     dict(name='server_1', address='1.1.1.1'),
                     dict(name='server_2',
                          address='2.2.2.1',
                          translation='192.168.2.1'),
                     dict(name='server_2', address='2.2.2.2'),
                     dict(name='server_3',
                          addresses=[
                              dict(address='3.3.3.1'),
                              dict(address='3.3.3.2')
                          ]),
                     dict(name='server_4',
                          addresses=[
                              dict(address='4.4.4.1',
                                   translation='192.168.14.1'),
                              dict(address='4.4.4.2')
                          ])
                 ]))

        module = AnsibleModule(
            argument_spec=self.spec.argument_spec,
            supports_check_mode=self.spec.supports_check_mode)

        m1 = V2Manager(module=module)
        m1.exists = Mock(side_effect=[False, True])
        m1.create_on_device = Mock(return_value=True)
        m1.client = Mock()
        m1.client.api.tmos_version = '13.1.0'

        # Override methods in the specific type of manager
        mm = ModuleManager(module=module)
        mm.get_manager = Mock(return_value=m1)
        mm.version_is_less_than = Mock(return_value=False)
        mm.gtm_provisioned = Mock(return_value=True)

        results = mm.exec_module()

        assert results['changed'] is True
        assert results['server_type'] == 'bigip'
Esempio n. 16
0
    def test_module_utils_basic_ansible_module_selinux_default_context(self):
        from ansible.module_utils import basic

        basic.MODULE_COMPLEX_ARGS = '{}'
        basic.MODULE_CONSTANTS = '{}'
        am = basic.AnsibleModule(argument_spec=dict(), )

        am.selinux_initial_context = MagicMock(
            return_value=[None, None, None, None])
        am.selinux_enabled = MagicMock(return_value=True)

        # we first test the cases where the python selinux lib is not installed
        basic.HAVE_SELINUX = False
        self.assertEqual(am.selinux_default_context(path='/foo/bar'),
                         [None, None, None, None])

        # all following tests assume the python selinux bindings are installed
        basic.HAVE_SELINUX = True

        basic.selinux = Mock()

        with patch.dict('sys.modules', {'selinux': basic.selinux}):
            # next, we test with a mocked implementation of selinux.matchpathcon to simulate
            # an actual context being found
            with patch('selinux.matchpathcon',
                       return_value=[0, 'unconfined_u:object_r:default_t:s0']):
                self.assertEqual(
                    am.selinux_default_context(path='/foo/bar'),
                    ['unconfined_u', 'object_r', 'default_t', 's0'])

            # we also test the case where matchpathcon returned a failure
            with patch('selinux.matchpathcon', return_value=[-1, '']):
                self.assertEqual(am.selinux_default_context(path='/foo/bar'),
                                 [None, None, None, None])

            # finally, we test where an OSError occurred during matchpathcon's call
            with patch('selinux.matchpathcon', side_effect=OSError):
                self.assertEqual(am.selinux_default_context(path='/foo/bar'),
                                 [None, None, None, None])

        delattr(basic, 'selinux')
Esempio n. 17
0
    def setUpClass(cls):
        class MockException(Exception):
            pass

        cls.MockException = MockException

        m = MagicMock()
        cls.server_mock = MagicMock()
        cls.server_mock.__class__ = MagicMock(add=Mock())
        nssrc_modules_mock = {
            'nssrc.com.citrix.netscaler.nitro.resource.config.ssl':
            m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.ssl.sslcertkey':
            m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.ssl.sslcertkey.sslcertkey':
            m,
        }

        cls.nitro_specific_patcher = patch.dict(sys.modules,
                                                nssrc_modules_mock)
        cls.nitro_base_patcher = nitro_base_patcher
Esempio n. 18
0
def test_warn_region_not_specified():

    set_module_args({
        "name": "lambda_name",
        "state": "present",
        # Module is called without a region causing error
        # "region": "us-east-1",
        "zip_file": "test/units/modules/cloud/amazon/fixtures/thezip.zip",
        "runtime": 'python2.7',
        "role": 'arn:aws:iam::987654321012:role/lambda_basic_execution',
        "handler": 'lambda_python.my_handler'})

    get_aws_connection_info_double = Mock(return_value=(None, None, None))

    with patch.object(lda, 'get_aws_connection_info', get_aws_connection_info_double):
        with patch.object(basic.AnsibleModule, 'fail_json', fail_json_double):
            try:
                lda.main()
            except AnsibleFailJson as e:
                result = e.args[0]
                assert("region must be specified" in result['msg'])
    def test_create_device_trust_idempotent(self, *args):
        set_module_args(
            dict(peer_server='10.10.10.10',
                 peer_hostname='foo.bar.baz',
                 peer_user='******',
                 peer_password='******',
                 server='localhost',
                 password='******',
                 user='******'))

        module = AnsibleModule(
            argument_spec=self.spec.argument_spec,
            supports_check_mode=self.spec.supports_check_mode)

        # Override methods in the specific type of manager
        mm = ModuleManager(module=module)
        mm.exists = Mock(return_value=True)

        results = mm.exec_module()

        assert results['changed'] is False
    def test_delete(self):
        set_module_args(
            dict(name='test-route',
                 password='******',
                 server='localhost',
                 user='******',
                 state='absent'))
        mut._CONNECTION = True

        module = F5AnsibleModule()
        obj = ModuleManager(module=module)

        # Override methods to force specific logic in the module to happen
        obj.exists = Mock()
        obj.exists.side_effect = [True, False]
        obj.remove_from_device = lambda: True
        obj.exit_json = lambda x: True
        results = obj.apply_changes()

        assert results['changed'] is True
        assert 'description' not in results
Esempio n. 21
0
    def setUpClass(cls):
        class MockException(Exception):
            pass

        cls.MockException = MockException

        m = MagicMock()
        cls.cs_action_mock = MagicMock()
        cls.cs_action_mock.__class__ = MagicMock(add=Mock())
        nssrc_modules_mock = {
            'nssrc.com.citrix.netscaler.nitro.resource.config.cs':
            m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.cs.csaction':
            m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.cs.csaction.csaction':
            cls.cs_action_mock,
        }

        cls.nitro_specific_patcher = patch.dict(sys.modules,
                                                nssrc_modules_mock)
        cls.nitro_base_patcher = nitro_base_patcher
 def test_configlet_action_remove_no_task(self):
     ''' Test configlet_action with remove that doesn't change configlet and
         adds proper info to return data. Does not including any task info.
     '''
     module = Mock()
     module.params = dict(action='remove',
                          switch_name='eos',
                          switch_port='3')
     config = '!\ninterface Ethernet3\n!\ninterface Ethernet4\n!'
     configlet = dict(name='eos-server', key='key', config=config)
     update_return = dict(data='Configlet eos-server successfully updated.')
     module.client.api.update_configlet.return_value = update_return
     result = cv_server_provision.configlet_action(module, configlet)
     self.assertIsNotNone(result)
     self.assertEqual(result['oldConfigBlock'], 'interface Ethernet3\n!')
     self.assertEqual(result['fullConfig'], config)
     self.assertEqual(result['updateConfigletResponse'],
                      update_return['data'])
     self.assertNotIn('changed', result)
     self.assertNotIn('taskCreated', result)
     self.assertEqual(module.client.api.update_configlet.call_count, 1)
    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,
        ):
            self.module = netscaler_service
            result = self.exited()
            service_proxy_mock.assert_has_calls([call.add()])
            self.assertTrue(result['changed'], msg='Change not recorded')
Esempio n. 24
0
    def test_botocore_exception_reports_nicely_via_fail_json_aws(self):

        basic._ANSIBLE_ARGS = to_bytes(json.dumps({'ANSIBLE_MODULE_ARGS': {}}))
        module = AnsibleAWSModule(argument_spec=dict(
            fail_mode=dict(type='list', default=['success'])))

        fail_json_double = Mock()
        err_msg = {'Error': {'Code': 'FakeClass.FakeError'}}
        with patch.object(basic.AnsibleModule, 'fail_json', fail_json_double):
            try:
                raise botocore.exceptions.ClientError(err_msg,
                                                      'Could not find you')
            except Exception as e:
                print("exception is " + str(e))
                module.fail_json_aws(
                    e, msg="Fake failure for testing boto exception messages")

        assert (len(fail_json_double.mock_calls) >
                0), "failed to call fail_json when should have"
        assert (len(fail_json_double.mock_calls) <
                2), "called fail_json multiple times when once would do"
        assert("test_botocore_exception_reports_nicely"
               in fail_json_double.mock_calls[0][2]["exception"]), \
            "exception traceback doesn't include correct function, fail call was actually: " \
            + str(fail_json_double.mock_calls[0])

        assert("Fake failure for testing boto exception messages:"
               in fail_json_double.mock_calls[0][2]["msg"]), \
            "error message doesn't include the local message; was: " \
            + str(fail_json_double.mock_calls[0])
        assert("Could not find you" in fail_json_double.mock_calls[0][2]["msg"]), \
            "error message doesn't include the botocore exception message; was: " \
            + str(fail_json_double.mock_calls[0])
        try:
            fail_json_double.mock_calls[0][2]["error"]
        except KeyError:
            raise Exception("error was missing; call was: " +
                            str(fail_json_double.mock_calls[0]))
        assert("FakeClass.FakeError" == fail_json_double.mock_calls[0][2]["error"]["code"]), \
            "Failed to find error/code; was: " + str(fail_json_double.mock_calls[0])
Esempio n. 25
0
    def test_present_server_update_immutable_attribute(self):
        set_module_args(
            dict(
                nitro_user='******',
                nitro_pass='******',
                nsip='192.0.2.1',
                state='present',
            ))
        from ansible.modules.network.netscaler import netscaler_ssl_certkey

        client_mock = Mock()

        m = Mock(return_value=client_mock)

        ssl_certkey_proxy_attrs = {
            'diff_object.return_value': {},
        }
        ssl_certkey_proxy_mock = Mock()
        ssl_certkey_proxy_mock.configure_mock(**ssl_certkey_proxy_attrs)
        config_proxy_mock = Mock(return_value=ssl_certkey_proxy_mock)

        with patch.multiple(
                'ansible.modules.network.netscaler.netscaler_ssl_certkey',
                nitro_exception=self.MockException,
                get_nitro_client=m,
                diff_list=Mock(return_value={}),
                get_immutables_intersection=Mock(return_value=['domain']),
                key_exists=Mock(side_effect=[True, True]),
                key_identical=Mock(side_effect=[False, False]),
                ConfigProxy=config_proxy_mock,
        ):
            self.module = netscaler_ssl_certkey
            result = self.failed()
            self.assertEqual(
                result['msg'],
                'Cannot update immutable attributes [\'domain\']')
            self.assertTrue(result['failed'])
    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')
Esempio n. 27
0
def test_dont_update_lambda_if_nothing_changed(monkeypatch):

    fake_lambda_connection = MagicMock()
    fake_lambda_connection.get_function.configure_mock(
        return_value={'Configuration': base_start_function_config_in_aws})
    fake_lambda_connection.update_function_configuration.configure_mock(
        return_value={'Version': 1})
    fake_boto3_conn = Mock(return_value=fake_lambda_connection)

    @patch("ansible.modules.cloud.amazon.lambda.boto3_conn", fake_boto3_conn)
    def call_module():
        with pytest.raises(SystemExit):
            lda.main()

    call_module()

    # guard against calling other than for a lambda connection (e.g. IAM)
    assert (len(fake_boto3_conn.mock_calls) == 1
            ), "multiple boto connections used unexpectedly"
    assert(len(fake_lambda_connection.update_function_configuration.mock_calls) == 0), \
        "updated lambda function when no configuration changed"
    assert(len(fake_lambda_connection.update_function_code.mock_calls) == 0 ), \
        "updated lambda code when no change should have happened"
 def test_main_port_not_in_config(self, mock_module, mock_connect,
                                  mock_info, mock_comp, mock_server_conf,
                                  mock_port_conf, mock_exception):
     ''' Test main fails if user specified port not in configlet.
     '''
     mock_module_object = Mock()
     mock_module_object.params = dict(action='add',
                                      switch_name='eos',
                                      switch_port='3')
     mock_module_object.fail_json.side_effect = SystemExit('Exiting')
     mock_module.return_value = mock_module_object
     mock_connect.return_value = 'Client'
     mock_info.return_value = 'Info'
     mock_server_conf.return_value = 'Configlet'
     mock_port_conf.return_value = None
     self.assertRaises(SystemExit, cv_server_provision.main)
     self.assertEqual(mock_connect.call_count, 1)
     self.assertEqual(mock_info.call_count, 1)
     self.assertEqual(mock_comp.call_count, 1)
     self.assertEqual(mock_server_conf.call_count, 1)
     self.assertEqual(mock_port_conf.call_count, 1)
     mock_module_object.fail_json.assert_called_with(
         msg='Port 3 is not configurable as a server port on switch eos.')
Esempio n. 29
0
    def test_cert_changed_fail_read_cert(self):
        set_module_args(
            dict(certificate='cert-foo',
                 private_key='private-foo',
                 dest='/etc/security/keystore.jks',
                 name='foo',
                 password='******'))

        module = AnsibleModule(
            argument_spec=self.spec.argument_spec,
            supports_check_mode=self.spec.supports_check_mode)

        module.fail_json = Mock()

        with patch('os.remove', return_value=True):
            self.run_commands.side_effect = [(1, '', 'Oops'),
                                             (0, 'foo: wxyz:9876:stuv', '')]
            cert_changed(module, "openssl", "keytool",
                         "/etc/security/keystore.jks", "changeit", 'foo')
            module.fail_json.assert_called_once_with(
                cmd="openssl x509 -noout -in /tmp/foo.crt -fingerprint -sha1",
                msg='',
                err='Oops',
                rc=1)
Esempio n. 30
0
    def test_edit_response_data_actual_body_data(self):
        args = copy.deepcopy(module_arguments)
        args.update(dict(
            nitro_user='******',
            nitro_pass='******',
            nitro_auth_token='##DDASKLFDJ',
        ))
        module_mock = Mock(params=args, from_json=json.loads)
        with patch('ansible.modules.network.netscaler.netscaler_nitro_request.AnsibleModule', Mock(return_value=module_mock)):
            with tempfile.TemporaryFile() as r:
                actual_body = {
                    'errorcode': 258,
                    'message': 'Some error',
                    'severity': 'ERROR',
                }
                r.write(codecs.encode(json.dumps(actual_body), 'utf-8'))
                r.seek(0)

                instance = netscaler_nitro_request.NitroAPICaller()
                info = {
                    'status': 200,
                }
                result = {}
                success_status = 200

                expected_result = {
                    'http_response_body': json.dumps(actual_body),
                    'http_response_data': info,
                }
                nitro_data = {}
                for key, value in actual_body.items():
                    nitro_data['nitro_%s' % key] = value
                expected_result.update(nitro_data)

                instance.edit_response_data(r, info, result, success_status)
                self.assertDictEqual(result, expected_result)