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 committed by GitHub
parent c97981403d
commit 7cc31b8653
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
43 changed files with 828 additions and 615 deletions

View File

@ -19,14 +19,14 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
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

@ -31,16 +31,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 {
@ -50,12 +53,12 @@ public class ResolveAddressHandlerTest {
private static EventLoopGroup group;
@BeforeClass
@BeforeAll
public static void createEventLoop() {
group = new DefaultEventLoopGroup();
}
@AfterClass
@AfterAll
public static void destroyEventLoop() {
if (group != null) {
group.shutdownGracefully();

View File

@ -37,9 +37,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.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.net.SocketAddress;
import java.util.List;
@ -50,17 +50,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 NioEventLoopGroup();
}
@AfterClass
@AfterEach
public static void destroy() {
GROUP.shutdownGracefully();
}

View File

@ -21,11 +21,15 @@ import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
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,8 +140,13 @@ public class FlushConsolidationHandlerTest {
assertEquals(1, flushCount.get());
assertEquals(1L, channel.readOutbound());
assertNull(channel.readOutbound());
assertThrows(IllegalStateException.class, new Executable() {
@Override
public void execute() throws Throwable {
channel.finish();
}
});
}
@Test
public void testFlushViaRemoval() {

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,11 @@ 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.verify;
import static org.slf4j.Logger.ROOT_LOGGER_NAME;
/**
@ -64,7 +69,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,30 +80,35 @@ 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() {
assertThrows(NullPointerException.class, new Executable() {
@Override
public void execute() throws Throwable {
LogLevel level = null;
new LoggingHandler(level);
}
});
}
@Test
public void shouldApplyCustomLogLevel() {

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

@ -21,7 +21,8 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
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;
@ -31,13 +32,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 {
@ -86,7 +87,7 @@ public class ApplicationProtocolNegotiationHandlerTest {
assertTrue(configureCalled.get());
}
@Test(expected = IllegalStateException.class)
@Test
public void testHandshakeSuccessButNoSslHandler() {
ChannelHandler alpnHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {
@Override
@ -94,13 +95,15 @@ public class ApplicationProtocolNegotiationHandlerTest {
fail();
}
};
EmbeddedChannel channel = new EmbeddedChannel(alpnHandler);
try {
final EmbeddedChannel channel = new EmbeddedChannel(alpnHandler);
channel.pipeline().fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS);
} finally {
assertNull(channel.pipeline().context(alpnHandler));
assertFalse(channel.finishAndReleaseAll());
assertThrows(IllegalStateException.class, new Executable() {
@Override
public void execute() throws Throwable {
channel.finishAndReleaseAll();
}
});
}
@Test

View File

@ -35,6 +35,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;
@ -47,63 +51,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<Object[]>();
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 DefaultEventLoopGroup();
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) {
@ -117,7 +97,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) {
@ -128,8 +108,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);
@ -230,8 +213,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,15 +39,20 @@ 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() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() throws Throwable {
new OpenSslCertificateException(Integer.MIN_VALUE);
}
});
}
@Test
public void testCanBeInstancedWhenOpenSslIsNotAvailable() {

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

@ -36,13 +36,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();
@ -107,7 +103,7 @@ public class OpenSslPrivateKeyMethodTest {
});
}
@AfterClass
@AfterAll
public static void destroy() {
if (OpenSsl.isBoringSSL()) {
GROUP.shutdownGracefully();
@ -116,12 +112,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) {
@ -170,11 +160,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 {
@ -182,14 +172,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());
@ -227,7 +218,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
@ -263,7 +254,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
@ -293,8 +284,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();
@ -313,20 +304,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;
}
@ -341,9 +335,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

@ -47,9 +47,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;
@ -65,19 +65,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 io.netty.util.internal.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<SslProvider>(3);
if (OpenSsl.isAvailable()) {
providers.add(SslProvider.OPENSSL);
@ -95,16 +96,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);
@ -277,8 +273,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())
@ -375,22 +373,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())
@ -508,39 +515,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 NioEventLoopGroup();
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 DefaultEventLoopGroup();
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,21 +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 static org.junit.Assume.assumeTrue;
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 {
@ -71,8 +72,11 @@ public class PemEncodedTest {
}
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testEncodedReturnsNull() throws Exception {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() throws Throwable {
PemPrivateKey.toPEM(UnpooledByteBufAllocator.DEFAULT, true, new PrivateKey() {
@Override
public String getAlgorithm() {
@ -90,6 +94,8 @@ public class PemEncodedTest {
}
});
}
});
}
private static void assertRelease(PemEncoded encoded) {
assertTrue(encoded.release());

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.SelfSignedCertificate;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Future;
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<Throwable>();
final CountDownLatch latch = new CountDownLatch(2);

View File

@ -53,7 +53,6 @@ import org.conscrypt.OpenSSLProvider;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;

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

@ -31,12 +31,10 @@ import io.netty.util.Mapping;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Promise;
import io.netty.util.internal.PlatformDependent;
import org.junit.Assert;
import org.junit.Assume;
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.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;
@ -46,12 +44,16 @@ 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<SslProvider>(Arrays.asList(SslProvider.values()));
if (!OpenSsl.isAvailable()) {
providers.remove(SslProvider.OPENSSL);
@ -67,32 +69,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 Exception {
Assume.assumeTrue(PlatformDependent.javaVersion() >= 8);
@ParameterizedTest(name = PARAMETERIZED_NAME)
@Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
@MethodSource("parameters")
public void testSniSNIMatcherMatchesClient(SslProvider serverProvider, SslProvider clientProvider)
throws Exception {
assumeTrue(PlatformDependent.javaVersion() >= 8);
SniClientJava8TestUtil.testSniClient(serverProvider, clientProvider, true);
}
@Test(timeout = 30000, expected = SSLException.class)
public void testSniSNIMatcherDoesNotMatchClient() throws Exception {
Assume.assumeTrue(PlatformDependent.javaVersion() >= 8);
@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 DefaultEventLoopGroup(1);
@ -148,11 +151,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());
if (PlatformDependent.javaVersion() >= 8) {
SniClientJava8TestUtil.assertSSLSession(

View File

@ -16,17 +16,6 @@
package io.netty.handler.ssl;
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;
@ -40,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;
@ -76,9 +62,25 @@ import io.netty.util.concurrent.Promise;
import io.netty.util.internal.ObjectUtil;
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 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() {
@ -135,8 +137,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<SslProvider>(3);
if (OpenSsl.isAvailable()) {
params.add(SslProvider.OPENSSL);
@ -146,20 +147,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<SslHandshakeCompletionEvent>();
SniHandler handler = new SniHandler(new DomainNameMappingBuilder<SslContext>(nettyContext).build());
EmbeddedChannel ch = new EmbeddedChannel(handler, new ChannelInboundHandlerAdapter() {
final EmbeddedChannel ch = new EmbeddedChannel(handler, new ChannelInboundHandlerAdapter() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof SslHandshakeCompletionEvent) {
@ -169,27 +165,29 @@ public class SniHandlerTest {
});
try {
byte[] bytes = new byte[1024];
final byte[] bytes = new byte[1024];
bytes[0] = SslUtils.SSL_CONTENT_TYPE_ALERT;
try {
DecoderException e = assertThrows(DecoderException.class, new Executable() {
@Override
public void execute() throws Throwable {
ch.writeInbound(Unpooled.wrappedBuffer(bytes));
fail();
} catch (DecoderException e) {
assertTrue(e.getCause() instanceof NotSslRecordException);
}
});
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);
@ -251,8 +249,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);
@ -268,13 +267,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" +
@ -285,7 +284,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)));
assertThrows(DecoderException.class, new Executable() {
@Override
public void execute() throws Throwable {
ch.writeInbound(Unpooled.wrappedBuffer(StringUtil.decodeHexDump(tlsHandshakeMessageHex)));
}
});
} finally {
ch.finishAndReleaseAll();
}
@ -294,8 +299,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);
@ -344,8 +350,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 {
@ -385,8 +393,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);
@ -471,8 +480,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:
@ -623,16 +634,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())
@ -640,7 +654,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,9 +18,8 @@ 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.Assert;
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;
@ -36,7 +35,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 {
@ -103,23 +106,33 @@ public class SslContextBuilderTest {
@Test
public void testContextFromManagersOpenssl() throws Exception {
OpenSsl.ensureAvailability();
Assume.assumeTrue(OpenSsl.useKeyManagerFactory());
assumeTrue(OpenSsl.useKeyManagerFactory());
testContextFromManagers(SslProvider.OPENSSL);
}
@Test(expected = SSLException.class)
@Test
public void testUnsupportedPrivateKeyFailsFastForServer() throws Exception {
Assume.assumeTrue(OpenSsl.isBoringSSL());
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());
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" +
@ -153,11 +166,16 @@ public class SslContextBuilderTest {
}
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testInvalidCipherJdk() throws Exception {
OpenSsl.ensureAvailability();
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() throws Throwable {
testInvalidCipher(SslProvider.JDK);
}
});
}
@Test
public void testInvalidCipherOpenSSL() throws Exception {

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,37 +31,48 @@ 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(
assertThrows(IOException.class, new Executable() {
@Override
public void execute() throws Throwable {
SslContext.toPrivateKey(
ResourcesUtil.getFile(getClass(), "test2_unencrypted.pem"), "");
Assert.assertNotNull(key);
}
});
}
@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 {
assertThrows(InvalidKeySpecException.class, new Executable() {
@Override
public void execute() throws Throwable {
SslContext.toPrivateKey(
ResourcesUtil.getFile(getClass(), "test_encrypted_empty_pass.pem"), null);
}
});
}
@Test
public void testSslContextWithEncryptedPrivateKey() throws SSLException {
@ -87,13 +98,18 @@ public abstract class SslContextTest {
newSslContext(crtFile, keyFile, null);
}
@Test(expected = SSLException.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");
assertThrows(SSLException.class, new Executable() {
@Override
public void execute() throws Throwable {
newSslContext(crtFile, keyFile, "");
}
});
}
@Test
public void testSupportedCiphers() throws KeyManagementException, NoSuchAlgorithmException, SSLException {
@ -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

@ -33,10 +33,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<SslProvider>(2);
List<SslProvider> clientProviders = new ArrayList<SslProvider>(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 ChannelInboundHandlerAdapter() {
@ -182,7 +171,8 @@ public class SslErrorTest {
protected void initChannel(Channel ch) {
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 ChannelInboundHandlerAdapter() {
@ -209,7 +199,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
@ -239,10 +235,17 @@ public class SslErrorTest {
}
}
private final class AlertValidationHandler extends ChannelInboundHandlerAdapter {
private static final class AlertValidationHandler extends ChannelInboundHandlerAdapter {
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;
}
@ -255,20 +258,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");
}
}
}
@ -276,7 +279,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

@ -62,8 +62,9 @@ import io.netty.util.internal.EmptyArrays;
import io.netty.util.internal.PlatformDependent;
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 java.net.InetSocketAddress;
import java.net.Socket;
@ -95,18 +96,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>();
@ -201,15 +205,27 @@ public class SslHandlerTest {
assertFalse(ch.finishAndReleaseAll());
}
@Test(expected = SslHandshakeTimeoutException.class, timeout = 3000)
@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)
@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 {
SSLEngine engine = SSLContext.getDefault().createSSLEngine();
@ -251,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);
@ -291,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}));
@ -299,11 +316,13 @@ public class SslHandlerTest {
// Should decode nothing yet.
assertThat(ch.readInbound(), is(nullValue()));
try {
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}));
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.
@ -312,14 +331,13 @@ public class SslHandlerTest {
// 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;
@ -329,26 +347,30 @@ public class SslHandlerTest {
protected void deallocate() {
}
};
try {
ExecutionException e = assertThrows(ExecutionException.class, new Executable() {
@Override
public void execute() throws Throwable {
ch.write(referenceCounted).get();
fail();
} catch (ExecutionException e) {
assertThat(e.getCause(), is(instanceOf(UnsupportedMessageTypeException.class)));
}
});
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 {
assertThrows(UnsupportedMessageTypeException.class, new Executable() {
@Override
public void execute() throws Throwable {
ch.writeOutbound(new Object());
} finally {
ch.finishAndReleaseAll();
}
});
ch.finishAndReleaseAll();
}
@Test
@ -446,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 {
NioEventLoopGroup group = new NioEventLoopGroup();
Channel sc = null;
@ -543,7 +566,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<SslCompletionEvent>();
@ -568,7 +592,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();
@ -731,7 +756,8 @@ public class SslHandlerTest {
}
}
@Test(timeout = 10000)
@Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testCloseOnHandshakeFailure() throws Exception {
final SelfSignedCertificate ssc = new SelfSignedCertificate();
@ -806,7 +832,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)
@ -879,12 +906,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);
}
@ -1113,23 +1142,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(OpenSsl.isTlsv13Supported());
testSessionTickets(SslProvider.OPENSSL, SslUtils.PROTOCOL_TLS_V1_3, false);
@ -1287,7 +1320,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() {
@ -1412,7 +1446,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);
}
@ -1425,8 +1459,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 {
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 {
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 {
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 {
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);
}
@ -350,7 +382,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,28 +51,48 @@ public class FingerprintTrustManagerFactoryTest {
}
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testFingerprintWithInvalidLength() {
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() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
FingerprintTrustManagerFactory.builder("SHA-256").fingerprints("00:00:00\n").build();
}
@Test(expected = IllegalStateException.class)
public void testWithNoFingerprints() {
FingerprintTrustManagerFactory.builder("SHA-256").build();
});
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithNoFingerprints() {
assertThrows(IllegalStateException.class, new Executable() {
@Override
public void execute() {
FingerprintTrustManagerFactory.builder("SHA-256").build();
}
});
}
@Test
public void testWithNullFingerprint() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
FingerprintTrustManagerFactory
.builder("SHA-256")
.fingerprints(FIRST_CERT_SHA256_FINGERPRINT, null)
.build();
}
});
}
@Test
public void testValidSHA1Fingerprint() throws Exception {
@ -96,7 +119,7 @@ public class FingerprintTrustManagerFactoryTest {
tm.checkClientTrusted(keyCertChain, "test");
}
@Test(expected = CertificateException.class)
@Test
public void testUntrustedCertificateWithSHA256Fingerprint() throws Exception {
FingerprintTrustManagerFactory factory = FingerprintTrustManagerFactory
.builder("SHA-256")
@ -105,8 +128,14 @@ public class FingerprintTrustManagerFactoryTest {
assertTrue(factory.engineGetTrustManagers().length > 0);
assertTrue(factory.engineGetTrustManagers()[0] instanceof X509TrustManager);
X509TrustManager tm = (X509TrustManager) factory.engineGetTrustManagers()[0];
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();
assertThrows(ClosedChannelException.class, new Executable() {
@Override
public void execute() throws Throwable {
check(new ChunkedNioFile(in) {
@Override
public void close() throws Exception {
//no op
}
});
Assert.fail();
}
});
}
@Test
@ -496,16 +505,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 {
Exception e = assertThrows(Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
ch.writeOutbound(input);
fail("Exception expected");
} catch (Exception e) {
assertEquals(error, e);
}
});
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,13 +15,6 @@
*/
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;
@ -29,13 +22,20 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
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 {
@ -68,8 +68,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<Object>();
ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() {
@ -93,7 +92,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

@ -22,11 +22,11 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
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

@ -33,11 +33,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;
@ -48,7 +48,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];
@ -56,7 +56,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++) {
@ -83,17 +83,17 @@ public class FileRegionThrottleTest {
}
}
@Before
@BeforeEach
public void setUp() {
group = new NioEventLoopGroup();
}
@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);
@ -114,7 +114,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,15 +16,9 @@
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 org.junit.AfterClass;
import org.junit.Test;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
@ -38,6 +32,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 {
@ -45,7 +44,7 @@ public class TrafficShapingHandlerTest {
private static final ScheduledExecutorService SES = Executors.newSingleThreadScheduledExecutor();
private static final DefaultEventLoopGroup GROUP = new DefaultEventLoopGroup(1);
@AfterClass
@AfterAll
public static void destroy() {
GROUP.shutdownGracefully();
SES.shutdown();