Exemplo n.º 1
0
    def test_route_through_edge(self):
        cluster_id = f"domain-{short_uid()}"
        cluster_url = f"http://localhost:{config.EDGE_PORT}/{cluster_id}"
        cluster = EdgeProxiedOpensearchCluster(cluster_url)

        try:
            cluster.start()
            assert cluster.wait_is_up(240), "gave up waiting for server"

            response = requests.get(cluster_url)
            assert response.ok, f"cluster endpoint returned an error: {response.text}"
            assert response.json()["version"]["number"] == "1.1.0"

            response = requests.get(f"{cluster_url}/_cluster/health")
            assert response.ok, f"cluster health endpoint returned an error: {response.text}"
            assert response.json()["status"] in [
                "red",
                "orange",
                "yellow",
                "green",
            ], "expected cluster state to be in a valid state"

        finally:
            cluster.shutdown()

        assert poll_condition(
            lambda: not cluster.is_up(), timeout=240
        ), "gave up waiting for cluster to shut down"
Exemplo n.º 2
0
def try_cluster_health(cluster_url: str):
    response = requests.get(cluster_url)
    assert response.ok, f"cluster endpoint returned an error: {response.text}"

    response = requests.get(f"{cluster_url}/_cluster/health")
    assert response.ok, f"cluster health endpoint returned an error: {response.text}"
    assert response.json()["status"] in [
        "orange",
        "yellow",
        "green",
    ], "expected cluster state to be in a valid state"
Exemplo n.º 3
0
 def test_set_external_hostname(self):
     bucket_name = 'test-bucket-%s' % short_uid()
     key = 'test.file'
     hostname_before = config.HOSTNAME_EXTERNAL
     config.HOSTNAME_EXTERNAL = 'foobar'
     try:
         content = 'test content 123'
         acl = 'public-read'
         self.s3_client.create_bucket(Bucket=bucket_name)
         # upload file
         response = self._perform_multipart_upload(bucket=bucket_name, key=key, data=content, acl=acl)
         expected_url = '%s://%s:%s/%s/%s' % (get_service_protocol(), config.HOSTNAME_EXTERNAL,
             config.PORT_S3, bucket_name, key)
         self.assertEqual(expected_url, response['Location'])
         # fix object ACL - currently not directly support for multipart uploads
         self.s3_client.put_object_acl(Bucket=bucket_name, Key=key, ACL=acl)
         # download object via API
         downloaded_object = self.s3_client.get_object(Bucket=bucket_name, Key=key)
         self.assertEqual(to_str(downloaded_object['Body'].read()), content)
         # download object directly from download link
         download_url = response['Location'].replace('%s:' % config.HOSTNAME_EXTERNAL, 'localhost:')
         response = safe_requests.get(download_url)
         self.assertEqual(response.status_code, 200)
         self.assertEqual(to_str(response.content), content)
     finally:
         config.HOSTNAME_EXTERNAL = hostname_before
Exemplo n.º 4
0
    def test_api_gateway_s3_get_integration(self):
        apigw_client = aws_stack.connect_to_service('apigateway')
        s3_client = aws_stack.connect_to_service('s3')

        bucket_name = 'test-bucket'
        object_name = 'test.json'
        object_content = '{ "success": "true" }'
        object_content_type = 'application/json'

        api = apigw_client.create_rest_api(name='test')
        api_id = api['id']

        s3_client.create_bucket(Bucket=bucket_name)
        s3_client.put_object(Bucket=bucket_name, Key=object_name, Body=object_content, ContentType=object_content_type)

        self.connect_api_gateway_to_s3(bucket_name, object_name, api_id, 'GET')

        apigw_client.create_deployment(restApiId=api_id, stageName='test')
        url = gateway_request_url(api_id, 'test', '/')
        result = requests.get(url)
        self.assertEqual(result.status_code, 200)
        self.assertEqual(result.text, object_content)
        self.assertEqual(result.headers['content-type'], object_content_type)
        # clean up
        apigw_client.delete_rest_api(restApiId=api_id)
        s3_client.delete_object(Bucket=bucket_name, Key=object_name)
        s3_client.delete_bucket(Bucket=bucket_name)
