Beispiel #1
0
 def test_create_label_gpt(self):
     # Like previous test, current implementation use parted to create the partition and
     # then retrieve and update the dictionary. Use check_mode to force to continue even if
     # dictionary is not updated.
     set_module_args({
         'device': '/dev/sdb',
         'number': 1,
         'flags': ["lvm"],
         'label': 'gpt',
         'name': 'lvmpartition',
         'state': 'present',
         '_ansible_check_mode': True,
     })
     with patch('ansible_collections.community.general.plugins.modules.parted.get_device_info', return_value=parted_dict2):
         self.execute_module(changed=True, script='unit KiB mklabel gpt mkpart primary 0% 100% unit KiB name 1 \'"lvmpartition"\' set 1 lvm on')
Beispiel #2
0
def test_instance_by_label_cannot_authenticate(capfd, access_token,
                                               default_args):
    set_module_args(default_args)
    module = linode_v4.initialise_module()
    client = LinodeClient(module.params['access_token'])

    target = 'linode_api4.linode_client.LinodeGroup.instances'
    with mock.patch(target, side_effect=LinodeApiError('foo')):
        with pytest.raises(SystemExit):
            linode_v4.maybe_instance_from_label(module, client)

    out, err = capfd.readouterr()
    results = json.loads(out)

    assert results['failed'] is True
    assert 'Unable to query the Linode API' in results['msg']
Beispiel #3
0
 def test_nitro_user_pass_credentials(self):
     args = copy.deepcopy(module_arguments)
     args.update(dict(
         nitro_user='******',
         nitro_pass='******',
     ))
     mock_module_instance = Mock(params=args)
     expected_headers = {
         'Content-Type': 'application/json',
         'X-NITRO-USER': '******',
         'X-NITRO-PASS': '******',
     }
     module_mock = Mock(return_value=mock_module_instance)
     with patch('ansible_collections.community.general.plugins.modules.network.netscaler.netscaler_nitro_request.AnsibleModule', module_mock):
         instance = netscaler_nitro_request.NitroAPICaller()
         self.assertDictEqual(instance._headers, expected_headers)
Beispiel #4
0
    def setUp(self):
        self._ptp_enabled = True
        self._ntp_enabled = True
        super(TestOnyxPtpModule, self).setUp()

        self.mock_get_ptp_config = patch.object(
            onyx_ptp_global.OnyxPtpGlobalModule, "_show_ptp_config")
        self.get_ptp_config = self.mock_get_ptp_config.start()
        self.mock_get_ntp_config = patch.object(
            onyx_ptp_global.OnyxPtpGlobalModule, "_show_ntp_config")
        self.get_ntp_config = self.mock_get_ntp_config.start()

        self.mock_load_config = patch(
            'ansible_collections.community.general.plugins.module_utils.network.onyx.onyx.load_config'
        )
        self.load_config = self.mock_load_config.start()
    def setUp(self):
        super(TestOnyxOspfModule, self).setUp()
        self._ospf_exists = True
        self.mock_get_config = patch.object(
            onyx_ospf.OnyxOspfModule,
            "_get_ospf_config")
        self.get_config = self.mock_get_config.start()

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

        self.mock_load_config = patch(
            'ansible_collections.community.general.plugins.module_utils.network.onyx.onyx.load_config')
        self.load_config = self.mock_load_config.start()
Beispiel #6
0
 def test_change_label_gpt(self):
     # When partitions already exists and label is changed, mkpart should be called even when partition already exists,
     # because new empty label will be created anyway
     set_module_args({
         'device': '/dev/sdb',
         'number': 1,
         'state': 'present',
         'label': 'gpt',
         '_ansible_check_mode': True,
     })
     with patch(
             'ansible_collections.community.general.plugins.modules.system.parted.get_device_info',
             return_value=parted_dict1):
         self.execute_module(
             changed=True,
             script='unit KiB mklabel gpt mkpart primary 0% 100%')
