tests: Replace usages of deprecated junit ExpectedException with assertThrows (#12103)

This commit is contained in:
Alex Panchenko 2025-05-30 07:25:37 +02:00 committed by GitHub
parent 83538cdae3
commit 22cf7cf2ac
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
14 changed files with 407 additions and 456 deletions

View File

@ -19,6 +19,7 @@ package io.grpc.netty;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -39,17 +40,13 @@ import java.net.InetSocketAddress;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLException; import javax.net.ssl.SSLException;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class NettyChannelBuilderTest { public class NettyChannelBuilderTest {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule public final ExpectedException thrown = ExpectedException.none();
private final SslContext noSslContext = null; private final SslContext noSslContext = null;
private void shutdown(ManagedChannel mc) throws Exception { private void shutdown(ManagedChannel mc) throws Exception {
@ -107,10 +104,9 @@ public class NettyChannelBuilderTest {
public void failOverrideInvalidAuthority() { public void failOverrideInvalidAuthority() {
NettyChannelBuilder builder = new NettyChannelBuilder(getTestSocketAddress()); NettyChannelBuilder builder = new NettyChannelBuilder(getTestSocketAddress());
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("Invalid authority:"); () -> builder.overrideAuthority("[invalidauthority"));
assertThat(e).hasMessageThat().isEqualTo("Invalid authority: [invalidauthority");
builder.overrideAuthority("[invalidauthority");
} }
@Test @Test
@ -128,20 +124,18 @@ public class NettyChannelBuilderTest {
NettyChannelBuilder builder = new NettyChannelBuilder(getTestSocketAddress()) NettyChannelBuilder builder = new NettyChannelBuilder(getTestSocketAddress())
.disableCheckAuthority() .disableCheckAuthority()
.enableCheckAuthority(); .enableCheckAuthority();
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expect(IllegalArgumentException.class); () -> builder.overrideAuthority("[invalidauthority"));
thrown.expectMessage("Invalid authority:"); assertThat(e).hasMessageThat().isEqualTo("Invalid authority: [invalidauthority");
builder.overrideAuthority("[invalidauthority");
} }
@Test @Test
public void failInvalidAuthority() { public void failInvalidAuthority() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Invalid host or port");
@SuppressWarnings("AddressSelection") // We actually expect zero addresses! @SuppressWarnings("AddressSelection") // We actually expect zero addresses!
Object unused = InetSocketAddress address = new InetSocketAddress("invalid_authority", 1234);
NettyChannelBuilder.forAddress(new InetSocketAddress("invalid_authority", 1234)); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
() -> NettyChannelBuilder.forAddress(address));
assertThat(e).hasMessageThat().isEqualTo("Invalid host or port: invalid_authority 1234");
} }
@Test @Test
@ -155,10 +149,10 @@ public class NettyChannelBuilderTest {
SslContext sslContext = mock(SslContext.class); SslContext sslContext = mock(SslContext.class);
NettyChannelBuilder builder = new NettyChannelBuilder(getTestSocketAddress()); NettyChannelBuilder builder = new NettyChannelBuilder(getTestSocketAddress());
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("Server SSL context can not be used for client channel"); () -> builder.sslContext(sslContext));
assertThat(e).hasMessageThat()
builder.sslContext(sslContext); .isEqualTo("Server SSL context can not be used for client channel");
} }
@Test @Test
@ -166,10 +160,10 @@ public class NettyChannelBuilderTest {
NettyChannelBuilder builder = NettyChannelBuilder.forTarget( NettyChannelBuilder builder = NettyChannelBuilder.forTarget(
"fakeTarget", InsecureChannelCredentials.create()); "fakeTarget", InsecureChannelCredentials.create());
thrown.expect(IllegalStateException.class); IllegalStateException e = assertThrows(IllegalStateException.class,
thrown.expectMessage("Cannot change security when using ChannelCredentials"); () -> builder.negotiationType(NegotiationType.TLS));
assertThat(e).hasMessageThat()
builder.negotiationType(NegotiationType.TLS); .isEqualTo("Cannot change security when using ChannelCredentials");
} }
@Test @Test
@ -177,10 +171,10 @@ public class NettyChannelBuilderTest {
NettyChannelBuilder builder = NettyChannelBuilder.forAddress( NettyChannelBuilder builder = NettyChannelBuilder.forAddress(
getTestSocketAddress(), InsecureChannelCredentials.create()); getTestSocketAddress(), InsecureChannelCredentials.create());
thrown.expect(IllegalStateException.class); IllegalStateException e = assertThrows(IllegalStateException.class,
thrown.expectMessage("Cannot change security when using ChannelCredentials"); () -> builder.negotiationType(NegotiationType.TLS));
assertThat(e).hasMessageThat()
builder.negotiationType(NegotiationType.TLS); .isEqualTo("Cannot change security when using ChannelCredentials");
} }
@Test @Test
@ -205,10 +199,9 @@ public class NettyChannelBuilderTest {
@Test @Test
public void createProtocolNegotiatorByType_tlsWithNoContext() { public void createProtocolNegotiatorByType_tlsWithNoContext() {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class,
NettyChannelBuilder.createProtocolNegotiatorByType( () -> NettyChannelBuilder.createProtocolNegotiatorByType(
NegotiationType.TLS, NegotiationType.TLS, noSslContext, null));
noSslContext, null);
} }
@Test @Test
@ -245,38 +238,40 @@ public class NettyChannelBuilderTest {
public void negativeKeepAliveTime() { public void negativeKeepAliveTime() {
NettyChannelBuilder builder = NettyChannelBuilder.forTarget("fakeTarget"); NettyChannelBuilder builder = NettyChannelBuilder.forTarget("fakeTarget");
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("keepalive time must be positive"); () -> builder.keepAliveTime(-1L, TimeUnit.HOURS));
builder.keepAliveTime(-1L, TimeUnit.HOURS); assertThat(e).hasMessageThat().isEqualTo("keepalive time must be positive");
} }
@Test @Test
public void negativeKeepAliveTimeout() { public void negativeKeepAliveTimeout() {
NettyChannelBuilder builder = NettyChannelBuilder.forTarget("fakeTarget"); NettyChannelBuilder builder = NettyChannelBuilder.forTarget("fakeTarget");
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("keepalive timeout must be positive"); () -> builder.keepAliveTimeout(-1L, TimeUnit.HOURS));
builder.keepAliveTimeout(-1L, TimeUnit.HOURS); assertThat(e).hasMessageThat().isEqualTo("keepalive timeout must be positive");
} }
@Test @Test
public void assertEventLoopAndChannelType_onlyGroupProvided() { public void assertEventLoopAndChannelType_onlyGroupProvided() {
NettyChannelBuilder builder = NettyChannelBuilder.forTarget("fakeTarget"); NettyChannelBuilder builder = NettyChannelBuilder.forTarget("fakeTarget");
builder.eventLoopGroup(mock(EventLoopGroup.class)); builder.eventLoopGroup(mock(EventLoopGroup.class));
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Both EventLoopGroup and ChannelType should be provided");
builder.assertEventLoopAndChannelType(); IllegalStateException e = assertThrows(IllegalStateException.class,
builder::assertEventLoopAndChannelType);
assertThat(e).hasMessageThat()
.isEqualTo("Both EventLoopGroup and ChannelType should be provided or neither should be");
} }
@Test @Test
public void assertEventLoopAndChannelType_onlyTypeProvided() { public void assertEventLoopAndChannelType_onlyTypeProvided() {
NettyChannelBuilder builder = NettyChannelBuilder.forTarget("fakeTarget"); NettyChannelBuilder builder = NettyChannelBuilder.forTarget("fakeTarget");
builder.channelType(LocalChannel.class, LocalAddress.class); builder.channelType(LocalChannel.class, LocalAddress.class);
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Both EventLoopGroup and ChannelType should be provided");
builder.assertEventLoopAndChannelType(); IllegalStateException e = assertThrows(IllegalStateException.class,
builder::assertEventLoopAndChannelType);
assertThat(e).hasMessageThat()
.isEqualTo("Both EventLoopGroup and ChannelType should be provided or neither should be");
} }
@Test @Test
@ -288,10 +283,11 @@ public class NettyChannelBuilderTest {
return null; return null;
} }
}); });
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Both EventLoopGroup and ChannelType should be provided");
builder.assertEventLoopAndChannelType(); IllegalStateException e = assertThrows(IllegalStateException.class,
builder::assertEventLoopAndChannelType);
assertThat(e).hasMessageThat()
.isEqualTo("Both EventLoopGroup and ChannelType should be provided or neither should be");
} }
@Test @Test

View File

