def test_same_client_message_shows_with_echo(self): """ With echo=true, the client can see messages they 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, data) = self.successResultOf( json_request(self, self.root, b"GET", '{0}/queues/{1}/messages?echo=true'.format( self.uri, self.queue_name), headers={b'Client-ID': [b'client-1']})) self.assertEquals(resp.code, 200) self.assertEquals(data['messages'][0]['body']['text'], 'Wow')
def test_post_and_list_messages(self): """ Posting a message to the queue should cause the message to be visible to another client. """ (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, data) = self.successResultOf( json_request(self, self.root, b"GET", '{0}/queues/{1}/messages'.format( self.uri, self.queue_name), headers={b'Client-ID': [b'client-2']})) self.assertEquals(resp.code, 200) self.assertEquals(data['messages'][0]['body']['text'], 'Wow')
def test_response_has_same_roles_despite_number_of_auths(self): """ The JSON response for authenticate has only one `identity:user-admin` role, no matter how many times the user authenticates. """ core = MimicCore(Clock(), []) root = MimicRoot(core).app.resource() creds = { "auth": { "passwordCredentials": { "username": "******", "password": "******" } } } self.successResultOf( json_request(self, root, "POST", "/identity/v2.0/tokens", creds)) self.successResultOf( json_request(self, root, "POST", "/identity/v2.0/tokens", creds)) (response, json_body) = self.successResultOf( json_request(self, root, "POST", "/identity/v2.0/tokens", creds)) self.assertEqual(200, response.code) self.assertEqual(json_body['access']['user']['roles'], HARD_CODED_ROLES)
def test_check_domains(self): """ ``GET/service/{service_id}/version/{version_id}/domain/check_all`` against Fastly mock returns an array with the status of all domain DNS records for a service version. """ uri = self.uri + '/service/{0}/version/{1}/domain' \ '?name=llamallama&comment=redpajama'.format( self.service_id, self.version_id) (response, json_body) = self.successResultOf(json_request( self, self.root, b"POST", uri)) uri = self.uri + '/service/{0}/version/{1}/domain/check_all' \ '?name=llamallama&comment=redpajama'.format( self.service_id, self.version_id) (response, json_body) = self.successResultOf(json_request( self, self.root, b"GET", uri)) domain_details = self.fastly_response.check_domains( service_id=self.service_id, service_version=self.version_id) self.assertEqual(200, response.code) self.assertEqual(sorted(json_body), sorted(domain_details))
def test_create_service(self): """ ``POST /service`` against the fastly API mock stores the created service and returns JSON-serialized service details. """ service_details = self.fastly_response.create_service([ ('customer_id', [self.customer_id]), ('name', [self.service_name]) ]) self.assertEqual(200, self.response.code) self.assertEqual(sorted(self.service_json), sorted(service_details)) (response, json_by_service_name) = self.successResultOf( json_request( self, self.root, "GET", self.uri + '/service/search?name={0}'.format(self.service_name))) self.assertEqual(200, self.response.code) (response, json_by_service_id) = self.successResultOf( json_request( self, self.root, "GET", self.uri + '/service/{0}/details'.format(self.service_id))) self.assertEqual(200, self.response.code) self.assertEqual(sorted(json_by_service_name['service_details']), sorted(json_by_service_id['versions'][0]))
def test_check_existing_username_is_true(self): """ Checking a username that exists gets a true response. """ (resp, _) = self.successResultOf(json_request( self, self.root, b"POST", '{0}/yo/'.format(self.uri), json.dumps({'username': '******', 'api_key': 'A1234567890'}).encode("utf-8"))) self.assertEquals(resp.code, 200) (resp, data) = self.successResultOf(json_request( self, self.root, b"GET", '{0}/check_username/?username=TESTUSER4'.format(self.uri))) self.assertEquals(resp.code, 200) self.assertEquals(data['exists'], True)
def test_create_then_get_node_with_mimimum_attributes(self): """ Test create node then get the node and verify attributes """ (response, content) = self.successResultOf( json_request(self, self.root, b"POST", self.url, body={})) self.assertEqual(response.code, 201) node_id = str(content['uuid']) self.assertFalse(content['properties']['memory_mb']) # get node (response, get_content) = self.successResultOf( json_request(self, self.root, b"GET", self.url + '/' + node_id)) self.assertEqual(200, response.code) self.assertEqual(content, get_content)
def test_create_then_get_node_with_mimimum_attributes(self): """ Test create node then get the node and verify attributes """ (response, content) = self.successResultOf(json_request( self, self.root, "POST", self.url, body=json.dumps({}))) self.assertEqual(response.code, 201) node_id = str(content['uuid']) self.assertFalse(content['properties']['memory_mb']) # get node (response, get_content) = self.successResultOf(json_request( self, self.root, "GET", self.url + '/' + node_id)) self.assertEqual(200, response.code) self.assertEqual(content, get_content)
def test_auth_accepts_tenant_id(self): """ If "tenantId" is passed, the tenant specified is used instead of a generated tenant ID. """ core = MimicCore(Clock(), []) root = MimicRoot(core).app.resource() (response, json_body) = self.successResultOf( json_request( self, root, "POST", "/identity/v2.0/tokens", { "auth": { "passwordCredentials": { "username": "******", "password": "******" }, "tenantId": "turtlepower" } })) self.assertEqual(200, response.code) self.assertEqual("turtlepower", json_body['access']['token']['tenant']['id']) token = json_body['access']['token']['id'] session = core.sessions.session_for_token(token) self.assertEqual(token, session.token) self.assertEqual("turtlepower", session.tenant_id)
def register_behavior(test_case, root, uri, behavior_name, parameters, criteria): """ Register a particular behavior. :param test_case: the test case with which to make assertions :param root: A mimic root API object :param str uri: The uri fo the behavior resource to register. :param str behavior_name: The name of the behavior :param dict parameters: A dictionary of parameters to pass to the behavior :param list criteria: The criteria for which this behavior should be applied. :return: The behavior ID of the registered behavior. """ behavior_json = {"name": behavior_name, "parameters": parameters, "criteria": criteria} response, body = test_case.successResultOf(json_request( test_case, root, "POST", uri, json.dumps(behavior_json))) test_case.assertEqual(response.code, 201) behavior_id = body.get("id") test_case.assertIsInstance(behavior_id, string_types) test_case.assertEqual(UUID(behavior_id).version, 4) return behavior_id
def test_api_service_endpoints_are_not_duplicated(self): """ The service catalog should not duplicate endpoints for an entry/endpoints """ regions_and_versions_list = [("ORD", "v1"), ("DFW", "v1"), ("DFW", "v2"), ("IAD", "v3")] core = MimicCore(Clock(), [ExampleAPI(regions_and_versions=regions_and_versions_list)]) root = MimicRoot(core).app.resource() (response, json_body) = self.successResultOf(json_request( self, root, "POST", "/identity/v2.0/tokens", { "auth": { "passwordCredentials": { "username": "******", "password": "******" } } } )) self.assertEqual(response.code, 200) service_catalog = json_body["access"]["serviceCatalog"] self.assertEqual(len(service_catalog), 1) endpoints_list = service_catalog[0]["endpoints"] self.assertEqual(len(endpoints_list), 4)
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)
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)
def test_response_service_catalog_has_base_uri(self): """ The JSON response's service catalog whose endpoints all begin with the same base URI as the request. """ core = MimicCore(Clock(), [ExampleAPI()]) root = MimicRoot(core).app.resource() (response, json_body) = self.successResultOf(json_request( self, root, "POST", "http://mybase/identity/v2.0/tokens", { "auth": { "passwordCredentials": { "username": "******", "password": "******" } } } )) self.assertEqual(200, response.code) services = json_body['access']['serviceCatalog'] self.assertEqual(1, len(services)) urls = [ endpoint['publicURL'] for endpoint in services[0]['endpoints'] ] self.assertEqual(1, len(urls)) self.assertTrue(urls[0].startswith('http://mybase/'), '{0} does not start with "http://mybase"' .format(urls[0]))
def test_create_condition(self): """ ``POST /service/{service_id}/version/{version_id}/condition`` against Fastly mock creates a condition (rule) for a particular service and version and returns JSON-serialized response. """ uri = self.uri + '/service/{0}/version/{1}/condition' \ '?name=testcondition&statement=req.url~+"index.html"&priority=10'.format( self.service_id, self.version_id) (response, json_body) = self.successResultOf(json_request( self, self.root, b"POST", uri)) url_data = [ ('name', ['testcondition']), ('statement', ['req.url~+"index.html"']), ('priority', [10]) ] condition = self.fastly_response.create_condition( url_data=url_data, service_id=self.service_id, service_version=self.version_id) self.assertEqual(200, response.code) self.assertEqual(sorted(json_body), sorted(condition))
def test_json_body_missing_required_field_name(self, remove_field): """ PUT - required fields must be present otherwise 400 is generated. """ data = { 'id': self.ept_template_id, 'name': 'some-name', 'type': 'some-type', 'region': 'some-region' } del data[remove_field] (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, body=data, headers=self.headers)) self.assertEqual(response.code, 400) self.assertEqual(json_body['badRequest']['code'], 400) self.assertTrue( json_body['badRequest']['message'].startswith( "JSON body does not contain the required parameters:" ) )
def test_new_endpoint_template_wrong_service_type(self): """ POST requires that the endpoint template and service have the same service types. """ self.core.add_api(self.eeapi) id_key = get_template_id(self, self.eeapi) data = { 'id': text_type(uuid.uuid4()), 'name': self.eeapi_name, 'type': 'some-type', 'region': 'some-region' } self.assertNotEqual(id_key, data['id']) (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, body=data, headers=self.headers)) self.assertEqual(response.code, 409) self.assertEqual(json_body['conflict']['code'], 409) self.assertEqual( json_body['conflict']['message'], "Endpoint already exists or service type does not match." )
def test_existing_endpoint_template(self): """ POST does not overwrite an existing endpoint template, 409 is generated instead. """ self.core.add_api(self.eeapi) id_key = get_template_id(self, self.eeapi) data = { 'id': id_key, 'name': self.eeapi_name, 'type': 'some-type', 'region': 'some-region' } (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, body=data, headers=self.headers)) self.assertEqual(response.code, 409) self.assertEqual(json_body['conflict']['code'], 409) self.assertEqual( json_body['conflict']['message'], "ID value is already assigned to an existing template" )
def test_invalid_service_id_in_json_body(self): """ POST - Service ID must be valid, otherwise results in 404. """ # Add a second API eeapi2 = make_example_external_api( self, name='d' + self.eeapi_name + text_type(uuid.uuid4()), service_type='service-' + text_type(uuid.uuid4()) ) eeapi2.id_key = '0' # ensure only one instance of the API has the endpoint template eeapi2.remove_template(get_template_id(self, eeapi2)) self.core.add_api(eeapi2) self.core.add_api(self.eeapi) data = { 'id': text_type(uuid.uuid4()), 'name': 'some-name', 'type': 'some-type', 'region': 'some-region' } (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, body=data, headers=self.headers)) self.assertEqual(response.code, 404) self.assertEqual(json_body['itemNotFound']['code'], 404) self.assertEqual( json_body['itemNotFound']['message'], "Service API for endoint template not found" )
def test_multiple_external_apis(self): """ GET can retrieve numerous External APIs that have External API Templates. """ api_list = [ make_example_external_api( self, name=self.eeapi_name + text_type(uuid.uuid4()), service_type='service-' + text_type(uuid.uuid4()) ) for ignored in range(10) ] # eeapi needs to be the first in the list api_list.insert(0, self.eeapi) for api in api_list: self.core.add_api(api) self.assertEqual(len(self.core._uuid_to_api_external), len(api_list)) (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, headers=self.headers)) self.assertEqual(response.code, 200) self.assertEqual(len(json_body['OS-KSCATALOG']), len(api_list)) self.assertEqual( len(json_body['OS-KSCATALOG:endpointsTemplates_links']), 0)
def test_json_body_missing_required_field(self, remove_field): """ POST requires 'name' field otherwise 400 is generated. """ # normal JSON body data = { 'type': 'some-type', 'name': 'some-name' } # remove a portion of the body per the DDT data del data[remove_field] # POST the resulting JSON to the REST API (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, body=data, headers=self.headers)) # API should return 400 since a required field is missing self.assertEqual(response.code, 400) self.assertEqual(json_body['badRequest']['code'], 400) self.assertEqual(json_body['badRequest']['message'], "Invalid Content. 'name' and 'type' fields are " "required.")
def test_multiple_external_apis(self): """ GET will list multiple external APIs. """ api_list = [ make_example_external_api( self, name=self.eeapi_name + text_type(uuid.uuid4()), service_type='service-' + text_type(uuid.uuid4()), set_enabled=True) for ignored in range(10) ] # eeapi should be the first entry in the list api_list.insert(0, self.eeapi) for api in api_list: self.core.add_api(api) self.assertEqual(len(self.core._uuid_to_api_external), len(api_list)) (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, headers=self.headers)) def get_header(header_name): return response.headers.getRawHeaders(header_name)[0].decode( "utf-8") self.assertEqual(response.code, 200) self.assertEqual(len(json_body['endpoints']), len(api_list)) self.assertEqual(len(json_body['endpoints_links']), 0)
def test_api_service_endpoints_are_not_duplicated(self): """ The service catalog should not duplicate endpoints for an entry/endpoints """ regions_and_versions_list = [("ORD", "v1"), ("DFW", "v1"), ("DFW", "v2"), ("IAD", "v3")] core = MimicCore( Clock(), [ExampleAPI(regions_and_versions=regions_and_versions_list)]) root = MimicRoot(core).app.resource() (response, json_body) = self.successResultOf( json_request( self, root, "POST", "/identity/v2.0/tokens", { "auth": { "passwordCredentials": { "username": "******", "password": "******" } } })) self.assertEqual(response.code, 200) service_catalog = json_body["access"]["serviceCatalog"] self.assertEqual(len(service_catalog), 1) endpoints_list = service_catalog[0]["endpoints"] self.assertEqual(len(endpoints_list), 4)
def test_get_token_and_catalog_for_token_credentials(self): """ The response returned should include the credentials that were supplied during authentication """ core = MimicCore(Clock(), [ExampleAPI()]) root = MimicRoot(core).app.resource() (response, json_body) = self.successResultOf( json_request( self, root, "POST", "/identity/v2.0/tokens", { "auth": { "tenantId": "12345", "token": { "id": "iuyiuyiuy-uyiuyiuy-1987878" } } })) self.assertEqual(response.code, 200) tenant_id = json_body["access"]["token"]["tenant"]["id"] self.assertEqual(tenant_id, "12345") tenant_name = json_body["access"]["token"]["tenant"]["name"] self.assertEqual(tenant_name, tenant_id) user_name = json_body["access"]["user"]["name"] self.assertTrue(user_name)
def test_new_endpoint_template_wrong_service_type(self): """ PUT requires that the service matches, otherwise results in 409. """ self.core.add_api(self.eeapi) data = { 'id': self.ept_template_id, 'name': self.eeapi_name, 'type': 'some-type', 'region': 'some-region' } (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, body=data, headers=self.headers)) self.assertEqual(response.code, 409) self.assertEqual(json_body['conflict']['code'], 409) self.assertEqual( json_body['conflict']['message'], "Endpoint already exists and service id or service type does not " "match." )
def test_create_response_object(self): """ ``POST /service/{service_id}/version/{version_id}/response_object`` against Fastly mock creates a response_object for a particular service and version and returns JSON-serialized response. """ uri = self.uri + '/service/{0}/version/{1}/response_object' \ '?status=200&response=Ok&name=testresponse&content=this+message+means+all+is+okay'.format( self.service_id, self.version_id) (response, json_body) = self.successResultOf(json_request( self, self.root, b"POST", uri)) url_data = [ ('status', ['200']), ('response', ['Ok']), ('cache_condition', [""]), ('request_condition', [""]), ('name', ['testresponse']), ('content', ['this+message+means+all+is+okay']), ('content_type', ["text/plain"]), ('service_id', [self.service_id]) ] response_object = self.fastly_response.create_response_object( url_data=url_data, service_id=self.service_id, service_version=self.version_id) self.assertEqual(200, response.code) self.assertEqual(sorted(json_body), sorted(response_object))
def test_json_body_id_value_not_matching_url(self): """ PUT requires that the endpoint template id in the URL and JSON data match, otherwise results in 409. """ self.core.add_api(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': 'some-random-key', 'name': self.eeapi_name, 'type': self.eeapi.type_key, 'region': 'some-region' } (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, body=data, headers=self.headers)) self.assertEqual(response.code, 409) self.assertEqual(json_body['conflict']['code'], 409) self.assertEqual( json_body['conflict']['message'], "Template ID in URL does not match that of the JSON body" )
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'])
def test_invalid_template_id(self): """ PUT requires the endpoint template id to match an existing endpoint template, otherwise results in 404. """ self.core.add_api(self.eeapi) id_key = get_template_id(self, self.eeapi) self.eeapi.remove_template(id_key) data = { 'id': id_key, 'name': self.eeapi_name, 'type': self.eeapi.type_key, 'region': 'some-region' } self.headers[b'serviceid'] = [self.eeapi.uuid_key.encode('utf8')] (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, body=data, headers=self.headers)) self.assertEqual(response.code, 404) self.assertEqual(json_body['itemNotFound']['code'], 404) self.assertEqual( json_body['itemNotFound']['message'], "Unable to update non-existent template. Template must " "first be added before it can be updated.", )
def test_get_token_and_catalog_for_token_credentials(self): """ The response returned should include the credentials that were supplied during authentication """ core = MimicCore(Clock(), [ExampleAPI()]) root = MimicRoot(core).app.resource() (response, json_body) = self.successResultOf(json_request( self, root, "POST", "/identity/v2.0/tokens", { "auth": { "tenantId": "12345", "token": { "id": "iuyiuyiuy-uyiuyiuy-1987878" } } } )) self.assertEqual(response.code, 200) tenant_id = json_body["access"]["token"]["tenant"]["id"] self.assertEqual(tenant_id, "12345") tenant_name = json_body["access"]["token"]["tenant"]["name"] self.assertEqual(tenant_name, tenant_id) user_name = json_body["access"]["user"]["name"] self.assertTrue(user_name)
def test_multiple_external_apis(self): """ GET will list multiple external APIs. """ api_list = [ make_example_external_api( self, name=self.eeapi_name + text_type(uuid.uuid4()), service_type='service-' + text_type(uuid.uuid4()), set_enabled=True ) for ignored in range(10) ] # eeapi should be the first entry in the list api_list.insert(0, self.eeapi) for api in api_list: self.core.add_api(api) self.assertEqual(len(self.core._uuid_to_api_external), len(api_list)) (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, headers=self.headers)) def get_header(header_name): return response.headers.getRawHeaders(header_name)[0].decode("utf-8") self.assertEqual(response.code, 200) self.assertEqual(len(json_body['endpoints']), len(api_list)) self.assertEqual(len(json_body['endpoints_links']), 0)
def test_get_token_and_catalog_for_api_credentials(self): """ The response returned should include the credentials that were supplied during authentication """ core = MimicCore(Clock(), [ExampleAPI()]) root = MimicRoot(core).app.resource() (response, json_body) = self.successResultOf(json_request( self, root, "POST", "/identity/v2.0/tokens", { "auth": { "RAX-KSKEY:apiKeyCredentials": { "username": "******", "apiKey": "jhgjhghg-nhghghgh-12222" }, "tenantName": "12345" } } )) self.assertEqual(response.code, 200) tenant_id = json_body["access"]["token"]["tenant"]["id"] self.assertEqual(tenant_id, "12345") tenant_name = json_body["access"]["token"]["tenant"]["name"] self.assertEqual(tenant_name, tenant_id) user_name = json_body["access"]["user"]["name"] self.assertEqual(user_name, "demoauthor")
def test_invalid_service_id_in_json_body(self): """ POST - Service ID must be valid, otherwise results in 404. """ # Add a second API eeapi2 = make_example_external_api( self, name='d' + self.eeapi_name + text_type(uuid.uuid4()), service_type='service-' + text_type(uuid.uuid4())) eeapi2.id_key = '0' # ensure only one instance of the API has the endpoint template eeapi2.remove_template(get_template_id(self, eeapi2)) self.core.add_api(eeapi2) self.core.add_api(self.eeapi) data = { 'id': text_type(uuid.uuid4()), 'name': 'some-name', 'type': 'some-type', 'region': 'some-region' } (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, body=data, headers=self.headers)) self.assertEqual(response.code, 404) self.assertEqual(json_body['itemNotFound']['code'], 404) self.assertEqual(json_body['itemNotFound']['message'], "Service API for endoint template not found")
def test_existing_endpoint_template(self): """ POST does not overwrite an existing endpoint template, 409 is generated instead. """ self.core.add_api(self.eeapi) id_key = get_template_id(self, self.eeapi) data = { 'id': id_key, 'name': self.eeapi_name, 'type': 'some-type', 'region': 'some-region' } (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, body=data, headers=self.headers)) self.assertEqual(response.code, 409) self.assertEqual(json_body['conflict']['code'], 409) self.assertEqual( json_body['conflict']['message'], "ID value is already assigned to an existing template")
def test_new_endpoint_template_wrong_service_type(self): """ POST requires that the endpoint template and service have the same service types. """ self.core.add_api(self.eeapi) id_key = get_template_id(self, self.eeapi) data = { 'id': text_type(uuid.uuid4()), 'name': self.eeapi_name, 'type': 'some-type', 'region': 'some-region' } self.assertNotEqual(id_key, data['id']) (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, body=data, headers=self.headers)) self.assertEqual(response.code, 409) self.assertEqual(json_body['conflict']['code'], 409) self.assertEqual( json_body['conflict']['message'], "Endpoint already exists or service type does not match.")
def test_response_has_auth_token(self): """ The JSON response has a access.token.id key corresponding to its MimicCore session, and therefore access.token.tenant.id should match that session's tenant_id. """ core = MimicCore(Clock(), []) root = MimicRoot(core).app.resource() (response, json_body) = self.successResultOf( json_request( self, root, "POST", "/identity/v2.0/tokens", { "auth": { "passwordCredentials": { "username": "******", "password": "******" } } })) self.assertEqual(200, response.code) token = json_body['access']['token']['id'] tenant_id = json_body['access']['token']['tenant']['id'] session = core.sessions.session_for_token(token) self.assertEqual(token, session.token) self.assertEqual(tenant_id, session.tenant_id)
def test_send_yo_to_same_username_gets_same_userid(self): """ Sending a Yo to the same username twice causes the same user ID to come back in the response. """ (resp, data1) = self.successResultOf(json_request( self, self.root, b"POST", '{0}/yo/'.format(self.uri), json.dumps({'username': '******', 'api_key': 'A1234567890'}).encode("utf-8"))) self.assertEquals(resp.code, 200) (resp, data2) = self.successResultOf(json_request( self, self.root, b"POST", '{0}/yo/'.format(self.uri), json.dumps({'username': '******', 'api_key': 'A1234567890'}).encode("utf-8"))) self.assertEquals(resp.code, 200) self.assertEquals(data1['recipient']['user_id'], data2['recipient']['user_id'])
def test_response_service_catalog_has_base_uri(self): """ The JSON response's service catalog whose endpoints all begin with the same base URI as the request. """ core = MimicCore(Clock(), [ExampleAPI()]) root = MimicRoot(core).app.resource() (response, json_body) = self.successResultOf( json_request( self, root, "POST", "http://mybase/identity/v2.0/tokens", { "auth": { "passwordCredentials": { "username": "******", "password": "******" } } })) self.assertEqual(200, response.code) services = json_body['access']['serviceCatalog'] self.assertEqual(1, len(services)) urls = [endpoint['publicURL'] for endpoint in services[0]['endpoints']] self.assertEqual(1, len(urls)) self.assertTrue( urls[0].startswith('http://mybase/'), '{0} does not start with "http://mybase"'.format(urls[0]))
def test_json_body_id_value_not_matching_url(self): """ PUT requires that the endpoint template id in the URL and JSON data match, otherwise results in 409. """ self.core.add_api(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': 'some-random-key', 'name': self.eeapi_name, 'type': self.eeapi.type_key, 'region': 'some-region' } (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, body=data, headers=self.headers)) self.assertEqual(response.code, 409) self.assertEqual(json_body['conflict']['code'], 409) self.assertEqual( json_body['conflict']['message'], "Template ID in URL does not match that of the JSON body")
def test_get_token_and_catalog_for_api_credentials(self): """ The response returned should include the credentials that were supplied during authentication """ core = MimicCore(Clock(), [ExampleAPI()]) root = MimicRoot(core).app.resource() (response, json_body) = self.successResultOf( json_request( self, root, "POST", "/identity/v2.0/tokens", { "auth": { "RAX-KSKEY:apiKeyCredentials": { "username": "******", "apiKey": "jhgjhghg-nhghghgh-12222" }, "tenantName": "12345" } })) self.assertEqual(response.code, 200) tenant_id = json_body["access"]["token"]["tenant"]["id"] self.assertEqual(tenant_id, "12345") tenant_name = json_body["access"]["token"]["tenant"]["name"] self.assertEqual(tenant_name, tenant_id) user_name = json_body["access"]["user"]["name"] self.assertEqual(user_name, "demoauthor")
def test_invalid_template_id(self): """ PUT requires the endpoint template id to match an existing endpoint template, otherwise results in 404. """ self.core.add_api(self.eeapi) id_key = get_template_id(self, self.eeapi) self.eeapi.remove_template(id_key) data = { 'id': id_key, 'name': self.eeapi_name, 'type': self.eeapi.type_key, 'region': 'some-region' } self.headers[b'serviceid'] = [self.eeapi.uuid_key.encode('utf8')] (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, body=data, headers=self.headers)) self.assertEqual(response.code, 404) self.assertEqual(json_body['itemNotFound']['code'], 404) self.assertEqual( json_body['itemNotFound']['message'], "Unable to update non-existent template. Template must " "first be added before it can be updated.", )
def test_json_body_missing_required_field(self, remove_field): """ POST requires 'name' field otherwise 400 is generated. """ # normal JSON body data = {'type': 'some-type', 'name': 'some-name'} # remove a portion of the body per the DDT data del data[remove_field] # POST the resulting JSON to the REST API (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, body=data, headers=self.headers)) # API should return 400 since a required field is missing self.assertEqual(response.code, 400) self.assertEqual(json_body['badRequest']['code'], 400) self.assertEqual( json_body['badRequest']['message'], "Invalid Content. 'name' and 'type' fields are " "required.")
def test_multiple_external_apis(self): """ GET can retrieve numerous External APIs that have External API Templates. """ api_list = [ make_example_external_api( self, name=self.eeapi_name + text_type(uuid.uuid4()), service_type='service-' + text_type(uuid.uuid4())) for ignored in range(10) ] # eeapi needs to be the first in the list api_list.insert(0, self.eeapi) for api in api_list: self.core.add_api(api) self.assertEqual(len(self.core._uuid_to_api_external), len(api_list)) (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, headers=self.headers)) self.assertEqual(response.code, 200) self.assertEqual(len(json_body['OS-KSCATALOG']), len(api_list)) self.assertEqual( len(json_body['OS-KSCATALOG:endpointsTemplates_links']), 0)
def test_create_cache_settings(self): """ ``POST /service/{service_id}/version/{version_id}/cache_settings`` against Fastly mock creates a caching setting (rule) for a particular service and version and returns JSON-serialized response. """ uri = self.uri + '/service/{0}/version/{1}/cache_settings' \ '?name=testcache&stale_ttl=1000&ttl=1000&action=cache'.format( self.service_id, self.version_id) (response, json_body) = self.successResultOf(json_request( self, self.root, b"POST", uri)) url_data = [ ('name', ['testcache']), ('stale_ttl', ['1000']), ('ttl', ['1000']), ('action', ['cache']) ] cache_settings = self.fastly_response.create_cache_settings( url_data=url_data, service_id=self.service_id, service_version=self.version_id) self.assertEqual(200, response.code) self.assertEqual(sorted(json_body), sorted(cache_settings))
def test_response_has_auth_token(self): """ The JSON response has a access.token.id key corresponding to its MimicCore session, and therefore access.token.tenant.id should match that session's tenant_id. """ core = MimicCore(Clock(), []) root = MimicRoot(core).app.resource() (response, json_body) = self.successResultOf(json_request( self, root, "POST", "/identity/v2.0/tokens", { "auth": { "passwordCredentials": { "username": "******", "password": "******" } } } )) self.assertEqual(200, response.code) token = json_body['access']['token']['id'] tenant_id = json_body['access']['token']['tenant']['id'] session = core.sessions.session_for_token(token) self.assertEqual(token, session.token) self.assertEqual(tenant_id, session.tenant_id)
def test_new_endpoint_template_wrong_service_type(self): """ PUT requires that the service matches, otherwise results in 409. """ self.core.add_api(self.eeapi) data = { 'id': self.ept_template_id, 'name': self.eeapi_name, 'type': 'some-type', 'region': 'some-region' } (response, json_body) = self.successResultOf( json_request(self, self.root, self.verb, self.uri, body=data, headers=self.headers)) self.assertEqual(response.code, 409) self.assertEqual(json_body['conflict']['code'], 409) self.assertEqual( json_body['conflict']['message'], "Endpoint already exists and service id or service type does not " "match.")
def test_auth_accepts_tenant_name(self): """ If "tenantName" is passed, the tenant specified is used instead of a generated tenant ID. """ core = MimicCore(Clock(), []) root = MimicRoot(core).app.resource() (response, json_body) = self.successResultOf(json_request( self, root, "POST", "/identity/v2.0/tokens", { "auth": { "passwordCredentials": { "username": "******", "password": "******" }, "tenantName": "turtlepower" } } )) self.assertEqual(200, response.code) self.assertEqual("turtlepower", json_body['access']['token']['tenant']['id']) token = json_body['access']['token']['id'] session = core.sessions.session_for_token(token) self.assertEqual(token, session.token) self.assertEqual("turtlepower", session.tenant_id)
def register_behavior(test_case, root, uri, behavior_name, parameters, criteria): """ Register a particular behavior. :param test_case: the test case with which to make assertions :param root: A mimic root API object :param str uri: The uri fo the behavior resource to register. :param str behavior_name: The name of the behavior :param dict parameters: A dictionary of parameters to pass to the behavior :param list criteria: The criteria for which this behavior should be applied. :return: The behavior ID of the registered behavior. """ behavior_json = { "name": behavior_name, "parameters": parameters, "criteria": criteria } response, body = test_case.successResultOf( json_request(test_case, root, "POST", uri, json.dumps(behavior_json))) test_case.assertEqual(response.code, 201) behavior_id = body.get("id") test_case.assertIsInstance(behavior_id, string_types) test_case.assertEqual(UUID(behavior_id).version, 4) return behavior_id
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)
def test_tick(self): """ ``/mimic/v1.1/tick`` (handled by :func:`MimicRoot.advance_time`) advances the clock associated with the service. """ clock = Clock() def do(): do.done = True do.done = False clock.callLater(3.5, do) core = MimicCore(clock, []) root = MimicRoot(core, clock).app.resource() self.assertEqual(do.done, False) jreq = json_request( self, root, "POST", "/mimic/v1.1/tick", body={"amount": 3.6} ) [response, json_content] = self.successResultOf(jreq) self.assertEqual(response.code, 200) expected = { 'advanced': 3.6, 'now': '1970-01-01T00:00:03.600000Z', } self.assertEqual(json_content, expected) self.assertEqual(do.done, True)
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])
def test_tick(self): """ ``/mimic/v1.1/tick`` (handled by :func:`MimicRoot.advance_time`) advances the clock associated with the service. """ clock = Clock() def do(): do.done = True do.done = False clock.callLater(3.5, do) core = MimicCore(clock, []) root = MimicRoot(core, clock).app.resource() self.assertEqual(do.done, False) jreq = json_request( self, root, "POST", "/mimic/v1.1/tick", body={"amount": 3.6} ) [response, json_content] = self.successResultOf(jreq) self.assertEqual(response.code, 200) expected = { 'advanced': 3.6, 'now': '1970-01-01T00:00:03.600000Z', } self.assertEqual(json_content, expected) self.assertEqual(do.done, True)
def get_server_flavor(self, postfix): """ Get flavors, assert response code is 200 and return response body. """ (response, content) = self.successResultOf(json_request(self, self.root, "GET", self.uri + postfix)) self.assertEqual(200, response.code) return content
def get_server_image(self, postfix): """ Get images, assert response code is 200 and return response body. """ (response, content) = self.successResultOf(json_request( self, self.root, b"GET", self.uri + postfix)) self.assertEqual(200, response.code) return content
def test_check_non_existing_username_is_false(self): """ Checking a username that do not exist gives a false response. """ (resp, data) = self.successResultOf(json_request( self, self.root, b"GET", '{0}/check_username/?username=TESTUSER5'.format(self.uri))) self.assertEquals(resp.code, 200) self.assertEquals(data['exists'], False)
def test_check_username_missing_username_errors(self): """ Trying to check the username without specifying a username causes an error. """ (resp, data) = self.successResultOf(json_request( self, self.root, b"GET", '{0}/check_username/'.format(self.uri))) self.assertEquals(resp.code, 400) self.assertEquals(data['error'], 'Must supply username')