Beispiel #7
0
 def test_when_namespace0_without_size(self):
     set_module_args({
         'namespace': [
             {
                 'type': 'pmem',
                 'mode': 'sector'
             },
         ],
     })
     with patch(
             'ansible_collections.community.general.plugins.modules.storage.pmem.pmem.PersistentMemory.pmem_run_command',
             side_effect=[
                 ndctl_region, ndctl_create_without_size, ndctl_list_N
             ]):
         with self.assertRaises(AnsibleExitJson) as result:
             pmem_module.main()
         self.result_check_ns(result, ndctl_list_N)
Beispiel #8
0
 def test_mas_proxy_call_headers_instance_name(self):
     args = copy.deepcopy(module_arguments)
     args.update(dict(
         nitro_auth_token='##ABDB',
         operation='add',
         instance_name='myname',
     ))
     mock_module_instance = Mock(params=args)
     expected_headers = {
         'Content-Type': 'application/json',
         '_MPS_API_PROXY_MANAGED_INSTANCE_NAME': args['instance_name'],
         'Cookie': 'NITRO_AUTH_TOKEN=%s' % args['nitro_auth_token'],
     }
     module_mock = Mock(return_value=mock_module_instance)
     with patch('ansible_collections.community.general.plugins.modules.network.netscaler.netscaler_nitro_request.AnsibleModule', module_mock):
         instance = netscaler_nitro_request.NitroAPICaller()
         self.assertDictEqual(instance._headers, expected_headers)
    def setUp(self):
        super(TestOnyxTrafficClassModule, self).setUp()
        self.mock_get_congestion_control_config = patch.object(
            onyx_traffic_class.OnyxTrafficClassModule,
            "_show_interface_congestion_control")
        self.get_congestion_control_config = self.mock_get_congestion_control_config.start(
        )

        self.mock_load_config = patch(
            'ansible_collections.community.general.plugins.module_utils.network.onyx.onyx.load_config'
        )
        self.load_config = self.mock_load_config.start()

        self.mock_get_dcb_config = patch.object(
            onyx_traffic_class.OnyxTrafficClassModule,
            "_show_interface_dcb_ets")
        self.get_dcb_config = self.mock_get_dcb_config.start()
Beispiel #10
0
    def test_add_annotation(self):
        """Check that result is changed"""
        set_module_args({
            'category': 'test category',
            'description': 'test description',
            'title': 'test title',
            'api_key': str(uuid.uuid4()),
        })

        cid = '/annotation/100000'

        def send(self,
                 request,
                 stream=False,
                 timeout=None,
                 verify=True,
                 cert=None,
                 proxies=None):
            data = {
                '_cid': cid,
                '_created': 1502146995,
                '_last_modified': 1502146995,
                '_last_modified_by': '/user/1000',
                'category': 'test category',
                'description': 'test description',
                'rel_metrics': [],
                'start': 1502145480,
                'stop': None,
                'title': 'test title',
            }
            raw = to_bytes(json.dumps(data))
            resp = HTTPResponse(body=io.BytesIO(raw), preload_content=False)
            resp.status = 200
            resp.reason = 'OK'
            resp.headers = {'X-Circonus-API-Version': '2.00'}
            return self.build_response(request, resp)

        with patch('requests.adapters.HTTPAdapter.send',
                   autospec=True,
                   side_effect=send) as send:
            with self.assertRaises(AnsibleExitJson) as result:
                self.module.main()
            self.assertTrue(result.exception.args[0]['changed'])
            self.assertEqual(result.exception.args[0]['annotation']['_cid'],
                             cid)
        self.assertEqual(send.call_count, 1)
Beispiel #11
0
def test_instance_already_deleted_no_change(default_args, mock_linode, capfd,
                                            access_token):
    default_args.update({'state': 'absent'})
    set_module_args(default_args)

    target = 'linode_api4.linode_client.LinodeGroup.instances'
    with mock.patch(target, return_value=[]):
        with pytest.raises(SystemExit) as sys_exit_exc:
            linode_v4.main()

    assert sys_exit_exc.value.code == 0

    out, err = capfd.readouterr()
    results = json.loads(out)

    assert results['changed'] is False
    assert results['instance'] == {}