Exemplo n.º 5
0
    def test_api_gateway_kinesis_integration(self):
        # create target Kinesis stream
        aws_stack.create_kinesis_stream(self.TEST_STREAM_KINESIS_API_GW)

        # create API Gateway and connect it to the target stream
        result = self.connect_api_gateway_to_kinesis('test_gateway1', self.TEST_STREAM_KINESIS_API_GW)

        # generate test data
        test_data = {'records': [
            {'data': '{"foo": "bar1"}'},
            {'data': '{"foo": "bar2"}'},
            {'data': '{"foo": "bar3"}'}
        ]}

        url = self.gateway_request_url(
            api_id=result['id'],
            stage_name=self.TEST_STAGE_NAME,
            path=self.API_PATH_DATA_INBOUND
        )

        # list Kinesis streams via API Gateway
        result = requests.get(url)
        result = json.loads(to_str(result.content))
        self.assertIn('StreamNames', result)

        # post test data to Kinesis via API Gateway
        result = requests.post(url, data=json.dumps(test_data))
        result = json.loads(to_str(result.content))
        self.assertEqual(result['FailedRecordCount'], 0)
        self.assertEqual(len(result['Records']), len(test_data['records']))

        # clean up
        kinesis = aws_stack.connect_to_service('kinesis')
        kinesis.delete_stream(StreamName=self.TEST_STREAM_KINESIS_API_GW)
Exemplo n.º 6
0
def get_template_body(req_data):
    body = req_data.get("TemplateBody")
    if body:
        return body
    url = req_data.get("TemplateURL")
    if url:
        response = run_safe(lambda: safe_requests.get(url, verify=False))
        # check error codes, and code 301 - fixes https://github.com/localstack/localstack/issues/1884
        status_code = 0 if response is None else response.status_code
        if response is None or status_code == 301 or status_code >= 400:
            # check if this is an S3 URL, then get the file directly from there
            url = convert_s3_to_local_url(url)
            if is_local_service_url(url):
                parsed_path = urlparse.urlparse(url).path.lstrip("/")
                parts = parsed_path.partition("/")
                client = aws_stack.connect_to_service("s3")
                LOG.debug(
                    "Download CloudFormation template content from local S3: %s - %s"
                    % (parts[0], parts[2]))
                result = client.get_object(Bucket=parts[0], Key=parts[2])
                body = to_str(result["Body"].read())
                return body
            raise Exception(
                "Unable to fetch template body (code %s) from URL %s" %
                (status_code, url))
        return response.content
    raise Exception("Unable to get template body from input: %s" % req_data)
def test_api_gateway_http_integration():
    test_port = 12123
    backend_url = 'http://localhost:%s%s' % (test_port, API_PATH_HTTP_BACKEND)

    # create target HTTP backend
    def listener(**kwargs):
        response = Response()
        response.status_code = 200
        response._content = json.dumps(
            kwargs['data']) if kwargs['data'] else '{}'
        return response

    proxy = GenericProxy(test_port, update_listener=listener)
    proxy.start()

    # create API Gateway and connect it to the HTTP backend
    result = connect_api_gateway_to_http('test_gateway2',
                                         backend_url,
                                         path=API_PATH_HTTP_BACKEND)

    # make test request to gateway
    url = INBOUND_GATEWAY_URL_PATTERN.format(api_id=result['id'],
                                             stage_name=TEST_STAGE_NAME,
                                             path=API_PATH_HTTP_BACKEND)
    result = requests.get(url)
    assert result.status_code == 200
    assert to_str(result.content) == '{}'
    data = {"data": 123}
    result = requests.post(url, data=json.dumps(data))
    assert result.status_code == 200
    assert json.loads(to_str(result.content)) == data

    # clean up
    proxy.stop()
