JAVA-22043 | Fixing httpclient live test (#14352)

* JAVA-22043 | fixing httpclient live test

* JAVA-22043 | fixing httpclient live test using lambda expression for execution
This commit is contained in:
Gaetano Piazzolla 2023-07-10 20:15:49 +02:00 committed by GitHub
parent fa1beff465
commit 82532d661d
6 changed files with 110 additions and 113 deletions

View File

@ -7,7 +7,6 @@ import static org.mockserver.model.HttpResponse.response;
import java.io.IOException; import java.io.IOException;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.net.URISyntaxException;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
@ -18,22 +17,19 @@ import org.mockserver.integration.ClientAndServer;
public class GetRequestMockServer { public class GetRequestMockServer {
public static ClientAndServer mockServer; public static ClientAndServer mockServer;
public static String serviceOneUrl;
public static String serviceTwoUrl;
public static int serverPort; public static int serverPort;
public static final String SERVER_ADDRESS = "127.0.0.1"; public static final String SERVER_ADDRESS = "127.0.0.1";
public static final String PATH_ONE = "/test1";
public static final String PATH_TWO = "/test2"; public static final String SECURITY_PATH = "/spring-security-rest-basic-auth/api/foos/1";
public static final String METHOD = "GET";
public static final String UPLOAD_PATH = "/spring-mvc-java/stub/multipart";
@BeforeAll @BeforeAll
static void startServer() throws IOException { static void startServer() throws IOException {
serverPort = getFreePort(); serverPort = getFreePort();
System.out.println("Free port "+serverPort); System.out.println("Free port " + serverPort);
serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
mockServer = startClientAndServer(serverPort); mockServer = startClientAndServer(serverPort);
mockGetRequest(); mockGetRequest();
} }
@ -44,33 +40,36 @@ public class GetRequestMockServer {
} }
private static void mockGetRequest() { private static void mockGetRequest() {
new MockServerClient(SERVER_ADDRESS, serverPort)
.when( MockServerClient client = new MockServerClient(SERVER_ADDRESS, serverPort);
request()
.withPath(PATH_ONE) client.when(
.withMethod(METHOD), request()
exactly(5) .withPath(SECURITY_PATH)
) .withMethod("GET"),
.respond( exactly(1)
response() )
.withStatusCode(HttpStatus.SC_OK) .respond(
.withBody("{\"status\":\"ok\"}") response()
); .withStatusCode(HttpStatus.SC_OK)
new MockServerClient(SERVER_ADDRESS, serverPort) .withBody("{\"status\":\"ok\"}")
.when( );
request()
.withPath(PATH_TWO) client.when(
.withMethod(METHOD), request()
exactly(1) .withPath(UPLOAD_PATH)
) .withMethod("POST"),
.respond( exactly(4)
response() )
.withStatusCode(HttpStatus.SC_OK) .respond(
.withBody("{\"status\":\"ok\"}") response()
); .withStatusCode(HttpStatus.SC_OK)
.withBody("{\"status\":\"ok\"}")
.withHeader("Content-Type", "multipart/form-data")
);
} }
private static int getFreePort () throws IOException { private static int getFreePort() throws IOException {
try (ServerSocket serverSocket = new ServerSocket(0)) { try (ServerSocket serverSocket = new ServerSocket(0)) {
return serverSocket.getLocalPort(); return serverSocket.getLocalPort();
} }

View File

@ -19,7 +19,7 @@ class HttpClientCancelRequestLiveTest {
void whenRequestIsCanceled_thenCorrect() throws IOException { void whenRequestIsCanceled_thenCorrect() throws IOException {
HttpGet request = new HttpGet(SAMPLE_URL); HttpGet request = new HttpGet(SAMPLE_URL);
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
httpClient.execute(request, response -> { httpClient.execute(request, response -> {
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
@ -28,6 +28,12 @@ class HttpClientCancelRequestLiveTest {
System.out.println("Response content length: " + entity.getContentLength()); System.out.println("Response content length: " + entity.getContentLength());
} }
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
if (entity != null) {
// Closes this stream and releases any system resources
entity.close();
}
// Do not feel like reading the response body // Do not feel like reading the response body
// Call abort on the request object // Call abort on the request object
request.abort(); request.abort();

View File

@ -4,6 +4,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.hc.core5.http.ParseException;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -13,7 +14,6 @@ import org.apache.hc.client5.http.entity.mime.HttpMultipartMode;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.entity.mime.StringBody; import org.apache.hc.client5.http.entity.mime.StringBody;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.ContentType;
@ -28,9 +28,8 @@ import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.URL; import java.net.URL;
import com.baeldung.httpclient.handler.CustomHttpClientResponseHandler;
class HttpClientMultipartLiveTest { class HttpClientMultipartLiveTest extends GetRequestMockServer {
// No longer available // No longer available
// private static final String SERVER = "http://echo.200please.com"; // private static final String SERVER = "http://echo.200please.com";
@ -45,13 +44,15 @@ class HttpClientMultipartLiveTest {
@BeforeEach @BeforeEach
public void before() { public void before() {
post = new HttpPost(SERVER); post = new HttpPost(SERVER);
String URL = "http://localhost:"+serverPort+"/spring-mvc-java/stub/multipart";
post = new HttpPost(URL);
} }
@Test @Test
void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException { void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
final URL url = Thread.currentThread() final URL url = Thread.currentThread()
.getContextClassLoader() .getContextClassLoader()
.getResource("uploads/" + TEXTFILENAME); .getResource("uploads/" + TEXTFILENAME);
final File file = new File(url.getPath()); final File file = new File(url.getPath());
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
@ -66,27 +67,28 @@ class HttpClientMultipartLiveTest {
final HttpEntity entity = builder.build(); final HttpEntity entity = builder.build();
post.setEntity(entity); post.setEntity(entity);
try(CloseableHttpClient client = HttpClientBuilder.create() try (CloseableHttpClient client = HttpClientBuilder.create()
.build(); .build()) {
CloseableHttpResponse response = (CloseableHttpResponse) client client.execute(post, response -> {
.execute(post, new CustomHttpClientResponseHandler())){ final int statusCode = response.getCode();
final int statusCode = response.getCode(); final String responseString = getContent(response.getEntity());
final String responseString = getContent(response.getEntity()); final String contentTypeInHeader = getContentTypeHeader();
final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); assertThat(statusCode, equalTo(HttpStatus.SC_OK));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); assertTrue(contentTypeInHeader.contains("multipart/form-data"));
System.out.println(responseString); System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader); System.out.println("POST Content Type: " + contentTypeInHeader);
return response;
});
} }
} }
@Test @Test
void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException { void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException {
final URL url = Thread.currentThread() final URL url = Thread.currentThread()
.getContextClassLoader() .getContextClassLoader()
.getResource("uploads/" + TEXTFILENAME); .getResource("uploads/" + TEXTFILENAME);
final File file = new File(url.getPath()); final File file = new File(url.getPath());
final String message = "This is a multipart post"; final String message = "This is a multipart post";
final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
@ -96,30 +98,31 @@ class HttpClientMultipartLiveTest {
final HttpEntity entity = builder.build(); final HttpEntity entity = builder.build();
post.setEntity(entity); post.setEntity(entity);
try(CloseableHttpClient client = HttpClientBuilder.create() try (CloseableHttpClient client = HttpClientBuilder.create()
.build(); .build()) {
CloseableHttpResponse response = (CloseableHttpResponse) client client.execute(post, response -> {
.execute(post, new CustomHttpClientResponseHandler())){
final int statusCode = response.getCode(); final int statusCode = response.getCode();
final String responseString = getContent(response.getEntity()); final String responseString = getContent(response.getEntity());
final String contentTypeInHeader = getContentTypeHeader(); final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); assertThat(statusCode, equalTo(HttpStatus.SC_OK));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); assertTrue(contentTypeInHeader.contains("multipart/form-data"));
System.out.println(responseString); System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader); System.out.println("POST Content Type: " + contentTypeInHeader);
return response;
});
} }
} }
@Test @Test
void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException {
final URL url = Thread.currentThread() final URL url = Thread.currentThread()
.getContextClassLoader() .getContextClassLoader()
.getResource("uploads/" + ZIPFILENAME); .getResource("uploads/" + ZIPFILENAME);
final URL url2 = Thread.currentThread() final URL url2 = Thread.currentThread()
.getContextClassLoader() .getContextClassLoader()
.getResource("uploads/" + IMAGEFILENAME); .getResource("uploads/" + IMAGEFILENAME);
final InputStream inputStream = new FileInputStream(url.getPath()); final InputStream inputStream = new FileInputStream(url.getPath());
final File file = new File(url2.getPath()); final File file = new File(url2.getPath());
final String message = "This is a multipart post"; final String message = "This is a multipart post";
@ -131,25 +134,25 @@ class HttpClientMultipartLiveTest {
final HttpEntity entity = builder.build(); final HttpEntity entity = builder.build();
post.setEntity(entity); post.setEntity(entity);
try(CloseableHttpClient client = HttpClientBuilder.create() try (CloseableHttpClient client = HttpClientBuilder.create()
.build(); .build()) {
CloseableHttpResponse response = (CloseableHttpResponse) client client.execute(post, response -> {
.execute(post, new CustomHttpClientResponseHandler())){ final int statusCode = response.getCode();
final String responseString = getContent(response.getEntity());
final int statusCode = response.getCode(); final String contentTypeInHeader = getContentTypeHeader();
final String responseString = getContent(response.getEntity()); assertThat(statusCode, equalTo(HttpStatus.SC_OK));
final String contentTypeInHeader = getContentTypeHeader(); assertTrue(contentTypeInHeader.contains("multipart/form-data;"));
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); System.out.println(responseString);
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); System.out.println("POST Content Type: " + contentTypeInHeader);
System.out.println(responseString); inputStream.close();
System.out.println("POST Content Type: " + contentTypeInHeader); return response;
inputStream.close(); });
} }
} }
@Test @Test
void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException, ParseException {
final String message = "This is a multipart post"; final String message = "This is a multipart post";
final byte[] bytes = "binary code".getBytes(); final byte[] bytes = "binary code".getBytes();
final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
@ -159,21 +162,20 @@ class HttpClientMultipartLiveTest {
final HttpEntity entity = builder.build(); final HttpEntity entity = builder.build();
post.setEntity(entity); post.setEntity(entity);
try(CloseableHttpClient client = HttpClientBuilder.create() try (CloseableHttpClient httpClient = HttpClientBuilder.create()
.build(); .build()) {
CloseableHttpResponse response = (CloseableHttpResponse) client httpClient.execute(post, response -> {
.execute(post, new CustomHttpClientResponseHandler())){ final int statusCode = response.getCode();
final String responseString = getContent(response.getEntity());
final int statusCode = response.getCode(); final String contentTypeInHeader = getContentTypeHeader();
final String responseString = getContent(response.getEntity()); assertThat(statusCode, equalTo(HttpStatus.SC_OK));
final String contentTypeInHeader = getContentTypeHeader(); assertTrue(contentTypeInHeader.contains("multipart/form-data;"));
assertThat(statusCode, equalTo(HttpStatus.SC_OK)); System.out.println(responseString);
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); System.out.println("POST Content Type: " + contentTypeInHeader);
System.out.println(responseString); return response;
System.out.println("POST Content Type: " + contentTypeInHeader); });
} }
} }
// UTIL // UTIL
@ -184,15 +186,15 @@ class HttpClientMultipartLiveTest {
StringBuilder content = new StringBuilder(); StringBuilder content = new StringBuilder();
while ((body = rd.readLine()) != null) { while ((body = rd.readLine()) != null) {
content.append(body) content.append(body)
.append("\n"); .append("\n");
} }
return content.toString() return content.toString()
.trim(); .trim();
} }
private String getContentTypeHeader() { private String getContentTypeHeader() {
return post.getEntity() return post.getEntity()
.getContentType(); .getContentType();
} }
} }

View File

@ -43,7 +43,7 @@ public class HttpClientLiveTest {
@Test(expected = ConnectTimeoutException.class) @Test(expected = ConnectTimeoutException.class)
public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException { public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException {
final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).setSocketTimeout(20).build(); final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5).setConnectTimeout(5).setSocketTimeout(2).build();
final HttpGet request = new HttpGet(SAMPLE_URL); final HttpGet request = new HttpGet(SAMPLE_URL);
request.setConfig(requestConfig); request.setConfig(requestConfig);
response = instance.execute(request); response = instance.execute(request);

View File

@ -1,5 +1,6 @@
package com.baeldung.httpclient.base; package com.baeldung.httpclient.base;
import com.baeldung.httpclient.GetRequestMockServer;
import com.baeldung.httpclient.ResponseUtil; import com.baeldung.httpclient.ResponseUtil;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
@ -9,14 +10,14 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.IOException; import java.io.IOException;
/* /*
* NOTE : Need module spring-security-rest-basic-auth to be running * NOTE : Need module spring-security-rest-basic-auth to be running
*/ */
public class HttpClientSandboxLiveTest { public class HttpClientSandboxLiveTest extends GetRequestMockServer {
@Test @Test
public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException { public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
@ -26,7 +27,7 @@ public class HttpClientSandboxLiveTest {
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build(); final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
final HttpGet httpGet = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1"); final HttpGet httpGet = new HttpGet("http://localhost:" + serverPort + "/spring-security-rest-basic-auth/api/foos/1");
final CloseableHttpResponse response = client.execute(httpGet); final CloseableHttpResponse response = client.execute(httpGet);
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());

View File

@ -1,11 +0,0 @@
package com.baeldung.httpclient.handler;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
public class CustomHttpClientResponseHandler implements HttpClientResponseHandler<ClassicHttpResponse> {
@Override
public ClassicHttpResponse handleResponse(ClassicHttpResponse response) {
return response;
}
}