Search in sources :

Example 1 with ClientYamlSuiteRestApi

use of org.elasticsearch.test.rest.yaml.restspec.ClientYamlSuiteRestApi in project elasticsearch by elastic.

the class ClientYamlTestClient method callApi.

/**
     * Calls an api with the provided parameters and body
     */
public ClientYamlTestResponse callApi(String apiName, Map<String, String> params, HttpEntity entity, Map<String, String> headers) throws IOException {
    if ("raw".equals(apiName)) {
        // Raw requests are bit simpler....
        Map<String, String> queryStringParams = new HashMap<>(params);
        String method = Objects.requireNonNull(queryStringParams.remove("method"), "Method must be set to use raw request");
        String path = "/" + Objects.requireNonNull(queryStringParams.remove("path"), "Path must be set to use raw request");
        // And everything else is a url parameter!
        try {
            Response response = restClient.performRequest(method, path, queryStringParams, entity);
            return new ClientYamlTestResponse(response);
        } catch (ResponseException e) {
            throw new ClientYamlTestResponseException(e);
        }
    }
    ClientYamlSuiteRestApi restApi = restApi(apiName);
    //divide params between ones that go within query string and ones that go within path
    Map<String, String> pathParts = new HashMap<>();
    Map<String, String> queryStringParams = new HashMap<>();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        if (restApi.getPathParts().contains(entry.getKey())) {
            pathParts.put(entry.getKey(), entry.getValue());
        } else {
            if (restApi.getParams().contains(entry.getKey()) || restSpec.isGlobalParameter(entry.getKey()) || restSpec.isClientParameter(entry.getKey())) {
                queryStringParams.put(entry.getKey(), entry.getValue());
            } else {
                throw new IllegalArgumentException("param [" + entry.getKey() + "] not supported in [" + restApi.getName() + "] " + "api");
            }
        }
    }
    List<String> supportedMethods = restApi.getSupportedMethods(pathParts.keySet());
    String requestMethod;
    if (entity != null) {
        if (!restApi.isBodySupported()) {
            throw new IllegalArgumentException("body is not supported by [" + restApi.getName() + "] api");
        }
        String contentType = entity.getContentType().getValue();
        //randomly test the GET with source param instead of GET/POST with body
        if (sendBodyAsSourceParam(supportedMethods, contentType)) {
            logger.debug("sending the request body as source param with GET method");
            queryStringParams.put("source", EntityUtils.toString(entity));
            queryStringParams.put("source_content_type", contentType);
            requestMethod = HttpGet.METHOD_NAME;
            entity = null;
        } else {
            requestMethod = RandomizedTest.randomFrom(supportedMethods);
        }
    } else {
        if (restApi.isBodyRequired()) {
            throw new IllegalArgumentException("body is required by [" + restApi.getName() + "] api");
        }
        requestMethod = RandomizedTest.randomFrom(supportedMethods);
    }
    //the rest path to use is randomized out of the matching ones (if more than one)
    ClientYamlSuiteRestPath restPath = RandomizedTest.randomFrom(restApi.getFinalPaths(pathParts));
    //Encode rules for path and query string parameters are different. We use URI to encode the path.
    //We need to encode each path part separately, as each one might contain slashes that need to be escaped, which needs to
    //be done manually.
    String requestPath;
    if (restPath.getPathParts().length == 0) {
        requestPath = "/";
    } else {
        StringBuilder finalPath = new StringBuilder();
        for (String pathPart : restPath.getPathParts()) {
            try {
                finalPath.append('/');
                // We append "/" to the path part to handle parts that start with - or other invalid characters
                URI uri = new URI(null, null, null, -1, "/" + pathPart, null, null);
                //manually escape any slash that each part may contain
                finalPath.append(uri.getRawPath().substring(1).replaceAll("/", "%2F"));
            } catch (URISyntaxException e) {
                throw new RuntimeException("unable to build uri", e);
            }
        }
        requestPath = finalPath.toString();
    }
    Header[] requestHeaders = new Header[headers.size()];
    int index = 0;
    for (Map.Entry<String, String> header : headers.entrySet()) {
        logger.info("Adding header {}\n with value {}", header.getKey(), header.getValue());
        requestHeaders[index++] = new BasicHeader(header.getKey(), header.getValue());
    }
    logger.debug("calling api [{}]", apiName);
    try {
        Response response = restClient.performRequest(requestMethod, requestPath, queryStringParams, entity, requestHeaders);
        return new ClientYamlTestResponse(response);
    } catch (ResponseException e) {
        throw new ClientYamlTestResponseException(e);
    }
}
Also used : HashMap(java.util.HashMap) ResponseException(org.elasticsearch.client.ResponseException) ClientYamlSuiteRestPath(org.elasticsearch.test.rest.yaml.restspec.ClientYamlSuiteRestPath) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) Response(org.elasticsearch.client.Response) ClientYamlSuiteRestApi(org.elasticsearch.test.rest.yaml.restspec.ClientYamlSuiteRestApi) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) HashMap(java.util.HashMap) Map(java.util.Map) BasicHeader(org.apache.http.message.BasicHeader)

Aggregations

URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Header (org.apache.http.Header)1 BasicHeader (org.apache.http.message.BasicHeader)1 Response (org.elasticsearch.client.Response)1 ResponseException (org.elasticsearch.client.ResponseException)1 ClientYamlSuiteRestApi (org.elasticsearch.test.rest.yaml.restspec.ClientYamlSuiteRestApi)1 ClientYamlSuiteRestPath (org.elasticsearch.test.rest.yaml.restspec.ClientYamlSuiteRestPath)1