Beispiel #12
0
    def test_from_params(self):
        with patch(make_absolute('HAS_TSS_AUTHORIZER'), False):
            self.assert_client_version('v0')

            with patch.dict(self.server_params, {'domain': 'foo'}):
                with self.assertRaises(tss.AnsibleError):
                    self._get_client()

        with patch.multiple(TSS_IMPORT_PATH,
                            HAS_TSS_AUTHORIZER=True,
                            PasswordGrantAuthorizer=DEFAULT,
                            DomainPasswordGrantAuthorizer=DEFAULT):

            self.assert_client_version('v1')

            with patch.dict(self.server_params, {'domain': 'foo'}):
                self.assert_client_version('v1')
Beispiel #13
0
 def test_create_new_primary_lvm_partition(self):
     # use check_mode, see previous test comment
     set_module_args({
         'device': '/dev/sdb',
         'number': 4,
         'flags': ["boot"],
         'state': 'present',
         'part_start': '257GiB',
         '_ansible_check_mode': True,
     })
     with patch(
             'ansible_collections.community.general.plugins.modules.system.parted.get_device_info',
             return_value=parted_dict1):
         self.execute_module(
             changed=True,
             script=
             'unit KiB mkpart primary 257GiB 100% unit KiB set 4 boot on')
Beispiel #14
0
    def test_update_configuration(self):
        """Validate updating the configuration"""
        initial = dict(alertingEnabled=True,
                       emailServerAddress='localhost',
                       sendAdditionalContactInformation=True,
                       additionalContactInformation='None',
                       emailSenderAddress='[email protected]',
                       recipientEmailAddresses=['[email protected]'])

        args = dict(state='enabled',
                    server=initial['emailServerAddress'],
                    sender=initial['emailSenderAddress'],
                    contact=initial['additionalContactInformation'],
                    recipients=initial['recipientEmailAddresses'])

        self._set_args(**args)

        alerts = Alerts()

        # Ensure when trigger updates when each relevant field is changed
        with mock.patch(self.REQ_FUNC, return_value=(200, None)) as req:
            with mock.patch.object(alerts,
                                   'get_configuration',
                                   return_value=initial):
                update = alerts.update_configuration()
                self.assertFalse(update)

                alerts.sender = '[email protected]'
                update = alerts.update_configuration()
                self.assertTrue(update)
                self._set_args(**args)

                alerts.recipients = ['[email protected]']
                update = alerts.update_configuration()
                self.assertTrue(update)
                self._set_args(**args)

                alerts.contact = 'abc'
                update = alerts.update_configuration()
                self.assertTrue(update)
                self._set_args(**args)

                alerts.server = 'abc'
                update = alerts.update_configuration()
                self.assertTrue(update)
    def test_upload_file(self):
        self.connection_mock.send.return_value = self._connection_response(
            {'id': '123'})

        open_mock = mock_open()
        with patch('%s.open' % BUILTINS_NAME, open_mock):
            resp = self.ftd_plugin.upload_file('/tmp/test.txt', '/files')

        assert {'id': '123'} == resp
        exp_headers = dict(BASE_HEADERS)
        exp_headers['Content-Length'] = len('--Encoded data--')
        exp_headers['Content-Type'] = 'multipart/form-data'
        self.connection_mock.send.assert_called_once_with(
            '/files',
            data='--Encoded data--',
            headers=exp_headers,
            method=HTTPMethod.POST)
        open_mock.assert_called_once_with('/tmp/test.txt', 'rb')
    def test_cert_changed_fingerprint_mismatch(self):
        set_module_args(
            dict(certificate='cert-foo',
                 private_key='private-foo',
                 dest='/path/to/keystore.jks',
                 name='foo',
                 password='******'))

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

        with patch('os.remove', return_value=True):
            self.run_commands.side_effect = [(0, 'foo=abcd:1234:efgh', ''),
                                             (0, 'SHA256: wxyz:9876:stuv', '')]
            result = cert_changed(module, "openssl", "keytool",
                                  "/path/to/keystore.jks", "changeit", 'foo')
            self.assertTrue(result, 'Fingerprint mismatch')
