com.linecorp.armeria.common.AggregatedHttpResponse Java Examples

The following examples show how to use com.linecorp.armeria.common.AggregatedHttpResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TokenBucketThrottlingStrategyTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void throttle3() throws Exception {
    final WebClient client = WebClient.of(serverRule.httpUri());
    final AggregatedHttpResponse response1 = client.get("/http-throttle3").aggregate().get();
    assertThat(response1.status()).isEqualTo(HttpStatus.OK);

    assertThat(response1.headers().contains(HttpHeaderNames.RETRY_AFTER)).isFalse();
    assertThat(response1.headers().contains("RateLimit-Remaining")).isFalse();
    assertThat(response1.headers().contains("X-Rate-Limit-Remaining")).isFalse();
    assertThat(response1.headers().contains("X-RateLimit-Remaining")).isFalse();
    assertThat(response1.headers().contains("X-RateLimit-Reset")).isFalse();

    final AggregatedHttpResponse response2 = client.get("/http-throttle3").aggregate().get();
    assertThat(response2.status()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS);

    assertThat(response2.headers().contains(HttpHeaderNames.RETRY_AFTER)).isTrue();
    final long retryAfter2 = Long.parseLong(response2.headers().get(HttpHeaderNames.RETRY_AFTER));
    assertThat(retryAfter2).isBetween(0L, 10L);
    assertThat(response2.headers().contains("RateLimit-Remaining")).isFalse();
    assertThat(response2.headers().contains("X-Rate-Limit-Remaining")).isFalse();
    assertThat(response2.headers().contains("X-RateLimit-Remaining")).isFalse();
    assertThat(response2.headers().contains("X-RateLimit-Reset")).isFalse();
}
 
Example #2
Source File: WebAppContainerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void https() throws Exception {
    final WebClient client = WebClient.builder(server().uri(SessionProtocol.HTTPS))
                                      .factory(ClientFactory.insecure())
                                      .build();
    final AggregatedHttpResponse response = client.get("/jsp/index.jsp").aggregate().get();
    final String actualContent = CR_OR_LF.matcher(response.contentUtf8())
                                         .replaceAll("");
    assertThat(actualContent).isEqualTo(
            "<html><body>" +
            "<p>Hello, Armerian World!</p>" +
            "<p>Have you heard about the class 'org.slf4j.Logger'?</p>" +
            "<p>Context path: </p>" + // ROOT context path
            "<p>Request URI: /index.jsp</p>" +
            "<p>Scheme: https</p>" +
            "</body></html>");
}
 
Example #3
Source File: ServiceBindingTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void routeService() throws InterruptedException {
    final WebClient client = WebClient.of(server.httpUri());
    AggregatedHttpResponse res = client.get("/greet/armeria").aggregate().join();
    propertyCheckLatch.await();
    assertThat(res.status()).isSameAs(HttpStatus.OK);
    assertThat(res.contentUtf8()).isEqualTo("armeria");

    res = client.post("/greet", "armeria").aggregate().join();
    assertThat(res.status()).isSameAs(HttpStatus.OK);
    assertThat(res.contentUtf8()).isEqualTo("armeria");

    res = client.put("/greet/armeria", "armeria").aggregate().join();
    assertThat(res.status()).isSameAs(HttpStatus.METHOD_NOT_ALLOWED);

    res = client.put("/greet", "armeria").aggregate().join();
    assertThat(res.status()).isSameAs(HttpStatus.METHOD_NOT_ALLOWED);
}
 
Example #4
Source File: ProxyClientIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testProxy_protocolUpgrade_notSharableExceptionNotThrown() throws Exception {
    DYNAMIC_HANDLER.setWriteCustomizer((ctx, msg, promise) -> {
        ctx.write(new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED), promise);
    });
    final ClientFactory clientFactory = ClientFactory.builder().proxyConfig(
            ProxyConfig.socks4(socksProxyServer.address())).build();
    final WebClient webClient = WebClient.builder(SessionProtocol.HTTP, backendServer.httpEndpoint())
                                         .factory(clientFactory)
                                         .decorator(LoggingClient.newDecorator())
                                         .build();
    final CompletableFuture<AggregatedHttpResponse> responseFuture =
            webClient.get(PROXY_PATH).aggregate();
    assertThatThrownBy(responseFuture::join).isInstanceOf(CompletionException.class)
                                            .hasCauseInstanceOf(UnprocessedRequestException.class)
                                            .hasRootCauseInstanceOf(ProxyConnectException.class);
    clientFactory.close();
}
 