@ -16,20 +16,19 @@
package io.grpc.netty; package io.grpc.netty;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.truth.Truth;
import io.grpc.ServerStreamTracer; import io.grpc.ServerStreamTracer;
import io.netty.channel.EventLoopGroup; import io.netty.channel.EventLoopGroup;
import io.netty.channel.local.LocalServerChannel; import io.netty.channel.local.LocalServerChannel;
import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContext;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -39,9 +38,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class NettyServerBuilderTest { public class NettyServerBuilderTest {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule public final ExpectedException thrown = ExpectedException.none();
private NettyServerBuilder builder = NettyServerBuilder.forPort(8080); private NettyServerBuilder builder = NettyServerBuilder.forPort(8080);
@Test @Test
@ -50,7 +46,7 @@ public class NettyServerBuilderTest {
NettyServer server = NettyServer server =
builder.buildTransportServers(ImmutableList.<ServerStreamTracer.Factory>of()); builder.buildTransportServers(ImmutableList.<ServerStreamTracer.Factory>of());
Truth.assertThat(server.getListenSocketAddresses()).hasSize(2); assertThat(server.getListenSocketAddresses()).hasSize(2);
} }
@Test @Test
@ -63,121 +59,112 @@ public class NettyServerBuilderTest {
SslContext sslContext = mock(SslContext.class); SslContext sslContext = mock(SslContext.class);
when(sslContext.isClient()).thenReturn(true); when(sslContext.isClient()).thenReturn(true);
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(
thrown.expectMessage("Client SSL context can not be used for server"); IllegalArgumentException.class, () -> builder.sslContext(sslContext));
builder.sslContext(sslContext); assertThat(e).hasMessageThat().isEqualTo("Client SSL context can not be used for server");
} }
@Test @Test
public void failIfKeepAliveTimeNegative() { public void failIfKeepAliveTimeNegative() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("keepalive time must be positive"); () -> builder.keepAliveTime(-10L, TimeUnit.HOURS));
assertThat(e).hasMessageThat().isEqualTo("keepalive time must be positive-10");
builder.keepAliveTime(-10L, TimeUnit.HOURS);
} }
@Test @Test
public void failIfKeepAliveTimeoutNegative() { public void failIfKeepAliveTimeoutNegative() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("keepalive timeout must be positive"); () -> builder.keepAliveTimeout(-10L, TimeUnit.HOURS));
assertThat(e).hasMessageThat().isEqualTo("keepalive timeout must be positive: -10");
builder.keepAliveTimeout(-10L, TimeUnit.HOURS);
} }
@Test @Test
public void failIfMaxConcurrentCallsPerConnectionNegative() { public void failIfMaxConcurrentCallsPerConnectionNegative() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("max must be positive"); () -> builder.maxConcurrentCallsPerConnection(0));
assertThat(e).hasMessageThat().isEqualTo("max must be positive: 0");
builder.maxConcurrentCallsPerConnection(0);
} }
@Test @Test
public void failIfMaxInboundMetadataSizeNonPositive() { public void failIfMaxInboundMetadataSizeNonPositive() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("maxInboundMetadataSize must be positive"); () -> builder.maxInboundMetadataSize(0));
assertThat(e).hasMessageThat().isEqualTo("maxInboundMetadataSize must be positive: 0");
builder.maxInboundMetadataSize(0);
} }
@Test @Test
public void failIfSoftInboundMetadataSizeNonPositive() { public void failIfSoftInboundMetadataSizeNonPositive() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("softLimitHeaderListSize must be positive"); () -> builder.maxInboundMetadataSize(0, 100));
assertThat(e).hasMessageThat().isEqualTo("softLimitHeaderListSize must be positive: 0");
builder.maxInboundMetadataSize(0, 100);
} }
@Test @Test
public void failIfMaxInboundMetadataSizeSmallerThanSoft() { public void failIfMaxInboundMetadataSizeSmallerThanSoft() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("must be greater than softLimitHeaderListSize"); () -> builder.maxInboundMetadataSize(100, 80));
assertThat(e).hasMessageThat().isEqualTo("maxInboundMetadataSize: 80 "
builder.maxInboundMetadataSize(100, 80); + "must be greater than softLimitHeaderListSize: 100");
} }
@Test @Test
public void failIfMaxConnectionIdleNegative() { public void failIfMaxConnectionIdleNegative() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("max connection idle must be positive"); () -> builder.maxConnectionIdle(-1, TimeUnit.HOURS));
assertThat(e).hasMessageThat().isEqualTo("max connection idle must be positive: -1");
builder.maxConnectionIdle(-1, TimeUnit.HOURS);
} }
@Test @Test
public void failIfMaxConnectionAgeNegative() { public void failIfMaxConnectionAgeNegative() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("max connection age must be positive"); () -> builder.maxConnectionAge(-1, TimeUnit.HOURS));
assertThat(e).hasMessageThat().isEqualTo("max connection age must be positive: -1");
builder.maxConnectionAge(-1, TimeUnit.HOURS);
} }
@Test @Test
public void failIfMaxConnectionAgeGraceNegative() { public void failIfMaxConnectionAgeGraceNegative() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("max connection age grace must be non-negative"); () -> builder.maxConnectionAgeGrace(-1, TimeUnit.HOURS));
assertThat(e).hasMessageThat().isEqualTo("max connection age grace must be non-negative: -1");
builder.maxConnectionAgeGrace(-1, TimeUnit.HOURS);
} }
@Test @Test
public void failIfPermitKeepAliveTimeNegative() { public void failIfPermitKeepAliveTimeNegative() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("permit keepalive time must be non-negative"); () -> builder.permitKeepAliveTime(-1, TimeUnit.HOURS));
assertThat(e).hasMessageThat().isEqualTo("permit keepalive time must be non-negative: -1");
builder.permitKeepAliveTime(-1, TimeUnit.HOURS);
} }
@Test @Test
public void assertEventLoopsAndChannelType_onlyBossGroupProvided() { public void assertEventLoopsAndChannelType_onlyBossGroupProvided() {
EventLoopGroup mockEventLoopGroup = mock(EventLoopGroup.class); EventLoopGroup mockEventLoopGroup = mock(EventLoopGroup.class);
builder.bossEventLoopGroup(mockEventLoopGroup); builder.bossEventLoopGroup(mockEventLoopGroup);
thrown.expect(IllegalStateException.class); IllegalStateException e = assertThrows(IllegalStateException.class,
thrown.expectMessage( builder::assertEventLoopsAndChannelType);
"All of BossEventLoopGroup, WorkerEventLoopGroup and ChannelType should be provided"); assertThat(e).hasMessageThat().isEqualTo(
"All of BossEventLoopGroup, WorkerEventLoopGroup and ChannelType should be provided "
builder.assertEventLoopsAndChannelType(); + "or neither should be");
} }
@Test @Test
public void assertEventLoopsAndChannelType_onlyWorkerGroupProvided() { public void assertEventLoopsAndChannelType_onlyWorkerGroupProvided() {
EventLoopGroup mockEventLoopGroup = mock(EventLoopGroup.class); EventLoopGroup mockEventLoopGroup = mock(EventLoopGroup.class);
builder.workerEventLoopGroup(mockEventLoopGroup); builder.workerEventLoopGroup(mockEventLoopGroup);
thrown.expect(IllegalStateException.class); IllegalStateException e = assertThrows(IllegalStateException.class,
thrown.expectMessage( builder::assertEventLoopsAndChannelType);
"All of BossEventLoopGroup, WorkerEventLoopGroup and ChannelType should be provided"); assertThat(e).hasMessageThat().isEqualTo(
"All of BossEventLoopGroup, WorkerEventLoopGroup and ChannelType should be provided "
builder.assertEventLoopsAndChannelType(); + "or neither should be");
} }
@Test @Test
public void assertEventLoopsAndChannelType_onlyTypeProvided() { public void assertEventLoopsAndChannelType_onlyTypeProvided() {
builder.channelType(LocalServerChannel.class); builder.channelType(LocalServerChannel.class);
thrown.expect(IllegalStateException.class); IllegalStateException e = assertThrows(IllegalStateException.class,
thrown.expectMessage( builder::assertEventLoopsAndChannelType);
"All of BossEventLoopGroup, WorkerEventLoopGroup and ChannelType should be provided"); assertThat(e).hasMessageThat().isEqualTo(
"All of BossEventLoopGroup, WorkerEventLoopGroup and ChannelType should be provided "
builder.assertEventLoopsAndChannelType(); + "or neither should be");
} }
@Test @Test

View File

