Exemple #1
0
 def test_load_balancer_goes_into_pending_update_state(self):
     """
     Test to verify a load balancer goes into PENDING-UPDATE state, for
     the given time in seconds when any action other than DELETE is performed
     on the lb.
     Adding a node to a loadbalancer in PENDING-UPDATE state results in 422.
     And such a load balancer can be deleted.
     """
     metadata = [{"key": "lb_pending_update", "value": 30}]
     create_response = self._create_loadbalancer_for_given_metadata(metadata)
     self.assertEqual(create_response.code, 202)
     create_lb_response_body = self.successResultOf(treq.json_content(create_response))
     lb = create_lb_response_body["loadBalancer"]
     self.assertEqual(lb["status"], "ACTIVE")
     create_node_response = self._add_node_to_lb(lb["id"])
     self.assertEqual(create_node_response.code, 200)
     # get loadbalncer after adding node and verify its in PENDING-UPDATE state
     errored_lb = self._get_loadbalancer(lb["id"])
     self.assertEqual(errored_lb["loadBalancer"]["status"], "PENDING-UPDATE")
     # Trying to add/list/delete node on a lb in PENDING-UPDATE state, results in 422
     create_node_response = self._add_node_to_lb(lb["id"])
     self.assertEqual(create_node_response.code, 422)
     delete_nodes = request(
         self, self.root, "DELETE", self.uri + '/loadbalancers/' +
         str(lb["id"]) + '/nodes/123')
     self.assertEqual(self.successResultOf(delete_nodes).code, 422)
     # An lb in PENDING-UPDATE state can be deleted
     delete_lb = request(self, self.root, "DELETE", self.uri + '/loadbalancers/' +
                         str(lb["id"]))
     delete_lb_response = self.successResultOf(delete_lb)
     self.assertEqual(delete_lb_response.code, 202)
Exemple #2
0
 def test_list_entity(self):
     """
     test list entity
     """
     req = request(self, self.root, "GET", self.uri + '/entities')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals(data['metadata']['count'], 1)
     for q in range(1, 101):
         self.createEntity('Cinnamon' + str(q))
     for q in range(1, 101):
         req = request(self, self.root, "GET",
                       self.uri + '/entities/?limit=' + str(q))
         resp = self.successResultOf(req)
         self.assertEquals(resp.code, 200)
         data = self.get_responsebody(resp)
         self.assertEquals(data['metadata']['count'], q)
         marker = data['metadata']['next_marker']
     req = request(self, self.root, "GET",
                   self.uri + '/entities/?marker=' + marker)
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals(data['metadata']['count'], 1)
     self.assertEquals(data['metadata']['next_marker'], None)
Exemple #3
0
    def test_test_alarm_clearing_response(self):
        """
        Sending HTTP DELETE to the entity's test-alarm response
        causes the response to be cleared and not returned later.
        """
        resp = self.successResultOf(
            request(self, self.root, "PUT",
                    '{0}/entities/{1}/alarms/test_response'.format(
                        self.ctl_uri, self.entity_id),
                    json.dumps([{'state': 'OK',
                                 'status': 'test-alarm working OK'}])))
        self.assertEquals(resp.code, 204)

        resp = self.successResultOf(request(self, self.root, "DELETE",
                                            '{0}/entities/{1}/alarms/test_response'.format(
                                                self.ctl_uri, self.entity_id)))
        self.assertEquals(resp.code, 204)

        (resp, data) = self.successResultOf(
            json_request(self, self.root, "POST",
                         self.uri + '/entities/' + self.entity_id + '/test-alarm',
                         json.dumps({'criteria': 'return new AlarmStatus(OK);',
                                     'check_data': [{}]})))
        self.assertEquals(resp.code, 200)
        self.assertEquals(1, len(data))
        self.assertNotEquals('test-alarm working OK', data[0]['status'])
Exemple #4
0
 def setUp(self):
     """
     Create a :obj:`MimicCore` with :obj:`LoadBalancerApi` as the only plugin.
     And create a load balancer and add nodes to the load balancer.
     """
     helper = APIMockHelper(self, [LoadBalancerApi()])
     self.root = helper.root
     self.uri = helper.uri
     create_lb = request(
         self, self.root, "POST", self.uri + '/loadbalancers',
         json.dumps({
             "loadBalancer": {
                 "name": "test_lb",
                 "protocol": "HTTP",
                 "virtualIps": [{"type": "PUBLIC"}]
             }
         })
     )
     create_lb_response = self.successResultOf(create_lb)
     self.create_lb_response_body = self.successResultOf(treq.json_content(
                                                         create_lb_response))
     create_node = request(
         self, self.root, "POST", self.uri + '/loadbalancers/' +
         str(self.create_lb_response_body["loadBalancer"]["id"]) + '/nodes',
         json.dumps({"nodes": [{"address": "127.0.0.1",
                                "port": 80,
                                "condition": "ENABLED",
                                "type": "PRIMARY",
                                "weight": 10}]})
     )
     self.create_node_response = self.successResultOf(create_node)
     self.create_node_response_body = self.successResultOf(treq.json_content(
                                                           self.create_node_response))
     self.node = self.create_node_response_body["nodes"]
Exemple #5
0
    def test_test_check_clears_metrics(self):
        """
        The test-check control API can clear metrics.

        ..note: Randomly generated string metrics are between 12 and 30
        characters long.
        """
        options = {'data': 'really great forty-three character sentence'}

        resp = self.successResultOf(
            request(self, self.root, "PUT",
                    '{0}/entities/{1}/checks/test_responses/{2}'.format(
                        self.ctl_uri, self.entity_id, 'agent.filesystem'),
                    json.dumps([{'metrics': {'options': options}}])))
        self.assertEquals(resp.code, 204)

        resp = self.successResultOf(
            request(self, self.root, "DELETE",
                    '{0}/entities/{1}/checks/test_responses/{2}'.format(
                        self.ctl_uri, self.entity_id, 'agent.filesystem')))
        self.assertEquals(resp.code, 204)

        (resp, data) = self.successResultOf(
            json_request(self, self.root, "POST",
                         self.uri + '/entities/' + self.entity_id + '/test-check',
                         json.dumps({'type': 'agent.filesystem'})))
        self.assertEquals(resp.code, 200)
        self.assertTrue(len(data[0]['metrics']['options']['data']) < 43)
