Search in sources :

Example 1 with RequestDefinition

use of org.mockserver.model.RequestDefinition in project OpenLineage by OpenLineage.

the class SparkContainerIntegrationTest method verifyEvents.

private void verifyEvents(String... eventFiles) {
    Path eventFolder = Paths.get("integrations/container/");
    mockServerClient.verify(Arrays.stream(eventFiles).map(fileEvent -> request().withPath("/api/v1/lineage").withBody(readJson(eventFolder.resolve(fileEvent)))).collect(Collectors.toList()).toArray(new RequestDefinition[0]));
}
Also used : Path(java.nio.file.Path) CsvSource(org.junit.jupiter.params.provider.CsvSource) Arrays(java.util.Arrays) SneakyThrows(lombok.SneakyThrows) LoggerFactory(org.slf4j.LoggerFactory) Network(org.testcontainers.containers.Network) AdminClient(org.apache.kafka.clients.admin.AdminClient) AfterAll(org.junit.jupiter.api.AfterAll) HttpRequest.request(org.mockserver.model.HttpRequest.request) MockServerContainer(org.testcontainers.containers.MockServerContainer) Files.readAllBytes(java.nio.file.Files.readAllBytes) BeforeAll(org.junit.jupiter.api.BeforeAll) EnabledIfSystemProperty(org.junit.jupiter.api.condition.EnabledIfSystemProperty) GenericContainer(org.testcontainers.containers.GenericContainer) Tag(org.junit.jupiter.api.Tag) MockServerClient(org.mockserver.client.MockServerClient) Path(java.nio.file.Path) Container(org.testcontainers.junit.jupiter.Container) KafkaContainer(org.testcontainers.containers.KafkaContainer) Logger(org.slf4j.Logger) ImmutableMap(com.google.common.collect.ImmutableMap) MatchType(org.mockserver.matchers.MatchType) JsonBody.json(org.mockserver.model.JsonBody.json) Testcontainers(org.testcontainers.junit.jupiter.Testcontainers) NewTopic(org.apache.kafka.clients.admin.NewTopic) Collectors(java.util.stream.Collectors) JsonBody(org.mockserver.model.JsonBody) Test(org.junit.jupiter.api.Test) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Paths(java.nio.file.Paths) Awaitility(org.awaitility.Awaitility) RequestDefinition(org.mockserver.model.RequestDefinition) RequestDefinition(org.mockserver.model.RequestDefinition)

Example 2 with RequestDefinition

use of org.mockserver.model.RequestDefinition in project mockserver by mock-server.

the class MockServerEventLogTest method shouldRetrieveLogEntriesWithNullRequestMatcher.