@ -24,6 +24,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -146,7 +147,6 @@ import org.junit.BeforeClass;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.DisableOnDebug; import org.junit.rules.DisableOnDebug;
import org.junit.rules.ExpectedException;
import org.junit.rules.TestRule; import org.junit.rules.TestRule;
import org.junit.rules.Timeout; import org.junit.rules.Timeout;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -174,8 +174,6 @@ public class ProtocolNegotiatorsTest {
private static final int TIMEOUT_SECONDS = 60; private static final int TIMEOUT_SECONDS = 60;
@Rule public final TestRule globalTimeout = new DisableOnDebug(Timeout.seconds(TIMEOUT_SECONDS)); @Rule public final TestRule globalTimeout = new DisableOnDebug(Timeout.seconds(TIMEOUT_SECONDS));
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule public final ExpectedException thrown = ExpectedException.none();
private final EventLoopGroup group = new DefaultEventLoop(); private final EventLoopGroup group = new DefaultEventLoop();
private Channel chan; private Channel chan;
@ -714,11 +712,10 @@ public class ProtocolNegotiatorsTest {
} }
@Test @Test
public void tlsHandler_failsOnNullEngine() throws Exception { public void tlsHandler_failsOnNullEngine() {
thrown.expect(NullPointerException.class); NullPointerException e = assertThrows(NullPointerException.class,
thrown.expectMessage("ssl"); () -> ProtocolNegotiators.serverTls(null));
assertThat(e).hasMessageThat().isEqualTo("sslContext");
Object unused = ProtocolNegotiators.serverTls(null);
} }
@ -1058,9 +1055,8 @@ public class ProtocolNegotiatorsTest {
@Test @Test
public void tls_failsOnNullSslContext() { public void tls_failsOnNullSslContext() {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class,
() -> ProtocolNegotiators.tls(null, null));
Object unused = ProtocolNegotiators.tls(null, null);
} }
@Test @Test
@ -1090,17 +1086,16 @@ public class ProtocolNegotiatorsTest {
} }
@Test @Test
public void httpProxy_nullAddressNpe() throws Exception { public void httpProxy_nullAddressNpe() {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class,
Object unused = () -> ProtocolNegotiators.httpProxy(null, "user", "pass", ProtocolNegotiators.plaintext()));
ProtocolNegotiators.httpProxy(null, "user", "pass", ProtocolNegotiators.plaintext());
} }
@Test @Test
public void httpProxy_nullNegotiatorNpe() throws Exception { public void httpProxy_nullNegotiatorNpe() {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class,
Object unused = ProtocolNegotiators.httpProxy( () -> ProtocolNegotiators.httpProxy(
InetSocketAddress.createUnresolved("localhost", 80), "user", "pass", null); InetSocketAddress.createUnresolved("localhost", 80), "user", "pass", null));
} }
@Test @Test
@ -1218,9 +1213,8 @@ public class ProtocolNegotiatorsTest {
assertFalse(negotiationFuture.isDone()); assertFalse(negotiationFuture.isDone());
String response = "HTTP/1.1 500 OMG\r\nContent-Length: 4\r\n\r\noops"; String response = "HTTP/1.1 500 OMG\r\nContent-Length: 4\r\n\r\noops";
serverContext.writeAndFlush(bb(response, serverContext.channel())).sync(); serverContext.writeAndFlush(bb(response, serverContext.channel())).sync();
thrown.expect(ProxyConnectException.class);
try { try {
negotiationFuture.sync(); assertThrows(ProxyConnectException.class, negotiationFuture::sync);
} finally { } finally {
channel.close(); channel.close();
} }

View File

@ -22,6 +22,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import com.google.common.util.concurrent.SettableFuture; import com.google.common.util.concurrent.SettableFuture;
@ -57,7 +58,6 @@ import javax.net.ssl.TrustManager;
import javax.security.auth.x500.X500Principal; import javax.security.auth.x500.X500Principal;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -67,8 +67,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class OkHttpChannelBuilderTest { public class OkHttpChannelBuilderTest {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule public final ExpectedException thrown = ExpectedException.none();
@Rule public final GrpcCleanupRule grpcCleanupRule = new GrpcCleanupRule(); @Rule public final GrpcCleanupRule grpcCleanupRule = new GrpcCleanupRule();
@Test @Test
@ -100,10 +98,9 @@ public class OkHttpChannelBuilderTest {
@Test @Test
public void failOverrideInvalidAuthority() { public void failOverrideInvalidAuthority() {
OkHttpChannelBuilder builder = OkHttpChannelBuilder.forAddress("good", 1234); OkHttpChannelBuilder builder = OkHttpChannelBuilder.forAddress("good", 1234);
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expect(IllegalArgumentException.class); () -> builder.overrideAuthority("[invalidauthority"));
thrown.expectMessage("Invalid authority:"); assertThat(e).hasMessageThat().isEqualTo("Invalid authority: [invalidauthority");
builder.overrideAuthority("[invalidauthority");
} }
@Test @Test
@ -119,17 +116,16 @@ public class OkHttpChannelBuilderTest {
.disableCheckAuthority() .disableCheckAuthority()
.enableCheckAuthority(); .enableCheckAuthority();
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("Invalid authority:"); () -> builder.overrideAuthority("[invalidauthority"));
builder.overrideAuthority("[invalidauthority"); assertThat(e).hasMessageThat().isEqualTo("Invalid authority: [invalidauthority");
} }
@Test @Test
public void failInvalidAuthority() { public void failInvalidAuthority() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("Invalid host or port"); () -> OkHttpChannelBuilder.forAddress("invalid_authority", 1234));
assertThat(e.getMessage()).isEqualTo("Invalid host or port: invalid_authority 1234");
OkHttpChannelBuilder.forAddress("invalid_authority", 1234);
} }
@Test @Test
@ -396,10 +392,10 @@ public class OkHttpChannelBuilderTest {
@Test @Test
public void failForUsingClearTextSpecDirectly() { public void failForUsingClearTextSpecDirectly() {
thrown.expect(IllegalArgumentException.class); OkHttpChannelBuilder builder = OkHttpChannelBuilder.forAddress("host", 1234);
thrown.expectMessage("plaintext ConnectionSpec is not accepted"); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
() -> builder.connectionSpec(ConnectionSpec.CLEARTEXT));
OkHttpChannelBuilder.forAddress("host", 1234).connectionSpec(ConnectionSpec.CLEARTEXT); assertThat(e).hasMessageThat().isEqualTo("plaintext ConnectionSpec is not accepted");
} }
@Test @Test

View File

@ -16,10 +16,12 @@
package io.grpc.okhttp; package io.grpc.okhttp;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -37,9 +39,7 @@ import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocket;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.ArgumentMatchers; import org.mockito.ArgumentMatchers;
@ -49,9 +49,6 @@ import org.mockito.ArgumentMatchers;
*/ */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class OkHttpProtocolNegotiatorTest { public class OkHttpProtocolNegotiatorTest {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule public final ExpectedException thrown = ExpectedException.none();
private final SSLSocket sock = mock(SSLSocket.class); private final SSLSocket sock = mock(SSLSocket.class);
private final Platform platform = mock(Platform.class); private final Platform platform = mock(Platform.class);
@ -118,21 +115,19 @@ public class OkHttpProtocolNegotiatorTest {
OkHttpProtocolNegotiator negotiator = OkHttpProtocolNegotiator.get(); OkHttpProtocolNegotiator negotiator = OkHttpProtocolNegotiator.get();
doReturn(parameters).when(sock).getSSLParameters(); doReturn(parameters).when(sock).getSSLParameters();
doThrow(new IOException()).when(sock).startHandshake(); doThrow(new IOException()).when(sock).startHandshake();
thrown.expect(IOException.class); assertThrows(IOException.class,
() -> negotiator.negotiate(sock, "hostname", ImmutableList.of(Protocol.HTTP_2)));
negotiator.negotiate(sock, "hostname", ImmutableList.of(Protocol.HTTP_2));
} }
@Test @Test
public void negotiate_noSelectedProtocol() throws Exception { public void negotiate_noSelectedProtocol() {
Platform platform = mock(Platform.class); Platform platform = mock(Platform.class);
OkHttpProtocolNegotiator negotiator = new OkHttpProtocolNegotiator(platform); OkHttpProtocolNegotiator negotiator = new OkHttpProtocolNegotiator(platform);
thrown.expect(RuntimeException.class); RuntimeException e = assertThrows(RuntimeException.class,
thrown.expectMessage("TLS ALPN negotiation failed"); () -> negotiator.negotiate(sock, "hostname", ImmutableList.of(Protocol.HTTP_2)));
assertThat(e).hasMessageThat().isEqualTo("TLS ALPN negotiation failed with protocols: [h2]");
negotiator.negotiate(sock, "hostname", ImmutableList.of(Protocol.HTTP_2));
} }
@Test @Test
@ -150,7 +145,7 @@ public class OkHttpProtocolNegotiatorTest {
// Checks that the super class is properly invoked. // Checks that the super class is properly invoked.
@Test @Test
public void negotiate_android_handshakeFails() throws Exception { public void negotiate_android_handshakeFails() {
when(platform.getTlsExtensionType()).thenReturn(TlsExtensionType.ALPN_AND_NPN); when(platform.getTlsExtensionType()).thenReturn(TlsExtensionType.ALPN_AND_NPN);
AndroidNegotiator negotiator = new AndroidNegotiator(platform); AndroidNegotiator negotiator = new AndroidNegotiator(platform);
@ -161,10 +156,9 @@ public class OkHttpProtocolNegotiatorTest {
} }
}; };
thrown.expect(IOException.class); IOException e = assertThrows(IOException.class,
thrown.expectMessage("expected"); () -> negotiator.negotiate(androidSock, "hostname", ImmutableList.of(Protocol.HTTP_2)));
assertThat(e).hasMessageThat().isEqualTo("expected");
negotiator.negotiate(androidSock, "hostname", ImmutableList.of(Protocol.HTTP_2));
} }
@VisibleForTesting @VisibleForTesting

View File