Exemplo n.º 8
0
    def test_elasticsearch_get_document(self):
        article_path = '{}/{}/employee/{}?pretty'.format(
            self.es_url, TEST_INDEX, TEST_DOC_ID)
        resp = requests.get(article_path, headers=COMMON_HEADERS)

        self.assertIn('I like to collect rock albums', resp.text,
            msg='Document not found({}): {}'.format(resp.status_code, resp.text))
Exemplo n.º 9
0
    def test_create_indexes_and_domains(self):
        indexes = ["index1", "index2"]
        for index_name in indexes:
            index_path = "{}/{}".format(self.es_url, index_name)
            requests.put(index_path, headers=COMMON_HEADERS)
            endpoint = "{}/_cat/indices/{}?format=json&pretty".format(
                self.es_url, index_name)
            req = requests.get(endpoint)
            self.assertEqual(200, req.status_code)
            req_result = json.loads(req.text)
            self.assertIn(req_result[0]["health"], ["green", "yellow"])
            self.assertIn(req_result[0]["index"], indexes)

        es_client = aws_stack.connect_to_service("es")
        test_domain_name_1 = "test1-%s" % short_uid()
        test_domain_name_2 = "test2-%s" % short_uid()
        self._create_domain(name=test_domain_name_1, version="6.8")
        self._create_domain(name=test_domain_name_2, version="6.8")
        status_test_domain_name_1 = es_client.describe_elasticsearch_domain(
            DomainName=test_domain_name_1)
        status_test_domain_name_2 = es_client.describe_elasticsearch_domain(
            DomainName=test_domain_name_2)
        self.assertFalse(
            status_test_domain_name_1["DomainStatus"]["Processing"])
        self.assertFalse(
            status_test_domain_name_2["DomainStatus"]["Processing"])
Exemplo n.º 10
0
def test_elasticsearch_get_document():
    article_path = '{}/{}/employee/{}?pretty'.format(
        ES_URL, TEST_INDEX, TEST_DOC_ID)
    resp = requests.get(article_path, headers=COMMON_HEADERS)

    assert_true('I like to collect rock albums' in resp.text,
        msg='Document not found({}): {}'.format(resp.status_code, resp.text))
Exemplo n.º 11
0
def test_elasticsearch_get_document():
    article_path = '{}/{}/employee/{}?pretty'.format(es_url, test_index,
                                                     test_doc_id)
    resp = requests.get(article_path, headers=common_headers)

    assert_true('I like to collect rock albums' in resp.text,
                msg='Document not found({}): {}'.format(
                    resp.status_code, resp.text))
Exemplo n.º 12
0
    def run_api_gateway_http_integration(self, int_type):
        test_port = get_free_tcp_port()
        backend_url = 'http://localhost:%s%s' % (test_port,
                                                 self.API_PATH_HTTP_BACKEND)

        # start test HTTP backend
        proxy = self.start_http_backend(test_port)

        # create API Gateway and connect it to the HTTP_PROXY/HTTP backend
        result = self.connect_api_gateway_to_http(
            int_type,
            'test_gateway2',
            backend_url,
            path=self.API_PATH_HTTP_BACKEND)

        url = self.gateway_request_url(api_id=result['id'],
                                       stage_name=self.TEST_STAGE_NAME,
                                       path=self.API_PATH_HTTP_BACKEND)

        # make sure CORS headers are present
        origin = 'localhost'
        result = requests.options(url, headers={'origin': origin})
        self.assertEqual(result.status_code, 200)
        self.assertTrue(
            re.match(
                result.headers['Access-Control-Allow-Origin'].replace(
                    '*', '.*'), origin))
        self.assertIn('POST', result.headers['Access-Control-Allow-Methods'])

        custom_result = json.dumps({'foo': 'bar'})

        # make test GET request to gateway
        result = requests.get(url)
        self.assertEqual(result.status_code, 200)
        expected = custom_result if int_type == 'custom' else '{}'
        self.assertEqual(json.loads(to_str(result.content))['data'], expected)

        # make test POST request to gateway
        data = json.dumps({'data': 123})
        result = requests.post(url, data=data)
        self.assertEqual(result.status_code, 200)
        expected = custom_result if int_type == 'custom' else data
        self.assertEqual(json.loads(to_str(result.content))['data'], expected)

        # make test POST request with non-JSON content type
        data = 'test=123'
        ctype = 'application/x-www-form-urlencoded'
        result = requests.post(url, data=data, headers={'content-type': ctype})
        self.assertEqual(result.status_code, 200)
        content = json.loads(to_str(result.content))
        headers = CaseInsensitiveDict(content['headers'])
        expected = custom_result if int_type == 'custom' else data
        self.assertEqual(content['data'], expected)
        self.assertEqual(headers['content-type'], ctype)

        # clean up
        proxy.stop()
