Always buffer response body in RestTestClient

Prior to this commit, `RestTestClient` tests could only perform
expectations on the response without consuming the body. In this case,
the client could leak HTTP connections with the underlying HTTP library
because the response was not entirely read.

This commit ensures that the response is always fully drained before
performing expectations. The client is configured to buffer the response
content, so further body expectations are always possible.

Fixes gh-35784
This commit is contained in:
Brian Clozel
2025-11-27 15:37:16 +01:00
parent 7a19cbb452
commit 08e6d762d2
3 changed files with 116 additions and 3 deletions
@@ -92,6 +92,8 @@ public class ExchangeResult {
this.uriTemplate = uriTemplate;
this.requestBody = requestBody;
this.converterDelegate = converter;
// buffer response body in all cases, or connections might leak if expectations do not read the response
bufferResponseBody();
}
ExchangeResult(ExchangeResult result) {
@@ -241,6 +243,15 @@ public class ExchangeResult {
formatBody(getResponseHeaders().getContentType(), getResponseBodyContent()) +"\n";
}
private void bufferResponseBody() {
try {
StreamUtils.drain(this.clientResponse.getBody());
}
catch (IOException ex) {
throw new IllegalStateException("Failed to get response content: " + ex);
}
}
private String formatStatus(HttpStatusCode statusCode) {
String result = statusCode.toString();
if (statusCode instanceof HttpStatus status) {