@Test
public void shouldRetrieveLogEntriesWithNullRequestMatcher() {
    Level originalLevel = ConfigurationProperties.logLevel();
    try {
        // given
        ConfigurationProperties.logLevel("INFO");
        mockServerLogger.logEvent(new LogEntry().setLogLevel(INFO).setType(RECEIVED_REQUEST).setHttpRequest(request("request_one")).setMessageFormat(RECEIVED_REQUEST_MESSAGE_FORMAT).setArguments(request("request_one")));
        mockServerLogger.logEvent(new LogEntry().setLogLevel(INFO).setType(NO_MATCH_RESPONSE).setHttpRequest(request("request_one")).setExpectation(new Expectation(request("request_one")).thenRespond(response("response_two"))).setMessageFormat("no expectation for:{}returning response:{}").setArguments(request("request_one"), notFoundResponse()));
        mockServerLogger.logEvent(new LogEntry().setLogLevel(INFO).setType(RECEIVED_REQUEST).setHttpRequests(new RequestDefinition[] { request("request_two"), request("request_three") }).setMessageFormat(RECEIVED_REQUEST_MESSAGE_FORMAT).setArguments(request("request_two")));
        mockServerLogger.logEvent(new LogEntry().setType(EXPECTATION_MATCHED).setLogLevel(INFO).setHttpRequest(request("request_two")).setExpectation(new Expectation(request("request_two")).thenRespond(response("response_two"))).setMessageFormat("request:{}matched expectation:{}").setArguments(request("request_two"), new Expectation(request("request_two")).thenRespond(response("response_two"))));
        mockServerLogger.logEvent(new LogEntry().setType(EXPECTATION_RESPONSE).setLogLevel(INFO).setHttpRequest(request("request_two")).setHttpResponse(response("response_two")).setMessageFormat("request:{}matched expectation:{}").setMessageFormat("returning response:{}for request:{}for action:{}").setArguments(request("request_two"), response("response_two"), response("response_two")));
        mockServerLogger.logEvent(new LogEntry().setType(TRACE).setHttpRequest(request("request_four")).setExpectation(new Expectation(request("request_four")).thenRespond(response("response_four"))).setMessageFormat("some random{}message").setArguments("argument_one"));
        mockServerLogger.logEvent(new LogEntry().setType(FORWARDED_REQUEST).setHttpRequest(request("request_five")).setHttpResponse(response("response_five")).setExpectation(request("request_five"), response("response_five")));
        // then
        assertThat(retrieveRequests(null), contains(request("request_one"), request("request_two"), request("request_three")));
        assertThat(retrieveRequestResponseMessageLogEntries(null), contains(new LogEntry().setEpochTime(EpochService.currentTimeMillis()).setLogLevel(INFO).setType(NO_MATCH_RESPONSE).setHttpRequest(request("request_one")).setExpectation(new Expectation(request("request_one")).thenRespond(response("response_two"))).setMessageFormat("no expectation for:{}returning response:{}").setArguments(request("request_one"), notFoundResponse()), new LogEntry().setEpochTime(EpochService.currentTimeMillis()).setLogLevel(INFO).setType(EXPECTATION_RESPONSE).setHttpRequest(request("request_two")).setHttpResponse(response("response_two")).setMessageFormat("request:{}matched expectation:{}").setMessageFormat("returning response:{}for request:{}for action:{}").setArguments(request("request_two"), response("response_two"), response("response_two")), new LogEntry().setType(FORWARDED_REQUEST).setHttpRequest(request("request_five")).setHttpResponse(response("response_five")).setExpectation(request("request_five"), response("response_five"))));
        assertThat(retrieveRecordedExpectations(null), contains(new Expectation(request("request_five"), Times.once(), TimeToLive.unlimited(), 0).thenRespond(response("response_five"))));
        List<LogEntry> actual = retrieveMessageLogEntries(null);
        assertThat(actual, contains(new LogEntry().setLogLevel(INFO).setType(RECEIVED_REQUEST).setHttpRequest(request("request_one")).setMessageFormat(RECEIVED_REQUEST_MESSAGE_FORMAT).setArguments(request("request_one")), new LogEntry().setLogLevel(INFO).setType(NO_MATCH_RESPONSE).setHttpRequest(request("request_one")).setExpectation(new Expectation(request("request_one")).thenRespond(response("response_two"))).setMessageFormat("no expectation for:{}returning response:{}").setArguments(request("request_one"), notFoundResponse()), new LogEntry().setLogLevel(INFO).setType(RECEIVED_REQUEST).setHttpRequests(new RequestDefinition[] { request("request_two"), request("request_three") }).setMessageFormat(RECEIVED_REQUEST_MESSAGE_FORMAT).setArguments(request("request_two")), new LogEntry().setType(EXPECTATION_MATCHED).setLogLevel(INFO).setHttpRequest(request("request_two")).setExpectation(new Expectation(request("request_two")).thenRespond(response("response_two"))).setMessageFormat("request:{}matched expectation:{}").setArguments(request("request_two"), new Expectation(request("request_two")).thenRespond(response("response_two"))), new LogEntry().setType(EXPECTATION_RESPONSE).setLogLevel(INFO).setHttpRequest(request("request_two")).setHttpResponse(response("response_two")).setMessageFormat("request:{}matched expectation:{}").setMessageFormat("returning response:{}for request:{}for action:{}").setArguments(request("request_two"), response("response_two"), response("response_two")), new LogEntry().setType(TRACE).setHttpRequest(request("request_four")).setExpectation(new Expectation(request("request_four")).thenRespond(response("response_four"))).setMessageFormat("some random{}message").setArguments("argument_one"), new LogEntry().setType(FORWARDED_REQUEST).setHttpRequest(request("request_five")).setHttpResponse(response("response_five")).setExpectation(request("request_five"), response("response_five"))));
    } finally {
        ConfigurationProperties.logLevel(originalLevel.name());
    }
}
Also used : RequestDefinition(org.mockserver.model.RequestDefinition) Level(org.slf4j.event.Level) Expectation(org.mockserver.mock.Expectation) LogEntry(org.mockserver.log.model.LogEntry) Test(org.junit.Test)