Exemplo n.º 13
0
 def test_create_indices(self, opensearch_endpoint):
     indices = ["index1", "index2"]
     for index_name in indices:
         index_path = f"{opensearch_endpoint}/{index_name}"
         requests.put(index_path, headers=COMMON_HEADERS)
         endpoint = f"{opensearch_endpoint}/_cat/indices/{index_name}?format=json&pretty"
         req = requests.get(endpoint)
         assert req.status_code == 200
         req_result = json.loads(req.text)
         assert req_result[0]["health"] in ["green", "yellow"]
         assert req_result[0]["index"] in indices
Exemplo n.º 14
0
    def test_search(self, opensearch_endpoint, opensearch_document_path):
        index = "/".join(opensearch_document_path.split("/")[:-2])
        # force the refresh of the index after the document was added, so it can appear in search
        response = requests.post(f"{opensearch_endpoint}/_refresh", headers=COMMON_HEADERS)
        assert response.ok

        search = {"query": {"match": {"last_name": "Fett"}}}
        response = requests.get(f"{index}/_search", data=json.dumps(search), headers=COMMON_HEADERS)

        assert (
            "I'm just a simple man" in response.text
        ), f"search unsuccessful({response.status_code}): {response.text}"
Exemplo n.º 15
0
def test_elasticsearch_search():
    search_path = '{}/{}/employee/_search?pretty'.format(es_url, test_index)

    search = {'query': {'match': {'last_name': 'Smith'}}}

    resp = requests.get(search_path,
                        data=json.dumps(search),
                        headers=common_headers)

    assert_true('I like to collect rock albums' in resp.text,
                msg='Search failed({}): {}'.format(resp.status_code,
                                                   resp.text))
Exemplo n.º 16
0
def test_elasticsearch_search():
    search_path = '{}/{}/employee/_search?pretty'.format(ES_URL, TEST_INDEX)

    search = {'query': {'match': {'last_name': 'Smith'}}}

    resp = requests.get(search_path,
                        data=json.dumps(search),
                        headers=COMMON_HEADERS)

    assert_true('I like to collect rock albums' in resp.text,
                msg='Search failed({}): {}'.format(resp.status_code,
                                                   resp.text))
Exemplo n.º 17
0
def get_template_body(req_data):
    body = req_data.get('TemplateBody')
    if body:
        return body[0]
    url = req_data.get('TemplateURL')
    if url:
        response = safe_requests.get(url[0])
        if response.status_code >= 400:
            raise Exception(
                'Unable to fetch template body (code %s) from URL %s' %
                (response.status_code, url[0]))
        return response.content
    raise Exception('Unable to get template body from input: %s' % req_data)