Exemple #6
0
 def test_multiplot_squarewave(self):
     """
     get datapoints for graph, specifically squarewave PING check graph
     """
     metrics = []
     squarewave_check_id = self.getXobjectIDfromResponse(
         self.createCheck('squarewave', self.entity_id))
     req = request(self, self.root, "GET", self.uri + '/views/metric_list')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     for m in data['values'][0]['checks'][0]['metrics']:
         mq = {
             'entity_id': self.entity_id,
             'check_id': squarewave_check_id,
             'metric': m['name']
         }
         metrics.append(mq)
     qstring = '?from=1412902262560&points=500&to=1412988662560'
     req = request(self, self.root, "POST",
                   self.uri + '/__experiments/multiplot' + qstring,
                   json.dumps({'metrics': metrics}))
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals(500, len(data['metrics'][0]['data']))
Exemple #7
0
 def test_agenthostinfo(self):
     """
     fetch agent host info
     """
     for q in range(4):
         req = request(
             self, self.root, "GET",
             self.uri + '/views/agent_host_info?entityId=' + self.entity_id)
         resp = self.successResultOf(req)
         self.assertEquals(resp.code, 400)
         data = self.get_responsebody(resp)
         self.assertEquals(True, 'Agent does not exist' in json.dumps(data))
     req = request(
         self, self.root, "GET",
         self.uri + '/views/agent_host_info?entityId=' + self.entity_id)
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals(True,
                       self.entity_id == data['values'][0]['entity_id'])
     req = request(self, self.root, "GET",
                   self.uri + '/views/agent_host_info')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 400)
     data = self.get_responsebody(resp)
     self.assertEquals(True, data['type'] == 'badRequest')
     req = request(
         self, self.root, "GET",
         self.uri + '/views/agent_host_info?entityId=enDoesNotExist')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 404)
     data = self.get_responsebody(resp)
     self.assertEquals(data['type'], 'notFoundError')
Exemple #8
0
 def test_delete_server_fails_specified_number_of_times(self):
     """
     Test to verify :func: `delete_server` does not delete the server,
     and returns the given response code, the number of times specified
     in the metadata
     """
     deletefail = {"times": 1, "code": 500}
     metadata = {"delete_server_failure": json.dumps(deletefail)}
     # create server and verify it was successful
     create_server_response = self.create_server(metadata=metadata)
     self.assertEquals(create_server_response.code, 202)
     create_server_response_body = self.successResultOf(
         treq.json_content(create_server_response))
     # delete server and verify the response
     delete_server = request(self, self.root, "DELETE", self.uri + '/servers/'
                             + create_server_response_body["server"]["id"])
     delete_server_response = self.successResultOf(delete_server)
     self.assertEqual(delete_server_response.code, 500)
     # get server and verify the server was not deleted
     get_server = request(self, self.root, "GET", self.uri + '/servers/' +
                          create_server_response_body["server"]["id"])
     get_server_response = self.successResultOf(get_server)
     self.assertEquals(get_server_response.code, 200)
     # delete server again and verify the response
     delete_server = request(self, self.root, "DELETE", self.uri + '/servers/'
                             + create_server_response_body["server"]["id"])
     delete_server_response = self.successResultOf(delete_server)
     self.assertEqual(delete_server_response.code, 204)
     self.assertEqual(self.successResultOf(treq.content(delete_server_response)),
                      b"")
     # get server and verify the server was deleted this time
     get_server = request(self, self.root, "GET", self.uri + '/servers/' +
                          create_server_response_body["server"]["id"])
     get_server_response = self.successResultOf(get_server)
     self.assertEquals(get_server_response.code, 404)
Exemple #9
0
    def test_list_servers_with_details_with_args(self):
        """
        :func:`list_servers_with_details`, used by
        ``GET /v2.0/<tenant_id>/servers/detail``, returns the server details
        for only the servers of a given name
        """
        request(
            self, self.root, "POST", self.uri + '/servers',
            json.dumps({
                "server": {
                    "name": 'non-matching-name',
                    "imageRef": "test-image",
                    "flavorRef": "test-flavor"
                }
            }))

        response, body = self.successResultOf(
            json_request(
                self, self.root, "GET",
                "{0}/servers/detail?name={1}".format(self.uri,
                                                     self.server_name)))
        self.assertEqual(response.code, 200)
        self.assertIsNot(body['servers'], None)
        self.assertIsNot(body['servers'][0], None)
        self.assertEqual(body['servers'][0]['id'], self.server_id)
        self.assertEqual(len(body['servers']), 1)
        self.assertEqual(body['servers'][0]['status'], 'ACTIVE')
        self.validate_server_detail_json(body['servers'][0])
Exemple #10
0
 def test_agenthostinfo(self):
     """
     fetch agent host info
     """
     for q in range(4):
         req = request(self, self.root, "GET",
                       self.uri + '/views/agent_host_info?entityId=' + self.entity_id)
         resp = self.successResultOf(req)
         self.assertEquals(resp.code, 400)
         data = self.get_responsebody(resp)
         self.assertEquals(True, 'Agent does not exist' in json.dumps(data))
     req = request(self, self.root, "GET",
                   self.uri + '/views/agent_host_info?entityId=' + self.entity_id)
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals(True, self.entity_id == data['values'][0]['entity_id'])
     req = request(self, self.root, "GET",
                   self.uri + '/views/agent_host_info')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 400)
     data = self.get_responsebody(resp)
     self.assertEquals(True, data['type'] == 'badRequest')
     req = request(self, self.root, "GET",
                   self.uri + '/views/agent_host_info?entityId=enDoesNotExist')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 404)
     data = self.get_responsebody(resp)
     self.assertEquals(data['type'], 'notFoundError')