@ -16,7 +16,9 @@
package io.grpc.okhttp; package io.grpc.okhttp;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import io.grpc.InternalChannelz.SocketOptions; import io.grpc.InternalChannelz.SocketOptions;
@ -26,9 +28,7 @@ import io.grpc.okhttp.internal.TlsVersion;
import java.net.Socket; import java.net.Socket;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -38,16 +38,12 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class UtilsTest { public class UtilsTest {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void convertSpecRejectsPlaintext() { public void convertSpecRejectsPlaintext() {
com.squareup.okhttp.ConnectionSpec plaintext = com.squareup.okhttp.ConnectionSpec.CLEARTEXT; com.squareup.okhttp.ConnectionSpec plaintext = com.squareup.okhttp.ConnectionSpec.CLEARTEXT;
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("plaintext ConnectionSpec is not accepted"); () -> Utils.convertSpec(plaintext));
Utils.convertSpec(plaintext); assertThat(e).hasMessageThat().isEqualTo("plaintext ConnectionSpec is not accepted");
} }
@Test @Test

View File

@ -16,6 +16,7 @@
package io.grpc.protobuf.lite; package io.grpc.protobuf.lite;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
@ -43,9 +44,7 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.Arrays; import java.util.Arrays;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -53,9 +52,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class ProtoLiteUtilsTest { public class ProtoLiteUtilsTest {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule public final ExpectedException thrown = ExpectedException.none();
private final Marshaller<Type> marshaller = ProtoLiteUtils.marshaller(Type.getDefaultInstance()); private final Marshaller<Type> marshaller = ProtoLiteUtils.marshaller(Type.getDefaultInstance());
private Type proto = Type.newBuilder().setName("name").build(); private Type proto = Type.newBuilder().setName("name").build();
@ -214,10 +210,9 @@ public class ProtoLiteUtilsTest {
@Test @Test
public void extensionRegistry_notNull() { public void extensionRegistry_notNull() {
thrown.expect(NullPointerException.class); NullPointerException e = assertThrows(NullPointerException.class,
thrown.expectMessage("newRegistry"); () -> ProtoLiteUtils.setExtensionRegistry(null));
assertThat(e).hasMessageThat().isEqualTo("newRegistry");
ProtoLiteUtils.setExtensionRegistry(null);
} }
@Test @Test

View File

@ -18,6 +18,7 @@ package io.grpc.testing;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.AdditionalAnswers.delegatesTo; import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
@ -35,9 +36,7 @@ import io.grpc.Server;
import io.grpc.internal.FakeClock; import io.grpc.internal.FakeClock;
import io.grpc.testing.GrpcCleanupRule.Resource; import io.grpc.testing.GrpcCleanupRule.Resource;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.junit.runners.model.MultipleFailureException; import org.junit.runners.model.MultipleFailureException;
@ -51,10 +50,6 @@ import org.mockito.InOrder;
public class GrpcCleanupRuleTest { public class GrpcCleanupRuleTest {
public static final FakeClock fakeClock = new FakeClock(); public static final FakeClock fakeClock = new FakeClock();
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test @Test
public void registerChannelReturnSameChannel() { public void registerChannelReturnSameChannel() {
ManagedChannel channel = mock(ManagedChannel.class); ManagedChannel channel = mock(ManagedChannel.class);
@ -72,10 +67,9 @@ public class GrpcCleanupRuleTest {
ManagedChannel channel = null; ManagedChannel channel = null;
GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
thrown.expect(NullPointerException.class); NullPointerException e = assertThrows(NullPointerException.class,
thrown.expectMessage("channel"); () -> grpcCleanup.register(channel));
assertThat(e).hasMessageThat().isEqualTo("channel");
grpcCleanup.register(channel);
} }
@Test @Test
@ -83,10 +77,9 @@ public class GrpcCleanupRuleTest {
Server server = null; Server server = null;
GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
thrown.expect(NullPointerException.class); NullPointerException e = assertThrows(NullPointerException.class,
thrown.expectMessage("server"); () -> grpcCleanup.register(server));
assertThat(e).hasMessageThat().isEqualTo("server");
grpcCleanup.register(server);
} }
@Test @Test

View File

@ -21,6 +21,7 @@ import static io.grpc.ConnectivityState.CONNECTING;
import static io.grpc.ConnectivityState.IDLE; import static io.grpc.ConnectivityState.IDLE;
import static io.grpc.ConnectivityState.READY; import static io.grpc.ConnectivityState.READY;
import static io.grpc.ConnectivityState.TRANSIENT_FAILURE; import static io.grpc.ConnectivityState.TRANSIENT_FAILURE;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.inOrder;
@ -53,9 +54,7 @@ import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
@ -68,10 +67,6 @@ import org.mockito.InOrder;
public class GracefulSwitchLoadBalancerTest { public class GracefulSwitchLoadBalancerTest {
private static final Object FAKE_CONFIG = new Object(); private static final Object FAKE_CONFIG = new Object();
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final Map<LoadBalancerProvider, LoadBalancer> balancers = new HashMap<>(); private final Map<LoadBalancerProvider, LoadBalancer> balancers = new HashMap<>();
private final Map<LoadBalancer, Helper> helpers = new HashMap<>(); private final Map<LoadBalancer, Helper> helpers = new HashMap<>();
private final Helper mockHelper = mock(Helper.class); private final Helper mockHelper = mock(Helper.class);
@ -102,8 +97,8 @@ public class GracefulSwitchLoadBalancerTest {
.build())); .build()));
Subchannel subchannel = mock(Subchannel.class); Subchannel subchannel = mock(Subchannel.class);
ConnectivityStateInfo connectivityStateInfo = ConnectivityStateInfo.forNonError(READY); ConnectivityStateInfo connectivityStateInfo = ConnectivityStateInfo.forNonError(READY);
thrown.expect(UnsupportedOperationException.class); assertThrows(UnsupportedOperationException.class,
gracefulSwitchLb.handleSubchannelState(subchannel, connectivityStateInfo); () -> gracefulSwitchLb.handleSubchannelState(subchannel, connectivityStateInfo));
} }
@Test @Test

View File

@ -17,6 +17,7 @@
package io.grpc.xds; package io.grpc.xds;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoInteractions;
@ -40,10 +41,9 @@ import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.junit.After; import org.junit.After;
import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -53,9 +53,6 @@ public class GrpcBootstrapperImplTest {
private static final String BOOTSTRAP_FILE_PATH = "/fake/fs/path/bootstrap.json"; private static final String BOOTSTRAP_FILE_PATH = "/fake/fs/path/bootstrap.json";
private static final String SERVER_URI = "trafficdirector.googleapis.com:443"; private static final String SERVER_URI = "trafficdirector.googleapis.com:443";
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final GrpcBootstrapperImpl bootstrapper = new GrpcBootstrapperImpl(); private final GrpcBootstrapperImpl bootstrapper = new GrpcBootstrapperImpl();
private String originalBootstrapPathFromEnvVar; private String originalBootstrapPathFromEnvVar;
@ -236,7 +233,7 @@ public class GrpcBootstrapperImplTest {
} }
@Test @Test
public void parseBootstrap_missingServerChannelCreds() throws XdsInitializationException { public void parseBootstrap_missingServerChannelCreds() {
String rawData = "{\n" String rawData = "{\n"
+ " \"xds_servers\": [\n" + " \"xds_servers\": [\n"
+ " {\n" + " {\n"
@ -246,13 +243,14 @@ public class GrpcBootstrapperImplTest {
+ "}"; + "}";
bootstrapper.setFileReader(createFileReader(BOOTSTRAP_FILE_PATH, rawData)); bootstrapper.setFileReader(createFileReader(BOOTSTRAP_FILE_PATH, rawData));
thrown.expect(XdsInitializationException.class); XdsInitializationException e = Assert.assertThrows(XdsInitializationException.class,
thrown.expectMessage("Invalid bootstrap: server " + SERVER_URI + " 'channel_creds' required"); bootstrapper::bootstrap);
bootstrapper.bootstrap(); assertThat(e).hasMessageThat()
.isEqualTo("Invalid bootstrap: server " + SERVER_URI + " 'channel_creds' required");
} }
@Test @Test
public void parseBootstrap_unsupportedServerChannelCreds() throws XdsInitializationException { public void parseBootstrap_unsupportedServerChannelCreds() {
String rawData = "{\n" String rawData = "{\n"
+ " \"xds_servers\": [\n" + " \"xds_servers\": [\n"
+ " {\n" + " {\n"
@ -265,9 +263,10 @@ public class GrpcBootstrapperImplTest {
+ "}"; + "}";
bootstrapper.setFileReader(createFileReader(BOOTSTRAP_FILE_PATH, rawData)); bootstrapper.setFileReader(createFileReader(BOOTSTRAP_FILE_PATH, rawData));
thrown.expect(XdsInitializationException.class); XdsInitializationException e = assertThrows(XdsInitializationException.class,
thrown.expectMessage("Server " + SERVER_URI + ": no supported channel credentials found"); bootstrapper::bootstrap);
bootstrapper.bootstrap(); assertThat(e).hasMessageThat()
.isEqualTo("Server " + SERVER_URI + ": no supported channel credentials found");
} }
@Test @Test
@ -294,7 +293,7 @@ public class GrpcBootstrapperImplTest {
} }
@Test @Test
public void parseBootstrap_noXdsServers() throws XdsInitializationException { public void parseBootstrap_noXdsServers() {
String rawData = "{\n" String rawData = "{\n"
+ " \"node\": {\n" + " \"node\": {\n"
+ " \"id\": \"ENVOY_NODE_ID\",\n" + " \"id\": \"ENVOY_NODE_ID\",\n"
@ -312,9 +311,10 @@ public class GrpcBootstrapperImplTest {
+ "}"; + "}";
bootstrapper.setFileReader(createFileReader(BOOTSTRAP_FILE_PATH, rawData)); bootstrapper.setFileReader(createFileReader(BOOTSTRAP_FILE_PATH, rawData));
thrown.expect(XdsInitializationException.class); XdsInitializationException e = assertThrows(XdsInitializationException.class,
thrown.expectMessage("Invalid bootstrap: 'xds_servers' does not exist."); bootstrapper::bootstrap);
bootstrapper.bootstrap(); assertThat(e).hasMessageThat()
.isEqualTo("Invalid bootstrap: 'xds_servers' does not exist.");
} }
@Test @Test
@ -343,8 +343,9 @@ public class GrpcBootstrapperImplTest {
+ "}"; + "}";
bootstrapper.setFileReader(createFileReader(BOOTSTRAP_FILE_PATH, rawData)); bootstrapper.setFileReader(createFileReader(BOOTSTRAP_FILE_PATH, rawData));
thrown.expectMessage("Invalid bootstrap: missing 'server_uri'"); XdsInitializationException e = assertThrows(XdsInitializationException.class,
bootstrapper.bootstrap(); bootstrapper::bootstrap);
assertThat(e).hasMessageThat().isEqualTo("Invalid bootstrap: missing 'server_uri'");
} }
@Test @Test
@ -870,7 +871,7 @@ public class GrpcBootstrapperImplTest {
} }
@Test @Test
public void badFederationConfig() throws Exception { public void badFederationConfig() {
String rawData = "{\n" String rawData = "{\n"
+ " \"authorities\": {\n" + " \"authorities\": {\n"
+ " \"a.com\": {\n" + " \"a.com\": {\n"

View File

@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import static io.envoyproxy.envoy.config.route.v3.RouteAction.ClusterSpecifierCase.CLUSTER_SPECIFIER_PLUGIN; import static io.envoyproxy.envoy.config.route.v3.RouteAction.ClusterSpecifierCase.CLUSTER_SPECIFIER_PLUGIN;
import static io.grpc.xds.XdsClusterResource.TRANSPORT_SOCKET_NAME_HTTP11_PROXY; import static io.grpc.xds.XdsClusterResource.TRANSPORT_SOCKET_NAME_HTTP11_PROXY;
import static io.grpc.xds.XdsEndpointResource.GRPC_EXPERIMENTAL_XDS_DUALSTACK_ENDPOINTS; import static io.grpc.xds.XdsEndpointResource.GRPC_EXPERIMENTAL_XDS_DUALSTACK_ENDPOINTS;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.github.udpa.udpa.type.v1.TypedStruct; import com.github.udpa.udpa.type.v1.TypedStruct;
@ -154,9 +155,7 @@ import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -173,9 +172,6 @@ public class GrpcXdsClientImplDataTest {
private static final String GRPC_EXPERIMENTAL_XDS_AUTHORITY_REWRITE = private static final String GRPC_EXPERIMENTAL_XDS_AUTHORITY_REWRITE =
"GRPC_EXPERIMENTAL_XDS_AUTHORITY_REWRITE"; "GRPC_EXPERIMENTAL_XDS_AUTHORITY_REWRITE";
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final FilterRegistry filterRegistry = FilterRegistry.getDefaultRegistry(); private final FilterRegistry filterRegistry = FilterRegistry.getDefaultRegistry();
private boolean originalEnableRouteLookup; private boolean originalEnableRouteLookup;
private boolean originalEnableLeastRequest; private boolean originalEnableLeastRequest;
@ -1572,11 +1568,12 @@ public class GrpcXdsClientImplDataTest {
throws ResourceInvalidException { throws ResourceInvalidException {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
HttpConnectionManager hcm = HttpConnectionManager.newBuilder().setXffNumTrustedHops(2).build(); HttpConnectionManager hcm = HttpConnectionManager.newBuilder().setXffNumTrustedHops(2).build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class,
thrown.expectMessage("HttpConnectionManager with xff_num_trusted_hops unsupported"); () -> XdsListenerResource.parseHttpConnectionManager(
XdsListenerResource.parseHttpConnectionManager( hcm, filterRegistry,
hcm, filterRegistry, true /* does not matter */, getXdsResourceTypeArgs(true)));
true /* does not matter */, getXdsResourceTypeArgs(true)); assertThat(e).hasMessageThat()
.isEqualTo("HttpConnectionManager with xff_num_trusted_hops unsupported");
} }
@Test @Test
@ -1586,12 +1583,13 @@ public class GrpcXdsClientImplDataTest {
HttpConnectionManager hcm = HttpConnectionManager.newBuilder() HttpConnectionManager hcm = HttpConnectionManager.newBuilder()
.addOriginalIpDetectionExtensions(TypedExtensionConfig.newBuilder().build()) .addOriginalIpDetectionExtensions(TypedExtensionConfig.newBuilder().build())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("HttpConnectionManager with original_ip_detection_extensions unsupported"); XdsListenerResource.parseHttpConnectionManager(
XdsListenerResource.parseHttpConnectionManager( hcm, filterRegistry, false, getXdsResourceTypeArgs(true)));
hcm, filterRegistry, false, getXdsResourceTypeArgs(true)); assertThat(e).hasMessageThat()
.isEqualTo("HttpConnectionManager with original_ip_detection_extensions unsupported");
} }
@Test @Test
public void parseHttpConnectionManager_missingRdsAndInlinedRouteConfiguration() public void parseHttpConnectionManager_missingRdsAndInlinedRouteConfiguration()
throws ResourceInvalidException { throws ResourceInvalidException {
@ -1604,11 +1602,12 @@ public class GrpcXdsClientImplDataTest {
HttpFilter.newBuilder().setName("terminal").setTypedConfig( HttpFilter.newBuilder().setName("terminal").setTypedConfig(
Any.pack(Router.newBuilder().build())).setIsOptional(true)) Any.pack(Router.newBuilder().build())).setIsOptional(true))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("HttpConnectionManager neither has inlined route_config nor RDS"); XdsListenerResource.parseHttpConnectionManager(
XdsListenerResource.parseHttpConnectionManager( hcm, filterRegistry,
hcm, filterRegistry, true /* does not matter */, getXdsResourceTypeArgs(true)));
true /* does not matter */, getXdsResourceTypeArgs(true)); assertThat(e).hasMessageThat()
.isEqualTo("HttpConnectionManager neither has inlined route_config nor RDS");
} }
@Test @Test
@ -1623,11 +1622,12 @@ public class GrpcXdsClientImplDataTest {
HttpFilter.newBuilder().setName("terminal").setTypedConfig( HttpFilter.newBuilder().setName("terminal").setTypedConfig(
Any.pack(Router.newBuilder().build())).setIsOptional(true)) Any.pack(Router.newBuilder().build())).setIsOptional(true))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("HttpConnectionManager contains duplicate HttpFilter: envoy.filter.foo"); XdsListenerResource.parseHttpConnectionManager(
XdsListenerResource.parseHttpConnectionManager( hcm, filterRegistry,
hcm, filterRegistry, true /* does not matter */, getXdsResourceTypeArgs(true)));
true /* does not matter */, getXdsResourceTypeArgs(true)); assertThat(e).hasMessageThat()
.isEqualTo("HttpConnectionManager contains duplicate HttpFilter: envoy.filter.foo");
} }
@Test @Test
@ -1641,11 +1641,12 @@ public class GrpcXdsClientImplDataTest {
HttpFilter.newBuilder().setName("envoy.filter.bar").setIsOptional(true) HttpFilter.newBuilder().setName("envoy.filter.bar").setIsOptional(true)
.setTypedConfig(Any.pack(HTTPFault.newBuilder().build()))) .setTypedConfig(Any.pack(HTTPFault.newBuilder().build())))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("The last HttpFilter must be a terminal filter: envoy.filter.bar"); XdsListenerResource.parseHttpConnectionManager(
XdsListenerResource.parseHttpConnectionManager(
hcm, filterRegistry, hcm, filterRegistry,
true /* does not matter */, getXdsResourceTypeArgs(true)); true /* does not matter */, getXdsResourceTypeArgs(true)));
assertThat(e).hasMessageThat()
.isEqualTo("The last HttpFilter must be a terminal filter: envoy.filter.bar");
} }
@Test @Test
@ -1659,11 +1660,12 @@ public class GrpcXdsClientImplDataTest {
.addHttpFilters( .addHttpFilters(
HttpFilter.newBuilder().setName("envoy.filter.foo").setIsOptional(true)) HttpFilter.newBuilder().setName("envoy.filter.foo").setIsOptional(true))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("A terminal HttpFilter must be the last filter: terminal"); XdsListenerResource.parseHttpConnectionManager(
XdsListenerResource.parseHttpConnectionManager(
hcm, filterRegistry, hcm, filterRegistry,
true, getXdsResourceTypeArgs(true)); true, getXdsResourceTypeArgs(true)));
assertThat(e).hasMessageThat()
.isEqualTo("A terminal HttpFilter must be the last filter: terminal");
} }
@Test @Test
@ -1675,11 +1677,12 @@ public class GrpcXdsClientImplDataTest {
.addHttpFilters( .addHttpFilters(
HttpFilter.newBuilder().setName("envoy.filter.bar").setIsOptional(true)) HttpFilter.newBuilder().setName("envoy.filter.bar").setIsOptional(true))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("The last HttpFilter must be a terminal filter: envoy.filter.bar"); XdsListenerResource.parseHttpConnectionManager(
XdsListenerResource.parseHttpConnectionManager(
hcm, filterRegistry, hcm, filterRegistry,
true /* does not matter */, getXdsResourceTypeArgs(true)); true /* does not matter */, getXdsResourceTypeArgs(true)));
assertThat(e).hasMessageThat()
.isEqualTo("The last HttpFilter must be a terminal filter: envoy.filter.bar");
} }
@Test @Test
@ -1687,11 +1690,12 @@ public class GrpcXdsClientImplDataTest {
HttpConnectionManager hcm = HttpConnectionManager hcm =
HttpConnectionManager.newBuilder() HttpConnectionManager.newBuilder()
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("Missing HttpFilter in HttpConnectionManager."); XdsListenerResource.parseHttpConnectionManager(
XdsListenerResource.parseHttpConnectionManager(
hcm, filterRegistry, hcm, filterRegistry,
true /* does not matter */, getXdsResourceTypeArgs(true)); true /* does not matter */, getXdsResourceTypeArgs(true)));
assertThat(e).hasMessageThat()
.isEqualTo("Missing HttpFilter in HttpConnectionManager.");
} }
@Test @Test
@ -1815,12 +1819,12 @@ public class GrpcXdsClientImplDataTest {
Any.pack(Router.newBuilder().build())).setIsOptional(true)) Any.pack(Router.newBuilder().build())).setIsOptional(true))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("Multiple ClusterSpecifierPlugins with the same name: rls-plugin-1"); XdsListenerResource.parseHttpConnectionManager(
hcm, filterRegistry,
XdsListenerResource.parseHttpConnectionManager( true /* does not matter */, getXdsResourceTypeArgs(true)));
hcm, filterRegistry, assertThat(e).hasMessageThat()
true /* does not matter */, getXdsResourceTypeArgs(true)); .isEqualTo("Multiple ClusterSpecifierPlugins with the same name: rls-plugin-1");
} }
@Test @Test
@ -1867,12 +1871,12 @@ public class GrpcXdsClientImplDataTest {
Any.pack(Router.newBuilder().build())).setIsOptional(true)) Any.pack(Router.newBuilder().build())).setIsOptional(true))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("ClusterSpecifierPlugin for [invalid-plugin-name] not found"); XdsListenerResource.parseHttpConnectionManager(
hcm, filterRegistry,
XdsListenerResource.parseHttpConnectionManager( true /* does not matter */, getXdsResourceTypeArgs(true)));
hcm, filterRegistry, assertThat(e).hasMessageThat()
true /* does not matter */, getXdsResourceTypeArgs(true)); .contains("ClusterSpecifierPlugin for [invalid-plugin-name] not found");
} }
@ -2001,12 +2005,12 @@ public class GrpcXdsClientImplDataTest {
HttpFilter.newBuilder().setName("terminal").setTypedConfig( HttpFilter.newBuilder().setName("terminal").setTypedConfig(
Any.pack(Router.newBuilder().build())).setIsOptional(true)) Any.pack(Router.newBuilder().build())).setIsOptional(true))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsListenerResource.parseHttpConnectionManager(
hcm3, filterRegistry,
true /* does not matter */, getXdsResourceTypeArgs(true)));
assertThat(e).hasMessageThat().isEqualTo(
"HttpConnectionManager contains invalid RDS: must specify ADS or self ConfigSource"); "HttpConnectionManager contains invalid RDS: must specify ADS or self ConfigSource");
XdsListenerResource.parseHttpConnectionManager(
hcm3, filterRegistry,
true /* does not matter */, getXdsResourceTypeArgs(true));
} }
@Test @Test
@ -2096,11 +2100,10 @@ public class GrpcXdsClientImplDataTest {
.setTypedConfig(Any.pack(StringValue.of("unregistered")))) .setTypedConfig(Any.pack(StringValue.of("unregistered"))))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsRouteConfigureResource.parseClusterSpecifierPlugin(pluginProto, registry));
assertThat(e).hasMessageThat().isEqualTo(
"Unsupported ClusterSpecifierPlugin type: type.googleapis.com/google.protobuf.StringValue"); "Unsupported ClusterSpecifierPlugin type: type.googleapis.com/google.protobuf.StringValue");
XdsRouteConfigureResource.parseClusterSpecifierPlugin(pluginProto, registry);
} }
@Test @Test
@ -2297,11 +2300,11 @@ public class GrpcXdsClientImplDataTest {
Cluster.TransportSocketMatch.newBuilder().setName("match1").build()) Cluster.TransportSocketMatch.newBuilder().setName("match1").build())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsClusterResource.processCluster(cluster, null, LRS_SERVER_INFO,
LoadBalancerRegistry.getDefaultRegistry()));
assertThat(e).hasMessageThat().isEqualTo(
"Cluster cluster-foo.googleapis.com: transport-socket-matches not supported."); "Cluster cluster-foo.googleapis.com: transport-socket-matches not supported.");
XdsClusterResource.processCluster(cluster, null, LRS_SERVER_INFO,
LoadBalancerRegistry.getDefaultRegistry());
} }
@Test @Test
@ -2346,12 +2349,12 @@ public class GrpcXdsClientImplDataTest {
.setLbPolicy(LbPolicy.ROUND_ROBIN) .setLbPolicy(LbPolicy.ROUND_ROBIN)
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsClusterResource.processCluster(cluster3, null, LRS_SERVER_INFO,
LoadBalancerRegistry.getDefaultRegistry()));
assertThat(e).hasMessageThat().isEqualTo(
"Cluster cluster-foo.googleapis.com: field eds_cluster_config must be set to indicate to" "Cluster cluster-foo.googleapis.com: field eds_cluster_config must be set to indicate to"
+ " use EDS over ADS or self ConfigSource"); + " use EDS over ADS or self ConfigSource");
XdsClusterResource.processCluster(cluster3, null, LRS_SERVER_INFO,
LoadBalancerRegistry.getDefaultRegistry());
} }
@Test @Test
@ -2620,10 +2623,11 @@ public class GrpcXdsClientImplDataTest {
.setName("listener1") .setName("listener1")
.setTrafficDirection(TrafficDirection.OUTBOUND) .setTrafficDirection(TrafficDirection.OUTBOUND)
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("Listener listener1 with invalid traffic direction: OUTBOUND"); XdsListenerResource.parseServerSideListener(
XdsListenerResource.parseServerSideListener( listener, null, filterRegistry, null, getXdsResourceTypeArgs(true)));
listener, null, filterRegistry, null, getXdsResourceTypeArgs(true)); assertThat(e).hasMessageThat()
.isEqualTo("Listener listener1 with invalid traffic direction: OUTBOUND");
} }
@Test @Test
@ -2644,10 +2648,11 @@ public class GrpcXdsClientImplDataTest {
.setTrafficDirection(TrafficDirection.INBOUND) .setTrafficDirection(TrafficDirection.INBOUND)
.addListenerFilters(ListenerFilter.newBuilder().build()) .addListenerFilters(ListenerFilter.newBuilder().build())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("Listener listener1 cannot have listener_filters"); XdsListenerResource.parseServerSideListener(listener, null, filterRegistry, null,
XdsListenerResource.parseServerSideListener( getXdsResourceTypeArgs(true)));
listener, null, filterRegistry, null, getXdsResourceTypeArgs(true)); assertThat(e).hasMessageThat()
.isEqualTo("Listener listener1 cannot have listener_filters");
} }
@Test @Test
@ -2658,10 +2663,11 @@ public class GrpcXdsClientImplDataTest {
.setTrafficDirection(TrafficDirection.INBOUND) .setTrafficDirection(TrafficDirection.INBOUND)
.setUseOriginalDst(BoolValue.of(true)) .setUseOriginalDst(BoolValue.of(true))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("Listener listener1 cannot have use_original_dst set to true"); XdsListenerResource.parseServerSideListener(listener, null, filterRegistry, null,
XdsListenerResource.parseServerSideListener( getXdsResourceTypeArgs(true)));
listener,null, filterRegistry, null, getXdsResourceTypeArgs(true)); assertThat(e).hasMessageThat()
.isEqualTo("Listener listener1 cannot have use_original_dst set to true");
} }
@Test @Test
@ -2674,11 +2680,10 @@ public class GrpcXdsClientImplDataTest {
.setSocketAddress( .setSocketAddress(
SocketAddress.newBuilder())) SocketAddress.newBuilder()))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("Invalid address: Empty address is not allowed."); XdsListenerResource.parseServerSideListener(
listener, null, filterRegistry, null, getXdsResourceTypeArgs(true)));
XdsListenerResource.parseServerSideListener( assertThat(e).hasMessageThat().isEqualTo("Invalid address: Empty address is not allowed.");
listener,null, filterRegistry, null, getXdsResourceTypeArgs(true));
} }
@Test @Test
@ -2692,11 +2697,10 @@ public class GrpcXdsClientImplDataTest {
SocketAddress.newBuilder() SocketAddress.newBuilder()
.setAddress("172.14.14.5").setNamedPort(""))) .setAddress("172.14.14.5").setNamedPort("")))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("NAMED_PORT is not supported in gRPC."); XdsListenerResource.parseServerSideListener(
listener, null, filterRegistry, null, getXdsResourceTypeArgs(true)));
XdsListenerResource.parseServerSideListener( assertThat(e).hasMessageThat().isEqualTo("NAMED_PORT is not supported in gRPC.");
listener,null, filterRegistry, null, getXdsResourceTypeArgs(true));
} }
@Test @Test
@ -2742,10 +2746,11 @@ public class GrpcXdsClientImplDataTest {
.setTrafficDirection(TrafficDirection.INBOUND) .setTrafficDirection(TrafficDirection.INBOUND)
.addAllFilterChains(Arrays.asList(filterChain1, filterChain2)) .addAllFilterChains(Arrays.asList(filterChain1, filterChain2))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("FilterChainMatch must be unique. Found duplicate:"); XdsListenerResource.parseServerSideListener(
XdsListenerResource.parseServerSideListener( listener, null, filterRegistry, null, getXdsResourceTypeArgs(true)));
listener, null, filterRegistry, null, getXdsResourceTypeArgs(true)); assertThat(e).hasMessageThat()
.startsWith("FilterChainMatch must be unique. Found duplicate:");
} }
@Test @Test
@ -2791,10 +2796,11 @@ public class GrpcXdsClientImplDataTest {
.setTrafficDirection(TrafficDirection.INBOUND) .setTrafficDirection(TrafficDirection.INBOUND)
.addAllFilterChains(Arrays.asList(filterChain1, filterChain2)) .addAllFilterChains(Arrays.asList(filterChain1, filterChain2))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("FilterChainMatch must be unique. Found duplicate:"); XdsListenerResource.parseServerSideListener(
XdsListenerResource.parseServerSideListener( listener, null, filterRegistry, null, getXdsResourceTypeArgs(true)));
listener,null, filterRegistry, null, getXdsResourceTypeArgs(true)); assertThat(e).hasMessageThat()
.startsWith("FilterChainMatch must be unique. Found duplicate:");
} }
@Test @Test
@ -2854,12 +2860,12 @@ public class GrpcXdsClientImplDataTest {
.setFilterChainMatch(FilterChainMatch.getDefaultInstance()) .setFilterChainMatch(FilterChainMatch.getDefaultInstance())
.setTransportSocket(TransportSocket.getDefaultInstance()) .setTransportSocket(TransportSocket.getDefaultInstance())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsListenerResource.parseFilterChain(
filterChain, "filter-chain-foo", null, filterRegistry, null, null,
getXdsResourceTypeArgs(true)));
assertThat(e).hasMessageThat().isEqualTo(
"FilterChain filter-chain-foo should contain exact one HttpConnectionManager filter"); "FilterChain filter-chain-foo should contain exact one HttpConnectionManager filter");
XdsListenerResource.parseFilterChain(
filterChain, "filter-chain-foo", null, filterRegistry, null, null,
getXdsResourceTypeArgs(true));
} }
@Test @Test
@ -2873,12 +2879,12 @@ public class GrpcXdsClientImplDataTest {
.setTransportSocket(TransportSocket.getDefaultInstance()) .setTransportSocket(TransportSocket.getDefaultInstance())
.addAllFilters(Arrays.asList(filter, filter)) .addAllFilters(Arrays.asList(filter, filter))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsListenerResource.parseFilterChain(
filterChain, "filter-chain-foo", null, filterRegistry, null, null,
getXdsResourceTypeArgs(true)));
assertThat(e).hasMessageThat().isEqualTo(
"FilterChain filter-chain-foo should contain exact one HttpConnectionManager filter"); "FilterChain filter-chain-foo should contain exact one HttpConnectionManager filter");
XdsListenerResource.parseFilterChain(
filterChain, "filter-chain-foo", null, filterRegistry, null, null,
getXdsResourceTypeArgs(true));
} }
@Test @Test
@ -2891,13 +2897,13 @@ public class GrpcXdsClientImplDataTest {
.setTransportSocket(TransportSocket.getDefaultInstance()) .setTransportSocket(TransportSocket.getDefaultInstance())
.addFilters(filter) .addFilters(filter)
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsListenerResource.parseFilterChain(
filterChain, "filter-chain-foo", null, filterRegistry, null, null,
getXdsResourceTypeArgs(true)));
assertThat(e).hasMessageThat().isEqualTo(
"FilterChain filter-chain-foo contains filter envoy.http_connection_manager " "FilterChain filter-chain-foo contains filter envoy.http_connection_manager "
+ "without typed_config"); + "without typed_config");
XdsListenerResource.parseFilterChain(
filterChain, "filter-chain-foo", null, filterRegistry, null, null,
getXdsResourceTypeArgs(true));
} }
@Test @Test
@ -2914,13 +2920,13 @@ public class GrpcXdsClientImplDataTest {
.setTransportSocket(TransportSocket.getDefaultInstance()) .setTransportSocket(TransportSocket.getDefaultInstance())
.addFilters(filter) .addFilters(filter)
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsListenerResource.parseFilterChain(
filterChain, "filter-chain-foo", null, filterRegistry, null, null,
getXdsResourceTypeArgs(true)));
assertThat(e).hasMessageThat().isEqualTo(
"FilterChain filter-chain-foo contains filter unsupported with unsupported " "FilterChain filter-chain-foo contains filter unsupported with unsupported "
+ "typed_config type unsupported-type-url"); + "typed_config type unsupported-type-url");
XdsListenerResource.parseFilterChain(
filterChain, "filter-chain-foo", null, filterRegistry, null, null,
getXdsResourceTypeArgs(true));
} }
@Test @Test
@ -2996,53 +3002,55 @@ public class GrpcXdsClientImplDataTest {
.setTrafficDirection(TrafficDirection.INBOUND) .setTrafficDirection(TrafficDirection.INBOUND)
.addAllFilterChains(Arrays.asList(filterChain0, filterChain1)) .addAllFilterChains(Arrays.asList(filterChain0, filterChain1))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("Filter chain names must be unique. Found duplicate: filter_chain"); XdsListenerResource.parseServerSideListener(
XdsListenerResource.parseServerSideListener( listenerProto, null, filterRegistry, null, getXdsResourceTypeArgs(true)));
listenerProto, null, filterRegistry, null, getXdsResourceTypeArgs(true)); assertThat(e).hasMessageThat()
.isEqualTo("Filter chain names must be unique. Found duplicate: filter_chain");
} }
@Test @Test
public void validateCommonTlsContext_tlsParams() throws ResourceInvalidException { public void validateCommonTlsContext_tlsParams() {
CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder()
.setTlsParams(TlsParameters.getDefaultInstance()) .setTlsParams(TlsParameters.getDefaultInstance())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("common-tls-context with tls_params is not supported"); XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false));
XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false); assertThat(e).hasMessageThat().isEqualTo("common-tls-context with tls_params is not supported");
} }
@Test @Test
public void validateCommonTlsContext_customHandshaker() throws ResourceInvalidException { public void validateCommonTlsContext_customHandshaker() {
CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder()
.setCustomHandshaker(TypedExtensionConfig.getDefaultInstance()) .setCustomHandshaker(TypedExtensionConfig.getDefaultInstance())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("common-tls-context with custom_handshaker is not supported"); XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false));
XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false); assertThat(e).hasMessageThat().isEqualTo(
"common-tls-context with custom_handshaker is not supported");
} }
@Test @Test
public void validateCommonTlsContext_validationContext() throws ResourceInvalidException { public void validateCommonTlsContext_validationContext() {
CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder()
.setValidationContext(CertificateValidationContext.getDefaultInstance()) .setValidationContext(CertificateValidationContext.getDefaultInstance())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("ca_certificate_provider_instance or system_root_certs is required " XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false));
+ "in upstream-tls-context"); assertThat(e).hasMessageThat().isEqualTo(
XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false); "ca_certificate_provider_instance or system_root_certs is required "
+ "in upstream-tls-context");
} }
@Test @Test
public void validateCommonTlsContext_validationContextSdsSecretConfig() public void validateCommonTlsContext_validationContextSdsSecretConfig() {
throws ResourceInvalidException {
CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder()
.setValidationContextSdsSecretConfig(SdsSecretConfig.getDefaultInstance()) .setValidationContextSdsSecretConfig(SdsSecretConfig.getDefaultInstance())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false));
assertThat(e).hasMessageThat().isEqualTo(
"common-tls-context with validation_context_sds_secret_config is not supported"); "common-tls-context with validation_context_sds_secret_config is not supported");
XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false);
} }
@Test @Test
@ -3050,10 +3058,10 @@ public class GrpcXdsClientImplDataTest {
throws ResourceInvalidException { throws ResourceInvalidException {
CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder()
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, true));
assertThat(e).hasMessageThat().isEqualTo(
"tls_certificate_provider_instance is required in downstream-tls-context"); "tls_certificate_provider_instance is required in downstream-tls-context");
XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, true);
} }
@Test @Test
@ -3085,11 +3093,11 @@ public class GrpcXdsClientImplDataTest {
.setTlsCertificateProviderInstance( .setTlsCertificateProviderInstance(
CertificateProviderPluginInstance.newBuilder().setInstanceName("bad-name")) CertificateProviderPluginInstance.newBuilder().setInstanceName("bad-name"))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsClusterResource.validateCommonTlsContext(commonTlsContext,
ImmutableSet.of("name1", "name2"), true));
assertThat(e).hasMessageThat().isEqualTo(
"CertificateProvider instance name 'bad-name' not defined in the bootstrap file."); "CertificateProvider instance name 'bad-name' not defined in the bootstrap file.");
XdsClusterResource
.validateCommonTlsContext(commonTlsContext, ImmutableSet.of("name1", "name2"), true);
} }
@Test @Test
@ -3197,11 +3205,11 @@ public class GrpcXdsClientImplDataTest {
.setCaCertificateProviderInstance(CertificateProviderPluginInstance.newBuilder() .setCaCertificateProviderInstance(CertificateProviderPluginInstance.newBuilder()
.setInstanceName("bad-name")))) .setInstanceName("bad-name"))))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsClusterResource.validateCommonTlsContext(commonTlsContext,
ImmutableSet.of("name1", "name2"), false));
assertThat(e).hasMessageThat().isEqualTo(
"ca_certificate_provider_instance name 'bad-name' not defined in the bootstrap file."); "ca_certificate_provider_instance name 'bad-name' not defined in the bootstrap file.");
XdsClusterResource
.validateCommonTlsContext(commonTlsContext, ImmutableSet.of("name1", "name2"), false);
} }
@ -3210,9 +3218,9 @@ public class GrpcXdsClientImplDataTest {
CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder()
.addTlsCertificates(TlsCertificate.getDefaultInstance()) .addTlsCertificates(TlsCertificate.getDefaultInstance())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("tls_certificate_provider_instance is unset"); XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false));
XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false); assertThat(e).hasMessageThat().isEqualTo("tls_certificate_provider_instance is unset");
} }
@Test @Test
@ -3221,10 +3229,10 @@ public class GrpcXdsClientImplDataTest {
CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder()
.addTlsCertificateSdsSecretConfigs(SdsSecretConfig.getDefaultInstance()) .addTlsCertificateSdsSecretConfigs(SdsSecretConfig.getDefaultInstance())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false));
assertThat(e).hasMessageThat().isEqualTo(
"tls_certificate_provider_instance is unset"); "tls_certificate_provider_instance is unset");
XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false);
} }
@Test @Test
@ -3232,10 +3240,11 @@ public class GrpcXdsClientImplDataTest {
throws ResourceInvalidException { throws ResourceInvalidException {
CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder() CommonTlsContext commonTlsContext = CommonTlsContext.newBuilder()
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("ca_certificate_provider_instance or system_root_certs is required " XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false));
+ "in upstream-tls-context"); assertThat(e).hasMessageThat().isEqualTo(
XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false); "ca_certificate_provider_instance or system_root_certs is required "
+ "in upstream-tls-context");
} }
@Test @Test
@ -3245,11 +3254,11 @@ public class GrpcXdsClientImplDataTest {
.setCombinedValidationContext( .setCombinedValidationContext(
CommonTlsContext.CombinedCertificateValidationContext.getDefaultInstance()) CommonTlsContext.CombinedCertificateValidationContext.getDefaultInstance())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false));
assertThat(e).hasMessageThat().isEqualTo(
"ca_certificate_provider_instance or system_root_certs is required in " "ca_certificate_provider_instance or system_root_certs is required in "
+ "upstream-tls-context"); + "upstream-tls-context");
XdsClusterResource.validateCommonTlsContext(commonTlsContext, null, false);
} }
@Test @Test
@ -3267,9 +3276,10 @@ public class GrpcXdsClientImplDataTest {
.setTlsCertificateProviderInstance( .setTlsCertificateProviderInstance(
CertificateProviderPluginInstance.getDefaultInstance()) CertificateProviderPluginInstance.getDefaultInstance())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("match_subject_alt_names only allowed in upstream_tls_context"); XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), true));
XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), true); assertThat(e).hasMessageThat().isEqualTo(
"match_subject_alt_names only allowed in upstream_tls_context");
} }
@Test @Test
@ -3284,10 +3294,10 @@ public class GrpcXdsClientImplDataTest {
.addVerifyCertificateSpki("foo"))) .addVerifyCertificateSpki("foo")))
.setTlsCertificateProviderInstance(CertificateProviderPluginInstance.getDefaultInstance()) .setTlsCertificateProviderInstance(CertificateProviderPluginInstance.getDefaultInstance())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("verify_certificate_spki in default_validation_context is not " XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), false));
+ "supported"); assertThat(e).hasMessageThat().isEqualTo(
XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), false); "verify_certificate_spki in default_validation_context is not supported");
} }
@Test @Test
@ -3302,10 +3312,10 @@ public class GrpcXdsClientImplDataTest {
.addVerifyCertificateHash("foo"))) .addVerifyCertificateHash("foo")))
.setTlsCertificateProviderInstance(CertificateProviderPluginInstance.getDefaultInstance()) .setTlsCertificateProviderInstance(CertificateProviderPluginInstance.getDefaultInstance())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("verify_certificate_hash in default_validation_context is not " XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), false));
+ "supported"); assertThat(e).hasMessageThat().isEqualTo(
XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), false); "verify_certificate_hash in default_validation_context is not supported");
} }
@Test @Test
@ -3321,11 +3331,11 @@ public class GrpcXdsClientImplDataTest {
.setTlsCertificateProviderInstance( .setTlsCertificateProviderInstance(
CertificateProviderPluginInstance.getDefaultInstance()) CertificateProviderPluginInstance.getDefaultInstance())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), false));
assertThat(e).hasMessageThat().isEqualTo(
"require_signed_certificate_timestamp in default_validation_context is not " "require_signed_certificate_timestamp in default_validation_context is not "
+ "supported"); + "supported");
XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), false);
} }
@Test @Test
@ -3340,9 +3350,9 @@ public class GrpcXdsClientImplDataTest {
.setCrl(DataSource.getDefaultInstance()))) .setCrl(DataSource.getDefaultInstance())))
.setTlsCertificateProviderInstance(CertificateProviderPluginInstance.getDefaultInstance()) .setTlsCertificateProviderInstance(CertificateProviderPluginInstance.getDefaultInstance())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("crl in default_validation_context is not supported"); XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), false));
XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), false); assertThat(e).hasMessageThat().isEqualTo("crl in default_validation_context is not supported");
} }
@Test @Test
@ -3357,18 +3367,19 @@ public class GrpcXdsClientImplDataTest {
.setCustomValidatorConfig(TypedExtensionConfig.getDefaultInstance()))) .setCustomValidatorConfig(TypedExtensionConfig.getDefaultInstance())))
.setTlsCertificateProviderInstance(CertificateProviderPluginInstance.getDefaultInstance()) .setTlsCertificateProviderInstance(CertificateProviderPluginInstance.getDefaultInstance())
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("custom_validator_config in default_validation_context is not " XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), false));
+ "supported"); assertThat(e).hasMessageThat().isEqualTo(
XdsClusterResource.validateCommonTlsContext(commonTlsContext, ImmutableSet.of(""), false); "custom_validator_config in default_validation_context is not supported");
} }
@Test @Test
public void validateDownstreamTlsContext_noCommonTlsContext() throws ResourceInvalidException { public void validateDownstreamTlsContext_noCommonTlsContext() throws ResourceInvalidException {
DownstreamTlsContext downstreamTlsContext = DownstreamTlsContext.getDefaultInstance(); DownstreamTlsContext downstreamTlsContext = DownstreamTlsContext.getDefaultInstance();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("common-tls-context is required in downstream-tls-context"); XdsListenerResource.validateDownstreamTlsContext(downstreamTlsContext, null));
XdsListenerResource.validateDownstreamTlsContext(downstreamTlsContext, null); assertThat(e).hasMessageThat().isEqualTo(
"common-tls-context is required in downstream-tls-context");
} }
@Test @Test
@ -3385,9 +3396,11 @@ public class GrpcXdsClientImplDataTest {
.setCommonTlsContext(commonTlsContext) .setCommonTlsContext(commonTlsContext)
.setRequireSni(BoolValue.of(true)) .setRequireSni(BoolValue.of(true))
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("downstream-tls-context with require-sni is not supported"); XdsListenerResource.validateDownstreamTlsContext(downstreamTlsContext,
XdsListenerResource.validateDownstreamTlsContext(downstreamTlsContext, ImmutableSet.of("")); ImmutableSet.of("")));
assertThat(e).hasMessageThat().isEqualTo(
"downstream-tls-context with require-sni is not supported");
} }
@Test @Test
@ -3404,18 +3417,20 @@ public class GrpcXdsClientImplDataTest {
.setCommonTlsContext(commonTlsContext) .setCommonTlsContext(commonTlsContext)
.setOcspStaplePolicy(DownstreamTlsContext.OcspStaplePolicy.STRICT_STAPLING) .setOcspStaplePolicy(DownstreamTlsContext.OcspStaplePolicy.STRICT_STAPLING)
.build(); .build();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage( XdsListenerResource.validateDownstreamTlsContext(downstreamTlsContext,
ImmutableSet.of("")));
assertThat(e).hasMessageThat().isEqualTo(
"downstream-tls-context with ocsp_staple_policy value STRICT_STAPLING is not supported"); "downstream-tls-context with ocsp_staple_policy value STRICT_STAPLING is not supported");
XdsListenerResource.validateDownstreamTlsContext(downstreamTlsContext, ImmutableSet.of(""));
} }
@Test @Test
public void validateUpstreamTlsContext_noCommonTlsContext() throws ResourceInvalidException { public void validateUpstreamTlsContext_noCommonTlsContext() throws ResourceInvalidException {
UpstreamTlsContext upstreamTlsContext = UpstreamTlsContext.getDefaultInstance(); UpstreamTlsContext upstreamTlsContext = UpstreamTlsContext.getDefaultInstance();
thrown.expect(ResourceInvalidException.class); ResourceInvalidException e = assertThrows(ResourceInvalidException.class, () ->
thrown.expectMessage("common-tls-context is required in upstream-tls-context"); XdsClusterResource.validateUpstreamTlsContext(upstreamTlsContext, null));
XdsClusterResource.validateUpstreamTlsContext(upstreamTlsContext, null); assertThat(e).hasMessageThat().isEqualTo(
"common-tls-context is required in upstream-tls-context");
} }
@Test @Test