Exemplo n.º 18
0
    def test_elasticsearch_search(self):
        search_path = "{}/{}/employee/_search?pretty".format(
            self.es_url, TEST_INDEX)

        search = {"query": {"match": {"last_name": "Smith"}}}

        resp = requests.get(search_path,
                            data=json.dumps(search),
                            headers=COMMON_HEADERS)

        self.assertIn(
            "I like to collect rock albums",
            resp.text,
            msg="Search failed({}): {}".format(resp.status_code, resp.text),
        )
Exemplo n.º 19
0
    def test_api_gateway_http_integration(self):
        test_port = 12123
        backend_url = 'http://localhost:%s%s' % (test_port, self.API_PATH_HTTP_BACKEND)

        # create target HTTP backend
        class TestListener(ProxyListener):

            def forward_request(self, **kwargs):
                response = Response()
                response.status_code = 200
                response._content = kwargs.get('data') or '{}'
                return response

        proxy = GenericProxy(test_port, update_listener=TestListener())
        proxy.start()

        # create API Gateway and connect it to the HTTP backend
        result = self.connect_api_gateway_to_http(
            'test_gateway2',
            backend_url,
            path=self.API_PATH_HTTP_BACKEND
        )

        url = INBOUND_GATEWAY_URL_PATTERN.format(
            api_id=result['id'],
            stage_name=self.TEST_STAGE_NAME,
            path=self.API_PATH_HTTP_BACKEND
        )

        # make sure CORS headers are present
        origin = 'localhost'
        result = requests.options(url, headers={'origin': origin})
        self.assertEqual(result.status_code, 200)
        self.assertTrue(re.match(result.headers['Access-Control-Allow-Origin'].replace('*', '.*'), origin))
        self.assertIn('POST', result.headers['Access-Control-Allow-Methods'])

        # make test request to gateway
        result = requests.get(url)
        self.assertEqual(result.status_code, 200)
        self.assertEqual(to_str(result.content), '{}')

        data = {'data': 123}
        result = requests.post(url, data=json.dumps(data))
        self.assertEqual(result.status_code, 200)
        self.assertEqual(json.loads(to_str(result.content)), data)

        # clean up
        proxy.stop()
Exemplo n.º 20
0
def test_elasticsearch_search():
    search_path = '{}/{}/employee/_search?pretty'.format(ES_URL, TEST_INDEX)

    search = {
        'query': {
            'match': {
                'last_name': 'Smith'
            }
        }
    }

    resp = requests.get(
        search_path,
        data=json.dumps(search),
        headers=COMMON_HEADERS)

    assert_true('I like to collect rock albums' in resp.text,
        msg='Search failed({}): {}'.format(resp.status_code, resp.text))
Exemplo n.º 21
0
def get_template_body(req_data):
    body = req_data.get('TemplateBody')
    if body:
        return body
    url = req_data.get('TemplateURL')
    if url:
        response = safe_requests.get(url)
        if response.status_code >= 400:
            # check if this is an S3 URL, then get the file directly from there
            if '://localhost' in url or re.match(r'.*s3(\-website)?\.([^\.]+\.)?amazonaws.com.*', url):
                parsed_path = urlparse.urlparse(url).path.lstrip('/')
                parts = parsed_path.partition('/')
                client = aws_stack.connect_to_service('s3')
                result = client.get_object(Bucket=parts[0], Key=parts[2])
                body = to_str(result['Body'].read())
                return body
            raise Exception('Unable to fetch template body (code %s) from URL %s' % (response.status_code, url))
        return response.content
    raise Exception('Unable to get template body from input: %s' % req_data)