Exemple #11
0
 def setUp(self):
     """
     Create a :obj:`MimicCore` with :obj:`QueueApi` as the only plugin,
     and create a queue
     """
     self.clock = Clock()
     self.core = MimicCore(self.clock, [QueueApi()])
     self.root = MimicRoot(self.core).app.resource()
     self.response = request(
         self, self.root, b"POST", "/identity/v2.0/tokens",
         json.dumps({
             "auth": {
                 "passwordCredentials": {
                     "username": "******",
                     "password": "******",
                 },
             }
         }).encode("utf-8"))
     self.auth_response = self.successResultOf(self.response)
     self.json_body = self.successResultOf(
         treq.json_content(self.auth_response))
     self.uri = self.json_body['access']['serviceCatalog'][0]['endpoints'][
         0]['publicURL']
     self.queue_name = "test_queue"
     self.create_queue = request(self, self.root, b"PUT",
                                 self.uri + '/queues/' + self.queue_name)
     self.create_queue_response = self.successResultOf(self.create_queue)
Exemple #12
0
 def test_multiplot(self):
     """
     get datapoints for graph
     """
     ecan = self.get_ecan_object_ids()
     metrics = []
     req = request(self, self.root, "GET", self.uri + '/views/metric_list',
                   '')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     for m in data['values'][0]['checks'][0]['metrics']:
         mq = {
             'entity_id': ecan['entity_id'],
             'check_id': ecan['check_id'],
             'metric': m['name']
         }
         metrics.append(mq)
     qstring = '?from=1412902262560&points=500&to=1412988662560'
     req = request(self, self.root, "POST",
                   self.uri + '/__experiments/multiplot' + qstring,
                   json.dumps({'metrics': metrics}))
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals(500, len(data['metrics'][0]['data']))
Exemple #13
0
 def test_delete_server_fails_specified_number_of_times(self):
     """
     Test to verify :func: `delete_server` does not delete the server,
     and returns the given response code, the number of times specified
     in the metadata
     """
     deletefail = {"times": 1, "code": 500}
     metadata = {"delete_server_failure": json.dumps(deletefail)}
     # create server and verify it was successful
     create_server_response = self.create_server(metadata=metadata)
     self.assertEquals(create_server_response.code, 202)
     create_server_response_body = self.successResultOf(
         treq.json_content(create_server_response))
     # delete server and verify the response
     delete_server = request(self, self.root, "DELETE", self.uri + '/servers/'
                             + create_server_response_body["server"]["id"])
     delete_server_response = self.successResultOf(delete_server)
     self.assertEqual(delete_server_response.code, 500)
     # get server and verify the server was not deleted
     get_server = request(self, self.root, "GET", self.uri + '/servers/' +
                          create_server_response_body["server"]["id"])
     get_server_response = self.successResultOf(get_server)
     self.assertEquals(get_server_response.code, 200)
     # delete server again and verify the response
     delete_server = request(self, self.root, "DELETE", self.uri + '/servers/'
                             + create_server_response_body["server"]["id"])
     delete_server_response = self.successResultOf(delete_server)
     self.assertEqual(delete_server_response.code, 204)
     self.assertEqual(self.successResultOf(treq.content(delete_server_response)),
                      b"")
     # get server and verify the server was deleted this time
     get_server = request(self, self.root, "GET", self.uri + '/servers/' +
                          create_server_response_body["server"]["id"])
     get_server_response = self.successResultOf(get_server)
     self.assertEquals(get_server_response.code, 404)
Exemple #14
0
 def test_get_container(self):
     """
     Creating a container and immediately retrieving it yields an empty list
     (since there are no objects) and several headers indicating that no
     objects are in the container and they consume no space.
     """
     self.createSwiftService()
     # create a container
     uri = (self.json_body['access']['serviceCatalog'][0]['endpoints'][0]
            ['publicURL'] + '/testcontainer').encode("ascii")
     create_container = request(self, self.root, b"PUT", uri)
     self.successResultOf(create_container)
     container_response = self.successResultOf(
         request(self, self.root, b"GET", uri)
     )
     self.assertEqual(container_response.code, 200)
     container_contents = self.successResultOf(
         treq.json_content(container_response)
     )
     self.assertEqual(container_contents, [])
     self.assertEqual(
         container_response.headers.getRawHeaders(
             b"X-Container-Object-Count")[0], b"0"
     )
     self.assertEqual(
         container_response.headers.getRawHeaders(
             b"X-Container-Bytes-Used")[0], b"0"
     )
Exemple #15
0
 def test_server_in_building_state_for_specified_time(self):
     """
     Test to verify :func:`create_server` creates a server in BUILD
     status for the time specified in the metadata.
     """
     metadata = {"server_building": 1}
     # create server with metadata to keep the server in building state for
     # 3 seconds
     create_server_response = self.create_server(metadata=metadata)
     # verify the create server was successful
     self.assertEquals(create_server_response.code, 202)
     create_server_response_body = self.successResultOf(
         treq.json_content(create_server_response))
     # get server and verify status is BUILD
     get_server = request(self, self.root, "GET", self.uri + '/servers/' +
                          create_server_response_body["server"]["id"])
     get_server_response = self.successResultOf(get_server)
     get_server_response_body = self.successResultOf(
         treq.json_content(get_server_response))
     self.assertEquals(get_server_response_body['server']['status'], "BUILD")
     # Time Passes...
     self.helper.clock.advance(2.0)
     # get server and verify status changed to active
     get_server = request(self, self.root, "GET", self.uri + '/servers/' +
                          create_server_response_body["server"]["id"])
     get_server_response = self.successResultOf(get_server)
     get_server_response_body = self.successResultOf(
         treq.json_content(get_server_response))
     self.assertEquals(get_server_response_body['server']['status'], "ACTIVE")
