Skip to content

Commit

Permalink
Merge pull request #103 from wiremock/map-http-status-codes
Browse files Browse the repository at this point in the history
Map http status codes
  • Loading branch information
leeturner authored Aug 23, 2024
2 parents b9e3a71 + e55ecf0 commit 924363a
Show file tree
Hide file tree
Showing 4 changed files with 142 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import static org.wiremock.grpc.dsl.GrpcResponseDefinitionBuilder.GRPC_STATUS_NAME;
import static org.wiremock.grpc.dsl.GrpcResponseDefinitionBuilder.GRPC_STATUS_REASON;

import com.github.tomakehurst.wiremock.common.Pair;
import com.github.tomakehurst.wiremock.http.HttpHeader;
import com.github.tomakehurst.wiremock.http.StubRequestHandler;
import com.github.tomakehurst.wiremock.stubbing.ServeEvent;
Expand All @@ -27,6 +28,7 @@
import io.grpc.stub.ServerCalls;
import io.grpc.stub.StreamObserver;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.jetty.http.HttpStatus;
import org.wiremock.grpc.dsl.WireMockGrpc;

public class ClientStreamingServerCallHandler extends BaseCallHandler
Expand Down Expand Up @@ -69,7 +71,24 @@ public void onNext(DynamicMessage request) {
(req, resp, attributes) -> {
final HttpHeader statusHeader = resp.getHeaders().getHeader(GRPC_STATUS_NAME);

if (!statusHeader.isPresent() && resp.getStatus() == 404) {
// 404 needs to be handled as a special case here because when using many requests,
// one reply not all the requests will match. We handle the 404 as a special case
// in the onCompleted method
if (!statusHeader.isPresent() && resp.getStatus() == HttpStatus.NOT_FOUND_404) {
return;
}

if (!statusHeader.isPresent()
&& GrpcStatusUtils.errorHttpToGrpcStatusMappings.containsKey(resp.getStatus())) {
final Pair<Status, String> statusMapping =
GrpcStatusUtils.errorHttpToGrpcStatusMappings.get(resp.getStatus());
final Status grpcStatus = statusMapping.a;
final WireMockGrpc.Status status =
WireMockGrpc.Status.valueOf(grpcStatus.getCode().name());

responseStatus.set(status);
statusReason.set(statusMapping.b);

return;
}

Expand Down Expand Up @@ -114,10 +133,12 @@ public void onCompleted() {
.withDescription(statusReason.get())
.asRuntimeException());
} else {
final Pair<Status, String> notFoundStatusMapping =
GrpcStatusUtils.errorHttpToGrpcStatusMappings.get(HttpStatus.NOT_FOUND_404);
final Status grpcStatus = notFoundStatusMapping.a;

responseObserver.onError(
Status.NOT_FOUND
.withDescription("No matching stub mapping found for gRPC request")
.asRuntimeException());
grpcStatus.withDescription(notFoundStatusMapping.b).asRuntimeException());
}
}
};
Expand Down
45 changes: 45 additions & 0 deletions src/main/java/org/wiremock/grpc/internal/GrpcStatusUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Copyright (C) 2024 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wiremock.grpc.internal;

import com.github.tomakehurst.wiremock.common.Pair;
import io.grpc.Status;
import java.util.Map;

