|
| 1 | +package com.retailsvc.http; |
| 2 | + |
| 3 | +import static java.net.HttpURLConnection.HTTP_NOT_FOUND; |
| 4 | +import static java.net.HttpURLConnection.HTTP_OK; |
| 5 | +import static org.assertj.core.api.Assertions.assertThat; |
| 6 | + |
| 7 | +import com.retailsvc.http.spec.Spec; |
| 8 | +import com.retailsvc.http.support.SpecFixtures; |
| 9 | +import java.net.URI; |
| 10 | +import java.net.http.HttpClient; |
| 11 | +import java.net.http.HttpRequest; |
| 12 | +import java.net.http.HttpResponse; |
| 13 | +import java.util.LinkedHashMap; |
| 14 | +import java.util.Map; |
| 15 | +import org.junit.jupiter.api.Test; |
| 16 | + |
| 17 | +class MultiSpecServerIT { |
| 18 | + |
| 19 | + @Test |
| 20 | + void twoBindingsServeTrafficAndUnknownPathReturns404() throws Exception { |
| 21 | + Spec v1 = SpecFixtures.specAt("http://localhost/api/v1"); |
| 22 | + Spec v2 = SpecFixtures.specAt("http://localhost/api/v2"); |
| 23 | + |
| 24 | + Map<String, RequestHandler> v1Handlers = handlersFor(v1, req -> Response.ok(Map.of("v", 1))); |
| 25 | + Map<String, RequestHandler> v2Handlers = handlersFor(v2, req -> Response.ok(Map.of("v", 2))); |
| 26 | + |
| 27 | + try (OpenApiServer server = |
| 28 | + OpenApiServer.builder() |
| 29 | + .port(0) |
| 30 | + .addSpec(v1, v1Handlers) |
| 31 | + .addSpec(v2, v2Handlers) |
| 32 | + .useExternalAuthentication() |
| 33 | + .build()) { |
| 34 | + |
| 35 | + int port = server.listenPort(); |
| 36 | + HttpResponse<String> v1Resp = get("http://localhost:" + port + "/api/v1/data"); |
| 37 | + HttpResponse<String> v2Resp = get("http://localhost:" + port + "/api/v2/data"); |
| 38 | + assertThat(v1Resp.statusCode()).isEqualTo(HTTP_OK); |
| 39 | + assertThat(v1Resp.body()).contains("\"v\":1"); |
| 40 | + assertThat(v2Resp.statusCode()).isEqualTo(HTTP_OK); |
| 41 | + assertThat(v2Resp.body()).contains("\"v\":2"); |
| 42 | + assertThat(get("http://localhost:" + port + "/nope").statusCode()).isEqualTo(HTTP_NOT_FOUND); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + private static Map<String, RequestHandler> handlersFor(Spec spec, RequestHandler shared) { |
| 47 | + Map<String, RequestHandler> out = new LinkedHashMap<>(); |
| 48 | + spec.operations().forEach(op -> out.put(op.operationId(), shared)); |
| 49 | + return out; |
| 50 | + } |
| 51 | + |
| 52 | + private static HttpResponse<String> get(String url) throws Exception { |
| 53 | + return HttpClient.newHttpClient() |
| 54 | + .send( |
| 55 | + HttpRequest.newBuilder(URI.create(url)).GET().build(), |
| 56 | + HttpResponse.BodyHandlers.ofString()); |
| 57 | + } |
| 58 | +} |
0 commit comments