Exemple #16
0
 def setUp(self):
     """
     Create a :obj:`MimicCore` with :obj:`QueueApi` as the only plugin,
     and create a queue
     """
     self.clock = Clock()
     self.core = MimicCore(self.clock, [QueueApi()])
     self.root = MimicRoot(self.core).app.resource()
     self.response = request(
         self, self.root, b"POST", "/identity/v2.0/tokens",
         json.dumps({
             "auth": {
                 "passwordCredentials": {
                     "username": "******",
                     "password": "******",
                 },
             }
         }).encode("utf-8")
     )
     self.auth_response = self.successResultOf(self.response)
     self.json_body = self.successResultOf(
         treq.json_content(self.auth_response))
     self.uri = self.json_body['access']['serviceCatalog'][0]['endpoints'][0]['publicURL']
     self.queue_name = "test_queue"
     self.create_queue = request(
         self, self.root, b"PUT", self.uri + '/queues/' + self.queue_name)
     self.create_queue_response = self.successResultOf(self.create_queue)
Exemple #17
0
 def test_put_object(self):
     """
     PUTting an object into a container causes the container to list that
     object.
     """
     self.createSwiftService()
     # create a container
     uri = (self.json_body['access']['serviceCatalog'][0]['endpoints'][0]
            ['publicURL'] + '/testcontainer')
     create_container = request(self, self.root, "PUT", uri)
     self.successResultOf(create_container)
     BODY = b'some bytes'
     object_uri = uri + "/" + "testobject"
     object_response = request(self,
                               self.root,
                               "PUT",
                               object_uri,
                               headers={"content-type": ["text/plain"]},
                               body=BODY)
     self.assertEqual(self.successResultOf(object_response).code, 201)
     container_response = self.successResultOf(
         request(self, self.root, "GET", uri))
     self.assertEqual(container_response.code, 200)
     container_contents = self.successResultOf(
         treq.json_content(container_response))
     self.assertEqual(len(container_contents), 1)
     self.assertEqual(container_contents[0]['name'], "testobject")
     self.assertEqual(container_contents[0]['content_type'], "text/plain")
     self.assertEqual(container_contents[0]['bytes'], len(BODY))
     object_response = self.successResultOf(
         request(self, self.root, "GET", object_uri))
     self.assertEqual(object_response.code, 200)
     object_body = self.successResultOf(treq.content(object_response))
     self.assertEquals(object_body, BODY)
Exemple #18
0
 def test_update_check(self):
     """
     update check
     """
     ecan = self.get_ecan_object_ids()
     req = request(
         self, self.root, "GET", self.uri + '/entities/' +
         ecan['entity_id'] + '/checks/' + ecan['check_id'], '')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     data['label'] = 'Iamamwhoami'
     req = request(
         self, self.root, "PUT", self.uri +
         '/entities/' + ecan['entity_id'] + '/checks/' + ecan['check_id'],
         json.dumps(data))
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 204)
     req = request(
         self, self.root, "GET", self.uri + '/entities/' +
         ecan['entity_id'] + '/checks/' + ecan['check_id'], '')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals('Iamamwhoami', data['label'])
Exemple #19
0
 def test_delete_alarm(self):
     """
     delete alarm
     """
     req = request(self, self.root, "DELETE",
                   self.uri + '/entities/' + self.entity_id + '/alarms/' + self.alarm_id)
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 204)
     req = request(self, self.root, "GET", self.uri + '/views/overview')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     self.assertEquals(0, len(self.get_responsebody(resp)['values'][0]['alarms']))
Exemple #20
0
    def test_delete_image(self):
        """
        Create and then delete Image and validate response
        """
        new_image = self.create_image()

        response = self.successResultOf(request(
            self, self.root, b"DELETE", self.uri + '/' + new_image['id']))
        self.assertEqual(204, response.code)

        response = self.successResultOf(request(
            self, self.root, b"GET", self.uri + '/' + new_image['id']))
        self.assertEqual(404, response.code)
Exemple #21
0
 def test_delete_entity(self):
     """
     delete entity
     """
     req = request(self, self.root, "DELETE",
                   self.uri + '/entities/' + self.entity_id)
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 204)
     req = request(self, self.root, "GET", self.uri + '/views/overview')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals(0, len(data['values']))
     self.assertEquals(0, data['metadata']['count'])
Exemple #22
0
 def test_delete_check(self):
     """
     delete check
     """
     req = request(self, self.root, "DELETE",
                   self.uri + '/entities/' + self.entity_id + '/checks/' + self.check_id)
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 204)
     req = request(self, self.root, "GET", self.uri + '/views/overview')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals(0, len(data['values'][0]['checks']))
     self.assertEquals(0, len(data['values'][0]['alarms']))
Exemple #23
0
 def test_delete_alarm(self):
     """
     delete alarm
     """
     req = request(
         self, self.root, "DELETE", self.uri + '/entities/' +
         self.entity_id + '/alarms/' + self.alarm_id)
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 204)
     req = request(self, self.root, "GET", self.uri + '/views/overview')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     self.assertEquals(
         0, len(self.get_responsebody(resp)['values'][0]['alarms']))
Exemple #24
0
 def test_delete_entity(self):
     """
     delete entity
     """
     req = request(self, self.root, "DELETE",
                   self.uri + '/entities/' + self.entity_id)
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 204)
     req = request(self, self.root, "GET", self.uri + '/views/overview')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals(0, len(data['values']))
     self.assertEquals(0, data['metadata']['count'])
Exemple #25
0
 def test_partial_update_entity(self):
     """
     Update an entity, fields not specified in the body don't change.
     """
     data = {'agent_id': 'ag13378901234'}
     req = request(self, self.root, "PUT", self.uri + '/entities/' + self.entity_id, json.dumps(data))
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 204)
     req = request(self, self.root, "GET", self.uri + '/entities/' + self.entity_id)
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals('ag13378901234', data['agent_id'])
     self.assertEquals('ItsAnEntity', data['label'])