Example #5
Source File: ContentServiceV1Test.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Test
void deleteFile() throws IOException {
    final WebClient client = dogma.httpClient();
    addFooJson(client);
    addBarTxt(client);

    final String body =
            '{' +
            "   \"path\": \"/foo.json\"," +
            "   \"type\": \"REMOVE\"," +
            "   \"commitMessage\" : {" +
            "       \"summary\" : \"Delete foo.json\"" +
            "   }" +
            '}';
    final RequestHeaders headers = RequestHeaders.of(HttpMethod.POST, CONTENTS_PREFIX,
                                                     HttpHeaderNames.CONTENT_TYPE, MediaType.JSON);
    final AggregatedHttpResponse res1 = client.execute(headers, body).aggregate().join();
    assertThat(ResponseHeaders.of(res1.headers()).status()).isEqualTo(HttpStatus.OK);

    final AggregatedHttpResponse res2 = client.get(CONTENTS_PREFIX + "/**").aggregate().join();
    // /a directory and /a/bar.txt file are left
    assertThat(Jackson.readTree(res2.contentUtf8()).size()).isEqualTo(2);
}
 
Example #6
Source File: AnnotatedServiceResponseConverterTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleObjectPublisherBasedResponseConverter() throws Exception {
    final WebClient client = WebClient.of(rule.httpUri() + "/publish/multi");

    AggregatedHttpResponse res;

    res = aggregated(client.get("/string"));
    assertThat(res.contentType()).isEqualTo(MediaType.JSON_UTF_8);
    assertThatJson(res.contentUtf8())
            .isArray().ofLength(3)
            .thatContains("a").thatContains("b").thatContains("c");

    res = aggregated(client.get("/jsonNode"));
    assertThat(res.contentType()).isEqualTo(MediaType.JSON_UTF_8);
    assertThatJson(res.contentUtf8())
            .isEqualTo("[{\"a\":\"1\"},{\"b\":\"2\"},{\"c\":\"3\"}]");
}
 
Example #7
Source File: ArmeriaCentralDogma.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the content of the specified {@link AggregatedHttpResponse} into a {@link JsonNode}.
 */
private static JsonNode toJson(AggregatedHttpResponse res, @Nullable JsonNodeType expectedNodeType) {
    final String content = toString(res);
    final JsonNode node;
    try {
        node = Jackson.readTree(content);
    } catch (JsonParseException e) {
        throw new CentralDogmaException("failed to parse the response JSON", e);
    }

    if (expectedNodeType != null && node.getNodeType() != expectedNodeType) {
        throw new CentralDogmaException(
                "invalid server response; expected: " + expectedNodeType +
                ", actual: " + node.getNodeType() + ", content: " + content);
    }
    return node;
}
 
Example #8
Source File: ContentServiceV1Test.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Test
void editFileWithJsonPatch() throws IOException {
    final WebClient client = dogma.httpClient();
    addFooJson(client);
    final AggregatedHttpResponse res1 = editFooJson(client);
    final String expectedJson =
            '{' +
            "   \"revision\": 3," +
            "   \"pushedAt\": \"${json-unit.ignore}\"" +
            '}';
    final String actualJson = res1.contentUtf8();
    assertThatJson(actualJson).isEqualTo(expectedJson);

    final AggregatedHttpResponse res2 = client.get(CONTENTS_PREFIX + "/foo.json").aggregate().join();
    assertThat(Jackson.readTree(res2.contentUtf8()).get("content").get("a").textValue())
            .isEqualToIgnoringCase("baz");
}
 
