Search in sources :

Example 6 with Header

use of io.github.microcks.domain.Header in project microcks by microcks.

the class PostmanTestStepsRunner method buildHeaders.

private ArrayNode buildHeaders(Set<Header> headers) {
    ArrayNode jsonHS = mapper.createArrayNode();
    for (Header header : headers) {
        ObjectNode jsonH = mapper.createObjectNode();
        jsonH.put("key", header.getName());
        jsonH.put("value", buildValue(header.getValues()));
        jsonHS.add(jsonH);
    }
    return jsonHS;
}
Also used : Header(io.github.microcks.domain.Header) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode)

Example 7 with Header

use of io.github.microcks.domain.Header in project microcks by microcks.

the class HttpTestRunner method runTest.

@Override
public List<TestReturn> runTest(Service service, Operation operation, TestResult testResult, List<Request> requests, String endpointUrl, HttpMethod method) throws URISyntaxException, IOException {
    if (log.isDebugEnabled()) {
        log.debug("Launching test run on " + endpointUrl + " for " + requests.size() + " request(s)");
    }
    if (requests.isEmpty()) {
        return null;
    }
    // Initialize result container.
    List<TestReturn> result = new ArrayList<TestReturn>();
    for (Request request : requests) {
        // Reset status code, message and request each time.
        int code = TestReturn.SUCCESS_CODE;
        String message = null;
        String customizedEndpointUrl = endpointUrl;
        if (service.getType().equals(ServiceType.REST)) {
            String operationName = operation.getName();
            // Name may start with verb, remove it if present.
            if (operationName.indexOf(' ') > 0 && operationName.indexOf(' ') < operationName.length()) {
                operationName = operationName.split(" ")[1];
            }
            customizedEndpointUrl += URIBuilder.buildURIFromPattern(operationName, request.getQueryParameters());
            log.debug("Using customized endpoint url: " + customizedEndpointUrl);
        }
        ClientHttpRequest httpRequest = clientHttpRequestFactory.createRequest(new URI(customizedEndpointUrl), method);
        // Set headers to request if any. Start with those coming from request itself.
        // Add or override existing headers with test specific ones for operation and globals.
        Set<Header> headers = new HashSet<>();
        if (request.getHeaders() != null) {
            headers.addAll(request.getHeaders());
        }
        if (testResult.getOperationsHeaders() != null) {
            if (testResult.getOperationsHeaders().getGlobals() != null) {
                headers.addAll(testResult.getOperationsHeaders().getGlobals());
            }
            if (testResult.getOperationsHeaders().get(operation.getName()) != null) {
                headers.addAll(testResult.getOperationsHeaders().get(operation.getName()));
            }
        }
        if (headers.size() > 0) {
            for (Header header : headers) {
                log.debug("Adding header " + header.getName() + " to request");
                httpRequest.getHeaders().add(header.getName(), buildValue(header.getValues()));
            }
            // Update request headers for traceability of possibly added ones.
            request.setHeaders(headers);
        }
        // Now manage specific authorization headers if there's a secret.
        if (secret != null) {
            addAuthorizationHeadersFromSecret(httpRequest, request, secret);
        }
        // Allow extensions to realize some pre-processing of request.
        prepareRequest(request);
        // If there's input content, add it to request.
        if (request.getContent() != null) {
            // Update request content with rendered body if necessary.
            request.setContent(TestRunnerCommons.renderRequestContent(request, headers));
            log.trace("Sending following request content: " + request.getContent());
            httpRequest.getBody().write(request.getContent().getBytes());
        }
        // Actually execute request.
        long startTime = System.currentTimeMillis();
        ClientHttpResponse httpResponse = null;
        try {
            httpResponse = httpRequest.execute();
        } catch (IOException ioe) {
            log.error("IOException while executing request " + request.getName() + " on " + endpointUrl, ioe);
            code = TestReturn.FAILURE_CODE;
            message = ioe.getMessage();
        }
        long duration = System.currentTimeMillis() - startTime;
        // Extract and store response body so that stream may not be consumed more than o1 time ;-)
        String responseContent = null;
        if (httpResponse != null) {
            StringWriter writer = new StringWriter();
            IOUtils.copy(httpResponse.getBody(), writer);
            responseContent = writer.toString();
        }
        // If still in success, check if http code is out of correct ranges (20x and 30x).
        if (code == TestReturn.SUCCESS_CODE) {
            code = extractTestReturnCode(service, operation, request, httpResponse, responseContent);
            message = extractTestReturnMessage(service, operation, request, httpResponse);
        }
        // Create a Response object for returning.
        Response response = new Response();
        if (httpResponse != null) {
            response.setContent(responseContent);
            response.setStatus(String.valueOf(httpResponse.getRawStatusCode()));
            log.debug("Response Content-Type: " + httpResponse.getHeaders().getContentType());
            if (httpResponse.getHeaders().getContentType() != null) {
                response.setMediaType(httpResponse.getHeaders().getContentType().toString());
            }
            headers = buildHeaders(httpResponse);
            if (headers != null) {
                response.setHeaders(headers);
            }
            httpResponse.close();
        }
        result.add(new TestReturn(code, duration, message, request, response));
    }
    return result;
}
Also used : TestReturn(io.github.microcks.domain.TestReturn) ArrayList(java.util.ArrayList) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) Request(io.github.microcks.domain.Request) IOException(java.io.IOException) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) URI(java.net.URI) Response(io.github.microcks.domain.Response) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) Header(io.github.microcks.domain.Header) StringWriter(java.io.StringWriter) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) HashSet(java.util.HashSet)