Example 3 with RequestDefinition

use of org.mockserver.model.RequestDefinition in project mockserver by mock-server.

the class ExpectationToJavaSerializer method serialize.

@Override
public String serialize(int numberOfSpacesToIndent, Expectation expectation) {
    StringBuffer output = new StringBuffer();
    if (expectation != null) {
        appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append("new MockServerClient(\"localhost\", 1080)");
        appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(".when(");
        RequestDefinition requestDefinition = expectation.getHttpRequest();
        if (requestDefinition instanceof HttpRequest) {
            output.append(new HttpRequestToJavaSerializer().serialize(numberOfSpacesToIndent + 1, (HttpRequest) requestDefinition));
        } else if (requestDefinition instanceof OpenAPIDefinition) {
            output.append(new OpenAPIMatcherToJavaSerializer().serialize(numberOfSpacesToIndent + 1, (OpenAPIDefinition) requestDefinition));
        }
        output.append(",");
        if (expectation.getTimes() != null) {
            output.append(new TimesToJavaSerializer().serialize(numberOfSpacesToIndent + 1, expectation.getTimes()));
        } else {
            appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append("null");
        }
        output.append(",");
        if (expectation.getTimeToLive() != null) {
            output.append(new TimeToLiveToJavaSerializer().serialize(numberOfSpacesToIndent + 1, expectation.getTimeToLive()));
        } else {
            appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append("null");
        }
        output.append(",");
        appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(expectation.getPriority());
        appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(")");
        if (expectation.getHttpResponse() != null) {
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(".respond(");
            output.append(new HttpResponseToJavaSerializer().serialize(numberOfSpacesToIndent + 1, expectation.getHttpResponse()));
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(")");
        }
        if (expectation.getHttpResponseTemplate() != null) {
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(".respond(");
            output.append(new HttpTemplateToJavaSerializer().serialize(numberOfSpacesToIndent + 1, expectation.getHttpResponseTemplate()));
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(")");
        }
        if (expectation.getHttpResponseClassCallback() != null) {
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(".respond(");
            output.append(new HttpClassCallbackToJavaSerializer().serialize(numberOfSpacesToIndent + 1, expectation.getHttpResponseClassCallback()));
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(")");
        }
        if (expectation.getHttpResponseObjectCallback() != null) {
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append("/*NOT POSSIBLE TO GENERATE CODE FOR OBJECT CALLBACK*/");
        }
        if (expectation.getHttpForward() != null) {
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(".forward(");
            output.append(new HttpForwardToJavaSerializer().serialize(numberOfSpacesToIndent + 1, expectation.getHttpForward()));
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(")");
        }
        if (expectation.getHttpOverrideForwardedRequest() != null) {
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(".forward(");
            output.append(new HttpOverrideForwardedRequestToJavaSerializer().serialize(numberOfSpacesToIndent + 1, expectation.getHttpOverrideForwardedRequest()));
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(")");
        }
        if (expectation.getHttpForwardTemplate() != null) {
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(".forward(");
            output.append(new HttpTemplateToJavaSerializer().serialize(numberOfSpacesToIndent + 1, expectation.getHttpForwardTemplate()));
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(")");
        }
        if (expectation.getHttpForwardClassCallback() != null) {
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(".forward(");
            output.append(new HttpClassCallbackToJavaSerializer().serialize(numberOfSpacesToIndent + 1, expectation.getHttpForwardClassCallback()));
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(")");
        }
        if (expectation.getHttpForwardObjectCallback() != null) {
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append("/*NOT POSSIBLE TO GENERATE CODE FOR OBJECT CALLBACK*/");
        }
        if (expectation.getHttpError() != null) {
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(".error(");
            output.append(new HttpErrorToJavaSerializer().serialize(numberOfSpacesToIndent + 1, expectation.getHttpError()));
            appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append(")");
        }
        output.append(";");
    }
    return output.toString();
}
Also used : HttpRequest(org.mockserver.model.HttpRequest) RequestDefinition(org.mockserver.model.RequestDefinition) OpenAPIDefinition(org.mockserver.model.OpenAPIDefinition)

Example 4 with RequestDefinition

use of org.mockserver.model.RequestDefinition in project mockserver by mock-server.

the class MockServerEventLog method verify.