Example #9
Source File: AnnotatedServiceRequestConverterTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testDefaultRequestConverter_text() throws Exception {
    final WebClient client = WebClient.of(server.httpUri());

    AggregatedHttpResponse response;

    final byte[] utf8 = "¥".getBytes(StandardCharsets.UTF_8);
    response = client.execute(AggregatedHttpRequest.of(HttpMethod.POST, "/2/default/text",
                                                       MediaType.PLAIN_TEXT_UTF_8, utf8))
                     .aggregate().join();
    assertThat(response.status()).isEqualTo(HttpStatus.OK);
    assertThat(response.content().array()).isEqualTo(utf8);

    final MediaType textPlain = MediaType.create("text", "plain");
    response = client.execute(AggregatedHttpRequest.of(HttpMethod.POST, "/2/default/text",
                                                       textPlain, utf8))
                     .aggregate().join();
    assertThat(response.status()).isEqualTo(HttpStatus.OK);
    // Response is encoded as UTF-8.
    assertThat(response.content().array()).isEqualTo(utf8);
}
 
Example #10
Source File: ContentCompressionTest.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Test
void http() throws Exception {
    final WebClient client =
            WebClient.builder("http://127.0.0.1:" + dogma.serverAddress().getPort())
                     .setHttpHeader(HttpHeaderNames.AUTHORIZATION, "Bearer " + CsrfToken.ANONYMOUS)
                     .setHttpHeader(HttpHeaderNames.ACCEPT_ENCODING, "deflate")
                     .build();

    final String contentPath = HttpApiV1Constants.PROJECTS_PREFIX + '/' + PROJ +
                               HttpApiV1Constants.REPOS + '/' + REPO +
                               "/contents" + PATH;

    final AggregatedHttpResponse compressedResponse = client.get(contentPath).aggregate().join();
    assertThat(compressedResponse.status()).isEqualTo(HttpStatus.OK);

    final HttpData content = compressedResponse.content();
    try (Reader in = new InputStreamReader(new InflaterInputStream(new ByteArrayInputStream(
            content.array(), 0, content.length())), StandardCharsets.UTF_8)) {

        assertThat(CharStreams.toString(in)).contains(CONTENT);
    }
}
 
Example #11
Source File: ArmeriaAutoConfigurationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void testThriftServiceRegistrationBean() throws Exception {
    final HelloService.Iface client = Clients.newClient(newUrl("tbinary+h1c") + "/thrift",
                                                        HelloService.Iface.class);
    assertThat(client.hello("world")).isEqualTo("hello world");

    final WebClient webClient = WebClient.of(newUrl("h1c"));
    final HttpResponse response = webClient.get("/internal/docs/specification.json");

    final AggregatedHttpResponse res = response.aggregate().get();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThatJson(res.contentUtf8()).node("services[2].name").isStringEqualTo(
            "com.linecorp.armeria.spring.test.thrift.main.HelloService");
    assertThatJson(res.contentUtf8())
            .node("services[2].exampleHttpHeaders[0].x-additional-header").isStringEqualTo("headerVal");
    assertThatJson(res.contentUtf8())
            .node("services[0].methods[0].exampleHttpHeaders[0].x-additional-header")
            .isStringEqualTo("headerVal");
}
 
Example #12
Source File: AnnotatedServiceHandlersOrderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void requestConverterOrder() throws Exception {
    final String body = "{\"foo\":\"bar\"}";
    final AggregatedHttpRequest aReq = AggregatedHttpRequest.of(
            HttpMethod.POST, "/1/requestConverterOrder", MediaType.JSON, body);

    final AggregatedHttpResponse aRes = executeRequest(aReq);

    assertThat(aRes.status()).isEqualTo(HttpStatus.OK);
    // Converted from the default converter which is JacksonRequestConverterFunction.
    assertThat(aRes.contentUtf8()).isEqualTo(body);

    // parameter level(+1) -> method level(+1) -> class level(+1) -> service level(+1) -> server level(+1)
    // -> default
    assertThat(requestCounter.get()).isEqualTo(5);
}
 