Exemplo n.º 22
0
def test_api_gateway_http_integration():
    test_port = 12123
    backend_url = 'http://localhost:%s%s' % (test_port, API_PATH_HTTP_BACKEND)

    # create target HTTP backend
    class TestListener(ProxyListener):

        def forward_request(self, **kwargs):
            response = Response()
            response.status_code = 200
            response._content = kwargs.get('data') or '{}'
            return response

    proxy = GenericProxy(test_port, update_listener=TestListener())
    proxy.start()

    # create API Gateway and connect it to the HTTP backend
    result = connect_api_gateway_to_http('test_gateway2', backend_url, path=API_PATH_HTTP_BACKEND)

    url = INBOUND_GATEWAY_URL_PATTERN.format(api_id=result['id'],
        stage_name=TEST_STAGE_NAME, path=API_PATH_HTTP_BACKEND)

    # make sure CORS headers are present
    origin = 'localhost'
    result = requests.options(url, headers={'origin': origin})
    assert result.status_code == 200
    assert re.match(result.headers['Access-Control-Allow-Origin'].replace('*', '.*'), origin)
    assert 'POST' in result.headers['Access-Control-Allow-Methods']

    # make test request to gateway
    result = requests.get(url)
    assert result.status_code == 200
    assert to_str(result.content) == '{}'
    data = {'data': 123}
    result = requests.post(url, data=json.dumps(data))
    assert result.status_code == 200
    assert json.loads(to_str(result.content)) == data

    # clean up
    proxy.stop()
Exemplo n.º 23
0
    def test_api_gateway_http_integration_with_path_request_parmeter(self):
        client = aws_stack.connect_to_service('apigateway')
        test_port = get_free_tcp_port()
        backend_url = 'http://localhost:%s/person/{id}' % (test_port)

        # start test HTTP backend
        proxy = self.start_http_backend(test_port)

        # create rest api
        api_rest = client.create_rest_api(name='test')
        api_id = api_rest['id']
        parent_response = client.get_resources(restApiId=api_id)
        parent_id = parent_response['items'][0]['id']
        resource_1 = client.create_resource(restApiId=api_id, parentId=parent_id, pathPart='person')
        resource_1_id = resource_1['id']
        resource_2 = client.create_resource(restApiId=api_id, parentId=resource_1_id, pathPart='{id}')
        resource_2_id = resource_2['id']
        client.put_method(
            restApiId=api_id, resourceId=resource_2_id, httpMethod='GET', authorizationType='NONE',
            apiKeyRequired=False, requestParameters={'method.request.path.id': True})
        client.put_integration(
            restApiId=api_id,
            resourceId=resource_2_id,
            httpMethod='GET',
            integrationHttpMethod='GET',
            type='HTTP',
            uri=backend_url,
            timeoutInMillis=3000,
            contentHandling='CONVERT_TO_BINARY',
            requestParameters={'integration.request.path.id': 'method.request.path.id'})
        client.create_deployment(restApiId=api_id, stageName='test')
        url = f'http://localhost:{config.EDGE_PORT}/restapis/{api_id}/test/_user_request_/person/123'
        result = requests.get(url)
        content = json.loads(result._content)
        self.assertEqual(result.status_code, 200)
        self.assertEqual(content['headers'].get(HEADER_LOCALSTACK_REQUEST_URL),
            f'http://localhost:{config.EDGE_PORT}/person/123')
        # clean up
        client.delete_rest_api(restApiId=api_id)
        proxy.stop()
Exemplo n.º 24
0
    def test_create_indexes_and_domains(self):
        indexes = ['index1', 'index2']
        for index_name in indexes:
            index_path = '{}/{}'.format(self.es_url, index_name)
            requests.put(index_path, headers=COMMON_HEADERS)
            endpoint = 'http://localhost:{}/_cat/indices/{}?format=json&pretty'.format(
                config.PORT_ELASTICSEARCH, index_name)
            req = requests.get(endpoint)
            self.assertEqual(req.status_code, 200)
            req_result = json.loads(req.text)
            self.assertTrue(req_result[0]['health'] in ['green', 'yellow'])
            self.assertTrue(req_result[0]['index'] in indexes)

        es_client = aws_stack.connect_to_service('es')
        test_domain_name_1 = 'test1-%s' % short_uid()
        test_domain_name_2 = 'test2-%s' % short_uid()
        self._create_domain(name=test_domain_name_1, version='6.8')
        self._create_domain(name=test_domain_name_2, version='6.8')
        status_test_domain_name_1 = es_client.describe_elasticsearch_domain(DomainName=test_domain_name_1)
        status_test_domain_name_2 = es_client.describe_elasticsearch_domain(DomainName=test_domain_name_2)
        self.assertTrue(status_test_domain_name_1['DomainStatus']['Created'])
        self.assertTrue(status_test_domain_name_2['DomainStatus']['Created'])
