Пример #1
0
    def test_refresh_token(self):
        self.mox.StubOutWithMock(self.client, "request")

        self.client.auth_token = TOKEN
        self.client.endpoint_url = ENDPOINT_URL

        res200 = self.mox.CreateMock(httplib2.Response)
        res200.status = 200
        res401 = self.mox.CreateMock(httplib2.Response)
        res401.status = 401

        # If a token is expired, neutron server retruns 401
        self.client.request(mox.StrContains(ENDPOINT_URL + '/resource'),
                            'GET',
                            headers=mox.ContainsKeyValue(
                                'X-Auth-Token', TOKEN)).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')
Пример #2
0
 def _test_list_resources_with_pagination(self, resources, cmd):
     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")
     fake_query = "marker=myid2&limit=2"
     reses1 = {resources: [{'id': 'myid1', },
                           {'id': 'myid2', }],
               '%s_links' % resources: [{'href': end_url(path, fake_query),
                                         'rel': 'next'}]}
     reses2 = {resources: [{'id': 'myid3', },
                           {'id': 'myid4', }]}
     self.client.format = self.format
     resstr1 = self.client.serialize(reses1)
     resstr2 = self.client.serialize(reses2)
     self.client.httpclient.request(
         end_url(path, "", format=self.format), 'GET',
         body=None,
         headers=mox.ContainsKeyValue(
             'X-Auth-Token', TOKEN)).AndReturn((MyResp(200), resstr1))
     self.client.httpclient.request(
         end_url(path, fake_query, format=self.format), 'GET',
         body=None,
         headers=mox.ContainsKeyValue(
             'X-Auth-Token', TOKEN)).AndReturn((MyResp(200), resstr2))
     self.mox.ReplayAll()
     cmd_parser = cmd.get_parser("list_" + resources)
     args = ['--request-format', self.format]
     shell.run_command(cmd, cmd_parser, args)
     self.mox.VerifyAll()
     self.mox.UnsetStubs()