Example #13
Source File: AnnotatedServiceAnnotationAliasTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void metaAnnotations() {
    final AggregatedHttpResponse msg =
            WebClient.of(rule.httpUri())
                     .execute(RequestHeaders.of(HttpMethod.POST, "/hello",
                                                HttpHeaderNames.CONTENT_TYPE,
                                                MediaType.PLAIN_TEXT_UTF_8,
                                                HttpHeaderNames.ACCEPT, "text/*"),
                              HttpData.ofUtf8("Armeria"))
                     .aggregate().join();
    assertThat(msg.status()).isEqualTo(HttpStatus.CREATED);
    assertThat(msg.contentType()).isEqualTo(MediaType.PLAIN_TEXT_UTF_8);
    assertThat(msg.headers().get(HttpHeaderNames.of("x-foo"))).isEqualTo("foo");
    assertThat(msg.headers().get(HttpHeaderNames.of("x-bar"))).isEqualTo("bar");
    assertThat(msg.contentUtf8())
            .isEqualTo("Hello, Armeria (decorated-1) (decorated-2) (decorated-3)!");
    assertThat(msg.trailers().get(HttpHeaderNames.of("x-baz"))).isEqualTo("baz");
    assertThat(msg.trailers().get(HttpHeaderNames.of("x-qux"))).isEqualTo("qux");
}
 
Example #14
Source File: MergeFileTest.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Test
void exceptionWhenOnlyOptionalFilesAndDoNotExist() {
    final WebClient client = dogma.httpClient();
    addFilesForMergeJson(client);
    final String queryString = "optional_path=/no_exist1.json" + '&' +
                               "optional_path=/no_exist2.json";

    final AggregatedHttpResponse aRes = client.get("/api/v1/projects/myPro/repos/myRepo/merge?" +
                                                   queryString).aggregate().join();
    assertThat(aRes.status()).isEqualTo(HttpStatus.NOT_FOUND);
    final String expectedJson =
            '{' +
            "     \"exception\": \"com.linecorp.centraldogma.common.EntryNotFoundException\"," +
            "     \"message\": \"Entry '/no_exist1.json,/no_exist2.json (revision: 4)' does not exist.\"" +
            '}';
    assertThatJson(aRes.contentUtf8()).isEqualTo(expectedJson);
}
 
Example #15
Source File: ObservableResponseConverterFunctionTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void maybe() {
    final WebClient client = WebClient.of(server.httpUri() + "/maybe");

    AggregatedHttpResponse res;

    res = client.get("/string").aggregate().join();
    assertThat(res.contentType()).isEqualTo(MediaType.PLAIN_TEXT_UTF_8);
    assertThat(res.contentUtf8()).isEqualTo("a");

    res = client.get("/json").aggregate().join();
    assertThat(res.contentType()).isEqualTo(MediaType.JSON_UTF_8);
    assertThatJson(res.contentUtf8()).isStringEqualTo("a");

    res = client.get("/empty").aggregate().join();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThat(res.content().isEmpty()).isTrue();

    res = client.get("/error").aggregate().join();
    assertThat(res.status()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);

    res = client.get("/http-response").aggregate().join();
    assertThat(res.contentType()).isEqualTo(MediaType.PLAIN_TEXT_UTF_8);
    assertThat(res.contentUtf8()).isEqualTo("a");
}
 
Example #16
Source File: RedirectServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void testMisconfiguredPathParams3() throws Exception {
    serverRule2c.start();

    final WebClient client = WebClient.of(serverRule2c.httpUri());
    AggregatedHttpResponse res = client.get("/test1a/qwe/asd/zxc").aggregate().get();
    assertThat(res.status()).isEqualTo(HttpStatus.TEMPORARY_REDIRECT);

    final String newLocation = res.headers().get(HttpHeaderNames.LOCATION);
    assertThat(newLocation).isEqualTo("/new1/null/new1/null/new1/null");

    res = client.get(newLocation).aggregate().get();
    assertThat(res.status()).isEqualTo(HttpStatus.NOT_FOUND);

    serverRule2c.stop();
}
 
Example #17
Source File: HttpServerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ClientAndProtocolProvider.class)
void testStrings_acceptEncodingDeflate(WebClient client) throws Exception {
    final RequestHeaders req = RequestHeaders.of(HttpMethod.GET, "/strings",
                                                 HttpHeaderNames.ACCEPT_ENCODING, "deflate");
    final CompletableFuture<AggregatedHttpResponse> f = client.execute(req).aggregate();

    final AggregatedHttpResponse res = f.get();

    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING)).isEqualTo("deflate");
    assertThat(res.headers().get(HttpHeaderNames.VARY)).isEqualTo("accept-encoding");

    final byte[] decoded;
    try (InflaterInputStream unzipper =
                 new InflaterInputStream(new ByteArrayInputStream(res.content().array()))) {
        decoded = ByteStreams.toByteArray(unzipper);
    }
    assertThat(new String(decoded, StandardCharsets.UTF_8)).isEqualTo("Armeria is awesome!");
}
 