Exemplo n.º 25
0
def get_template_body(req_data):
    body = req_data.get('TemplateBody')
    if body:
        return body
    url = req_data.get('TemplateURL')
    if url:
        response = run_safe(lambda: safe_requests.get(url, verify=False))
        # check error codes, and code 301 - fixes https://github.com/localstack/localstack/issues/1884
        status_code = 0 if response is None else response.status_code
        if not response or status_code == 301 or status_code >= 400:
            # check if this is an S3 URL, then get the file directly from there
            if '://localhost' in url or re.match(
                    r'.*s3(\-website)?\.([^\.]+\.)?amazonaws.com.*', url):
                parsed_path = urlparse.urlparse(url).path.lstrip('/')
                parts = parsed_path.partition('/')
                client = aws_stack.connect_to_service('s3')
                result = client.get_object(Bucket=parts[0], Key=parts[2])
                body = to_str(result['Body'].read())
                return body
            raise Exception(
                'Unable to fetch template body (code %s) from URL %s' %
                (status_code, url))
        return response.content
    raise Exception('Unable to get template body from input: %s' % req_data)
Exemplo n.º 26
0
    def test_api_gateway_http_integration(self):
        test_port = 12123
        backend_url = 'http://localhost:%s%s' % (test_port,
                                                 self.API_PATH_HTTP_BACKEND)

        # create target HTTP backend
        class TestListener(ProxyListener):
            def forward_request(self, **kwargs):
                response = Response()
                response.status_code = 200
                result = {
                    'data': kwargs.get('data') or '{}',
                    'headers': dict(kwargs.get('headers'))
                }
                response._content = json.dumps(json_safe(result))
                return response

        proxy = GenericProxy(test_port, update_listener=TestListener())
        proxy.start()

        # create API Gateway and connect it to the HTTP backend
        result = self.connect_api_gateway_to_http(
            'test_gateway2', backend_url, path=self.API_PATH_HTTP_BACKEND)

        url = self.gateway_request_url(api_id=result['id'],
                                       stage_name=self.TEST_STAGE_NAME,
                                       path=self.API_PATH_HTTP_BACKEND)

        # make sure CORS headers are present
        origin = 'localhost'
        result = requests.options(url, headers={'origin': origin})
        self.assertEqual(result.status_code, 200)
        self.assertTrue(
            re.match(
                result.headers['Access-Control-Allow-Origin'].replace(
                    '*', '.*'), origin))
        self.assertIn('POST', result.headers['Access-Control-Allow-Methods'])

        # make test GET request to gateway
        result = requests.get(url)
        self.assertEqual(result.status_code, 200)
        self.assertEqual(json.loads(to_str(result.content))['data'], '{}')

        # make test POST request to gateway
        data = json.dumps({'data': 123})
        result = requests.post(url, data=data)
        self.assertEqual(result.status_code, 200)
        self.assertEqual(json.loads(to_str(result.content))['data'], data)

        # make test POST request with non-JSON content type
        data = 'test=123'
        ctype = 'application/x-www-form-urlencoded'
        result = requests.post(url, data=data, headers={'content-type': ctype})
        self.assertEqual(result.status_code, 200)
        content = json.loads(to_str(result.content))
        headers = CaseInsensitiveDict(content['headers'])
        self.assertEqual(content['data'], data)
        self.assertEqual(headers['content-type'], ctype)

        # clean up
        proxy.stop()