Beispiel #17
0
def test_instance_already_created(default_args, mock_linode, capfd,
                                  access_token):
    default_args.update({'type': 'foo', 'region': 'bar', 'image': 'baz'})
    set_module_args(default_args)

    target = 'linode_api4.linode_client.LinodeGroup.instances'
    with mock.patch(target, return_value=[mock_linode]):
        with pytest.raises(SystemExit) as sys_exit_exc:
            linode_v4.main()

    assert sys_exit_exc.value.code == 0

    out, err = capfd.readouterr()
    results = json.loads(out)

    assert results['changed'] is False
    assert 'root_password' not in results['instance']
    assert (results['instance']['label'] == mock_linode._raw_json['label'])
Beispiel #18
0
    def test_edit_response_data_no_body_fail_status(self):
        with patch('ansible_collections.community.general.plugins.modules.network.netscaler.netscaler_nitro_request.AnsibleModule'):
            instance = netscaler_nitro_request.NitroAPICaller()
            r = None
            info = {
                'status': 201,
            }
            result = {}
            success_status = 200

            expected_result = {
                'nitro_errorcode': -1,
                'nitro_message': 'HTTP status %s' % info['status'],
                'nitro_severity': 'ERROR',
                'http_response_body': '',
                'http_response_data': info,
            }
            instance.edit_response_data(r, info, result, success_status)
            self.assertDictEqual(result, expected_result)
Beispiel #19
0
 def test_fail_when_size_isnot_set_to_multiple_namespaces(self):
     with self.assertRaises(AnsibleFailJson):
         set_module_args({
             'namespace': [
                 {
                     'type': 'pmem',
                     'mode': 'sector'
                 },
                 {
                     'size': '500GB',
                     'type': 'blk',
                     'mode': 'sector'
                 },
             ],
         })
         with patch(
                 'ansible_collections.community.general.plugins.modules.storage.pmem.pmem.PersistentMemory.pmem_run_command',
                 side_effect=[ndctl_region]):
             pmem_module.main()
    def test_cert_changed_alias_does_not_exist(self):
        set_module_args(dict(
            certificate='cert-foo',
            private_key='private-foo',
            dest='/path/to/keystore.jks',
            name='foo',
            password='******'
        ))

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

        with patch('os.remove', return_value=True):
            self.run_commands.side_effect = [(0, 'foo=abcd:1234:efgh', ''),
                                             (1, 'keytool error: java.lang.Exception: Alias <foo> does not exist', '')]
            result = cert_changed(module, "openssl", "keytool", "/path/to/keystore.jks", "changeit", 'foo')
            self.assertTrue(result, 'Certificate does not exist')
Beispiel #21
0
 def test_fail_on_conflicting_authentication_methods(self):
     args = copy.deepcopy(module_arguments)
     args.update(dict(
         nitro_user='******',
         nitro_pass='******',
         nitro_auth_token='##DDASKLFDJ',
     ))
     mock_module_instance = Mock(params=args)
     expected_calls = [
         call.fail_json(
             changed=False,
             failed=True,
             msg='Cannot define both authentication token and username/password'
         )
     ]
     module_mock = Mock(return_value=mock_module_instance)
     with patch('ansible_collections.community.general.plugins.modules.network.netscaler.netscaler_nitro_request.AnsibleModule', module_mock):
         netscaler_nitro_request.NitroAPICaller()
         mock_module_instance.assert_has_calls(expected_calls)