Exemple #26
0
 def test_update_suppression(self):
     """
     Update an suppression
     """
     postdata = {'id': self.sp_id, 'label': 'changed'}
     req = request(self, self.root, "PUT", self.uri + '/suppressions/' + self.sp_id,
                   json.dumps(postdata))
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 204)
     req = request(self, self.root, "GET", self.uri + '/suppressions/' + self.sp_id)
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals('changed', data['label'])
Exemple #27
0
    def test_session_created_for_token(self):
        """
        A session is created for the token provided
        """
        core = MimicCore(Clock(), [])
        root = MimicRoot(core).app.resource()

        token = '1234567890'

        request(self, root, "GET",
                "/identity/v2.0/tokens/{0}/endpoints".format(token))

        session = core.sessions.session_for_token(token)
        self.assertEqual(token, session.token)
Exemple #28
0
 def test_delete_check(self):
     """
     delete check
     """
     req = request(
         self, self.root, "DELETE", self.uri + '/entities/' +
         self.entity_id + '/checks/' + self.check_id)
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 204)
     req = request(self, self.root, "GET", self.uri + '/views/overview')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals(0, len(data['values'][0]['checks']))
     self.assertEquals(0, len(data['values'][0]['alarms']))
Exemple #29
0
 def test_get_notification_plan(self):
     """
     Get a specific notification plan
     """
     req = request(self, self.root, "GET", self.uri + '/notification_plans/' + self.np_id)
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals(data['id'], self.np_id)
     req = request(self, self.root, "GET",
                   self.uri + '/notification_plans/npTechnicalContactsEmail')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals(data['id'], 'npTechnicalContactsEmail')
Exemple #30
0
    def test_session_created_for_token(self):
        """
        A session is created for the token provided
        """
        core, root = core_and_root([])

        token = '1234567890'

        request(
            self, root, "GET",
            "/identity/v2.0/tokens/{0}/endpoints".format(token)
        )

        session = core.sessions.session_for_token(token)
        self.assertEqual(token, session.token)
Exemple #31
0
    def test_delete_load_balancer_and_pending_delete_state(self):
        """
        Test to verify a load balancer goes into PENDING-DELETE state, for
        the given time in seconds and then goes into a DELETED status.
        Also, verify when a load balancer in PENDING-DELETE or DELETED status
        is deleted, response code 400 is returned.
        """
        metadata = [{"key": "lb_pending_delete", "value": 1}]
        lb = self._create_loadbalancer(metadata)

        # Verify the lb status goes into PENDING-DELETE
        del_lb_response = self._delete_loadbalancer(lb["id"])
        self.assertEqual(del_lb_response.code, 202)
        del_lb_content = self.successResultOf(treq.content(del_lb_response))
        self.assertEqual(del_lb_content, '')
        deleted_lb = self._get_loadbalancer(lb["id"])
        self.assertEqual(deleted_lb["loadBalancer"]["status"], "PENDING-DELETE")

        # Trying to delete a lb in PENDING-DELETE status results in 400
        self.assertEqual(self._delete_loadbalancer(lb["id"]).code, 400)
        self.helper.clock.advance(1.0000001)

        # Lb goes into DELETED status after time specified in metadata
        deleted_lb = self._get_loadbalancer(lb["id"])
        self.assertEqual(deleted_lb["loadBalancer"]["status"], "DELETED")

        # Trying to delete a lb in DELETED status results in 400
        self.assertEqual(self._delete_loadbalancer(lb["id"]).code, 400)

        # GET node on load balancer in DELETED status results in 410
        get_node = request(
            self, self.root, "GET", self.uri + '/loadbalancers/' +
            str(lb["id"]) + '/nodes/123')
        get_node_response = self.successResultOf(get_node)
        self.assertEqual(get_node_response.code, 410)

        # List node on load balancer in DELETED status results in 410
        list_nodes = request(
            self, self.root, "GET", self.uri + '/loadbalancers/' + str(lb["id"])
            + '/nodes')
        self.assertEqual(self.successResultOf(list_nodes).code, 410)

        # Progress past "deleting now"
        self.helper.clock.advance(4000)
        list_nodes = request(
            self, self.root, "GET", self.uri + '/loadbalancers/' + str(lb["id"])
            + '/nodes')
        self.assertEqual(self.successResultOf(list_nodes).code, 404)
Exemple #32
0
    def test_error_delete_keypair(self):
        resp = self.successResultOf(request(
            self, self.helper.root, b"DELETE", self.helper.uri +
            '/os-keypairs/keydoesntexist'
        ))

        self.assertEqual(resp.code, 404)
Exemple #33
0
 def test_delete_non_existant_image(self):
     """
     Return 404 when trying to DELETE a non existant image.
     """
     response = self.successResultOf(request(
         self, self.root, b"DELETE", self.uri + '/' + '1111'))
     self.assertEqual(404, response.code)
Exemple #34
0
    def test_delete_node(self):
        """
        Delete node returns 204 deletes the given node_id.
        """
        content = self.create_node()
        node_id = str(content['uuid'])

        # delete node
        response = self.successResultOf(request(
            self, self.root, "DELETE", self.url + '/' + node_id))
        self.assertEqual(response.code, 204)

        # get node
        response = self.successResultOf(request(
            self, self.root, "GET", self.url + '/' + node_id))
        self.assertEqual(404, response.code)
Exemple #35
0
 def createSuppression(self, label):
     postdata = {'label': label}
     req = request(self, self.root, "POST", self.uri + '/suppressions',
                   json.dumps(postdata))
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 201)
     return resp