Exemplo n.º 27
0
    def test_apigateway_with_lambda_integration(self):
        apigw_client = aws_stack.connect_to_service('apigateway')

        # create Lambda function
        lambda_name = 'apigw-lambda-%s' % short_uid()
        self.create_lambda_function(lambda_name)
        lambda_uri = aws_stack.lambda_function_arn(lambda_name)
        target_uri = aws_stack.apigateway_invocations_arn(lambda_uri)

        # create REST API
        api = apigw_client.create_rest_api(name='test-api', description='')
        api_id = api['id']
        root_res_id = apigw_client.get_resources(
            restApiId=api_id)['items'][0]['id']
        api_resource = apigw_client.create_resource(restApiId=api_id,
                                                    parentId=root_res_id,
                                                    pathPart='test')

        apigw_client.put_method(restApiId=api_id,
                                resourceId=api_resource['id'],
                                httpMethod='GET',
                                authorizationType='NONE')

        rs = apigw_client.put_integration(
            restApiId=api_id,
            resourceId=api_resource['id'],
            httpMethod='GET',
            integrationHttpMethod='POST',
            type='AWS',
            uri=target_uri,
            requestTemplates={
                'application/json': '{"param1": "$input.params(\'param1\')"}'
            })
        self.assertEqual(rs['ResponseMetadata']['HTTPStatusCode'], 200)
        for key in [
                'httpMethod', 'type', 'passthroughBehavior',
                'cacheKeyParameters', 'uri', 'cacheNamespace'
        ]:
            self.assertIn(key, rs)
        self.assertNotIn('responseTemplates', rs)

        apigw_client.create_deployment(restApiId=api_id,
                                       stageName=self.TEST_STAGE_NAME)

        rs = apigw_client.get_integration(restApiId=api_id,
                                          resourceId=api_resource['id'],
                                          httpMethod='GET')
        self.assertEqual(rs['ResponseMetadata']['HTTPStatusCode'], 200)
        self.assertEqual(rs['type'], 'AWS')
        self.assertEqual(rs['httpMethod'], 'POST')
        self.assertEqual(rs['uri'], target_uri)

        # invoke the gateway endpoint
        url = self.gateway_request_url(api_id=api_id,
                                       stage_name=self.TEST_STAGE_NAME,
                                       path='/test')
        response = requests.get('%s?param1=foobar' % url)
        self.assertLess(response.status_code, 400)
        content = json.loads(to_str(response.content))
        self.assertEqual(content.get('httpMethod'), 'POST')
        self.assertEqual(
            content.get('requestContext', {}).get('resourceId'),
            api_resource['id'])
        self.assertEqual(
            content.get('requestContext', {}).get('stage'),
            self.TEST_STAGE_NAME)
        self.assertEqual(content.get('body'), '{"param1": "foobar"}')

        # delete integration
        rs = apigw_client.delete_integration(
            restApiId=api_id,
            resourceId=api_resource['id'],
            httpMethod='GET',
        )
        self.assertEqual(rs['ResponseMetadata']['HTTPStatusCode'], 200)

        with self.assertRaises(ClientError) as ctx:
            # This call should not be successful as the integration is deleted
            apigw_client.get_integration(restApiId=api_id,
                                         resourceId=api_resource['id'],
                                         httpMethod='GET')
        self.assertEqual(ctx.exception.response['Error']['Code'],
                         'BadRequestException')

        # clean up
        lambda_client = aws_stack.connect_to_service('lambda')
        lambda_client.delete_function(FunctionName=lambda_name)
        apigw_client.delete_rest_api(restApiId=api_id)
Exemplo n.º 28
0
 def test_get_document(self, opensearch_document_path):
     response = requests.get(opensearch_document_path)
     assert (
         "I'm just a simple man" in response.text
     ), f"document not found({response.status_code}): {response.text}"