Search in sources :

Example 11 with Response

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

the class ServiceServiceTest method testImportServiceDefinitionMainAndSecondary.

@Test
public void testImportServiceDefinitionMainAndSecondary() {
    List<Service> services = null;
    try {
        File artifactFile = new File("target/test-classes/io/github/microcks/service/weather-forecast-raw-openapi.yaml");
        services = service.importServiceDefinition(artifactFile, null, new ArtifactInfo("weather-forecast-raw-openapi.yaml", true));
    } catch (MockRepositoryImportException mrie) {
        mrie.printStackTrace();
        fail("No MockRepositoryImportException should have be thrown");
    }
    assertNotNull(services);
    assertEquals(1, services.size());
    // Inspect Service own attributes.
    Service importedSvc = services.get(0);
    assertEquals("WeatherForecast API", importedSvc.getName());
    assertEquals("1.1.0", importedSvc.getVersion());
    assertEquals("weather-forecast-raw-openapi.yaml", importedSvc.getSourceArtifact());
    assertNotNull(importedSvc.getMetadata());
    assertEquals(1, importedSvc.getOperations().size());
    assertNull(importedSvc.getOperations().get(0).getResourcePaths());
    // Inspect and check resources.
    List<Resource> resources = resourceRepository.findByServiceId(importedSvc.getId());
    assertEquals(1, resources.size());
    Resource resource = resources.get(0);
    assertEquals("WeatherForecast API-1.1.0.yaml", resource.getName());
    assertEquals("weather-forecast-raw-openapi.yaml", resource.getSourceArtifact());
    // Inspect and check requests.
    List<Request> requests = requestRepository.findByOperationId(IdBuilder.buildOperationId(importedSvc, importedSvc.getOperations().get(0)));
    assertEquals(0, requests.size());
    // Inspect and check responses.
    List<Response> responses = responseRepository.findByOperationId(IdBuilder.buildOperationId(importedSvc, importedSvc.getOperations().get(0)));
    assertEquals(0, responses.size());
    try {
        File artifactFile = new File("target/test-classes/io/github/microcks/service/weather-forecast-postman.json");
        services = service.importServiceDefinition(artifactFile, null, new ArtifactInfo("weather-forecast-postman.json", false));
    } catch (MockRepositoryImportException mrie) {
        mrie.printStackTrace();
        fail("No MockRepositoryImportException should have be thrown");
    }
    // Inspect Service own attributes.
    importedSvc = services.get(0);
    assertEquals("WeatherForecast API", importedSvc.getName());
    assertEquals("1.1.0", importedSvc.getVersion());
    assertEquals("weather-forecast-raw-openapi.yaml", importedSvc.getSourceArtifact());
    assertNotNull(importedSvc.getMetadata());
    assertEquals(1, importedSvc.getOperations().size());
    assertEquals(DispatchStyles.URI_ELEMENTS, importedSvc.getOperations().get(0).getDispatcher());
    assertEquals(5, importedSvc.getOperations().get(0).getResourcePaths().size());
    // Inspect and check resources.
    resources = resourceRepository.findByServiceId(importedSvc.getId());
    assertEquals(1, resources.size());
    resource = resources.get(0);
    assertEquals("WeatherForecast API-1.1.0.yaml", resource.getName());
    assertEquals("weather-forecast-raw-openapi.yaml", resource.getSourceArtifact());
    // Inspect and check requests.
    requests = requestRepository.findByOperationId(IdBuilder.buildOperationId(importedSvc, importedSvc.getOperations().get(0)));
    assertEquals(5, requests.size());
    for (Request request : requests) {
        assertEquals("weather-forecast-postman.json", request.getSourceArtifact());
    }
    // Inspect and check responses.
    responses = responseRepository.findByOperationId(IdBuilder.buildOperationId(importedSvc, importedSvc.getOperations().get(0)));
    assertEquals(5, requests.size());
    for (Response response : responses) {
        assertEquals("weather-forecast-postman.json", response.getSourceArtifact());
    }
}
Also used : Response(io.github.microcks.domain.Response) Resource(io.github.microcks.domain.Resource) Request(io.github.microcks.domain.Request) Service(io.github.microcks.domain.Service) File(java.io.File) MockRepositoryImportException(io.github.microcks.util.MockRepositoryImportException) Test(org.junit.Test)

Example 12 with Response

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

the class SoapController method execute.