Exemple #36
0
    def test_vendor_passthru_cache_image_fails_when_args_invalid(self):
        """
        Test ``/nodes/<node-id>/vendor_passthru/cache_image`` returns a 400 when
        the body for the request is invalid
        """
        new_node = self.create_node()
        node_id = new_node['uuid']

        body_list = [{
            "image_info": {}
        }, {
            "image": {
                "id": "111"
            }
        }, {
            "image_invalid": {
                "inv": None
            }
        }, {
            "image_info": {
                "id": None
            }
        }]
        for each in body_list:
            url = "/ironic/v1/nodes/{0}/vendor_passthru/cache_image".format(
                node_id)
            response = self.successResultOf(
                request(self,
                        self.root,
                        b"POST",
                        url,
                        body=json.dumps(each).encode("utf-8")))
            self.assertEqual(response.code, 400)
Exemple #37
0
    def test_delete_node(self):
        """
        Delete node returns 204 deletes the given node_id.
        """
        content = self.create_node()
        node_id = str(content['uuid'])

        # delete node
        response = self.successResultOf(
            request(self, self.root, b"DELETE", self.url + '/' + node_id))
        self.assertEqual(response.code, 204)

        # get node
        response = self.successResultOf(
            request(self, self.root, b"GET", self.url + '/' + node_id))
        self.assertEqual(404, response.code)
Exemple #38
0
    def test_vendor_passthru_cache_image_list_nodes(self):
        """
        Test ``/nodes/<node-id>/vendor_passthru/cache_image`` returns a 202 and
        sets the cache_image_id and cache_status on the node, and not the other nodes.
        """
        content1 = self.get_nodes('/detail')
        node_id = content1['nodes'].pop()['uuid']

        image_id = str(uuid4())
        body = {"image_info": {"id": image_id}}
        url = self.url + "/{0}/vendor_passthru/cache_image".format(node_id)
        response = self.successResultOf(
            request(self,
                    self.root,
                    b"POST",
                    url,
                    body=json.dumps(body).encode("utf-8")))
        self.assertEqual(response.code, 202)

        # GET node and verify the cache attributes on `driver_info`
        content = self.get_nodes('/' + str(node_id))
        self.assertEqual(content['driver_info']['cache_image_id'], image_id)
        self.assertEqual(content['driver_info']['cache_status'], 'cached')

        # verify the other nodes are not cached
        content2 = self.get_nodes('/detail')
        self.assertTrue(content1, content2)
        non_cached_nodes = [each for each in content2['nodes']]
        non_cached_nodes.pop()
        for each in non_cached_nodes:
            self.assertFalse(each['driver_info']['cache_image_id'])
            self.assertFalse(each['driver_info']['cache_status'])
Exemple #39
0
 def test_same_client_message_is_invisible(self):
     """
     By default, the client does not see messages they themselves posted.
     """
     (resp, data) = self.successResultOf(
         json_request(self,
                      self.root,
                      b"POST",
                      '{0}/queues/{1}/messages'.format(
                          self.uri, self.queue_name), [{
                              'ttl': 60,
                              'body': {
                                  'text': 'Wow'
                              }
                          }],
                      headers={b'Client-ID': [b'client-1']}))
     self.assertEquals(resp.code, 201)
     self.assertEquals(len(data['resources']), 1)
     resp = self.successResultOf(
         request(self,
                 self.root,
                 b"GET",
                 '{0}/queues/{1}/messages'.format(self.uri,
                                                  self.queue_name),
                 headers={b'Client-ID': [b'client-1']}))
     self.assertEquals(resp.code, 204)
Exemple #40
0
    def test_template_validate(self):
        """
        Test template validation, ensuring correct JSON response.
        """
        req_bodies = {'url': {'template_url': "http://bogus.url/here"},
                      'inline': {'template': "http://bogus.url/here"},
                      'wrong': {}}

        requests = dict(
            (key, request(self, self.root, b"POST", self.uri + '/validate',
                          body=json.dumps(body).encode("utf-8")))
            for (key, body) in req_bodies.items()
        )

        responses = dict(
            (key, self.successResultOf(req)) for (key, req) in requests.items()
        )

        resp_bodies = dict(
            (key, self.get_responsebody(resp))
            for (key, resp) in responses.items() if key != 'wrong')

        self.assertEqual(responses['url'].code, 200)
        self.assertEqual(responses['inline'].code, 200)
        self.assertEqual(responses['wrong'].code, 400)

        self.assertTrue('Parameters' in resp_bodies['url'])
        self.assertTrue('Parameters' in resp_bodies['inline'])
Exemple #41
0
 def test_jsonhome(self):
     req = request(self, self.root, "GET",
                   self.uri + '/__experiments/json_home', '')
     resp = self.successResultOf(req)
     self.assertEquals(resp.code, 200)
     data = self.get_responsebody(resp)
     self.assertEquals(True, 'mimicking' in json.dumps(data))
Exemple #42
0
 def test_old_messages_expire(self):
     """
     Messages expire after their TTL.
     """
     (resp, data) = self.successResultOf(
         json_request(self,
                      self.root,
                      b"POST",
                      '{0}/queues/{1}/messages'.format(
                          self.uri, self.queue_name), [{
                              'ttl': 60,
                              'body': {
                                  'text': 'Wow'
                              }
                          }],
                      headers={b'Client-ID': [b'client-1']}))
     self.assertEquals(resp.code, 201)
     self.assertEquals(len(data['resources']), 1)
     self.clock.advance(61)
     resp = self.successResultOf(
         request(self,
                 self.root,
                 b"GET",
                 '{0}/queues/{1}/messages?echo=true'.format(
                     self.uri, self.queue_name),
                 headers={b'Client-ID': [b'client-2']}))
     self.assertEquals(resp.code, 204)
Exemple #43
0
 def test_get_non_existant_image(self):
     """
     Return 404 when trying to GET a non existant image.
     """
     response = self.successResultOf(
         request(self, self.root, "GET", self.uri + '/' + '1111'))
     self.assertEqual(404, response.code)