public void verify(VerificationSequence verificationSequence, Consumer<String> resultConsumer) {
    if (verificationSequence != null) {
        final String logCorrelationId = UUIDService.getUUID();
        if (MockServerLogger.isEnabled(Level.INFO)) {
            mockServerLogger.logEvent(new LogEntry().setType(VERIFICATION).setLogLevel(Level.INFO).setCorrelationId(logCorrelationId).setHttpRequests(verificationSequence.getHttpRequests().toArray(new RequestDefinition[0])).setMessageFormat(VERIFICATION_REQUEST_SEQUENCES_MESSAGE_FORMAT).setArguments(verificationSequence));
        }
        if (verificationSequence.getExpectationIds() != null && !verificationSequence.getExpectationIds().isEmpty()) {
            retrieveAllRequests(verificationSequence.getExpectationIds().stream().map(ExpectationId::getId).collect(Collectors.toList()), allRequests -> {
                List<RequestDefinition> requestDefinitions = allRequests.stream().map(RequestAndExpectationId::getRequestDefinition).collect(Collectors.toList());
                try {
                    String failureMessage = "";
                    int requestLogCounter = 0;
                    for (ExpectationId expectationId : verificationSequence.getExpectationIds()) {
                        if (expectationId != null) {
                            boolean foundRequest = false;
                            for (; !foundRequest && requestLogCounter < allRequests.size(); requestLogCounter++) {
                                if (allRequests.get(requestLogCounter).matches(expectationId)) {
                                    // move on to next request
                                    foundRequest = true;
                                }
                            }
                            if (!foundRequest) {
                                failureMessage = verificationSequenceFailureMessage(verificationSequence, logCorrelationId, requestDefinitions);
                                break;
                            }
                        }
                    }
                    verificationSequenceSuccessMessage(verificationSequence, resultConsumer, logCorrelationId, failureMessage);
                } catch (Throwable throwable) {
                    verificationSequenceExceptionHandler(verificationSequence, resultConsumer, logCorrelationId, throwable, "exception:{} while processing verification sequence:{}", "exception while processing verification sequence");
                }
            });
        } else {
            retrieveAllRequests(false, allRequests -> {
                try {
                    String failureMessage = "";
                    int requestLogCounter = 0;
                    for (RequestDefinition verificationHttpRequest : verificationSequence.getHttpRequests()) {
                        if (verificationHttpRequest != null) {
                            verificationHttpRequest.withLogCorrelationId(logCorrelationId);
                            HttpRequestMatcher httpRequestMatcher = matcherBuilder.transformsToMatcher(verificationHttpRequest);
                            boolean foundRequest = false;
                            for (; !foundRequest && requestLogCounter < allRequests.size(); requestLogCounter++) {
                                if (httpRequestMatcher.matches(allRequests.get(requestLogCounter).cloneWithLogCorrelationId())) {
                                    // move on to next request
                                    foundRequest = true;
                                }
                            }
                            if (!foundRequest) {
                                failureMessage = verificationSequenceFailureMessage(verificationSequence, logCorrelationId, allRequests);
                                break;
                            }
                        }
                    }
                    verificationSequenceSuccessMessage(verificationSequence, resultConsumer, logCorrelationId, failureMessage);
                } catch (Throwable throwable) {
                    verificationSequenceExceptionHandler(verificationSequence, resultConsumer, logCorrelationId, throwable, "exception:{} while processing verification sequence:{}", "exception while processing verification sequence");
                }
            });
        }
    } else {
        resultConsumer.accept("");
    }
}
Also used : RequestAndExpectationId(org.mockserver.log.model.RequestAndExpectationId) ExpectationId(org.mockserver.model.ExpectationId) HttpRequestMatcher(org.mockserver.matchers.HttpRequestMatcher) RequestDefinition(org.mockserver.model.RequestDefinition) LogEntry(org.mockserver.log.model.LogEntry)

Example 5 with RequestDefinition

use of org.mockserver.model.RequestDefinition in project mockserver by mock-server.

the class MockServerEventLogTest method shouldRetrieveLogEntriesWithRequestMatcher.

