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.ChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.net.SocketAddress;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
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.assertSame;
public class DynamicAddressConnectHandlerTest {
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.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Promise;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.List;
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 {
@ -51,12 +54,12 @@ public class ResolveAddressHandlerTest {
private static EventLoopGroup group;
@BeforeClass
@BeforeAll
public static void createEventLoop() {
group = new MultithreadEventLoopGroup(LocalHandler.newFactory());
}
@AfterClass
@AfterAll
public static void destroyEventLoop() {
if (group != null) {
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.IdleStateHandler;
import io.netty.util.ReferenceCountUtil;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.net.SocketAddress;
import java.util.Queue;
@ -48,17 +48,21 @@ import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicReference;
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 {
private static EventLoopGroup GROUP;
@BeforeClass
@BeforeAll
public static void init() {
GROUP = new MultithreadEventLoopGroup(NioHandler.newFactory());
}
@AfterClass
@AfterAll
public static void destroy() {
GROUP.shutdownGracefully();
}

View File

@ -18,11 +18,15 @@ package io.netty.handler.flush;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
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 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 {
@ -124,10 +128,10 @@ public class FlushConsolidationHandlerTest {
assertFalse(channel.finish());
}
@Test(expected = IllegalStateException.class)
@Test
public void testFlushViaException() {
final AtomicInteger flushCount = new AtomicInteger();
EmbeddedChannel channel = newChannel(flushCount, false);
final EmbeddedChannel channel = newChannel(flushCount, false);
// Simulate read loop;
channel.pipeline().fireChannelRead(1L);
assertEquals(0, flushCount.get());
@ -136,7 +140,12 @@ public class FlushConsolidationHandlerTest {
assertEquals(1, flushCount.get());
assertEquals(1L, (long) channel.readOutbound());
assertNull(channel.readOutbound());
channel.finish();
assertThrows(IllegalStateException.class, new Executable() {
@Override
public void execute() throws Throwable {
channel.finish();
}
});
}
@Test

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -36,6 +36,10 @@ import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.ReferenceCountUtil;
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.security.NoSuchAlgorithmException;
@ -48,63 +52,39 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
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.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.
*/
@RunWith(Parameterized.class)
public class CipherSuiteCanaryTest {
private static EventLoopGroup GROUP;
private static SelfSignedCertificate CERT;
@Parameters(name = "{index}: serverSslProvider = {0}, clientSslProvider = {1}, rfcCipherName = {2}, delegate = {3}")
public static Collection<Object[]> parameters() {
static Collection<Object[]> parameters() {
List<Object[]> dst = new ArrayList<>();
dst.addAll(expand("TLS_DHE_RSA_WITH_AES_128_GCM_SHA256")); // DHE-RSA-AES128-GCM-SHA256
return dst;
}
@BeforeClass
@BeforeAll
public static void init() throws Exception {
GROUP = new MultithreadEventLoopGroup(LocalHandler.newFactory());
CERT = new SelfSignedCertificate();
}
@AfterClass
@AfterAll
public static void destroy() {
GROUP.shutdownGracefully();
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 {
boolean cipherSupported = false;
if (provider == SslProvider.JDK) {
@ -118,7 +98,7 @@ public class CipherSuiteCanaryTest {
} else {
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) {
@ -129,8 +109,11 @@ public class CipherSuiteCanaryTest {
}
}
@Test
public void testHandshake() throws Exception {
@ParameterizedTest(
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
// implementations.
assumeCipherAvailable(serverSslProvider, rfcCipherName);
@ -231,8 +214,8 @@ public class CipherSuiteCanaryTest {
client.writeAndFlush(Unpooled.wrappedBuffer(new byte[] {'P', 'I', 'N', 'G'}))
.syncUninterruptibly();
assertTrue("client timeout", clientPromise.await(5L, TimeUnit.SECONDS));
assertTrue("server timeout", serverPromise.await(5L, TimeUnit.SECONDS));
assertTrue(clientPromise.await(5L, TimeUnit.SECONDS), "client timeout");
assertTrue(serverPromise.await(5L, TimeUnit.SECONDS), "server timeout");
clientPromise.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.InternalLoggerFactory;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
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 {

View File

@ -22,14 +22,15 @@ import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.Collection;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
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.is;
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 {
private static final UnpooledByteBufAllocator ALLOC = UnpooledByteBufAllocator.DEFAULT;
@ -60,16 +60,7 @@ public class CloseNotifyTest {
}
};
private final SslProvider provider;
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() {
static Collection<Object[]> data() {
return asList(new Object[][] {
{ SslProvider.JDK, PROTOCOL_TLS_V1_2 },
{ SslProvider.JDK, PROTOCOL_TLS_V1_3 },
@ -78,9 +69,11 @@ public class CloseNotifyTest {
});
}
@Test(timeout = 5000)
public void eventsOrder() throws Exception {
assumeTrue("OpenSSL is not available", provider != SslProvider.OPENSSL || OpenSsl.isAvailable());
@ParameterizedTest(name = "{index}: provider={0}, protocol={1}")
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
@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)) {
// Ensure we support TLSv1.3
@ -89,8 +82,8 @@ public class CloseNotifyTest {
BlockingQueue<Object> clientEventQueue = new LinkedBlockingQueue<Object>();
BlockingQueue<Object> serverEventQueue = new LinkedBlockingQueue<Object>();
EmbeddedChannel clientChannel = initChannel(true, clientEventQueue);
EmbeddedChannel serverChannel = initChannel(false, serverEventQueue);
EmbeddedChannel clientChannel = initChannel(provider, protocol, true, clientEventQueue);
EmbeddedChannel serverChannel = initChannel(provider, protocol, false, serverEventQueue);
try {
// handshake:
@ -119,7 +112,7 @@ public class CloseNotifyTest {
assertThat(clientEventQueue.poll(), instanceOf(SslCloseCompletionEvent.class));
// 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
// "close_notify" alert. This is a legit behavior according to the spec:
// 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());
} else {
discardEmptyOutboundBuffers(clientChannel);
@ -150,11 +143,11 @@ public class CloseNotifyTest {
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);
}
private EmbeddedChannel initChannel(final boolean useClientMode,
private static EmbeddedChannel initChannel(SslProvider provider, String protocol, final boolean useClientMode,
final BlockingQueue<Object> eventQueue) throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate();

View File

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

View File

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

View File

@ -17,13 +17,15 @@ package io.netty.handler.ssl;
import io.netty.buffer.UnpooledByteBufAllocator;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import javax.net.ssl.KeyManagerFactory;
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 {
@ -40,7 +42,7 @@ public class OpenSslCachingKeyMaterialProviderTest extends OpenSslKeyMaterialPro
@Override
protected void assertRelease(OpenSslKeyMaterial material) {
Assert.assertFalse(material.release());
assertFalse(material.release());
}
@Test

View File

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

View File

@ -18,9 +18,7 @@ package io.netty.handler.ssl;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.util.internal.EmptyArrays;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLException;
import javax.net.ssl.X509ExtendedKeyManager;
@ -29,6 +27,8 @@ import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import static org.junit.jupiter.api.Assertions.fail;
public class OpenSslKeyMaterialManagerTest {
@Test
@ -71,7 +71,7 @@ public class OpenSslKeyMaterialManagerTest {
new OpenSslKeyMaterialProvider(keyManager, null) {
@Override
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;
}
});

View File

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

View File

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

View File

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

View File

@ -16,20 +16,22 @@
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.File;
import java.io.FileInputStream;
import java.security.PrivateKey;
import io.netty.buffer.UnpooledByteBufAllocator;
import org.junit.Test;
import io.netty.handler.ssl.util.SelfSignedCertificate;
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 {
@ -70,22 +72,27 @@ public class PemEncodedTest {
}
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testEncodedReturnsNull() throws Exception {
PemPrivateKey.toPEM(UnpooledByteBufAllocator.DEFAULT, true, new PrivateKey() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public String getAlgorithm() {
return null;
}
public void execute() throws Throwable {
PemPrivateKey.toPEM(UnpooledByteBufAllocator.DEFAULT, true, new PrivateKey() {
@Override
public String getAlgorithm() {
return null;
}
@Override
public String getFormat() {
return null;
}
@Override
public String getFormat() {
return null;
}
@Override
public byte[] getEncoded() {
return null;
@Override
public byte[] getEncoded() {
return null;
}
});
}
});
}

View File

@ -18,10 +18,9 @@ package io.netty.handler.ssl;
import io.netty.util.CharsetUtil;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
/**
* The test vectors here were provided via:
* 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.util.ReferenceCountUtil;
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.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public abstract class RenegotiateTest {
@Test(timeout = 30000)
@Test
@Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void testRenegotiateServer() throws Throwable {
final AtomicReference<Throwable> error = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(2);

View File

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

View File

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

View File

@ -18,8 +18,9 @@ package io.netty.handler.ssl;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.handler.ssl.util.SelfSignedCertificate;
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.SSLEngine;
@ -35,7 +36,11 @@ import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
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 {
@ -102,23 +107,33 @@ public class SslContextBuilderTest {
@Test
public void testContextFromManagersOpenssl() throws Exception {
OpenSsl.ensureAvailability();
Assume.assumeTrue(OpenSsl.supportsKeyManagerFactory());
assumeTrue(OpenSsl.supportsKeyManagerFactory());
testContextFromManagers(SslProvider.OPENSSL);
}
@Test(expected = SSLException.class)
@Test
public void testUnsupportedPrivateKeyFailsFastForServer() throws Exception {
Assume.assumeTrue(OpenSsl.isBoringSSL());
testUnsupportedPrivateKeyFailsFast(true);
assumeTrue(OpenSsl.isBoringSSL());
assertThrows(SSLException.class, new Executable() {
@Override
public void execute() throws Throwable {
testUnsupportedPrivateKeyFailsFast(true);
}
});
}
@Test(expected = SSLException.class)
@Test
public void testUnsupportedPrivateKeyFailsFastForClient() throws Exception {
Assume.assumeTrue(OpenSsl.isBoringSSL());
testUnsupportedPrivateKeyFailsFast(false);
assumeTrue(OpenSsl.isBoringSSL());
assertThrows(SSLException.class, new Executable() {
@Override
public void execute() throws Throwable {
testUnsupportedPrivateKeyFailsFast(false);
}
});
}
private static void testUnsupportedPrivateKeyFailsFast(boolean server) throws Exception {
Assume.assumeTrue(OpenSsl.isBoringSSL());
assumeTrue(OpenSsl.isBoringSSL());
String cert = "-----BEGIN CERTIFICATE-----\n" +
"MIICODCCAY2gAwIBAgIEXKTrajAKBggqhkjOPQQDBDBUMQswCQYDVQQGEwJVUzEM\n" +
"MAoGA1UECAwDTi9hMQwwCgYDVQQHDANOL2ExDDAKBgNVBAoMA04vYTEMMAoGA1UE\n" +
@ -152,10 +167,15 @@ public class SslContextBuilderTest {
}
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testInvalidCipherJdk() throws Exception {
OpenSsl.ensureAvailability();
testInvalidCipher(SslProvider.JDK);
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() throws Throwable {
testInvalidCipher(SslProvider.JDK);
}
});
}
@Test

View File

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

View File

@ -15,7 +15,7 @@
*/
package io.netty.handler.ssl;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
@ -25,8 +25,8 @@ import java.security.cert.X509Certificate;
import java.util.Arrays;
import static io.netty.handler.ssl.Java8SslTestUtils.loadCertCollection;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
public class SslContextTrustManagerTest {
@Test
@ -84,7 +84,7 @@ public class SslContextTrustManagerTest {
for (int i = 0; i < eecResources.length; i++) {
X509Certificate eecCert = eecCerts[i];
assertNotNull("Cannot use cert " + eecResources[i], eecCert);
assertNotNull(eecCert, "Cannot use cert " + eecResources[i]);
try {
tm.checkServerTrusted(new X509Certificate[] { eecCert }, "RSA");
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.concurrent.Promise;
import io.netty.util.internal.EmptyArrays;
import org.junit.Assume;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import javax.net.ssl.ManagerFactoryParameters;
import javax.net.ssl.SSLException;
@ -60,14 +59,11 @@ import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
@RunWith(Parameterized.class)
public class SslErrorTest {
@Parameterized.Parameters(
name = "{index}: serverProvider = {0}, clientProvider = {1}, exception = {2}, serverProduceError = {3}")
public static Collection<Object[]> data() {
static Collection<Object[]> data() {
List<SslProvider> serverProviders = new ArrayList<>(2);
List<SslProvider> clientProviders = new ArrayList<>(3);
@ -110,21 +106,13 @@ public class SslErrorTest {
new CertPathValidatorException("x", null, null, -1, reason));
}
private final SslProvider serverProvider;
private final SslProvider clientProvider;
private final CertificateException exception;
private final boolean serverProduceError;
public SslErrorTest(SslProvider serverProvider, SslProvider clientProvider,
CertificateException exception, boolean serverProduceError) {
this.serverProvider = serverProvider;
this.clientProvider = clientProvider;
this.exception = exception;
this.serverProduceError = serverProduceError;
}
@Test(timeout = 30000)
public void testCorrectAlert() throws Exception {
@ParameterizedTest(
name = "{index}: serverProvider = {0}, clientProvider = {1}, exception = {2}, serverProduceError = {3}")
@MethodSource("data")
@Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void testCorrectAlert(SslProvider serverProvider, final SslProvider clientProvider,
final CertificateException exception, final boolean serverProduceError)
throws Exception {
// 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.
OpenSsl.ensureAvailability();
@ -140,11 +128,11 @@ public class SslErrorTest {
.sslProvider(clientProvider);
if (serverProduceError) {
sslServerCtxBuilder.trustManager(new ExceptionTrustManagerFactory());
sslServerCtxBuilder.trustManager(new ExceptionTrustManagerFactory(exception));
sslClientCtxBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
} else {
sslServerCtxBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
sslClientCtxBuilder.trustManager(new ExceptionTrustManagerFactory());
sslClientCtxBuilder.trustManager(new ExceptionTrustManagerFactory(exception));
}
final SslContext sslServerCtx = sslServerCtxBuilder.build();
@ -163,7 +151,8 @@ public class SslErrorTest {
protected void initChannel(Channel ch) {
ch.pipeline().addLast(sslServerCtx.newHandler(ch.alloc()));
if (!serverProduceError) {
ch.pipeline().addLast(new AlertValidationHandler(promise));
ch.pipeline().addLast(new AlertValidationHandler(clientProvider, serverProduceError,
exception, promise));
}
ch.pipeline().addLast(new ChannelHandler() {
@ -183,7 +172,8 @@ public class SslErrorTest {
ch.pipeline().addLast(sslClientCtx.newHandler(ch.alloc()));
if (serverProduceError) {
ch.pipeline().addLast(new AlertValidationHandler(promise));
ch.pipeline().addLast(new AlertValidationHandler(clientProvider, serverProduceError,
exception, promise));
}
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
protected void engineInit(KeyStore keyStore) { }
@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;
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;
}
@ -256,20 +259,20 @@ public class SslErrorTest {
CertPathValidatorException.Reason reason =
((CertPathValidatorException) exception.getCause()).getReason();
if (reason == CertPathValidatorException.BasicReason.EXPIRED) {
verifyException(unwrappedCause, promise, "expired");
verifyException(clientProvider, serverProduceError, unwrappedCause, promise, "expired");
} else if (reason == CertPathValidatorException.BasicReason.NOT_YET_VALID) {
// 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) {
verifyException(unwrappedCause, promise, "revoked");
verifyException(clientProvider, serverProduceError, unwrappedCause, promise, "revoked");
}
} else if (exception instanceof CertificateExpiredException) {
verifyException(unwrappedCause, promise, "expired");
verifyException(clientProvider, serverProduceError, unwrappedCause, promise, "expired");
} else if (exception instanceof CertificateNotYetValidException) {
// 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) {
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
// 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();
// When the error is produced on the client side and the client side uses JDK as provider it will always
// use "certificate unknown".

View File

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

View File

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

View File

@ -16,15 +16,18 @@
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 java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import static io.netty.handler.ssl.Java8SslTestUtils.loadCertCollection;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class FingerprintTrustManagerFactoryTest {
@ -48,27 +51,47 @@ public class FingerprintTrustManagerFactoryTest {
}
}
@Test(expected = IllegalArgumentException.class)
@Test
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() {
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() {
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() {
FingerprintTrustManagerFactory
.builder("SHA-256")
.fingerprints(FIRST_CERT_SHA256_FINGERPRINT, null)
.build();
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
FingerprintTrustManagerFactory
.builder("SHA-256")
.fingerprints(FIRST_CERT_SHA256_FINGERPRINT, null)
.build();
}
});
}
@Test
@ -97,7 +120,7 @@ public class FingerprintTrustManagerFactoryTest {
tm.checkClientTrusted(keyCertChain, "test");
}
@Test(expected = CertificateException.class)
@Test
public void testUntrustedCertificateWithSHA256Fingerprint() throws Exception {
FingerprintTrustManagerFactory factory = FingerprintTrustManagerFactory
.builder("SHA-256")
@ -106,8 +129,14 @@ public class FingerprintTrustManagerFactoryTest {
assertTrue(factory.engineGetTrustManagers().length > 0);
assertTrue(factory.engineGetTrustManagers()[0] instanceof X509TrustManager);
X509TrustManager tm = (X509TrustManager) factory.engineGetTrustManagers()[0];
tm.checkClientTrusted(SECOND_CHAIN, "test");
final X509TrustManager tm = (X509TrustManager) factory.engineGetTrustManagers()[0];
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.ReferenceCountUtil;
import io.netty.util.internal.PlatformDependent;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.io.ByteArrayInputStream;
import java.io.File;
@ -43,7 +43,11 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
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 {
private static final byte[] BYTES = new byte[1024 * 64];
@ -120,8 +124,8 @@ public class ChunkedWriteHandlerTest {
//no op
}
});
Assert.assertTrue(in.isOpen());
Assert.assertEquals(expectedPosition, in.position());
assertTrue(in.isOpen());
assertEquals(expectedPosition, in.position());
} finally {
if (in != null) {
in.close();
@ -129,17 +133,22 @@ public class ChunkedWriteHandlerTest {
}
}
@Test(expected = ClosedChannelException.class)
@Test
public void testChunkedNioFileFailOnClosedFileChannel() throws IOException {
final FileChannel in = new RandomAccessFile(TMP, "r").getChannel();
in.close();
check(new ChunkedNioFile(in) {
assertThrows(ClosedChannelException.class, new Executable() {
@Override
public void close() throws Exception {
//no op
public void execute() throws Throwable {
check(new ChunkedNioFile(in) {
@Override
public void close() throws Exception {
//no op
}
});
}
});
Assert.fail();
}
@Test
@ -490,16 +499,16 @@ public class ChunkedWriteHandlerTest {
@Test
public void testCloseFailedChunkedInput() {
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());
try {
ch.writeOutbound(input);
fail("Exception expected");
} catch (Exception e) {
assertEquals(error, e);
}
Exception e = assertThrows(Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
ch.writeOutbound(input);
}
});
assertEquals(error, e);
assertTrue(input.isClosed());
assertFalse(ch.finish());

View File

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

View File

@ -15,26 +15,26 @@
*/
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.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.ReferenceCountUtil;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
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 {
@ -67,8 +67,7 @@ public class IdleStateHandlerTest {
}
private static void anyIdle(TestableIdleStateHandler idleStateHandler, Object... expected) throws Exception {
assertTrue("The number of expected events must be >= 1", expected.length >= 1);
assertThat(expected.length, greaterThanOrEqualTo(1));
final List<Object> events = new ArrayList<>();
ChannelHandler handler = new ChannelHandler() {
@ -92,7 +91,7 @@ public class IdleStateHandlerTest {
// Compare the expected with the actual IdleStateEvents
for (int i = 0; i < expected.length; 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 {
channel.finishAndReleaseAll();

View File

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

View File

@ -16,18 +16,12 @@
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.ScheduledExecutorService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.MultithreadEventLoopGroup;
import io.netty.channel.local.LocalHandler;
import org.junit.AfterClass;
import org.junit.Test;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
@ -39,6 +33,11 @@ import io.netty.channel.local.LocalChannel;
import io.netty.channel.local.LocalServerChannel;
import io.netty.util.Attribute;
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 {
@ -47,7 +46,7 @@ public class TrafficShapingHandlerTest {
private static final MultithreadEventLoopGroup GROUP =
new MultithreadEventLoopGroup(1, LocalHandler.newFactory());
@AfterClass
@AfterAll
public static void destroy() {
GROUP.shutdownGracefully();
SES.shutdown();