View File

@ -16,6 +16,7 @@
package io.grpc.xds; package io.grpc.xds;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -26,17 +27,13 @@ import io.grpc.xds.PriorityLoadBalancerProvider.PriorityLbConfig;
import io.grpc.xds.PriorityLoadBalancerProvider.PriorityLbConfig.PriorityChildConfig; import io.grpc.xds.PriorityLoadBalancerProvider.PriorityLbConfig.PriorityChildConfig;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Tests for {@link PriorityLoadBalancerProvider}. */ /** Tests for {@link PriorityLoadBalancerProvider}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class PriorityLoadBalancerProviderTest { public class PriorityLoadBalancerProviderTest {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule public final ExpectedException thrown = ExpectedException.none();
@SuppressWarnings("ExpectedExceptionChecker") @SuppressWarnings("ExpectedExceptionChecker")
@Test @Test
@ -48,8 +45,8 @@ public class PriorityLoadBalancerProviderTest {
newChildConfig(mock(LoadBalancerProvider.class), null), true)); newChildConfig(mock(LoadBalancerProvider.class), null), true));
List<String> priorities = ImmutableList.of(); List<String> priorities = ImmutableList.of();
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class,
new PriorityLbConfig(childConfigs, priorities); () -> new PriorityLbConfig(childConfigs, priorities));
} }
@SuppressWarnings("ExpectedExceptionChecker") @SuppressWarnings("ExpectedExceptionChecker")
@ -62,8 +59,8 @@ public class PriorityLoadBalancerProviderTest {
newChildConfig(mock(LoadBalancerProvider.class), null), true)); newChildConfig(mock(LoadBalancerProvider.class), null), true));
List<String> priorities = ImmutableList.of("p0", "p1"); List<String> priorities = ImmutableList.of("p0", "p1");
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class,
new PriorityLbConfig(childConfigs, priorities); () -> new PriorityLbConfig(childConfigs, priorities));
} }
private Object newChildConfig(LoadBalancerProvider provider, Object config) { private Object newChildConfig(LoadBalancerProvider provider, Object config) {

View File

@ -19,6 +19,7 @@ package io.grpc.xds;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static io.grpc.Metadata.ASCII_STRING_MARSHALLER; import static io.grpc.Metadata.ASCII_STRING_MARSHALLER;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -50,7 +51,6 @@ import java.util.Collections;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.Mock; import org.mockito.Mock;
@ -64,9 +64,6 @@ public class SharedXdsClientPoolProviderTest {
private static final String SERVER_URI = "trafficdirector.googleapis.com"; private static final String SERVER_URI = "trafficdirector.googleapis.com";
@Rule @Rule
public final MockitoRule mocks = MockitoJUnit.rule(); public final MockitoRule mocks = MockitoJUnit.rule();
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final Node node = Node.newBuilder().setId("SharedXdsClientPoolProviderTest").build(); private final Node node = Node.newBuilder().setId("SharedXdsClientPoolProviderTest").build();
private final MetricRecorder metricRecorder = new MetricRecorder() {}; private final MetricRecorder metricRecorder = new MetricRecorder() {};
private static final String DUMMY_TARGET = "dummy"; private static final String DUMMY_TARGET = "dummy";
@ -83,9 +80,9 @@ public class SharedXdsClientPoolProviderTest {
BootstrapInfo.builder().servers(Collections.<ServerInfo>emptyList()).node(node).build(); BootstrapInfo.builder().servers(Collections.<ServerInfo>emptyList()).node(node).build();
when(bootstrapper.bootstrap()).thenReturn(bootstrapInfo); when(bootstrapper.bootstrap()).thenReturn(bootstrapInfo);
SharedXdsClientPoolProvider provider = new SharedXdsClientPoolProvider(bootstrapper); SharedXdsClientPoolProvider provider = new SharedXdsClientPoolProvider(bootstrapper);
thrown.expect(XdsInitializationException.class); XdsInitializationException e = assertThrows(XdsInitializationException.class,
thrown.expectMessage("No xDS server provided"); () -> provider.getOrCreate(DUMMY_TARGET, metricRecorder));
provider.getOrCreate(DUMMY_TARGET, metricRecorder); assertThat(e).hasMessageThat().isEqualTo("No xDS server provided");
assertThat(provider.get(DUMMY_TARGET)).isNull(); assertThat(provider.get(DUMMY_TARGET)).isNull();
} }

View File

@ -17,6 +17,7 @@
package io.grpc.xds; package io.grpc.xds;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import io.grpc.LoadBalancer.PickResult; import io.grpc.LoadBalancer.PickResult;
@ -30,7 +31,6 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.Mock; import org.mockito.Mock;
@ -42,9 +42,6 @@ import org.mockito.junit.MockitoRule;
*/ */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class WeightedRandomPickerTest { public class WeightedRandomPickerTest {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule @Rule
public final MockitoRule mockitoRule = MockitoJUnit.rule(); public final MockitoRule mockitoRule = MockitoJUnit.rule();
@ -128,20 +125,18 @@ public class WeightedRandomPickerTest {
public void emptyList() { public void emptyList() {
List<WeightedChildPicker> emptyList = new ArrayList<>(); List<WeightedChildPicker> emptyList = new ArrayList<>();
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> new WeightedRandomPicker(emptyList));
new WeightedRandomPicker(emptyList);
} }
@Test @Test
public void negativeWeight() { public void negativeWeight() {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> new WeightedChildPicker(-1, childPicker0));
new WeightedChildPicker(-1, childPicker0);
} }
@Test @Test
public void overWeightSingle() { public void overWeightSingle() {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class,
new WeightedChildPicker(Integer.MAX_VALUE * 3L, childPicker0); () -> new WeightedChildPicker(Integer.MAX_VALUE * 3L, childPicker0));
} }
@Test @Test
@ -152,8 +147,8 @@ public class WeightedRandomPickerTest {
new WeightedChildPicker(Integer.MAX_VALUE, childPicker1), new WeightedChildPicker(Integer.MAX_VALUE, childPicker1),
new WeightedChildPicker(10, childPicker2)); new WeightedChildPicker(10, childPicker2));
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class,
new WeightedRandomPicker(weightedChildPickers, fakeRandom); () -> new WeightedRandomPicker(weightedChildPickers, fakeRandom));
} }
@Test @Test