Example #18
Source File: ContentPreviewingClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Unlike {@link #decodedContentPreview()}, the content preview of this test is encoded data because
 * the previewing decorator is inserted before {@link DecodingClient}.
 */
@Test
void contentPreviewIsDecodedInPreviewer() {
    final WebClient client = WebClient.builder(server.httpUri())
                                      .decorator(decodingContentPreviewDecorator())
                                      .decorator(DecodingClient.newDecorator())
                                      .build();
    final RequestHeaders headers = RequestHeaders.of(HttpMethod.POST, "/",
                                                     HttpHeaderNames.CONTENT_TYPE,
                                                     MediaType.PLAIN_TEXT_UTF_8);

    final ClientRequestContext context;
    try (ClientRequestContextCaptor captor = Clients.newContextCaptor()) {
        final AggregatedHttpResponse res = client.execute(headers, "Armeria").aggregate().join();
        assertThat(res.contentUtf8()).isEqualTo("Hello Armeria!");
        assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING)).isEqualTo("gzip");
        context = captor.get();
    }

    final RequestLog requestLog = context.log().whenComplete().join();
    assertThat(requestLog.requestContentPreview()).isEqualTo("Armeria");
    assertThat(requestLog.responseContentPreview()).isEqualTo("Hello Armeria!");
}
 
Example #19
Source File: HttpServerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ClientAndProtocolProvider.class)
void testTimeoutAfterPartialContent(WebClient client) throws Exception {
    serverRequestTimeoutMillis = 1000L;
    final CompletableFuture<AggregatedHttpResponse> f = client.get("/content_delay/2000").aggregate();

    // Because the service has written out the content partially, there's no way for the service
    // to reply with '503 Service Unavailable', so it will just close the stream.

    final Class<? extends Throwable> expectedCauseType =
            client.scheme().sessionProtocol().isMultiplex() ?
            ClosedStreamException.class : ClosedSessionException.class;

    assertThatThrownBy(f::get).isInstanceOf(ExecutionException.class)
                              .hasCauseInstanceOf(expectedCauseType);
}
 
Example #20
Source File: ShiroLoginAndLogoutTest.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private void loginAndLogout(AggregatedHttpResponse loginRes) throws Exception {
    assertThat(loginRes.status()).isEqualTo(HttpStatus.OK);

    // Ensure authorization works.
    final AccessToken accessToken = Jackson.readValue(loginRes.contentUtf8(), AccessToken.class);
    final String sessionId = accessToken.accessToken();

    assertThat(usersMe(client, sessionId).status()).isEqualTo(HttpStatus.OK);

    // Log out.
    assertThat(logout(client, sessionId).status()).isEqualTo(HttpStatus.OK);
    assertThat(usersMe(client, sessionId).status()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
 
Example #21
Source File: ArmeriaReactiveWebServerFactoryTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void shouldReturnNonCompressedResponse_dueToUserAgent() {
    final ArmeriaReactiveWebServerFactory factory = factory();
    final Compression compression = new Compression();
    compression.setEnabled(true);
    compression.setMinResponseSize(DataSize.ofBytes(1));
    compression.setExcludedUserAgents(new String[] { "test-agent/[0-9]+\\.[0-9]+\\.[0-9]+$" });
    factory.setCompression(compression);
    runEchoServer(factory, server -> {
        final AggregatedHttpResponse res = sendPostRequest(httpClient(server));
        validateEchoResponse(res);
        assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING)).isNull();
    });
}
 
Example #22
Source File: HttpClientIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testEscapedPathParam() throws Exception {
    final WebClient client = WebClient.of(server.httpUri());

    final AggregatedHttpResponse response = client.get("/oneparam/foo%2Fbar").aggregate().get();

    assertThat(response.contentUtf8()).isEqualTo("routed");
}
 