Exemple #44
0
    def create_server(self,
                      name=None,
                      imageRef=None,
                      flavorRef=None,
                      metadata=None,
                      body='default'):
        """
        Creates a server with the given specifications and returns the response
        object

        :param name: Name of the server
        :param imageRef: Image of the server
        :param flavorRef: Flavor size of the server
        :param metadat: Metadata of the server
        """
        if body == 'default':
            json_request = json.dumps({
                "server": {
                    "name": name or 'test_server',
                    "imageRef": imageRef or "test-image",
                    "flavorRef": flavorRef or "test-flavor",
                    "metadata": metadata or {}
                }
            })
        elif body is None:
            json_request = ""
        else:
            json_request = body

        create_server = request(self, self.root, "POST", self.uri + '/servers',
                                json_request)
        create_server_response = self.successResultOf(create_server)
        return create_server_response
Exemple #45
0
 def test_create_server_failure_using_behaviors(self):
     """
     :func:`create_server` fails with given error message and response code
     when a behavior is registered that matches its hostname.
     """
     serverfail = {"message": "Create server failure", "code": 500}
     criterion = {
         "name": "fail",
         "parameters": serverfail,
         "criteria": [{
             "server_name": "failing_server_name"
         }]
     }
     set_criteria = request(
         self, self.root, "POST",
         self.nova_control_endpoint + "/behaviors/creation/",
         json.dumps(criterion))
     set_criteria_response = self.successResultOf(set_criteria)
     self.assertEqual(set_criteria_response.code, 201)
     create_server_response = self.create_server(name="failing_server_name")
     self.assertEquals(create_server_response.code, 500)
     create_server_response_body = self.successResultOf(
         treq.json_content(create_server_response))
     self.assertEquals(create_server_response_body['message'],
                       "Create server failure")
     self.assertEquals(create_server_response_body['code'], 500)
Exemple #46
0
 def test_get_non_existant_loadbalancer(self):
     """
     Test to verify :func:`get_load_balancers` for a non existant load balancer id.
     """
     get_lb = request(self, self.root, "GET", self.uri + '/loadbalancers/123')
     get_lb_response = self.successResultOf(get_lb)
     self.assertEqual(get_lb_response.code, 404)
Exemple #47
0
    def _validate_provisioning(self, new_provision_state):
        """
        Creates a node and verifies the node is 'available'.
        Changes the provision_state of the nodes to `new_provision_state`
        and verifies the state is set.
        Returns the node object after the update.
        """
        # create a node
        content = self.create_node()
        node_id = content['uuid']
        provision_state = content['provision_state']
        self.assertEqual(provision_state, 'available')

        # Change the provision_state
        url = self.url + "/{0}/states/provision".format(node_id)
        response = self.successResultOf(
            request(self,
                    self.root,
                    b"PUT",
                    url,
                    body=json.dumps({
                        'target': new_provision_state
                    }).encode("utf-8")))
        self.assertEqual(response.code, 202)

        content = self.get_nodes('/' + str(node_id))
        return content
Exemple #48
0
 def test_load_balancer_goes_into_error_state_when_adding_node(self):
     """
     Test to verify a load balancer goes into error state when adding a node.
     Adding a node to a loadbalancer in ERROR state results in 422.
     And such a load balancer can only be deleted.
     """
     metadata = [{"key": "lb_error_state", "value": "error"}]
     create_response = self._create_loadbalancer_for_given_metadata(metadata)
     self.assertEqual(create_response.code, 202)
     create_lb_response_body = self.successResultOf(treq.json_content(create_response))
     lb = create_lb_response_body["loadBalancer"]
     self.assertEqual(lb["status"], "ACTIVE")
     create_node_response = self._add_node_to_lb(lb["id"])
     self.assertEqual(create_node_response.code, 200)
     # get loadbalncer after adding node and verify its in error state
     errored_lb = self._get_loadbalancer(lb["id"])
     self.assertEqual(errored_lb["loadBalancer"]["status"], "ERROR")
     # adding another node to a lb in ERROR state, results in 422
     create_node_response = self._add_node_to_lb(lb["id"])
     self.assertEqual(create_node_response.code, 422)
     # An lb in ERROR state can be deleted
     delete_lb = request(self, self.root, "DELETE", self.uri + '/loadbalancers/' +
                         str(lb["id"]))
     delete_lb_response = self.successResultOf(delete_lb)
     self.assertEqual(delete_lb_response.code, 202)
Exemple #49
0
    def test_vendor_passthru_cache_image(self):
        """
        Test ``/nodes/<node-id>/vendor_passthru/cache_image`` returns a 202 and
        sets the cache_image_id and cache_status on the node
        """
        new_node = self.create_node({'properties': {'memory_mb': 131072}})
        node_id = new_node['uuid']

        self.assertFalse(new_node['driver_info'].get('cache_image_id'))
        self.assertFalse(new_node['driver_info'].get('cache_status'))

        image_id = str(uuid4())
        body = {"image_info": {"id": image_id}}
        url = self.url + "/{0}/vendor_passthru/cache_image".format(node_id)
        response = self.successResultOf(
            request(self,
                    self.root,
                    b"POST",
                    url,
                    body=json.dumps(body).encode("utf-8")))
        self.assertEqual(response.code, 202)

        # GET node and verify the cache attributes on `driver_info`
        content = self.get_nodes('/' + str(node_id))
        self.assertEqual(content['driver_info']['cache_image_id'], image_id)
        self.assertEqual(content['driver_info']['cache_status'], 'cached')
Exemple #50
0
 def test_list_queues(self):
     """
     Test to verify :func:`list_queues` on ``GET /v2.0/<tenant_id>/queues``
     """
     list_queues = request(self, self.root, b"GET", self.uri + '/queues')
     list_queues_response = self.successResultOf(list_queues)
     self.assertEqual(list_queues_response.code, 200)