public class GrpcStatusUtils {

private GrpcStatusUtils() {}

// https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md
public static final Map<Integer, Pair<Status, String>> errorHttpToGrpcStatusMappings =
Map.of(
400,
new Pair<>(Status.INTERNAL, "Bad Request"),
401,
new Pair<>(Status.UNAUTHENTICATED, "You are not authorized to access this resource"),
403,
new Pair<>(Status.PERMISSION_DENIED, "You are not authorized to access this resource"),
404,
new Pair<>(Status.UNIMPLEMENTED, "No matching stub mapping found for gRPC request"),
429,
new Pair<>(Status.UNAVAILABLE, "Too many requests"),
502,
new Pair<>(Status.UNAVAILABLE, "Bad Gateway"),
503,
new Pair<>(Status.UNAVAILABLE, "Service Unavailable"),
504,
new Pair<>(Status.UNAVAILABLE, "Gateway Timeout"));
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import static org.wiremock.grpc.dsl.GrpcResponseDefinitionBuilder.GRPC_STATUS_REASON;
import static org.wiremock.grpc.internal.Delays.delayIfRequired;

import com.github.tomakehurst.wiremock.common.Pair;
import com.github.tomakehurst.wiremock.http.HttpHeader;
import com.github.tomakehurst.wiremock.http.StubRequestHandler;
import com.github.tomakehurst.wiremock.stubbing.ServeEvent;
Expand Down Expand Up @@ -60,11 +61,12 @@ public void invoke(DynamicMessage request, StreamObserver<DynamicMessage> respon

delayIfRequired(resp);

if (!statusHeader.isPresent() && resp.getStatus() == 404) {
if (!statusHeader.isPresent()
&& GrpcStatusUtils.errorHttpToGrpcStatusMappings.containsKey(resp.getStatus())) {
final Pair<Status, String> statusMapping =
GrpcStatusUtils.errorHttpToGrpcStatusMappings.get(resp.getStatus());
responseObserver.onError(
Status.NOT_FOUND
.withDescription("No matching stub mapping found for gRPC request")
.asRuntimeException());
statusMapping.a.withDescription(statusMapping.b).asRuntimeException());
return;
}

Expand Down
72 changes: 66 additions & 6 deletions src/test/java/org/wiremock/grpc/GrpcAcceptanceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,31 @@
*/
package org.wiremock.grpc;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson;
import static com.github.tomakehurst.wiremock.client.WireMock.moreThanOrExactly;
import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.wiremock.grpc.dsl.WireMockGrpc.*;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.iterableWithSize;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.wiremock.grpc.dsl.WireMockGrpc.Status;
import static org.wiremock.grpc.dsl.WireMockGrpc.equalToMessage;
import static org.wiremock.grpc.dsl.WireMockGrpc.json;
import static org.wiremock.grpc.dsl.WireMockGrpc.jsonTemplate;
import static org.wiremock.grpc.dsl.WireMockGrpc.message;
import static org.wiremock.grpc.dsl.WireMockGrpc.messageAsAny;
import static org.wiremock.grpc.dsl.WireMockGrpc.method;

import com.example.grpc.AnotherGreetingServiceGrpc;
import com.example.grpc.GreetingServiceGrpc;
Expand All @@ -44,14 +62,19 @@
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Stream;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.wiremock.grpc.client.AnotherGreetingsClient;
import org.wiremock.grpc.client.GreetingsClient;
import org.wiremock.grpc.dsl.WireMockGrpcService;
import org.wiremock.grpc.internal.GrpcStatusUtils;

public class GrpcAcceptanceTest {

Expand All @@ -73,6 +96,14 @@ public class GrpcAcceptanceTest {
.extensions(new GrpcExtensionFactory()))
.build();

public static Stream<Arguments> statusProvider() {
return GrpcStatusUtils.errorHttpToGrpcStatusMappings.entrySet().stream()
.map(
entry ->
Arguments.of(
entry.getKey(), entry.getValue().a.getCode().name(), entry.getValue().b));
}

@BeforeEach
void init() {
wireMock = wm.getRuntimeInfo().getWireMock();
Expand Down Expand Up @@ -167,7 +198,21 @@ void matchesRequestViaExactMessageEquality() {
StatusRuntimeException exception =
assertThrows(StatusRuntimeException.class, () -> greetingsClient.greet("Wrong"));
assertThat(
exception.getMessage(), is("NOT_FOUND: No matching stub mapping found for gRPC request"));
exception.getMessage(),
is("UNIMPLEMENTED: No matching stub mapping found for gRPC request"));
}

@ParameterizedTest
@MethodSource("statusProvider")
void shouldReturnTheCorrectGrpcErrorStatusForCorrespondingHttpStatus(
Integer httpStatus, String grpcStatus, String message) {
wm.stubFor(
post(urlPathEqualTo("/com.example.grpc.GreetingService/greeting"))
.willReturn(aResponse().withStatus(httpStatus)));

StatusRuntimeException exception =
assertThrows(StatusRuntimeException.class, () -> greetingsClient.greet("Tom"));
assertThat(exception.getMessage(), is(grpcStatus + ": " + message));
}

@Test
Expand Down Expand Up @@ -204,7 +249,7 @@ void throwsNotFoundWhenNoStreamingClientMessageMatches() {
assertThat(exception.getCause(), instanceOf(StatusRuntimeException.class));
assertThat(
exception.getCause().getMessage(),
is("NOT_FOUND: No matching stub mapping found for gRPC request"));
is("UNIMPLEMENTED: No matching stub mapping found for gRPC request"));
}

@Test
Expand All @@ -221,6 +266,21 @@ void throwsReturnedErrorFromStreamingClientCall() {
assertThat(exception.getCause().getMessage(), is("INVALID_ARGUMENT: Jerf is not a valid name"));
}

@ParameterizedTest
@MethodSource("statusProvider")
void throwsReturnedErrorFromStreamingClientCallWhenServerOnlyReturnsAHttpStatus(
Integer httpStatus, String grpcStatus, String message) {
wm.stubFor(
post(urlPathEqualTo("/com.example.grpc.GreetingService/manyGreetingsOneReply"))
.willReturn(aResponse().withStatus(httpStatus)));

Exception exception =
assertThrows(
Exception.class, () -> greetingsClient.manyGreetingsOneReply("Tom", "Jerf", "Rob"));
assertThat(exception.getCause(), instanceOf(StatusRuntimeException.class));
assertThat(exception.getCause().getMessage(), is(grpcStatus + ": " + message));
}

@Test
void returnsStreamedResponseToUnaryRequest() {
mockGreetingService.stubFor(
Expand Down

0 comments on commit 924363a

Please sign in to comment.