Example 8 with Header

use of io.github.microcks.domain.Header in project microcks by microcks.

the class HttpTestRunner method buildAuthHeaderWithSecret.

/**
 * Build a Microcks header for traceability.
 */
private Header buildAuthHeaderWithSecret(String name, String type) {
    Header authHeader = new Header();
    authHeader.setName(name);
    authHeader.setValues(new TreeSet<>(Arrays.asList(type + "<value-from-secret>")));
    return authHeader;
}
Also used : Header(io.github.microcks.domain.Header)

Example 9 with Header

use of io.github.microcks.domain.Header in project microcks by microcks.

the class HttpTestRunner method buildHeaders.

/**
 * Build domain headers from ClientHttpResponse ones.
 */
private Set<Header> buildHeaders(ClientHttpResponse httpResponse) {
    if (httpResponse.getHeaders() != null && !httpResponse.getHeaders().isEmpty()) {
        Set<Header> headers = new HashSet<>();
        HttpHeaders responseHeaders = httpResponse.getHeaders();
        for (Entry<String, List<String>> responseHeader : responseHeaders.entrySet()) {
            Header header = new Header();
            header.setName(responseHeader.getKey());
            header.setValues(new HashSet<>(responseHeader.getValue()));
            headers.add(header);
        }
        return headers;
    }
    return null;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Header(io.github.microcks.domain.Header) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet)

Example 10 with Header

use of io.github.microcks.domain.Header in project microcks by microcks.

the class TestRunnerCommons method renderRequestContent.

/**
 * Render the request content using the Expression Language compatible {@code TemplateEngine} if required.
 * If rendering template fails, we just produce a log error message and stick to templatized content.
 * @param request The request that will be sent for test.
 * @param headers The set of computed headers to use for request body evaluation
 * @return The rendered response body payload.
 */
public static String renderRequestContent(Request request, Set<Header> headers) {
    if (request.getContent().contains(TemplateEngine.DEFAULT_EXPRESSION_PREFIX)) {
        log.debug("Response contains dynamic EL expression, rendering it...");
        TemplateEngine engine = TemplateEngineFactory.getTemplateEngine();
        // Create and fill an evaluable request object.
        EvaluableRequest evaluableRequest = new EvaluableRequest(request.getContent(), null);
        // Adding query parameters...
        Map<String, String> evaluableParams = new HashMap<>();
        for (Parameter parameter : request.getQueryParameters()) {
            evaluableParams.put(parameter.getName(), parameter.getValue());
        }
        evaluableRequest.setParams(evaluableParams);
        // Adding headers...
        Map<String, String> evaluableHeaders = new HashMap<>();
        for (Header header : request.getHeaders()) {
            evaluableHeaders.put(header.getName(), String.join(",", header.getValues()));
        }
        evaluableRequest.setHeaders(evaluableHeaders);
        // Register the request variable and evaluate the request body.
        engine.getContext().setVariable("request", evaluableRequest);
        try {
            return engine.getValue(request.getContent());
        } catch (Throwable t) {
            log.error("Failing at evaluating template " + request.getContent(), t);
            return request.getContent();
        }
    }
    return request.getContent();
}
Also used : TemplateEngine(io.github.microcks.util.el.TemplateEngine) Header(io.github.microcks.domain.Header) HashMap(java.util.HashMap) Parameter(io.github.microcks.domain.Parameter) EvaluableRequest(io.github.microcks.util.el.EvaluableRequest)

Aggregations

Header (io.github.microcks.domain.Header)19 JsonNode (com.fasterxml.jackson.databind.JsonNode)6 ArrayList (java.util.ArrayList)5 EventMessage (io.github.microcks.domain.EventMessage)4 Response (io.github.microcks.domain.Response)4 IOException (java.io.IOException)4 HashMap (java.util.HashMap)4 HashSet (java.util.HashSet)4 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)3 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)3 Operation (io.github.microcks.domain.Operation)3 Service (io.github.microcks.domain.Service)3 HttpHeaders (org.springframework.http.HttpHeaders)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 Request (io.github.microcks.domain.Request)2 Resource (io.github.microcks.domain.Resource)2 FallbackSpecification (io.github.microcks.util.dispatcher.FallbackSpecification)2 URI (java.net.URI)2 ResponseEntity (org.springframework.http.ResponseEntity)2 ClientHttpRequest (org.springframework.http.client.ClientHttpRequest)2