Пример #3
0
 def test_get_id_from_id_then_name_empty(self):
     _id = str(uuid.uuid4())
     reses = {
         'networks': [
             {
                 'id': _id,
             },
         ],
     }
     resstr = self.client.serialize(reses)
     resstr1 = self.client.serialize({'networks': []})
     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), resstr1))
     self.client.httpclient.request(
         test_cli20.end_url(path, "fields=id&name=" + _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)
Пример #4
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.end_url(path, "fields=id&name=" + name),
         '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.assertTrue('Multiple' in ex.message)
Пример #5
0
    def test_remove_firewall_rule(self):
        """firewall-policy-remove-rule myid ruleid
        """
        resource = 'firewall_policy'
        cmd = firewallpolicy.FirewallPolicyRemoveRule(
            test_cli20.MyApp(sys.stdout),
            None)
        myid = 'myid'
        args = ['myid', 'removerule']
        extrafields = {'firewall_rule_id': 'removerule', }

        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 + "_remove_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 + "_remove_rule")
        shell.run_command(cmd, cmd_parser, args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
Пример #6
0
    def test_disassociate_healthmonitor(self):
        cmd = healthmonitor.DisassociateHealthMonitor(
            test_cli20.MyApp(sys.stdout), None)
        resource = 'health_monitor'
        health_monitor_id = 'hm-id'
        pool_id = 'p_id'
        args = [health_monitor_id, pool_id]

        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        cmd.get_client().MultipleTimes().AndReturn(self.client)

        path = (
            getattr(self.client, "disassociate_pool_health_monitors_path") % {
                'pool': pool_id,
                'health_monitor': health_monitor_id
            })
        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(args)
        cmd.run(parsed_args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
Пример #7
0
    def test_associate_healthmonitor(self):
        cmd = healthmonitor.AssociateHealthMonitor(
            test_cli20.MyApp(sys.stdout), None)
        resource = 'health_monitor'
        health_monitor_id = 'hm-id'
        pool_id = 'p_id'
        args = [health_monitor_id, pool_id]

        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        cmd.get_client().MultipleTimes().AndReturn(self.client)

        body = {resource: {'id': health_monitor_id}}
        result = {
            resource: {
                'id': health_monitor_id
            },
        }
        result_str = self.client.serialize(result)

        path = getattr(self.client,
                       "associate_pool_health_monitors_path") % pool_id
        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(args)
        cmd.run(parsed_args)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()
Пример #8
0
 def _test_show_resource(self, resource, cmd, myid, args, fields=[]):
     self.mox.StubOutWithMock(cmd, "get_client")
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     cmd.get_client().MultipleTimes().AndReturn(self.client)
     query = "&".join(["fields=%s" % field for field in fields])
     expected_res = {resource:
                     {self.id_field: myid,
                      'name': 'myname', }, }
     self.client.format = self.format
     resstr = self.client.serialize(expected_res)
     path = getattr(self.client, resource + "_path")
     self.client.httpclient.request(
         end_url(path % myid, query, format=self.format), 'GET',
         body=None,
         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("show_" + resource)
     shell.run_command(cmd, cmd_parser, args)
     self.mox.VerifyAll()
     self.mox.UnsetStubs()
     _str = self.fake_stdout.make_string()
     self.assertTrue(myid in _str)
     self.assertTrue('myname' in _str)
 def test_list_external_nets_empty_with_column(self):
     resources = "networks"
     cmd = network.ListExternalNetwork(test_cli20.MyApp(sys.stdout), None)
     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: []}
     resstr = self.client.serialize(reses)
     # url method body
     query = "router%3Aexternal=True&id=myfakeid"
     args = ['-c', 'id', '--', '--id', 'myfakeid']
     path = getattr(self.client, resources + "_path")
     self.client.httpclient.request(
         test_cli20.end_url(path, query),
         '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.assertEquals('\n', _str)
Пример #10
0
 def _test_update_resource_action(self,
                                  resource,
                                  cmd,
                                  myid,
                                  action,
                                  args,
                                  body,
                                  retval=None):
     self.mox.StubOutWithMock(cmd, "get_client")
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     cmd.get_client().MultipleTimes().AndReturn(self.client)
     path = getattr(self.client, 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))
     args.extend(['--request-format', self.format])
     self.mox.ReplayAll()
     cmd_parser = cmd.get_parser("delete_" + resource)
     shell.run_command(cmd, cmd_parser, args)
     self.mox.VerifyAll()
     self.mox.UnsetStubs()
     _str = self.fake_stdout.make_string()
     self.assertIn(myid, _str)
Пример #11
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 = urllib.urlencode(params)
        self.client.httpclient.auth_token = 'token'

        self.client.httpclient.request(end_url('/test',
                                               query=expect_query,
                                               format=self.format),
                                       '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()
Пример #12
0
    def test_do_request(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)
Пример #13
0
    def test_retrieve_pool_stats(self):
        """lb-pool-stats test_id."""
        resource = 'pool'
        cmd = pool.RetrievePoolStats(test_cli20.MyApp(sys.stdout), None)
        my_id = self.test_id
        fields = ['bytes_in', 'bytes_out']
        args = ['--fields', 'bytes_in', '--fields', 'bytes_out', my_id]

        self.mox.StubOutWithMock(cmd, "get_client")
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        cmd.get_client().MultipleTimes().AndReturn(self.client)
        query = "&".join(["fields=%s" % field for field in fields])
        expected_res = {'stats': {'bytes_in': '1234', 'bytes_out': '4321'}}
        resstr = self.client.serialize(expected_res)
        path = getattr(self.client, "pool_path_stats")
        return_tup = (test_cli20.MyResp(200), resstr)
        self.client.httpclient.request(
            test_cli20.end_url(path % my_id, query),
            'GET',
            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(args)
        cmd.run(parsed_args)

        self.mox.VerifyAll()
        self.mox.UnsetStubs()
        _str = self.fake_stdout.make_string()
        self.assertIn('bytes_in', _str)
        self.assertIn('bytes_out', _str)
Пример #14
0
    def test_report_state_no_service(self):
        host = 'foo'
        binary = 'bar'
        topic = 'test'
        service_create = {
            'host': host,
            'binary': binary,
            'topic': topic,
            'report_count': 0,
            'availability_zone': 'nova'
        }
        service_ref = {
            'host': host,
            'binary': binary,
            'topic': topic,
            'report_count': 0,
            'availability_zone': 'nova',
            'id': 1
        }

        service.db.service_get_by_args(mox.IgnoreArg(), host,
                                       binary).AndRaise(exception.NotFound())
        service.db.service_create(mox.IgnoreArg(),
                                  service_create).AndReturn(service_ref)
        service.db.service_get(mox.IgnoreArg(),
                               service_ref['id']).AndReturn(service_ref)
        service.db.service_update(mox.IgnoreArg(), service_ref['id'],
                                  mox.ContainsKeyValue('report_count', 1))

        self.mox.ReplayAll()
        serv = service.Service(host, binary, topic,
                               'nova.tests.test_service.FakeManager')
        serv.start()
        serv.report_state()
Пример #15
0
    def test_get_endpoint_url_failed(self):
        self.mox.StubOutWithMock(self.client, "request")

        self.client.auth_token = TOKEN

        res200 = self.mox.CreateMock(httplib2.Response)
        res200.status = 200
        res401 = self.mox.CreateMock(httplib2.Response)
        res401.status = 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')
Пример #16
0
 def _test_update_resource(self, resource, cmd, myid, args, extrafields):
     self.mox.StubOutWithMock(cmd, "get_client")
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     cmd.get_client().MultipleTimes().AndReturn(self.client)
     body = {resource: extrafields}
     path = getattr(self.client, resource + "_path")
     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 % myid, 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_" + resource)
     shell.run_command(cmd, cmd_parser, args)
     self.mox.VerifyAll()
     self.mox.UnsetStubs()
     _str = self.fake_stdout.make_string()
     self.assertTrue(myid in _str)
Пример #17
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,
                              **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', 'credential',
                                      'network_profile', 'policy_profile',
                                      'ikepolicy', 'ipsecpolicy',
                                      'metering_label', 'metering_label_rule']
        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(resource,
                                                           self.client)
        path = getattr(self.client, resource_plural + "_path")
        # 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.assertTrue(myid in _str)
        if name:
            self.assertTrue(name in _str)
 def mox_calls(path, data):
     filters, response = self._build_test_data(data)
     self.client.httpclient.request(
         test_cli20.end_url(path, 'fields=id&fields=cidr' + filters),
         'GET',
         body=None,
         headers=mox.ContainsKeyValue(
             'X-Auth-Token', test_cli20.TOKEN)).AndReturn(response)
Пример #19
0
  def testAdvancedUsage(self):
    """And should work with other Comparators.

    Note: this test is reliant on In and ContainsKeyValue.
    """
    test_dict = {"mock" : "obj", "testing" : "isCOOL"}
    self.assert_(mox.And(mox.In("testing"),
                           mox.ContainsKeyValue("mock", "obj")) == test_dict)
Пример #20
0
    def test_emit(self):
        fake_date = "2013 3 7"
        log_message = "Log me too."

        self.mox.StubOutWithMock(self.handler, 'save')
        self.mox.StubOutWithMock(datetime, 'datetime')
        datetime.datetime.now().AndReturn(fake_date)

        self.handler.save(
            mox.And(mox.ContainsKeyValue("msg", log_message),
                    mox.ContainsKeyValue("level", "INFO"),
                    mox.ContainsKeyValue("timestamp", fake_date)))

        self.mox.ReplayAll()

        self.logger.info(log_message)

        self.mox.VerifyAll()
 def setup_list_stub(resources, data, query):
     reses = {resources: data}
     resstr = self.client.serialize(reses)
     resp = (test_cli20.MyResp(200), resstr)
     path = getattr(self.client, resources + '_path')
     self.client.httpclient.request(
         test_cli20.end_url(path, query), 'GET',
         body=None,
         headers=mox.ContainsKeyValue(
             'X-Auth-Token', test_cli20.TOKEN)).AndReturn(resp)
Пример #22
0
    def test_set_default_control_exchange(self):
        messaging.set_transport_defaults(control_exchange='foo')

        self.mox.StubOutWithMock(driver, 'DriverManager')
        invoke_kwds = mox.ContainsKeyValue('default_exchange', 'foo')
        driver.DriverManager(mox.IgnoreArg(),
                             mox.IgnoreArg(),
                             invoke_on_load=mox.IgnoreArg(),
                             invoke_args=mox.IgnoreArg(),
                             invoke_kwds=invoke_kwds).\
            AndReturn(_FakeManager(_FakeDriver(self.conf)))
        self.mox.ReplayAll()

        messaging.get_transport(self.conf)
Пример #23
0
    def test_report_state_newly_connected(self):
        service_ref = self._service_start_mocks()

        service.db.service_get(mox.IgnoreArg(),
                               service_ref['id']).AndReturn(service_ref)
        service.db.service_update(mox.IgnoreArg(), service_ref['id'],
                                  mox.ContainsKeyValue('report_count', 1))

        self.mox.ReplayAll()
        serv = service.Service(self.host, self.binary, self.topic,
                               'nova.tests.test_service.FakeManager')
        serv.start()
        serv.model_disconnected = True
        serv.report_state()

        self.assert_(not serv.model_disconnected)
Пример #24
0
    def test_get_endpoint_url(self):
        self.mox.StubOutWithMock(self.client, "request")

        self.client.auth_token = TOKEN

        res200 = get_response(200)

        self.client.request(
            mox.StrContains(AUTH_URL + '/tokens/%s/endpoints' % TOKEN), 'GET',
            headers=mox.IsA(dict)
        ).AndReturn((res200, json.dumps(ENDPOINTS_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')
    def test_refresh_token_no_auth_url(self):
        self.mox.StubOutWithMock(self.client, "request")
        self.client.auth_url = None

        self.client.auth_token = TOKEN
        self.client.endpoint_url = ENDPOINT_URL

        res401 = get_response(401)

        # If a token is expired, neutron server returns 401
        self.client.request(mox.StrContains(ENDPOINT_URL + '/resource'),
                            'GET',
                            headers=mox.ContainsKeyValue(
                                'X-Auth-Token', TOKEN)).AndReturn((res401, ''))
        self.mox.ReplayAll()
        self.assertRaises(exceptions.NoAuthURLProvided, self.client.do_request,
                          '/resource', 'GET')
Пример #26
0
 def _test_delete_resource(self, resource, cmd, myid, args):
     self.mox.StubOutWithMock(cmd, "get_client")
     self.mox.StubOutWithMock(self.client.httpclient, "request")
     cmd.get_client().MultipleTimes().AndReturn(self.client)
     path = getattr(self.client, resource + "_path")
     self.client.httpclient.request(
         end_url(path % myid, format=self.format), 'DELETE',
         body=None,
         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("delete_" + resource)
     shell.run_command(cmd, cmd_parser, args)
     self.mox.VerifyAll()
     self.mox.UnsetStubs()
     _str = self.fake_stdout.make_string()
     self.assertTrue(myid in _str)
Пример #27
0
    def test_get_token(self):
        self.mox.StubOutWithMock(self.client, "request")

        res200 = get_response(200)

        self.client.request(
            AUTH_URL + '/tokens', 'POST',
            body=self.auth_body, 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')
        self.assertEqual(self.client.endpoint_url, ENDPOINT_URL)
        self.assertEqual(self.client.auth_token, TOKEN)
 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.end_url(path, "fields=id&name=" + name), '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.NeutronClientException as ex:
         self.assertIn('Unable to find', ex.message)
         self.assertEqual(404, ex.status_code)
        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, "_check_uri_length")
            self.client._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._check_uri_length(mox.IgnoreArg()).AndReturn(None)
                self.client.httpclient.request(
                    test_cli20.end_url(path,
                                       'fields=id&fields=cidr%s' % filters),
                    'GET',
                    body=None,
                    headers=mox.ContainsKeyValue(
                        'X-Auth-Token', test_cli20.TOKEN)).AndReturn(response)
Пример #30
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)