@Test
public void shouldRetrieveLogEntriesWithRequestMatcher() {
    Level originalLevel = ConfigurationProperties.logLevel();
    try {
        // given
        ConfigurationProperties.logLevel("INFO");
        mockServerLogger.logEvent(new LogEntry().setLogLevel(INFO).setType(RECEIVED_REQUEST).setHttpRequest(request("request_one")).setMessageFormat(RECEIVED_REQUEST_MESSAGE_FORMAT).setArguments(request("request_one")));
        mockServerLogger.logEvent(new LogEntry().setLogLevel(INFO).setType(NO_MATCH_RESPONSE).setHttpRequest(request("request_one")).setExpectation(new Expectation(request("request_one")).thenRespond(response("response_two"))).setMessageFormat("no expectation for:{}returning response:{}").setArguments(request("request_one"), notFoundResponse()));
        mockServerLogger.logEvent(new LogEntry().setLogLevel(INFO).setType(RECEIVED_REQUEST).setHttpRequest(request("request_two")).setMessageFormat(RECEIVED_REQUEST_MESSAGE_FORMAT).setArguments(request("request_two")));
        mockServerLogger.logEvent(new LogEntry().setType(EXPECTATION_MATCHED).setLogLevel(INFO).setHttpRequest(request("request_two")).setExpectation(new Expectation(request("request_two")).thenRespond(response("response_two"))).setMessageFormat("request:{}matched expectation:{}").setArguments(request("request_two"), new Expectation(request("request_two")).thenRespond(response("response_two"))));
        mockServerLogger.logEvent(new LogEntry().setType(EXPECTATION_RESPONSE).setLogLevel(INFO).setHttpRequest(request("request_two")).setHttpResponse(response("response_two")).setMessageFormat("request:{}matched expectation:{}").setMessageFormat("returning response:{}for request:{}for action:{}").setArguments(request("request_two"), response("response_two"), response("response_two")));
        mockServerLogger.logEvent(new LogEntry().setType(TRACE).setHttpRequest(request("request_four")).setExpectation(new Expectation(request("request_four")).thenRespond(response("response_four"))).setMessageFormat("some random{}message").setArguments("argument_one"));
        mockServerLogger.logEvent(new LogEntry().setType(FORWARDED_REQUEST).setHttpRequest(request("request_five")).setHttpResponse(response("response_five")).setExpectation(request("request_five"), response("response_five")));
        // then
        RequestDefinition requestMatcher = request("request_one");
        assertThat(retrieveRequests(requestMatcher), contains(request("request_one")));
        assertThat(retrieveRequestResponseMessageLogEntries(requestMatcher), contains(new LogEntry().setEpochTime(EpochService.currentTimeMillis()).setLogLevel(INFO).setType(NO_MATCH_RESPONSE).setHttpRequest(request("request_one")).setExpectation(new Expectation(request("request_one")).thenRespond(response("response_two"))).setMessageFormat("no expectation for:{}returning response:{}").setArguments(request("request_one"), notFoundResponse())));
        assertThat(retrieveRecordedExpectations(requestMatcher), empty());
        assertThat(retrieveMessageLogEntries(requestMatcher), contains(new LogEntry().setLogLevel(INFO).setType(RECEIVED_REQUEST).setHttpRequest(request("request_one")).setMessageFormat(RECEIVED_REQUEST_MESSAGE_FORMAT).setArguments(request("request_one")), new LogEntry().setLogLevel(INFO).setType(NO_MATCH_RESPONSE).setHttpRequest(request("request_one")).setExpectation(new Expectation(request("request_one")).thenRespond(response("response_two"))).setMessageFormat("no expectation for:{}returning response:{}").setArguments(request("request_one"), notFoundResponse())));
    } finally {
        ConfigurationProperties.logLevel(originalLevel.name());
    }
}
Also used : RequestDefinition(org.mockserver.model.RequestDefinition) Level(org.slf4j.event.Level) Expectation(org.mockserver.mock.Expectation) LogEntry(org.mockserver.log.model.LogEntry) Test(org.junit.Test)

Aggregations

RequestDefinition (org.mockserver.model.RequestDefinition)7 LogEntry (org.mockserver.log.model.LogEntry)5 Level (org.slf4j.event.Level)3 ImmutableMap (com.google.common.collect.ImmutableMap)2 Collectors (java.util.stream.Collectors)2 Test (org.junit.Test)2 HttpRequestMatcher (org.mockserver.matchers.HttpRequestMatcher)2 Expectation (org.mockserver.mock.Expectation)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 HOST (com.google.common.net.HttpHeaders.HOST)1 io.netty.channel (io.netty.channel)1 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)1 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)1 io.netty.handler.codec.http.websocketx (io.netty.handler.codec.http.websocketx)1 AttributeKey (io.netty.util.AttributeKey)1