Browse Source

Polishing in client tests

pull/34223/head
rstoyanchev 1 year ago
parent
commit
b9efa91ecc
  1. 19
      spring-web/src/test/java/org/springframework/http/client/AbstractMockWebServerTests.java
  2. 36
      spring-web/src/test/java/org/springframework/http/client/BufferingClientHttpRequestFactoryTests.java
  3. 27
      spring-web/src/test/java/org/springframework/http/client/InterceptingClientHttpRequestFactoryTests.java
  4. 12
      spring-web/src/test/java/org/springframework/http/client/JdkClientHttpRequestFactoryTests.java

19
spring-web/src/test/java/org/springframework/http/client/AbstractMockWebServerTests.java

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2024 the original author or authors. * Copyright 2002-2025 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,8 +16,6 @@
package org.springframework.http.client; package org.springframework.http.client;
import java.util.Collections;
import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
@ -25,7 +23,6 @@ import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -41,8 +38,6 @@ public abstract class AbstractMockWebServerTests {
protected String baseUrl; protected String baseUrl;
protected static final MediaType textContentType =
new MediaType("text", "plain", Collections.singletonMap("charset", "UTF-8"));
@BeforeEach @BeforeEach
void setUp() throws Exception { void setUp() throws Exception {
@ -58,13 +53,14 @@ public abstract class AbstractMockWebServerTests {
this.server.shutdown(); this.server.shutdown();
} }
protected class TestDispatcher extends Dispatcher { protected class TestDispatcher extends Dispatcher {
@Override @Override
public MockResponse dispatch(RecordedRequest request) { public MockResponse dispatch(RecordedRequest request) {
try { try {
if (request.getPath().equals("/echo")) { if (request.getPath().equals("/echo")) {
assertThat(request.getHeader("Host")) assertThat(request.getHeader("Host")).contains("localhost:" + port);
.contains("localhost:" + port);
MockResponse response = new MockResponse() MockResponse response = new MockResponse()
.setHeaders(request.getHeaders()) .setHeaders(request.getHeaders())
.setHeader("Content-Length", request.getBody().size()) .setHeader("Content-Length", request.getBody().size())
@ -80,8 +76,7 @@ public abstract class AbstractMockWebServerTests {
return new MockResponse().setResponseCode(404); return new MockResponse().setResponseCode(404);
} }
else if (request.getPath().equals("/status/299")) { else if (request.getPath().equals("/status/299")) {
assertThat(request.getHeader("Expect")) assertThat(request.getHeader("Expect")).contains("299");
.contains("299");
return new MockResponse().setResponseCode(299); return new MockResponse().setResponseCode(299);
} }
else if(request.getPath().startsWith("/params")) { else if(request.getPath().startsWith("/params")) {
@ -112,8 +107,8 @@ public abstract class AbstractMockWebServerTests {
} }
return new MockResponse().setResponseCode(404); return new MockResponse().setResponseCode(404);
} }
catch (Throwable exc) { catch (Throwable ex) {
return new MockResponse().setResponseCode(500).setBody(exc.toString()); return new MockResponse().setResponseCode(500).setBody(ex.toString());
} }
} }
} }

36
spring-web/src/test/java/org/springframework/http/client/BufferingClientHttpRequestFactoryTests.java

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2024 the original author or authors. * Copyright 2002-2025 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,7 +18,6 @@ package org.springframework.http.client;
import java.net.URI; import java.net.URI;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -37,30 +36,29 @@ class BufferingClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryT
@Test @Test
void repeatableRead() throws Exception { void repeatableRead() throws Exception {
ClientHttpRequest request = factory.createRequest(URI.create(baseUrl + "/echo"), HttpMethod.PUT); ClientHttpRequest request = factory.createRequest(URI.create(baseUrl + "/echo"), HttpMethod.PUT);
assertThat(request.getMethod()).as("Invalid HTTP method").isEqualTo(HttpMethod.PUT); assertThat(request.getMethod()).isEqualTo(HttpMethod.PUT);
String headerName = "MyHeader";
String headerValue1 = "value1"; String header = "MyHeader";
request.getHeaders().add(headerName, headerValue1); request.getHeaders().add(header, "value1");
String headerValue2 = "value2"; request.getHeaders().add(header, "value2");
request.getHeaders().add(headerName, headerValue2);
byte[] body = "Hello World".getBytes(StandardCharsets.UTF_8); byte[] body = "Hello World".getBytes(StandardCharsets.UTF_8);
request.getHeaders().setContentLength(body.length);
FileCopyUtils.copy(body, request.getBody()); FileCopyUtils.copy(body, request.getBody());
try (ClientHttpResponse response = request.execute()) { request.getHeaders().setContentLength(body.length);
assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK);
assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK);
assertThat(response.getHeaders().containsHeader(headerName)).as("Header not found").isTrue(); try (ClientHttpResponse response = request.execute()) {
assertThat(response.getHeaders().containsHeader(headerName)).as("Header not found").isTrue(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getHeaders().get(headerName)).as("Header value not found").isEqualTo(Arrays.asList(headerValue1, headerValue2)); assertThat(response.getHeaders().get(header)).containsExactly("value1", "value2");
assertThat(response.getHeaders().get(headerName)).as("Header value not found").isEqualTo(Arrays.asList(headerValue1, headerValue2)); assertThat(response.getHeaders().get(header)).containsExactly("value1", "value2");
byte[] result = FileCopyUtils.copyToByteArray(response.getBody()); byte[] result = FileCopyUtils.copyToByteArray(response.getBody());
assertThat(Arrays.equals(body, result)).as("Invalid body").isTrue(); assertThat(result).isEqualTo(body);
FileCopyUtils.copyToByteArray(response.getBody());
assertThat(Arrays.equals(body, result)).as("Invalid body").isTrue(); result = FileCopyUtils.copyToByteArray(response.getBody());
assertThat(result).isEqualTo(body);
} }
} }

27
spring-web/src/test/java/org/springframework/http/client/InterceptingClientHttpRequestFactoryTests.java

@ -56,7 +56,7 @@ class InterceptingClientHttpRequestFactoryTests {
} }
@Test @Test
void shouldInvokeInterceptors() throws Exception { void invokeInterceptors() throws Exception {
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new NoOpInterceptor()); interceptors.add(new NoOpInterceptor());
interceptors.add(new NoOpInterceptor()); interceptors.add(new NoOpInterceptor());
@ -74,7 +74,7 @@ class InterceptingClientHttpRequestFactoryTests {
} }
@Test @Test
void shouldSkipIntercetor() throws Exception { void skipInterceptor() throws Exception {
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add((request, body, execution) -> responseMock); interceptors.add((request, body, execution) -> responseMock);
interceptors.add(new NoOpInterceptor()); interceptors.add(new NoOpInterceptor());
@ -89,7 +89,7 @@ class InterceptingClientHttpRequestFactoryTests {
} }
@Test @Test
void interceptorShouldUpdateRequestHeader() throws Exception { void updateRequestHeader() throws Exception {
final String headerName = "Foo"; final String headerName = "Foo";
final String headerValue = "Bar"; final String headerValue = "Bar";
final String otherValue = "Baz"; final String otherValue = "Baz";
@ -115,7 +115,7 @@ class InterceptingClientHttpRequestFactoryTests {
} }
@Test @Test
void interceptorShouldUpdateRequestAttribute() throws Exception { void updateRequestAttribute() throws Exception {
final String attrName = "Foo"; final String attrName = "Foo";
final String attrValue = "Bar"; final String attrValue = "Bar";
@ -137,7 +137,7 @@ class InterceptingClientHttpRequestFactoryTests {
} }
@Test @Test
void interceptorShouldUpdateRequestURI() throws Exception { void updateRequestURI() throws Exception {
final URI changedUri = URI.create("https://example.com/2"); final URI changedUri = URI.create("https://example.com/2");
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> execution.execute(new HttpRequestWrapper(request) { ClientHttpRequestInterceptor interceptor = (request, body, execution) -> execution.execute(new HttpRequestWrapper(request) {
@ -161,7 +161,7 @@ class InterceptingClientHttpRequestFactoryTests {
} }
@Test @Test
void interceptorShouldUpdateRequestMethod() throws Exception { void updateRequestMethod() throws Exception {
final HttpMethod changedMethod = HttpMethod.POST; final HttpMethod changedMethod = HttpMethod.POST;
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> execution.execute(new HttpRequestWrapper(request) { ClientHttpRequestInterceptor interceptor = (request, body, execution) -> execution.execute(new HttpRequestWrapper(request) {
@ -185,7 +185,7 @@ class InterceptingClientHttpRequestFactoryTests {
} }
@Test @Test
void interceptorShouldUpdateRequestBody() throws Exception { void updateRequestBody() throws Exception {
final byte[] changedBody = "Foo".getBytes(); final byte[] changedBody = "Foo".getBytes();
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> execution.execute(request, changedBody); ClientHttpRequestInterceptor interceptor = (request, body, execution) -> execution.execute(request, changedBody);
requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor)); requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
@ -197,7 +197,7 @@ class InterceptingClientHttpRequestFactoryTests {
} }
@Test @Test
void interceptorShouldAlwaysExecuteNextInterceptor() throws Exception { void multipleExecutions() throws Exception {
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new MultipleExecutionInterceptor()); interceptors.add(new MultipleExecutionInterceptor());
interceptors.add(new NoOpInterceptor()); interceptors.add(new NoOpInterceptor());
@ -217,18 +217,21 @@ class InterceptingClientHttpRequestFactoryTests {
private int invocationCount = 0; private int invocationCount = 0;
@Override @Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) public ClientHttpResponse intercept(
throws IOException { HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
invocationCount++; invocationCount++;
return execution.execute(request, body); return execution.execute(request, body);
} }
} }
private static class MultipleExecutionInterceptor implements ClientHttpRequestInterceptor { private static class MultipleExecutionInterceptor implements ClientHttpRequestInterceptor {
@Override @Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) public ClientHttpResponse intercept(
throws IOException { HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
// execute another request first // execute another request first
execution.execute(new MockClientHttpRequest(), body); execution.execute(new MockClientHttpRequest(), body);
return execution.execute(request, body); return execution.execute(request, body);

12
spring-web/src/test/java/org/springframework/http/client/JdkClientHttpRequestFactoryTests.java

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2024 the original author or authors. * Copyright 2002-2025 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -39,6 +39,7 @@ class JdkClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryTests {
private static @Nullable String originalPropertyValue; private static @Nullable String originalPropertyValue;
@BeforeAll @BeforeAll
static void setProperty() { static void setProperty() {
originalPropertyValue = System.getProperty("jdk.httpclient.allowRestrictedHeaders"); originalPropertyValue = System.getProperty("jdk.httpclient.allowRestrictedHeaders");
@ -55,6 +56,7 @@ class JdkClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryTests {
} }
} }
@Override @Override
protected ClientHttpRequestFactory createRequestFactory() { protected ClientHttpRequestFactory createRequestFactory() {
return new JdkClientHttpRequestFactory(); return new JdkClientHttpRequestFactory();
@ -69,7 +71,8 @@ class JdkClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryTests {
@Test @Test
void customizeDisallowedHeaders() throws IOException { void customizeDisallowedHeaders() throws IOException {
ClientHttpRequest request = this.factory.createRequest(URI.create(this.baseUrl + "/status/299"), HttpMethod.PUT); URI uri = URI.create(this.baseUrl + "/status/299");
ClientHttpRequest request = this.factory.createRequest(uri, HttpMethod.PUT);
request.getHeaders().set("Expect", "299"); request.getHeaders().set("Expect", "299");
try (ClientHttpResponse response = request.execute()) { try (ClientHttpResponse response = request.execute()) {
@ -79,8 +82,9 @@ class JdkClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryTests {
@Test // gh-31451 @Test // gh-31451
public void contentLength0() throws IOException { public void contentLength0() throws IOException {
BufferingClientHttpRequestFactory bufferingFactory = new BufferingClientHttpRequestFactory(this.factory); URI uri = URI.create(this.baseUrl + "/methods/get");
ClientHttpRequest request = bufferingFactory.createRequest(URI.create(this.baseUrl + "/methods/get"), HttpMethod.GET); ClientHttpRequest request =
new BufferingClientHttpRequestFactory(this.factory).createRequest(uri, HttpMethod.GET);
try (ClientHttpResponse response = request.execute()) { try (ClientHttpResponse response = request.execute()) {
assertThat(response.getStatusCode()).as("Invalid response status").isEqualTo(HttpStatus.OK); assertThat(response.getStatusCode()).as("Invalid response status").isEqualTo(HttpStatus.OK);

Loading…
Cancel
Save