Example #23
Source File: HttpServerCorsTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void testCorsForbidden() throws Exception {
    final WebClient client = client();
    final AggregatedHttpResponse response = request(client, HttpMethod.POST, "/cors", "http://example.org",
                                                    "POST");

    assertNull(response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN));
}
 
Example #24
Source File: AnnotatedServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Post
@Path("/a/string-aggregate-response1")
public AggregatedHttpResponse postStringAggregateResponse1(AggregatedHttpRequest request,
                                                           RequestContext ctx) {
    validateContext(ctx);
    return AggregatedHttpResponse.of(ResponseHeaders.of(HttpStatus.OK), request.content());
}
 
Example #25
Source File: HttpClientIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void testHeaderOverridableByClientOption(String path, AsciiString headerName,
                                                        String headerValue) throws Exception {
    final WebClient client = WebClient.builder(server.httpUri())
                                      .setHttpHeader(headerName, headerValue)
                                      .build();

    final AggregatedHttpResponse response = client.get(path).aggregate().get();

    assertThat(response.contentUtf8()).isEqualTo(headerValue);
}
 
Example #26
Source File: RepositoryServiceV1Test.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Test
void removeRepository() {
    final WebClient client = dogma.httpClient();
    createRepository(client,"foo");
    final AggregatedHttpResponse aRes = client.delete(REPOS_PREFIX + "/foo").aggregate().join();
    assertThat(ResponseHeaders.of(aRes.headers()).status()).isEqualTo(HttpStatus.NO_CONTENT);
}
 
Example #27
Source File: MainTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testFavicon() {
    // Download the favicon.
    final AggregatedHttpResponse res = client.get("/favicon.ico").aggregate().join();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThat(res.headers().contentType()).isEqualTo(MediaType.parse("image/x-icon"));
}
 
Example #28
Source File: ServerSentEventsTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void singleEvent() {
    final AggregatedHttpResponse response =
            WebClient.of(rule.httpUri() + "/single").get("/sse").aggregate().join();
    assertThat(response.status()).isEqualTo(HttpStatus.OK);
    assertThat(response.headers().contentType()).isEqualTo(MediaType.EVENT_STREAM);
    assertThat(response.content().toStringUtf8()).isEqualTo("event:add\n\n");
}
 
Example #29
Source File: LocalArmeriaPortHttpsTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpServiceRegistrationBean() throws Exception {
    final HttpResponse response = WebClient.builder(newUrl("https"))
                                           .factory(clientFactory)
                                           .build()
                                           .get("/ok");
    final AggregatedHttpResponse res = response.aggregate().get();
    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThat(res.contentUtf8()).isEqualTo("ok");
}
 
Example #30
Source File: ContentServiceV1Test.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Test
void emptyChangeSet() {
    final WebClient client = dogma.httpClient();
    // Add /foo.json and then remove it, which is essentially a no-op.
    final String body = '{' +
                        "  \"commitMessage\": {" +
                        "    \"summary\": \"do nothing\"," +
                        "    \"detail\": \"\"," +
                        "    \"markup\": \"PLAINTEXT\"" +
                        "  }," +
                        "  \"changes\": [" +
                        "    {" +
                        "      \"path\": \"/foo.json\"," +
                        "      \"type\": \"UPSERT_JSON\"," +
                        "      \"content\": {}" +
                        "    }," +
                        "    {" +
                        "      \"path\": \"/foo.json\"," +
                        "      \"type\": \"REMOVE\"" +
                        "    }" +
                        "  ]" +
                        '}';
    final RequestHeaders headers = RequestHeaders.of(HttpMethod.POST, CONTENTS_PREFIX,
                                                     HttpHeaderNames.CONTENT_TYPE, MediaType.JSON);
    final AggregatedHttpResponse res = client.execute(headers, body).aggregate().join();
    assertThat(ResponseHeaders.of(res.headers()).status()).isEqualTo(HttpStatus.CONFLICT);
    assertThatJson(res.contentUtf8()).isEqualTo(
            '{' +
            "  \"exception\": \"" + RedundantChangeException.class.getName() + "\"," +
            "  \"message\": \"${json-unit.ignore}\"" +
            '}');
}