Use Junit5 for handler module (#11444)

Motivation:

We should aim to use junit5 everywhere

Modifications:

Migrate most of the handler module to use junit5

Result:

Part of #10757
This commit is contained in:
Norman Maurer 2021-07-02 15:06:06 +02:00
parent ef231fda50
commit cb82277d36
42 changed files with 837 additions and 613 deletions

View File

@ -19,14 +19,14 @@ import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise; import io.netty.channel.ChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.net.SocketAddress; import java.net.SocketAddress;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
public class DynamicAddressConnectHandlerTest { public class DynamicAddressConnectHandlerTest {
private static final SocketAddress LOCAL = new SocketAddress() { }; private static final SocketAddress LOCAL = new SocketAddress() { };

View File

@ -32,16 +32,19 @@ import io.netty.resolver.AddressResolver;
import io.netty.resolver.AddressResolverGroup; import io.netty.resolver.AddressResolverGroup;
import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.Promise;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
public class ResolveAddressHandlerTest { public class ResolveAddressHandlerTest {
@ -51,12 +54,12 @@ public class ResolveAddressHandlerTest {
private static EventLoopGroup group; private static EventLoopGroup group;
@BeforeClass @BeforeAll
public static void createEventLoop() { public static void createEventLoop() {
group = new MultithreadEventLoopGroup(LocalHandler.newFactory()); group = new MultithreadEventLoopGroup(LocalHandler.newFactory());
} }
@AfterClass @AfterAll
public static void destroyEventLoop() { public static void destroyEventLoop() {
if (group != null) { if (group != null) {
group.shutdownGracefully(); group.shutdownGracefully();

View File

@ -36,9 +36,9 @@ import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.timeout.IdleStateEvent; import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler; import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.util.Queue; import java.util.Queue;
@ -48,17 +48,21 @@ import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import static java.util.concurrent.TimeUnit.*; import static java.util.concurrent.TimeUnit.*;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
public class FlowControlHandlerTest { public class FlowControlHandlerTest {
private static EventLoopGroup GROUP; private static EventLoopGroup GROUP;
@BeforeClass @BeforeAll
public static void init() { public static void init() {
GROUP = new MultithreadEventLoopGroup(NioHandler.newFactory()); GROUP = new MultithreadEventLoopGroup(NioHandler.newFactory());
} }
@AfterClass @AfterAll
public static void destroy() { public static void destroy() {
GROUP.shutdownGracefully(); GROUP.shutdownGracefully();
} }

View File

@ -18,11 +18,15 @@ package io.netty.handler.flush;
import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class FlushConsolidationHandlerTest { public class FlushConsolidationHandlerTest {
@ -124,10 +128,10 @@ public class FlushConsolidationHandlerTest {
assertFalse(channel.finish()); assertFalse(channel.finish());
} }
@Test(expected = IllegalStateException.class) @Test
public void testFlushViaException() { public void testFlushViaException() {
final AtomicInteger flushCount = new AtomicInteger(); final AtomicInteger flushCount = new AtomicInteger();
EmbeddedChannel channel = newChannel(flushCount, false); final EmbeddedChannel channel = newChannel(flushCount, false);
// Simulate read loop; // Simulate read loop;
channel.pipeline().fireChannelRead(1L); channel.pipeline().fireChannelRead(1L);
assertEquals(0, flushCount.get()); assertEquals(0, flushCount.get());
@ -136,7 +140,12 @@ public class FlushConsolidationHandlerTest {
assertEquals(1, flushCount.get()); assertEquals(1, flushCount.get());
assertEquals(1L, (long) channel.readOutbound()); assertEquals(1L, (long) channel.readOutbound());
assertNull(channel.readOutbound()); assertNull(channel.readOutbound());
channel.finish(); assertThrows(IllegalStateException.class, new Executable() {
@Override
public void execute() throws Throwable {
channel.finish();
}
});
} }
@Test @Test

View File

@ -22,16 +22,17 @@ import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.internal.SocketUtils; import io.netty.util.internal.SocketUtils;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
public class IpSubnetFilterTest { public class IpSubnetFilterTest {
@ -109,16 +110,16 @@ public class IpSubnetFilterTest {
protected ChannelFuture channelRejected(ChannelHandlerContext ctx, InetSocketAddress remoteAddress) { protected ChannelFuture channelRejected(ChannelHandlerContext ctx, InetSocketAddress remoteAddress) {
assertTrue(ctx.channel().isActive()); assertTrue(ctx.channel().isActive());
assertTrue(ctx.channel().isWritable()); assertTrue(ctx.channel().isWritable());
Assert.assertEquals("192.168.57.1", remoteAddress.getHostName()); assertEquals("192.168.57.1", remoteAddress.getHostName());
return ctx.writeAndFlush(Unpooled.wrappedBuffer(message)); return ctx.writeAndFlush(Unpooled.wrappedBuffer(message));
} }
}; };
EmbeddedChannel chDeny = newEmbeddedInetChannel("192.168.57.1", denyHandler); EmbeddedChannel chDeny = newEmbeddedInetChannel("192.168.57.1", denyHandler);
ByteBuf out = chDeny.readOutbound(); ByteBuf out = chDeny.readOutbound();
Assert.assertEquals(7, out.readableBytes()); assertEquals(7, out.readableBytes());
for (byte i = 1; i <= 7; i++) { for (byte i = 1; i <= 7; i++) {
Assert.assertEquals(i, out.readByte()); assertEquals(i, out.readByte());
} }
assertFalse(chDeny.isActive()); assertFalse(chDeny.isActive());
assertFalse(chDeny.isOpen()); assertFalse(chDeny.isOpen());
@ -126,7 +127,7 @@ public class IpSubnetFilterTest {
RuleBasedIpFilter allowHandler = new RuleBasedIpFilter(filter0) { RuleBasedIpFilter allowHandler = new RuleBasedIpFilter(filter0) {
@Override @Override
protected ChannelFuture channelRejected(ChannelHandlerContext ctx, InetSocketAddress remoteAddress) { protected ChannelFuture channelRejected(ChannelHandlerContext ctx, InetSocketAddress remoteAddress) {
Assert.fail(); fail();
return null; return null;
} }
}; };

View File

@ -18,8 +18,7 @@ package io.netty.handler.ipfilter;
import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandler;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.internal.SocketUtils; import io.netty.util.internal.SocketUtils;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
@ -29,6 +28,9 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class UniqueIpFilterTest { public class UniqueIpFilterTest {
@Test @Test
@ -42,8 +44,8 @@ public class UniqueIpFilterTest {
Future<EmbeddedChannel> future2 = newChannelAsync(barrier, executorService, ipFilter); Future<EmbeddedChannel> future2 = newChannelAsync(barrier, executorService, ipFilter);
EmbeddedChannel ch1 = future1.get(); EmbeddedChannel ch1 = future1.get();
EmbeddedChannel ch2 = future2.get(); EmbeddedChannel ch2 = future2.get();
Assert.assertTrue(ch1.isActive() || ch2.isActive()); assertTrue(ch1.isActive() || ch2.isActive());
Assert.assertFalse(ch1.isActive() && ch2.isActive()); assertFalse(ch1.isActive() && ch2.isActive());
barrier.reset(); barrier.reset();
ch1.close().await(); ch1.close().await();

View File

@ -26,11 +26,13 @@ import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelMetadata; import io.netty.channel.ChannelMetadata;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import org.junit.After;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.Before; import org.junit.jupiter.api.AfterEach;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.mockito.ArgumentMatcher; import org.mockito.ArgumentMatcher;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -44,8 +46,12 @@ import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.sameInstance; import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.slf4j.Logger.ROOT_LOGGER_NAME; import static org.slf4j.Logger.ROOT_LOGGER_NAME;
/** /**
@ -64,7 +70,7 @@ public class LoggingHandlerTest {
*/ */
private Appender<ILoggingEvent> appender; private Appender<ILoggingEvent> appender;
@BeforeClass @BeforeAll
public static void beforeClass() { public static void beforeClass() {
for (Iterator<Appender<ILoggingEvent>> i = rootLogger.iteratorForAppenders(); i.hasNext();) { for (Iterator<Appender<ILoggingEvent>> i = rootLogger.iteratorForAppenders(); i.hasNext();) {
Appender<ILoggingEvent> a = i.next(); Appender<ILoggingEvent> a = i.next();
@ -75,29 +81,34 @@ public class LoggingHandlerTest {
Unpooled.buffer(); Unpooled.buffer();
} }
@AfterClass @AfterAll
public static void afterClass() { public static void afterClass() {
for (Appender<ILoggingEvent> a: oldAppenders) { for (Appender<ILoggingEvent> a: oldAppenders) {
rootLogger.addAppender(a); rootLogger.addAppender(a);
} }
} }
@Before @BeforeEach
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void setup() { public void setup() {
appender = mock(Appender.class); appender = mock(Appender.class);
logger.addAppender(appender); logger.addAppender(appender);
} }
@After @AfterEach
public void teardown() { public void teardown() {
logger.detachAppender(appender); logger.detachAppender(appender);
} }
@Test(expected = NullPointerException.class) @Test
public void shouldNotAcceptNullLogLevel() { public void shouldNotAcceptNullLogLevel() {
LogLevel level = null; assertThrows(NullPointerException.class, new Executable() {
new LoggingHandler(level); @Override
public void execute() throws Throwable {
LogLevel level = null;
new LoggingHandler(level);
}
});
} }
@Test @Test

View File

@ -29,14 +29,14 @@ import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel; import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import io.netty.util.NetUtil; import io.netty.util.NetUtil;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.net.Inet4Address; import java.net.Inet4Address;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import static org.junit.Assert.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
public class PcapWriteHandlerTest { public class PcapWriteHandlerTest {

View File

@ -20,7 +20,8 @@ import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.DecoderException; import io.netty.handler.codec.DecoderException;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
@ -30,13 +31,13 @@ import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLHandshakeException;
import static io.netty.handler.ssl.CloseNotifyTest.assertCloseNotify; import static io.netty.handler.ssl.CloseNotifyTest.assertCloseNotify;
import static org.junit.Assert.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
public class ApplicationProtocolNegotiationHandlerTest { public class ApplicationProtocolNegotiationHandlerTest {
@ -85,7 +86,7 @@ public class ApplicationProtocolNegotiationHandlerTest {
assertTrue(configureCalled.get()); assertTrue(configureCalled.get());
} }
@Test(expected = IllegalStateException.class) @Test
public void testHandshakeSuccessButNoSslHandler() { public void testHandshakeSuccessButNoSslHandler() {
ChannelHandler alpnHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) { ChannelHandler alpnHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {
@Override @Override
@ -93,13 +94,15 @@ public class ApplicationProtocolNegotiationHandlerTest {
fail(); fail();
} }
}; };
EmbeddedChannel channel = new EmbeddedChannel(alpnHandler); final EmbeddedChannel channel = new EmbeddedChannel(alpnHandler);
try { channel.pipeline().fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS);
channel.pipeline().fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS); assertNull(channel.pipeline().context(alpnHandler));
} finally { assertThrows(IllegalStateException.class, new Executable() {
assertNull(channel.pipeline().context(alpnHandler)); @Override
assertFalse(channel.finishAndReleaseAll()); public void execute() throws Throwable {
} channel.finishAndReleaseAll();
}
});
} }
@Test @Test

View File

@ -36,6 +36,10 @@ import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate; import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.Promise;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@ -48,63 +52,39 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngine;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/** /**
* The purpose of this unit test is to act as a canary and catch changes in supported cipher suites. * The purpose of this unit test is to act as a canary and catch changes in supported cipher suites.
*/ */
@RunWith(Parameterized.class)
public class CipherSuiteCanaryTest { public class CipherSuiteCanaryTest {
private static EventLoopGroup GROUP; private static EventLoopGroup GROUP;
private static SelfSignedCertificate CERT; private static SelfSignedCertificate CERT;
@Parameters(name = "{index}: serverSslProvider = {0}, clientSslProvider = {1}, rfcCipherName = {2}, delegate = {3}") static Collection<Object[]> parameters() {
public static Collection<Object[]> parameters() {
List<Object[]> dst = new ArrayList<>(); List<Object[]> dst = new ArrayList<>();
dst.addAll(expand("TLS_DHE_RSA_WITH_AES_128_GCM_SHA256")); // DHE-RSA-AES128-GCM-SHA256 dst.addAll(expand("TLS_DHE_RSA_WITH_AES_128_GCM_SHA256")); // DHE-RSA-AES128-GCM-SHA256
return dst; return dst;
} }
@BeforeClass @BeforeAll
public static void init() throws Exception { public static void init() throws Exception {
GROUP = new MultithreadEventLoopGroup(LocalHandler.newFactory()); GROUP = new MultithreadEventLoopGroup(LocalHandler.newFactory());
CERT = new SelfSignedCertificate(); CERT = new SelfSignedCertificate();
} }
@AfterClass @AfterAll
public static void destroy() { public static void destroy() {
GROUP.shutdownGracefully(); GROUP.shutdownGracefully();
CERT.delete(); CERT.delete();
} }
private final SslProvider serverSslProvider;
private final SslProvider clientSslProvider;
private final String rfcCipherName;
private final boolean delegate;
public CipherSuiteCanaryTest(SslProvider serverSslProvider, SslProvider clientSslProvider,
String rfcCipherName, boolean delegate) {
this.serverSslProvider = serverSslProvider;
this.clientSslProvider = clientSslProvider;
this.rfcCipherName = rfcCipherName;
this.delegate = delegate;
}
private static void assumeCipherAvailable(SslProvider provider, String cipher) throws NoSuchAlgorithmException { private static void assumeCipherAvailable(SslProvider provider, String cipher) throws NoSuchAlgorithmException {
boolean cipherSupported = false; boolean cipherSupported = false;
if (provider == SslProvider.JDK) { if (provider == SslProvider.JDK) {
@ -118,7 +98,7 @@ public class CipherSuiteCanaryTest {
} else { } else {
cipherSupported = OpenSsl.isCipherSuiteAvailable(cipher); cipherSupported = OpenSsl.isCipherSuiteAvailable(cipher);
} }
Assume.assumeTrue("Unsupported cipher: " + cipher, cipherSupported); assumeTrue(cipherSupported, "Unsupported cipher: " + cipher);
} }
private static SslHandler newSslHandler(SslContext sslCtx, ByteBufAllocator allocator, Executor executor) { private static SslHandler newSslHandler(SslContext sslCtx, ByteBufAllocator allocator, Executor executor) {
@ -129,8 +109,11 @@ public class CipherSuiteCanaryTest {
} }
} }
@Test @ParameterizedTest(
public void testHandshake() throws Exception { name = "{index}: serverSslProvider = {0}, clientSslProvider = {1}, rfcCipherName = {2}, delegate = {3}")
@MethodSource("parameters")
public void testHandshake(SslProvider serverSslProvider, SslProvider clientSslProvider,
String rfcCipherName, boolean delegate) throws Exception {
// Check if the cipher is supported at all which may not be the case for various JDK versions and OpenSSL API // Check if the cipher is supported at all which may not be the case for various JDK versions and OpenSSL API
// implementations. // implementations.
assumeCipherAvailable(serverSslProvider, rfcCipherName); assumeCipherAvailable(serverSslProvider, rfcCipherName);
@ -231,8 +214,8 @@ public class CipherSuiteCanaryTest {
client.writeAndFlush(Unpooled.wrappedBuffer(new byte[] {'P', 'I', 'N', 'G'})) client.writeAndFlush(Unpooled.wrappedBuffer(new byte[] {'P', 'I', 'N', 'G'}))
.syncUninterruptibly(); .syncUninterruptibly();
assertTrue("client timeout", clientPromise.await(5L, TimeUnit.SECONDS)); assertTrue(clientPromise.await(5L, TimeUnit.SECONDS), "client timeout");
assertTrue("server timeout", serverPromise.await(5L, TimeUnit.SECONDS)); assertTrue(serverPromise.await(5L, TimeUnit.SECONDS), "server timeout");
clientPromise.sync(); clientPromise.sync();
serverPromise.sync(); serverPromise.sync();

View File

@ -18,12 +18,13 @@ package io.netty.handler.ssl;
import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory; import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance; import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class CipherSuiteConverterTest { public class CipherSuiteConverterTest {

View File

@ -22,14 +22,15 @@ import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate; import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.Test; import org.junit.jupiter.api.Timeout;
import org.junit.runner.RunWith; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.runners.Parameterized; import org.junit.jupiter.params.provider.MethodSource;
import java.util.Collection; import java.util.Collection;
import java.util.Queue; import java.util.Queue;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSession;
@ -47,9 +48,8 @@ import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue;
@RunWith(Parameterized.class)
public class CloseNotifyTest { public class CloseNotifyTest {
private static final UnpooledByteBufAllocator ALLOC = UnpooledByteBufAllocator.DEFAULT; private static final UnpooledByteBufAllocator ALLOC = UnpooledByteBufAllocator.DEFAULT;
@ -60,16 +60,7 @@ public class CloseNotifyTest {
} }
}; };
private final SslProvider provider; static Collection<Object[]> data() {
private final String protocol;
public CloseNotifyTest(SslProvider provider, String protocol) {
this.provider = provider;
this.protocol = protocol;
}
@Parameterized.Parameters(name = "{index}: provider={0}, protocol={1}")
public static Collection<Object[]> data() {
return asList(new Object[][] { return asList(new Object[][] {
{ SslProvider.JDK, PROTOCOL_TLS_V1_2 }, { SslProvider.JDK, PROTOCOL_TLS_V1_2 },
{ SslProvider.JDK, PROTOCOL_TLS_V1_3 }, { SslProvider.JDK, PROTOCOL_TLS_V1_3 },
@ -78,9 +69,11 @@ public class CloseNotifyTest {
}); });
} }
@Test(timeout = 5000) @ParameterizedTest(name = "{index}: provider={0}, protocol={1}")
public void eventsOrder() throws Exception { @Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
assumeTrue("OpenSSL is not available", provider != SslProvider.OPENSSL || OpenSsl.isAvailable()); @MethodSource("data")
public void eventsOrder(SslProvider provider, String protocol) throws Exception {
assumeTrue(provider != SslProvider.OPENSSL || OpenSsl.isAvailable(), "OpenSSL is not available");
if (PROTOCOL_TLS_V1_3.equals(protocol)) { if (PROTOCOL_TLS_V1_3.equals(protocol)) {
// Ensure we support TLSv1.3 // Ensure we support TLSv1.3
@ -89,8 +82,8 @@ public class CloseNotifyTest {
BlockingQueue<Object> clientEventQueue = new LinkedBlockingQueue<Object>(); BlockingQueue<Object> clientEventQueue = new LinkedBlockingQueue<Object>();
BlockingQueue<Object> serverEventQueue = new LinkedBlockingQueue<Object>(); BlockingQueue<Object> serverEventQueue = new LinkedBlockingQueue<Object>();
EmbeddedChannel clientChannel = initChannel(true, clientEventQueue); EmbeddedChannel clientChannel = initChannel(provider, protocol, true, clientEventQueue);
EmbeddedChannel serverChannel = initChannel(false, serverEventQueue); EmbeddedChannel serverChannel = initChannel(provider, protocol, false, serverEventQueue);
try { try {
// handshake: // handshake:
@ -119,7 +112,7 @@ public class CloseNotifyTest {
assertThat(clientEventQueue.poll(), instanceOf(SslCloseCompletionEvent.class)); assertThat(clientEventQueue.poll(), instanceOf(SslCloseCompletionEvent.class));
// make sure client automatically responds with close_notify: // make sure client automatically responds with close_notify:
if (!jdkTls13()) { if (!jdkTls13(provider, protocol)) {
// JDK impl of TLSv1.3 does not automatically generate "close_notify" in response to the received // JDK impl of TLSv1.3 does not automatically generate "close_notify" in response to the received
// "close_notify" alert. This is a legit behavior according to the spec: // "close_notify" alert. This is a legit behavior according to the spec:
// https://tools.ietf.org/html/rfc8446#section-6.1. Handle it differently: // https://tools.ietf.org/html/rfc8446#section-6.1. Handle it differently:
@ -133,7 +126,7 @@ public class CloseNotifyTest {
} }
} }
if (jdkTls13()) { if (jdkTls13(provider, protocol)) {
assertCloseNotify((ByteBuf) clientChannel.readOutbound()); assertCloseNotify((ByteBuf) clientChannel.readOutbound());
} else { } else {
discardEmptyOutboundBuffers(clientChannel); discardEmptyOutboundBuffers(clientChannel);
@ -150,11 +143,11 @@ public class CloseNotifyTest {
assertThat(serverChannel.releaseOutbound(), is(false)); assertThat(serverChannel.releaseOutbound(), is(false));
} }
private boolean jdkTls13() { private static boolean jdkTls13(SslProvider provider, String protocol) {
return provider == SslProvider.JDK && PROTOCOL_TLS_V1_3.equals(protocol); return provider == SslProvider.JDK && PROTOCOL_TLS_V1_3.equals(protocol);
} }
private EmbeddedChannel initChannel(final boolean useClientMode, private static EmbeddedChannel initChannel(SslProvider provider, String protocol, final boolean useClientMode,
final BlockingQueue<Object> eventQueue) throws Exception { final BlockingQueue<Object> eventQueue) throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate(); SelfSignedCertificate ssc = new SelfSignedCertificate();

View File

@ -17,12 +17,13 @@
package io.netty.handler.ssl; package io.netty.handler.ssl;
import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngine;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class DelegatingSslContextTest { public class DelegatingSslContextTest {
private static final String[] EXPECTED_PROTOCOLS = { SslUtils.PROTOCOL_TLS_V1_1 }; private static final String[] EXPECTED_PROTOCOLS = { SslUtils.PROTOCOL_TLS_V1_1 };
@ -31,10 +32,10 @@ public class DelegatingSslContextTest {
SslContext delegating = newDelegatingSslContext(); SslContext delegating = newDelegatingSslContext();
SSLEngine engine = delegating.newEngine(UnpooledByteBufAllocator.DEFAULT); SSLEngine engine = delegating.newEngine(UnpooledByteBufAllocator.DEFAULT);
Assert.assertArrayEquals(EXPECTED_PROTOCOLS, engine.getEnabledProtocols()); assertArrayEquals(EXPECTED_PROTOCOLS, engine.getEnabledProtocols());
engine = delegating.newEngine(UnpooledByteBufAllocator.DEFAULT, "localhost", 9090); engine = delegating.newEngine(UnpooledByteBufAllocator.DEFAULT, "localhost", 9090);
Assert.assertArrayEquals(EXPECTED_PROTOCOLS, engine.getEnabledProtocols()); assertArrayEquals(EXPECTED_PROTOCOLS, engine.getEnabledProtocols());
} }
@Test @Test
@ -42,10 +43,10 @@ public class DelegatingSslContextTest {
SslContext delegating = newDelegatingSslContext(); SslContext delegating = newDelegatingSslContext();
SslHandler handler = delegating.newHandler(UnpooledByteBufAllocator.DEFAULT); SslHandler handler = delegating.newHandler(UnpooledByteBufAllocator.DEFAULT);
Assert.assertArrayEquals(EXPECTED_PROTOCOLS, handler.engine().getEnabledProtocols()); assertArrayEquals(EXPECTED_PROTOCOLS, handler.engine().getEnabledProtocols());
handler = delegating.newHandler(UnpooledByteBufAllocator.DEFAULT, "localhost", 9090); handler = delegating.newHandler(UnpooledByteBufAllocator.DEFAULT, "localhost", 9090);
Assert.assertArrayEquals(EXPECTED_PROTOCOLS, handler.engine().getEnabledProtocols()); assertArrayEquals(EXPECTED_PROTOCOLS, handler.engine().getEnabledProtocols());
} }
private static SslContext newDelegatingSslContext() throws Exception { private static SslContext newDelegatingSslContext() throws Exception {

View File

@ -15,14 +15,14 @@
*/ */
package io.netty.handler.ssl; package io.netty.handler.ssl;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import static org.junit.Assert.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class IdentityCipherSuiteFilterTest { public class IdentityCipherSuiteFilterTest {

View File

@ -17,13 +17,15 @@ package io.netty.handler.ssl;
import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator;
import org.hamcrest.CoreMatchers; import org.hamcrest.CoreMatchers;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.KeyManagerFactory;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class OpenSslCachingKeyMaterialProviderTest extends OpenSslKeyMaterialProviderTest { public class OpenSslCachingKeyMaterialProviderTest extends OpenSslKeyMaterialProviderTest {
@ -40,7 +42,7 @@ public class OpenSslCachingKeyMaterialProviderTest extends OpenSslKeyMaterialPro
@Override @Override
protected void assertRelease(OpenSslKeyMaterial material) { protected void assertRelease(OpenSslKeyMaterial material) {
Assert.assertFalse(material.release()); assertFalse(material.release());
} }
@Test @Test

View File

@ -16,15 +16,18 @@
package io.netty.handler.ssl; package io.netty.handler.ssl;
import io.netty.internal.tcnative.CertificateVerifier; import io.netty.internal.tcnative.CertificateVerifier;
import org.junit.Assert; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.function.Executable;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class OpenSslCertificateExceptionTest { public class OpenSslCertificateExceptionTest {
@BeforeClass @BeforeAll
public static void ensureOpenSsl() { public static void ensureOpenSsl() {
OpenSsl.ensureAvailability(); OpenSsl.ensureAvailability();
} }
@ -36,14 +39,19 @@ public class OpenSslCertificateExceptionTest {
if (field.isAccessible()) { if (field.isAccessible()) {
int errorCode = field.getInt(null); int errorCode = field.getInt(null);
OpenSslCertificateException exception = new OpenSslCertificateException(errorCode); OpenSslCertificateException exception = new OpenSslCertificateException(errorCode);
Assert.assertEquals(errorCode, exception.errorCode()); assertEquals(errorCode, exception.errorCode());
} }
} }
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testNonValidErrorCode() { public void testNonValidErrorCode() {
new OpenSslCertificateException(Integer.MIN_VALUE); assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() throws Throwable {
new OpenSslCertificateException(Integer.MIN_VALUE);
}
});
} }
@Test @Test

View File

@ -18,9 +18,7 @@ package io.netty.handler.ssl;
import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.EmptyArrays;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Assume;
import org.junit.Test;
import javax.net.ssl.SSLException; import javax.net.ssl.SSLException;
import javax.net.ssl.X509ExtendedKeyManager; import javax.net.ssl.X509ExtendedKeyManager;
@ -29,6 +27,8 @@ import java.security.Principal;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import static org.junit.jupiter.api.Assertions.fail;
public class OpenSslKeyMaterialManagerTest { public class OpenSslKeyMaterialManagerTest {
@Test @Test
@ -71,7 +71,7 @@ public class OpenSslKeyMaterialManagerTest {
new OpenSslKeyMaterialProvider(keyManager, null) { new OpenSslKeyMaterialProvider(keyManager, null) {
@Override @Override
OpenSslKeyMaterial chooseKeyMaterial(ByteBufAllocator allocator, String alias) throws Exception { OpenSslKeyMaterial chooseKeyMaterial(ByteBufAllocator allocator, String alias) throws Exception {
Assert.fail("Should not be called when alias is null"); fail("Should not be called when alias is null");
return null; return null;
} }
}); });

View File

@ -19,8 +19,8 @@ import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.internal.tcnative.SSL; import io.netty.internal.tcnative.SSL;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.X509KeyManager; import javax.net.ssl.X509KeyManager;
@ -31,8 +31,11 @@ import java.security.Principal;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class OpenSslKeyMaterialProviderTest { public class OpenSslKeyMaterialProviderTest {
@ -40,8 +43,8 @@ public class OpenSslKeyMaterialProviderTest {
static final String EXISTING_ALIAS = "1"; static final String EXISTING_ALIAS = "1";
private static final String NON_EXISTING_ALIAS = "nonexisting"; private static final String NON_EXISTING_ALIAS = "nonexisting";
@BeforeClass @BeforeAll
public static void checkOpenSsl() { static void checkOpenSsl() {
OpenSsl.ensureAvailability(); OpenSsl.ensureAvailability();
} }

View File

@ -37,13 +37,11 @@ import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.Promise;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import org.junit.AfterClass;
import org.junit.Assume; import org.junit.Assume;
import org.junit.BeforeClass; import org.junit.jupiter.api.AfterAll;
import org.junit.Test; import org.junit.jupiter.api.BeforeAll;
import org.junit.runner.RunWith; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.runners.Parameterized; import org.junit.jupiter.params.provider.MethodSource;
import org.junit.runners.Parameterized.Parameters;
import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
@ -67,27 +65,25 @@ import java.util.concurrent.atomic.AtomicBoolean;
import static io.netty.handler.ssl.OpenSslTestUtils.checkShouldUseKeyManagerFactory; import static io.netty.handler.ssl.OpenSslTestUtils.checkShouldUseKeyManagerFactory;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@RunWith(Parameterized.class)
public class OpenSslPrivateKeyMethodTest { public class OpenSslPrivateKeyMethodTest {
private static final String RFC_CIPHER_NAME = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"; private static final String RFC_CIPHER_NAME = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256";
private static EventLoopGroup GROUP; private static EventLoopGroup GROUP;
private static SelfSignedCertificate CERT; private static SelfSignedCertificate CERT;
private static ExecutorService EXECUTOR; private static ExecutorService EXECUTOR;
@Parameters(name = "{index}: delegate = {0}") static Collection<Object[]> parameters() {
public static Collection<Object[]> parameters() {
List<Object[]> dst = new ArrayList<Object[]>(); List<Object[]> dst = new ArrayList<Object[]>();
dst.add(new Object[] { true }); dst.add(new Object[] { true });
dst.add(new Object[] { false }); dst.add(new Object[] { false });
return dst; return dst;
} }
@BeforeClass @BeforeAll
public static void init() throws Exception { public static void init() throws Exception {
checkShouldUseKeyManagerFactory(); checkShouldUseKeyManagerFactory();
@ -102,7 +98,7 @@ public class OpenSslPrivateKeyMethodTest {
EXECUTOR = Executors.newCachedThreadPool(DelegateThread::new); EXECUTOR = Executors.newCachedThreadPool(DelegateThread::new);
} }
@AfterClass @AfterAll
public static void destroy() { public static void destroy() {
if (OpenSsl.isBoringSSL()) { if (OpenSsl.isBoringSSL()) {
GROUP.shutdownGracefully(); GROUP.shutdownGracefully();
@ -111,12 +107,6 @@ public class OpenSslPrivateKeyMethodTest {
} }
} }
private final boolean delegate;
public OpenSslPrivateKeyMethodTest(boolean delegate) {
this.delegate = delegate;
}
private static void assumeCipherAvailable(SslProvider provider) throws NoSuchAlgorithmException { private static void assumeCipherAvailable(SslProvider provider) throws NoSuchAlgorithmException {
boolean cipherSupported = false; boolean cipherSupported = false;
if (provider == SslProvider.JDK) { if (provider == SslProvider.JDK) {
@ -165,11 +155,11 @@ public class OpenSslPrivateKeyMethodTest {
.build(); .build();
} }
private Executor delegateExecutor() { private static Executor delegateExecutor(boolean delegate) {
return delegate ? EXECUTOR : null; return delegate ? EXECUTOR : null;
} }
private void assertThread() { private static void assertThread(boolean delegate) {
if (delegate && OpenSslContext.USE_TASKS) { if (delegate && OpenSslContext.USE_TASKS) {
assertEquals(DelegateThread.class, Thread.currentThread().getClass()); assertEquals(DelegateThread.class, Thread.currentThread().getClass());
} else { } else {
@ -177,14 +167,15 @@ public class OpenSslPrivateKeyMethodTest {
} }
} }
@Test @ParameterizedTest(name = "{index}: delegate = {0}")
public void testPrivateKeyMethod() throws Exception { @MethodSource("parameters")
public void testPrivateKeyMethod(final boolean delegate) throws Exception {
final AtomicBoolean signCalled = new AtomicBoolean(); final AtomicBoolean signCalled = new AtomicBoolean();
final SslContext sslServerContext = buildServerContext(new OpenSslPrivateKeyMethod() { final SslContext sslServerContext = buildServerContext(new OpenSslPrivateKeyMethod() {
@Override @Override
public byte[] sign(SSLEngine engine, int signatureAlgorithm, byte[] input) throws Exception { public byte[] sign(SSLEngine engine, int signatureAlgorithm, byte[] input) throws Exception {
signCalled.set(true); signCalled.set(true);
assertThread(); assertThread(delegate);
assertEquals(CERT.cert().getPublicKey(), assertEquals(CERT.cert().getPublicKey(),
engine.getSession().getLocalCertificates()[0].getPublicKey()); engine.getSession().getLocalCertificates()[0].getPublicKey());
@ -222,7 +213,7 @@ public class OpenSslPrivateKeyMethodTest {
@Override @Override
protected void initChannel(Channel ch) { protected void initChannel(Channel ch) {
ChannelPipeline pipeline = ch.pipeline(); ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(newSslHandler(sslServerContext, ch.alloc(), delegateExecutor())); pipeline.addLast(newSslHandler(sslServerContext, ch.alloc(), delegateExecutor(delegate)));
pipeline.addLast(new SimpleChannelInboundHandler<Object>() { pipeline.addLast(new SimpleChannelInboundHandler<Object>() {
@Override @Override
@ -258,7 +249,7 @@ public class OpenSslPrivateKeyMethodTest {
@Override @Override
protected void initChannel(Channel ch) { protected void initChannel(Channel ch) {
ChannelPipeline pipeline = ch.pipeline(); ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(newSslHandler(sslClientContext, ch.alloc(), delegateExecutor())); pipeline.addLast(newSslHandler(sslClientContext, ch.alloc(), delegateExecutor(delegate)));
pipeline.addLast(new SimpleChannelInboundHandler<Object>() { pipeline.addLast(new SimpleChannelInboundHandler<Object>() {
@Override @Override
@ -288,8 +279,8 @@ public class OpenSslPrivateKeyMethodTest {
client.writeAndFlush(Unpooled.wrappedBuffer(new byte[] {'P', 'I', 'N', 'G'})) client.writeAndFlush(Unpooled.wrappedBuffer(new byte[] {'P', 'I', 'N', 'G'}))
.syncUninterruptibly(); .syncUninterruptibly();
assertTrue("client timeout", clientPromise.await(5L, TimeUnit.SECONDS)); assertTrue(clientPromise.await(5L, TimeUnit.SECONDS), "client timeout");
assertTrue("server timeout", serverPromise.await(5L, TimeUnit.SECONDS)); assertTrue(serverPromise.await(5L, TimeUnit.SECONDS), "server timeout");
clientPromise.sync(); clientPromise.sync();
serverPromise.sync(); serverPromise.sync();
@ -308,20 +299,23 @@ public class OpenSslPrivateKeyMethodTest {
} }
} }
@Test @ParameterizedTest(name = "{index}: delegate = {0}")
public void testPrivateKeyMethodFailsBecauseOfException() throws Exception { @MethodSource("parameters")
testPrivateKeyMethodFails(false); public void testPrivateKeyMethodFailsBecauseOfException(final boolean delegate) throws Exception {
testPrivateKeyMethodFails(delegate, false);
} }
@Test @ParameterizedTest(name = "{index}: delegate = {0}")
public void testPrivateKeyMethodFailsBecauseOfNull() throws Exception { @MethodSource("parameters")
testPrivateKeyMethodFails(true); public void testPrivateKeyMethodFailsBecauseOfNull(final boolean delegate) throws Exception {
testPrivateKeyMethodFails(delegate, true);
} }
private void testPrivateKeyMethodFails(final boolean returnNull) throws Exception {
private void testPrivateKeyMethodFails(final boolean delegate, final boolean returnNull) throws Exception {
final SslContext sslServerContext = buildServerContext(new OpenSslPrivateKeyMethod() { final SslContext sslServerContext = buildServerContext(new OpenSslPrivateKeyMethod() {
@Override @Override
public byte[] sign(SSLEngine engine, int signatureAlgorithm, byte[] input) throws Exception { public byte[] sign(SSLEngine engine, int signatureAlgorithm, byte[] input) throws Exception {
assertThread(); assertThread(delegate);
if (returnNull) { if (returnNull) {
return null; return null;
} }
@ -336,9 +330,9 @@ public class OpenSslPrivateKeyMethodTest {
final SslContext sslClientContext = buildClientContext(); final SslContext sslClientContext = buildClientContext();
SslHandler serverSslHandler = newSslHandler( SslHandler serverSslHandler = newSslHandler(
sslServerContext, UnpooledByteBufAllocator.DEFAULT, delegateExecutor()); sslServerContext, UnpooledByteBufAllocator.DEFAULT, delegateExecutor(delegate));
SslHandler clientSslHandler = newSslHandler( SslHandler clientSslHandler = newSslHandler(
sslClientContext, UnpooledByteBufAllocator.DEFAULT, delegateExecutor()); sslClientContext, UnpooledByteBufAllocator.DEFAULT, delegateExecutor(delegate));
try { try {
try { try {

View File

@ -15,15 +15,16 @@
*/ */
package io.netty.handler.ssl; package io.netty.handler.ssl;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class OpenSslTest { public class OpenSslTest {
@Test @Test
public void testDefaultCiphers() { public void testDefaultCiphers() {
if (!OpenSsl.isTlsv13Supported()) { if (!OpenSsl.isTlsv13Supported()) {
Assert.assertTrue( assertTrue(
OpenSsl.DEFAULT_CIPHERS.size() <= SslUtils.DEFAULT_CIPHER_SUITES.length); OpenSsl.DEFAULT_CIPHERS.size() <= SslUtils.DEFAULT_CIPHER_SUITES.length);
} }
} }

View File

@ -20,16 +20,17 @@ import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPipeline;
import org.junit.Before;
import org.junit.Test; import org.junit.jupiter.api.BeforeEach;
import org.junit.runner.RunWith; import org.junit.jupiter.api.Test;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class OptionalSslHandlerTest { public class OptionalSslHandlerTest {
private static final String SSL_HANDLER_NAME = "sslhandler"; private static final String SSL_HANDLER_NAME = "sslhandler";
@ -44,8 +45,9 @@ public class OptionalSslHandlerTest {
@Mock @Mock
private ChannelPipeline pipeline; private ChannelPipeline pipeline;
@Before @BeforeEach
public void setUp() throws Exception { public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
when(context.pipeline()).thenReturn(pipeline); when(context.pipeline()).thenReturn(pipeline);
} }

View File

@ -46,9 +46,9 @@ import io.netty.util.concurrent.Promise;
import io.netty.util.concurrent.PromiseNotifier; import io.netty.util.concurrent.PromiseNotifier;
import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.EmptyArrays;
import io.netty.util.internal.ResourcesUtil; import io.netty.util.internal.ResourcesUtil;
import org.junit.Test; import org.junit.jupiter.api.Timeout;
import org.junit.runner.RunWith; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.runners.Parameterized; import org.junit.jupiter.params.provider.MethodSource;
import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.ManagerFactoryParameters;
import javax.net.ssl.SSLException; import javax.net.ssl.SSLException;
@ -64,19 +64,20 @@ import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import static io.netty.buffer.ByteBufUtil.writeAscii; import static io.netty.buffer.ByteBufUtil.writeAscii;
import static java.util.concurrent.ThreadLocalRandom.current; import static java.util.concurrent.ThreadLocalRandom.current;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@RunWith(Parameterized.class)
public class ParameterizedSslHandlerTest { public class ParameterizedSslHandlerTest {
@Parameterized.Parameters(name = "{index}: clientProvider={0}, {index}: serverProvider={1}") private static final String PARAMETERIZED_NAME = "{index}: clientProvider={0}, {index}: serverProvider={1}";
public static Collection<Object[]> data() {
static Collection<Object[]> data() {
List<SslProvider> providers = new ArrayList<>(3); List<SslProvider> providers = new ArrayList<>(3);
if (OpenSsl.isAvailable()) { if (OpenSsl.isAvailable()) {
providers.add(SslProvider.OPENSSL); providers.add(SslProvider.OPENSSL);
@ -94,16 +95,11 @@ public class ParameterizedSslHandlerTest {
return params; return params;
} }
private final SslProvider clientProvider; @ParameterizedTest(name = PARAMETERIZED_NAME)
private final SslProvider serverProvider; @MethodSource("data")
@Timeout(value = 48000, unit = TimeUnit.MILLISECONDS)
public ParameterizedSslHandlerTest(SslProvider clientProvider, SslProvider serverProvider) { public void testCompositeBufSizeEstimationGuaranteesSynchronousWrite(
this.clientProvider = clientProvider; SslProvider clientProvider, SslProvider serverProvider)
this.serverProvider = serverProvider;
}
@Test(timeout = 480000)
public void testCompositeBufSizeEstimationGuaranteesSynchronousWrite()
throws CertificateException, SSLException, ExecutionException, InterruptedException { throws CertificateException, SSLException, ExecutionException, InterruptedException {
compositeBufSizeEstimationGuaranteesSynchronousWrite(serverProvider, clientProvider, compositeBufSizeEstimationGuaranteesSynchronousWrite(serverProvider, clientProvider,
true, true, true); true, true, true);
@ -273,8 +269,10 @@ public class ParameterizedSslHandlerTest {
} }
} }
@Test(timeout = 30000) @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testAlertProducedAndSend() throws Exception { @MethodSource("data")
@Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void testAlertProducedAndSend(SslProvider clientProvider, SslProvider serverProvider) throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate(); SelfSignedCertificate ssc = new SelfSignedCertificate();
final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()) final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
@ -371,22 +369,31 @@ public class ParameterizedSslHandlerTest {
} }
} }
@Test(timeout = 30000) @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testCloseNotify() throws Exception { @MethodSource("data")
testCloseNotify(5000, false); @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void testCloseNotify(SslProvider clientProvider, SslProvider serverProvider) throws Exception {
testCloseNotify(clientProvider, serverProvider, 5000, false);
} }
@Test(timeout = 30000) @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testCloseNotifyReceivedTimeout() throws Exception { @MethodSource("data")
testCloseNotify(100, true); @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void testCloseNotifyReceivedTimeout(SslProvider clientProvider, SslProvider serverProvider)
throws Exception {
testCloseNotify(clientProvider, serverProvider, 100, true);
} }
@Test(timeout = 30000) @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testCloseNotifyNotWaitForResponse() throws Exception { @MethodSource("data")
testCloseNotify(0, false); @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void testCloseNotifyNotWaitForResponse(SslProvider clientProvider, SslProvider serverProvider)
throws Exception {
testCloseNotify(clientProvider, serverProvider, 0, false);
} }
private void testCloseNotify(final long closeNotifyReadTimeout, final boolean timeout) throws Exception { private void testCloseNotify(SslProvider clientProvider, SslProvider serverProvider,
final long closeNotifyReadTimeout, final boolean timeout) throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate(); SelfSignedCertificate ssc = new SelfSignedCertificate();
final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()) final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
@ -498,39 +505,54 @@ public class ParameterizedSslHandlerTest {
} }
} }
@Test(timeout = 30000) @ParameterizedTest(name = PARAMETERIZED_NAME)
public void reentryOnHandshakeCompleteNioChannel() throws Exception { @MethodSource("data")
@Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void reentryOnHandshakeCompleteNioChannel(SslProvider clientProvider, SslProvider serverProvider)
throws Exception {
EventLoopGroup group = new MultithreadEventLoopGroup(NioHandler.newFactory()); EventLoopGroup group = new MultithreadEventLoopGroup(NioHandler.newFactory());
try { try {
Class<? extends ServerChannel> serverClass = NioServerSocketChannel.class; Class<? extends ServerChannel> serverClass = NioServerSocketChannel.class;
Class<? extends Channel> clientClass = NioSocketChannel.class; Class<? extends Channel> clientClass = NioSocketChannel.class;
SocketAddress bindAddress = new InetSocketAddress(0); SocketAddress bindAddress = new InetSocketAddress(0);
reentryOnHandshakeComplete(group, bindAddress, serverClass, clientClass, false, false); reentryOnHandshakeComplete(clientProvider, serverProvider, group, bindAddress,
reentryOnHandshakeComplete(group, bindAddress, serverClass, clientClass, false, true); serverClass, clientClass, false, false);
reentryOnHandshakeComplete(group, bindAddress, serverClass, clientClass, true, false); reentryOnHandshakeComplete(clientProvider, serverProvider, group, bindAddress,
reentryOnHandshakeComplete(group, bindAddress, serverClass, clientClass, true, true); serverClass, clientClass, false, true);
reentryOnHandshakeComplete(clientProvider, serverProvider, group, bindAddress,
serverClass, clientClass, true, false);
reentryOnHandshakeComplete(clientProvider, serverProvider, group, bindAddress,
serverClass, clientClass, true, true);
} finally { } finally {
group.shutdownGracefully(); group.shutdownGracefully();
} }
} }
@Test(timeout = 30000) @ParameterizedTest(name = PARAMETERIZED_NAME)
public void reentryOnHandshakeCompleteLocalChannel() throws Exception { @MethodSource("data")
@Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void reentryOnHandshakeCompleteLocalChannel(SslProvider clientProvider, SslProvider serverProvider)
throws Exception {
EventLoopGroup group = new MultithreadEventLoopGroup(LocalHandler.newFactory()); EventLoopGroup group = new MultithreadEventLoopGroup(LocalHandler.newFactory());
try { try {
Class<? extends ServerChannel> serverClass = LocalServerChannel.class; Class<? extends ServerChannel> serverClass = LocalServerChannel.class;
Class<? extends Channel> clientClass = LocalChannel.class; Class<? extends Channel> clientClass = LocalChannel.class;
SocketAddress bindAddress = new LocalAddress(String.valueOf(current().nextLong())); SocketAddress bindAddress = new LocalAddress(String.valueOf(current().nextLong()));
reentryOnHandshakeComplete(group, bindAddress, serverClass, clientClass, false, false); reentryOnHandshakeComplete(clientProvider, serverProvider, group, bindAddress,
reentryOnHandshakeComplete(group, bindAddress, serverClass, clientClass, false, true); serverClass, clientClass, false, false);
reentryOnHandshakeComplete(group, bindAddress, serverClass, clientClass, true, false); reentryOnHandshakeComplete(clientProvider, serverProvider, group, bindAddress,
reentryOnHandshakeComplete(group, bindAddress, serverClass, clientClass, true, true); serverClass, clientClass, false, true);
reentryOnHandshakeComplete(clientProvider, serverProvider, group, bindAddress,
serverClass, clientClass, true, false);
reentryOnHandshakeComplete(clientProvider, serverProvider, group, bindAddress,
serverClass, clientClass, true, true);
} finally { } finally {
group.shutdownGracefully(); group.shutdownGracefully();
} }
} }
private void reentryOnHandshakeComplete(EventLoopGroup group, SocketAddress bindAddress, private void reentryOnHandshakeComplete(SslProvider clientProvider, SslProvider serverProvider,
EventLoopGroup group, SocketAddress bindAddress,
Class<? extends ServerChannel> serverClass, Class<? extends ServerChannel> serverClass,
Class<? extends Channel> clientClass, boolean serverAutoRead, Class<? extends Channel> clientClass, boolean serverAutoRead,
boolean clientAutoRead) throws Exception { boolean clientAutoRead) throws Exception {

View File

@ -16,20 +16,22 @@
package io.netty.handler.ssl; package io.netty.handler.ssl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.security.PrivateKey; import java.security.PrivateKey;
import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator;
import org.junit.Test;
import io.netty.handler.ssl.util.SelfSignedCertificate; import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
public class PemEncodedTest { public class PemEncodedTest {
@ -70,22 +72,27 @@ public class PemEncodedTest {
} }
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testEncodedReturnsNull() throws Exception { public void testEncodedReturnsNull() throws Exception {
PemPrivateKey.toPEM(UnpooledByteBufAllocator.DEFAULT, true, new PrivateKey() { assertThrows(IllegalArgumentException.class, new Executable() {
@Override @Override
public String getAlgorithm() { public void execute() throws Throwable {
return null; PemPrivateKey.toPEM(UnpooledByteBufAllocator.DEFAULT, true, new PrivateKey() {
} @Override
public String getAlgorithm() {
return null;
}
@Override @Override
public String getFormat() { public String getFormat() {
return null; return null;
} }
@Override @Override
public byte[] getEncoded() { public byte[] getEncoded() {
return null; return null;
}
});
} }
}); });
} }

View File

@ -18,10 +18,9 @@ package io.netty.handler.ssl;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.encoders.Hex;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
/** /**
* The test vectors here were provided via: * The test vectors here were provided via:
* https://www.ietf.org/mail-archive/web/tls/current/msg03416.html * https://www.ietf.org/mail-archive/web/tls/current/msg03416.html

View File

@ -31,14 +31,17 @@ import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate; import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.FutureListener; import io.netty.util.concurrent.FutureListener;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
public abstract class RenegotiateTest { public abstract class RenegotiateTest {
@Test(timeout = 30000) @Test
@Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void testRenegotiateServer() throws Throwable { public void testRenegotiateServer() throws Throwable {
final AtomicReference<Throwable> error = new AtomicReference<>(); final AtomicReference<Throwable> error = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(2); final CountDownLatch latch = new CountDownLatch(2);

View File

@ -15,10 +15,10 @@
*/ */
package io.netty.handler.ssl; package io.netty.handler.ssl;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
public class SignatureAlgorithmConverterTest { public class SignatureAlgorithmConverterTest {

View File

@ -30,11 +30,11 @@ import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.Promise;
import org.junit.Assert; import io.netty.util.internal.PlatformDependent;
import org.junit.Test; import org.junit.jupiter.api.Timeout;
import org.junit.runner.RunWith; import org.junit.jupiter.api.function.Executable;
import org.junit.runners.Parameterized; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.runners.Parameterized.Parameters; import org.junit.jupiter.params.provider.MethodSource;
import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLException; import javax.net.ssl.SSLException;
@ -44,12 +44,17 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
@RunWith(Parameterized.class)
public class SniClientTest { public class SniClientTest {
private static final String PARAMETERIZED_NAME = "{index}: serverSslProvider = {0}, clientSslProvider = {1}";
@Parameters(name = "{index}: serverSslProvider = {0}, clientSslProvider = {1}") static Collection<Object[]> parameters() {
public static Collection<Object[]> parameters() {
List<SslProvider> providers = new ArrayList<>(Arrays.asList(SslProvider.values())); List<SslProvider> providers = new ArrayList<>(Arrays.asList(SslProvider.values()));
if (!OpenSsl.isAvailable()) { if (!OpenSsl.isAvailable()) {
providers.remove(SslProvider.OPENSSL); providers.remove(SslProvider.OPENSSL);
@ -65,30 +70,33 @@ public class SniClientTest {
return params; return params;
} }
private final SslProvider serverProvider; @ParameterizedTest(name = PARAMETERIZED_NAME)
private final SslProvider clientProvider; @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
@MethodSource("parameters")
public SniClientTest(SslProvider serverProvider, SslProvider clientProvider) { public void testSniSNIMatcherMatchesClient(SslProvider serverProvider, SslProvider clientProvider)
this.serverProvider = serverProvider; throws Throwable {
this.clientProvider = clientProvider; assumeTrue(PlatformDependent.javaVersion() >= 8);
}
@Test(timeout = 30000)
public void testSniClient() throws Exception {
testSniClient(serverProvider, clientProvider);
}
@Test(timeout = 30000)
public void testSniSNIMatcherMatchesClient() throws Throwable {
SniClientJava8TestUtil.testSniClient(serverProvider, clientProvider, true); SniClientJava8TestUtil.testSniClient(serverProvider, clientProvider, true);
} }
@Test(timeout = 30000, expected = SSLException.class) @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testSniSNIMatcherDoesNotMatchClient() throws Throwable { @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
SniClientJava8TestUtil.testSniClient(serverProvider, clientProvider, false); @MethodSource("parameters")
public void testSniSNIMatcherDoesNotMatchClient(
final SslProvider serverProvider, final SslProvider clientProvider) {
assumeTrue(PlatformDependent.javaVersion() >= 8);
assertThrows(SSLException.class, new Executable() {
@Override
public void execute() throws Throwable {
SniClientJava8TestUtil.testSniClient(serverProvider, clientProvider, false);
}
});
} }
private static void testSniClient(SslProvider sslServerProvider, SslProvider sslClientProvider) throws Exception { @ParameterizedTest(name = PARAMETERIZED_NAME)
@Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
@MethodSource("parameters")
public void testSniClient(SslProvider sslServerProvider, SslProvider sslClientProvider) throws Exception {
String sniHostName = "sni.netty.io"; String sniHostName = "sni.netty.io";
LocalAddress address = new LocalAddress("test"); LocalAddress address = new LocalAddress("test");
EventLoopGroup group = new MultithreadEventLoopGroup(1, LocalHandler.newFactory()); EventLoopGroup group = new MultithreadEventLoopGroup(1, LocalHandler.newFactory());
@ -134,11 +142,11 @@ public class SniClientTest {
sslClientContext.newEngine(ByteBufAllocator.DEFAULT, sniHostName, -1)); sslClientContext.newEngine(ByteBufAllocator.DEFAULT, sniHostName, -1));
cc = cb.group(group).channel(LocalChannel.class).handler(handler) cc = cb.group(group).channel(LocalChannel.class).handler(handler)
.connect(address).syncUninterruptibly().channel(); .connect(address).syncUninterruptibly().channel();
Assert.assertEquals(sniHostName, promise.syncUninterruptibly().getNow()); assertEquals(sniHostName, promise.syncUninterruptibly().getNow());
// After we are done with handshaking getHandshakeSession() should return null. // After we are done with handshaking getHandshakeSession() should return null.
handler.handshakeFuture().syncUninterruptibly(); handler.handshakeFuture().syncUninterruptibly();
Assert.assertNull(handler.engine().getHandshakeSession()); assertNull(handler.engine().getHandshakeSession());
SniClientJava8TestUtil.assertSSLSession( SniClientJava8TestUtil.assertSSLSession(
handler.engine().getUseClientMode(), handler.engine().getSession(), sniHostName); handler.engine().getUseClientMode(), handler.engine().getSession(), sniHostName);

View File

@ -16,18 +16,6 @@
package io.netty.handler.ssl; package io.netty.handler.ssl;
import static java.util.Objects.requireNonNull;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import java.io.File; import java.io.File;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.util.ArrayList; import java.util.ArrayList;
@ -41,9 +29,6 @@ import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException; import javax.net.ssl.SSLException;
import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Future;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap; import io.netty.bootstrap.ServerBootstrap;
@ -78,9 +63,26 @@ import io.netty.util.concurrent.Promise;
import io.netty.util.internal.ResourcesUtil; import io.netty.util.internal.ResourcesUtil;
import io.netty.util.internal.StringUtil; import io.netty.util.internal.StringUtil;
import org.mockito.Mockito; import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static java.util.Objects.requireNonNull;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assume.assumeTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
@RunWith(Parameterized.class)
public class SniHandlerTest { public class SniHandlerTest {
private static ApplicationProtocolConfig newApnConfig() { private static ApplicationProtocolConfig newApnConfig() {
@ -137,8 +139,7 @@ public class SniHandlerTest {
return sslCtxBuilder.build(); return sslCtxBuilder.build();
} }
@Parameterized.Parameters(name = "{index}: sslProvider={0}") static Iterable<?> data() {
public static Iterable<?> data() {
List<SslProvider> params = new ArrayList<>(3); List<SslProvider> params = new ArrayList<>(3);
if (OpenSsl.isAvailable()) { if (OpenSsl.isAvailable()) {
params.add(SslProvider.OPENSSL); params.add(SslProvider.OPENSSL);
@ -148,20 +149,15 @@ public class SniHandlerTest {
return params; return params;
} }
private final SslProvider provider; @ParameterizedTest(name = "{index}: sslProvider={0}")
@MethodSource("data")
public SniHandlerTest(SslProvider provider) { public void testNonSslRecord(SslProvider provider) throws Exception {
this.provider = provider;
}
@Test
public void testNonSslRecord() throws Exception {
SslContext nettyContext = makeSslContext(provider, false); SslContext nettyContext = makeSslContext(provider, false);
try { try {
final AtomicReference<SslHandshakeCompletionEvent> evtRef = final AtomicReference<SslHandshakeCompletionEvent> evtRef =
new AtomicReference<>(); new AtomicReference<SslHandshakeCompletionEvent>();
SniHandler handler = new SniHandler(new DomainNameMappingBuilder<>(nettyContext).build()); SniHandler handler = new SniHandler(new DomainNameMappingBuilder<>(nettyContext).build());
EmbeddedChannel ch = new EmbeddedChannel(handler, new ChannelHandler() { final EmbeddedChannel ch = new EmbeddedChannel(handler, new ChannelHandler() {
@Override @Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof SslHandshakeCompletionEvent) { if (evt instanceof SslHandshakeCompletionEvent) {
@ -171,27 +167,29 @@ public class SniHandlerTest {
}); });
try { try {
byte[] bytes = new byte[1024]; final byte[] bytes = new byte[1024];
bytes[0] = SslUtils.SSL_CONTENT_TYPE_ALERT; bytes[0] = SslUtils.SSL_CONTENT_TYPE_ALERT;
try { DecoderException e = assertThrows(DecoderException.class, new Executable() {
ch.writeInbound(Unpooled.wrappedBuffer(bytes)); @Override
fail(); public void execute() throws Throwable {
} catch (DecoderException e) { ch.writeInbound(Unpooled.wrappedBuffer(bytes));
assertTrue(e.getCause() instanceof NotSslRecordException); }
} });
assertThat(e.getCause(), CoreMatchers.instanceOf(NotSslRecordException.class));
assertFalse(ch.finish()); assertFalse(ch.finish());
} finally { } finally {
ch.finishAndReleaseAll(); ch.finishAndReleaseAll();
} }
assertTrue(evtRef.get().cause() instanceof NotSslRecordException); assertThat(evtRef.get().cause(), CoreMatchers.instanceOf(NotSslRecordException.class));
} finally { } finally {
releaseAll(nettyContext); releaseAll(nettyContext);
} }
} }
@Test @ParameterizedTest(name = "{index}: sslProvider={0}")
public void testServerNameParsing() throws Exception { @MethodSource("data")
public void testServerNameParsing(SslProvider provider) throws Exception {
SslContext nettyContext = makeSslContext(provider, false); SslContext nettyContext = makeSslContext(provider, false);
SslContext leanContext = makeSslContext(provider, false); SslContext leanContext = makeSslContext(provider, false);
SslContext leanContext2 = makeSslContext(provider, false); SslContext leanContext2 = makeSslContext(provider, false);
@ -253,8 +251,9 @@ public class SniHandlerTest {
} }
} }
@Test(expected = DecoderException.class) @ParameterizedTest(name = "{index}: sslProvider={0}")
public void testNonAsciiServerNameParsing() throws Exception { @MethodSource("data")
public void testNonAsciiServerNameParsing(SslProvider provider) throws Exception {
SslContext nettyContext = makeSslContext(provider, false); SslContext nettyContext = makeSslContext(provider, false);
SslContext leanContext = makeSslContext(provider, false); SslContext leanContext = makeSslContext(provider, false);
SslContext leanContext2 = makeSslContext(provider, false); SslContext leanContext2 = makeSslContext(provider, false);
@ -270,13 +269,13 @@ public class SniHandlerTest {
.build(); .build();
SniHandler handler = new SniHandler(mapping); SniHandler handler = new SniHandler(mapping);
EmbeddedChannel ch = new EmbeddedChannel(handler); final EmbeddedChannel ch = new EmbeddedChannel(handler);
try { try {
// hex dump of a client hello packet, which contains an invalid hostname "CHAT4。LEANCLOUD。CN" // hex dump of a client hello packet, which contains an invalid hostname "CHAT4。LEANCLOUD。CN"
String tlsHandshakeMessageHex1 = "16030100"; String tlsHandshakeMessageHex1 = "16030100";
// part 2 // part 2
String tlsHandshakeMessageHex = "bd010000b90303a74225676d1814ba57faff3b366" + final String tlsHandshakeMessageHex = "bd010000b90303a74225676d1814ba57faff3b366" +
"3656ed05ee9dbb2a4dbb1bb1c32d2ea5fc39e0000000100008c0000001700150000164348" + "3656ed05ee9dbb2a4dbb1bb1c32d2ea5fc39e0000000100008c0000001700150000164348" +
"415434E380824C45414E434C4F5544E38082434E000b000403000102000a00340032000e0" + "415434E380824C45414E434C4F5544E38082434E000b000403000102000a00340032000e0" +
"00d0019000b000c00180009000a0016001700080006000700140015000400050012001300" + "00d0019000b000c00180009000a0016001700080006000700140015000400050012001300" +
@ -287,7 +286,13 @@ public class SniHandlerTest {
// Decode should fail because of the badly encoded "HostName" string in the SNI extension // Decode should fail because of the badly encoded "HostName" string in the SNI extension
// that isn't ASCII as per RFC 6066 - https://tools.ietf.org/html/rfc6066#page-6 // that isn't ASCII as per RFC 6066 - https://tools.ietf.org/html/rfc6066#page-6
ch.writeInbound(Unpooled.wrappedBuffer(StringUtil.decodeHexDump(tlsHandshakeMessageHex1))); ch.writeInbound(Unpooled.wrappedBuffer(StringUtil.decodeHexDump(tlsHandshakeMessageHex1)));
ch.writeInbound(Unpooled.wrappedBuffer(StringUtil.decodeHexDump(tlsHandshakeMessageHex)));
assertThrows(DecoderException.class, new Executable() {
@Override
public void execute() throws Throwable {
ch.writeInbound(Unpooled.wrappedBuffer(StringUtil.decodeHexDump(tlsHandshakeMessageHex)));
}
});
} finally { } finally {
ch.finishAndReleaseAll(); ch.finishAndReleaseAll();
} }
@ -296,8 +301,9 @@ public class SniHandlerTest {
} }
} }
@Test @ParameterizedTest(name = "{index}: sslProvider={0}")
public void testFallbackToDefaultContext() throws Exception { @MethodSource("data")
public void testFallbackToDefaultContext(SslProvider provider) throws Exception {
SslContext nettyContext = makeSslContext(provider, false); SslContext nettyContext = makeSslContext(provider, false);
SslContext leanContext = makeSslContext(provider, false); SslContext leanContext = makeSslContext(provider, false);
SslContext leanContext2 = makeSslContext(provider, false); SslContext leanContext2 = makeSslContext(provider, false);
@ -346,8 +352,10 @@ public class SniHandlerTest {
} }
} }
@Test(timeout = 10000) @ParameterizedTest(name = "{index}: sslProvider={0}")
public void testMajorVersionNot3() throws Exception { @MethodSource("data")
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testMajorVersionNot3(SslProvider provider) throws Exception {
SslContext nettyContext = makeSslContext(provider, false); SslContext nettyContext = makeSslContext(provider, false);
try { try {
@ -387,8 +395,9 @@ public class SniHandlerTest {
} }
} }
@Test @ParameterizedTest(name = "{index}: sslProvider={0}")
public void testSniWithApnHandler() throws Exception { @MethodSource("data")
public void testSniWithApnHandler(SslProvider provider) throws Exception {
SslContext nettyContext = makeSslContext(provider, true); SslContext nettyContext = makeSslContext(provider, true);
SslContext sniContext = makeSslContext(provider, true); SslContext sniContext = makeSslContext(provider, true);
final SslContext clientContext = makeSslClientContext(provider, true); final SslContext clientContext = makeSslClientContext(provider, true);
@ -473,8 +482,10 @@ public class SniHandlerTest {
} }
} }
@Test(timeout = 30000) @ParameterizedTest(name = "{index}: sslProvider={0}")
public void testReplaceHandler() throws Exception { @MethodSource("data")
@Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void testReplaceHandler(SslProvider provider) throws Exception {
switch (provider) { switch (provider) {
case OPENSSL: case OPENSSL:
case OPENSSL_REFCNT: case OPENSSL_REFCNT:
@ -620,16 +631,19 @@ public class SniHandlerTest {
} }
} }
@Test @ParameterizedTest(name = "{index}: sslProvider={0}")
public void testNonFragmented() throws Exception { @MethodSource("data")
testWithFragmentSize(Integer.MAX_VALUE); public void testNonFragmented(SslProvider provider) throws Exception {
} testWithFragmentSize(provider, Integer.MAX_VALUE);
@Test
public void testFragmented() throws Exception {
testWithFragmentSize(50);
} }
private void testWithFragmentSize(final int maxFragmentSize) throws Exception { @ParameterizedTest(name = "{index}: sslProvider={0}")
@MethodSource("data")
public void testFragmented(SslProvider provider) throws Exception {
testWithFragmentSize(provider, 50);
}
private void testWithFragmentSize(SslProvider provider, final int maxFragmentSize) throws Exception {
final String sni = "netty.io"; final String sni = "netty.io";
SelfSignedCertificate cert = new SelfSignedCertificate(); SelfSignedCertificate cert = new SelfSignedCertificate();
final SslContext context = SslContextBuilder.forServer(cert.key(), cert.cert()) final SslContext context = SslContextBuilder.forServer(cert.key(), cert.cert())
@ -637,7 +651,7 @@ public class SniHandlerTest {
.build(); .build();
try { try {
@SuppressWarnings("unchecked") final EmbeddedChannel server = new EmbeddedChannel( @SuppressWarnings("unchecked") final EmbeddedChannel server = new EmbeddedChannel(
new SniHandler(Mockito.mock(DomainNameMapping.class)) { new SniHandler(mock(DomainNameMapping.class)) {
@Override @Override
protected Future<SslContext> lookup(final ChannelHandlerContext ctx, final String hostname) { protected Future<SslContext> lookup(final ChannelHandlerContext ctx, final String hostname) {
assertEquals(sni, hostname); assertEquals(sni, hostname);

View File

@ -18,8 +18,9 @@ package io.netty.handler.ssl;
import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.handler.ssl.util.SelfSignedCertificate; import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import org.junit.Assume;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngine;
@ -35,7 +36,11 @@ import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.Collections; import java.util.Collections;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
public class SslContextBuilderTest { public class SslContextBuilderTest {
@ -102,23 +107,33 @@ public class SslContextBuilderTest {
@Test @Test
public void testContextFromManagersOpenssl() throws Exception { public void testContextFromManagersOpenssl() throws Exception {
OpenSsl.ensureAvailability(); OpenSsl.ensureAvailability();
Assume.assumeTrue(OpenSsl.supportsKeyManagerFactory()); assumeTrue(OpenSsl.supportsKeyManagerFactory());
testContextFromManagers(SslProvider.OPENSSL); testContextFromManagers(SslProvider.OPENSSL);
} }
@Test(expected = SSLException.class) @Test
public void testUnsupportedPrivateKeyFailsFastForServer() throws Exception { public void testUnsupportedPrivateKeyFailsFastForServer() throws Exception {
Assume.assumeTrue(OpenSsl.isBoringSSL()); assumeTrue(OpenSsl.isBoringSSL());
testUnsupportedPrivateKeyFailsFast(true); assertThrows(SSLException.class, new Executable() {
@Override
public void execute() throws Throwable {
testUnsupportedPrivateKeyFailsFast(true);
}
});
} }
@Test(expected = SSLException.class) @Test
public void testUnsupportedPrivateKeyFailsFastForClient() throws Exception { public void testUnsupportedPrivateKeyFailsFastForClient() throws Exception {
Assume.assumeTrue(OpenSsl.isBoringSSL()); assumeTrue(OpenSsl.isBoringSSL());
testUnsupportedPrivateKeyFailsFast(false); assertThrows(SSLException.class, new Executable() {
@Override
public void execute() throws Throwable {
testUnsupportedPrivateKeyFailsFast(false);
}
});
} }
private static void testUnsupportedPrivateKeyFailsFast(boolean server) throws Exception { private static void testUnsupportedPrivateKeyFailsFast(boolean server) throws Exception {
Assume.assumeTrue(OpenSsl.isBoringSSL()); assumeTrue(OpenSsl.isBoringSSL());
String cert = "-----BEGIN CERTIFICATE-----\n" + String cert = "-----BEGIN CERTIFICATE-----\n" +
"MIICODCCAY2gAwIBAgIEXKTrajAKBggqhkjOPQQDBDBUMQswCQYDVQQGEwJVUzEM\n" + "MIICODCCAY2gAwIBAgIEXKTrajAKBggqhkjOPQQDBDBUMQswCQYDVQQGEwJVUzEM\n" +
"MAoGA1UECAwDTi9hMQwwCgYDVQQHDANOL2ExDDAKBgNVBAoMA04vYTEMMAoGA1UE\n" + "MAoGA1UECAwDTi9hMQwwCgYDVQQHDANOL2ExDDAKBgNVBAoMA04vYTEMMAoGA1UE\n" +
@ -152,10 +167,15 @@ public class SslContextBuilderTest {
} }
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testInvalidCipherJdk() throws Exception { public void testInvalidCipherJdk() throws Exception {
OpenSsl.ensureAvailability(); OpenSsl.ensureAvailability();
testInvalidCipher(SslProvider.JDK); assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() throws Throwable {
testInvalidCipher(SslProvider.JDK);
}
});
} }
@Test @Test

View File

@ -16,8 +16,8 @@
package io.netty.handler.ssl; package io.netty.handler.ssl;
import io.netty.util.internal.ResourcesUtil; import io.netty.util.internal.ResourcesUtil;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.function.Executable;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -31,36 +31,47 @@ import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException; import javax.net.ssl.SSLException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assume.assumeNotNull; import static org.junit.Assume.assumeNotNull;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public abstract class SslContextTest { public abstract class SslContextTest {
@Test(expected = IOException.class) @Test
public void testUnencryptedEmptyPassword() throws Exception { public void testUnencryptedEmptyPassword() throws Exception {
PrivateKey key = SslContext.toPrivateKey( assertThrows(IOException.class, new Executable() {
ResourcesUtil.getFile(getClass(), "test2_unencrypted.pem"), ""); @Override
Assert.assertNotNull(key); public void execute() throws Throwable {
SslContext.toPrivateKey(
ResourcesUtil.getFile(getClass(), "test2_unencrypted.pem"), "");
}
});
} }
@Test @Test
public void testUnEncryptedNullPassword() throws Exception { public void testUnEncryptedNullPassword() throws Exception {
PrivateKey key = SslContext.toPrivateKey( PrivateKey key = SslContext.toPrivateKey(
ResourcesUtil.getFile(getClass(), "test2_unencrypted.pem"), null); ResourcesUtil.getFile(getClass(), "test2_unencrypted.pem"), null);
Assert.assertNotNull(key); assertNotNull(key);
} }
@Test @Test
public void testEncryptedEmptyPassword() throws Exception { public void testEncryptedEmptyPassword() throws Exception {
PrivateKey key = SslContext.toPrivateKey( PrivateKey key = SslContext.toPrivateKey(
ResourcesUtil.getFile(getClass(), "test_encrypted_empty_pass.pem"), ""); ResourcesUtil.getFile(getClass(), "test_encrypted_empty_pass.pem"), "");
Assert.assertNotNull(key); assertNotNull(key);
} }
@Test(expected = InvalidKeySpecException.class) @Test
public void testEncryptedNullPassword() throws Exception { public void testEncryptedNullPassword() throws Exception {
SslContext.toPrivateKey( assertThrows(InvalidKeySpecException.class, new Executable() {
ResourcesUtil.getFile(getClass(), "test_encrypted_empty_pass.pem"), null); @Override
public void execute() throws Throwable {
SslContext.toPrivateKey(
ResourcesUtil.getFile(getClass(), "test_encrypted_empty_pass.pem"), null);
}
});
} }
@Test @Test
@ -87,12 +98,17 @@ public abstract class SslContextTest {
newSslContext(crtFile, keyFile, null); newSslContext(crtFile, keyFile, null);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testSslContextWithUnencryptedPrivateKeyEmptyPass() throws SSLException { public void testSslContextWithUnencryptedPrivateKeyEmptyPass() throws SSLException {
File keyFile = ResourcesUtil.getFile(getClass(), "test_unencrypted.pem"); final File keyFile = ResourcesUtil.getFile(getClass(), "test_unencrypted.pem");
File crtFile = ResourcesUtil.getFile(getClass(), "test.crt"); final File crtFile = ResourcesUtil.getFile(getClass(), "test.crt");
newSslContext(crtFile, keyFile, ""); assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() throws Throwable {
newSslContext(crtFile, keyFile, "");
}
});
} }
@Test @Test
@ -116,9 +132,15 @@ public abstract class SslContextTest {
assertFalse(sslContext.cipherSuites().contains(unsupportedCipher)); assertFalse(sslContext.cipherSuites().contains(unsupportedCipher));
} }
@Test(expected = CertificateException.class) @Test
public void testUnsupportedParams() throws CertificateException { public void testUnsupportedParams() throws CertificateException {
SslContext.toX509Certificates(new File(getClass().getResource("ec_params_unsupported.pem").getFile())); assertThrows(CertificateException.class, new Executable() {
@Override
public void execute() throws Throwable {
SslContext.toX509Certificates(
new File(getClass().getResource("ec_params_unsupported.pem").getFile()));
}
});
} }
protected abstract SslContext newSslContext(File crtFile, File keyFile, String pass) throws SSLException; protected abstract SslContext newSslContext(File crtFile, File keyFile, String pass) throws SSLException;

View File

@ -15,7 +15,7 @@
*/ */
package io.netty.handler.ssl; package io.netty.handler.ssl;
import org.junit.Test; import org.junit.jupiter.api.Test;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.TrustManagerFactory;
@ -25,8 +25,8 @@ import java.security.cert.X509Certificate;
import java.util.Arrays; import java.util.Arrays;
import static io.netty.handler.ssl.Java8SslTestUtils.loadCertCollection; import static io.netty.handler.ssl.Java8SslTestUtils.loadCertCollection;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.fail;
public class SslContextTrustManagerTest { public class SslContextTrustManagerTest {
@Test @Test
@ -84,7 +84,7 @@ public class SslContextTrustManagerTest {
for (int i = 0; i < eecResources.length; i++) { for (int i = 0; i < eecResources.length; i++) {
X509Certificate eecCert = eecCerts[i]; X509Certificate eecCert = eecCerts[i];
assertNotNull("Cannot use cert " + eecResources[i], eecCert); assertNotNull(eecCert, "Cannot use cert " + eecResources[i]);
try { try {
tm.checkServerTrusted(new X509Certificate[] { eecCert }, "RSA"); tm.checkServerTrusted(new X509Certificate[] { eecCert }, "RSA");
if (!expectations[i]) { if (!expectations[i]) {

View File

@ -34,10 +34,9 @@ import io.netty.handler.ssl.util.SimpleTrustManagerFactory;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.Promise;
import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.EmptyArrays;
import org.junit.Assume; import org.junit.jupiter.api.Timeout;
import org.junit.Test; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.runner.RunWith; import org.junit.jupiter.params.provider.MethodSource;
import org.junit.runners.Parameterized;
import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.ManagerFactoryParameters;
import javax.net.ssl.SSLException; import javax.net.ssl.SSLException;
@ -60,14 +59,11 @@ import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.concurrent.TimeUnit;
@RunWith(Parameterized.class)
public class SslErrorTest { public class SslErrorTest {
@Parameterized.Parameters( static Collection<Object[]> data() {
name = "{index}: serverProvider = {0}, clientProvider = {1}, exception = {2}, serverProduceError = {3}")
public static Collection<Object[]> data() {
List<SslProvider> serverProviders = new ArrayList<>(2); List<SslProvider> serverProviders = new ArrayList<>(2);
List<SslProvider> clientProviders = new ArrayList<>(3); List<SslProvider> clientProviders = new ArrayList<>(3);
@ -110,21 +106,13 @@ public class SslErrorTest {
new CertPathValidatorException("x", null, null, -1, reason)); new CertPathValidatorException("x", null, null, -1, reason));
} }
private final SslProvider serverProvider; @ParameterizedTest(
private final SslProvider clientProvider; name = "{index}: serverProvider = {0}, clientProvider = {1}, exception = {2}, serverProduceError = {3}")
private final CertificateException exception; @MethodSource("data")
private final boolean serverProduceError; @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void testCorrectAlert(SslProvider serverProvider, final SslProvider clientProvider,
public SslErrorTest(SslProvider serverProvider, SslProvider clientProvider, final CertificateException exception, final boolean serverProduceError)
CertificateException exception, boolean serverProduceError) { throws Exception {
this.serverProvider = serverProvider;
this.clientProvider = clientProvider;
this.exception = exception;
this.serverProduceError = serverProduceError;
}
@Test(timeout = 30000)
public void testCorrectAlert() throws Exception {
// As this only works correctly at the moment when OpenSslEngine is used on the server-side there is // As this only works correctly at the moment when OpenSslEngine is used on the server-side there is
// no need to run it if there is no openssl is available at all. // no need to run it if there is no openssl is available at all.
OpenSsl.ensureAvailability(); OpenSsl.ensureAvailability();
@ -140,11 +128,11 @@ public class SslErrorTest {
.sslProvider(clientProvider); .sslProvider(clientProvider);
if (serverProduceError) { if (serverProduceError) {
sslServerCtxBuilder.trustManager(new ExceptionTrustManagerFactory()); sslServerCtxBuilder.trustManager(new ExceptionTrustManagerFactory(exception));
sslClientCtxBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE); sslClientCtxBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
} else { } else {
sslServerCtxBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE); sslServerCtxBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
sslClientCtxBuilder.trustManager(new ExceptionTrustManagerFactory()); sslClientCtxBuilder.trustManager(new ExceptionTrustManagerFactory(exception));
} }
final SslContext sslServerCtx = sslServerCtxBuilder.build(); final SslContext sslServerCtx = sslServerCtxBuilder.build();
@ -163,7 +151,8 @@ public class SslErrorTest {
protected void initChannel(Channel ch) { protected void initChannel(Channel ch) {
ch.pipeline().addLast(sslServerCtx.newHandler(ch.alloc())); ch.pipeline().addLast(sslServerCtx.newHandler(ch.alloc()));
if (!serverProduceError) { if (!serverProduceError) {
ch.pipeline().addLast(new AlertValidationHandler(promise)); ch.pipeline().addLast(new AlertValidationHandler(clientProvider, serverProduceError,
exception, promise));
} }
ch.pipeline().addLast(new ChannelHandler() { ch.pipeline().addLast(new ChannelHandler() {
@ -183,7 +172,8 @@ public class SslErrorTest {
ch.pipeline().addLast(sslClientCtx.newHandler(ch.alloc())); ch.pipeline().addLast(sslClientCtx.newHandler(ch.alloc()));
if (serverProduceError) { if (serverProduceError) {
ch.pipeline().addLast(new AlertValidationHandler(promise)); ch.pipeline().addLast(new AlertValidationHandler(clientProvider, serverProduceError,
exception, promise));
} }
ch.pipeline().addLast(new ChannelHandler() { ch.pipeline().addLast(new ChannelHandler() {
@ -210,7 +200,13 @@ public class SslErrorTest {
} }
} }
private final class ExceptionTrustManagerFactory extends SimpleTrustManagerFactory { private static final class ExceptionTrustManagerFactory extends SimpleTrustManagerFactory {
private final CertificateException exception;
ExceptionTrustManagerFactory(CertificateException exception) {
this.exception = exception;
}
@Override @Override
protected void engineInit(KeyStore keyStore) { } protected void engineInit(KeyStore keyStore) { }
@Override @Override
@ -240,10 +236,17 @@ public class SslErrorTest {
} }
} }
private final class AlertValidationHandler implements ChannelHandler { private static final class AlertValidationHandler implements ChannelHandler {
private final SslProvider clientProvider;
private final boolean serverProduceError;
private final CertificateException exception;
private final Promise<Void> promise; private final Promise<Void> promise;
AlertValidationHandler(Promise<Void> promise) { AlertValidationHandler(SslProvider clientProvider, boolean serverProduceError,
CertificateException exception, Promise<Void> promise) {
this.clientProvider = clientProvider;
this.serverProduceError = serverProduceError;
this.exception = exception;
this.promise = promise; this.promise = promise;
} }
@ -256,20 +259,20 @@ public class SslErrorTest {
CertPathValidatorException.Reason reason = CertPathValidatorException.Reason reason =
((CertPathValidatorException) exception.getCause()).getReason(); ((CertPathValidatorException) exception.getCause()).getReason();
if (reason == CertPathValidatorException.BasicReason.EXPIRED) { if (reason == CertPathValidatorException.BasicReason.EXPIRED) {
verifyException(unwrappedCause, promise, "expired"); verifyException(clientProvider, serverProduceError, unwrappedCause, promise, "expired");
} else if (reason == CertPathValidatorException.BasicReason.NOT_YET_VALID) { } else if (reason == CertPathValidatorException.BasicReason.NOT_YET_VALID) {
// BoringSSL may use "expired" in this case while others use "bad" // BoringSSL may use "expired" in this case while others use "bad"
verifyException(unwrappedCause, promise, "expired", "bad"); verifyException(clientProvider, serverProduceError, unwrappedCause, promise, "expired", "bad");
} else if (reason == CertPathValidatorException.BasicReason.REVOKED) { } else if (reason == CertPathValidatorException.BasicReason.REVOKED) {
verifyException(unwrappedCause, promise, "revoked"); verifyException(clientProvider, serverProduceError, unwrappedCause, promise, "revoked");
} }
} else if (exception instanceof CertificateExpiredException) { } else if (exception instanceof CertificateExpiredException) {
verifyException(unwrappedCause, promise, "expired"); verifyException(clientProvider, serverProduceError, unwrappedCause, promise, "expired");
} else if (exception instanceof CertificateNotYetValidException) { } else if (exception instanceof CertificateNotYetValidException) {
// BoringSSL may use "expired" in this case while others use "bad" // BoringSSL may use "expired" in this case while others use "bad"
verifyException(unwrappedCause, promise, "expired", "bad"); verifyException(clientProvider, serverProduceError, unwrappedCause, promise, "expired", "bad");
} else if (exception instanceof CertificateRevokedException) { } else if (exception instanceof CertificateRevokedException) {
verifyException(unwrappedCause, promise, "revoked"); verifyException(clientProvider, serverProduceError, unwrappedCause, promise, "revoked");
} }
} }
} }
@ -277,7 +280,8 @@ public class SslErrorTest {
// Its a bit hacky to verify against the message that is part of the exception but there is no other way // Its a bit hacky to verify against the message that is part of the exception but there is no other way
// at the moment as there are no different exceptions for the different alerts. // at the moment as there are no different exceptions for the different alerts.
private void verifyException(Throwable cause, Promise<Void> promise, String... messageParts) { private static void verifyException(SslProvider clientProvider, boolean serverProduceError,
Throwable cause, Promise<Void> promise, String... messageParts) {
String message = cause.getMessage(); String message = cause.getMessage();
// When the error is produced on the client side and the client side uses JDK as provider it will always // When the error is produced on the client side and the client side uses JDK as provider it will always
// use "certificate unknown". // use "certificate unknown".

View File

@ -58,8 +58,10 @@ import io.netty.util.concurrent.Promise;
import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.EmptyArrays;
import org.hamcrest.CoreMatchers; import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import org.junit.Assume;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Disabled;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
@ -95,18 +97,21 @@ import javax.net.ssl.X509ExtendedTrustManager;
import static io.netty.buffer.Unpooled.wrappedBuffer; import static io.netty.buffer.Unpooled.wrappedBuffer;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
public class SslHandlerTest { public class SslHandlerTest {
@Test(timeout = 5000) @Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
public void testNonApplicationDataFailureFailsQueuedWrites() throws NoSuchAlgorithmException, InterruptedException { public void testNonApplicationDataFailureFailsQueuedWrites() throws NoSuchAlgorithmException, InterruptedException {
final CountDownLatch writeLatch = new CountDownLatch(1); final CountDownLatch writeLatch = new CountDownLatch(1);
final Queue<ChannelPromise> writesToFail = new ConcurrentLinkedQueue<ChannelPromise>(); final Queue<ChannelPromise> writesToFail = new ConcurrentLinkedQueue<ChannelPromise>();
@ -198,14 +203,26 @@ public class SslHandlerTest {
assertFalse(ch.finishAndReleaseAll()); assertFalse(ch.finishAndReleaseAll());
} }
@Test(expected = SslHandshakeTimeoutException.class, timeout = 3000) @Test
public void testClientHandshakeTimeout() throws Throwable { @Timeout(value = 3000, unit = TimeUnit.MILLISECONDS)
testHandshakeTimeout(true); public void testClientHandshakeTimeout() throws Exception {
assertThrows(SslHandshakeTimeoutException.class, new Executable() {
@Override
public void execute() throws Throwable {
testHandshakeTimeout(true);
}
});
} }
@Test(expected = SslHandshakeTimeoutException.class, timeout = 3000) @Test
public void testServerHandshakeTimeout() throws Throwable { @Timeout(value = 3000, unit = TimeUnit.MILLISECONDS)
testHandshakeTimeout(false); public void testServerHandshakeTimeout() throws Exception {
assertThrows(SslHandshakeTimeoutException.class, new Executable() {
@Override
public void execute() throws Throwable {
testHandshakeTimeout(false);
}
});
} }
private static SSLEngine newServerModeSSLEngine() throws NoSuchAlgorithmException { private static SSLEngine newServerModeSSLEngine() throws NoSuchAlgorithmException {
@ -250,7 +267,8 @@ public class SslHandlerTest {
} }
} }
@Test(timeout = 5000L) @Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
public void testHandshakeAndClosePromiseFailedOnRemoval() throws Exception { public void testHandshakeAndClosePromiseFailedOnRemoval() throws Exception {
SSLEngine engine = SSLContext.getDefault().createSSLEngine(); SSLEngine engine = SSLContext.getDefault().createSSLEngine();
engine.setUseClientMode(true); engine.setUseClientMode(true);
@ -290,7 +308,7 @@ public class SslHandlerTest {
@Test @Test
public void testTruncatedPacket() throws Exception { public void testTruncatedPacket() throws Exception {
SSLEngine engine = newServerModeSSLEngine(); SSLEngine engine = newServerModeSSLEngine();
EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine)); final EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine));
// Push the first part of a 5-byte handshake message. // Push the first part of a 5-byte handshake message.
ch.writeInbound(wrappedBuffer(new byte[]{22, 3, 1, 0, 5})); ch.writeInbound(wrappedBuffer(new byte[]{22, 3, 1, 0, 5}));
@ -298,27 +316,28 @@ public class SslHandlerTest {
// Should decode nothing yet. // Should decode nothing yet.
assertThat(ch.readInbound(), is(nullValue())); assertThat(ch.readInbound(), is(nullValue()));
try { DecoderException e = assertThrows(DecoderException.class, new Executable() {
// Push the second part of the 5-byte handshake message. @Override
ch.writeInbound(wrappedBuffer(new byte[]{2, 0, 0, 1, 0})); public void execute() throws Throwable {
fail(); // Push the second part of the 5-byte handshake message.
} catch (DecoderException e) { ch.writeInbound(wrappedBuffer(new byte[]{2, 0, 0, 1, 0}));
// Be sure we cleanup the channel and release any pending messages that may have been generated because }
// of an alert. });
// See https://github.com/netty/netty/issues/6057. // Be sure we cleanup the channel and release any pending messages that may have been generated because
ch.finishAndReleaseAll(); // of an alert.
// See https://github.com/netty/netty/issues/6057.
ch.finishAndReleaseAll();
// The pushed message is invalid, so it should raise an exception if it decoded the message correctly. // The pushed message is invalid, so it should raise an exception if it decoded the message correctly.
assertThat(e.getCause(), is(instanceOf(SSLProtocolException.class))); assertThat(e.getCause(), is(instanceOf(SSLProtocolException.class)));
}
} }
@Test @Test
public void testNonByteBufWriteIsReleased() throws Exception { public void testNonByteBufWriteIsReleased() throws Exception {
SSLEngine engine = newServerModeSSLEngine(); SSLEngine engine = newServerModeSSLEngine();
EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine)); final EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine));
AbstractReferenceCounted referenceCounted = new AbstractReferenceCounted() { final AbstractReferenceCounted referenceCounted = new AbstractReferenceCounted() {
@Override @Override
public ReferenceCounted touch(Object hint) { public ReferenceCounted touch(Object hint) {
return this; return this;
@ -328,26 +347,30 @@ public class SslHandlerTest {
protected void deallocate() { protected void deallocate() {
} }
}; };
try {
ch.write(referenceCounted).get(); ExecutionException e = assertThrows(ExecutionException.class, new Executable() {
fail(); @Override
} catch (ExecutionException e) { public void execute() throws Throwable {
assertThat(e.getCause(), is(instanceOf(UnsupportedMessageTypeException.class))); ch.write(referenceCounted).get();
} }
});
assertThat(e.getCause(), is(instanceOf(UnsupportedMessageTypeException.class)));
assertEquals(0, referenceCounted.refCnt()); assertEquals(0, referenceCounted.refCnt());
assertTrue(ch.finishAndReleaseAll()); assertTrue(ch.finishAndReleaseAll());
} }
@Test(expected = UnsupportedMessageTypeException.class) @Test
public void testNonByteBufNotPassThrough() throws Exception { public void testNonByteBufNotPassThrough() throws Exception {
SSLEngine engine = newServerModeSSLEngine(); SSLEngine engine = newServerModeSSLEngine();
EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine)); final EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine));
try { assertThrows(UnsupportedMessageTypeException.class, new Executable() {
ch.writeOutbound(new Object()); @Override
} finally { public void execute() throws Throwable {
ch.finishAndReleaseAll(); ch.writeOutbound(new Object());
} }
});
ch.finishAndReleaseAll();
} }
@Test @Test
@ -445,7 +468,8 @@ public class SslHandlerTest {
new TlsReadTest().test(true); new TlsReadTest().test(true);
} }
@Test(timeout = 30000) @Test
@Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void testRemoval() throws Exception { public void testRemoval() throws Exception {
EventLoopGroup group = new MultithreadEventLoopGroup(NioHandler.newFactory()); EventLoopGroup group = new MultithreadEventLoopGroup(NioHandler.newFactory());
Channel sc = null; Channel sc = null;
@ -537,7 +561,8 @@ public class SslHandlerTest {
assertTrue(handler.sslCloseFuture().cause() instanceof ClosedChannelException); assertTrue(handler.sslCloseFuture().cause() instanceof ClosedChannelException);
} }
@Test(timeout = 5000) @Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
public void testEventsFired() throws Exception { public void testEventsFired() throws Exception {
SSLEngine engine = newServerModeSSLEngine(); SSLEngine engine = newServerModeSSLEngine();
final BlockingQueue<SslCompletionEvent> events = new LinkedBlockingQueue<>(); final BlockingQueue<SslCompletionEvent> events = new LinkedBlockingQueue<>();
@ -562,7 +587,8 @@ public class SslHandlerTest {
assertTrue(events.isEmpty()); assertTrue(events.isEmpty());
} }
@Test(timeout = 5000) @Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
public void testHandshakeFailBeforeWritePromise() throws Exception { public void testHandshakeFailBeforeWritePromise() throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate(); SelfSignedCertificate ssc = new SelfSignedCertificate();
final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
@ -724,7 +750,8 @@ public class SslHandlerTest {
} }
} }
@Test(timeout = 10000) @Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testCloseOnHandshakeFailure() throws Exception { public void testCloseOnHandshakeFailure() throws Exception {
final SelfSignedCertificate ssc = new SelfSignedCertificate(); final SelfSignedCertificate ssc = new SelfSignedCertificate();
@ -799,7 +826,8 @@ public class SslHandlerTest {
assertTrue(engine.isOutboundDone()); assertTrue(engine.isOutboundDone());
} }
@Test(timeout = 10000) @Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testHandshakeFailedByWriteBeforeChannelActive() throws Exception { public void testHandshakeFailedByWriteBeforeChannelActive() throws Exception {
final SslContext sslClientCtx = SslContextBuilder.forClient() final SslContext sslClientCtx = SslContextBuilder.forClient()
.protocols(SslUtils.PROTOCOL_SSL_V3) .protocols(SslUtils.PROTOCOL_SSL_V3)
@ -869,12 +897,14 @@ public class SslHandlerTest {
} }
} }
@Test(timeout = 10000) @Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testHandshakeTimeoutFlushStartsHandshake() throws Exception { public void testHandshakeTimeoutFlushStartsHandshake() throws Exception {
testHandshakeTimeout0(false); testHandshakeTimeout0(false);
} }
@Test(timeout = 10000) @Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testHandshakeTimeoutStartTLS() throws Exception { public void testHandshakeTimeoutStartTLS() throws Exception {
testHandshakeTimeout0(true); testHandshakeTimeout0(true);
} }
@ -1089,23 +1119,27 @@ public class SslHandlerTest {
} }
} }
@Test(timeout = 5000L) @Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
public void testSessionTicketsWithTLSv12() throws Throwable { public void testSessionTicketsWithTLSv12() throws Throwable {
testSessionTickets(SslProvider.OPENSSL, SslUtils.PROTOCOL_TLS_V1_2, true); testSessionTickets(SslProvider.OPENSSL, SslUtils.PROTOCOL_TLS_V1_2, true);
} }
@Test(timeout = 5000L) @Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
public void testSessionTicketsWithTLSv13() throws Throwable { public void testSessionTicketsWithTLSv13() throws Throwable {
assumeTrue(SslProvider.isTlsv13Supported(SslProvider.OPENSSL)); assumeTrue(SslProvider.isTlsv13Supported(SslProvider.OPENSSL));
testSessionTickets(SslProvider.OPENSSL, SslUtils.PROTOCOL_TLS_V1_3, true); testSessionTickets(SslProvider.OPENSSL, SslUtils.PROTOCOL_TLS_V1_3, true);
} }
@Test(timeout = 5000L) @Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
public void testSessionTicketsWithTLSv12AndNoKey() throws Throwable { public void testSessionTicketsWithTLSv12AndNoKey() throws Throwable {
testSessionTickets(SslProvider.OPENSSL, SslUtils.PROTOCOL_TLS_V1_2, false); testSessionTickets(SslProvider.OPENSSL, SslUtils.PROTOCOL_TLS_V1_2, false);
} }
@Test(timeout = 5000L) @Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
public void testSessionTicketsWithTLSv13AndNoKey() throws Throwable { public void testSessionTicketsWithTLSv13AndNoKey() throws Throwable {
assumeTrue(SslProvider.isTlsv13Supported(SslProvider.OPENSSL)); assumeTrue(SslProvider.isTlsv13Supported(SslProvider.OPENSSL));
testSessionTickets(SslProvider.OPENSSL, SslUtils.PROTOCOL_TLS_V1_3, false); testSessionTickets(SslProvider.OPENSSL, SslUtils.PROTOCOL_TLS_V1_3, false);
@ -1263,7 +1297,8 @@ public class SslHandlerTest {
} }
} }
@Test(timeout = 10000L) @Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testHandshakeFailureOnlyFireExceptionOnce() throws Exception { public void testHandshakeFailureOnlyFireExceptionOnce() throws Exception {
final SslContext sslClientCtx = SslContextBuilder.forClient() final SslContext sslClientCtx = SslContextBuilder.forClient()
.trustManager(new X509ExtendedTrustManager() { .trustManager(new X509ExtendedTrustManager() {
@ -1385,7 +1420,7 @@ public class SslHandlerTest {
@Test @Test
public void testHandshakeFailureCipherMissmatchTLSv13Jdk() throws Exception { public void testHandshakeFailureCipherMissmatchTLSv13Jdk() throws Exception {
Assume.assumeTrue(SslProvider.isTlsv13Supported(SslProvider.JDK)); assumeTrue(SslProvider.isTlsv13Supported(SslProvider.JDK));
testHandshakeFailureCipherMissmatch(SslProvider.JDK, true); testHandshakeFailureCipherMissmatch(SslProvider.JDK, true);
} }
@ -1399,8 +1434,8 @@ public class SslHandlerTest {
@Test @Test
public void testHandshakeFailureCipherMissmatchTLSv13OpenSsl() throws Exception { public void testHandshakeFailureCipherMissmatchTLSv13OpenSsl() throws Exception {
OpenSsl.ensureAvailability(); OpenSsl.ensureAvailability();
Assume.assumeTrue(SslProvider.isTlsv13Supported(SslProvider.OPENSSL)); assumeTrue(SslProvider.isTlsv13Supported(SslProvider.OPENSSL));
Assume.assumeFalse("BoringSSL does not support setting ciphers for TLSv1.3 explicit", OpenSsl.isBoringSSL()); assumeFalse(OpenSsl.isBoringSSL(), "BoringSSL does not support setting ciphers for TLSv1.3 explicit");
testHandshakeFailureCipherMissmatch(SslProvider.OPENSSL, true); testHandshakeFailureCipherMissmatch(SslProvider.OPENSSL, true);
} }

View File

@ -17,7 +17,7 @@ package io.netty.handler.ssl;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngine;
@ -27,9 +27,9 @@ import java.nio.ByteOrder;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import static io.netty.handler.ssl.SslUtils.getEncryptedPacketLength; import static io.netty.handler.ssl.SslUtils.getEncryptedPacketLength;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
public class SslUtilsTest { public class SslUtilsTest {

View File

@ -41,6 +41,11 @@ import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate; import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.function.Executable;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
@ -50,51 +55,60 @@ import java.util.concurrent.atomic.AtomicReference;
import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLHandshakeException;
import org.junit.BeforeClass; import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.Assert.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.Assert.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.junit.Assume.assumeTrue;
public class OcspTest { public class OcspTest {
@BeforeClass @BeforeAll
public static void checkOcspSupported() { public static void checkOcspSupported() {
assumeTrue(OpenSsl.isOcspSupported()); assumeTrue(OpenSsl.isOcspSupported());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testJdkClientEnableOcsp() throws Exception { public void testJdkClientEnableOcsp() throws Exception {
SslContextBuilder.forClient() assertThrows(IllegalArgumentException.class, new Executable() {
.sslProvider(SslProvider.JDK) @Override
.enableOcsp(true) public void execute() throws Throwable {
.build(); SslContextBuilder.forClient()
.sslProvider(SslProvider.JDK)
.enableOcsp(true)
.build();
}
});
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testJdkServerEnableOcsp() throws Exception { public void testJdkServerEnableOcsp() throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate(); final SelfSignedCertificate ssc = new SelfSignedCertificate();
try { try {
SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()) assertThrows(IllegalArgumentException.class, new Executable() {
.sslProvider(SslProvider.JDK) @Override
.enableOcsp(true) public void execute() throws Throwable {
.build(); SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
.sslProvider(SslProvider.JDK)
.enableOcsp(true)
.build();
}
});
} finally { } finally {
ssc.delete(); ssc.delete();
} }
} }
@Test(expected = IllegalStateException.class) @Test
public void testClientOcspNotEnabledOpenSsl() throws Exception { public void testClientOcspNotEnabledOpenSsl() throws Exception {
testClientOcspNotEnabled(SslProvider.OPENSSL); testClientOcspNotEnabled(SslProvider.OPENSSL);
} }
@Test(expected = IllegalStateException.class) @Test
public void testClientOcspNotEnabledOpenSslRefCnt() throws Exception { public void testClientOcspNotEnabledOpenSslRefCnt() throws Exception {
testClientOcspNotEnabled(SslProvider.OPENSSL_REFCNT); testClientOcspNotEnabled(SslProvider.OPENSSL_REFCNT);
} }
@ -105,9 +119,14 @@ public class OcspTest {
.build(); .build();
try { try {
SslHandler sslHandler = context.newHandler(ByteBufAllocator.DEFAULT); SslHandler sslHandler = context.newHandler(ByteBufAllocator.DEFAULT);
ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine(); final ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();
try { try {
engine.getOcspResponse(); assertThrows(IllegalStateException.class, new Executable() {
@Override
public void execute() {
engine.getOcspResponse();
}
});
} finally { } finally {
engine.release(); engine.release();
} }
@ -116,12 +135,12 @@ public class OcspTest {
} }
} }
@Test(expected = IllegalStateException.class) @Test
public void testServerOcspNotEnabledOpenSsl() throws Exception { public void testServerOcspNotEnabledOpenSsl() throws Exception {
testServerOcspNotEnabled(SslProvider.OPENSSL); testServerOcspNotEnabled(SslProvider.OPENSSL);
} }
@Test(expected = IllegalStateException.class) @Test
public void testServerOcspNotEnabledOpenSslRefCnt() throws Exception { public void testServerOcspNotEnabledOpenSslRefCnt() throws Exception {
testServerOcspNotEnabled(SslProvider.OPENSSL_REFCNT); testServerOcspNotEnabled(SslProvider.OPENSSL_REFCNT);
} }
@ -134,9 +153,14 @@ public class OcspTest {
.build(); .build();
try { try {
SslHandler sslHandler = context.newHandler(ByteBufAllocator.DEFAULT); SslHandler sslHandler = context.newHandler(ByteBufAllocator.DEFAULT);
ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine(); final ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();
try { try {
engine.setOcspResponse(new byte[] { 1, 2, 3 }); assertThrows(IllegalStateException.class, new Executable() {
@Override
public void execute() {
engine.setOcspResponse(new byte[] { 1, 2, 3 });
}
});
} finally { } finally {
engine.release(); engine.release();
} }
@ -148,12 +172,14 @@ public class OcspTest {
} }
} }
@Test(timeout = 10000L) @Test
@Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS)
public void testClientAcceptingOcspStapleOpenSsl() throws Exception { public void testClientAcceptingOcspStapleOpenSsl() throws Exception {
testClientAcceptingOcspStaple(SslProvider.OPENSSL); testClientAcceptingOcspStaple(SslProvider.OPENSSL);
} }
@Test(timeout = 10000L) @Test
@Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS)
public void testClientAcceptingOcspStapleOpenSslRefCnt() throws Exception { public void testClientAcceptingOcspStapleOpenSslRefCnt() throws Exception {
testClientAcceptingOcspStaple(SslProvider.OPENSSL_REFCNT); testClientAcceptingOcspStaple(SslProvider.OPENSSL_REFCNT);
} }
@ -194,12 +220,14 @@ public class OcspTest {
assertArrayEquals(response, actual); assertArrayEquals(response, actual);
} }
@Test(timeout = 10000L) @Test
@Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS)
public void testClientRejectingOcspStapleOpenSsl() throws Exception { public void testClientRejectingOcspStapleOpenSsl() throws Exception {
testClientRejectingOcspStaple(SslProvider.OPENSSL); testClientRejectingOcspStaple(SslProvider.OPENSSL);
} }
@Test(timeout = 10000L) @Test
@Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS)
public void testClientRejectingOcspStapleOpenSslRefCnt() throws Exception { public void testClientRejectingOcspStapleOpenSslRefCnt() throws Exception {
testClientRejectingOcspStaple(SslProvider.OPENSSL_REFCNT); testClientRejectingOcspStaple(SslProvider.OPENSSL_REFCNT);
} }
@ -234,15 +262,17 @@ public class OcspTest {
assertArrayEquals(response, actual); assertArrayEquals(response, actual);
Throwable cause = causeRef.get(); Throwable cause = causeRef.get();
assertTrue("" + cause, cause instanceof SSLHandshakeException); assertThat(cause, CoreMatchers.instanceOf(SSLHandshakeException.class));
} }
@Test(timeout = 10000L) @Test
@Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS)
public void testServerHasNoStapleOpenSsl() throws Exception { public void testServerHasNoStapleOpenSsl() throws Exception {
testServerHasNoStaple(SslProvider.OPENSSL); testServerHasNoStaple(SslProvider.OPENSSL);
} }
@Test(timeout = 10000L) @Test
@Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS)
public void testServerHasNoStapleOpenSslRefCnt() throws Exception { public void testServerHasNoStapleOpenSslRefCnt() throws Exception {
testServerHasNoStaple(SslProvider.OPENSSL_REFCNT); testServerHasNoStaple(SslProvider.OPENSSL_REFCNT);
} }
@ -282,12 +312,14 @@ public class OcspTest {
assertNull(actual); assertNull(actual);
} }
@Test(timeout = 10000L) @Test
@Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS)
public void testClientExceptionOpenSsl() throws Exception { public void testClientExceptionOpenSsl() throws Exception {
testClientException(SslProvider.OPENSSL); testClientException(SslProvider.OPENSSL);
} }
@Test(timeout = 10000L) @Test
@Timeout(value = 10000L, unit = TimeUnit.MILLISECONDS)
public void testClientExceptionOpenSslRefCnt() throws Exception { public void testClientExceptionOpenSslRefCnt() throws Exception {
testClientException(SslProvider.OPENSSL_REFCNT); testClientException(SslProvider.OPENSSL_REFCNT);
} }
@ -347,7 +379,7 @@ public class OcspTest {
Channel server = newServer(group, address, serverSslContext, response, serverHandler); Channel server = newServer(group, address, serverSslContext, response, serverHandler);
Channel client = newClient(group, address, clientSslContext, callback, clientHandler); Channel client = newClient(group, address, clientSslContext, callback, clientHandler);
try { try {
assertTrue("Something went wrong.", latch.await(10L, TimeUnit.SECONDS)); assertTrue(latch.await(10L, TimeUnit.SECONDS));
} finally { } finally {
client.close().syncUninterruptibly(); client.close().syncUninterruptibly();
server.close().syncUninterruptibly(); server.close().syncUninterruptibly();

View File

@ -16,15 +16,18 @@
package io.netty.handler.ssl.util; package io.netty.handler.ssl.util;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import static io.netty.handler.ssl.Java8SslTestUtils.loadCertCollection; import static io.netty.handler.ssl.Java8SslTestUtils.loadCertCollection;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class FingerprintTrustManagerFactoryTest { public class FingerprintTrustManagerFactoryTest {
@ -48,27 +51,47 @@ public class FingerprintTrustManagerFactoryTest {
} }
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testFingerprintWithInvalidLength() { public void testFingerprintWithInvalidLength() {
FingerprintTrustManagerFactory.builder("SHA-256").fingerprints("00:00:00").build(); assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
FingerprintTrustManagerFactory.builder("SHA-256").fingerprints("00:00:00").build();
}
});
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testFingerprintWithUnexpectedCharacters() { public void testFingerprintWithUnexpectedCharacters() {
FingerprintTrustManagerFactory.builder("SHA-256").fingerprints("00:00:00\n").build(); assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
FingerprintTrustManagerFactory.builder("SHA-256").fingerprints("00:00:00\n").build();
}
});
} }
@Test(expected = IllegalStateException.class) @Test
public void testWithNoFingerprints() { public void testWithNoFingerprints() {
FingerprintTrustManagerFactory.builder("SHA-256").build(); assertThrows(IllegalStateException.class, new Executable() {
@Override
public void execute() {
FingerprintTrustManagerFactory.builder("SHA-256").build();
}
});
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testWithNullFingerprint() { public void testWithNullFingerprint() {
FingerprintTrustManagerFactory assertThrows(IllegalArgumentException.class, new Executable() {
.builder("SHA-256") @Override
.fingerprints(FIRST_CERT_SHA256_FINGERPRINT, null) public void execute() {
.build(); FingerprintTrustManagerFactory
.builder("SHA-256")
.fingerprints(FIRST_CERT_SHA256_FINGERPRINT, null)
.build();
}
});
} }
@Test @Test
@ -97,7 +120,7 @@ public class FingerprintTrustManagerFactoryTest {
tm.checkClientTrusted(keyCertChain, "test"); tm.checkClientTrusted(keyCertChain, "test");
} }
@Test(expected = CertificateException.class) @Test
public void testUntrustedCertificateWithSHA256Fingerprint() throws Exception { public void testUntrustedCertificateWithSHA256Fingerprint() throws Exception {
FingerprintTrustManagerFactory factory = FingerprintTrustManagerFactory FingerprintTrustManagerFactory factory = FingerprintTrustManagerFactory
.builder("SHA-256") .builder("SHA-256")
@ -106,8 +129,14 @@ public class FingerprintTrustManagerFactoryTest {
assertTrue(factory.engineGetTrustManagers().length > 0); assertTrue(factory.engineGetTrustManagers().length > 0);
assertTrue(factory.engineGetTrustManagers()[0] instanceof X509TrustManager); assertTrue(factory.engineGetTrustManagers()[0] instanceof X509TrustManager);
X509TrustManager tm = (X509TrustManager) factory.engineGetTrustManagers()[0]; final X509TrustManager tm = (X509TrustManager) factory.engineGetTrustManagers()[0];
tm.checkClientTrusted(SECOND_CHAIN, "test");
assertThrows(CertificateException.class, new Executable() {
@Override
public void execute() throws Throwable {
tm.checkClientTrusted(SECOND_CHAIN, "test");
}
});
} }
} }

View File

@ -27,8 +27,8 @@ import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test; import org.junit.jupiter.api.function.Executable;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
@ -43,7 +43,11 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import static java.util.concurrent.TimeUnit.*; import static java.util.concurrent.TimeUnit.*;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ChunkedWriteHandlerTest { public class ChunkedWriteHandlerTest {
private static final byte[] BYTES = new byte[1024 * 64]; private static final byte[] BYTES = new byte[1024 * 64];
@ -120,8 +124,8 @@ public class ChunkedWriteHandlerTest {
//no op //no op
} }
}); });
Assert.assertTrue(in.isOpen()); assertTrue(in.isOpen());
Assert.assertEquals(expectedPosition, in.position()); assertEquals(expectedPosition, in.position());
} finally { } finally {
if (in != null) { if (in != null) {
in.close(); in.close();
@ -129,17 +133,22 @@ public class ChunkedWriteHandlerTest {
} }
} }
@Test(expected = ClosedChannelException.class) @Test
public void testChunkedNioFileFailOnClosedFileChannel() throws IOException { public void testChunkedNioFileFailOnClosedFileChannel() throws IOException {
final FileChannel in = new RandomAccessFile(TMP, "r").getChannel(); final FileChannel in = new RandomAccessFile(TMP, "r").getChannel();
in.close(); in.close();
check(new ChunkedNioFile(in) {
assertThrows(ClosedChannelException.class, new Executable() {
@Override @Override
public void close() throws Exception { public void execute() throws Throwable {
//no op check(new ChunkedNioFile(in) {
@Override
public void close() throws Exception {
//no op
}
});
} }
}); });
Assert.fail();
} }
@Test @Test
@ -490,16 +499,16 @@ public class ChunkedWriteHandlerTest {
@Test @Test
public void testCloseFailedChunkedInput() { public void testCloseFailedChunkedInput() {
Exception error = new Exception("Unable to produce a chunk"); Exception error = new Exception("Unable to produce a chunk");
ThrowingChunkedInput input = new ThrowingChunkedInput(error); final ThrowingChunkedInput input = new ThrowingChunkedInput(error);
final EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler());
EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler()); Exception e = assertThrows(Exception.class, new Executable() {
@Override
try { public void execute() throws Throwable {
ch.writeOutbound(input); ch.writeOutbound(input);
fail("Exception expected"); }
} catch (Exception e) { });
assertEquals(error, e); assertEquals(error, e);
}
assertTrue(input.isClosed()); assertTrue(input.isClosed());
assertFalse(ch.finish()); assertFalse(ch.finish());

View File

@ -15,7 +15,8 @@
*/ */
package io.netty.handler.timeout; package io.netty.handler.timeout;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static io.netty.handler.timeout.IdleStateEvent.*; import static io.netty.handler.timeout.IdleStateEvent.*;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;

View File

@ -15,26 +15,26 @@
*/ */
package io.netty.handler.timeout; package io.netty.handler.timeout;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundBuffer; import io.netty.channel.ChannelOutboundBuffer;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import org.junit.jupiter.api.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
public class IdleStateHandlerTest { public class IdleStateHandlerTest {
@ -67,8 +67,7 @@ public class IdleStateHandlerTest {
} }
private static void anyIdle(TestableIdleStateHandler idleStateHandler, Object... expected) throws Exception { private static void anyIdle(TestableIdleStateHandler idleStateHandler, Object... expected) throws Exception {
assertThat(expected.length, greaterThanOrEqualTo(1));
assertTrue("The number of expected events must be >= 1", expected.length >= 1);
final List<Object> events = new ArrayList<>(); final List<Object> events = new ArrayList<>();
ChannelHandler handler = new ChannelHandler() { ChannelHandler handler = new ChannelHandler() {
@ -92,7 +91,7 @@ public class IdleStateHandlerTest {
// Compare the expected with the actual IdleStateEvents // Compare the expected with the actual IdleStateEvents
for (int i = 0; i < expected.length; i++) { for (int i = 0; i < expected.length; i++) {
Object evt = events.get(i); Object evt = events.get(i);
assertSame("Element " + i + " is not matching", expected[i], evt); assertSame(expected[i], evt, "Element " + i + " is not matching");
} }
} finally { } finally {
channel.finishAndReleaseAll(); channel.finishAndReleaseAll();

View File

@ -19,11 +19,11 @@ import io.netty.channel.DefaultChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.concurrent.DefaultEventExecutorGroup; import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.EventExecutorGroup;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
public class WriteTimeoutHandlerTest { public class WriteTimeoutHandlerTest {

View File

@ -34,11 +34,11 @@ import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeEach;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@ -49,7 +49,7 @@ import java.nio.charset.Charset;
import java.util.Random; import java.util.Random;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
public class FileRegionThrottleTest { public class FileRegionThrottleTest {
private static final byte[] BYTES = new byte[64 * 1024 * 4]; private static final byte[] BYTES = new byte[64 * 1024 * 4];
@ -57,7 +57,7 @@ public class FileRegionThrottleTest {
private static File tmp; private static File tmp;
private EventLoopGroup group; private EventLoopGroup group;
@BeforeClass @BeforeAll
public static void beforeClass() throws IOException { public static void beforeClass() throws IOException {
final Random r = new Random(); final Random r = new Random();
for (int i = 0; i < BYTES.length; i++) { for (int i = 0; i < BYTES.length; i++) {
@ -74,17 +74,17 @@ public class FileRegionThrottleTest {
} }
} }
@Before @BeforeEach
public void setUp() { public void setUp() {
group = new MultithreadEventLoopGroup(NioHandler.newFactory()); group = new MultithreadEventLoopGroup(NioHandler.newFactory());
} }
@After @AfterEach
public void tearDown() { public void tearDown() {
group.shutdownGracefully(); group.shutdownGracefully();
} }
@Ignore("This test is flaky, need more investigation") @Disabled("This test is flaky, need more investigation")
@Test @Test
public void testGlobalWriteThrottle() throws Exception { public void testGlobalWriteThrottle() throws Exception {
final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(1);
@ -105,7 +105,7 @@ public class FileRegionThrottleTest {
cc.writeAndFlush(Unpooled.copiedBuffer("send-file\n", CharsetUtil.US_ASCII)).sync(); cc.writeAndFlush(Unpooled.copiedBuffer("send-file\n", CharsetUtil.US_ASCII)).sync();
latch.await(); latch.await();
long timeTaken = TrafficCounter.milliSecondFromNano() - start; long timeTaken = TrafficCounter.milliSecondFromNano() - start;
assertTrue("Data streamed faster than expected", timeTaken > 3000); assertTrue(timeTaken > 3000, "Data streamed faster than expected");
sc.close().sync(); sc.close().sync();
cc.close().sync(); cc.close().sync();
} }

View File

@ -16,18 +16,12 @@
package io.netty.handler.traffic; package io.netty.handler.traffic;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandler;
import io.netty.channel.MultithreadEventLoopGroup; import io.netty.channel.MultithreadEventLoopGroup;
import io.netty.channel.local.LocalHandler; import io.netty.channel.local.LocalHandler;
import org.junit.AfterClass;
import org.junit.Test;
import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap; import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
@ -39,6 +33,11 @@ import io.netty.channel.local.LocalChannel;
import io.netty.channel.local.LocalServerChannel; import io.netty.channel.local.LocalServerChannel;
import io.netty.util.Attribute; import io.netty.util.Attribute;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
public class TrafficShapingHandlerTest { public class TrafficShapingHandlerTest {
@ -47,7 +46,7 @@ public class TrafficShapingHandlerTest {
private static final MultithreadEventLoopGroup GROUP = private static final MultithreadEventLoopGroup GROUP =
new MultithreadEventLoopGroup(1, LocalHandler.newFactory()); new MultithreadEventLoopGroup(1, LocalHandler.newFactory());
@AfterClass @AfterAll
public static void destroy() { public static void destroy() {
GROUP.shutdownGracefully(); GROUP.shutdownGracefully();
SES.shutdown(); SES.shutdown();