Exemple #1
0
    def _test_update_resource(self,
                              resource,
                              cmd,
                              myid,
                              args,
                              extrafields,
                              cmd_resource=None,
                              parent_id=None):
        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        cmd.get_client().MultipleTimes().AndReturn(self.client)
        if not cmd_resource:
            cmd_resource = resource

        body = {resource: extrafields}
        path = getattr(self.client, cmd_resource + "_path")
        if parent_id:
            path = path % (parent_id, myid)
        else:
            path = path % myid
        self.client.format = self.format
        # Work around for LP #1217791. XML deserializer called from
        # MyComparator does not decodes XML string correctly.
        if self.format == 'json':
            mox_body = MyComparator(body, self.client)
        else:
            mox_body = self.client.serialize(body)
        self.client.httpclient.request(
            MyUrlComparator(end_url(path, format=self.format), self.client),
            'PUT',
            body=mox_body,
            headers=mox.ContainsKeyValue('X-Auth-Token', TOKEN)).AndReturn(
                (MyResp(204), None))
        args.extend(['--request-format', self.format])
        self.mox.ReplayAll()
        cmd_parser = cmd.get_parser("update_" + cmd_resource)
        shell.run_command(cmd, cmd_parser, args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
        _str = self.fake_stdout.make_string()
        self.assertIn(myid, _str)
    def _test_show_resource(self,
                            resource,
                            cmd,
                            myid,
                            args,
                            fields=(),
                            cmd_resource=None,
                            parent_id=None):
        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        cmd.get_client().MultipleTimes().AndReturn(self.client)
        if not cmd_resource:
            cmd_resource = resource

        query = "&".join(["fields=%s" % field for field in fields])
        expected_res = {
            resource: {
                self.id_field: myid,
                'name': 'myname',
            },
        }
        resstr = self.client.serialize(expected_res)
        path = getattr(self.client, cmd_resource + "_path")
        if parent_id:
            path = path % (parent_id, myid)
        else:
            path = path % myid
        self.client.httpclient.request(end_url(path, query),
                                       'GET',
                                       body=None,
                                       headers=mox.ContainsKeyValue(
                                           'X-Auth-Token', TOKEN)).AndReturn(
                                               (MyResp(200), resstr))
        self.mox.ReplayAll()
        cmd_parser = cmd.get_parser("show_" + cmd_resource)
        shell.run_command(cmd, cmd_parser, args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
        _str = self.fake_stdout.make_string()
        self.assertIn(myid, _str)
        self.assertIn('myname', _str)
Exemple #3
0
    def _test_add_to_hosting_device(self, resource, cmd, cmd_args, destination,
                                    body, result):
        path = ((hostingdevice.HostingDevice.resource_path + destination) %
                cmd_args[0])
        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        cmd.get_client().MultipleTimes().AndReturn(self.client)
        result_str = self.client.serialize(result)
        return_tup = (test_cli20.MyResp(200), result_str)

        self.client.httpclient.request(
            test_cli20.end_url(path), 'POST',
            body=test_cli20.MyComparator(body, self.client),
            headers=mox.ContainsKeyValue(
                'X-Auth-Token', test_cli20.TOKEN)).AndReturn(return_tup)
        self.mox.ReplayAll()
        cmd_parser = cmd.get_parser('test_' + resource)
        parsed_args = cmd_parser.parse_args(cmd_args)
        cmd.run(parsed_args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
Exemple #4
0
    def test_use_given_endpoint_url(self):
        self.client = client.HTTPClient(username=USERNAME,
                                        tenant_name=TENANT_NAME,
                                        password=PASSWORD,
                                        auth_url=AUTH_URL,
                                        region_name=REGION,
                                        endpoint_url=ENDPOINT_OVERRIDE)
        self.assertEqual(self.client.endpoint_url, ENDPOINT_OVERRIDE)

        self.mox.StubOutWithMock(self.client, "request")

        self.client.auth_token = TOKEN
        res200 = get_response(200)

        self.client.request(mox.StrContains(ENDPOINT_OVERRIDE + '/resource'),
                            'GET',
                            headers=mox.ContainsKeyValue(
                                'X-Auth-Token', TOKEN)).AndReturn((res200, ''))
        self.mox.ReplayAll()
        self.client.do_request('/resource', 'GET')
        self.assertEqual(self.client.endpoint_url, ENDPOINT_OVERRIDE)
 def _test_update_resource_action(self, resource, cmd, myid, action, args,
                                  body, retval=None, cmd_resource=None):
     self.mox.StubOutWithMock(cmd, "get_client")
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     cmd.get_client().MultipleTimes().AndReturn(self.client)
     if not cmd_resource:
         cmd_resource = resource
     path = getattr(self.client, cmd_resource + "_path")
     path_action = '%s/%s' % (myid, action)
     self.client.httpclient.request(
         end_url(path % path_action, format=self.format), 'PUT',
         body=MyComparator(body, self.client),
         headers=mox.ContainsKeyValue(
             'X-Auth-Token', TOKEN)).AndReturn((MyResp(204), retval))
     self.mox.ReplayAll()
     cmd_parser = cmd.get_parser("delete_" + cmd_resource)
     shell.run_command(cmd, cmd_parser, args)
     self.mox.VerifyAll()
     self.mox.UnsetStubs()
     _str = self.fake_stdout.make_string()
     self.assertIn(myid, _str)
Exemple #6
0
    def test_do_request_error_without_response_body(self):
        self.client.format = self.format
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        params = {'test': 'value'}
        expect_query = six.moves.urllib.parse.urlencode(params)
        self.client.httpclient.auth_token = 'token'

        self.client.httpclient.request(
            MyUrlComparator(end_url(
                '/test', query=expect_query, format=self.format), self.client),
            'PUT', body='',
            headers=mox.ContainsKeyValue('X-Auth-Token', 'token')
        ).AndReturn((MyResp(400, reason='An error'), ''))

        self.mox.ReplayAll()
        error = self.assertRaises(exceptions.NeutronClientException,
                                  self.client.do_request, 'PUT', '/test',
                                  body='', params=params)
        self.assertEqual("An error", str(error))
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
Exemple #7
0
 def test_get_id_from_name_multiple(self):
     name = 'myname'
     reses = {'networks': [{'id': str(uuid.uuid4())},
                           {'id': str(uuid.uuid4())}]}
     resstr = self.client.serialize(reses)
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     path = getattr(self.client, "networks_path")
     self.client.httpclient.request(
         test_cli20.MyUrlComparator(
             test_cli20.end_url(path, "fields=id&name=" + name),
             self.client),
         'GET',
         body=None,
         headers=mox.ContainsKeyValue('X-Auth-Token', test_cli20.TOKEN)
     ).AndReturn((test_cli20.MyResp(200), resstr))
     self.mox.ReplayAll()
     try:
         neutronV20.find_resourceid_by_name_or_id(
             self.client, 'network', name)
     except exceptions.NeutronClientNoUniqueMatch as ex:
         self.assertIn('Multiple', ex.message)
Exemple #8
0
    def _test_disassoc_with_cfg_agent(self, resource, cmd, cmd_args,
                                      destination):
        path = ((scheduler.ConfigAgentHandlingHostingDevice.resource_path +
                 destination + '/%s') % cmd_args)
        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        cmd.get_client().MultipleTimes().AndReturn(self.client)

        return_tup = (test_cli20.MyResp(204), None)
        self.client.httpclient.request(
            test_cli20.end_url(path),
            'DELETE',
            body=None,
            headers=mox.ContainsKeyValue(
                'X-Auth-Token', test_cli20.TOKEN)).AndReturn(return_tup)
        self.mox.ReplayAll()
        cmd_parser = cmd.get_parser('test_' + resource)
        parsed_args = cmd_parser.parse_args(cmd_args)
        cmd.run(parsed_args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
Exemple #9
0
 def test_get_id_from_name_notfound(self):
     name = 'myname'
     reses = {'networks': []}
     resstr = self.client.serialize(reses)
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     path = getattr(self.client, "networks_path")
     self.client.httpclient.request(
         test_cli20.MyUrlComparator(
             test_cli20.end_url(path, "fields=id&name=" + name),
             self.client),
         'GET',
         body=None,
         headers=mox.ContainsKeyValue('X-Auth-Token',
                                      test_cli20.TOKEN)).AndReturn(
                                          (test_cli20.MyResp(200), resstr))
     self.mox.ReplayAll()
     exception = self.assertRaises(exceptions.NotFound,
                                   neutronV20.find_resourceid_by_name_or_id,
                                   self.client, 'network', name)
     self.assertIn('Unable to find', exception.message)
     self.assertEqual(404, exception.status_code)
Exemple #10
0
    def test_do_request_error_without_response_body(self):
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        params = {'test': 'value'}
        expect_query = six.moves.urllib.parse.urlencode(params)
        self.client.httpclient.auth_token = 'token'
        resp_headers = {'x-openstack-request-id': REQUEST_ID}

        self.client.httpclient.request(
            MyUrlComparator(end_url('/test', query=expect_query), self.client),
            'PUT', body='',
            headers=mox.ContainsKeyValue('X-Auth-Token', 'token')
        ).AndReturn((MyResp(400, headers=resp_headers, reason='An error'), ''))

        self.mox.ReplayAll()
        error = self.assertRaises(exceptions.NeutronClientException,
                                  self.client.do_request, 'PUT', '/test',
                                  body='', params=params)
        expected_error = "An error\nNeutron server returns " \
                         "request_ids: %s" % [REQUEST_ID]
        self.assertEqual(expected_error, str(error))
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
    def _test_update_resource(self,
                              resource,
                              cmd,
                              myid,
                              args,
                              extrafields,
                              cmd_resource=None,
                              parent_id=None):
        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        cmd.get_client().MultipleTimes().AndReturn(self.client)
        if not cmd_resource:
            cmd_resource = resource

        body = {resource: extrafields}
        path = getattr(self.client, cmd_resource + "_path")

        if parent_id:
            path = path % (parent_id, myid)
        else:
            path = path % extrafields['vcenter_id']
        mox_body = MyComparator(body, self.client)

        self.client.httpclient.request(MyUrlComparator(end_url(path),
                                                       self.client),
                                       'PUT',
                                       body=mox_body,
                                       headers=mox.ContainsKeyValue(
                                           'X-Auth-Token', TOKEN)).AndReturn(
                                               (MyResp(204), None))
        self.mox.ReplayAll()
        cmd_parser = cmd.get_parser("update_" + cmd_resource)
        neutronshell.run_command(cmd, cmd_parser, args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
        _str = self.fake_stdout.make_string()
        # Delete a given vcenter cluster with given details
        # will return nothing
        self.assertEqual(_str, '')
    def _test_add_to_hosting_device(self, resource, cmd, cmd_args, destination,
                                    body, result):
        path = ((hostingdevice.HostingDevice.resource_path + destination) %
                cmd_args[0])
        cmd_parser = cmd.get_parser('test_' + resource)
        parsed_args = cmd_parser.parse_args(cmd_args)
        result_str = self.client.serialize(result)
        return_tup = (test_cli20.MyResp(200), result_str)

        if getattr(self, 'mox', None):
            self.mox.StubOutWithMock(cmd, "get_client")
            self.mox.StubOutWithMock(self.client.httpclient, "request")
            cmd.get_client().MultipleTimes().AndReturn(self.client)
            self.client.httpclient.request(
                test_cli20.end_url(path), 'POST',
                body=test_cli20.MyComparator(body, self.client),
                headers=mox.ContainsKeyValue(
                    'X-Auth-Token', test_cli20.TOKEN)).AndReturn(return_tup)
            self.mox.ReplayAll()
            cmd.run(parsed_args)
            self.mox.VerifyAll()
            self.mox.UnsetStubs()
        else:
            mock_request_calls = [
                mock.call(
                    test_cli20.end_url(path), 'POST',
                    body=test_cli20.MyComparator(body, self.client),
                    headers=test_cli20.ContainsKeyValue(
                        {'X-Auth-Token': test_cli20.TOKEN}))
            ]

            with mock.patch.object(cmd, "get_client",
                    return_value=self.client) as mock_get_client:
                with mock.patch.object(self.client.httpclient, "request",
                        return_value=return_tup) as mock_request:
                    cmd.run(parsed_args)
                    mock_request.assert_has_calls(mock_request_calls)
                    self.assert_mock_multiple_calls_with_same_arguments(
                        mock_get_client, mock.call(), None)
        def mox_calls(path, data):
            sub_data_lists = [data[:len(data) - 1], data[len(data) - 1:]]
            filters, response = self._build_test_data(data)

            # 1 char of extra URI len will cause a split in 2 requests
            self.mox.StubOutWithMock(self.client.httpclient,
                                     "_check_uri_length")
            self.client.httpclient._check_uri_length(mox.IgnoreArg()).AndRaise(
                exceptions.RequestURITooLong(excess=1))

            for data in sub_data_lists:
                filters, response = self._build_test_data(data)
                self.client.httpclient._check_uri_length(
                    mox.IgnoreArg()).AndReturn(None)
                self.client.httpclient.request(
                    test_cli20.MyUrlComparator(
                        test_cli20.end_url(path, 'fields=id&fields=cidr%s' %
                                           filters), self.client),
                    'GET',
                    body=None,
                    headers=mox.ContainsKeyValue(
                        'X-Auth-Token', test_cli20.TOKEN)).AndReturn(response)
Exemple #14
0
    def test_get_endpoint_url_failed(self):
        self.mox.StubOutWithMock(self.client, "request")

        self.client.auth_token = TOKEN

        res200 = get_response(200)
        res401 = get_response(401)

        self.client.request(
            mox.StrContains(AUTH_URL + '/tokens/%s/endpoints' % TOKEN), 'GET',
            headers=mox.IsA(dict)
        ).AndReturn((res401, ''))
        self.client.request(
            AUTH_URL + '/tokens', 'POST',
            body=mox.IsA(str), headers=mox.IsA(dict)
        ).AndReturn((res200, json.dumps(KS_TOKEN_RESULT)))
        self.client.request(
            mox.StrContains(ENDPOINT_URL + '/resource'), 'GET',
            headers=mox.ContainsKeyValue('X-Auth-Token', TOKEN)
        ).AndReturn((res200, ''))
        self.mox.ReplayAll()
        self.client.do_request('/resource', 'GET')
Exemple #15
0
    def test_do_request_request_ids(self):
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        params = {'test': 'value'}
        expect_query = six.moves.urllib.parse.urlencode(params)
        self.client.httpclient.auth_token = 'token'
        body = params
        expect_body = self.client.serialize(body)
        resp_headers = {'x-openstack-request-id': REQUEST_ID}
        self.client.httpclient.request(
            MyUrlComparator(end_url('/test', query=expect_query), self.client),
            'PUT', body=expect_body,
            headers=mox.ContainsKeyValue('X-Auth-Token', 'token')
        ).AndReturn((MyResp(200, resp_headers), expect_body))

        self.mox.ReplayAll()
        result = self.client.do_request('PUT', '/test', body=body,
                                        params=params)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()

        self.assertEqual(body, result)
        self.assertEqual([REQUEST_ID], result.request_ids)
    def test_insert_firewall_rule(self):
        """firewall-policy-insert-rule myid newruleid
        --insert-before ruleAid
        --insert-after ruleBid
        """
        resource = 'firewall_policy'
        cmd = firewallpolicy.FirewallPolicyInsertRule(
            test_cli20.MyApp(sys.stdout), None)
        myid = 'myid'
        args = [
            'myid', 'newrule', '--insert-before', 'rule2', '--insert-after',
            'rule1'
        ]
        extrafields = {
            'firewall_rule_id': 'newrule',
            'insert_before': 'rule2',
            'insert_after': 'rule1'
        }

        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        cmd.get_client().MultipleTimes().AndReturn(self.client)
        body = extrafields
        path = getattr(self.client, resource + "_insert_path")
        self.client.httpclient.request(
            test_cli20.MyUrlComparator(
                test_cli20.end_url(path % myid, format=self.format),
                self.client),
            'PUT',
            body=test_cli20.MyComparator(body, self.client),
            headers=mox.ContainsKeyValue('X-Auth-Token',
                                         test_cli20.TOKEN)).AndReturn(
                                             (test_cli20.MyResp(204), None))
        args.extend(['--request-format', self.format])
        self.mox.ReplayAll()
        cmd_parser = cmd.get_parser(resource + "_insert_rule")
        shell.run_command(cmd, cmd_parser, args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
Exemple #17
0
 def _test_tags_query(self, cmd, resources, args, query):
     self.mox.StubOutWithMock(cmd, "get_client")
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     cmd.get_client().MultipleTimes().AndReturn(self.client)
     path = getattr(self.client, resources + "_path")
     res = {resources: [{'id': 'myid'}]}
     resstr = self.client.serialize(res)
     self.client.httpclient.request(
         test_cli20.MyUrlComparator(test_cli20.end_url(path, query),
                                    self.client),
         'GET',
         body=None,
         headers=mox.ContainsKeyValue('X-Auth-Token',
                                      test_cli20.TOKEN)).AndReturn(
                                          (test_cli20.MyResp(200), resstr))
     self.mox.ReplayAll()
     cmd_parser = cmd.get_parser("list_networks")
     shell.run_command(cmd, cmd_parser, args)
     self.mox.VerifyAll()
     self.mox.UnsetStubs()
     _str = self.fake_stdout.make_string()
     self.assertIn('myid', _str)
Exemple #18
0
    def test_do_request_unicode(self):
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        unicode_text = u'\u7f51\u7edc'
        # url with unicode
        action = u'/test'
        expected_action = action
        # query string with unicode
        params = {'test': unicode_text}
        expect_query = urlparse.urlencode(utils.safe_encode_dict(params))
        # request body with unicode
        body = params
        expect_body = self.client.serialize(body)
        self.client.httpclient.auth_token = encodeutils.safe_encode(
            unicode_text)
        expected_auth_token = encodeutils.safe_encode(unicode_text)
        resp_headers = {'x-openstack-request-id': REQUEST_ID}

        self.client.httpclient.request(end_url(expected_action,
                                               query=expect_query,
                                               format=self.format),
                                       'PUT',
                                       body=expect_body,
                                       headers=mox.ContainsKeyValue(
                                           'X-Auth-Token',
                                           expected_auth_token)).AndReturn(
                                               (MyResp(200, resp_headers),
                                                expect_body))

        self.mox.ReplayAll()
        result = self.client.do_request('PUT',
                                        action,
                                        body=body,
                                        params=params)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()

        # test response with unicode
        self.assertEqual(body, result)
 def test_get_id_from_id(self):
     _id = str(uuid.uuid4())
     reses = {
         'networks': [
             {
                 'id': _id,
             },
         ],
     }
     resstr = self.client.serialize(reses)
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     path = getattr(self.client, "networks_path")
     self.client.httpclient.request(
         test_cli20.end_url(path, "fields=id&id=" + _id),
         'GET',
         body=None,
         headers=mox.ContainsKeyValue('X-Auth-Token',
                                      test_cli20.TOKEN)).AndReturn(
                                          (test_cli20.MyResp(200), resstr))
     self.mox.ReplayAll()
     returned_id = neutronV20.find_resourceid_by_name_or_id(
         self.client, 'network', _id)
     self.assertEqual(_id, returned_id)
Exemple #20
0
 def test_get_id_from_name_multiple_with_project_not_found(self):
     name = 'web_server'
     project = str(uuid.uuid4())
     resstr_notfound = self.client.serialize({'security_groups': []})
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     path = getattr(self.client, "security_groups_path")
     self.client.httpclient.request(test_cli20.MyUrlComparator(
         test_cli20.end_url(
             path, "fields=id&name=%s&tenant_id=%s" % (name, project)),
         self.client),
                                    'GET',
                                    body=None,
                                    headers=mox.ContainsKeyValue(
                                        'X-Auth-Token',
                                        test_cli20.TOKEN)).AndReturn(
                                            (test_cli20.MyResp(200),
                                             resstr_notfound))
     self.mox.ReplayAll()
     exc = self.assertRaises(exceptions.NotFound,
                             neutronV20.find_resourceid_by_name_or_id,
                             self.client, 'security_group', name, project)
     self.assertIn('Unable to find', exc.message)
     self.assertEqual(404, exc.status_code)
Exemple #21
0
    def test_get_id_from_name_multiple_with_project(self):
        name = 'web_server'
        project = str(uuid.uuid4())
        expect_id = str(uuid.uuid4())
        reses = {'security_groups':
                 [{'id': expect_id, 'tenant_id': project}]}
        resstr = self.client.serialize(reses)
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        path = getattr(self.client, "security_groups_path")
        self.client.httpclient.request(
            test_cli20.MyUrlComparator(
                test_cli20.end_url(path, "fields=id&name=%s&tenant_id=%s" %
                                         (name, project)), self.client),
            'GET',
            body=None,
            headers=mox.ContainsKeyValue('X-Auth-Token', test_cli20.TOKEN)
        ).AndReturn((test_cli20.MyResp(200), resstr))
        self.mox.ReplayAll()

        observed_id = neutronV20.find_resourceid_by_name_or_id(
            self.client, 'security_group', name, project)

        self.assertEqual(expect_id, observed_id)
Exemple #22
0
    def test_do_request_unicode(self):
        self.client.format = self.format
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        unicode_text = u'\u7f51\u7edc'
        # url with unicode
        action = u'/test'
        expected_action = action.encode('utf-8')
        # query string with unicode
        params = {'test': unicode_text}
        expect_query = urllib.urlencode({'test': unicode_text.encode('utf-8')})
        # request body with unicode
        body = params
        expect_body = self.client.serialize(body)
        # headers with unicode
        self.client.httpclient.auth_token = unicode_text
        expected_auth_token = unicode_text.encode('utf-8')

        self.client.httpclient.request(end_url(expected_action,
                                               query=expect_query,
                                               format=self.format),
                                       'PUT',
                                       body=expect_body,
                                       headers=mox.ContainsKeyValue(
                                           'X-Auth-Token',
                                           expected_auth_token)).AndReturn(
                                               (MyResp(200), expect_body))

        self.mox.ReplayAll()
        res_body = self.client.do_request('PUT',
                                          action,
                                          body=body,
                                          params=params)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()

        # test response with unicode
        self.assertEqual(res_body, body)
    def _test_list_columns(self, cmd, resources,
                           resources_out, args=('-f', 'json'),
                           cmd_resources=None, parent_id=None):
        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        cmd.get_client().MultipleTimes().AndReturn(self.client)
        if not cmd_resources:
            cmd_resources = resources

        resstr = self.client.serialize(resources_out)

        path = getattr(self.client, cmd_resources + "_path")
        if parent_id:
            path = path % parent_id
        self.client.httpclient.request(
            end_url(path, format=self.format), 'GET',
            body=None,
            headers=mox.ContainsKeyValue(
                'X-Auth-Token', TOKEN)).AndReturn((MyResp(200), resstr))
        self.mox.ReplayAll()
        cmd_parser = cmd.get_parser("list_" + cmd_resources)
        shell.run_command(cmd, cmd_parser, args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
 def _test_delete_resource(self, resource, cmd, myid, args,
                           cmd_resource=None, parent_id=None):
     self.mox.StubOutWithMock(cmd, "get_client")
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     cmd.get_client().MultipleTimes().AndReturn(self.client)
     if not cmd_resource:
         cmd_resource = resource
     path = getattr(self.client, cmd_resource + "_path")
     if parent_id:
         path = path % (parent_id, myid)
     else:
         path = path % (myid)
     self.client.httpclient.request(
         end_url(path, format=self.format), 'DELETE',
         body=None,
         headers=mox.ContainsKeyValue(
             'X-Auth-Token', TOKEN)).AndReturn((MyResp(204), None))
     self.mox.ReplayAll()
     cmd_parser = cmd.get_parser("delete_" + cmd_resource)
     shell.run_command(cmd, cmd_parser, args)
     self.mox.VerifyAll()
     self.mox.UnsetStubs()
     _str = self.fake_stdout.make_string()
     self.assertIn(myid, _str)
Exemple #25
0
 def _test_tag_operation(self,
                         cmd,
                         path,
                         method,
                         args,
                         prog_name,
                         body=None):
     self.mox.StubOutWithMock(cmd, "get_client")
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     cmd.get_client().MultipleTimes().AndReturn(self.client)
     if body:
         body = test_cli20.MyComparator(body, self.client)
     self.client.httpclient.request(
         test_cli20.MyUrlComparator(test_cli20.end_url(path), self.client),
         method,
         body=body,
         headers=mox.ContainsKeyValue('X-Auth-Token',
                                      test_cli20.TOKEN)).AndReturn(
                                          (test_cli20.MyResp(204), None))
     self.mox.ReplayAll()
     cmd_parser = cmd.get_parser(prog_name)
     shell.run_command(cmd, cmd_parser, args)
     self.mox.VerifyAll()
     self.mox.UnsetStubs()
    def _test_list_resources(self, resources, cmd, detail=False, tags=[],
                             fields_1=[], fields_2=[], page_size=None,
                             sort_key=[], sort_dir=[], response_contents=None,
                             base_args=None, path=None):
        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        cmd.get_client().MultipleTimes().AndReturn(self.client)
        if response_contents is None:
            contents = [{self.id_field: 'myid1', },
                        {self.id_field: 'myid2', }, ]
        else:
            contents = response_contents
        reses = {resources: contents}
        self.client.format = self.format
        resstr = self.client.serialize(reses)
        # url method body
        query = ""
        args = base_args if base_args is not None else []
        if detail:
            args.append('-D')
        args.extend(['--request-format', self.format])
        if fields_1:
            for field in fields_1:
                args.append('--fields')
                args.append(field)

        if tags:
            args.append('--')
            args.append("--tag")
        for tag in tags:
            args.append(tag)
            if isinstance(tag, unicode):
                tag = urllib.quote(tag.encode('utf-8'))
            if query:
                query += "&tag=" + tag
            else:
                query = "tag=" + tag
        if (not tags) and fields_2:
            args.append('--')
        if fields_2:
            args.append("--fields")
            for field in fields_2:
                args.append(field)
        if detail:
            query = query and query + '&verbose=True' or 'verbose=True'
        fields_1.extend(fields_2)
        for field in fields_1:
            if query:
                query += "&fields=" + field
            else:
                query = "fields=" + field
        if page_size:
            args.append("--page-size")
            args.append(str(page_size))
            if query:
                query += "&limit=%s" % page_size
            else:
                query = "limit=%s" % page_size
        if sort_key:
            for key in sort_key:
                args.append('--sort-key')
                args.append(key)
                if query:
                    query += '&'
                query += 'sort_key=%s' % key
        if sort_dir:
            len_diff = len(sort_key) - len(sort_dir)
            if len_diff > 0:
                sort_dir += ['asc'] * len_diff
            elif len_diff < 0:
                sort_dir = sort_dir[:len(sort_key)]
            for dir in sort_dir:
                args.append('--sort-dir')
                args.append(dir)
                if query:
                    query += '&'
                query += 'sort_dir=%s' % dir
        if path is None:
            path = getattr(self.client, resources + "_path")
        self.client.httpclient.request(
            MyUrlComparator(end_url(path, query, format=self.format),
                            self.client),
            'GET',
            body=None,
            headers=mox.ContainsKeyValue(
                'X-Auth-Token', TOKEN)).AndReturn((MyResp(200), resstr))
        self.mox.ReplayAll()
        cmd_parser = cmd.get_parser("list_" + resources)
        shell.run_command(cmd, cmd_parser, args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
        _str = self.fake_stdout.make_string()
        if response_contents is None:
            self.assertIn('myid1', _str)
        return _str
    def _test_list_external_nets(self,
                                 resources,
                                 cmd,
                                 detail=False,
                                 tags=(),
                                 fields_1=(),
                                 fields_2=()):
        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        self.mox.StubOutWithMock(network.ListNetwork, "extend_list")
        network.ListNetwork.extend_list(mox.IsA(list), mox.IgnoreArg())
        cmd.get_client().MultipleTimes().AndReturn(self.client)
        reses = {
            resources: [
                {
                    'id': 'myid1',
                },
                {
                    'id': 'myid2',
                },
            ],
        }

        resstr = self.client.serialize(reses)

        # url method body
        query = ""
        args = detail and [
            '-D',
        ] or []
        if fields_1:
            for field in fields_1:
                args.append('--fields')
                args.append(field)
        if tags:
            args.append('--')
            args.append("--tag")
        for tag in tags:
            args.append(tag)
        if (not tags) and fields_2:
            args.append('--')
        if fields_2:
            args.append("--fields")
            for field in fields_2:
                args.append(field)
        for field in itertools.chain(fields_1, fields_2):
            if query:
                query += "&fields=" + field
            else:
                query = "fields=" + field
        if query:
            query += '&router%3Aexternal=True'
        else:
            query += 'router%3Aexternal=True'
        for tag in tags:
            if query:
                query += "&tag=" + tag
            else:
                query = "tag=" + tag
        if detail:
            query = query and query + '&verbose=True' or 'verbose=True'
        path = getattr(self.client, resources + "_path")

        self.client.httpclient.request(
            test_cli20.MyUrlComparator(test_cli20.end_url(path, query),
                                       self.client),
            'GET',
            body=None,
            headers=mox.ContainsKeyValue('X-Auth-Token',
                                         test_cli20.TOKEN)).AndReturn(
                                             (test_cli20.MyResp(200), resstr))
        self.mox.ReplayAll()
        cmd_parser = cmd.get_parser("list_" + resources)
        shell.run_command(cmd, cmd_parser, args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
        _str = self.fake_stdout.make_string()

        self.assertIn('myid1', _str)
Exemple #28
0
    def _test_create_resource(self,
                              resource,
                              cmd,
                              name,
                              myid,
                              args,
                              position_names,
                              position_values,
                              tenant_id=None,
                              tags=None,
                              admin_state_up=True,
                              extra_body=None,
                              cmd_resource=None,
                              parent_id=None,
                              **kwargs):
        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        cmd.get_client().MultipleTimes().AndReturn(self.client)
        non_admin_status_resources = [
            'subnet', 'floatingip', 'security_group', 'security_group_rule',
            'qos_queue', 'network_gateway', 'gateway_device', 'credential',
            'network_profile', 'policy_profile', 'ikepolicy', 'ipsecpolicy',
            'metering_label', 'metering_label_rule', 'net_partition'
        ]
        if not cmd_resource:
            cmd_resource = resource
        if (resource in non_admin_status_resources):
            body = {
                resource: {},
            }
        else:
            body = {
                resource: {
                    'admin_state_up': admin_state_up,
                },
            }
        if tenant_id:
            body[resource].update({'tenant_id': tenant_id})
        if tags:
            body[resource].update({'tags': tags})
        if extra_body:
            body[resource].update(extra_body)
        body[resource].update(kwargs)

        for i in range(len(position_names)):
            body[resource].update({position_names[i]: position_values[i]})
        ress = {
            resource: {
                self.id_field: myid
            },
        }
        if name:
            ress[resource].update({'name': name})
        self.client.format = self.format
        resstr = self.client.serialize(ress)
        # url method body
        resource_plural = neutronV2_0._get_resource_plural(
            cmd_resource, self.client)
        path = getattr(self.client, resource_plural + "_path")
        if parent_id:
            path = path % parent_id
        # Work around for LP #1217791. XML deserializer called from
        # MyComparator does not decodes XML string correctly.
        if self.format == 'json':
            mox_body = MyComparator(body, self.client)
        else:
            mox_body = self.client.serialize(body)
        self.client.httpclient.request(end_url(path, format=self.format),
                                       'POST',
                                       body=mox_body,
                                       headers=mox.ContainsKeyValue(
                                           'X-Auth-Token', TOKEN)).AndReturn(
                                               (MyResp(200), resstr))
        args.extend(['--request-format', self.format])
        self.mox.ReplayAll()
        cmd_parser = cmd.get_parser('create_' + resource)
        shell.run_command(cmd, cmd_parser, args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
        _str = self.fake_stdout.make_string()
        self.assertIn(myid, _str)
        if name:
            self.assertIn(name, _str)
Exemple #29
0
    def _test_list_resources(self,
                             resources,
                             cmd,
                             detail=False,
                             tags=(),
                             fields_1=(),
                             fields_2=(),
                             page_size=None,
                             sort_key=(),
                             sort_dir=(),
                             response_contents=None,
                             base_args=None,
                             path=None,
                             cmd_resources=None,
                             parent_id=None,
                             output_format=None,
                             query=""):
        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        cmd.get_client().MultipleTimes().AndReturn(self.client)
        if not cmd_resources:
            cmd_resources = resources
        if response_contents is None:
            contents = [
                {
                    self.id_field: 'myid1',
                },
                {
                    self.id_field: 'myid2',
                },
            ]
        else:
            contents = response_contents
        reses = {resources: contents}
        resstr = self.client.serialize(reses)
        # url method body
        args = base_args if base_args is not None else []
        if detail:
            args.append('-D')
        if fields_1:
            for field in fields_1:
                args.append('--fields')
                args.append(field)

        if tags:
            args.append('--')
            args.append("--tag")
        for tag in tags:
            args.append(tag)
            tag_query = urlparse.urlencode(
                {'tag': encodeutils.safe_encode(tag)})
            if query:
                query += "&" + tag_query
            else:
                query = tag_query
        if (not tags) and fields_2:
            args.append('--')
        if fields_2:
            args.append("--fields")
            for field in fields_2:
                args.append(field)
        if detail:
            query = query and query + '&verbose=True' or 'verbose=True'
        for field in itertools.chain(fields_1, fields_2):
            if query:
                query += "&fields=" + field
            else:
                query = "fields=" + field
        if page_size:
            args.append("--page-size")
            args.append(str(page_size))
            if query:
                query += "&limit=%s" % page_size
            else:
                query = "limit=%s" % page_size
        if sort_key:
            for key in sort_key:
                args.append('--sort-key')
                args.append(key)
                if query:
                    query += '&'
                query += 'sort_key=%s' % key
        if sort_dir:
            len_diff = len(sort_key) - len(sort_dir)
            if len_diff > 0:
                sort_dir = tuple(sort_dir) + ('asc', ) * len_diff
            elif len_diff < 0:
                sort_dir = sort_dir[:len(sort_key)]
            for dir in sort_dir:
                args.append('--sort-dir')
                args.append(dir)
                if query:
                    query += '&'
                query += 'sort_dir=%s' % dir
        if path is None:
            path = getattr(self.client, cmd_resources + "_path")
            if parent_id:
                path = path % parent_id
        if output_format:
            args.append('-f')
            args.append(output_format)
        self.client.httpclient.request(
            MyUrlComparator(end_url(path, query, format=self.format),
                            self.client),
            'GET',
            body=None,
            headers=mox.ContainsKeyValue('X-Auth-Token', TOKEN)).AndReturn(
                (MyResp(200), resstr))
        self.mox.ReplayAll()
        cmd_parser = cmd.get_parser("list_" + cmd_resources)
        shell.run_command(cmd, cmd_parser, args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
        _str = self.fake_stdout.make_string()
        if response_contents is None:
            self.assertIn('myid1', _str)
        return _str
Exemple #30
0
    def _test_create_resource(self,
                              resource,
                              cmd,
                              name,
                              myid,
                              args,
                              position_names,
                              position_values,
                              tenant_id=None,
                              tags=None,
                              admin_state_up=True,
                              extra_body=None,
                              cmd_resource=None,
                              parent_id=None,
                              no_api_call=False,
                              expected_exception=None,
                              **kwargs):
        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        cmd.get_client().MultipleTimes().AndReturn(self.client)
        if not cmd_resource:
            cmd_resource = resource
        if (resource in self.non_admin_status_resources):
            body = {
                resource: {},
            }
        else:
            body = {
                resource: {
                    'admin_state_up': admin_state_up,
                },
            }
        if tenant_id:
            body[resource].update({'tenant_id': tenant_id})
        if tags:
            body[resource].update({'tags': tags})
        if extra_body:
            body[resource].update(extra_body)
        body[resource].update(kwargs)

        for i in range(len(position_names)):
            body[resource].update({position_names[i]: position_values[i]})
        ress = {
            resource: {
                self.id_field: myid
            },
        }
        if name:
            ress[resource].update({'name': name})
        resstr = self.client.serialize(ress)
        # url method body
        resource_plural = neutronV2_0._get_resource_plural(
            cmd_resource, self.client)
        path = getattr(self.client, resource_plural + "_path")
        if parent_id:
            path = path % parent_id
        mox_body = MyComparator(body, self.client)

        if not no_api_call:
            self.client.httpclient.request(end_url(path, format=self.format),
                                           'POST',
                                           body=mox_body,
                                           headers=mox.ContainsKeyValue(
                                               'X-Auth-Token',
                                               TOKEN)).AndReturn(
                                                   (MyResp(200), resstr))
        self.mox.ReplayAll()
        cmd_parser = cmd.get_parser('create_' + resource)
        if expected_exception:
            self.assertRaises(expected_exception, shell.run_command, cmd,
                              cmd_parser, args)
        else:
            shell.run_command(cmd, cmd_parser, args)
            _str = self.fake_stdout.make_string()
            self.assertIn(myid, _str)
            if name:
                self.assertIn(name, _str)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()