@RequestMapping(value = "/{service}/{version}/**", method = RequestMethod.POST)
public ResponseEntity<?> execute(@PathVariable("service") String serviceName, @PathVariable("version") String version, @RequestParam(value = "validate", required = false) Boolean validate, @RequestParam(value = "delay", required = false) Long delay, @RequestBody String body, HttpServletRequest request) {
    log.info("Servicing mock response for service [{}, {}]", serviceName, version);
    log.debug("Request body: " + body);
    long startTime = System.currentTimeMillis();
    // If serviceName was encoded with '+' instead of '%20', replace them.
    if (serviceName.contains("+")) {
        serviceName = serviceName.replace('+', ' ');
    }
    log.info("Service name: " + serviceName);
    // Retrieve service and correct operation.
    Service service = serviceRepository.findByNameAndVersion(serviceName, version);
    Operation rOperation = null;
    // Enhancement : retrieve SOAPAction from request headers
    String action = extractSoapAction(request);
    log.debug("Extracted SOAP action from headers: {}", action);
    if (action != null && action.length() > 0) {
        for (Operation operation : service.getOperations()) {
            if (action.equals(operation.getAction())) {
                rOperation = operation;
                log.info("Found valid operation {}", rOperation.getName());
                break;
            }
        }
    }
    // Enhancement : if not found, try getting operation from soap:body directly!
    if (rOperation == null) {
        String operationName = extractOperationName(body);
        log.debug("Extracted operation name from payload: {}", operationName);
        if (operationName != null) {
            for (Operation operation : service.getOperations()) {
                if (operationName.equals(operation.getInputName()) || operationName.equals(operation.getName())) {
                    rOperation = operation;
                    log.info("Found valid operation {}", rOperation.getName());
                    break;
                }
            }
        }
    }
    // Now processing the request and send a response.
    if (rOperation != null) {
        log.debug("Found a valid operation with rules: {}", rOperation.getDispatcherRules());
        if (validate != null && validate) {
            log.debug("Soap message validation is turned on, validating...");
            try {
                List<XmlError> errors = SoapMessageValidator.validateSoapMessage(rOperation.getInputName(), service.getXmlNS(), body, resourceUrl + UriUtils.encodePath(service.getName() + "-" + version, "UTF-8") + ".wsdl", true);
                log.debug("SoapBody validation errors: " + errors.size());
                // Return a 400 http code with errors.
                if (errors != null && errors.size() > 0) {
                    return new ResponseEntity<Object>(errors, HttpStatus.BAD_REQUEST);
                }
            } catch (Exception e) {
                log.error("Error during Soap validation", e);
                return new ResponseEntity<Object>("Error during Soap validation: " + e.getMessage(), HttpStatus.BAD_REQUEST);
            }
        }
        // We must find dispatcher and its rules. Default to operation ones but
        // if we have a Fallback this is the one who is holding the first pass rules.
        String dispatcher = rOperation.getDispatcher();
        String dispatcherRules = rOperation.getDispatcherRules();
        FallbackSpecification fallback = MockControllerCommons.getFallbackIfAny(rOperation);
        if (fallback != null) {
            dispatcher = fallback.getDispatcher();
            dispatcherRules = fallback.getDispatcherRules();
        }
        Response response = null;
        String dispatchCriteria = null;
        // Depending on dispatcher, evaluate request with rules.
        if (DispatchStyles.QUERY_MATCH.equals(dispatcher)) {
            dispatchCriteria = getDispatchCriteriaFromXPathEval(dispatcherRules, body);
        } else if (DispatchStyles.SCRIPT.equals(dispatcher)) {
            dispatchCriteria = getDispatchCriteriaFromScriptEval(dispatcherRules, body, request);
        }
        log.debug("Dispatch criteria for finding response is {}", dispatchCriteria);
        List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria(IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
        if (responses.isEmpty() && fallback != null) {
            // If we've found nothing and got a fallback, that's the moment!
            responses = responseRepository.findByOperationIdAndName(IdBuilder.buildOperationId(service, rOperation), fallback.getFallback());
        }
        if (!responses.isEmpty()) {
            response = responses.get(0);
        }
        // Set Content-Type to "text/xml".
        HttpHeaders responseHeaders = new HttpHeaders();
        // Check to see if we are processing a SOAP 1.2 request
        if (request.getContentType().startsWith("application/soap+xml")) {
            // we are; set Content-Type to "application/soap+xml"
            responseHeaders.setContentType(MediaType.valueOf("application/soap+xml;charset=UTF-8"));
        } else {
            // Set Content-Type to "text/xml".
            responseHeaders.setContentType(MediaType.valueOf("text/xml;charset=UTF-8"));
        }
        // Render response content before waiting and returning.
        String responseContent = MockControllerCommons.renderResponseContent(body, null, request, response);
        // Setting delay to default one if not set.
        if (delay == null && rOperation.getDefaultDelay() != null) {
            delay = rOperation.getDefaultDelay();
        }
        MockControllerCommons.waitForDelay(startTime, delay);
        // Publish an invocation event before returning if enabled.
        if (enableInvocationStats) {
            MockControllerCommons.publishMockInvocation(applicationContext, this, service, response, startTime);
        }
        if (response.isFault()) {
            return new ResponseEntity<Object>(responseContent, responseHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<Object>(responseContent, responseHeaders, HttpStatus.OK);
    }
    log.debug("No valid operation found by Microcks...");
    return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Service(io.github.microcks.domain.Service) XmlError(org.apache.xmlbeans.XmlError) Operation(io.github.microcks.domain.Operation) Response(io.github.microcks.domain.Response) ResponseEntity(org.springframework.http.ResponseEntity) FallbackSpecification(io.github.microcks.util.dispatcher.FallbackSpecification) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 13 with Response

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

the class TestRunnerService method updateTestCaseResultWithReturns.

/**
 */
private void updateTestCaseResultWithReturns(TestCaseResult testCaseResult, List<TestReturn> testReturns, String testCaseId) {
    // Prepare a bunch of flag we're going to complete.
    boolean successFlag = true;
    long caseElapsedTime = 0;
    List<Response> responses = new ArrayList<>();
    List<Request> actualRequests = new ArrayList<>();
    for (TestReturn testReturn : testReturns) {
        // Deal with elapsed time and success flag.
        caseElapsedTime += testReturn.getElapsedTime();
        TestStepResult testStepResult = testReturn.buildTestStepResult();
        if (!testStepResult.isSuccess()) {
            successFlag = false;
        }
        // Extract, complete and store response and request.
        testReturn.getResponse().setTestCaseId(testCaseId);
        testReturn.getRequest().setTestCaseId(testCaseId);
        responses.add(testReturn.getResponse());
        actualRequests.add(testReturn.getRequest());
        testCaseResult.getTestStepResults().add(testStepResult);
    }
    // Save the responses into repository to get their ids.
    log.debug("Saving {} responses with testCaseId {}", responses.size(), testCaseId);
    responseRepository.saveAll(responses);
    // Associate responses to requests before saving requests.
    for (int i = 0; i < actualRequests.size(); i++) {
        actualRequests.get(i).setResponseId(responses.get(i).getId());
    }
    log.debug("Saving {} requests with testCaseId {}", responses.size(), testCaseId);
    requestRepository.saveAll(actualRequests);
    // We cannot consider as success if we have no TestStepResults associated...
    if (testCaseResult.getTestStepResults().size() > 0) {
        testCaseResult.setSuccess(successFlag);
    }
    testCaseResult.setElapsedTime(caseElapsedTime);
}
Also used : Response(io.github.microcks.domain.Response) TestStepResult(io.github.microcks.domain.TestStepResult) TestReturn(io.github.microcks.domain.TestReturn) ArrayList(java.util.ArrayList) PageRequest(org.springframework.data.domain.PageRequest) Request(io.github.microcks.domain.Request)

Aggregations

Response (io.github.microcks.domain.Response)13 Request (io.github.microcks.domain.Request)8 Service (io.github.microcks.domain.Service)6 Header (io.github.microcks.domain.Header)5 Resource (io.github.microcks.domain.Resource)5 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 Operation (io.github.microcks.domain.Operation)4 MockRepositoryImportException (io.github.microcks.util.MockRepositoryImportException)4 IOException (java.io.IOException)4 TestReturn (io.github.microcks.domain.TestReturn)3 FallbackSpecification (io.github.microcks.util.dispatcher.FallbackSpecification)3 File (java.io.File)3 ArrayList (java.util.ArrayList)3 Test (org.junit.Test)3 ClientHttpResponse (org.springframework.http.client.ClientHttpResponse)2 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)1 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 JsonWriteFeature (com.fasterxml.jackson.core.json.JsonWriteFeature)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1