Beispiel #22
0
    def test_threshold_argument_pass(self):
        """Verify AuditLog arument's max_records and threshold upper and lower boundaries."""
        initial = {
            "max_records": 1000,
            "log_level": "writeOnly",
            "full_policy": "overWrite",
            "threshold": 90
        }
        threshold_set = (60, 75, 90)

        for threshold in threshold_set:
            initial["threshold"] = threshold
            self._set_args(**initial)
            with mock.patch(self.REQ_FUNC,
                            return_value=(200, {
                                "runningAsProxy": False
                            })):
                audit_log = AuditLog()
                self.assertTrue(audit_log.threshold == threshold)
Beispiel #23
0
    def test_update_configuration_request_exception(self):
        """Validate exception handling when request throws an exception."""
        config_response = dict(asupEnabled=True,
                               onDemandEnabled=True,
                               remoteDiagsEnabled=True,
                               schedule=dict(daysOfWeek=[],
                                             dailyMinTime=0,
                                             weeklyMinTime=0,
                                             dailyMaxTime=24,
                                             weeklyMaxTime=24))

        self._set_args(dict(state="enabled"))
        asup = Asup()
        with self.assertRaises(Exception):
            with mock.patch.object(asup,
                                   'get_configuration',
                                   return_value=config_response):
                with mock.patch(self.REQ_FUNC, side_effect=Exception):
                    asup.update_configuration()
    def test_add_annotation_unicode(self):
        """Check that result is changed.
           Note: it seems there is a bug which prevent to create an annotation
           with a non-ASCII category if this category already exists, in such
           case an Internal Server Error (500) occurs."""
        set_module_args({
            'category': 'new catégorÿ',
            'description': 'test description',
            'title': 'test title',
            'api_key': str(uuid.uuid4()),
        })

        cid = '/annotation/100000'

        def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
            data = {
                '_cid': '/annotation/100000',
                '_created': 1502236928,
                '_last_modified': 1502236928,
                '_last_modified_by': '/user/1000',
                # use res['annotation']['category'].encode('latin1').decode('utf8')
                'category': u'new cat\xc3\xa9gor\xc3\xbf',
                'description': 'test description',
                'rel_metrics': [],
                'start': 1502236927,
                'stop': 1502236927,
                'title': 'test title',
            }

            raw = to_bytes(json.dumps(data), encoding='latin1')
            resp = HTTPResponse(body=io.BytesIO(raw), preload_content=False)
            resp.status = 200
            resp.reason = 'OK'
            resp.headers = {'X-Circonus-API-Version': '2.00'}
            return self.build_response(request, resp)

        with patch('requests.adapters.HTTPAdapter.send', autospec=True, side_effect=send) as send:
            with self.assertRaises(AnsibleExitJson) as result:
                self.module.main()
            self.assertTrue(result.exception.args[0]['changed'])
            self.assertEqual(result.exception.args[0]['annotation']['_cid'], cid)
        self.assertEqual(send.call_count, 1)
Beispiel #25
0
    def test_exec_with_become_no_plugin_set(self, test_win_updates):
        set_become_mock = MagicMock()
        test_win_updates._connection.become = None
        test_win_updates._connection.set_become_plugin = set_become_mock

        with patch('ansible.plugins.action.ActionBase._execute_module',
                   new=MagicMock()):
            test_win_updates._execute_module_with_become(
                'win_updates', {}, {}, True, False)

        assert set_become_mock.call_count == 2
        assert isinstance(set_become_mock.mock_calls[0][1][0], BecomeModule)
        assert set_become_mock.mock_calls[0][1][0].name == 'runas'
        assert set_become_mock.mock_calls[0][1][0].get_option(
            'become_user') == 'SYSTEM'
        assert set_become_mock.mock_calls[0][1][0].get_option(
            'become_flags') == ''
        assert set_become_mock.mock_calls[0][1][0].get_option(
            'become_pass') is None
        assert set_become_mock.mock_calls[1][1] == (None, )
