def test_ensure_feature_is_enabled_called(self):
        set_module_args(dict(
            nitro_user='******',
            nitro_pass='******',
            nsip='1.1.1.1',
            state='present',
            save_config=False,
        ))
        from ansible.modules.network.netscaler import netscaler_lb_vserver

        client_mock = Mock()

        lb_vserver_proxy_mock = Mock()
        feature_mock = Mock()

        with patch.multiple(
            'ansible.modules.network.netscaler.netscaler_lb_vserver',
            get_nitro_client=Mock(return_value=client_mock),
            lb_vserver_exists=Mock(side_effect=[True, True]),
            lb_vserver_identical=Mock(side_effect=[True, True]),
            servicegroup_bindings_identical=Mock(side_effect=[True, True]),
            service_bindings_identical=Mock(side_effect=[True, True]),

            ConfigProxy=Mock(return_value=lb_vserver_proxy_mock),
            ensure_feature_is_enabled=feature_mock,
            do_state_change=Mock(return_value=Mock(errorcode=0)),
        ):
            self.module = netscaler_lb_vserver
            self.exited()
            feature_mock.assert_called_with(client_mock, 'LB')
    def test_absent_cs_action_execution_flow(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',
            get_nitro_client=m,
            diff_list=Mock(return_value={}),
            get_immutables_intersection=Mock(return_value=[]),
            action_exists=Mock(side_effect=[True, False]),
            action_identical=Mock(side_effect=[False, True]),
            ensure_feature_is_enabled=Mock(return_value=True),
            ConfigProxy=config_proxy_mock,
        ):
            self.module = netscaler_cs_action
            self.exited()
            cs_action_proxy_mock.assert_has_calls([call.delete()])
    def test_ensure_feature_is_enabled_called(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

        gslb_site_proxy_mock = Mock()
        ensure_feature_is_enabled_mock = Mock()
        client_mock = Mock()

        with patch.multiple(
            'ansible.modules.network.netscaler.netscaler_gslb_site',
            get_nitro_client=Mock(return_value=client_mock),
            gslb_site_exists=Mock(side_effect=[False, True]),
            gslb_site_identical=Mock(side_effect=[True]),
            nitro_exception=self.MockException,
            ensure_feature_is_enabled=ensure_feature_is_enabled_mock,
            ConfigProxy=Mock(return_value=gslb_site_proxy_mock),
        ):
            self.module = netscaler_gslb_site
            self.exited()
            ensure_feature_is_enabled_mock.assert_called_with(client_mock, 'GSLB')
    def test_present_gslb_site_identical_flow(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',
            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=[True, True]),
            nitro_exception=self.MockException,
            ensure_feature_is_enabled=Mock(),
            ConfigProxy=config_proxy_mock,
        ):
            self.module = netscaler_gslb_site
            self.exited()
            gslb_site_proxy_mock.assert_not_called()
    def test_absent_gslb_site_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_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 still exists')
            self.assertTrue(result['failed'])