Exemple #51
0
 def test_add_load_balancer_with_nodes(self):
     """
     Test to verify :func:`add_load_balancer` on ``POST /v1.0/<tenant_id>/loadbalancers``,
     with nodes
     """
     lb_name = 'mimic_lb'
     create_lb = request(
         self, self.root, "POST", self.uri + '/loadbalancers',
         json.dumps({
             "loadBalancer": {
                 "name": lb_name,
                 "protocol": "HTTP",
                 "virtualIps": [{"type": "PUBLIC"}],
                 "nodes": [{"address": "127.0.0.2",
                            "port": 80,
                            "condition": "ENABLED",
                            "type": "PRIMARY"},
                           {"address": "127.0.0.0",
                            "port": 80,
                            "condition": "ENABLED",
                            "type": "SECONDARY"}]
             }
         })
     )
     create_lb_response = self.successResultOf(create_lb)
     create_lb_response_body = self.successResultOf(treq.json_content(create_lb_response))
     self.assertEqual(create_lb_response.code, 202)
     self.assertEqual(len(create_lb_response_body['loadBalancer']['nodes']), 2)
    def test_update_endpoint_template(self, has_service_header):
        """
        PUT to update an endpoint template results in 201, service-id
        header is optional.
        """
        self.core.add_api(self.eeapi)
        id_key = get_template_id(self, self.eeapi)

        eeapi2 = make_example_external_api(
            self,
            name=self.eeapi_name + text_type(uuid.uuid4()),
            service_type='service-' + text_type(uuid.uuid4()))
        eeapi2.remove_template(get_template_id(self, eeapi2))
        self.core.add_api(eeapi2)

        data = {
            'id': id_key,
            'name': self.eeapi_name,
            'type': self.eeapi.type_key,
            'region': 'some-region'
        }

        if has_service_header:
            self.headers[b'serviceid'] = [self.eeapi.uuid_key.encode('utf8')]

        req = request(self,
                      self.root,
                      self.verb,
                      self.uri,
                      body=json.dumps(data).encode("utf-8"),
                      headers=self.headers)

        response = self.successResultOf(req)
        self.assertEqual(response.code, 201)
Exemple #53
0
 def test_delete_non_existant_loadbalancer(self):
     """
     Test to verify :func:`delete_load_balancers` for a non existant load balancer.
     """
     delete_lb = request(self, self.root, 'DELETE', self.uri + '/loadbalancers/123')
     delete_lb_response = self.successResultOf(delete_lb)
     self.assertEqual(delete_lb_response.code, 404)
Exemple #54
0
 def test_list_queues(self):
     """
     Test to verify :func:`list_queues` on ``GET /v2.0/<tenant_id>/queues``
     """
     list_queues = request(self, self.root, b"GET", self.uri + '/queues')
     list_queues_response = self.successResultOf(list_queues)
     self.assertEqual(list_queues_response.code, 200)
Exemple #55
0
 def _delete_loadbalancer(self, lb_id):
     """
     Deletes the given load balancer id and returns the response
     """
     delete_lb = request(self, self.root, "DELETE", self.uri + '/loadbalancers/' +
                         str(lb_id))
     return self.successResultOf(delete_lb)
Exemple #56
0
 def test_get_server_ips(self):
     """
     Test to verify :func:`get_ips` on ``GET /v2.0/<tenant_id>/servers/<server_id>/ips``
     """
     get_server_ips = request(self, self.root, "GET",
                              self.uri + '/servers/' + self.server_id + '/ips')
     get_server_ips_response = self.successResultOf(get_server_ips)
     get_server_ips_response_body = self.successResultOf(
         treq.json_content(get_server_ips_response))
     self.assertEqual(get_server_ips_response.code, 200)
     list_servers_detail = request(self, self.root, "GET", self.uri + '/servers/detail')
     list_servers_detail_response = self.successResultOf(list_servers_detail)
     list_servers_detail_response_body = self.successResultOf(
         treq.json_content(list_servers_detail_response))
     self.assertEqual(get_server_ips_response_body['addresses'],
                      list_servers_detail_response_body['servers'][0]['addresses'])
Exemple #57
0
 def createSwiftService(self, rackspace_flavor=True):
     """
     Set up to create the requests
     """
     self.swift_mock = SwiftMock(rackspace_flavor)
     self.core = MimicCore(Clock(), [self.swift_mock])
     self.root = MimicRoot(self.core).app.resource()
     self.response = request(
         self,
         self.root,
         b"POST",
         b"/identity/v2.0/tokens",
         dumps({
             "auth": {
                 "passwordCredentials": {
                     "username": "******",
                     "password": "******",
                 },
                 # TODO: should this really be 'tenantId'?
                 "tenantName": "fun_tenant",
             }
         }).encode("utf-8"))
     self.auth_response = self.successResultOf(self.response)
     text_body = self.successResultOf(treq.content(
         self.auth_response)).decode("utf-8")
     self.json_body = loads(text_body)
Exemple #58
0
    def test_vendor_passthru_cache_image_list_nodes(self):
        """
        Test ``/nodes/<node-id>/vendor_passthru/cache_image`` returns a 202 and
        sets the cache_image_id and cache_status on the node, and not the other nodes.
        """
        content1 = self.get_nodes('/detail')
        node_id = content1['nodes'].pop()['uuid']

        image_id = str(uuid4())
        body = {"image_info": {"id": image_id}}
        url = self.url + "/{0}/vendor_passthru/cache_image".format(node_id)
        response = self.successResultOf(request(
            self, self.root, "POST", url, body=json.dumps(body)))
        self.assertEqual(response.code, 202)

        # GET node and verify the cache attributes on `driver_info`
        content = self.get_nodes('/' + str(node_id))
        self.assertEqual(content['driver_info']['cache_image_id'], image_id)
        self.assertEqual(content['driver_info']['cache_status'], 'cached')

        # verify the other nodes are not cached
        content2 = self.get_nodes('/detail')
        self.assertTrue(content1, content2)
        non_cached_nodes = [each for each in content2['nodes']]
        non_cached_nodes.pop()
        for each in non_cached_nodes:
            self.assertFalse(each['driver_info']['cache_image_id'])
            self.assertFalse(each['driver_info']['cache_status'])