You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hc.apache.org by ol...@apache.org on 2021/05/23 15:59:57 UTC
[httpcomponents-core] 01/01: Updated test cases with exception
asserts
This is an automated email from the ASF dual-hosted git repository.
olegk pushed a commit to branch devel
in repository https://gitbox.apache.org/repos/asf/httpcomponents-core.git
commit 03e197a1301ce085748a0b24d461aee7a3c5efc6
Author: Oleg Kalnichevski <ol...@apache.org>
AuthorDate: Sun May 23 17:52:51 2021 +0200
Updated test cases with exception asserts
---
.../hc/core5/http2/hpack/TestHPackCoding.java | 9 +-
.../http2/impl/TestDefaultH2RequestConverter.java | 139 ++++++---------------
.../http2/impl/TestDefaultH2ResponseConverter.java | 67 +++-------
.../core5/http2/impl/io/TestFrameInOutBuffers.java | 16 +--
.../http2/impl/nio/TestFrameInOutBuffers.java | 22 ++--
.../core5/reactive/TestReactiveDataConsumer.java | 14 +--
.../testing/classic/ClassicTLSIntegrationTest.java | 61 ++++-----
.../testing/nio/H2ProtocolNegotiationTest.java | 1 -
.../hc/core5/concurrent/TestBasicFuture.java | 15 ++-
.../impl/TestDefaultConnectionReuseStrategy.java | 5 +-
.../impl/TestDefaultContentLengthStrategy.java | 20 +--
.../hc/core5/http/impl/io/TestChunkCoding.java | 43 +++----
.../impl/io/TestDefaultBHttpClientConnection.java | 10 +-
.../impl/io/TestDefaultBHttpServerConnection.java | 10 +-
.../hc/core5/http/impl/io/TestRequestParser.java | 5 +-
.../hc/core5/http/impl/io/TestResponseParser.java | 5 +-
.../http/impl/io/TestSessionInOutBuffers.java | 10 +-
.../hc/core5/http/impl/nio/TestChunkDecoder.java | 63 ++++++----
.../http/impl/nio/TestLengthDelimitedDecoder.java | 10 +-
.../http/impl/nio/TestSessionInOutBuffers.java | 10 +-
.../core5/http/io/entity/TestByteArrayEntity.java | 20 +--
.../hc/core5/http/io/entity/TestEntityUtils.java | 15 ++-
.../http/io/entity/TestInputStreamEntity.java | 10 +-
.../hc/core5/http/message/TestBasicMessages.java | 9 +-
.../nio/entity/TestDigestingEntityProducer.java | 2 +-
.../http/protocol/TestRequestHandlerRegistry.java | 5 +-
.../http/protocol/TestStandardInterceptors.java | 17 +--
.../core5/http/protocol/TestUriPatternMatcher.java | 15 ++-
.../protocol/TestUriPatternOrderedMatcher.java | 15 ++-
.../core5/http/protocol/TestUriRegexMatcher.java | 15 ++-
.../hc/core5/http/ssl/TestTlsVersionParser.java | 26 ++--
.../org/apache/hc/core5/pool/TestLaxConnPool.java | 10 +-
.../org/apache/hc/core5/pool/TestPoolEntry.java | 10 +-
.../apache/hc/core5/pool/TestStrictConnPool.java | 10 +-
.../org/apache/hc/core5/reactor/IOWorkersTest.java | 6 +-
.../apache/hc/core5/ssl/TestSSLContextBuilder.java | 106 +++++++---------
.../java/org/apache/hc/core5/util/TestArgs.java | 126 +++++++++++--------
.../java/org/apache/hc/core5/util/TestAsserts.java | 36 +++---
.../org/apache/hc/core5/util/TestTimeValue.java | 5 +-
.../java/org/apache/hc/core5/util/TestTimeout.java | 5 +-
40 files changed, 499 insertions(+), 499 deletions(-)
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/hpack/TestHPackCoding.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/hpack/TestHPackCoding.java
index 0eac03f..85798e6 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/hpack/TestHPackCoding.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/hpack/TestHPackCoding.java
@@ -170,14 +170,14 @@ public class TestHPackCoding {
Assert.assertEquals(4, srcRO.remaining());
}
- @Test(expected = HPackException.class)
+ @Test
public void testPlainStringDecodingTruncated() throws Exception {
final ByteBuffer src = createByteBuffer(
0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x6b, 0x65);
final ByteArrayBuffer buffer = new ByteArrayBuffer(16);
- HPackDecoder.decodePlainString(buffer, src);
+ Assert.assertThrows(HPackException.class, () -> HPackDecoder.decodePlainString(buffer, src));
}
@Test
@@ -1039,7 +1039,7 @@ public class TestHPackCoding {
Assert.assertEquals(0, inboundTable2.dynamicLength());
}
- @Test(expected = HeaderListConstraintException.class)
+ @Test
public void testHeaderSizeLimit() throws Exception {
final HPackEncoder encoder = new HPackEncoder(StandardCharsets.US_ASCII);
@@ -1060,7 +1060,8 @@ public class TestHPackCoding {
MatcherAssert.assertThat(decoder.decodeHeaders(wrap(buf)).size(), CoreMatchers.equalTo(2));
decoder.setMaxListSize(200);
- decoder.decodeHeaders(wrap(buf));
+ Assert.assertThrows(HeaderListConstraintException.class, () ->
+ decoder.decodeHeaders(wrap(buf)));
}
}
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/TestDefaultH2RequestConverter.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/TestDefaultH2RequestConverter.java
index 17f6251..9be504e 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/TestDefaultH2RequestConverter.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/TestDefaultH2RequestConverter.java
@@ -38,15 +38,10 @@ import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicHttpRequest;
import org.apache.hc.core5.net.URIAuthority;
import org.junit.Assert;
-import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
public class TestDefaultH2RequestConverter {
- @Rule
- public final ExpectedException thrown = ExpectedException.none();
-
@Test
public void testConvertFromFieldsBasic() throws Exception {
@@ -72,10 +67,6 @@ public class TestDefaultH2RequestConverter {
@Test
public void testConvertFromFieldsUpperCaseHeaderName() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Header name ':Path' is invalid (header name contains uppercase characters)");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":method", "GET"),
new BasicHeader(":scheme", "http"),
@@ -84,15 +75,13 @@ public class TestDefaultH2RequestConverter {
new BasicHeader("custom", "value"));
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(headers);
+
+ Assert.assertThrows("Header name ':Path' is invalid (header name contains uppercase characters)",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsConnectionHeader() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Header 'connection: keep-alive' is illegal for HTTP/2 messages");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":method", "GET"),
new BasicHeader(":scheme", "http"),
@@ -101,15 +90,12 @@ public class TestDefaultH2RequestConverter {
new BasicHeader("connection", "keep-alive"));
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(headers);
+ Assert.assertThrows("Header 'connection: keep-alive' is illegal for HTTP/2 messages",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsPseudoHeaderSequence() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Invalid sequence of headers (pseudo-headers must precede message headers)");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":method", "GET"),
new BasicHeader(":scheme", "http"),
@@ -118,15 +104,12 @@ public class TestDefaultH2RequestConverter {
new BasicHeader(":path", "/"));
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(headers);
+ Assert.assertThrows("Invalid sequence of headers (pseudo-headers must precede message headers)",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsMissingMethod() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Mandatory request header ':method' not found");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":scheme", "http"),
new BasicHeader(":authority", "www.example.com"),
@@ -134,15 +117,12 @@ public class TestDefaultH2RequestConverter {
new BasicHeader("custom", "value"));
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(headers);
+ Assert.assertThrows("Mandatory request header ':method' not found",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsMissingScheme() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Mandatory request header ':scheme' not found");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":method", "GET"),
new BasicHeader(":authority", "www.example.com"),
@@ -150,15 +130,12 @@ public class TestDefaultH2RequestConverter {
new BasicHeader("custom", "value"));
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(headers);
+ Assert.assertThrows("Mandatory request header ':scheme' not found",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsMissingPath() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Mandatory request header ':path' not found");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":method", "GET"),
new BasicHeader(":scheme", "http"),
@@ -166,15 +143,12 @@ public class TestDefaultH2RequestConverter {
new BasicHeader("custom", "value"));
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(headers);
+ Assert.assertThrows("Mandatory request header ':path' not found",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsUnknownPseudoHeader() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Unsupported request header ':custom'");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":method", "GET"),
new BasicHeader(":scheme", "http"),
@@ -183,15 +157,12 @@ public class TestDefaultH2RequestConverter {
new BasicHeader(":custom", "value"));
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(headers);
+ Assert.assertThrows("Unsupported request header ':custom'",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsMultipleMethod() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Multiple ':method' request headers are illegal");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":method", "GET"),
new BasicHeader(":method", "GET"),
@@ -201,15 +172,12 @@ public class TestDefaultH2RequestConverter {
new BasicHeader("custom", "value"));
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(headers);
+ Assert.assertThrows("Multiple ':method' request headers are illegal",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsMultipleScheme() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Multiple ':scheme' request headers are illegal");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":method", "GET"),
new BasicHeader(":scheme", "http"),
@@ -219,15 +187,12 @@ public class TestDefaultH2RequestConverter {
new BasicHeader("custom", "value"));
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(headers);
+ Assert.assertThrows("Multiple ':scheme' request headers are illegal",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsMultiplePath() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Multiple ':path' request headers are illegal");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":method", "GET"),
new BasicHeader(":scheme", "https"),
@@ -237,7 +202,8 @@ public class TestDefaultH2RequestConverter {
new BasicHeader("custom", "value"));
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(headers);
+ Assert.assertThrows("Multiple ':path' request headers are illegal",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
@@ -254,24 +220,17 @@ public class TestDefaultH2RequestConverter {
@Test
public void testConvertFromFieldsConnectMissingAuthority() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Header ':authority' is mandatory for CONNECT request");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":method", "CONNECT"),
new BasicHeader("custom", "value"));
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(headers);
+ Assert.assertThrows("Header ':authority' is mandatory for CONNECT request",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsConnectPresentScheme() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Header ':scheme' must not be set for CONNECT request");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":method", "CONNECT"),
new BasicHeader(":scheme", "http"),
@@ -279,15 +238,12 @@ public class TestDefaultH2RequestConverter {
new BasicHeader("custom", "value"));
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(headers);
+ Assert.assertThrows("Header ':scheme' must not be set for CONNECT request",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsConnectPresentPath() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Header ':path' must not be set for CONNECT request");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":method", "CONNECT"),
new BasicHeader(":authority", "www.example.com"),
@@ -295,7 +251,8 @@ public class TestDefaultH2RequestConverter {
new BasicHeader("custom", "value"));
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(headers);
+ Assert.assertThrows("Header ':path' must not be set for CONNECT request",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
@@ -328,30 +285,24 @@ public class TestDefaultH2RequestConverter {
@Test
public void testConvertFromMessageMissingScheme() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Request scheme is not set");
-
final HttpRequest request = new BasicHttpRequest("GET", new HttpHost("host"), "/");
request.addHeader("Custom123", "Value");
request.setScheme(null);
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(request);
+ Assert.assertThrows("Request scheme is not set",
+ HttpException.class, () -> converter.convert(request));
}
@Test
public void testConvertFromMessageMissingPath() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Request path is not set");
-
final HttpRequest request = new BasicHttpRequest("GET", new HttpHost("host"), "/");
request.addHeader("Custom123", "Value");
request.setPath(null);
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(request);
+ Assert.assertThrows("Request path is not set",
+ HttpException.class, () -> converter.convert(request));
}
@Test
@@ -378,55 +329,43 @@ public class TestDefaultH2RequestConverter {
@Test
public void testConvertFromMessageConnectMissingAuthority() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("CONNECT request authority is not set");
-
final HttpRequest request = new BasicHttpRequest("CONNECT", null, null);
request.addHeader("Custom123", "Value");
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(request);
+ Assert.assertThrows("CONNECT request authority is not set",
+ HttpException.class, () -> converter.convert(request));
}
@Test
public void testConvertFromMessageConnectWithPath() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("CONNECT request path must be null");
-
final HttpRequest request = new BasicHttpRequest("CONNECT", "/");
request.setAuthority(new URIAuthority("host"));
request.addHeader("Custom123", "Value");
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(request);
+ Assert.assertThrows("CONNECT request path must be null",
+ HttpException.class, () -> converter.convert(request));
}
@Test
public void testConvertFromMessageConnectionHeader() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Header 'Connection: Keep-Alive' is illegal for HTTP/2 messages");
-
final HttpRequest request = new BasicHttpRequest("GET", new HttpHost("host"), "/");
request.addHeader("Connection", "Keep-Alive");
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(request);
+ Assert.assertThrows("Header 'Connection: Keep-Alive' is illegal for HTTP/2 messages",
+ HttpException.class, () -> converter.convert(request));
}
@Test
public void testConvertFromMessageInvalidHeader() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Header name ':custom' is invalid");
-
final HttpRequest request = new BasicHttpRequest("GET", new HttpHost("host"), "/");
request.addHeader(":custom", "stuff");
final DefaultH2RequestConverter converter = new DefaultH2RequestConverter();
- converter.convert(request);
+ Assert.assertThrows("Header name ':custom' is invalid",
+ HttpException.class, () -> converter.convert(request));
}
}
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/TestDefaultH2ResponseConverter.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/TestDefaultH2ResponseConverter.java
index 1d16d06..6253f55 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/TestDefaultH2ResponseConverter.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/TestDefaultH2ResponseConverter.java
@@ -36,15 +36,10 @@ import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicHttpResponse;
import org.junit.Assert;
-import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
public class TestDefaultH2ResponseConverter {
- @Rule
- public final ExpectedException thrown = ExpectedException.none();
-
@Test
public void testConvertFromFieldsBasic() throws Exception {
@@ -67,69 +62,52 @@ public class TestDefaultH2ResponseConverter {
@Test
public void testConvertFromFieldsUpperCaseHeaderName() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Header name ':Status' is invalid (header name contains uppercase characters)");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":Status", "200"),
new BasicHeader("location", "http://www.example.com/"),
new BasicHeader("custom123", "value"));
final DefaultH2ResponseConverter converter = new DefaultH2ResponseConverter();
- converter.convert(headers);
+ Assert.assertThrows("Header name ':Status' is invalid (header name contains uppercase characters)",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsInvalidStatusCode() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Invalid response status: boom");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":status", "boom"),
new BasicHeader("location", "http://www.example.com/"),
new BasicHeader("custom123", "value"));
final DefaultH2ResponseConverter converter = new DefaultH2ResponseConverter();
- converter.convert(headers);
+ Assert.assertThrows(HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsConnectionHeader() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Header 'connection: keep-alive' is illegal for HTTP/2 messages");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":status", "200"),
new BasicHeader("location", "http://www.example.com/"),
new BasicHeader("connection", "keep-alive"));
final DefaultH2ResponseConverter converter = new DefaultH2ResponseConverter();
- converter.convert(headers);
+ Assert.assertThrows("Header 'connection: keep-alive' is illegal for HTTP/2 messages",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsMissingStatus() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Mandatory response header ':status' not found");
-
final List<Header> headers = Arrays.asList(
new BasicHeader("location", "http://www.example.com/"),
new BasicHeader("custom", "value"));
final DefaultH2ResponseConverter converter = new DefaultH2ResponseConverter();
- converter.convert(headers);
+ Assert.assertThrows("Mandatory response header ':status' not found",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsUnknownPseudoHeader() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Unsupported response header ':custom'");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":status", "200"),
new BasicHeader(":custom", "200"),
@@ -137,15 +115,12 @@ public class TestDefaultH2ResponseConverter {
new BasicHeader("custom1", "value"));
final DefaultH2ResponseConverter converter = new DefaultH2ResponseConverter();
- converter.convert(headers);
+ Assert.assertThrows("Unsupported response header ':custom'",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
public void testConvertFromFieldsMultipleStatus() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Multiple ':status' response headers are illegal");
-
final List<Header> headers = Arrays.asList(
new BasicHeader(":status", "200"),
new BasicHeader(":status", "200"),
@@ -153,7 +128,8 @@ public class TestDefaultH2ResponseConverter {
new BasicHeader("custom1", "value"));
final DefaultH2ResponseConverter converter = new DefaultH2ResponseConverter();
- converter.convert(headers);
+ Assert.assertThrows("Multiple ':status' response headers are illegal",
+ HttpException.class, () -> converter.convert(headers));
}
@Test
@@ -177,41 +153,32 @@ public class TestDefaultH2ResponseConverter {
@Test
public void testConvertFromMessageInvalidStatus() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Response status 99 is invalid");
-
final HttpResponse response = new BasicHttpResponse(99);
response.addHeader("Custom123", "Value");
final DefaultH2ResponseConverter converter = new DefaultH2ResponseConverter();
- converter.convert(response);
+ Assert.assertThrows("Response status 99 is invalid",
+ HttpException.class, () -> converter.convert(response));
}
@Test
public void testConvertFromMessageConnectionHeader() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Header 'Connection: Keep-Alive' is illegal for HTTP/2 messages");
-
final HttpResponse response = new BasicHttpResponse(200);
response.addHeader("Connection", "Keep-Alive");
final DefaultH2ResponseConverter converter = new DefaultH2ResponseConverter();
- converter.convert(response);
+ Assert.assertThrows("Header 'Connection: Keep-Alive' is illegal for HTTP/2 messages",
+ HttpException.class, () -> converter.convert(response));
}
@Test
public void testConvertFromMessageInvalidHeader() throws Exception {
-
- thrown.expect(HttpException.class);
- thrown.expectMessage("Header name ':custom' is invalid");
-
final HttpResponse response = new BasicHttpResponse(200);
response.addHeader(":custom", "stuff");
final DefaultH2ResponseConverter converter = new DefaultH2ResponseConverter();
- converter.convert(response);
+ Assert.assertThrows("Header name ':custom' is invalid",
+ HttpException.class, () -> converter.convert(response));
}
}
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/io/TestFrameInOutBuffers.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/io/TestFrameInOutBuffers.java
index 68e803a..5a7b6cc 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/io/TestFrameInOutBuffers.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/io/TestFrameInOutBuffers.java
@@ -209,39 +209,39 @@ public class TestFrameInOutBuffers {
Assert.assertNull(payload);
}
- @Test(expected = ConnectionClosedException.class)
+ @Test
public void testReadFrameConnectionClosed() throws Exception {
final FrameInputBuffer inBuffer = new FrameInputBuffer(16 * 1024);
final ByteArrayInputStream inputStream = new ByteArrayInputStream(new byte[] {});
- inBuffer.read(inputStream);
+ Assert.assertThrows(ConnectionClosedException.class, () -> inBuffer.read(inputStream));
}
- @Test(expected = H2CorruptFrameException.class)
+ @Test
public void testReadFrameCorruptFrame() throws Exception {
final FrameInputBuffer inBuffer = new FrameInputBuffer(16 * 1024);
final ByteArrayInputStream inputStream = new ByteArrayInputStream(new byte[] {0,0});
- inBuffer.read(inputStream);
+ Assert.assertThrows(H2CorruptFrameException.class, () -> inBuffer.read(inputStream));
}
- @Test(expected = H2ConnectionException.class)
+ @Test
public void testWriteFrameExceedingLimit() throws Exception {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
final FrameOutputBuffer outbuffer = new FrameOutputBuffer(1024);
final RawFrame frame = new RawFrame(FrameType.DATA.getValue(), 0, 1,
ByteBuffer.wrap(new byte[2048]));
- outbuffer.write(frame, outputStream);
+ Assert.assertThrows(H2ConnectionException.class, () -> outbuffer.write(frame, outputStream));
}
- @Test(expected = H2ConnectionException.class)
+ @Test
public void testReadFrameExceedingLimit() throws Exception {
final FrameInputBuffer inBuffer = new FrameInputBuffer(16 * 1024);
final ByteArrayInputStream inputStream = new ByteArrayInputStream(
new byte[] {0,-128,-128,0,0,0,0,0,1});
- inBuffer.read(inputStream);
+ Assert.assertThrows(H2ConnectionException.class, () -> inBuffer.read(inputStream));
}
}
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestFrameInOutBuffers.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestFrameInOutBuffers.java
index c9e8603..cf6ab17 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestFrameInOutBuffers.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestFrameInOutBuffers.java
@@ -233,42 +233,44 @@ public class TestFrameInOutBuffers {
Assert.assertNull(payload);
}
- @Test(expected = ConnectionClosedException.class)
+ @Test
public void testReadFrameConnectionClosed() throws Exception {
final FrameInputBuffer inBuffer = new FrameInputBuffer(16 * 1024);
final ReadableByteChannelMock readableChannel = new ReadableByteChannelMock(new byte[] {});
Assert.assertEquals(null, inBuffer.read(readableChannel));
- inBuffer.read(readableChannel);
+ Assert.assertThrows(ConnectionClosedException.class, () ->
+ inBuffer.read(readableChannel));
}
- @Test(expected = H2CorruptFrameException.class)
+ @Test
public void testReadFrameCorruptFrame() throws Exception {
final FrameInputBuffer inBuffer = new FrameInputBuffer(16 * 1024);
final ReadableByteChannelMock readableChannel = new ReadableByteChannelMock(new byte[] {0,0});
- Assert.assertEquals(null, inBuffer.read(readableChannel));
- inBuffer.read(readableChannel);
+ Assert.assertThrows(H2CorruptFrameException.class, () ->
+ inBuffer.read(readableChannel));
}
- @Test(expected = H2ConnectionException.class)
+ @Test
public void testWriteFrameExceedingLimit() throws Exception {
final WritableByteChannelMock writableChannel = new WritableByteChannelMock(1024);
final FrameOutputBuffer outbuffer = new FrameOutputBuffer(1024);
final RawFrame frame = new RawFrame(FrameType.DATA.getValue(), 0, 1,
ByteBuffer.wrap(new byte[2048]));
- outbuffer.write(frame, writableChannel);
+ Assert.assertThrows(H2ConnectionException.class, () ->
+ outbuffer.write(frame, writableChannel));
}
- @Test(expected = H2ConnectionException.class)
+ @Test
public void testReadFrameExceedingLimit() throws Exception {
final FrameInputBuffer inBuffer = new FrameInputBuffer(16 * 1024);
final ReadableByteChannelMock readableChannel = new ReadableByteChannelMock(
new byte[] {0,-128,-128,0,0,0,0,0,1});
- Assert.assertEquals(null, inBuffer.read(readableChannel));
- inBuffer.read(readableChannel);
+ Assert.assertThrows(H2ConnectionException.class, () ->
+ inBuffer.read(readableChannel));
}
}
diff --git a/httpcore5-reactive/src/test/java/org/apache/hc/core5/reactive/TestReactiveDataConsumer.java b/httpcore5-reactive/src/test/java/org/apache/hc/core5/reactive/TestReactiveDataConsumer.java
index 2350746..3d1b283 100644
--- a/httpcore5-reactive/src/test/java/org/apache/hc/core5/reactive/TestReactiveDataConsumer.java
+++ b/httpcore5-reactive/src/test/java/org/apache/hc/core5/reactive/TestReactiveDataConsumer.java
@@ -35,6 +35,10 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
+import io.reactivex.Flowable;
+import io.reactivex.Notification;
+import io.reactivex.Observable;
+import io.reactivex.Single;
import org.apache.hc.core5.http.HttpStreamResetException;
import org.apache.hc.core5.http.nio.CapacityChannel;
import org.junit.Assert;
@@ -42,11 +46,6 @@ import org.junit.Test;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
-import io.reactivex.Flowable;
-import io.reactivex.Notification;
-import io.reactivex.Observable;
-import io.reactivex.Single;
-
public class TestReactiveDataConsumer {
@Test
@@ -93,7 +92,7 @@ public class TestReactiveDataConsumer {
Assert.assertSame(ex, single.blockingGet().get(0).getError());
}
- @Test(expected = HttpStreamResetException.class)
+ @Test
public void testCancellation() throws Exception {
final ReactiveDataConsumer consumer = new ReactiveDataConsumer();
consumer.subscribe(new Subscriber<ByteBuffer>() {
@@ -115,7 +114,8 @@ public class TestReactiveDataConsumer {
}
});
- consumer.consume(ByteBuffer.wrap(new byte[1024]));
+ Assert.assertThrows(HttpStreamResetException.class, () ->
+ consumer.consume(ByteBuffer.wrap(new byte[1024])));
}
@Test
diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/classic/ClassicTLSIntegrationTest.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/classic/ClassicTLSIntegrationTest.java
index 0876347..c7d01fd 100644
--- a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/classic/ClassicTLSIntegrationTest.java
+++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/classic/ClassicTLSIntegrationTest.java
@@ -30,7 +30,6 @@ package org.apache.hc.core5.testing.classic;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
-import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import org.apache.hc.core5.http.ClassicHttpRequest;
@@ -142,7 +141,7 @@ public class ClassicTLSIntegrationTest {
CoreMatchers.equalTo("CN=localhost,OU=Apache HttpComponents,O=Apache Software Foundation"));
}
- @Test(expected = SSLHandshakeException.class)
+ @Test
public void testTLSTrustFailure() throws Exception {
server = ServerBootstrap.bootstrap()
.setSocketConfig(SocketConfig.custom()
@@ -168,12 +167,14 @@ public class ClassicTLSIntegrationTest {
final HttpHost target = new HttpHost("https", "localhost", server.getLocalPort());
final ClassicHttpRequest request1 = new BasicClassicHttpRequest(Method.POST, "/stuff");
request1.setEntity(new StringEntity("some stuff", ContentType.TEXT_PLAIN));
- try (final ClassicHttpResponse response1 = requester.execute(target, request1, TIMEOUT, context)) {
- EntityUtils.consume(response1.getEntity());
- }
+ Assert.assertThrows(IOException.class, () -> {
+ try (final ClassicHttpResponse response1 = requester.execute(target, request1, TIMEOUT, context)) {
+ EntityUtils.consume(response1.getEntity());
+ }
+ });
}
- @Test(expected = IOException.class)
+ @Test
public void testTLSClientAuthFailure() throws Exception {
server = ServerBootstrap.bootstrap()
.setSslContext(SSLTestContexts.createClientSSLContext())
@@ -201,12 +202,14 @@ public class ClassicTLSIntegrationTest {
final HttpHost target = new HttpHost("https", "localhost", server.getLocalPort());
final ClassicHttpRequest request1 = new BasicClassicHttpRequest(Method.POST, "/stuff");
request1.setEntity(new StringEntity("some stuff", ContentType.TEXT_PLAIN));
- try (final ClassicHttpResponse response1 = requester.execute(target, request1, TIMEOUT, context)) {
- EntityUtils.consume(response1.getEntity());
- }
+ Assert.assertThrows(IOException.class, () -> {
+ try (final ClassicHttpResponse response1 = requester.execute(target, request1, TIMEOUT, context)) {
+ EntityUtils.consume(response1.getEntity());
+ }
+ });
}
- @Test(expected = IOException.class)
+ @Test
public void testSSLDisabledByDefault() throws Exception {
server = ServerBootstrap.bootstrap()
.setSslContext(SSLTestContexts.createServerSSLContext())
@@ -227,9 +230,11 @@ public class ClassicTLSIntegrationTest {
final HttpHost target = new HttpHost("https", "localhost", server.getLocalPort());
final ClassicHttpRequest request1 = new BasicClassicHttpRequest(Method.POST, "/stuff");
request1.setEntity(new StringEntity("some stuff", ContentType.TEXT_PLAIN));
- try (final ClassicHttpResponse response1 = requester.execute(target, request1, TIMEOUT, context)) {
- EntityUtils.consume(response1.getEntity());
- }
+ Assert.assertThrows(IOException.class, () -> {
+ try (final ClassicHttpResponse response1 = requester.execute(target, request1, TIMEOUT, context)) {
+ EntityUtils.consume(response1.getEntity());
+ }
+ });
}
@Test
@@ -250,7 +255,6 @@ public class ClassicTLSIntegrationTest {
"TLS_DH_anon_WITH_AES_128_CBC_SHA",
"SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
"SSL_RSA_WITH_NULL_SHA",
- "SSL_RSA_WITH_3DES_EDE_CBC_SHA",
"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
"TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA",
"TLS_DH_anon_WITH_AES_256_GCM_SHA384",
@@ -267,22 +271,21 @@ public class ClassicTLSIntegrationTest {
.setSslContext(SSLTestContexts.createServerSSLContext())
.setSslSetupHandler(sslParameters -> sslParameters.setProtocols(new String[]{cipherSuite}))
.create();
- try {
- server.start();
-
- final HttpContext context = new BasicHttpContext();
- final HttpHost target = new HttpHost("https", "localhost", server.getLocalPort());
- final ClassicHttpRequest request1 = new BasicClassicHttpRequest(Method.POST, "/stuff");
- request1.setEntity(new StringEntity("some stuff", ContentType.TEXT_PLAIN));
- try (final ClassicHttpResponse response1 = requester.execute(target, request1, TIMEOUT, context)) {
- EntityUtils.consume(response1.getEntity());
+ Assert.assertThrows(Exception.class, () -> {
+ try {
+ server.start();
+
+ final HttpContext context = new BasicHttpContext();
+ final HttpHost target = new HttpHost("https", "localhost", server.getLocalPort());
+ final ClassicHttpRequest request1 = new BasicClassicHttpRequest(Method.POST, "/stuff");
+ request1.setEntity(new StringEntity("some stuff", ContentType.TEXT_PLAIN));
+ try (final ClassicHttpResponse response1 = requester.execute(target, request1, TIMEOUT, context)) {
+ EntityUtils.consume(response1.getEntity());
+ }
+ } finally {
+ server.close(CloseMode.IMMEDIATE);
}
-
- Assert.fail("IOException expected");
- } catch (final IOException | IllegalArgumentException expected) {
- } finally {
- server.close(CloseMode.IMMEDIATE);
- }
+ });
}
}
diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2ProtocolNegotiationTest.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2ProtocolNegotiationTest.java
index d25d325..dc959b0 100644
--- a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2ProtocolNegotiationTest.java
+++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2ProtocolNegotiationTest.java
@@ -39,7 +39,6 @@ import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.HttpVersion;
import org.apache.hc.core5.http.Message;
import org.apache.hc.core5.http.Method;
-import org.apache.hc.core5.http.ProtocolVersion;
import org.apache.hc.core5.http.URIScheme;
import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer;
import org.apache.hc.core5.http.nio.AsyncClientEndpoint;
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/concurrent/TestBasicFuture.java b/httpcore5/src/test/java/org/apache/hc/core5/concurrent/TestBasicFuture.java
index 62037f6..2a06cb5 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/concurrent/TestBasicFuture.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/concurrent/TestBasicFuture.java
@@ -171,7 +171,7 @@ public class TestBasicFuture {
Assert.assertFalse(future.isCancelled());
}
- @Test(expected = CancellationException.class)
+ @Test
public void testAsyncCancelled() throws Exception {
final BasicFuture<Object> future = new BasicFuture<>(null);
@@ -184,10 +184,11 @@ public class TestBasicFuture {
});
t.setDaemon(true);
t.start();
- future.get(60, TimeUnit.SECONDS);
+ Assert.assertThrows(CancellationException.class, () ->
+ future.get(60, TimeUnit.SECONDS));
}
- @Test(expected=TimeoutException.class)
+ @Test
public void testAsyncTimeout() throws Exception {
final BasicFuture<Object> future = new BasicFuture<>(null);
final Object result = new Object();
@@ -201,13 +202,15 @@ public class TestBasicFuture {
});
t.setDaemon(true);
t.start();
- future.get(1, TimeUnit.MILLISECONDS);
+ Assert.assertThrows(TimeoutException.class, () ->
+ future.get(1, TimeUnit.MILLISECONDS));
}
- @Test(expected=TimeoutValueException.class)
+ @Test
public void testAsyncNegativeTimeout() throws Exception {
final BasicFuture<Object> future = new BasicFuture<>(null);
- future.get(-1, TimeUnit.MILLISECONDS);
+ Assert.assertThrows(TimeoutValueException.class, () ->
+ future.get(-1, TimeUnit.MILLISECONDS));
}
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/TestDefaultConnectionReuseStrategy.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/TestDefaultConnectionReuseStrategy.java
index 9252f7b..6ec240a 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/TestDefaultConnectionReuseStrategy.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/TestDefaultConnectionReuseStrategy.java
@@ -55,9 +55,10 @@ public class TestDefaultConnectionReuseStrategy {
context = new BasicHttpContext(null);
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testInvalidResponseArg() throws Exception {
- reuseStrategy.keepAlive(null, null, this.context);
+ Assert.assertThrows(NullPointerException.class, () ->
+ reuseStrategy.keepAlive(null, null, this.context));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/TestDefaultContentLengthStrategy.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/TestDefaultContentLengthStrategy.java
index 5353855..becda22 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/TestDefaultContentLengthStrategy.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/TestDefaultContentLengthStrategy.java
@@ -73,20 +73,22 @@ public class TestDefaultContentLengthStrategy {
Assert.assertEquals(ContentLengthStrategy.CHUNKED, lenStrategy.determineLength(message));
}
- @Test(expected = NotImplementedException.class)
+ @Test
public void testEntityWithIdentityTransferEncoding() throws Exception {
final ContentLengthStrategy lenStrategy = new DefaultContentLengthStrategy();
final HttpMessage message = new TestHttpMessage();
message.addHeader("Transfer-Encoding", "Identity");
- lenStrategy.determineLength(message);
+ Assert.assertThrows(NotImplementedException.class, () ->
+ lenStrategy.determineLength(message));
}
- @Test(expected=ProtocolException.class)
+ @Test
public void testEntityWithInvalidTransferEncoding() throws Exception {
final ContentLengthStrategy lenStrategy = new DefaultContentLengthStrategy();
final HttpMessage message = new TestHttpMessage();
message.addHeader("Transfer-Encoding", "whatever");
- lenStrategy.determineLength(message);
+ Assert.assertThrows(ProtocolException.class, () ->
+ lenStrategy.determineLength(message));
}
@Test
@@ -97,20 +99,22 @@ public class TestDefaultContentLengthStrategy {
Assert.assertEquals(100, lenStrategy.determineLength(message));
}
- @Test(expected=ProtocolException.class)
+ @Test
public void testEntityWithInvalidContentLength() throws Exception {
final ContentLengthStrategy lenStrategy = new DefaultContentLengthStrategy();
final HttpMessage message = new TestHttpMessage();
message.addHeader("Content-Length", "whatever");
- lenStrategy.determineLength(message);
+ Assert.assertThrows(ProtocolException.class, () ->
+ lenStrategy.determineLength(message));
}
- @Test(expected=ProtocolException.class)
+ @Test
public void testEntityWithNegativeContentLength() throws Exception {
final ContentLengthStrategy lenStrategy = new DefaultContentLengthStrategy();
final HttpMessage message = new TestHttpMessage();
message.addHeader("Content-Length", "-10");
- lenStrategy.determineLength(message);
+ Assert.assertThrows(ProtocolException.class, () ->
+ lenStrategy.determineLength(message));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestChunkCoding.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestChunkCoding.java
index 313abfa..9bc1e84 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestChunkCoding.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestChunkCoding.java
@@ -39,7 +39,6 @@ import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.MalformedChunkCodingException;
import org.apache.hc.core5.http.MessageConstraintException;
import org.apache.hc.core5.http.StreamClosedException;
-import org.apache.hc.core5.http.TruncatedChunkException;
import org.apache.hc.core5.http.io.SessionInputBuffer;
import org.apache.hc.core5.http.io.SessionOutputBuffer;
import org.apache.hc.core5.http.message.BasicHeader;
@@ -167,7 +166,7 @@ public class TestChunkCoding {
}
// Missing closing chunk
- @Test(expected=ConnectionClosedException.class)
+ @Test
public void testChunkedInputStreamNoClosingChunk() throws IOException {
final String s = "5\r\n01234\r\n";
final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16);
@@ -175,12 +174,12 @@ public class TestChunkCoding {
final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream);
final byte[] tmp = new byte[5];
Assert.assertEquals(5, in.read(tmp));
- in.read();
- in.close();
+ Assert.assertThrows(ConnectionClosedException.class, () -> in.read());
+ Assert.assertThrows(ConnectionClosedException.class, () -> in.close());
}
// Truncated stream (missing closing CRLF)
- @Test(expected=MalformedChunkCodingException.class)
+ @Test
public void testCorruptChunkedInputStreamTruncatedCRLF() throws IOException {
final String s = "5\r\n01234";
final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16);
@@ -188,12 +187,12 @@ public class TestChunkCoding {
final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream);
final byte[] tmp = new byte[5];
Assert.assertEquals(5, in.read(tmp));
- in.read();
+ Assert.assertThrows(MalformedChunkCodingException.class, () -> in.read());
in.close();
}
// Missing \r\n at the end of the first chunk
- @Test(expected=MalformedChunkCodingException.class)
+ @Test
public void testCorruptChunkedInputStreamMissingCRLF() throws IOException {
final String s = "5\r\n012345\r\n56789\r\n0\r\n";
final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16);
@@ -201,48 +200,50 @@ public class TestChunkCoding {
final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream);
final byte[] buffer = new byte[300];
final ByteArrayOutputStream out = new ByteArrayOutputStream();
- int len;
- while ((len = in.read(buffer)) > 0) {
- out.write(buffer, 0, len);
- }
+ Assert.assertThrows(MalformedChunkCodingException.class, () -> {
+ int len;
+ while ((len = in.read(buffer)) > 0) {
+ out.write(buffer, 0, len);
+ }
+ });
in.close();
}
// Missing LF
- @Test(expected=MalformedChunkCodingException.class)
+ @Test
public void testCorruptChunkedInputStreamMissingLF() throws IOException {
final String s = "5\r01234\r\n5\r\n56789\r\n0\r\n";
final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16);
final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.ISO_8859_1));
final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream);
- in.read();
+ Assert.assertThrows(MalformedChunkCodingException.class, () -> in.read());
in.close();
}
// Invalid chunk size
- @Test(expected = MalformedChunkCodingException.class)
+ @Test
public void testCorruptChunkedInputStreamInvalidSize() throws IOException {
final String s = "whatever\r\n01234\r\n5\r\n56789\r\n0\r\n";
final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16);
final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.ISO_8859_1));
final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream);
- in.read();
+ Assert.assertThrows(MalformedChunkCodingException.class, () -> in.read());
in.close();
}
// Negative chunk size
- @Test(expected = MalformedChunkCodingException.class)
+ @Test
public void testCorruptChunkedInputStreamNegativeSize() throws IOException {
final String s = "-5\r\n01234\r\n5\r\n56789\r\n0\r\n";
final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16);
final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.ISO_8859_1));
final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream);
- in.read();
+ Assert.assertThrows(MalformedChunkCodingException.class, () -> in.read());
in.close();
}
// Truncated chunk
- @Test(expected = TruncatedChunkException.class)
+ @Test
public void testCorruptChunkedInputStreamTruncatedChunk() throws IOException {
final String s = "3\r\n12";
final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16);
@@ -250,19 +251,19 @@ public class TestChunkCoding {
final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream);
final byte[] buffer = new byte[300];
Assert.assertEquals(2, in.read(buffer));
- in.read(buffer);
+ Assert.assertThrows(MalformedChunkCodingException.class, () -> in.read(buffer));
in.close();
}
// Invalid footer
- @Test(expected = MalformedChunkCodingException.class)
+ @Test
public void testCorruptChunkedInputStreamInvalidFooter() throws IOException {
final String s = "1\r\n0\r\n0\r\nstuff\r\n";
final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16);
final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.ISO_8859_1));
final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream);
in.read();
- in.read();
+ Assert.assertThrows(MalformedChunkCodingException.class, () -> in.read());
in.close();
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestDefaultBHttpClientConnection.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestDefaultBHttpClientConnection.java
index 986e48b..4517234 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestDefaultBHttpClientConnection.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestDefaultBHttpClientConnection.java
@@ -190,7 +190,7 @@ public class TestDefaultBHttpClientConnection {
Assert.assertTrue(content instanceof ChunkedInputStream);
}
- @Test(expected = NotImplementedException.class)
+ @Test
public void testReadResponseEntityIdentity() throws Exception {
final String s = "HTTP/1.1 200 OK\r\nServer: test\r\nTransfer-Encoding: identity\r\n\r\n123";
final ByteArrayInputStream inStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII));
@@ -207,7 +207,8 @@ public class TestDefaultBHttpClientConnection {
Assert.assertTrue(response.containsHeader("Server"));
Assert.assertEquals(1, conn.getEndpointDetails().getResponseCount());
- conn.receiveResponseEntity(response);
+ Assert.assertThrows(NotImplementedException.class, () ->
+ conn.receiveResponseEntity(response));
}
@Test
@@ -303,7 +304,7 @@ public class TestDefaultBHttpClientConnection {
"chunked\r\n\r\n3\r\n123\r\n0\r\n\r\n", s);
}
- @Test(expected = LengthRequiredException.class)
+ @Test
public void testWriteRequestEntityNoContentLength() throws Exception {
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
Mockito.when(socket.getOutputStream()).thenReturn(outStream);
@@ -317,7 +318,8 @@ public class TestDefaultBHttpClientConnection {
request.setEntity(new StringEntity("123", ContentType.TEXT_PLAIN));
conn.sendRequestHeader(request);
- conn.sendRequestEntity(request);
+ Assert.assertThrows(LengthRequiredException.class, () ->
+ conn.sendRequestEntity(request));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestDefaultBHttpServerConnection.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestDefaultBHttpServerConnection.java
index 5ea892f..e7ddb89 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestDefaultBHttpServerConnection.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestDefaultBHttpServerConnection.java
@@ -162,7 +162,7 @@ public class TestDefaultBHttpServerConnection {
Assert.assertTrue(content instanceof ChunkedInputStream);
}
- @Test(expected = ProtocolException.class)
+ @Test
public void testReadRequestEntityIdentity() throws Exception {
final String s = "POST /stuff HTTP/1.1\r\nUser-Agent: test\r\nTransfer-Encoding: " +
"identity\r\n\r\n123";
@@ -182,7 +182,8 @@ public class TestDefaultBHttpServerConnection {
Assert.assertNull(request.getEntity());
Assert.assertEquals(1, conn.getEndpointDetails().getRequestCount());
- conn.receiveRequestEntity(request);
+ Assert.assertThrows(ProtocolException.class, () ->
+ conn.receiveRequestEntity(request));
}
@Test
@@ -296,7 +297,7 @@ public class TestDefaultBHttpServerConnection {
"chunked\r\n\r\n3\r\n123\r\n0\r\n\r\n", s);
}
- @Test(expected = NotImplementedException.class)
+ @Test
public void testWriteResponseEntityIdentity() throws Exception {
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
Mockito.when(socket.getOutputStream()).thenReturn(outStream);
@@ -311,7 +312,8 @@ public class TestDefaultBHttpServerConnection {
response.setEntity(new StringEntity("123", ContentType.TEXT_PLAIN));
conn.sendResponseHeader(response);
- conn.sendResponseEntity(response);
+ Assert.assertThrows(NotImplementedException.class, () ->
+ conn.sendResponseEntity(response));
conn.flush();
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestRequestParser.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestRequestParser.java
index 10a0614..08406e7 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestRequestParser.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestRequestParser.java
@@ -95,7 +95,7 @@ public class TestRequestParser {
Assert.assertEquals(1, headers.length);
}
- @Test(expected = RequestHeaderFieldsTooLargeException.class)
+ @Test
public void testBasicMessageParsingTooManyLeadingEmptyLines() throws Exception {
final String s =
"\r\n" +
@@ -109,7 +109,8 @@ public class TestRequestParser {
final DefaultHttpRequestParser parser = new DefaultHttpRequestParser(
Http1Config.custom().setMaxEmptyLineCount(3).build());
- parser.parse(inBuffer, inputStream);
+ Assert.assertThrows(RequestHeaderFieldsTooLargeException.class, () ->
+ parser.parse(inBuffer, inputStream));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestResponseParser.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestResponseParser.java
index c21e1bf..7299f2e 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestResponseParser.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestResponseParser.java
@@ -95,7 +95,7 @@ public class TestResponseParser {
Assert.assertEquals(1, headers.length);
}
- @Test(expected = MessageConstraintException.class)
+ @Test
public void testBasicMessageParsingTooManyLeadingEmptyLines() throws Exception {
final String s =
"\r\n" +
@@ -109,7 +109,8 @@ public class TestResponseParser {
final DefaultHttpResponseParser parser = new DefaultHttpResponseParser(
Http1Config.custom().setMaxEmptyLineCount(3).build());
- parser.parse(inBuffer, inputStream);
+ Assert.assertThrows(MessageConstraintException.class, () ->
+ parser.parse(inBuffer, inputStream));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestSessionInOutBuffers.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestSessionInOutBuffers.java
index ca3de8e..82d3e4a 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestSessionInOutBuffers.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestSessionInOutBuffers.java
@@ -599,7 +599,7 @@ public class TestSessionInOutBuffers {
Assert.assertEquals(expected, bytesRead);
}
- @Test(expected=CharacterCodingException.class)
+ @Test
public void testUnmappableInputActionReport() throws Exception {
final String s = "This text contains a circumflex \u0302 !!!";
final CharsetEncoder encoder = StandardCharsets.ISO_8859_1.newEncoder();
@@ -609,7 +609,8 @@ public class TestSessionInOutBuffers {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
final CharArrayBuffer chbuffer = new CharArrayBuffer(32);
chbuffer.append(s);
- outbuffer.writeLine(chbuffer, outputStream);
+ Assert.assertThrows(CharacterCodingException.class, () ->
+ outbuffer.writeLine(chbuffer, outputStream));
}
@Test
@@ -644,7 +645,7 @@ public class TestSessionInOutBuffers {
Assert.assertEquals("This text contains a circumflex !!!\r\n", result);
}
- @Test(expected=CharacterCodingException.class)
+ @Test
public void testMalformedInputActionReport() throws Exception {
final byte[] tmp = constructString(SWISS_GERMAN_HELLO).getBytes(StandardCharsets.ISO_8859_1);
final CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
@@ -653,7 +654,8 @@ public class TestSessionInOutBuffers {
final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16, decoder);
final ByteArrayInputStream inputStream = new ByteArrayInputStream(tmp);
final CharArrayBuffer chbuffer = new CharArrayBuffer(32);
- inBuffer.readLine(chbuffer, inputStream);
+ Assert.assertThrows(CharacterCodingException.class, () ->
+ inBuffer.readLine(chbuffer, inputStream));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestChunkDecoder.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestChunkDecoder.java
index 43a935a..8603f1e 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestChunkDecoder.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestChunkDecoder.java
@@ -215,7 +215,7 @@ public class TestChunkDecoder {
Assert.assertTrue(decoder.isCompleted());
}
- @Test(expected=MalformedChunkCodingException.class)
+ @Test
public void testMalformedChunkSizeDecoding() throws Exception {
final String s = "5\r\n01234\r\n5zz\r\n56789\r\n6\r\nabcdef\r\n0\r\n\r\n";
final ReadableByteChannel channel = new ReadableByteChannelMock(
@@ -226,10 +226,11 @@ public class TestChunkDecoder {
final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
final ByteBuffer dst = ByteBuffer.allocate(1024);
- decoder.read(dst);
+ Assert.assertThrows(MalformedChunkCodingException.class, () ->
+ decoder.read(dst));
}
- @Test(expected=MalformedChunkCodingException.class)
+ @Test
public void testMalformedChunkEndingDecoding() throws Exception {
final String s = "5\r\n01234\r\n5\r\n56789\r\r6\r\nabcdef\r\n0\r\n\r\n";
final ReadableByteChannel channel = new ReadableByteChannelMock(
@@ -240,10 +241,11 @@ public class TestChunkDecoder {
final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
final ByteBuffer dst = ByteBuffer.allocate(1024);
- decoder.read(dst);
+ Assert.assertThrows(MalformedChunkCodingException.class, () ->
+ decoder.read(dst));
}
- @Test(expected=TruncatedChunkException.class)
+ @Test
public void testMalformedChunkTruncatedChunk() throws Exception {
final String s = "3\r\n12";
final ReadableByteChannel channel = new ReadableByteChannelMock(
@@ -255,7 +257,8 @@ public class TestChunkDecoder {
final ByteBuffer dst = ByteBuffer.allocate(1024);
Assert.assertEquals(2, decoder.read(dst));
- decoder.read(dst);
+ Assert.assertThrows(TruncatedChunkException.class, () ->
+ decoder.read(dst));
}
@Test
@@ -281,7 +284,7 @@ public class TestChunkDecoder {
Assert.assertEquals("abcde fghij", trailers.get(0).getValue());
}
- @Test(expected=IOException.class)
+ @Test
public void testMalformedFooters() throws Exception {
final String s = "10;key=\"value\"\r\n1234567890123456\r\n" +
"5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1 abcde\r\n\r\n";
@@ -293,10 +296,11 @@ public class TestChunkDecoder {
final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
final ByteBuffer dst = ByteBuffer.allocate(1024);
- decoder.read(dst);
+ Assert.assertThrows(IOException.class, () ->
+ decoder.read(dst));
}
- @Test(expected=MalformedChunkCodingException.class)
+ @Test
public void testMissingLastCRLF() throws Exception {
final String s = "10\r\n1234567890123456\r\n" +
"5\r\n12345\r\n5\r\n12345";
@@ -309,12 +313,14 @@ public class TestChunkDecoder {
final ByteBuffer dst = ByteBuffer.allocate(1024);
- while (dst.hasRemaining() && !decoder.isCompleted()) {
- decoder.read(dst);
- }
+ Assert.assertThrows(MalformedChunkCodingException.class, () -> {
+ while (dst.hasRemaining() && !decoder.isCompleted()) {
+ decoder.read(dst);
+ }
+ });
}
- @Test(expected=ConnectionClosedException.class)
+ @Test
public void testMissingClosingChunk() throws Exception {
final String s = "10\r\n1234567890123456\r\n" +
"5\r\n12345\r\n5\r\n12345\r\n";
@@ -327,20 +333,22 @@ public class TestChunkDecoder {
final ByteBuffer dst = ByteBuffer.allocate(1024);
- long bytesRead = 0;
- try {
- while (dst.hasRemaining() && !decoder.isCompleted()) {
- final int i = decoder.read(dst);
- if (i > 0) {
- bytesRead += i;
+ Assert.assertThrows(ConnectionClosedException.class, () -> {
+ long bytesRead = 0;
+ try {
+ while (dst.hasRemaining() && !decoder.isCompleted()) {
+ final int i = decoder.read(dst);
+ if (i > 0) {
+ bytesRead += i;
+ }
}
+ } catch (final MalformedChunkCodingException ex) {
+ Assert.assertEquals(26L, bytesRead);
+ Assert.assertEquals("12345678901234561234512345", CodecTestUtils.convert(dst));
+ Assert.assertTrue(decoder.isCompleted());
+ throw ex;
}
- } catch (final MalformedChunkCodingException ex) {
- Assert.assertEquals(26L, bytesRead);
- Assert.assertEquals("12345678901234561234512345", CodecTestUtils.convert(dst));
- Assert.assertTrue(decoder.isCompleted());
- throw ex;
- }
+ });
}
@Test
@@ -570,7 +578,7 @@ public class TestChunkDecoder {
}
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testInvalidInput() throws Exception {
final String s = "10;key=\"value\"\r\n1234567890123456\r\n" +
"5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1 abcde\r\n\r\n";
@@ -580,7 +588,8 @@ public class TestChunkDecoder {
final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, 0, StandardCharsets.US_ASCII);
final BasicHttpTransportMetrics metrics = new BasicHttpTransportMetrics();
final ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
- decoder.read(null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ decoder.read(null));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestLengthDelimitedDecoder.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestLengthDelimitedDecoder.java
index a455ff5..d1906bd 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestLengthDelimitedDecoder.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestLengthDelimitedDecoder.java
@@ -545,7 +545,7 @@ public class TestLengthDelimitedDecoder {
Assert.assertEquals(0, metrics.getBytesTransferred());
}
- @Test(expected=ConnectionClosedException.class)
+ @Test
public void testTruncatedContent() throws Exception {
final ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {"1234567890"}, StandardCharsets.US_ASCII);
@@ -559,10 +559,11 @@ public class TestLengthDelimitedDecoder {
final int bytesRead = decoder.read(dst);
Assert.assertEquals(10, bytesRead);
- decoder.read(dst);
+ Assert.assertThrows(ConnectionClosedException.class, () ->
+ decoder.read(dst));
}
- @Test(expected=ConnectionClosedException.class)
+ @Test
public void testTruncatedContentWithFile() throws Exception {
final ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {"1234567890"}, StandardCharsets.US_ASCII);
@@ -577,7 +578,8 @@ public class TestLengthDelimitedDecoder {
final FileChannel fchannel = testfile.getChannel();
final long bytesRead = decoder.transfer(fchannel, 0, Integer.MAX_VALUE);
Assert.assertEquals(10, bytesRead);
- decoder.transfer(fchannel, 0, Integer.MAX_VALUE);
+ Assert.assertThrows(ConnectionClosedException.class, () ->
+ decoder.transfer(fchannel, 0, Integer.MAX_VALUE));
}
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestSessionInOutBuffers.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestSessionInOutBuffers.java
index 3381713..331b6f1 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestSessionInOutBuffers.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestSessionInOutBuffers.java
@@ -521,7 +521,7 @@ public class TestSessionInOutBuffers {
outbuf.writeLine(chbuffer);
}
- @Test(expected=CharacterCodingException.class)
+ @Test
public void testMalformedInputActionReport() throws Exception {
final String s = constructString(SWISS_GERMAN_HELLO);
final byte[] tmp = s.getBytes(StandardCharsets.ISO_8859_1);
@@ -534,7 +534,8 @@ public class TestSessionInOutBuffers {
while (inbuf.fill(channel) > 0) {
}
final CharArrayBuffer chbuffer = new CharArrayBuffer(16);
- inbuf.readLine(chbuffer, true);
+ Assert.assertThrows(CharacterCodingException.class, () ->
+ inbuf.readLine(chbuffer, true));
}
@Test
@@ -571,7 +572,7 @@ public class TestSessionInOutBuffers {
Assert.assertEquals("Gr\ufffdezi_z\ufffdm\ufffd", chbuffer.toString());
}
- @Test(expected=CharacterCodingException.class)
+ @Test
public void testUnmappableInputActionReport() throws Exception {
final String s = "This text contains a circumflex \u0302!!!";
final CharsetEncoder encoder = StandardCharsets.ISO_8859_1.newEncoder();
@@ -580,7 +581,8 @@ public class TestSessionInOutBuffers {
final SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 16, encoder);
final CharArrayBuffer chbuffer = new CharArrayBuffer(16);
chbuffer.append(s);
- outbuf.writeLine(chbuffer);
+ Assert.assertThrows(CharacterCodingException.class, () ->
+ outbuf.writeLine(chbuffer));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestByteArrayEntity.java b/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestByteArrayEntity.java
index 55fc39c..fa2315c 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestByteArrayEntity.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestByteArrayEntity.java
@@ -61,27 +61,31 @@ public class TestByteArrayEntity {
Assert.assertFalse(entity.isStreaming());
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testIllegalConstructorNullByteArray() throws Exception {
- new ByteArrayEntity(null, null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ new ByteArrayEntity(null, null));
}
- @Test(expected=IndexOutOfBoundsException.class)
+ @Test
public void testIllegalConstructorBadLen() throws Exception {
final byte[] bytes = "Message content".getBytes(StandardCharsets.US_ASCII);
- new ByteArrayEntity(bytes, 0, bytes.length + 1, null);
+ Assert.assertThrows(IndexOutOfBoundsException.class, () ->
+ new ByteArrayEntity(bytes, 0, bytes.length + 1, null));
}
- @Test(expected=IndexOutOfBoundsException.class)
+ @Test
public void testIllegalConstructorBadOff1() throws Exception {
final byte[] bytes = "Message content".getBytes(StandardCharsets.US_ASCII);
- new ByteArrayEntity(bytes, -1, bytes.length, null);
+ Assert.assertThrows(IndexOutOfBoundsException.class, () ->
+ new ByteArrayEntity(bytes, -1, bytes.length, null));
}
- @Test(expected=IndexOutOfBoundsException.class)
+ @Test
public void testIllegalConstructorBadOff2() throws Exception {
final byte[] bytes = "Message content".getBytes(StandardCharsets.US_ASCII);
- new ByteArrayEntity(bytes, bytes.length + 1, bytes.length, null);
+ Assert.assertThrows(IndexOutOfBoundsException.class, () ->
+ new ByteArrayEntity(bytes, bytes.length + 1, bytes.length, null));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestEntityUtils.java b/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestEntityUtils.java
index 370a3e1..f094d1b 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestEntityUtils.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestEntityUtils.java
@@ -53,17 +53,19 @@ import org.junit.Test;
*/
public class TestEntityUtils {
- @Test(expected = NullPointerException.class)
+ @Test
public void testNullEntityToByteArray() throws Exception {
- EntityUtils.toByteArray(null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ EntityUtils.toByteArray(null));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testMaxIntContentToByteArray() throws Exception {
final byte[] content = "Message content".getBytes(StandardCharsets.ISO_8859_1);
final BasicHttpEntity entity = new BasicHttpEntity(new ByteArrayInputStream(content),
Integer.MAX_VALUE + 100L, ContentType.TEXT_PLAIN.withCharset(StandardCharsets.ISO_8859_1));
- EntityUtils.toByteArray(entity);
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ EntityUtils.toByteArray(entity));
}
@Test
@@ -100,12 +102,13 @@ public class TestEntityUtils {
}
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testMaxIntContentToString() throws Exception {
final byte[] content = "Message content".getBytes(StandardCharsets.ISO_8859_1);
final BasicHttpEntity entity = new BasicHttpEntity(new ByteArrayInputStream(content),
Integer.MAX_VALUE + 100L, ContentType.TEXT_PLAIN.withCharset(StandardCharsets.ISO_8859_1));
- EntityUtils.toString(entity);
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ EntityUtils.toString(entity));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestInputStreamEntity.java b/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestInputStreamEntity.java
index 35e0e17..781550c 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestInputStreamEntity.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestInputStreamEntity.java
@@ -53,9 +53,10 @@ public class TestInputStreamEntity {
Assert.assertTrue(entity.isStreaming());
}
- @Test(expected = NullPointerException.class)
+ @Test
public void testNullConstructor() throws Exception {
- new InputStreamEntity(null, 0, null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ new InputStreamEntity(null, 0, null));
}
@Test
@@ -118,9 +119,10 @@ public class TestInputStreamEntity {
Assert.assertEquals(message, s);
}
- @Test(expected = NullPointerException.class)
+ @Test
public void testWriteToNull() throws Exception {
final InputStreamEntity entity = new InputStreamEntity(EmptyInputStream.INSTANCE, 0, null);
- entity.writeTo(null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ entity.writeTo(null));
}
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicMessages.java b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicMessages.java
index 020d6a3..ed14fb2 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicMessages.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicMessages.java
@@ -27,6 +27,8 @@
package org.apache.hc.core5.http.message;
+import java.net.URI;
+
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpResponse;
@@ -36,8 +38,6 @@ import org.apache.hc.core5.net.URIAuthority;
import org.junit.Assert;
import org.junit.Test;
-import java.net.URI;
-
/**
* Unit tests for {@link org.apache.hc.core5.http.HttpMessage}.
*
@@ -214,9 +214,10 @@ public class TestBasicMessages {
Assert.assertEquals(new URI("http://%21example%21.com/stuff"), request.getUri());
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testRequestPathWithMultipleLeadingSlashes() throws Exception {
- new BasicHttpRequest(Method.GET, URI.create("http://host//stuff"));
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ new BasicHttpRequest(Method.GET, URI.create("http://host//stuff")));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/nio/entity/TestDigestingEntityProducer.java b/httpcore5/src/test/java/org/apache/hc/core5/http/nio/entity/TestDigestingEntityProducer.java
index cc1250c..1e5091c 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/nio/entity/TestDigestingEntityProducer.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/nio/entity/TestDigestingEntityProducer.java
@@ -30,9 +30,9 @@ package org.apache.hc.core5.http.nio.entity;
import java.nio.charset.StandardCharsets;
import java.util.List;
+import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.WritableByteChannelMock;
-import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.nio.BasicDataStreamChannel;
import org.junit.Assert;
import org.junit.Test;
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestRequestHandlerRegistry.java b/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestRequestHandlerRegistry.java
index 7b813c2..7ca50ab 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestRequestHandlerRegistry.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestRequestHandlerRegistry.java
@@ -77,10 +77,11 @@ public class TestRequestHandlerRegistry {
Assert.assertEquals("stuff", handlerRegistry.resolve(new BasicHttpRequest(Method.GET, new HttpHost("127.0.0.1"), "/testabc"), context));
}
- @Test(expected = MisdirectedRequestException.class)
+ @Test
public void testResolveByUnknownHostname() throws Exception {
handlerRegistry.register("myhost", "/test*", "stuff");
- handlerRegistry.resolve(new BasicHttpRequest(Method.GET, new HttpHost("otherhost"), "/test"), context);
+ Assert.assertThrows(MisdirectedRequestException.class, () ->
+ handlerRegistry.resolve(new BasicHttpRequest(Method.GET, new HttpHost("otherhost"), "/test"), context));
}
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestStandardInterceptors.java b/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestStandardInterceptors.java
index cef1f8a..090138b 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestStandardInterceptors.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestStandardInterceptors.java
@@ -38,8 +38,8 @@ import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.HttpVersion;
import org.apache.hc.core5.http.Method;
import org.apache.hc.core5.http.ProtocolException;
-import org.apache.hc.core5.http.io.entity.EmptyInputStream;
import org.apache.hc.core5.http.io.entity.BasicHttpEntity;
+import org.apache.hc.core5.http.io.entity.EmptyInputStream;
import org.apache.hc.core5.http.io.entity.HttpEntities;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
@@ -311,13 +311,14 @@ public class TestStandardInterceptors {
Assert.assertEquals("h1, h2", header2.getValue());
}
- @Test(expected = ProtocolException.class)
+ @Test
public void testRequestContentTraceWithEntity() throws Exception {
final HttpContext context = new BasicHttpContext(null);
final BasicClassicHttpRequest request = new BasicClassicHttpRequest(Method.TRACE, "/");
request.setEntity(new StringEntity("stuff"));
final RequestContent interceptor = new RequestContent();
- interceptor.process(request, request.getEntity(), context);
+ Assert.assertThrows(ProtocolException.class, () ->
+ interceptor.process(request, request.getEntity(), context));
}
@Test
@@ -1056,22 +1057,24 @@ public class TestStandardInterceptors {
interceptor.process(request, request.getEntity(), context);
}
- @Test(expected = ProtocolException.class)
+ @Test
public void testRequestHttp11HostHeaderAbsent() throws Exception {
final HttpContext context = new BasicHttpContext(null);
final BasicClassicHttpRequest request = new BasicClassicHttpRequest(Method.GET, "/");
final RequestValidateHost interceptor = new RequestValidateHost();
- interceptor.process(request, request.getEntity(), context);
+ Assert.assertThrows(ProtocolException.class, () ->
+ interceptor.process(request, request.getEntity(), context));
}
- @Test(expected = ProtocolException.class)
+ @Test
public void testRequestHttp11MultipleHostHeaders() throws Exception {
final HttpContext context = new BasicHttpContext(null);
final BasicClassicHttpRequest request = new BasicClassicHttpRequest(Method.GET, "/");
request.addHeader(HttpHeaders.HOST, "blah");
request.addHeader(HttpHeaders.HOST, "blah");
final RequestValidateHost interceptor = new RequestValidateHost();
- interceptor.process(request, request.getEntity(), context);
+ Assert.assertThrows(ProtocolException.class, () ->
+ interceptor.process(request, request.getEntity(), context));
}
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestUriPatternMatcher.java b/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestUriPatternMatcher.java
index ac77aee..cba39c8 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestUriPatternMatcher.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestUriPatternMatcher.java
@@ -76,10 +76,11 @@ public class TestUriPatternMatcher {
Assert.assertNull(h);
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testRegisterNull() throws Exception {
final LookupRegistry<Object> matcher = new UriPatternMatcher<>();
- matcher.register(null, null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ matcher.register(null, null));
}
@Test
@@ -154,16 +155,18 @@ public class TestUriPatternMatcher {
Assert.assertTrue(h1 == h);
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testRegisterInvalidInput() throws Exception {
final LookupRegistry<Object> matcher = new UriPatternMatcher<>();
- matcher.register(null, null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ matcher.register(null, null));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testLookupInvalidInput() throws Exception {
final LookupRegistry<Object> matcher = new UriPatternMatcher<>();
- matcher.lookup(null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ matcher.lookup(null));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestUriPatternOrderedMatcher.java b/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestUriPatternOrderedMatcher.java
index f9b575a..1a79351 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestUriPatternOrderedMatcher.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestUriPatternOrderedMatcher.java
@@ -76,10 +76,11 @@ public class TestUriPatternOrderedMatcher {
Assert.assertNull(h);
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testRegisterNull() throws Exception {
final LookupRegistry<Object> matcher = new UriPatternOrderedMatcher<>();
- matcher.register(null, null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ matcher.register(null, null));
}
@Test
@@ -154,16 +155,18 @@ public class TestUriPatternOrderedMatcher {
Assert.assertTrue(h1 == h);
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testRegisterInvalidInput() throws Exception {
final LookupRegistry<Object> matcher = new UriPatternOrderedMatcher<>();
- matcher.register(null, null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ matcher.register(null, null));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testLookupInvalidInput() throws Exception {
final LookupRegistry<Object> matcher = new UriPatternOrderedMatcher<>();
- matcher.lookup(null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ matcher.lookup(null));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestUriRegexMatcher.java b/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestUriRegexMatcher.java
index 56ca167..4c71a66 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestUriRegexMatcher.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestUriRegexMatcher.java
@@ -60,10 +60,11 @@ public class TestUriRegexMatcher {
Assert.assertNull(h);
}
- @Test(expected = NullPointerException.class)
+ @Test
public void testRegisterNull() throws Exception {
final LookupRegistry<Object> matcher = new UriRegexMatcher<>();
- matcher.register(null, null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ matcher.register(null, null));
}
@Test
@@ -196,16 +197,18 @@ public class TestUriRegexMatcher {
Assert.assertTrue(h1 == h);
}
- @Test(expected = NullPointerException.class)
+ @Test
public void testRegisterInvalidInput() throws Exception {
final LookupRegistry<Object> matcher = new UriRegexMatcher<>();
- matcher.register(null, null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ matcher.register(null, null));
}
- @Test(expected = NullPointerException.class)
+ @Test
public void testLookupInvalidInput() throws Exception {
final LookupRegistry<Object> matcher = new UriRegexMatcher<>();
- matcher.lookup(null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ matcher.lookup(null));
}
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/ssl/TestTlsVersionParser.java b/httpcore5/src/test/java/org/apache/hc/core5/http/ssl/TestTlsVersionParser.java
index 7966ae2..35545fb 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/ssl/TestTlsVersionParser.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/ssl/TestTlsVersionParser.java
@@ -32,6 +32,7 @@ import org.apache.hc.core5.http.ProtocolVersion;
import org.apache.hc.core5.util.Tokenizer;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
+import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -64,29 +65,34 @@ public class TestTlsVersionParser {
MatcherAssert.assertThat(cursor.getPos(), CoreMatchers.equalTo(8));
}
- @Test(expected = ParseException.class)
+ @Test
public void testParseFailure1() throws Exception {
- impl.parse("Tlsv1");
+ Assert.assertThrows(ParseException.class, () ->
+ impl.parse("Tlsv1"));
}
- @Test(expected = ParseException.class)
+ @Test
public void testParseFailure2() throws Exception {
- impl.parse("TLSV1");
+ Assert.assertThrows(ParseException.class, () ->
+ impl.parse("TLSV1"));
}
- @Test(expected = ParseException.class)
+ @Test
public void testParseFailure3() throws Exception {
- impl.parse("TLSv");
+ Assert.assertThrows(ParseException.class, () ->
+ impl.parse("TLSv"));
}
- @Test(expected = ParseException.class)
+ @Test
public void testParseFailure4() throws Exception {
- impl.parse("TLSv1A");
+ Assert.assertThrows(ParseException.class, () ->
+ impl.parse("TLSv1A"));
}
- @Test(expected = ParseException.class)
+ @Test
public void testParseFailure5() throws Exception {
- impl.parse("TLSv1.A");
+ Assert.assertThrows(ParseException.class, () ->
+ impl.parse("TLSv1.A"));
}
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/pool/TestLaxConnPool.java b/httpcore5/src/test/java/org/apache/hc/core5/pool/TestLaxConnPool.java
index e2fd951..87948dd 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/pool/TestLaxConnPool.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/pool/TestLaxConnPool.java
@@ -111,10 +111,11 @@ public class TestLaxConnPool {
}
}
- @Test(expected = IllegalStateException.class)
+ @Test
public void testReleaseUnknownEntry() throws Exception {
final LaxConnPool<String, HttpConnection> pool = new LaxConnPool<>(2);
- pool.release(new PoolEntry<>("somehost"), true);
+ Assert.assertThrows(IllegalStateException.class, () ->
+ pool.release(new PoolEntry<>("somehost"), true));
}
@Test
@@ -372,10 +373,11 @@ public class TestLaxConnPool {
Assert.assertEquals(0, totals.getLeased());
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testGetStatsInvalid() throws Exception {
final LaxConnPool<String, HttpConnection> pool = new LaxConnPool<>(2);
- pool.getStats(null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ pool.getStats(null));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/pool/TestPoolEntry.java b/httpcore5/src/test/java/org/apache/hc/core5/pool/TestPoolEntry.java
index 17d887f..8573215 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/pool/TestPoolEntry.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/pool/TestPoolEntry.java
@@ -71,9 +71,10 @@ public class TestPoolEntry {
Assert.assertEquals(Deadline.MIN_VALUE, entry1.getExpiryDeadline());
}
- @Test(expected = NullPointerException.class)
+ @Test
public void testNullConstructor() throws Exception {
- new PoolEntry<String, HttpConnection>(null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ new PoolEntry<String, HttpConnection>(null));
}
@Test
@@ -107,11 +108,12 @@ public class TestPoolEntry {
Assert.assertEquals(validityDeadline, entry2.getExpiryDeadline());
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testInvalidExpiry() throws Exception {
final PoolEntry<String, HttpConnection> entry = new PoolEntry<>(
"route1", TimeValue.of(0L, TimeUnit.MILLISECONDS), currentTimeSupplier);
- entry.updateExpiry(null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ entry.updateExpiry(null));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/pool/TestStrictConnPool.java b/httpcore5/src/test/java/org/apache/hc/core5/pool/TestStrictConnPool.java
index 1a62cf0..47ebf72 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/pool/TestStrictConnPool.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/pool/TestStrictConnPool.java
@@ -125,10 +125,11 @@ public class TestStrictConnPool {
}
}
- @Test(expected = IllegalStateException.class)
+ @Test
public void testReleaseUnknownEntry() throws Exception {
final StrictConnPool<String, HttpConnection> pool = new StrictConnPool<>(2, 2);
- pool.release(new PoolEntry<>("somehost"), true);
+ Assert.assertThrows(IllegalStateException.class, () ->
+ pool.release(new PoolEntry<>("somehost"), true));
}
@Test
@@ -597,10 +598,11 @@ public class TestStrictConnPool {
Assert.assertEquals(0, totals.getLeased());
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testGetStatsInvalid() throws Exception {
final StrictConnPool<String, HttpConnection> pool = new StrictConnPool<>(2, 2);
- pool.getStats(null);
+ Assert.assertThrows(NullPointerException.class, () ->
+ pool.getStats(null));
}
@Test
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/reactor/IOWorkersTest.java b/httpcore5/src/test/java/org/apache/hc/core5/reactor/IOWorkersTest.java
index 7deccb1..fa635fc 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/reactor/IOWorkersTest.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/reactor/IOWorkersTest.java
@@ -26,17 +26,17 @@
*/
package org.apache.hc.core5.reactor;
-import org.junit.Test;
-
import static org.mockito.Mockito.mock;
+import org.junit.Test;
+
public class IOWorkersTest {
@Test
public void testIndexOverflow() {
final SingleCoreIOReactor reactor = new SingleCoreIOReactor(null, mock(IOEventHandlerFactory.class), IOReactorConfig.DEFAULT, null, null, null);
final IOWorkers.Selector selector = IOWorkers.newSelector(new SingleCoreIOReactor[]{reactor, reactor, reactor});
- for (long i = 0; i < (long) Integer.MAX_VALUE + 10; i++) {
+ for (long i = Integer.MAX_VALUE - 10; i < (long) Integer.MAX_VALUE + 10; i++) {
selector.next();
}
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/ssl/TestSSLContextBuilder.java b/httpcore5/src/test/java/org/apache/hc/core5/ssl/TestSSLContextBuilder.java
index 819fec3..905c850 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/ssl/TestSSLContextBuilder.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/ssl/TestSSLContextBuilder.java
@@ -52,9 +52,9 @@ import java.util.concurrent.atomic.AtomicReference;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException;
+import javax.net.ssl.SSLProtocolException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
@@ -66,9 +66,7 @@ import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.BeforeClass;
-import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
/**
* Unit tests for {@link SSLContextBuilder}.
@@ -86,9 +84,6 @@ public class TestSSLContextBuilder {
Assume.assumeTrue("Java version must be 8 or greater", ReflectionUtils.determineJRELevel() >= 8);
}
- @Rule
- public final ExpectedException thrown = ExpectedException.none();
-
private static final Timeout TIMEOUT = Timeout.ofSeconds(5);
private ExecutorService executorService;
@@ -118,7 +113,7 @@ public class TestSSLContextBuilder {
.build();
Assert.assertNotNull(sslContext);
Assert.assertEquals("TLS", sslContext.getProtocol());
- Assert.assertEquals(PROVIDER_SUN_JSSE, sslContext.getProvider().getName());
+ Assert.assertEquals(PROVIDER_SUN_JSSE, sslContext.getProvider().getName());
}
@Test
@@ -135,7 +130,7 @@ public class TestSSLContextBuilder {
.build();
Assert.assertNotNull(sslContext);
Assert.assertEquals("TLS", sslContext.getProtocol());
- Assert.assertEquals(PROVIDER_SUN_JSSE, sslContext.getProvider().getName());
+ Assert.assertEquals(PROVIDER_SUN_JSSE, sslContext.getProvider().getName());
}
@Test
@@ -155,36 +150,39 @@ public class TestSSLContextBuilder {
new SSLContextBuilder().build();
}
- @Test(expected=NoSuchAlgorithmException.class)
+ @Test
public void testBuildNoSuchKeyManagerFactoryAlgorithm() throws Exception {
final URL resource1 = getResource("/test-keypasswd.p12");
final String storePassword = "nopassword";
final String keyPassword = "password";
- SSLContextBuilder.create()
- .setKeyManagerFactoryAlgorithm(" BAD ")
- .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray())
- .build();
+ Assert.assertThrows(NoSuchAlgorithmException.class, () ->
+ SSLContextBuilder.create()
+ .setKeyManagerFactoryAlgorithm(" BAD ")
+ .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray())
+ .build());
}
- @Test(expected= KeyStoreException.class)
+ @Test
public void testBuildNoSuchKeyStoreType() throws Exception {
final URL resource1 = getResource("/test-keypasswd.p12");
final String storePassword = "nopassword";
final String keyPassword = "password";
- SSLContextBuilder.create()
- .setKeyStoreType(" BAD ")
- .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray())
- .build();
+ Assert.assertThrows(KeyStoreException.class, () ->
+ SSLContextBuilder.create()
+ .setKeyStoreType(" BAD ")
+ .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray())
+ .build());
}
- @Test(expected=NoSuchAlgorithmException.class)
+ @Test
public void testBuildNoSuchTrustManagerFactoryAlgorithm() throws Exception {
final URL resource1 = getResource("/test-keypasswd.p12");
final String storePassword = "nopassword";
- SSLContextBuilder.create()
- .setTrustManagerFactoryAlgorithm(" BAD ")
- .loadTrustMaterial(resource1, storePassword.toCharArray())
- .build();
+ Assert.assertThrows(NoSuchAlgorithmException.class, () ->
+ SSLContextBuilder.create()
+ .setTrustManagerFactoryAlgorithm(" BAD ")
+ .loadTrustMaterial(resource1, storePassword.toCharArray())
+ .build());
}
@Test
@@ -192,11 +190,11 @@ public class TestSSLContextBuilder {
final URL resource1 = getResource("/test-server.p12");
final String storePassword = "nopassword";
final String keyPassword = "nopassword";
- final SSLContext sslContext=SSLContextBuilder.create()
+ final SSLContext sslContext = SSLContextBuilder.create()
.setProvider(Security.getProvider(PROVIDER_SUN_JSSE))
.loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray())
.build();
- Assert.assertEquals(PROVIDER_SUN_JSSE, sslContext.getProvider().getName());
+ Assert.assertEquals(PROVIDER_SUN_JSSE, sslContext.getProvider().getName());
}
@Test
@@ -204,25 +202,23 @@ public class TestSSLContextBuilder {
final URL resource1 = getResource("/test-server.p12");
final String storePassword = "nopassword";
final String keyPassword = "nopassword";
- final SSLContext sslContext=SSLContextBuilder.create()
+ final SSLContext sslContext = SSLContextBuilder.create()
.setProvider(PROVIDER_SUN_JSSE)
.loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray())
.build();
- Assert.assertEquals(PROVIDER_SUN_JSSE, sslContext.getProvider().getName());
+ Assert.assertEquals(PROVIDER_SUN_JSSE, sslContext.getProvider().getName());
}
@Test
public void testKeyWithAlternatePasswordInvalid() throws Exception {
-
- thrown.expect(UnrecoverableKeyException.class);
-
final URL resource1 = getResource("/test-keypasswd.p12");
final String storePassword = "nopassword";
final String keyPassword = "!password";
- SSLContextBuilder.create()
- .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray())
- .loadTrustMaterial(resource1, storePassword.toCharArray())
- .build();
+ Assert.assertThrows(UnrecoverableKeyException.class, () ->
+ SSLContextBuilder.create()
+ .loadKeyMaterial(resource1, storePassword.toCharArray(), keyPassword.toCharArray())
+ .loadTrustMaterial(resource1, storePassword.toCharArray())
+ .build());
}
@Test
@@ -267,8 +263,6 @@ public class TestSSLContextBuilder {
@Test
public void testSSLHandshakeServerNotTrusted() throws Exception {
- thrown.expect(IOException.class);
-
final URL resource1 = getResource("/test-server.p12");
final String storePassword = "nopassword";
final String keyPassword = "nopassword";
@@ -295,7 +289,7 @@ public class TestSSLContextBuilder {
try (final SSLSocket clientSocket = (SSLSocket) clientSslContext.getSocketFactory().createSocket()) {
clientSocket.connect(new InetSocketAddress("localhost", localPort), TIMEOUT.toMillisecondsIntBound());
clientSocket.setSoTimeout(TIMEOUT.toMillisecondsIntBound());
- clientSocket.startHandshake();
+ Assert.assertThrows(IOException.class, clientSocket::startHandshake);
}
}
@@ -420,8 +414,6 @@ public class TestSSLContextBuilder {
@Test
public void testSSLHandshakeClientUnauthenticatedError() throws Exception {
- thrown.expect(IOException.class);
-
final URL resource1 = getResource("/test-server.p12");
final String storePassword = "nopassword";
final String keyPassword = "nopassword";
@@ -450,9 +442,11 @@ public class TestSSLContextBuilder {
try (final SSLSocket clientSocket = (SSLSocket) clientSslContext.getSocketFactory().createSocket()) {
clientSocket.connect(new InetSocketAddress("localhost", localPort), TIMEOUT.toMillisecondsIntBound());
clientSocket.setSoTimeout(TIMEOUT.toMillisecondsIntBound());
- clientSocket.startHandshake();
- final InputStream inputStream = clientSocket.getInputStream();
- Assert.assertEquals(-1, inputStream.read());
+ Assert.assertThrows(IOException.class, () -> {
+ clientSocket.startHandshake();
+ final InputStream inputStream = clientSocket.getInputStream();
+ inputStream.read();
+ });
}
}
@@ -555,12 +549,6 @@ public class TestSSLContextBuilder {
@Test
public void testSSLHandshakeProtocolMismatch1() throws Exception {
- if (isWindows()) {
- thrown.expect(IOException.class);
- } else {
- thrown.expect(SSLHandshakeException.class);
- }
-
final URL resource1 = getResource("/test-server.p12");
final String storePassword = "nopassword";
final String keyPassword = "nopassword";
@@ -594,18 +582,16 @@ public class TestSSLContextBuilder {
clientSocket.setEnabledProtocols(new String[] {"SSLv3"} );
clientSocket.connect(new InetSocketAddress("localhost", localPort), TIMEOUT.toMillisecondsIntBound());
clientSocket.setSoTimeout(TIMEOUT.toMillisecondsIntBound());
- clientSocket.startHandshake();
+ if (isWindows()) {
+ Assert.assertThrows(IOException.class, clientSocket::startHandshake);
+ } else {
+ Assert.assertThrows(SSLHandshakeException.class, clientSocket::startHandshake);
+ }
}
}
@Test
public void testSSLHandshakeProtocolMismatch2() throws Exception {
- if (isWindows()) {
- thrown.expect(IOException.class);
- } else {
- thrown.expect(SSLException.class);
- }
-
final URL resource1 = getResource("/test-server.p12");
final String storePassword = "nopassword";
final String keyPassword = "nopassword";
@@ -637,12 +623,14 @@ public class TestSSLContextBuilder {
final Set<String> supportedClientProtocols = new LinkedHashSet<>(
Arrays.asList(clientSocket.getSupportedProtocols()));
Assert.assertTrue(supportedClientProtocols.contains("TLSv1"));
- clientSocket.setEnabledProtocols(new String[] { "TLSv1" });
+ clientSocket.setEnabledProtocols(new String[]{"TLSv1"});
clientSocket.connect(new InetSocketAddress("localhost", localPort), TIMEOUT.toMillisecondsIntBound());
clientSocket.setSoTimeout(TIMEOUT.toMillisecondsIntBound());
- clientSocket.startHandshake();
- final InputStream inputStream = clientSocket.getInputStream();
- Assert.assertEquals(-1, inputStream.read());
+ if (isWindows()) {
+ Assert.assertThrows(IOException.class, clientSocket::startHandshake);
+ } else {
+ Assert.assertThrows(SSLProtocolException.class, clientSocket::startHandshake);
+ }
}
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/util/TestArgs.java b/httpcore5/src/test/java/org/apache/hc/core5/util/TestArgs.java
index c7efa11..89750c7 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/util/TestArgs.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/util/TestArgs.java
@@ -49,9 +49,10 @@ public class TestArgs {
Args.check(true, "All is well");
}
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void testArgCheckFail() {
- Args.check(false, "Oopsie");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.check(false, "Oopsie"));
}
@Test
@@ -60,9 +61,10 @@ public class TestArgs {
Assert.assertSame(stuff, Args.notNull(stuff, "Stuff"));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testArgNotNullFail() {
- Args.notNull(null, "Stuff");
+ Assert.assertThrows(NullPointerException.class, () ->
+ Args.notNull(null, "Stuff"));
}
@Test
@@ -71,29 +73,34 @@ public class TestArgs {
Assert.assertSame(stuff, Args.notEmpty(stuff, "Stuff"));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testArgNotEmptyFail1() {
- Args.notEmpty((String) null, "Stuff");
+ Assert.assertThrows(NullPointerException.class, () ->
+ Args.notEmpty((String) null, "Stuff"));
}
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void testArgNotEmptyFail2() {
- Args.notEmpty("", "Stuff");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.notEmpty("", "Stuff"));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testArgNotBlankFail1() {
- Args.notBlank((String) null, "Stuff");
+ Assert.assertThrows(NullPointerException.class, () ->
+ Args.notBlank((String) null, "Stuff"));
}
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void testArgNotBlankFail2() {
- Args.notBlank("", "Stuff");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.notBlank("", "Stuff"));
}
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void testArgNotBlankFail3() {
- Args.notBlank(" \t \n\r", "Stuff");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.notBlank(" \t \n\r", "Stuff"));
}
@Test
@@ -102,14 +109,16 @@ public class TestArgs {
Assert.assertSame(list, Args.notEmpty(list, "List"));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testArgCollectionNotEmptyFail1() {
- Args.notEmpty((List<?>) null, "List");
+ Assert.assertThrows(NullPointerException.class, () ->
+ Args.notEmpty((List<?>) null, "List"));
}
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void testArgCollectionNotEmptyFail2() {
- Args.notEmpty(Collections.emptyList(), "List");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.notEmpty(Collections.emptyList(), "List"));
}
@Test
@@ -117,14 +126,16 @@ public class TestArgs {
Assert.assertEquals(1, Args.positive(1, "Number"));
}
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void testPositiveIntFail1() {
- Args.positive(-1, "Number");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.positive(-1, "Number"));
}
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void testPositiveIntFail2() {
- Args.positive(0, "Number");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.positive(0, "Number"));
}
@Test
@@ -137,14 +148,16 @@ public class TestArgs {
final Timeout timeout = Timeout.parse("1200 MILLISECONDS");
Assert.assertEquals(timeout, Args.positive(timeout, "No Error"));
}
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void testPositiveLongFail1() {
- Args.positive(-1L, "Number");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.positive(-1L, "Number"));
}
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void testPositiveLongFail2() {
- Args.positive(0L, "Number");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.positive(0L, "Number"));
}
@Test
@@ -157,9 +170,10 @@ public class TestArgs {
Assert.assertEquals(0, Args.notNegative(0, "Number"));
}
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void testNotNegativeIntFail1() {
- Args.notNegative(-1, "Number");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.notNegative(-1, "Number"));
}
@Test
@@ -172,65 +186,76 @@ public class TestArgs {
Assert.assertEquals(0L, Args.notNegative(0L, "Number"));
}
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void testNotNegativeLongFail1() {
- Args.notNegative(-1L, "Number");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.notNegative(-1L, "Number"));
}
- //
+ @Test
public void testIntSmallestRangeOK() {
Args.checkRange(0, 0, 0, "Number");
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testIntSmallestRangeFailLow() {
- Args.checkRange(-1, 0, 0, "Number");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.checkRange(-1, 0, 0, "Number"));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testIntRangeFailLow() {
- Args.checkRange(-101, -100, 100, "Number");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.checkRange(-101, -100, 100, "Number"));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testIntRangeFailHigh() {
- Args.checkRange(101, -100, 100, "Number");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.checkRange(101, -100, 100, "Number"));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testIntSmallestRangeFailHigh() {
- Args.checkRange(1, 0, 0, "Number");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.checkRange(1, 0, 0, "Number"));
}
+ @Test
public void testIntFullRangeOK() {
Args.checkRange(0, Integer.MIN_VALUE, Integer.MAX_VALUE, "Number");
}
- //
+ @Test
public void testLongSmallestRangeOK() {
Args.checkRange(0L, 0L, 0L, "Number");
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testLongSmallestRangeFailLow() {
- Args.checkRange(-1L, 0L, 0L, "Number");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.checkRange(-1L, 0L, 0L, "Number"));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testLongRangeFailLow() {
- Args.checkRange(-101L, -100L, 100L, "Number");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.checkRange(-101L, -100L, 100L, "Number"));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testLongRangeFailHigh() {
- Args.checkRange(101L, -100L, 100L, "Number");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.checkRange(101L, -100L, 100L, "Number"));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testLongSmallestRangeFailHigh() {
- Args.checkRange(1L, 0L, 0L, "Number");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.checkRange(1L, 0L, 0L, "Number"));
}
+ @Test
public void testLongFullRangeOK() {
Args.checkRange(0L, Long.MIN_VALUE, Long.MAX_VALUE, "Number");
}
@@ -268,9 +293,10 @@ public class TestArgs {
Assert.assertSame(stuff, Args.containsNoBlanks(stuff, "abg"));
}
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void check() {
- Args.check(false, "Error,", "ABG");
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ Args.check(false, "Error,", "ABG"));
}
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/util/TestAsserts.java b/httpcore5/src/test/java/org/apache/hc/core5/util/TestAsserts.java
index 2bbf1e7..3a8ae32 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/util/TestAsserts.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/util/TestAsserts.java
@@ -27,6 +27,7 @@
package org.apache.hc.core5.util;
+import org.junit.Assert;
import org.junit.Test;
/**
@@ -39,39 +40,46 @@ public class TestAsserts {
Asserts.check(true, "All is well");
}
- @Test(expected=IllegalStateException.class)
+ @Test
public void testExpressionCheckFail() {
- Asserts.check(false, "Oopsie");
+ Assert.assertThrows(IllegalStateException.class, () ->
+ Asserts.check(false, "Oopsie"));
}
- @Test(expected=IllegalStateException.class)
+ @Test
public void testExpressionNotNullFail() {
- Asserts.notNull(null, "Stuff");
+ Assert.assertThrows(IllegalStateException.class, () ->
+ Asserts.notNull(null, "Stuff"));
}
- @Test(expected=IllegalStateException.class)
+ @Test
public void testExpressionNotEmptyFail1() {
- Asserts.notEmpty(null, "Stuff");
+ Assert.assertThrows(IllegalStateException.class, () ->
+ Asserts.notEmpty(null, "Stuff"));
}
- @Test(expected=IllegalStateException.class)
+ @Test
public void testExpressionNotEmptyFail2() {
- Asserts.notEmpty("", "Stuff");
+ Assert.assertThrows(IllegalStateException.class, () ->
+ Asserts.notEmpty("", "Stuff"));
}
- @Test(expected=IllegalStateException.class)
+ @Test
public void testExpressionNotEmptyBlank1() {
- Asserts.notBlank(null, "Stuff");
+ Assert.assertThrows(IllegalStateException.class, () ->
+ Asserts.notBlank(null, "Stuff"));
}
- @Test(expected=IllegalStateException.class)
+ @Test
public void testExpressionNotEmptyBlank2() {
- Asserts.notBlank("", "Stuff");
+ Assert.assertThrows(IllegalStateException.class, () ->
+ Asserts.notBlank("", "Stuff"));
}
- @Test(expected=IllegalStateException.class)
+ @Test
public void testExpressionNotBlankFail3() {
- Asserts.notBlank(" \t \n\r", "Stuff");
+ Assert.assertThrows(IllegalStateException.class, () ->
+ Asserts.notBlank(" \t \n\r", "Stuff"));
}
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/util/TestTimeValue.java b/httpcore5/src/test/java/org/apache/hc/core5/util/TestTimeValue.java
index be53eac..0392e4e 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/util/TestTimeValue.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/util/TestTimeValue.java
@@ -113,9 +113,10 @@ public class TestTimeValue {
Assert.assertEquals(30000, TimeValue.ofMinutes(1).divide(2, TimeUnit.MILLISECONDS).toMilliseconds());
}
- @Test(expected = ArithmeticException.class)
+ @Test
public void testDivideBy0() {
- TimeValue.ofMilliseconds(0).divide(0);
+ Assert.assertThrows(ArithmeticException.class, () ->
+ TimeValue.ofMilliseconds(0).divide(0));
}
private void testFactory(final TimeUnit timeUnit) {
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/util/TestTimeout.java b/httpcore5/src/test/java/org/apache/hc/core5/util/TestTimeout.java
index 8afdd2a..21fb15f 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/util/TestTimeout.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/util/TestTimeout.java
@@ -156,9 +156,10 @@ public class TestTimeout {
test(Long.MAX_VALUE);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testNegative1() {
- test(-1);
+ Assert.assertThrows(IllegalArgumentException.class, () ->
+ test(-1));
}
@Test