Beispiel #26
0
    def test_max_records_argument_pass(self):
        """Verify AuditLog arument's max_records and threshold upper and lower boundaries."""
        initial = {
            "max_records": 1000,
            "log_level": "writeOnly",
            "full_policy": "overWrite",
            "threshold": 90
        }
        max_records_set = (self.MAX_RECORDS_MINIMUM, 25000,
                           self.MAX_RECORDS_MAXIMUM)

        for max_records in max_records_set:
            initial["max_records"] = max_records
            self._set_args(**initial)
            with mock.patch(self.REQ_FUNC,
                            return_value=(200, {
                                "runningAsProxy": False
                            })):
                audit_log = AuditLog()
                self.assertTrue(audit_log.max_records == max_records)
Beispiel #27
0
    def test_cert_changed_password_mismatch(self):
        set_module_args(dict(
            certificate='cert-foo',
            private_key='private-foo',
            dest='/path/to/keystore.jks',
            name='foo',
            password='******'
        ))

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

        with patch('os.remove', return_value=True):
            self.create_file.side_effect = ['/tmp/placeholder']
            self.run_commands.side_effect = [(0, 'foo=abcd:1234:efgh', ''),
                                             (1, 'keytool error: java.io.IOException: Keystore password was incorrect', '')]
            result = cert_changed(module, "openssl", "keytool", "/path/to/keystore.jks", "changeit", 'foo')
            self.assertTrue(result, 'Password mismatch detected')
    def test_cert_changed_fingerprint_mismatch(self):
        set_module_args(
            dict(certificate='cert-foo',
                 private_key='private-foo',
                 dest='/path/to/keystore.jks',
                 name='foo',
                 password='******'))

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

        with patch('os.remove', return_value=True):
            self.create_file.side_effect = ['/tmp/placeholder', '']
            self.run_command.side_effect = [(0, 'foo=abcd:1234:efgh', ''),
                                            (0, 'SHA256: wxyz:9876:stuv', '')]
            self.get_bin_path.side_effect = ['keytool', 'openssl', '']
            jks = JavaKeystore(module)
            result = jks.cert_changed()
            self.assertTrue(result, 'Fingerprint mismatch')
Beispiel #29
0
    def test_threshold_argument_fail(self):
        """Verify AuditLog arument's max_records and threshold upper and lower boundaries."""
        initial = {
            "max_records": 1000,
            "log_level": "writeOnly",
            "full_policy": "overWrite",
            "threshold": 90
        }
        threshold_set = (59, 91)

        for threshold in threshold_set:
            with self.assertRaisesRegexp(
                    AnsibleFailJson,
                    r"Audit-log percent threshold must be between 60 and 90"):
                initial["threshold"] = threshold
                self._set_args(**initial)
                with mock.patch(self.REQ_FUNC,
                                return_value=(200, {
                                    "runningAsProxy": False
                                })):
                    AuditLog()
Beispiel #30
0
    def setUp(self):
        super(TestOnyxInterfaceModule, self).setUp()
        self.mock_get_config = patch.object(
            onyx_interface.OnyxInterfaceModule, "_get_interfaces_config")
        self.get_config = self.mock_get_config.start()

        self.mock_get_interfaces_status = patch.object(
            onyx_interface.OnyxInterfaceModule, "_get_interfaces_status")
        self.get_interfaces_status = self.mock_get_interfaces_status.start()

        self.mock_get_interfaces_rates = patch.object(
            onyx_interface.OnyxInterfaceModule, "_get_interfaces_rates")
        self.get_interfaces_rates = self.mock_get_interfaces_rates.start()

        self.mock_load_config = patch(
            'ansible_collections.community.general.plugins.module_utils.network.onyx.onyx.load_config')
        self.load_config = self.mock_load_config.start()

        self.mock_get_version = patch.object(
            onyx_interface.OnyxInterfaceModule, "_get_os_version")
        self.get_version = self.mock_get_version.start()