Exemple #6
0
    def test_udevadm_uuid(self):
        module = Mock()
        module.run_command = Mock(return_value=(0, UDEVADM_OUTPUT, ''))  # (rc, out, err)
        lh = linux.LinuxHardware(module=module, load_on_init=False)
        udevadm_uuid = lh._udevadm_uuid('mock_device')

        self.assertEqual(udevadm_uuid, '57b1a3e7-9019-4747-9809-7ec52bba9179')
    def test_graceful_login_error(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

        if sys.version_info[:2] == (2, 6):
            self.skipTest('requests library not available under python2.6')

        class MockException(Exception):
            pass
        client_mock = Mock()
        attrs = {'login.side_effect': requests.exceptions.SSLError}
        client_mock.configure_mock(**attrs)
        m = Mock(return_value=client_mock)
        with patch.multiple(
            'ansible.modules.network.netscaler.netscaler_gslb_site',
            get_nitro_client=m,
            nitro_exception=MockException,
        ):
            self.module = netscaler_gslb_site
            result = self.failed()
            self.assertTrue(result['msg'].startswith('SSL Error'), msg='SSL Error was not handled gracefully')
    def test_absent_server_noop_flow(self):
        set_module_args(dict(
            nitro_user='******',
            nitro_pass='******',
            nsip='1.1.1.1',
            state='absent',
        ))
        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',
            get_nitro_client=m,
            diff_list=Mock(return_value={}),
            get_immutables_intersection=Mock(return_value=[]),
            key_exists=Mock(side_effect=[False, False]),
            key_identical=Mock(side_effect=[False, False]),
            ConfigProxy=config_proxy_mock,
        ):
            self.module = netscaler_ssl_certkey
            self.exited()
            ssl_certkey_proxy_mock.assert_not_called()
    def test_update_lb_vserver_workflow(self):
        set_module_args(dict(
            nitro_user='******',
            nitro_pass='******',
            nsip='1.1.1.1',
            state='present',
            save_config=False,
        ))
        from ansible.modules.network.netscaler import netscaler_lb_vserver

        lb_vserver_proxy_mock = Mock()

        with patch.multiple(
            'ansible.modules.network.netscaler.netscaler_lb_vserver',
            get_nitro_client=Mock(return_value=Mock()),
            lb_vserver_exists=Mock(side_effect=[True, True]),
            lb_vserver_identical=Mock(side_effect=[False, True]),
            servicegroup_bindings_identical=Mock(side_effect=[True, True]),
            service_bindings_identical=Mock(side_effect=[True, True]),

            ConfigProxy=Mock(return_value=lb_vserver_proxy_mock),
            ensure_feature_is_enabled=Mock(return_value=True),
            do_state_change=Mock(return_value=Mock(errorcode=0)),
            get_immutables_intersection=Mock(return_value=[]),
        ):
            self.module = netscaler_lb_vserver
            result = self.exited()
            lb_vserver_proxy_mock.assert_has_calls([call.update()])
            self.assertTrue(result['changed'])
 def test_ensure_feature_is_enabled(self):
     client = Mock()
     attrs = {'get_enabled_features.return_value': ['GSLB']}
     client.configure_mock(**attrs)
     ensure_feature_is_enabled(client, 'GSLB')
     ensure_feature_is_enabled(client, 'LB')
     client.enable_features.assert_called_once_with('LB')
    def test_present_server_update_immutable_attribute(self):
        set_module_args(dict(
            nitro_user='******',
            nitro_pass='******',
            nsip='1.1.1.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_ssl_bindings_not_called_for_non_ssl_service(self):
        set_module_args(dict(
            nitro_user='******',
            nitro_pass='******',
            nsip='1.1.1.1',
            state='present',
            save_config=False,
            servicetype='HTTP',
        ))
        from ansible.modules.network.netscaler import netscaler_lb_vserver

        lb_vserver_proxy_mock = Mock()
        ssl_sync_mock = Mock()

        client_mock = Mock()

        with patch.multiple(
            'ansible.modules.network.netscaler.netscaler_lb_vserver',
            get_nitro_client=Mock(return_value=client_mock),
            lb_vserver_exists=Mock(side_effect=[True, True]),
            lb_vserver_identical=Mock(side_effect=[False, True]),
            servicegroup_bindings_identical=Mock(side_effect=[True, True]),
            service_bindings_identical=Mock(side_effect=[True, True]),
            ssl_certkey_bindings_identical=Mock(side_effect=[False, True]),
            ssl_certkey_bindings_sync=ssl_sync_mock,
            ConfigProxy=Mock(return_value=lb_vserver_proxy_mock),
            ensure_feature_is_enabled=Mock(return_value=True),
            do_state_change=Mock(return_value=Mock(errorcode=0)),
            get_immutables_intersection=(Mock(return_value=[])),
        ):
            self.module = netscaler_lb_vserver
            result = self.exited()
            ssl_sync_mock.assert_not_called()
            self.assertTrue(result['changed'])
 def test_main_show(self, mock_module, mock_connect, mock_info, mock_comp,
                    mock_server_conf, mock_port_conf, mock_conf_action):
     ''' Test main good with show action.
     '''
     mock_module_object = Mock()
     mock_module_object.params = dict(action='show', switch_name='eos',
                                      switch_port='3', auto_run=False)
     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 = 'Port'
     mock_conf_action.return_value = dict()
     cv_server_provision.main()
     self.assertEqual(mock_connect.call_count, 1)
     self.assertEqual(mock_info.call_count, 1)
     mock_comp.assert_not_called()
     self.assertEqual(mock_server_conf.call_count, 1)
     self.assertEqual(mock_port_conf.call_count, 1)
     self.assertEqual(mock_conf_action.call_count, 1)
     mock_module_object.fail_json.assert_not_called()
     return_dict = dict(changed=False, switchInfo='Info',
                        switchConfigurable=True, portConfigurable=True,
                        taskCreated=False, taskExecuted=False,
                        taskCompleted=False)
     mock_module_object.exit_json.assert_called_with(**return_dict)
    def test_present_server_identical_flow(self):
        set_module_args(dict(
            nitro_user='******',
            nitro_pass='******',
            nsip='1.1.1.1',
            state='present',
        ))
        from ansible.modules.network.netscaler import netscaler_server

        client_mock = Mock()

        m = Mock(return_value=client_mock)

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

        with patch.multiple(
            'ansible.modules.network.netscaler.netscaler_server',
            get_nitro_client=m,
            diff_list=Mock(return_value={}),
            get_immutables_intersection=Mock(return_value=[]),
            server_exists=Mock(side_effect=[True, True]),
            server_identical=Mock(side_effect=[True, True]),
            ConfigProxy=config_proxy_mock,
            do_state_change=Mock(return_value=Mock(errorcode=0))
        ):
            self.module = netscaler_server
            self.exited()
            server_proxy_mock.assert_not_called()
 def test_config_from_template_fail_no_vlan(self, mock_file_sys, mock_env,
                                            mock_debug, mock_find):
     ''' Test config_from_template fail. Template needs vlan but none provided.
     '''
     module = Mock()
     module.params = dict(switch_name='eos', switch_port='3',
                          server_name='new', template='jinja.j2',
                          port_vlan=None)
     mock_file_sys.return_value = 'file'
     mock_debug.return_value = 'debug'
     template_mock = Mock()
     template_mock.render.return_value = ('interface Ethernet3\n'
                                          '   description test\n!')
     env_mock = Mock()
     env_mock.loader.get_source.return_value = ['one', 'two']
     env_mock.parse.return_value = 'parsed'
     env_mock.get_template.return_value = template_mock
     mock_env.return_value = env_mock
     mock_find.return_value = dict(server_name=None, switch_port=None,
                                   port_vlan=None)
     result = cv_server_provision.config_from_template(module)
     self.assertIsNotNone(result)
     expected = 'interface Ethernet3\n   description test\n!'
     self.assertEqual(result, expected)
     self.assertEqual(mock_file_sys.call_count, 1)
     self.assertEqual(mock_env.call_count, 1)
     module.fail_json.assert_called_with(msg='Template jinja.j2 requires a'
                                             ' vlan. Please re-run with vlan'
                                             ' number provided.')
 def test_main_module_args(self, mock_module, mock_connect, mock_info,
                           mock_comp, mock_server_conf, mock_exception):
     ''' Test main module args.
     '''
     mock_module_object = Mock()
     mock_module_object.params = dict(action='show', 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.side_effect = mock_exception('Error Getting Info')
     argument_spec = dict(
         host=dict(required=True),
         port=dict(required=False, default=None),
         protocol=dict(default='https', choices=['http', 'https']),
         username=dict(required=True),
         password=dict(required=True, no_log=True),
         server_name=dict(required=True),
         switch_name=dict(required=True),
         switch_port=dict(required=True),
         port_vlan=dict(required=False, default=None),
         template=dict(require=True),
         action=dict(default='show', choices=['show', 'add', 'remove']),
         auto_run=dict(type='bool', default=False),
     )
     self.assertRaises(SystemExit, cv_server_provision.main)
     mock_module.assert_called_with(argument_spec=argument_spec,
                                    supports_check_mode=False)
     self.assertEqual(mock_connect.call_count, 1)
     self.assertEqual(mock_info.call_count, 1)
     mock_comp.assert_not_called()
     mock_server_conf.assert_not_called()
     mock_module_object.fail_json.assert_called_with(msg='Error Getting Info')
    def test_new_gslb_vserver_execution_flow(self):
        set_module_args(dict(
            nitro_user='******',
            nitro_pass='******',
            nsip='1.1.1.1',
            state='present',
        ))
        from ansible.modules.network.netscaler import netscaler_gslb_vserver

        client_mock = Mock()

        m = Mock(return_value=client_mock)

        glsb_service_proxy_attrs = {
            'diff_object.return_value': {},
        }
        gslb_service_proxy_mock = Mock()
        gslb_service_proxy_mock.configure_mock(**glsb_service_proxy_attrs)
        config_proxy_mock = Mock(return_value=gslb_service_proxy_mock)

        with patch.multiple(
            'ansible.modules.network.netscaler.netscaler_gslb_vserver',
            get_nitro_client=m,
            gslb_vserver_exists=Mock(side_effect=[False, True]),
            gslb_vserver_identical=Mock(side_effect=[True]),
            nitro_exception=self.MockException,
            do_state_change=Mock(return_value=Mock(errorcode=0)),
            ensure_feature_is_enabled=Mock(),
            ConfigProxy=config_proxy_mock,
        ):
            self.module = netscaler_gslb_vserver
            self.exited()
            gslb_service_proxy_mock.assert_has_calls([call.add()])
 def test_config_from_template_good_vlan(self, mock_file_sys, mock_env, mock_debug,
                                         mock_find):
     ''' Test config_from_template good. With port_vlan.
     '''
     module = Mock()
     module.params = dict(switch_name='eos', switch_port='3',
                          server_name='new', template='jinja.j2', port_vlan='7')
     mock_file_sys.return_value = 'file'
     mock_debug.return_value = 'debug'
     template_mock = Mock()
     template_mock.render.return_value = ('interface Ethernet3\n'
                                          '   description test\n'
                                          '   switchport\n'
                                          '   switchport access vlan 7\n'
                                          '   no shutdown\n!')
     env_mock = Mock()
     env_mock.loader.get_source.return_value = ['one', 'two']
     env_mock.parse.return_value = 'parsed'
     env_mock.get_template.return_value = template_mock
     mock_env.return_value = env_mock
     mock_find.return_value = dict(server_name=None, switch_port=None,
                                   port_vlan=None)
     result = cv_server_provision.config_from_template(module)
     self.assertIsNotNone(result)
     expected = ('interface Ethernet3\n'
                 '   description test\n'
                 '   switchport\n'
                 '   switchport access vlan 7\n'
                 '   no shutdown\n!')
     self.assertEqual(result, expected)
     self.assertEqual(mock_file_sys.call_count, 1)
     self.assertEqual(mock_env.call_count, 1)
     module.fail_json.assert_not_called()
 def test_config_from_template_fail_wrong_port(self, mock_file_sys, mock_env,
                                               mock_debug, mock_find):
     ''' Test config_from_template fail. Wrong port number in template.
     '''
     module = Mock()
     module.params = dict(switch_name='eos', switch_port='4',
                          server_name='new', template='jinja.j2')
     mock_file_sys.return_value = 'file'
     mock_debug.return_value = 'debug'
     template_mock = Mock()
     template_mock.render.return_value = ('interface Ethernet3\n'
                                          '   description test\n!')
     env_mock = Mock()
     env_mock.loader.get_source.return_value = ['one', 'two']
     env_mock.parse.return_value = 'parsed'
     env_mock.get_template.return_value = template_mock
     mock_env.return_value = env_mock
     mock_find.return_value = dict(server_name=None, switch_port=None)
     result = cv_server_provision.config_from_template(module)
     self.assertIsNotNone(result)
     expected = 'interface Ethernet3\n   description test\n!'
     self.assertEqual(result, expected)
     self.assertEqual(mock_file_sys.call_count, 1)
     self.assertEqual(mock_env.call_count, 1)
     module.fail_json.assert_called_with(msg='Template content does not'
                                             ' configure proper interface'
                                             ' - %s' % expected)
    def test_present_cs_action_failed_create(self):
        set_module_args(dict(
            nitro_user='******',
            nitro_pass='******',
            nsip='1.1.1.1',
            state='present',
        ))
        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=[False, False]),
            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 does not exist')
            self.assertTrue(result['failed'])
 def test_configlet_action_add_with_task(self, mock_template):
     ''' Test configlet_action add with change updates configlet and adds
         proper info to return data. Including task spawned info.
     '''
     module = Mock()
     module.params = dict(action='add', switch_name='eos', switch_port='3')
     config = '!\ninterface Ethernet3\n!\ninterface Ethernet4\n!'
     configlet = dict(name='eos-server', key='key', config=config)
     template_config = ('interface Ethernet3\n   description Host eos'
                        ' managed by Ansible and Jinja template\n'
                        '   load-interval 30\n'
                        '   switchport\n'
                        '   switchport mode trunk\n'
                        '   no shutdown\n!')
     mock_template.return_value = template_config
     update_return = dict(data='Configlet eos-server successfully updated'
                               ' and task initiated.')
     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!')
     full_config = '!\n' + template_config + '\ninterface Ethernet4\n!'
     self.assertEqual(result['fullConfig'], full_config)
     self.assertEqual(result['updateConfigletResponse'],
                      update_return['data'])
     self.assertTrue(result['changed'])
     self.assertTrue(result['taskCreated'])
     self.assertEqual(module.client.api.update_configlet.call_count, 1)
    def test_absent_server_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_server

        client_mock = Mock()

        m = Mock(return_value=client_mock)

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

        with patch.multiple(
            'ansible.modules.network.netscaler.netscaler_server',
            nitro_exception=self.MockException,
            get_nitro_client=m,
            diff_list=Mock(return_value={}),
            get_immutables_intersection=Mock(return_value=[]),
            server_exists=Mock(side_effect=[True, True]),
            server_identical=Mock(side_effect=[False, False]),
            ConfigProxy=config_proxy_mock,
            do_state_change=Mock(return_value=Mock(errorcode=0))
        ):
            self.module = netscaler_server
            result = self.failed()
            self.assertEqual(result['msg'], 'Server seems to be present')
            self.assertTrue(result['failed'])
 def test_main_add_auto_run_no_task(self, mock_module, mock_connect,
                                    mock_info, mock_comp, mock_server_conf,
                                    mock_port_conf, mock_conf_action, mock_conf_task,
                                    mock_wait):
     ''' Test main good with add and auto_run. Config not updated, no task.
     '''
     mock_module_object = Mock()
     mock_module_object.params = dict(action='add', switch_name='eos',
                                      switch_port='3', auto_run=True)
     mock_module.return_value = mock_module_object
     mock_client_object = Mock()
     mock_connect.return_value = mock_client_object
     mock_info.return_value = 'Info'
     mock_server_conf.return_value = 'Configlet'
     mock_port_conf.return_value = 'Port'
     mock_conf_action.return_value = dict(taskCreated=True, changed=False)
     mock_conf_task.return_value = None
     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)
     self.assertEqual(mock_conf_action.call_count, 1)
     self.assertEqual(mock_conf_task.call_count, 1)
     mock_wait.assert_not_called()
     mock_module_object.fail_json.assert_not_called()
     return_dict = dict(changed=False, switchInfo='Info',
                        switchConfigurable=True, portConfigurable=True,
                        taskCreated=False, taskExecuted=False,
                        taskCompleted=False)
     mock_module_object.exit_json.assert_called_with(**return_dict)
    def test_new_ssl_certkey_execution_flow(self):
        set_module_args(dict(
            nitro_user='******',
            nitro_pass='******',
            nsip='1.1.1.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',
            get_nitro_client=m,
            key_exists=Mock(side_effect=[False, True]),
            key_identical=Mock(side_effect=[True]),
            ConfigProxy=config_proxy_mock,
        ):
            self.module = netscaler_ssl_certkey
            self.exited()
            ssl_certkey_proxy_mock.assert_has_calls([call.add()])
    def test_graceful_nitro_error_on_login(self):
        set_module_args(dict(
            nitro_user='******',
            nitro_pass='******',
            nsip='1.1.1.1',
            state='present',
        ))
        from ansible.modules.network.netscaler import netscaler_lb_monitor

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

        client_mock = Mock()
        client_mock.login = Mock(side_effect=MockException)
        m = Mock(return_value=client_mock)
        with patch.multiple(
            'ansible.modules.network.netscaler.netscaler_lb_monitor',
            get_nitro_client=m,
            nitro_exception=MockException,
        ):
            self.module = netscaler_lb_monitor
            result = self.failed()
            self.assertTrue(result['msg'].startswith('nitro exception'), msg='nitro exception during login not handled properly')
    def test_create_new_lb_monitor_workflow(self):
        set_module_args(dict(
            nitro_user='******',
            nitro_pass='******',
            nsip='1.1.1.1',
            state='present',
            save_config=False,
        ))
        from ansible.modules.network.netscaler import netscaler_lb_monitor

        lb_monitor_proxy_mock = Mock(diff_object=Mock(return_value={}))

        with patch.multiple(
            'ansible.modules.network.netscaler.netscaler_lb_monitor',
            get_nitro_client=Mock(return_value=Mock()),
            lbmonitor_exists=Mock(side_effect=[False, True]),
            lbmonitor_identical=Mock(side_effect=[True]),

            ConfigProxy=Mock(return_value=lb_monitor_proxy_mock),
            ensure_feature_is_enabled=Mock(return_value=True),
        ):
            self.module = netscaler_lb_monitor
            result = self.exited()
            lb_monitor_proxy_mock.assert_has_calls([call.add()])
            self.assertTrue(result['changed'])
 def _mock_module(self):
     mock_module = Mock()
     mock_module.params = {'gather_subset': self.gather_subset,
                           'gather_timeout': 5,
                           'filter': '*'}
     mock_module.get_bin_path = Mock(return_value=None)
     return mock_module
Exemple #28
0
    def test_find_bind_mounts_no_findmnts(self):
        module = Mock()
        module.get_bin_path = Mock(return_value=None)
        lh = facts.LinuxHardware(module=module, load_on_init=False)
        bind_mounts = lh._find_bind_mounts()

        self.assertIsInstance(bind_mounts, set)
        self.assertEqual(len(bind_mounts), 0)
Exemple #29
0
    def test_lsblk_uuid_no_lsblk(self):
        module = Mock()
        module.get_bin_path = Mock(return_value=None)
        lh = facts.LinuxHardware(module=module, load_on_init=False)
        lsblk_uuids = lh._lsblk_uuid()

        self.assertIsInstance(lsblk_uuids, dict)
        self.assertEquals(len(lsblk_uuids), 0)
Exemple #30
0
 def _mock_module(self):
     mock_module = Mock()
     mock_module.params = {'gather_subset': self.gather_subset,
                           'gather_timeout': 10,
                           'filter': '*'}
     mock_module.get_bin_path = Mock(return_value='/usr/bin/lsb_release')
     mock_module.run_command = Mock(return_value=(0, lsb_release_a_fedora_output, ''))
     return mock_module
Exemple #31
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
Exemple #33
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_run_single_command(self, *args):
        set_module_args(dict(
            commands=[
                "tmsh show sys version"
            ],
            server='localhost',
            user='******',
            password='******'
        ))

        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)

        # 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
Exemple #35
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':
            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
Exemple #36
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)
Exemple #37
0
    def setUpClass(cls):
        class MockException(Exception):
            pass

        cls.MockException = MockException

        m = MagicMock()
        cls.cs_vserver_mock = MagicMock()
        cls.cs_vserver_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.csvserver': m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver.csvserver': m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver_cspolicy_binding': m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver_cspolicy_binding.csvserver_cspolicy_binding': m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver_lbvserver_binding': m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver_lbvserver_binding.csvserver_lbvserver_binding': m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.ssl': m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.ssl.sslvserver_sslcertkey_binding': m,
            'nssrc.com.citrix.netscaler.nitro.resource.config.ssl.sslvserver_sslcertkey_binding.sslvserver_sslcertkey_binding': m,
        }

        cls.nitro_specific_patcher = patch.dict(sys.modules, nssrc_modules_mock)
        cls.nitro_base_patcher = nitro_base_patcher
    def test_botocore_exception_without_response_reports_nicely_via_fail_json_aws(
            self):
        basic._ANSIBLE_ARGS = to_bytes(
            json.dumps({
                'ANSIBLE_MODULE_ARGS': {
                    '_ansible_tmpdir': '/tmp/ansible-abc'
                }
            }))
        module = AnsibleAWSModule(argument_spec=dict(
            fail_mode=dict(type='list', default=['success'])))

        fail_json_double = Mock()
        err_msg = None
        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"

        assert("test_botocore_exception_without_response_reports_nicely_via_fail_json_aws"
               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])
    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)
    def test_activate_import_from_file(self, *args):
        set_module_args(
            dict(
                name='fake_policy',
                file=self.policy,
                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)

        # 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['file'] == self.policy
        assert results['active'] is True
    def test_create_policy_rule_idempotent_check(self, *args):
        set_module_args(dict(
            name="rule1",
            state='present',
            policy='policy1',
            actions=[
                dict(
                    type='forward',
                    pool='baz'
                )
            ],
            conditions=[
                dict(
                    type='http_uri',
                    path_begins_with_any=['/ABC']
                )
            ],
            password='******',
            server='localhost',
            user='******'
        ))

        current = ApiParameters(load_fixture('load_ltm_policy_draft_rule_http-uri_forward.json'))
        client = AnsibleF5Client(
            argument_spec=self.spec.argument_spec,
            supports_check_mode=self.spec.supports_check_mode,
            f5_product_name=self.spec.f5_product_name
        )

        # Override methods to force specific logic in the module to happen
        mm = ModuleManager(client)
        mm.exists = Mock(return_value=True)
        mm.read_current_from_device = Mock(return_value=current)
        mm.draft_exists = Mock(return_value=False)
        mm.update_on_device = Mock(return_value=True)
        mm._create_existing_policy_draft_on_device = Mock(return_value=True)
        mm.publish_on_device = Mock(return_value=True)

        results = mm.exec_module()

        assert results['changed'] is True
    def test_import_from_template(self, *args):
        set_module_args(dict(
            name='fake_policy',
            template='LotusDomino 6.5 (http)',
            state='present',
            server='localhost',
            password='******',
            user='******',
        ))

        current = V1Parameters(load_fixture('load_asm_policy_inactive.json'))
        client = AnsibleF5Client(
            argument_spec=self.spec.argument_spec,
            supports_check_mode=self.spec.supports_check_mode,
            f5_product_name=self.spec.f5_product_name
        )

        # Override methods to force specific logic in the module to happen
        v1 = V1Manager(client)
        v1.exists = Mock(return_value=False)
        v1.create_from_template_on_device = Mock(return_value=True)
        v1.wait_for_task = Mock(side_effect=[True, True])
        v1.read_current_from_device = Mock(return_value=current)
        v1._file_is_missing = Mock(return_value=False)

        # Override methods to force specific logic in the module to happen
        mm = ModuleManager(client)
        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'] == 'LotusDomino 6.5 (http)'
        assert results['active'] is False
Exemple #43
0
    def test_raw_test_environment_is_None(self):

        play_context = Mock()
        task = MagicMock(Task)
        task. async = MagicMock()
        connection = Mock()

        task.args = {'_raw_params': 'Args1'}
        task.environment = None
        play_context.check_mode = False

        self.mock_am = ActionModule(task,
                                    connection,
                                    play_context,
                                    loader=None,
                                    templar=None,
                                    shared_loader_obj=None)
        self.mock_am._low_level_execute_command = Mock(return_value={})
        self.mock_am.display = Mock()

        self.assertEqual(task.environment, None)
    def test_get_typed_pool_facts(self, *args):
        set_module_args(dict(
            include='pool',
            password='******',
            server='localhost',
            user='******'
        ))

        fixture1 = load_fixture('load_gtm_pool_a_collection.json')
        fixture2 = load_fixture('load_gtm_pool_a_example_stats.json')
        collection = [FakeARecord(attrs=x) for x in fixture1['items']]
        stats = Stats(FakeStatResource(fixture2['entries']))

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

        # Override methods in the specific type of manager
        tfm = TypedPoolFactManager(client)
        tfm.read_collection_from_device = Mock(return_value=collection)
        tfm.read_stats_from_device = Mock(return_value=stats.stat)

        tm = PoolFactManager(client)
        tm.version_is_less_than_12 = Mock(return_value=False)
        tm.get_manager = Mock(return_value=tfm)

        # Override methods to force specific logic in the module to happen
        mm = ModuleManager(client)
        mm.get_manager = Mock(return_value=tm)
        mm.gtm_provisioned = Mock(return_value=True)

        results = mm.exec_module()

        assert results['changed'] is True
        assert 'pool' in results
        assert len(results['pool']) > 0
        assert 'load_balancing_mode' in results['pool'][0]
Exemple #45
0
    def test_raw_executable_is_not_empty_string(self):

        play_context = Mock()
        task = MagicMock(Task)
        task. async = MagicMock()
        connection = Mock()

        task.args = {'_raw_params': 'Args1'}
        play_context.check_mode = False

        self.mock_am = ActionModule(task,
                                    connection,
                                    play_context,
                                    loader=None,
                                    templar=None,
                                    shared_loader_obj=None)
        self.mock_am._low_level_execute_command = Mock(return_value={})
        self.mock_am.display = Mock()

        self.mock_am.run()
        self.mock_am._low_level_execute_command.assert_called_with(
            'Args1', executable=False)
Exemple #46
0
    def test_raw_check_mode_is_True(self):

        play_context = Mock()
        task = MagicMock(Task)
        task. async = MagicMock()
        connection = Mock()

        task.args = {'_raw_params': 'Args1'}
        play_context.check_mode = True

        self.mock_am = ActionModule(task,
                                    connection,
                                    play_context,
                                    loader=None,
                                    templar=None,
                                    shared_loader_obj=None)
        self.mock_am._low_level_execute_command = Mock(return_value={})
        self.mock_am.display = Mock()

        skipped_result = self.mock_am.run()

        self.assertEqual(skipped_result.get('skipped'), True)
Exemple #47
0
    def test_update_pool(self, *args):
        set_module_args(dict(
            name='foo',
            preferred_lb_method='topology',
            alternate_lb_method='drop-packet',
            fallback_lb_method='cpu',
            type='a',
            password='******',
            server='localhost',
            user='******'
        ))

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

        current = Parameters(load_fixture('load_gtm_pool_a_default.json'))

        # Override methods in the specific type of manager
        tm = TypedManager(client)
        tm.exists = Mock(side_effect=[True, True])
        tm.update_on_device = Mock(return_value=True)
        tm.read_current_from_device = Mock(return_value=current)

        # Override methods to force specific logic in the module to happen
        mm = ModuleManager(client)
        mm.version_is_less_than_12 = Mock(return_value=False)
        mm.get_manager = Mock(return_value=tm)
        mm.gtm_provisioned = Mock(return_value=True)

        results = mm.exec_module()

        assert results['changed'] is True
        assert results['preferred_lb_method'] == 'topology'
        assert results['alternate_lb_method'] == 'drop-packet'
        assert results['fallback_lb_method'] == 'cpu'
Exemple #48
0
    def test_create(self, *args):
        set_module_args(
            dict(license_key='xxxx-yyyy-zzzz',
                 license_server='foo-license.f5.com',
                 accept_eula=True,
                 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.exists = Mock(side_effect=[False, True])
        mm.read_dossier_from_device = Mock(return_value=True)
        mm.generate_license_from_remote = Mock(return_value=True)
        mm.upload_license_to_device = Mock(return_value=True)
        mm.upload_eula_to_device = Mock(return_value=True)
        mm.reload_license = Mock(return_value=True)

        results = mm.exec_module()
        assert results['changed'] is True
Exemple #49
0
    def test_absent_cs_vserver_execution_flow(self):
        set_module_args(dict(
            nitro_user='******',
            nitro_pass='******',
            nsip='192.0.2.1',
            state='absent',
        ))
        from ansible.modules.network.netscaler import netscaler_cs_vserver

        client_mock = Mock()

        m = Mock(return_value=client_mock)

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

        with patch.multiple(
            'ansible.modules.network.netscaler.netscaler_cs_vserver',
            get_nitro_client=m,
            diff_list=Mock(return_value={}),
            get_immutables_intersection=Mock(return_value=[]),
            cs_vserver_exists=Mock(side_effect=[True, False]),
            cs_vserver_identical=Mock(side_effect=[False, True]),
            ensure_feature_is_enabled=Mock(return_value=True),
            ConfigProxy=config_proxy_mock,
        ):
            self.module = netscaler_cs_vserver
            self.exited()
            cs_vserver_proxy_mock.assert_has_calls([call.delete()])
Exemple #50
0
    def test_present_server_failed_create(self):
        set_module_args(
            dict(
                nitro_user='******',
                nitro_pass='******',
                nsip='1.1.1.1',
                state='present',
            ))
        from ansible.modules.network.netscaler import netscaler_server

        client_mock = Mock()

        m = Mock(return_value=client_mock)

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

        with patch.multiple(
                'ansible.modules.network.netscaler.netscaler_server',
                nitro_exception=self.MockException,
                get_nitro_client=m,
                diff_list=Mock(return_value={}),
                get_immutables_intersection=Mock(return_value=[]),
                server_exists=Mock(side_effect=[False, False]),
                server_identical=Mock(side_effect=[False, False]),
                ConfigProxy=config_proxy_mock,
                do_state_change=Mock(return_value=Mock(errorcode=0))):
            self.module = netscaler_server
            result = self.failed()
            self.assertEqual(result['msg'], 'Server does not seem to exist')
            self.assertTrue(result['failed'])
Exemple #51
0
    def test_cs_vserver_ssl_not_called(self):
        set_module_args(dict(
            nitro_user='******',
            nitro_pass='******',
            nsip='192.0.2.1',
            state='present',
        ))
        from ansible.modules.network.netscaler import netscaler_cs_vserver

        client_mock = Mock()

        m = Mock(return_value=client_mock)

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

        with patch.multiple(
            'ansible.modules.network.netscaler.netscaler_cs_vserver',
            nitro_exception=self.MockException,
            get_nitro_client=m,
            diff_list=Mock(return_value={}),
            get_immutables_intersection=Mock(return_value=[]),
            cs_vserver_exists=Mock(side_effect=[True, True]),
            cs_vserver_identical=Mock(side_effect=[False, True]),
            ensure_feature_is_enabled=Mock(return_value=True),
            ssl_certkey_bindings_identical=Mock(side_effect=[False, True]),
            ssl_certkey_bindings_sync=ssl_certkey_bindings_sync_mock,
            do_state_change=Mock(return_value=Mock(errorcode=0)),
            ConfigProxy=config_proxy_mock,
        ):
            self.module = netscaler_cs_vserver
            result = self.exited()
            self.assertTrue(result['changed'])
            self.assertFalse(ssl_certkey_bindings_sync_mock.called)
Exemple #52
0
    def test_absent_server_noop_flow(self):
        set_module_args(
            dict(
                nitro_user='******',
                nitro_pass='******',
                nsip='192.0.2.1',
                state='absent',
            ))
        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',
                get_nitro_client=m,
                diff_list=Mock(return_value={}),
                get_immutables_intersection=Mock(return_value=[]),
                key_exists=Mock(side_effect=[False, False]),
                key_identical=Mock(side_effect=[False, False]),
                ConfigProxy=config_proxy_mock,
        ):
            self.module = netscaler_ssl_certkey
            self.exited()
            ssl_certkey_proxy_mock.assert_not_called()
Exemple #53
0
    def test_absent_server_failed_delete(self):
        set_module_args(
            dict(
                nitro_user='******',
                nitro_pass='******',
                nsip='192.0.2.1',
                state='absent',
            ))
        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=[]),
                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'], 'SSL certkey still exists')
            self.assertTrue(result['failed'])
Exemple #54
0
    def test_new_ssl_certkey_execution_flow(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',
                get_nitro_client=m,
                key_exists=Mock(side_effect=[False, True]),
                key_identical=Mock(side_effect=[True]),
                ConfigProxy=config_proxy_mock,
        ):
            self.module = netscaler_ssl_certkey
            self.exited()
            ssl_certkey_proxy_mock.assert_has_calls([call.add()])
Exemple #55
0
    def test_new_cs_vserver_execution_flow(self):
        set_module_args(dict(
            nitro_user='******',
            nitro_pass='******',
            nsip='192.0.2.1',
            state='present',
        ))
        from ansible.modules.network.netscaler import netscaler_cs_vserver

        client_mock = Mock()

        m = Mock(return_value=client_mock)

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

        with patch.multiple(
            'ansible.modules.network.netscaler.netscaler_cs_vserver',
            get_nitro_client=m,
            cs_vserver_exists=Mock(side_effect=[False, True]),
            cs_vserver_identical=Mock(side_effect=[True]),
            ensure_feature_is_enabled=Mock(return_value=True),
            ConfigProxy=config_proxy_mock,
            nitro_exception=self.MockException,
            do_state_change=Mock(return_value=Mock(errorcode=0)),
        ):
            self.module = netscaler_cs_vserver
            self.exited()
            cs_vserver_proxy_mock.assert_has_calls([call.add()])
Exemple #56
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'])
Exemple #57
0
    def test_present_cs_vserver_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_cs_vserver

        client_mock = Mock()

        m = Mock(return_value=client_mock)

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

        with patch.multiple(
            'ansible.modules.network.netscaler.netscaler_cs_vserver',
            nitro_exception=self.MockException,
            get_nitro_client=m,
            diff_list=Mock(return_value={}),
            get_immutables_intersection=Mock(return_value=['domain']),
            cs_vserver_exists=Mock(side_effect=[True, True]),
            cs_vserver_identical=Mock(side_effect=[False, False]),
            ensure_feature_is_enabled=Mock(return_value=True),
            ConfigProxy=config_proxy_mock,
        ):
            self.module = netscaler_cs_vserver
            result = self.failed()
            self.assertEqual(result['msg'], 'Cannot update immutable attributes [\'domain\']')
            self.assertTrue(result['failed'])
    def test_present_gslb_site_failed_create(self):
        set_module_args(
            dict(
                nitro_user='******',
                nitro_pass='******',
                nsip='192.0.2.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=[False, False]),
                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 does not exist')
            self.assertTrue(result['failed'])
Exemple #59
0
    def test_module_utils_basic_ansible_module_set_context_if_different(self):
        from ansible.module_utils import basic

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

        basic.HAS_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.HAS_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')
    def test_modified_gslb_site_execution_flow(self):
        set_module_args(
            dict(
                nitro_user='******',
                nitro_pass='******',
                nsip='192.0.2.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',
                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, True]),
                ensure_feature_is_enabled=Mock(),
                nitro_exception=self.MockException,
                ConfigProxy=config_proxy_mock,
        ):
            self.module = netscaler_gslb_site
            self.exited()
            gslb_site_proxy_mock.assert_has_calls([call.update()])