From 61045159b3aa0e0fcafd6d484914fa48ee479169 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 12:44:32 -0400 Subject: [PATCH 01/43] chore: change test dependency --- java-core/google-cloud-core-grpc/pom.xml | 14 ++++++++++++-- java-core/google-cloud-core-http/pom.xml | 14 ++++++++++++-- java-core/google-cloud-core/pom.xml | 14 ++++++++++++-- java-core/pom.xml | 11 ++++++----- 4 files changed, 42 insertions(+), 11 deletions(-) diff --git a/java-core/google-cloud-core-grpc/pom.xml b/java-core/google-cloud-core-grpc/pom.xml index e34018d001..044b9bda98 100644 --- a/java-core/google-cloud-core-grpc/pom.xml +++ b/java-core/google-cloud-core-grpc/pom.xml @@ -56,8 +56,18 @@ - junit - junit + org.junit.platform + junit-platform-launcher + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.vintage + junit-vintage-engine test diff --git a/java-core/google-cloud-core-http/pom.xml b/java-core/google-cloud-core-http/pom.xml index fd9d09276d..2f36c04031 100644 --- a/java-core/google-cloud-core-http/pom.xml +++ b/java-core/google-cloud-core-http/pom.xml @@ -77,8 +77,18 @@ - junit - junit + org.junit.platform + junit-platform-launcher + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.vintage + junit-vintage-engine test diff --git a/java-core/google-cloud-core/pom.xml b/java-core/google-cloud-core/pom.xml index 2fdb90a847..2407e2b65f 100644 --- a/java-core/google-cloud-core/pom.xml +++ b/java-core/google-cloud-core/pom.xml @@ -76,8 +76,18 @@ - junit - junit + org.junit.platform + junit-platform-launcher + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.vintage + junit-vintage-engine test diff --git a/java-core/pom.xml b/java-core/pom.xml index af452d0855..4b4daa8900 100644 --- a/java-core/pom.xml +++ b/java-core/pom.xml @@ -37,13 +37,14 @@ pom import - - junit - junit - 4.13.2 - test + org.junit + junit-bom + 5.10.2 + pom + import + com.google.truth truth From ba073a2acbba424655d69c019a19f338a4a43ec4 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 12:47:12 -0400 Subject: [PATCH 02/43] change tests --- .../cloud/testing/BaseEmulatorHelperTest.java | 10 +++++----- .../google/cloud/testing/CommandWrapperTest.java | 14 +++++++------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/BaseEmulatorHelperTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/BaseEmulatorHelperTest.java index 2c6d7495be..79b58a83c9 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/BaseEmulatorHelperTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/BaseEmulatorHelperTest.java @@ -32,10 +32,10 @@ import java.util.concurrent.TimeoutException; import java.util.logging.Logger; import org.easymock.EasyMock; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.threeten.bp.Duration; -public class BaseEmulatorHelperTest { +class BaseEmulatorHelperTest { private static final String BLOCK_UNTIL = "Block until"; @@ -82,7 +82,7 @@ public void reset() throws IOException { } @Test - public void testEmulatorHelper() throws IOException, InterruptedException, TimeoutException { + void testEmulatorHelper() throws IOException, InterruptedException, TimeoutException { Process process = EasyMock.createStrictMock(Process.class); InputStream stream = new ByteArrayInputStream(BLOCK_UNTIL.getBytes(Charsets.UTF_8)); EmulatorRunner emulatorRunner = EasyMock.createStrictMock(EmulatorRunner.class); @@ -102,7 +102,7 @@ public void testEmulatorHelper() throws IOException, InterruptedException, Timeo } @Test - public void testEmulatorHelperDownloadWithRetries() + void testEmulatorHelperDownloadWithRetries() throws IOException, InterruptedException, TimeoutException { String mockExternalForm = "mockExternalForm"; String mockInputStream = "mockInputStream"; @@ -145,7 +145,7 @@ public void testEmulatorHelperDownloadWithRetries() } @Test - public void testEmulatorHelperMultipleRunners() + void testEmulatorHelperMultipleRunners() throws IOException, InterruptedException, TimeoutException { Process process = EasyMock.createStrictMock(Process.class); InputStream stream = new ByteArrayInputStream(BLOCK_UNTIL.getBytes(Charsets.UTF_8)); diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/CommandWrapperTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/CommandWrapperTest.java index 88b246c754..3353e59661 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/CommandWrapperTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/CommandWrapperTest.java @@ -26,9 +26,9 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class CommandWrapperTest { +class CommandWrapperTest { private static final List COMMAND = ImmutableList.of("my", "command"); private static final List WIN_COMMAND = ImmutableList.of("cmd", "/C", "my", "command"); @@ -38,7 +38,7 @@ public class CommandWrapperTest { private static final File UNIX_NULL_FILE = new File("/dev/null"); @Test - public void testCommandWrapperCommand() { + void testCommandWrapperCommand() { CommandWrapper commandWrapper = CommandWrapper.create(); commandWrapper.setCommand(COMMAND); ProcessBuilder processBuilder = commandWrapper.getBuilder(); @@ -53,7 +53,7 @@ public void testCommandWrapperCommand() { } @Test - public void testCommandWrapperRedirectErrorStream() { + void testCommandWrapperRedirectErrorStream() { CommandWrapper commandWrapper = CommandWrapper.create(); commandWrapper.setCommand(COMMAND); commandWrapper.setRedirectErrorStream(); @@ -69,7 +69,7 @@ public void testCommandWrapperRedirectErrorStream() { } @Test - public void testCommandWrapperRedirectErrorInherit() { + void testCommandWrapperRedirectErrorInherit() { CommandWrapper commandWrapper = CommandWrapper.create(); commandWrapper.setCommand(COMMAND); commandWrapper.setRedirectErrorInherit(); @@ -85,7 +85,7 @@ public void testCommandWrapperRedirectErrorInherit() { } @Test - public void testCommandWrapperDirectory() { + void testCommandWrapperDirectory() { CommandWrapper commandWrapper = CommandWrapper.create(); commandWrapper.setCommand(COMMAND); commandWrapper.setDirectory(DIRECTORY); @@ -101,7 +101,7 @@ public void testCommandWrapperDirectory() { } @Test - public void testCommandWrapperRedirectOutputToNull() { + void testCommandWrapperRedirectOutputToNull() { CommandWrapper commandWrapper = CommandWrapper.create(); commandWrapper.setCommand(COMMAND); commandWrapper.setRedirectOutputToNull(); From fc4bcb347d4956b96ee50188ce8cc45d6bc8a147 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 12:50:56 -0400 Subject: [PATCH 03/43] change tests --- .../java/com/google/cloud/testing/CommandWrapperTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/CommandWrapperTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/CommandWrapperTest.java index 3353e59661..bc9cdc4a8c 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/CommandWrapperTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/CommandWrapperTest.java @@ -16,10 +16,10 @@ package com.google.cloud.testing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.ImmutableList; import java.io.File; From e7dd1390c0d41afdd2e9f3f475ddb6b412ea651e Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 12:51:53 -0400 Subject: [PATCH 04/43] change tests --- .../java/com/google/cloud/testing/LogRecorderTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/LogRecorderTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/LogRecorderTest.java index d6df12e278..5a3616f170 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/LogRecorderTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/LogRecorderTest.java @@ -23,9 +23,9 @@ import com.google.common.truth.Truth; import java.util.logging.Level; import java.util.logging.Logger; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class LogRecorderTest { +class LogRecorderTest { private static final String LOG_LINES = "INFO: log line 1\n" + "log line 2\n" + "FINE: log line 3\n"; @@ -33,7 +33,7 @@ public class LogRecorderTest { private final LogRecorder logRecorder = new LogRecorder(testLogger); @Test - public void shouldAggregateLogs() { + void shouldAggregateLogs() { for (String logLine : LOG_LINES.split("\n")) { logRecorder.record(logLine); } @@ -50,7 +50,7 @@ public void shouldAggregateLogs() { } @Test - public void shouldBeEmptyAfterFlushCall() { + void shouldBeEmptyAfterFlushCall() { for (String logLine : LOG_LINES.split("\n")) { logRecorder.record(logLine); } From d97231d3313cad6c071ac6403258447cce02445d Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:01:54 -0400 Subject: [PATCH 05/43] change tests --- .../com/google/cloud/testing/VersionTest.java | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/VersionTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/VersionTest.java index fe65026b60..2d5e69fe46 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/VersionTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/VersionTest.java @@ -16,18 +16,18 @@ package com.google.cloud.testing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -public class VersionTest { +class VersionTest { @Test - public void testFromString() { + void testFromString() { Version version = Version.fromString("2016.01.13"); assertEquals(2016, version.getMajor()); assertEquals(1, version.getMinor()); @@ -39,57 +39,57 @@ public void testFromString() { } @Test - public void testFromStringWithAlphas() { + void testFromStringWithAlphas() { try { Version.fromString("2016.01.hello"); - Assert.fail(); + Assertions.fail(); } catch (IllegalArgumentException ex) { assertNotNull(ex.getMessage()); } } @Test - public void testFromStringMissingPatch() { + void testFromStringMissingPatch() { try { Version.fromString("2016.01"); - Assert.fail(); + Assertions.fail(); } catch (IllegalArgumentException ex) { assertNotNull(ex.getMessage()); } } @Test - public void testFromStringMissingMinor() { + void testFromStringMissingMinor() { try { Version.fromString("2016"); - Assert.fail(); + Assertions.fail(); } catch (IllegalArgumentException ex) { assertNotNull(ex.getMessage()); } } @Test - public void testFromStringEmpty() { + void testFromStringEmpty() { try { Version.fromString(""); - Assert.fail(); + Assertions.fail(); } catch (IllegalArgumentException ex) { assertNotNull(ex.getMessage()); } } @Test - public void testFromStringNull() { + void testFromStringNull() { try { Version.fromString(null); - Assert.fail(); + Assertions.fail(); } catch (NullPointerException ex) { assertNull(ex.getMessage()); } } @Test - public void testCompare() { + void testCompare() { Version version = Version.fromString("2016.01.13"); Version sameVersion = Version.fromString("2016.01.13"); Version olderVersion = Version.fromString("2015.12.01"); From f4f37b62d0f138a58b34152c28cba38d7a0795b3 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:03:03 -0400 Subject: [PATCH 06/43] change tests --- .../java/com/google/cloud/AsyncPageImplTest.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/AsyncPageImplTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/AsyncPageImplTest.java index 241793b3be..92327a0b1c 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/AsyncPageImplTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/AsyncPageImplTest.java @@ -16,16 +16,16 @@ package com.google.cloud; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; import com.google.api.gax.paging.AsyncPage; import com.google.common.collect.ImmutableList; import java.util.concurrent.ExecutionException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class AsyncPageImplTest { +class AsyncPageImplTest { private static final ImmutableList VALUES1 = ImmutableList.of("1", "2"); private static final ImmutableList VALUES2 = ImmutableList.of("3", "4"); @@ -51,7 +51,7 @@ public ApiFuture> getNextPage() { } @Test - public void testPage() { + void testPage() { final AsyncPageImpl nextResult = new AsyncPageImpl<>(null, "c", VALUES2); AsyncPageImpl.NextPageFetcher fetcher = new TestPageFetcher(nextResult); AsyncPageImpl result = new AsyncPageImpl<>(fetcher, "c", VALUES1); @@ -61,7 +61,7 @@ public void testPage() { } @Test - public void testPageAsync() throws ExecutionException, InterruptedException { + void testPageAsync() throws ExecutionException, InterruptedException { final AsyncPageImpl nextResult = new AsyncPageImpl<>(null, "c", VALUES2); AsyncPageImpl.NextPageFetcher fetcher = new TestPageFetcher(nextResult); AsyncPageImpl result = new AsyncPageImpl<>(fetcher, "c", VALUES1); @@ -71,7 +71,7 @@ public void testPageAsync() throws ExecutionException, InterruptedException { } @Test - public void testIterateAll() { + void testIterateAll() { final AsyncPageImpl nextResult2 = new AsyncPageImpl<>(null, "c3", VALUES3); AsyncPageImpl.NextPageFetcher fetcher2 = new TestPageFetcher(nextResult2); final AsyncPageImpl nextResult1 = new AsyncPageImpl<>(fetcher2, "c2", VALUES2); @@ -81,7 +81,7 @@ public void testIterateAll() { } @Test - public void testAsyncPageAndIterateAll() throws ExecutionException, InterruptedException { + void testAsyncPageAndIterateAll() throws ExecutionException, InterruptedException { final AsyncPageImpl nextResult2 = new AsyncPageImpl<>(null, "c3", VALUES3); AsyncPageImpl.NextPageFetcher fetcher2 = new TestPageFetcher(nextResult2); final AsyncPageImpl nextResult1 = new AsyncPageImpl<>(fetcher2, "c2", VALUES2); From db78162daba9de5fd8b149665255d51e98d14a49 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:05:48 -0400 Subject: [PATCH 07/43] change tests --- .../java/com/google/cloud/BaseSerializationTest.java | 12 ++++++------ .../java/com/google/cloud/SerializationTest.java | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java index 5dcd1726bb..036998f767 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java @@ -17,8 +17,8 @@ package com.google.cloud; import static com.google.common.base.MoreObjects.firstNonNull; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -26,7 +26,7 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Base class for serialization tests. To use this class in your tests override the {@code @@ -35,7 +35,7 @@ * for proper serialization. Both methods can return {@code null} if no such object needs to be * tested. */ -public abstract class BaseSerializationTest { +abstract class BaseSerializationTest { /** Returns all objects for which correct serialization must be tested. */ protected abstract Serializable[] serializableObjects(); @@ -44,7 +44,7 @@ public abstract class BaseSerializationTest { protected abstract Restorable[] restorableObjects(); @Test - public void testSerializableObjects() throws Exception { + void testSerializableObjects() throws Exception { for (Serializable obj : firstNonNull(serializableObjects(), new Serializable[0])) { Object copy = serializeAndDeserialize(obj); assertEquals(obj, obj); @@ -57,7 +57,7 @@ public void testSerializableObjects() throws Exception { } @Test - public void testRestorableObjects() throws Exception { + void testRestorableObjects() throws Exception { for (Restorable restorable : firstNonNull(restorableObjects(), new Restorable[0])) { RestorableState state = restorable.capture(); RestorableState deserializedState = serializeAndDeserialize(state); diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java index 6c35c665b5..20e164d417 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java @@ -25,7 +25,7 @@ import java.io.Serializable; import org.threeten.bp.Duration; -public class SerializationTest extends BaseSerializationTest { +class SerializationTest extends BaseSerializationTest { private static final BaseServiceException BASE_SERVICE_EXCEPTION = new BaseServiceException(ExceptionData.from(42, "message", "reason", false)); From d84ffa1c2476dd7499e701a2dea07911af5cf5d1 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:07:13 -0400 Subject: [PATCH 08/43] change tests --- .../google/cloud/BaseServiceExceptionTest.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseServiceExceptionTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseServiceExceptionTest.java index 4bc5993f7f..cfa06a6586 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseServiceExceptionTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseServiceExceptionTest.java @@ -22,18 +22,18 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.cloud.BaseServiceException.ExceptionData; import com.google.common.collect.ImmutableSet; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link BaseServiceException}. */ -public class BaseServiceExceptionTest { +class BaseServiceExceptionTest { private static final int CODE = 1; private static final int CODE_NO_REASON = 2; @@ -64,7 +64,7 @@ public CustomServiceException(int code, String message, String reason, boolean i } @Test - public void testBaseServiceException() { + void testBaseServiceException() { BaseServiceException serviceException = new BaseServiceException(ExceptionData.from(CODE, MESSAGE, REASON, NOT_RETRYABLE)); assertEquals(CODE, serviceException.getCode()); @@ -121,7 +121,7 @@ public void testBaseServiceException() { } @Test - public void testTranslateAndThrow() throws Exception { + void testTranslateAndThrow() throws Exception { BaseServiceException cause = new BaseServiceException(ExceptionData.from(CODE, MESSAGE, REASON, NOT_RETRYABLE)); RetryHelper.RetryHelperException exceptionMock = @@ -141,7 +141,7 @@ public void testTranslateAndThrow() throws Exception { @Test @SuppressWarnings("TruthSelfEquals") - public void testError_Equal() { + void testError_Equal() { BaseServiceException.Error error = new BaseServiceException.Error(0, "reason", true); assertThat(error).isEqualTo(error); assertThat(error.hashCode()).isEqualTo(error.hashCode()); From 849ea75d4aede3a7769a40974bec19804fdf64bb Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:11:11 -0400 Subject: [PATCH 09/43] change tests --- .../google/cloud/BaseWriteChannelTest.java | 39 ++++++++++--------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseWriteChannelTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseWriteChannelTest.java index 65743a347a..0bc83b1eb1 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseWriteChannelTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseWriteChannelTest.java @@ -17,11 +17,12 @@ package com.google.cloud; import static com.google.common.truth.Truth.assertThat; -import static junit.framework.TestCase.assertFalse; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import com.google.cloud.spi.ServiceRpcFactory; import java.io.IOException; @@ -30,10 +31,10 @@ import java.nio.channels.ClosedChannelException; import java.util.Arrays; import java.util.Random; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class BaseWriteChannelTest { +class BaseWriteChannelTest { private abstract static class CustomService implements Service {} @@ -58,8 +59,8 @@ protected CustomServiceOptions( private static final Random RANDOM = new Random(); private static BaseWriteChannel channel; - @Before - public void setUp() { + @BeforeEach + void setUp() { channel = new BaseWriteChannel(null, ENTITY, UPLOAD_ID) { @Override @@ -78,8 +79,8 @@ protected BaseState.Builder stateBuilder() { } @Test - public void testConstructor() { - assertEquals(null, channel.getOptions()); + void testConstructor() { + assertNull(channel.getOptions()); assertEquals(ENTITY, channel.getEntity()); assertEquals(0, channel.getPosition()); assertEquals(UPLOAD_ID, channel.getUploadId()); @@ -90,20 +91,22 @@ public void testConstructor() { } @Test - public void testClose() throws IOException { + void testClose() throws IOException { channel.close(); assertFalse(channel.isOpen()); assertNull(channel.getBuffer()); } - @Test(expected = ClosedChannelException.class) + @Test public void testValidateOpen() throws IOException { channel.close(); - channel.write(ByteBuffer.allocate(42)); + assertThrows( + ClosedChannelException.class, + () -> channel.write(ByteBuffer.allocate(42))); } @Test - public void testChunkSize() { + void testChunkSize() { channel.setChunkSize(42); assertThat(channel.getChunkSize() >= MIN_CHUNK_SIZE).isTrue(); assertThat(channel.getChunkSize() % MIN_CHUNK_SIZE).isEqualTo(0); @@ -118,7 +121,7 @@ public void testChunkSize() { } @Test - public void testWrite() throws IOException { + void testWrite() throws IOException { channel.write(ByteBuffer.wrap(CONTENT)); assertEquals(CONTENT.length, channel.getLimit()); assertEquals(DEFAULT_CHUNK_SIZE, channel.getBuffer().length); @@ -126,7 +129,7 @@ public void testWrite() throws IOException { } @Test - public void testWriteAndFlush() throws IOException { + void testWriteAndFlush() throws IOException { ByteBuffer content = randomBuffer(DEFAULT_CHUNK_SIZE + 1); channel.write(content); assertEquals(DEFAULT_CHUNK_SIZE, channel.getPosition()); From 982705287d26f6c6f524c8fd4ce7834eb1da8eb2 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:12:21 -0400 Subject: [PATCH 10/43] change tests --- .../com/google/cloud/BatchResultTest.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/BatchResultTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/BatchResultTest.java index 001bba9834..e8f6ae2da5 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/BatchResultTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/BatchResultTest.java @@ -16,27 +16,27 @@ package com.google.cloud; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.cloud.BaseServiceException.ExceptionData; import org.easymock.EasyMock; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class BatchResultTest { +class BatchResultTest { private BatchResult result; - @Before + @BeforeEach public void setUp() { result = new BatchResult() {}; } @Test - public void testSuccess() { + void testSuccess() { assertFalse(result.completed()); try { result.get(); @@ -51,7 +51,7 @@ public void testSuccess() { } @Test - public void testError() { + void testError() { assertFalse(result.completed()); try { result.get(); @@ -77,7 +77,7 @@ public void testError() { } @Test - public void testNotifyError() { + void testNotifyError() { final BaseServiceException ex = new BaseServiceException(ExceptionData.from(0, "message", "reason", false)); assertFalse(result.completed()); @@ -97,7 +97,7 @@ public void testNotifyError() { } @Test - public void testNotifySuccess() { + void testNotifySuccess() { assertFalse(result.completed()); BatchResult.Callback callback = EasyMock.createStrictMock(BatchResult.Callback.class); From 421d1ea4b80b65e1064d999420ab17890aff01ca Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:13:51 -0400 Subject: [PATCH 11/43] change tests --- .../java/com/google/cloud/ByteArrayTest.java | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/ByteArrayTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/ByteArrayTest.java index 42873f8643..67237b5371 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/ByteArrayTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/ByteArrayTest.java @@ -16,8 +16,8 @@ package com.google.cloud; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.common.io.ByteStreams; import com.google.protobuf.ByteString; @@ -26,10 +26,10 @@ import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -public class ByteArrayTest { +class ByteArrayTest { private static final String STRING_CONTENT = "Hello, ByteArray!"; private static final byte[] BYTES_CONTENT = STRING_CONTENT.getBytes(StandardCharsets.UTF_8); @@ -42,14 +42,14 @@ public class ByteArrayTest { private static ByteArray streamArray; - @BeforeClass - public static void beforeClass() throws IOException { + @BeforeAll + static void beforeClass() throws IOException { streamArray = ByteArray.copyFrom(STREAM_CONTENT); BYTE_BUFFER_CONTENT.flip(); } @Test - public void testCopyFromString() throws IOException { + void testCopyFromString() throws IOException { assertEquals(STRING_CONTENT, STRING_ARRAY.toStringUtf8()); assertArrayEquals(BYTES_CONTENT, STRING_ARRAY.toByteArray()); assertEquals(BYTE_BUFFER_CONTENT.asReadOnlyBuffer(), STRING_ARRAY.asReadOnlyByteBuffer()); @@ -57,7 +57,7 @@ public void testCopyFromString() throws IOException { } @Test - public void testCopyFromByteArray() throws IOException { + void testCopyFromByteArray() throws IOException { assertEquals(STRING_CONTENT, BYTES_ARRAY.toStringUtf8()); assertArrayEquals(BYTES_CONTENT, BYTES_ARRAY.toByteArray()); assertEquals(BYTE_BUFFER_CONTENT.asReadOnlyBuffer(), BYTES_ARRAY.asReadOnlyByteBuffer()); @@ -65,7 +65,7 @@ public void testCopyFromByteArray() throws IOException { } @Test - public void testCopyFromByteBuffer() throws IOException { + void testCopyFromByteBuffer() throws IOException { assertEquals(STRING_CONTENT, BYTE_BUFFER_ARRAY.toStringUtf8()); assertArrayEquals(BYTES_CONTENT, BYTE_BUFFER_ARRAY.toByteArray()); assertEquals(BYTE_BUFFER_CONTENT.asReadOnlyBuffer(), BYTE_BUFFER_ARRAY.asReadOnlyByteBuffer()); @@ -73,7 +73,7 @@ public void testCopyFromByteBuffer() throws IOException { } @Test - public void testCopyFromStream() throws IOException { + void testCopyFromStream() throws IOException { assertEquals(STRING_CONTENT, streamArray.toStringUtf8()); assertArrayEquals(BYTES_CONTENT, streamArray.toByteArray()); assertEquals(BYTE_BUFFER_CONTENT.asReadOnlyBuffer(), streamArray.asReadOnlyByteBuffer()); @@ -81,32 +81,32 @@ public void testCopyFromStream() throws IOException { } @Test - public void testLength() { + void testLength() { assertEquals(BYTES_CONTENT.length, ARRAY.length()); } @Test - public void testToStringUtf8() { + void testToStringUtf8() { assertEquals(STRING_CONTENT, ARRAY.toStringUtf8()); } @Test - public void testToByteArray() { + void testToByteArray() { assertArrayEquals(BYTES_CONTENT, ARRAY.toByteArray()); } @Test - public void testAsReadOnlyByteBuffer() { + void testAsReadOnlyByteBuffer() { assertEquals(BYTE_BUFFER_CONTENT.asReadOnlyBuffer(), ARRAY.asReadOnlyByteBuffer()); } @Test - public void testAsInputStream() throws IOException { + void testAsInputStream() throws IOException { assertArrayEquals(BYTES_CONTENT, ByteStreams.toByteArray(ARRAY.asInputStream())); } @Test - public void testHashCode() { + void testHashCode() { assertEquals(STRING_ARRAY.hashCode(), BYTES_ARRAY.hashCode()); assertEquals(BYTES_ARRAY.hashCode(), BYTE_BUFFER_ARRAY.hashCode()); assertEquals(BYTE_BUFFER_ARRAY.hashCode(), streamArray.hashCode()); From c04aa05b7801790ed27e4446c55934da52eaaf59 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:14:44 -0400 Subject: [PATCH 12/43] change tests --- .../src/test/java/com/google/cloud/ConditionTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/ConditionTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/ConditionTest.java index 67e0e6c2b5..19abe3eba3 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/ConditionTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/ConditionTest.java @@ -18,12 +18,12 @@ import static com.google.common.truth.Truth.assertThat; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public final class ConditionTest { +final class ConditionTest { @Test - public void title_nullable() { + void title_nullable() { Condition condition = Condition.newBuilder().setTitle(null).setDescription("desc").setExpression("expr").build(); @@ -31,7 +31,7 @@ public void title_nullable() { } @Test - public void description_nullable() { + void description_nullable() { Condition condition = Condition.newBuilder().setTitle("title").setDescription(null).setExpression("expr").build(); From 5a5299140f28ead389cd1a832005434e0e84cc75 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:17:10 -0400 Subject: [PATCH 13/43] change tests --- .../test/java/com/google/cloud/DateTest.java | 25 ++++++++----------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/DateTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/DateTest.java index d95efaf094..6b2a6e4df5 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/DateTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/DateTest.java @@ -18,23 +18,20 @@ import static com.google.common.testing.SerializableTester.reserializeAndAssert; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import com.google.common.testing.EqualsTester; import java.text.ParseException; import java.text.SimpleDateFormat; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Unit tests for {@link Date}. */ -@RunWith(JUnit4.class) -public class DateTest { +class DateTest { private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); @Test - public void parseDate() { + void parseDate() { verifyDate("2016-09-18", 2016, 9, 18); verifyDate("2000-01-01", 2000, 1, 1); verifyDate("9999-12-31", 9999, 12, 31); @@ -53,7 +50,7 @@ private void verifyDate(String input, int year, int month, int day) { } @Test - public void parseInvalidDates() { + void parseInvalidDates() { parseInvalidDate("2016/09/18"); parseInvalidDate("2016 09 18"); parseInvalidDate("2016-9-18"); @@ -112,7 +109,7 @@ private void parseInvalidDay(String input) { } @Test - public void testToString() { + void testToString() { Date date = Date.fromYearMonthDay(10, 9, 5); assertThat(date.toString()).isEqualTo("0010-09-05"); date = Date.fromYearMonthDay(2016, 12, 31); @@ -122,7 +119,7 @@ public void testToString() { } @Test - public void equalAndHashCode() { + void equalAndHashCode() { Date d1 = Date.fromYearMonthDay(2016, 9, 18); Date d2 = Date.fromYearMonthDay(2016, 9, 18); Date d3 = Date.fromYearMonthDay(2016, 9, 19); @@ -130,7 +127,7 @@ public void equalAndHashCode() { } @Test - public void validOrdering() { + void validOrdering() { Date d1 = Date.fromYearMonthDay(2016, 9, 18); Date d2 = Date.fromYearMonthDay(2016, 9, 19); Date d3 = Date.fromYearMonthDay(2016, 9, 20); @@ -140,12 +137,12 @@ public void validOrdering() { } @Test - public void serialization() { + void serialization() { reserializeAndAssert(Date.fromYearMonthDay(2017, 4, 20)); } @Test - public void testToJavaUtilDate() throws ParseException { + void testToJavaUtilDate() throws ParseException { Date gcDate = Date.parseDate("2016-09-18"); java.util.Date juDate1 = SIMPLE_DATE_FORMAT.parse("2016-09-18"); java.util.Date juDate2 = Date.toJavaUtilDate(gcDate); @@ -153,7 +150,7 @@ public void testToJavaUtilDate() throws ParseException { } @Test - public void testFromJavaUtilDate() throws ParseException { + void testFromJavaUtilDate() throws ParseException { java.util.Date juDate = SIMPLE_DATE_FORMAT.parse("2016-09-18"); Date gcDate = Date.fromJavaUtilDate(juDate); assertThat(gcDate.getYear()).isEqualTo(2016); From 7bb27e3b5545d839e76edfc7c09d482cd045d105 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:20:53 -0400 Subject: [PATCH 14/43] change tests --- .../google/cloud/ExceptionHandlerTest.java | 31 +++++++++++-------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/ExceptionHandlerTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/ExceptionHandlerTest.java index 50e0583c89..1cc34425d7 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/ExceptionHandlerTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/ExceptionHandlerTest.java @@ -16,9 +16,10 @@ package com.google.cloud; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.cloud.ExceptionHandler.Interceptor; import com.google.cloud.ExceptionHandler.Interceptor.RetryResult; @@ -27,13 +28,13 @@ import java.nio.channels.ClosedByInterruptException; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicReference; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link ExceptionHandler}. */ -public class ExceptionHandlerTest { +class ExceptionHandlerTest { @Test - public void testVerifyCaller() { + void testVerifyCaller() { class A implements Callable { @Override public Object call() throws IOException, InterruptedException { @@ -106,7 +107,7 @@ private static void assertInvalidCallable(Callable callable, ExceptionHan } @Test - public void testShouldTry() { + void testShouldTry() { ExceptionHandler handler = ExceptionHandler.newBuilder().retryOn(IOException.class).build(); assertTrue(handler.shouldRetry(new IOException(), null)); assertTrue(handler.shouldRetry(new ClosedByInterruptException(), null)); @@ -166,8 +167,8 @@ public RetryResult beforeEval(Exception exception) { assertFalse(handler.shouldRetry(new NullPointerException(), null)); } - @Test(expected = NullPointerException.class) - public void testNullRetryResultFromBeforeEval() { + @Test + void testNullRetryResultFromBeforeEval() { @SuppressWarnings("serial") Interceptor interceptor = new Interceptor() { @@ -184,11 +185,13 @@ public RetryResult afterEval(Exception exception, RetryResult retryResult) { }; ExceptionHandler handler = ExceptionHandler.newBuilder().addInterceptors(interceptor).build(); - handler.shouldRetry(new Exception(), null); + assertThrows( + NullPointerException.class, + () -> handler.shouldRetry(new Exception(), null)); } - @Test(expected = NullPointerException.class) - public void testNullRetryResultFromAfterEval() { + @Test + void testNullRetryResultFromAfterEval() { @SuppressWarnings("serial") Interceptor interceptor = new Interceptor() { @@ -205,6 +208,8 @@ public RetryResult afterEval(Exception exception, RetryResult retryResult) { }; ExceptionHandler handler = ExceptionHandler.newBuilder().addInterceptors(interceptor).build(); - handler.shouldRetry(new Exception(), null); + assertThrows( + NullPointerException.class, + () -> handler.shouldRetry(new Exception(), null)); } } From cadee13c3a33bd4be53ddeeaea5190da821cddd0 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:21:55 -0400 Subject: [PATCH 15/43] change tests --- .../google/cloud/FieldSelectorHelperTest.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/FieldSelectorHelperTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/FieldSelectorHelperTest.java index 7b94ff5294..1a617e9290 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/FieldSelectorHelperTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/FieldSelectorHelperTest.java @@ -16,15 +16,15 @@ package com.google.cloud; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.cloud.FieldSelector.Helper; import com.google.common.collect.ImmutableList; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class FieldSelectorHelperTest { +class FieldSelectorHelperTest { private static final FieldSelector FIELD1 = new FieldSelector() { @@ -52,7 +52,7 @@ public String getSelector() { private static final String CONTAINER = "container"; @Test - public void testSelector() { + void testSelector() { String selector = Helper.selector(REQUIRED_FIELDS, FIELD3); assertTrue(selector.contains("field1")); assertTrue(selector.contains("field2")); @@ -61,7 +61,7 @@ public void testSelector() { } @Test - public void testListSelector() { + void testListSelector() { String selector = Helper.listSelector(CONTAINER, REQUIRED_FIELDS, FIELD3); assertTrue(selector.startsWith("nextPageToken,container(")); assertTrue(selector.contains("field1")); @@ -72,7 +72,7 @@ public void testListSelector() { } @Test - public void testListSelectorWithExtraFields() { + void testListSelectorWithExtraFields() { String selector = Helper.listSelector(CONTAINER, REQUIRED_FIELDS, new FieldSelector[] {FIELD3}, "field4"); assertTrue(selector.startsWith("nextPageToken,container(")); @@ -85,7 +85,7 @@ public void testListSelectorWithExtraFields() { } @Test - public void testListSelectorWithFirstLevelFields() { + void testListSelectorWithFirstLevelFields() { String selector = Helper.listSelector( FIRST_LEVEL_FIELDS, CONTAINER, REQUIRED_FIELDS, new FieldSelector[] {FIELD3}, "field4"); From 5e6e1f8ff3e678f937e0ee83d09494ba13e9a30c Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:25:26 -0400 Subject: [PATCH 16/43] change tests --- .../java/com/google/cloud/IdentityTest.java | 81 ++++++++++--------- 1 file changed, 41 insertions(+), 40 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/IdentityTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/IdentityTest.java index 8f8abb170c..5f4de7fef3 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/IdentityTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/IdentityTest.java @@ -16,12 +16,13 @@ package com.google.cloud; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class IdentityTest { +class IdentityTest { private static final Identity ALL_USERS = Identity.allUsers(); private static final Identity ALL_AUTH_USERS = Identity.allAuthenticatedUsers(); @@ -35,96 +36,96 @@ public class IdentityTest { private static final Identity PROJECT_VIEWER = Identity.projectViewer("my-sample-project"); @Test - public void testAllUsers() { + void testAllUsers() { assertEquals(Identity.Type.ALL_USERS, ALL_USERS.getType()); assertNull(ALL_USERS.getValue()); } @Test - public void testAllAuthenticatedUsers() { + void testAllAuthenticatedUsers() { assertEquals(Identity.Type.ALL_AUTHENTICATED_USERS, ALL_AUTH_USERS.getType()); assertNull(ALL_AUTH_USERS.getValue()); } @Test - public void testUser() { + void testUser() { assertEquals(Identity.Type.USER, USER.getType()); assertEquals("abc@gmail.com", USER.getValue()); } - @Test(expected = NullPointerException.class) - public void testUserNullEmail() { - Identity.user(null); + @Test + void testUserNullEmail() { + assertThrows(NullPointerException.class, () -> Identity.user(null)); } @Test - public void testServiceAccount() { + void testServiceAccount() { assertEquals(Identity.Type.SERVICE_ACCOUNT, SERVICE_ACCOUNT.getType()); assertEquals("service-account@gmail.com", SERVICE_ACCOUNT.getValue()); } - @Test(expected = NullPointerException.class) - public void testServiceAccountNullEmail() { - Identity.serviceAccount(null); + @Test + void testServiceAccountNullEmail() { + assertThrows(NullPointerException.class, () -> Identity.serviceAccount(null)); } @Test - public void testGroup() { + void testGroup() { assertEquals(Identity.Type.GROUP, GROUP.getType()); assertEquals("group@gmail.com", GROUP.getValue()); } - @Test(expected = NullPointerException.class) - public void testGroupNullEmail() { - Identity.group(null); + @Test + void testGroupNullEmail() { + assertThrows(NullPointerException.class, () -> Identity.group(null)); } @Test - public void testDomain() { + void testDomain() { assertEquals(Identity.Type.DOMAIN, DOMAIN.getType()); assertEquals("google.com", DOMAIN.getValue()); } - @Test(expected = NullPointerException.class) - public void testDomainNullId() { - Identity.domain(null); + @Test + void testDomainNullId() { + assertThrows(NullPointerException.class, () -> Identity.domain(null)); } @Test - public void testProjectOwner() { + void testProjectOwner() { assertEquals(Identity.Type.PROJECT_OWNER, PROJECT_OWNER.getType()); assertEquals("my-sample-project", PROJECT_OWNER.getValue()); } - @Test(expected = NullPointerException.class) - public void testProjectOwnerNullId() { - Identity.projectOwner(null); + @Test + void testProjectOwnerNullId() { + assertThrows(NullPointerException.class, () -> Identity.projectOwner(null)); } @Test - public void testProjectEditor() { + void testProjectEditor() { assertEquals(Identity.Type.PROJECT_EDITOR, PROJECT_EDITOR.getType()); assertEquals("my-sample-project", PROJECT_EDITOR.getValue()); } - @Test(expected = NullPointerException.class) - public void testProjectEditorNullId() { - Identity.projectEditor(null); + @Test + void testProjectEditorNullId() { + assertThrows(NullPointerException.class, () -> Identity.projectEditor(null)); } @Test - public void testProjectViewer() { + void testProjectViewer() { assertEquals(Identity.Type.PROJECT_VIEWER, PROJECT_VIEWER.getType()); assertEquals("my-sample-project", PROJECT_VIEWER.getValue()); } - @Test(expected = NullPointerException.class) - public void testProjectViewerNullId() { - Identity.projectViewer(null); + @Test + void testProjectViewerNullId() { + assertThrows(NullPointerException.class, () -> Identity.projectViewer(null)); } @Test - public void testIdentityToAndFromPb() { + void testIdentityToAndFromPb() { compareIdentities(ALL_USERS, Identity.valueOf(ALL_USERS.strValue())); compareIdentities(ALL_AUTH_USERS, Identity.valueOf(ALL_AUTH_USERS.strValue())); compareIdentities(USER, Identity.valueOf(USER.strValue())); @@ -136,18 +137,18 @@ public void testIdentityToAndFromPb() { compareIdentities(PROJECT_VIEWER, Identity.valueOf(PROJECT_VIEWER.strValue())); } - @Test(expected = IllegalArgumentException.class) - public void testValueOfEmpty() { - Identity.valueOf(""); + @Test + void testValueOfEmpty() { + assertThrows(IllegalArgumentException.class, () -> Identity.valueOf("")); } @Test - public void testUnrecognizedToString() { + void testUnrecognizedToString() { assertEquals("a:b", Identity.valueOf("a:b").strValue()); } @Test - public void testValueOfThreePart() { + void testValueOfThreePart() { Identity identity = Identity.valueOf("a:b:c"); assertEquals("A", identity.getType().name()); assertEquals("b:c", identity.getValue()); From 93f62392fa5110683e7f9125b45a9fb033488b29 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:28:12 -0400 Subject: [PATCH 17/43] change tests --- .../cloud/MonitoredResourceDescriptorTest.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceDescriptorTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceDescriptorTest.java index b29896af48..042ba30feb 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceDescriptorTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceDescriptorTest.java @@ -16,16 +16,16 @@ package com.google.cloud; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import com.google.cloud.MonitoredResourceDescriptor.LabelDescriptor; import com.google.cloud.MonitoredResourceDescriptor.LabelDescriptor.ValueType; import com.google.common.collect.ImmutableList; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class MonitoredResourceDescriptorTest { +class MonitoredResourceDescriptorTest { private static final LabelDescriptor BOOLEAN_LABEL = new LabelDescriptor("booleanKey", ValueType.BOOL, "Boolean label"); @@ -50,7 +50,7 @@ public class MonitoredResourceDescriptorTest { .build(); @Test - public void testLabelDescriptor() { + void testLabelDescriptor() { assertEquals("booleanKey", BOOLEAN_LABEL.getKey()); assertEquals(ValueType.BOOL, BOOLEAN_LABEL.getValueType()); assertEquals("Boolean label", BOOLEAN_LABEL.getDescription()); @@ -66,7 +66,7 @@ public void testLabelDescriptor() { } @Test - public void testBuilder() { + void testBuilder() { assertEquals(TYPE, RESOURCE_DESCRIPTOR.getType()); assertEquals(NAME, RESOURCE_DESCRIPTOR.getName()); assertEquals(DISPLAY_NAME, RESOURCE_DESCRIPTOR.getDisplayName()); @@ -82,7 +82,7 @@ public void testBuilder() { } @Test - public void testToAndFromPbLabelDescriptor() { + void testToAndFromPbLabelDescriptor() { compareLabelDescriptor(BOOLEAN_LABEL, LabelDescriptor.fromPb(BOOLEAN_LABEL.toPb())); compareLabelDescriptor(STRING_LABEL, LabelDescriptor.fromPb(STRING_LABEL.toPb())); compareLabelDescriptor(INT_LABEL, LabelDescriptor.fromPb(INT_LABEL.toPb())); @@ -91,7 +91,7 @@ public void testToAndFromPbLabelDescriptor() { } @Test - public void testToAndFromPb() { + void testToAndFromPb() { compareResourceDescriptor( RESOURCE_DESCRIPTOR, MonitoredResourceDescriptor.fromPb(RESOURCE_DESCRIPTOR.toPb())); MonitoredResourceDescriptor resourceDescriptor = From d2f28b5626b12d1cdeb7767b964ad728e2809fd1 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:29:58 -0400 Subject: [PATCH 18/43] change tests --- .../com/google/cloud/MonitoredResourceTest.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceTest.java index 6054a7aa34..32fce0154d 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceTest.java @@ -16,13 +16,13 @@ package com.google.cloud; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.common.collect.ImmutableMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class MonitoredResourceTest { +class MonitoredResourceTest { private static final String TYPE = "cloudsql_database"; private static final Map LABELS = @@ -31,7 +31,7 @@ public class MonitoredResourceTest { MonitoredResource.newBuilder(TYPE).setLabels(LABELS).build(); @Test - public void testBuilder() { + void testBuilder() { assertEquals(TYPE, MONITORED_RESOURCE.getType()); assertEquals(LABELS, MONITORED_RESOURCE.getLabels()); MonitoredResource monitoredResource = @@ -54,7 +54,7 @@ public void testBuilder() { } @Test - public void testToBuilder() { + void testToBuilder() { compareMonitoredResource(MONITORED_RESOURCE, MONITORED_RESOURCE.toBuilder().build()); MonitoredResource monitoredResource = MONITORED_RESOURCE.toBuilder().setType("global").clearLabels().build(); @@ -71,7 +71,7 @@ public void testToBuilder() { } @Test - public void testOf() { + void testOf() { MonitoredResource monitoredResource = MonitoredResource.of(TYPE, LABELS); assertEquals(TYPE, monitoredResource.getType()); assertEquals(LABELS, monitoredResource.getLabels()); @@ -79,7 +79,7 @@ public void testOf() { } @Test - public void testToAndFromPb() { + void testToAndFromPb() { compareMonitoredResource( MONITORED_RESOURCE, MonitoredResource.fromPb(MONITORED_RESOURCE.toPb())); MonitoredResource monitoredResource = From c5ede6ff90d87358ac1a0fa4d22d488d2ede74ea Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:30:33 -0400 Subject: [PATCH 19/43] change tests --- .../src/test/java/com/google/cloud/PageImplTest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/PageImplTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/PageImplTest.java index 5e6a6782d6..db11d66951 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/PageImplTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/PageImplTest.java @@ -16,13 +16,13 @@ package com.google.cloud; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.api.gax.paging.Page; import com.google.common.collect.ImmutableList; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class PageImplTest { +class PageImplTest { private static final ImmutableList VALUES = ImmutableList.of("1", "2"); private static final ImmutableList NEXT_VALUES = ImmutableList.of("3", "4"); @@ -45,7 +45,7 @@ public Page getNextPage() { } @Test - public void testPage() { + void testPage() { final PageImpl nextResult = new PageImpl<>(null, "c", NEXT_VALUES); PageImpl.NextPageFetcher fetcher = new TestPageFetcher(nextResult); PageImpl result = new PageImpl<>(fetcher, "c", VALUES); @@ -55,7 +55,7 @@ public void testPage() { } @Test - public void testIterateAll() { + void testIterateAll() { final PageImpl nextResult = new PageImpl<>(null, "c", NEXT_VALUES); PageImpl.NextPageFetcher fetcher = new TestPageFetcher(nextResult); PageImpl result = new PageImpl<>(fetcher, "c", VALUES); From 48f681dae6d1f7c40238c7e8218e4a4d2b55ea4c Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:31:44 -0400 Subject: [PATCH 20/43] change tests --- .../java/com/google/cloud/PolicyTest.java | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/PolicyTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/PolicyTest.java index 98695c2a4c..e7d70ce385 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/PolicyTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/PolicyTest.java @@ -16,12 +16,12 @@ package com.google.cloud; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.cloud.Policy.DefaultMarshaller; import com.google.common.collect.ImmutableMap; @@ -30,9 +30,9 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class PolicyTest { +class PolicyTest { private static final Identity ALL_USERS = Identity.allUsers(); private static final Identity ALL_AUTH_USERS = Identity.allAuthenticatedUsers(); @@ -63,9 +63,9 @@ public class PolicyTest { .build(); @Test - public void testBuilder() { + void testBuilder() { assertEquals(BINDINGS, SIMPLE_POLICY.getBindings()); - assertEquals(null, SIMPLE_POLICY.getEtag()); + assertNull(SIMPLE_POLICY.getEtag()); assertEquals(0, SIMPLE_POLICY.getVersion()); assertEquals(BINDINGS, FULL_POLICY.getBindings()); assertEquals("etag", FULL_POLICY.getEtag()); @@ -105,7 +105,7 @@ public void testBuilder() { } @Test - public void testPolicyOrderShouldNotMatter() { + void testPolicyOrderShouldNotMatter() { Role role1 = Role.of("role1"); Identity identity1 = Identity.user("user1@example.com"); Role role2 = Role.of("role2"); @@ -118,7 +118,7 @@ public void testPolicyOrderShouldNotMatter() { } @Test - public void testPolicyMultipleAddIdentitiesShouldNotMatter() { + void testPolicyMultipleAddIdentitiesShouldNotMatter() { Role role1 = Role.of("role1"); Identity identity1 = Identity.user("user1@example.com"); Role role2 = Role.of("role2"); @@ -135,7 +135,7 @@ public void testPolicyMultipleAddIdentitiesShouldNotMatter() { } @Test - public void testIllegalPolicies() { + void testIllegalPolicies() { try { Policy.newBuilder().addIdentity(null, USER); fail("Null role should cause exception."); @@ -181,7 +181,7 @@ public void testIllegalPolicies() { } @Test - public void testEqualsHashCode() { + void testEqualsHashCode() { assertNotNull(FULL_POLICY); Policy emptyPolicy = Policy.newBuilder().build(); Policy anotherPolicy = Policy.newBuilder().build(); @@ -195,25 +195,25 @@ public void testEqualsHashCode() { } @Test - public void testBindings() { + void testBindings() { assertTrue(Policy.newBuilder().build().getBindings().isEmpty()); assertEquals(BINDINGS, SIMPLE_POLICY.getBindings()); } @Test - public void testEtag() { + void testEtag() { assertNull(SIMPLE_POLICY.getEtag()); assertEquals("etag", FULL_POLICY.getEtag()); } @Test - public void testVersion() { + void testVersion() { assertEquals(0, SIMPLE_POLICY.getVersion()); assertEquals(1, FULL_POLICY.getVersion()); } @Test - public void testDefaultMarshaller() { + void testDefaultMarshaller() { DefaultMarshaller marshaller = new DefaultMarshaller(); Policy emptyPolicy = Policy.newBuilder().build(); assertEquals(emptyPolicy, marshaller.fromPb(marshaller.toPb(emptyPolicy))); From 9f0d7bf427b35792ca76029f59ac33d72c922db3 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:57:08 -0400 Subject: [PATCH 21/43] change tests --- .../java/com/google/cloud/PolicyV3Test.java | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/PolicyV3Test.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/PolicyV3Test.java index bdddf656f4..164ac6aeeb 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/PolicyV3Test.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/PolicyV3Test.java @@ -16,12 +16,12 @@ package com.google.cloud; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.cloud.Policy.DefaultMarshaller; import com.google.common.collect.ImmutableList; @@ -29,9 +29,9 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class PolicyV3Test { +class PolicyV3Test { private static final String ALL_USERS = "allUsers"; private static final String ALL_AUTH_USERS = "allAuthenticatedUsers"; @@ -79,7 +79,7 @@ public class PolicyV3Test { .build(); @Test - public void testBuilderV1() { + void testBuilderV1() { assertEquals(BINDINGS_NO_CONDITIONS, FULL_POLICY_V1.getBindingsList()); assertEquals(1, FULL_POLICY_V1.getVersion()); assertEquals("etag", FULL_POLICY_V1.getEtag()); @@ -90,7 +90,7 @@ public void testBuilderV1() { } @Test - public void testBuilderV3WithConditions() { + void testBuilderV3WithConditions() { assertEquals(BINDINGS_WITH_CONDITIONS, FULL_POLICY_V3.getBindingsList()); assertEquals(3, FULL_POLICY_V3.getVersion()); assertEquals("etag", FULL_POLICY_V3.getEtag()); @@ -101,7 +101,7 @@ public void testBuilderV3WithConditions() { } @Test - public void testBuilderV1ToV3Compatability() { + void testBuilderV1ToV3Compatability() { assertEquals(BINDINGS_WITH_CONDITIONS, FULL_POLICY_V3_WITH_VERSION_1.getBindingsList()); assertEquals(1, FULL_POLICY_V3_WITH_VERSION_1.getVersion()); assertEquals("etag", FULL_POLICY_V3_WITH_VERSION_1.getEtag()); @@ -117,7 +117,7 @@ public void testBuilderV1ToV3Compatability() { } @Test - public void removeMemberFromPolicy() { + void removeMemberFromPolicy() { assertEquals(3, FULL_POLICY_V3.getBindingsList().get(0).getMembers().size()); List bindings = new ArrayList<>(FULL_POLICY_V3.getBindingsList()); @@ -134,7 +134,7 @@ public void removeMemberFromPolicy() { } @Test - public void addMemberFromPolicy() { + void addMemberFromPolicy() { assertEquals(3, FULL_POLICY_V3.getBindingsList().get(0).getMembers().size()); List bindings = new ArrayList<>(FULL_POLICY_V3.getBindingsList()); @@ -150,7 +150,7 @@ public void addMemberFromPolicy() { } @Test - public void removeBindingFromPolicy() { + void removeBindingFromPolicy() { assertEquals(2, FULL_POLICY_V3.getBindingsList().size()); List bindings = new ArrayList<>(FULL_POLICY_V3.getBindingsList()); @@ -168,7 +168,7 @@ public void removeBindingFromPolicy() { } @Test - public void addBindingToPolicy() { + void addBindingToPolicy() { assertEquals(2, FULL_POLICY_V3.getBindingsList().size()); List bindings = new ArrayList<>(FULL_POLICY_V3.getBindingsList()); bindings.add(Binding.newBuilder().setRole(OWNER).setMembers(ImmutableList.of(USER)).build()); @@ -177,7 +177,7 @@ public void addBindingToPolicy() { } @Test - public void testIllegalPolicies() { + void testIllegalPolicies() { try { Binding.newBuilder().setRole(null).build(); fail("Null role should cause exception."); @@ -233,7 +233,7 @@ public void testIllegalPolicies() { } @Test - public void testEqualsHashCode() { + void testEqualsHashCode() { assertNotNull(FULL_POLICY_V3); Policy emptyPolicy = Policy.newBuilder().build(); Policy anotherPolicy = Policy.newBuilder().build(); @@ -247,26 +247,26 @@ public void testEqualsHashCode() { } @Test - public void testBindings() { + void testBindings() { assertTrue(Policy.newBuilder().build().getBindingsList().isEmpty()); assertEquals(BINDINGS_WITH_CONDITIONS, FULL_POLICY_V3.getBindingsList()); } @Test - public void testEtag() { + void testEtag() { assertNotNull(FULL_POLICY_V3.getEtag()); assertEquals("etag", FULL_POLICY_V3.getEtag()); } @Test - public void testVersion() { + void testVersion() { assertEquals(1, FULL_POLICY_V1.getVersion()); assertEquals(3, FULL_POLICY_V3.getVersion()); assertEquals(1, FULL_POLICY_V3_WITH_VERSION_1.getVersion()); } @Test - public void testDefaultMarshaller() { + void testDefaultMarshaller() { DefaultMarshaller marshaller = new DefaultMarshaller(); Policy emptyPolicy = Policy.newBuilder().build(); assertEquals(emptyPolicy, marshaller.fromPb(marshaller.toPb(emptyPolicy))); From 9f21f355b3032d9e885557d8dbbe204c3f7e0821 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 14:58:02 -0400 Subject: [PATCH 22/43] change tests --- .../test/java/com/google/cloud/RetryOptionTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/RetryOptionTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/RetryOptionTest.java index ebea89f2fc..a458d31f67 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/RetryOptionTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/RetryOptionTest.java @@ -16,14 +16,14 @@ package com.google.cloud; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import com.google.api.gax.retrying.RetrySettings; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.threeten.bp.Duration; -public class RetryOptionTest { +class RetryOptionTest { private static final RetryOption TOTAL_TIMEOUT = RetryOption.totalTimeout(Duration.ofMillis(420L)); @@ -46,7 +46,7 @@ public class RetryOptionTest { .build(); @Test - public void testEqualsAndHashCode() { + void testEqualsAndHashCode() { assertEquals(TOTAL_TIMEOUT, TOTAL_TIMEOUT); assertEquals(INITIAL_RETRY_DELAY, INITIAL_RETRY_DELAY); assertEquals(RETRY_DELAY_MULTIPLIER, RETRY_DELAY_MULTIPLIER); @@ -84,7 +84,7 @@ public void testEqualsAndHashCode() { } @Test - public void testMergeToSettings() { + void testMergeToSettings() { RetrySettings defRetrySettings = RetrySettings.newBuilder().build(); assertEquals(defRetrySettings, RetryOption.mergeToSettings(defRetrySettings)); From 07338883423c1b71d6c2c48da3dac67d6ba77898 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 15:00:20 -0400 Subject: [PATCH 23/43] change tests --- .../test/java/com/google/cloud/RoleTest.java | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/RoleTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/RoleTest.java index d6fcdf8441..694d507911 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/RoleTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/RoleTest.java @@ -17,17 +17,18 @@ package com.google.cloud; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class RoleTest { +class RoleTest { private static final Role VIEWER = Role.of("viewer"); private static final Role EDITOR = Role.of("editor"); private static final Role OWNER = Role.of("owner"); @Test - public void testOf() { + void testOf() { assertThat(VIEWER.getValue()).isEqualTo("roles/viewer"); assertThat(EDITOR.getValue()).isEqualTo("roles/editor"); assertThat(OWNER.getValue()).isEqualTo("roles/owner"); @@ -40,23 +41,23 @@ public void testOf() { } @Test - public void testViewer() { + void testViewer() { assertThat(Role.viewer().getValue()).isEqualTo("roles/viewer"); } @Test - public void testEditor() { + void testEditor() { assertThat(Role.editor().getValue()).isEqualTo("roles/editor"); } @Test - public void testOwner() { + void testOwner() { assertThat(Role.owner().getValue()).isEqualTo("roles/owner"); } - @Test(expected = NullPointerException.class) - public void testOfNullValue() { - Role.of(null); + @Test + void testOfNullValue() { + assertThrows(NullPointerException.class, () -> Role.of(null)); } private void compareRoles(Role expected, Role actual) { From 322de93e37d1a29a937bd51124e616c0e7d79cb8 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 15:03:50 -0400 Subject: [PATCH 24/43] change tests --- .../com/google/cloud/ServiceOptionsTest.java | 89 ++++++++++--------- 1 file changed, 45 insertions(+), 44 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java index 1b79e48ddc..48c1ae0b94 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java @@ -17,14 +17,13 @@ package com.google.cloud; import static com.google.common.truth.Truth.assertThat; -import static junit.framework.TestCase.assertFalse; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; @@ -50,9 +49,9 @@ import java.util.Map; import java.util.Set; import java.util.regex.Pattern; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ServiceOptionsTest { +class ServiceOptionsTest { private static GoogleCredentials credentials; private static GoogleCredentials credentialsWithProjectId; private static GoogleCredentials credentialsWithQuotaProject; @@ -378,15 +377,15 @@ public void testBuilder_quotaProjectServiceOptionTakesPrecedence() { assertEquals("quota-project-id", quotaProjectCredsWithQuotaProject.getQuotaProjectId()); assertEquals("quota-project-id", quotaProjectCredsWithQuotaProject2.getQuotaProjectId()); assertEquals("some-quota-project-id", quotaProjectCreds.getQuotaProjectId()); - assertEquals(null, none.getQuotaProjectId()); + assertNull(none.getQuotaProjectId()); } @Test - public void testBuilderNoCredentials() { + void testBuilderNoCredentials() { assertEquals(NoCredentials.getInstance(), OPTIONS_NO_CREDENTIALS.getCredentials()); - assertTrue(NoCredentials.getInstance().equals(OPTIONS_NO_CREDENTIALS.getCredentials())); - assertFalse(NoCredentials.getInstance().equals(OPTIONS.getCredentials())); - assertFalse(NoCredentials.getInstance().equals(null)); + assertEquals(NoCredentials.getInstance(), OPTIONS_NO_CREDENTIALS.getCredentials()); + assertNotEquals(NoCredentials.getInstance(), OPTIONS.getCredentials()); + assertNotEquals(null, NoCredentials.getInstance()); assertSame(TEST_CLOCK, OPTIONS_NO_CREDENTIALS.getClock()); assertEquals("host", OPTIONS_NO_CREDENTIALS.getHost()); assertEquals("project-id", OPTIONS_NO_CREDENTIALS.getProjectId()); @@ -394,20 +393,22 @@ public void testBuilderNoCredentials() { assertEquals("quota-project-id", OPTIONS.getQuotaProjectId()); } - @Test(expected = NullPointerException.class) - public void testBuilderNullCredentials() { - TestServiceOptions.newBuilder().setCredentials(null).build(); + @Test + void testBuilderNullCredentials() { + assertThrows( + NullPointerException.class, + () -> TestServiceOptions.newBuilder().setCredentials(null).build()); } @Test - public void testBuilderServiceAccount_setsProjectId() { + void testBuilderServiceAccount_setsProjectId() { TestServiceOptions options = TestServiceOptions.newBuilder().setCredentials(credentialsWithProjectId).build(); assertEquals("someprojectid", options.getProjectId()); } @Test - public void testBuilderServiceAccount_explicitSetProjectIdBefore() { + void testBuilderServiceAccount_explicitSetProjectIdBefore() { TestServiceOptions options = TestServiceOptions.newBuilder() .setProjectId("override-project-id") @@ -417,7 +418,7 @@ public void testBuilderServiceAccount_explicitSetProjectIdBefore() { } @Test - public void testBuilderServiceAccount_explicitSetProjectIdAfter() { + void testBuilderServiceAccount_explicitSetProjectIdAfter() { TestServiceOptions options = TestServiceOptions.newBuilder() .setCredentials(credentialsWithProjectId) @@ -427,44 +428,44 @@ public void testBuilderServiceAccount_explicitSetProjectIdAfter() { } @Test - public void testGetProjectIdRequired() { + void testGetProjectIdRequired() { assertTrue(OPTIONS.projectIdRequired()); } @Test - public void testService() { + void testService() { assertTrue(OPTIONS.getService() instanceof TestServiceImpl); } @Test - public void testRpc() { + void testRpc() { assertTrue(OPTIONS.getRpc() instanceof DefaultTestServiceRpc); } @Test - public void testBaseEquals() { + void testBaseEquals() { assertEquals(OPTIONS, OPTIONS_COPY); assertNotEquals(DEFAULT_OPTIONS, OPTIONS); } @Test - public void testLibraryName() { + void testLibraryName() { assertEquals(LIBRARY_NAME, ServiceOptions.getLibraryName()); } @Test - public void testApplicationName() { + void testApplicationName() { assertTrue(APPLICATION_NAME_PATTERN.matcher(OPTIONS.getApplicationName()).matches()); } @Test - public void testBaseHashCode() { + void testBaseHashCode() { assertEquals(OPTIONS.hashCode(), OPTIONS_COPY.hashCode()); assertNotEquals(DEFAULT_OPTIONS.hashCode(), OPTIONS.hashCode()); } @Test - public void testGetServiceAccountProjectId() throws Exception { + void testGetServiceAccountProjectId() throws Exception { File credentialsFile = File.createTempFile("credentials", ".json"); credentialsFile.deleteOnExit(); Files.write("{\"project_id\":\"my-project-id\"}".getBytes(), credentialsFile); @@ -475,7 +476,7 @@ public void testGetServiceAccountProjectId() throws Exception { } @Test - public void testGetServiceAccountProjectId_badJson() throws Exception { + void testGetServiceAccountProjectId_badJson() throws Exception { File credentialsFile = File.createTempFile("credentials", ".json"); credentialsFile.deleteOnExit(); Files.write("asdfghj".getBytes(StandardCharsets.UTF_8), credentialsFile); @@ -486,14 +487,14 @@ public void testGetServiceAccountProjectId_badJson() throws Exception { } @Test - public void testGetServiceAccountProjectId_nonExistentFile() throws Exception { + void testGetServiceAccountProjectId_nonExistentFile() throws Exception { File credentialsFile = new File("/doesnotexist"); assertNull(ServiceOptions.getValueFromCredentialsFile(credentialsFile.getPath(), "project_id")); } @Test - public void testResponseHeaderContainsMetaDataFlavor() throws Exception { + void testResponseHeaderContainsMetaDataFlavor() throws Exception { Multimap headers = ArrayListMultimap.create(); headers.put("Metadata-Flavor", "Google"); HttpResponse httpResponse = createHttpResponseWithHeader(headers); @@ -501,20 +502,20 @@ public void testResponseHeaderContainsMetaDataFlavor() throws Exception { } @Test - public void testResponseHeaderDoesNotContainMetaDataFlavor() throws Exception { + void testResponseHeaderDoesNotContainMetaDataFlavor() throws Exception { Multimap headers = ArrayListMultimap.create(); HttpResponse httpResponse = createHttpResponseWithHeader(headers); assertThat(ServiceOptions.headerContainsMetadataFlavor(httpResponse)).isFalse(); } @Test - public void testGetResolvedEndpoint_noUniverseDomain() { + void testGetResolvedEndpoint_noUniverseDomain() { TestServiceOptions options = TestServiceOptions.newBuilder().setProjectId("project-id").build(); assertThat(options.getResolvedHost("service")).isEqualTo("https://service.googleapis.com"); } @Test - public void testGetResolvedEndpoint_emptyUniverseDomain() { + void testGetResolvedEndpoint_emptyUniverseDomain() { TestServiceOptions options = TestServiceOptions.newBuilder().setUniverseDomain("").setProjectId("project-id").build(); IllegalArgumentException exception = @@ -523,7 +524,7 @@ public void testGetResolvedEndpoint_emptyUniverseDomain() { } @Test - public void testGetResolvedEndpoint_customUniverseDomain() { + void testGetResolvedEndpoint_customUniverseDomain() { TestServiceOptions options = TestServiceOptions.newBuilder() .setUniverseDomain("test.com") @@ -533,7 +534,7 @@ public void testGetResolvedEndpoint_customUniverseDomain() { } @Test - public void testGetResolvedEndpoint_customUniverseDomain_customHost() { + void testGetResolvedEndpoint_customUniverseDomain_customHost() { TestServiceOptions options = TestServiceOptions.newBuilder() .setUniverseDomain("test.com") @@ -544,14 +545,14 @@ public void testGetResolvedEndpoint_customUniverseDomain_customHost() { } @Test - public void testGetResolvedApiaryHost_noUniverseDomain() { + void testGetResolvedApiaryHost_noUniverseDomain() { TestServiceOptions options = TestServiceOptions.newBuilder().setProjectId("project-id").build(); assertThat(options.getResolvedApiaryHost("service")) .isEqualTo("https://service.googleapis.com/"); } @Test - public void testGetResolvedApiaryHost_customUniverseDomain_noHost() { + void testGetResolvedApiaryHost_customUniverseDomain_noHost() { TestServiceOptions options = TestServiceOptions.newBuilder() .setUniverseDomain("test.com") @@ -562,7 +563,7 @@ public void testGetResolvedApiaryHost_customUniverseDomain_noHost() { } @Test - public void testGetResolvedApiaryHost_customUniverseDomain_customHost() { + void testGetResolvedApiaryHost_customUniverseDomain_customHost() { TestServiceOptions options = TestServiceOptions.newBuilder() .setUniverseDomain("test.com") @@ -574,7 +575,7 @@ public void testGetResolvedApiaryHost_customUniverseDomain_customHost() { // No User Configuration = GDU, Default Credentials = GDU @Test - public void testIsValidUniverseDomain_noUserUniverseDomainConfig_defaultCredentials() + void testIsValidUniverseDomain_noUserUniverseDomainConfig_defaultCredentials() throws IOException { TestServiceOptions options = TestServiceOptions.newBuilder() @@ -588,7 +589,7 @@ public void testIsValidUniverseDomain_noUserUniverseDomainConfig_defaultCredenti // No User Configuration = GDU, non Default Credentials = random.com // non-GDU Credentials could be any domain, the tests use random.com @Test - public void testIsValidUniverseDomain_noUserUniverseDomainConfig_nonGDUCredentials() + void testIsValidUniverseDomain_noUserUniverseDomainConfig_nonGDUCredentials() throws IOException { TestServiceOptions options = TestServiceOptions.newBuilder() @@ -602,7 +603,7 @@ public void testIsValidUniverseDomain_noUserUniverseDomainConfig_nonGDUCredentia // User Configuration = random.com, Default Credentials = GDU // User Credentials could be set to any domain, the tests use random.com @Test - public void testIsValidUniverseDomain_userUniverseDomainConfig_defaultCredentials() + void testIsValidUniverseDomain_userUniverseDomainConfig_defaultCredentials() throws IOException { TestServiceOptions options = TestServiceOptions.newBuilder() @@ -618,7 +619,7 @@ public void testIsValidUniverseDomain_userUniverseDomainConfig_defaultCredential // User Credentials and non GDU Credentials could be set to any domain, // the tests use random.com @Test - public void testIsValidUniverseDomain_userUniverseDomainConfig_nonGDUCredentials() + void testIsValidUniverseDomain_userUniverseDomainConfig_nonGDUCredentials() throws IOException { TestServiceOptions options = TestServiceOptions.newBuilder() From 5a055456886a37bbb3e531152d5b9e86f82d3f42 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 15:06:41 -0400 Subject: [PATCH 25/43] change tests --- .../java/com/google/cloud/StringEnumTest.java | 39 ++++++++++--------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/StringEnumTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/StringEnumTest.java index 781fbb8925..a5812776f8 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/StringEnumTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/StringEnumTest.java @@ -16,18 +16,19 @@ package com.google.cloud; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.api.core.ApiFunction; import com.google.common.testing.EqualsTester; import java.util.Arrays; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -public class StringEnumTest { +class StringEnumTest { - public static class Letter extends StringEnumValue { + static class Letter extends StringEnumValue { private static final long serialVersionUID = -1717976087182628526L; private Letter(String constant) { @@ -64,28 +65,30 @@ public static Letter[] values() { } } - @Test(expected = NullPointerException.class) - public void testNullClass() { - new StringEnumType(null, Letter.CONSTRUCTOR); + @Test + void testNullClass() { + assertThrows( + NullPointerException.class, + () -> new StringEnumType(null, Letter.CONSTRUCTOR)); } @Test - public void testNullConstructor() { + void testNullConstructor() { try { new StringEnumType(Letter.class, null); - Assert.fail(); + Assertions.fail(); } catch (NullPointerException ex) { assertNull(ex.getMessage()); } } @Test - public void testEnumInstances() { + void testEnumInstances() { assertThat(Letter.A.toString()).isEqualTo("A"); } @Test - public void testValueOf() { + void testValueOf() { assertThat(Letter.valueOf("A")).isSameInstanceAs(Letter.A); assertThat(Letter.valueOf("B")).isSameInstanceAs(Letter.B); assertThat(Letter.valueOf("C")).isSameInstanceAs(Letter.C); @@ -93,14 +96,14 @@ public void testValueOf() { } @Test - public void testValueOfStrict() { + void testValueOfStrict() { assertThat(Letter.valueOfStrict("A")).isSameInstanceAs(Letter.A); assertThat(Letter.valueOfStrict("B")).isSameInstanceAs(Letter.B); assertThat(Letter.valueOfStrict("C")).isSameInstanceAs(Letter.C); } @Test - public void testEquals() { + void testEquals() { new EqualsTester() .addEqualityGroup(Letter.A, Letter.valueOf("A"), Letter.valueOfStrict("A")) .addEqualityGroup(Letter.B, Letter.valueOf("B"), Letter.valueOfStrict("B")) @@ -110,17 +113,17 @@ public void testEquals() { } @Test - public void testValueOfStrict_invalid() { + void testValueOfStrict_invalid() { try { Letter.valueOfStrict("NonExistentLetter"); - Assert.fail(); + Assertions.fail(); } catch (IllegalArgumentException ex) { assertNotNull(ex.getMessage()); } } @Test - public void testValues() { + void testValues() { assertThat( Arrays.asList(Letter.values()).containsAll(Arrays.asList(Letter.A, Letter.B, Letter.C))) .isTrue(); From d21cd32bc1d66c7d567c10795143014b51c45ddb Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 15:08:03 -0400 Subject: [PATCH 26/43] change tests --- .../java/com/google/cloud/StructsTest.java | 33 +++++++++---------- 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/StructsTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/StructsTest.java index 8c1610bbac..abc86633cb 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/StructsTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/StructsTest.java @@ -16,8 +16,8 @@ package com.google.cloud; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -27,12 +27,9 @@ import com.google.protobuf.Value; import java.util.HashMap; import java.util.Map; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -@RunWith(JUnit4.class) public class StructsTest { private static final Double NUMBER = 42.0; @@ -75,8 +72,8 @@ public class StructsTest { private static final Struct STRUCT = Struct.newBuilder().putAllFields(VALUE_MAP).build(); private static final ImmutableMap EMPTY_MAP = ImmutableMap.of(); - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { INNER_MAP.put("null", null); INNER_MAP.put("number", NUMBER); INNER_MAP.put("string", STRING); @@ -101,7 +98,7 @@ private void checkStructField(Struct struct, String key, Value expected) { } @Test - public void testAsMap() { + void testAsMap() { Map map = Structs.asMap(STRUCT); checkMapField(map, "null", null); checkMapField(map, "number", NUMBER); @@ -113,7 +110,7 @@ public void testAsMap() { } @Test - public void testAsMapPut() { + void testAsMapPut() { Map map = Structs.asMap(STRUCT); try { map.put("key", "value"); @@ -124,7 +121,7 @@ public void testAsMapPut() { } @Test - public void testAsMapRemove() { + void testAsMapRemove() { Map map = Structs.asMap(STRUCT); try { map.remove("null"); @@ -135,14 +132,14 @@ public void testAsMapRemove() { } @Test - public void testAsMapEmpty() { + void testAsMapEmpty() { Map map = Structs.asMap(Struct.getDefaultInstance()); assertThat(map).isEmpty(); assertEquals(EMPTY_MAP, map); } @Test - public void testAsMapNull() { + void testAsMapNull() { try { Structs.asMap(null); fail(); @@ -151,7 +148,7 @@ public void testAsMapNull() { } @Test - public void testNewStruct() { + void testNewStruct() { Struct struct = Structs.newStruct(MAP); checkStructField(struct, "null", NULL_VALUE); checkStructField(struct, "number", NUMBER_VALUE); @@ -163,13 +160,13 @@ public void testNewStruct() { } @Test - public void testNewStructEmpty() { + void testNewStructEmpty() { Struct struct = Structs.newStruct(EMPTY_MAP); assertThat(struct.getFieldsMap()).isEmpty(); } @Test - public void testNewStructNull() { + void testNewStructNull() { try { Structs.newStruct(null); fail(); @@ -178,7 +175,7 @@ public void testNewStructNull() { } @Test - public void testNumbers() { + void testNumbers() { int intNumber = Integer.MIN_VALUE; long longNumber = Long.MAX_VALUE; float floatNumber = Float.MIN_VALUE; From 5a582998c991f8a25c27b981e6407221cff2d555 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 15:09:44 -0400 Subject: [PATCH 27/43] change tests --- .../java/com/google/cloud/TimestampTest.java | 77 +++++++++---------- 1 file changed, 37 insertions(+), 40 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/TimestampTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/TimestampTest.java index 5eaeb0a894..8a01d4b242 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/TimestampTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/TimestampTest.java @@ -18,8 +18,8 @@ import static com.google.common.testing.SerializableTester.reserializeAndAssert; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import com.google.common.testing.EqualsTester; import java.util.Calendar; @@ -27,14 +27,11 @@ import java.util.GregorianCalendar; import java.util.TimeZone; import java.util.concurrent.TimeUnit; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** Unit tests for {@link com.google.cloud.Timestamp}. */ -@RunWith(JUnit4.class) -public class TimestampTest { +class TimestampTest { private static final String TEST_TIME_ISO = "2015-10-12T15:14:54Z"; private static final long TEST_TIME_SECONDS = 1444662894L; private static final long TEST_TIME_MICROSECONDS = 10000100L; @@ -45,14 +42,14 @@ public class TimestampTest { private static final Date TEST_DATE_PRE_EPOCH = new Date(TEST_TIME_MILLISECONDS_NEGATIVE); @Test - public void minValue() { + void minValue() { // MIN_VALUE is before the start of the Gregorian calendar... use magic value. assertThat(Timestamp.MIN_VALUE.getSeconds()).isEqualTo(-62135596800L); assertThat(Timestamp.MIN_VALUE.getNanos()).isEqualTo(0); } @Test - public void maxValue() { + void maxValue() { TimeZone tz = TimeZone.getTimeZone("UTC"); GregorianCalendar calendar = new GregorianCalendar(tz); calendar.set(9999, Calendar.DECEMBER, 31, 23, 59, 59); @@ -64,14 +61,14 @@ public void maxValue() { } @Test - public void ofMicroseconds() { + void ofMicroseconds() { Timestamp timestamp = Timestamp.ofTimeMicroseconds(TEST_TIME_MICROSECONDS); assertThat(timestamp.getSeconds()).isEqualTo(TEST_TIME_MICROSECONDS / 1000000L); assertThat(timestamp.getNanos()).isEqualTo(TEST_TIME_MICROSECONDS % 1000000L * 1000); } @Test - public void ofDate() { + void ofDate() { Timestamp timestamp = Timestamp.of(TEST_DATE); Long expectedSeconds = TimeUnit.MILLISECONDS.toSeconds(TEST_TIME_MILLISECONDS); Long expectedNanos = @@ -82,7 +79,7 @@ public void ofDate() { } @Test - public void testOf() { + void testOf() { String expectedTimestampString = "1970-01-01T00:00:12.345000000Z"; java.sql.Timestamp input = new java.sql.Timestamp(12345); Timestamp timestamp = Timestamp.of(input); @@ -90,7 +87,7 @@ public void testOf() { } @Test - public void testOf_exactSecond() { + void testOf_exactSecond() { String expectedTimestampString = "1970-01-01T00:00:12Z"; java.sql.Timestamp input = new java.sql.Timestamp(12000); Timestamp timestamp = Timestamp.of(input); @@ -98,7 +95,7 @@ public void testOf_exactSecond() { } @Test - public void testOf_preEpoch() { + void testOf_preEpoch() { String expectedTimestampString = "1969-12-31T23:59:47.655000000Z"; java.sql.Timestamp input = new java.sql.Timestamp(-12345); Timestamp timestamp = Timestamp.of(input); @@ -106,7 +103,7 @@ public void testOf_preEpoch() { } @Test - public void testOf_onEpoch() { + void testOf_onEpoch() { String expectedTimestampString = "1970-01-01T00:00:00Z"; java.sql.Timestamp input = new java.sql.Timestamp(0); Timestamp timestamp = Timestamp.of(input); @@ -114,7 +111,7 @@ public void testOf_onEpoch() { } @Test - public void testOf_preEpochExactSecond() { + void testOf_preEpochExactSecond() { String expectedTimestampString = "1969-12-31T23:59:59Z"; java.sql.Timestamp input = new java.sql.Timestamp(-1000); Timestamp timestamp = Timestamp.of(input); @@ -122,7 +119,7 @@ public void testOf_preEpochExactSecond() { } @Test - public void ofDatePreEpoch() { + void ofDatePreEpoch() { Timestamp timestamp = Timestamp.of(TEST_DATE_PRE_EPOCH); long expectedSeconds = TEST_TIME_MILLISECONDS_NEGATIVE / 1_000; int expectedNanos = (int) (TEST_TIME_MILLISECONDS_NEGATIVE % 1_000 * 1000_000); @@ -135,14 +132,14 @@ public void ofDatePreEpoch() { } @Test - public void toDate() { + void toDate() { Timestamp timestamp = Timestamp.ofTimeSecondsAndNanos(TEST_TIME_SECONDS, 1234 * 1000); Date date = timestamp.toDate(); assertThat(TEST_TIME_MILLISECONDS).isEqualTo(date.getTime()); } @Test - public void toFromSqlTimestamp() { + void toFromSqlTimestamp() { long seconds = TEST_TIME_SECONDS; int nanos = 500000000; @@ -157,67 +154,67 @@ public void toFromSqlTimestamp() { } @Test - public void boundsSecondsMin() { + void boundsSecondsMin() { try { Timestamp.ofTimeSecondsAndNanos(Timestamp.MIN_VALUE.getSeconds() - 1, 999999999); - Assert.fail(); + Assertions.fail(); } catch (IllegalArgumentException ex) { assertNotNull(ex.getMessage()); } } @Test - public void boundsSecondsMax() { + void boundsSecondsMax() { try { Timestamp.ofTimeSecondsAndNanos(Timestamp.MAX_VALUE.getSeconds() + 1, 0); - Assert.fail(); + Assertions.fail(); } catch (IllegalArgumentException ex) { assertNotNull(ex.getMessage()); } } @Test - public void boundsNanosMin() { + void boundsNanosMin() { try { Timestamp.ofTimeSecondsAndNanos(TEST_TIME_SECONDS, -1); - Assert.fail(); + Assertions.fail(); } catch (IllegalArgumentException ex) { assertNotNull(ex.getMessage()); } } @Test - public void boundsNanosMax() { + void boundsNanosMax() { try { Timestamp.ofTimeSecondsAndNanos(TEST_TIME_SECONDS, 1000000000); - Assert.fail(); + Assertions.fail(); } catch (IllegalArgumentException ex) { assertNotNull(ex.getMessage()); } } @Test - public void boundsSqlTimestampMin() { + void boundsSqlTimestampMin() { try { Timestamp.of(new java.sql.Timestamp((Timestamp.MIN_VALUE.getSeconds() - 1) * 1000)); - Assert.fail(); + Assertions.fail(); } catch (IllegalArgumentException ex) { assertNotNull(ex.getMessage()); } } @Test - public void boundsSqlTimestampMax() { + void boundsSqlTimestampMax() { try { Timestamp.of(new java.sql.Timestamp((Timestamp.MAX_VALUE.getSeconds() + 1) * 1000)); - Assert.fail(); + Assertions.fail(); } catch (IllegalArgumentException ex) { assertNotNull(ex.getMessage()); } } @Test - public void equalsAndHashCode() { + void equalsAndHashCode() { EqualsTester tester = new EqualsTester(); tester.addEqualityGroup( Timestamp.ofTimeSecondsAndNanos(TEST_TIME_SECONDS, 0), @@ -229,7 +226,7 @@ public void equalsAndHashCode() { } @Test - public void testToString() { + void testToString() { assertThat(Timestamp.MIN_VALUE.toString()).isEqualTo("0001-01-01T00:00:00Z"); assertThat(Timestamp.MAX_VALUE.toString()).isEqualTo("9999-12-31T23:59:59.999999999Z"); assertThat(Timestamp.ofTimeSecondsAndNanos(0, 0).toString()).isEqualTo("1970-01-01T00:00:00Z"); @@ -240,7 +237,7 @@ public void testToString() { } @Test - public void parseTimestamp() { + void parseTimestamp() { assertThat(Timestamp.parseTimestamp("0001-01-01T00:00:00Z")).isEqualTo(Timestamp.MIN_VALUE); assertThat(Timestamp.parseTimestamp("9999-12-31T23:59:59.999999999Z")) .isEqualTo(Timestamp.MAX_VALUE); @@ -249,7 +246,7 @@ public void parseTimestamp() { } @Test - public void parseTimestampWithoutTimeZoneOffset() { + void parseTimestampWithoutTimeZoneOffset() { assertThat(Timestamp.parseTimestamp("0001-01-01T00:00:00")).isEqualTo(Timestamp.MIN_VALUE); assertThat(Timestamp.parseTimestamp("9999-12-31T23:59:59.999999999")) .isEqualTo(Timestamp.MAX_VALUE); @@ -258,7 +255,7 @@ public void parseTimestampWithoutTimeZoneOffset() { } @Test - public void parseTimestampWithTimeZoneOffset() { + void parseTimestampWithTimeZoneOffset() { assertThat(Timestamp.parseTimestamp("0001-01-01T00:00:00-00:00")) .isEqualTo(Timestamp.MIN_VALUE); assertThat(Timestamp.parseTimestamp("9999-12-31T23:59:59.999999999-00:00")) @@ -270,7 +267,7 @@ public void parseTimestampWithTimeZoneOffset() { } @Test - public void fromProto() { + void fromProto() { com.google.protobuf.Timestamp proto = com.google.protobuf.Timestamp.newBuilder().setSeconds(1234).setNanos(567).build(); Timestamp timestamp = Timestamp.fromProto(proto); @@ -279,7 +276,7 @@ public void fromProto() { } @Test - public void comparable() { + void comparable() { assertThat(Timestamp.MIN_VALUE).isLessThan(Timestamp.MAX_VALUE); assertThat(Timestamp.MAX_VALUE).isGreaterThan(Timestamp.MIN_VALUE); @@ -300,7 +297,7 @@ public void comparable() { } @Test - public void serialization() throws Exception { + void serialization() throws Exception { reserializeAndAssert(Timestamp.parseTimestamp("9999-12-31T23:59:59.999999999Z")); } } From 282ea923b5a8e8893a69afacdfeac2e0b012c0b3 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 15:11:27 -0400 Subject: [PATCH 28/43] change tests --- .../cloud/grpc/BaseGrpcServiceExceptionTest.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/BaseGrpcServiceExceptionTest.java b/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/BaseGrpcServiceExceptionTest.java index 696de60c55..9eb2a7fd49 100644 --- a/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/BaseGrpcServiceExceptionTest.java +++ b/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/BaseGrpcServiceExceptionTest.java @@ -20,10 +20,10 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.gax.grpc.GrpcStatusCode; import com.google.api.gax.rpc.InternalException; @@ -33,16 +33,16 @@ import java.io.IOException; import java.net.SocketException; import java.net.SocketTimeoutException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class BaseGrpcServiceExceptionTest { +class BaseGrpcServiceExceptionTest { private static final String MESSAGE = "some message"; private static final boolean NOT_RETRYABLE = false; private static final boolean IDEMPOTENT = true; @Test - public void testBaseServiceException() { + void testBaseServiceException() { BaseGrpcServiceException serviceException = null; IOException exception = new SocketTimeoutException(); @@ -86,7 +86,7 @@ public void testBaseServiceException() { } @Test - public void testTranslateAndThrow() throws Exception { + void testTranslateAndThrow() throws Exception { IOException exception = new SocketTimeoutException(); BaseGrpcServiceException cause = new BaseGrpcServiceException(exception, IDEMPOTENT); RetryHelper.RetryHelperException exceptionMock = From 046a43a1aaef7929a50c26007a99315f29568270 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 15:12:11 -0400 Subject: [PATCH 29/43] change tests --- .../cloud/grpc/GrpcTransportOptionsTest.java | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/GrpcTransportOptionsTest.java b/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/GrpcTransportOptionsTest.java index b51eab96ce..a112dd5e07 100644 --- a/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/GrpcTransportOptionsTest.java +++ b/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/GrpcTransportOptionsTest.java @@ -16,18 +16,18 @@ package com.google.cloud.grpc; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.cloud.grpc.GrpcTransportOptions.DefaultExecutorFactory; import com.google.cloud.grpc.GrpcTransportOptions.ExecutorFactory; import java.util.concurrent.ScheduledExecutorService; import org.easymock.EasyMock; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GrpcTransportOptionsTest { +class GrpcTransportOptionsTest { private static final ExecutorFactory MOCK_EXECUTOR_FACTORY = EasyMock.createMock(ExecutorFactory.class); @@ -38,13 +38,13 @@ public class GrpcTransportOptionsTest { private static final GrpcTransportOptions OPTIONS_COPY = OPTIONS.toBuilder().build(); @Test - public void testBuilder() { + void testBuilder() { assertSame(MOCK_EXECUTOR_FACTORY, OPTIONS.getExecutorFactory()); assertTrue(DEFAULT_OPTIONS.getExecutorFactory() instanceof DefaultExecutorFactory); } @Test - public void testBaseEquals() { + void testBaseEquals() { assertEquals(OPTIONS, OPTIONS_COPY); assertNotEquals(DEFAULT_OPTIONS, OPTIONS); GrpcTransportOptions options = @@ -53,7 +53,7 @@ public void testBaseEquals() { } @Test - public void testBaseHashCode() { + void testBaseHashCode() { assertEquals(OPTIONS.hashCode(), OPTIONS_COPY.hashCode()); assertNotEquals(DEFAULT_OPTIONS.hashCode(), OPTIONS.hashCode()); GrpcTransportOptions options = @@ -62,7 +62,7 @@ public void testBaseHashCode() { } @Test - public void testDefaultExecutorFactory() { + void testDefaultExecutorFactory() { ExecutorFactory executorFactory = new DefaultExecutorFactory(); ScheduledExecutorService executorService = executorFactory.get(); assertSame(executorService, executorFactory.get()); From de50f00ca0d4f80075225f89c46b786fb0851388 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 15:14:31 -0400 Subject: [PATCH 30/43] change tests --- .../cloud/grpc/SharedResourceHolderTest.java | 40 +++++++++++-------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/SharedResourceHolderTest.java b/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/SharedResourceHolderTest.java index ba70a0de55..574a64b414 100644 --- a/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/SharedResourceHolderTest.java +++ b/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/SharedResourceHolderTest.java @@ -16,8 +16,19 @@ package com.google.cloud.grpc; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.easymock.EasyMock.anyLong; +import static org.easymock.EasyMock.anyObject; +import static org.easymock.EasyMock.createNiceMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.util.LinkedList; import java.util.concurrent.Delayed; @@ -26,20 +37,17 @@ import java.util.concurrent.TimeUnit; import org.easymock.EasyMock; import org.easymock.IAnswer; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * This class was copied from grpc-core to prevent dependence on an unstable API that may be subject * to changes - * (https://github.com/grpc/grpc-java/blob/d07ecbe037d2705a1c9f4b6345581f860e505b56/core/src/test/java/io/grpc/internal/SharedResourceHolderTest.java) + * (SharedResourceHolderTest) * *

Unit tests for {@link SharedResourceHolder}. */ -@RunWith(JUnit4.class) -public class SharedResourceHolderTest { +class SharedResourceHolderTest { private final LinkedList> scheduledDestroyTasks = new LinkedList<>(); @@ -67,13 +75,13 @@ public void close(ResourceInstance instance) { private static final SharedResourceHolder.Resource SHARED_BAR = new ResourceFactory(); - @Before - public void setUp() { + @BeforeEach + void setUp() { holder = new SharedResourceHolder(new MockExecutorFactory()); } @Test - public void destroyResourceWhenRefCountReachesZero() { + void destroyResourceWhenRefCountReachesZero() { ResourceInstance foo1 = holder.getInternal(SHARED_FOO); ResourceInstance sharedFoo = foo1; ResourceInstance foo2 = holder.getInternal(SHARED_FOO); @@ -121,7 +129,7 @@ public void destroyResourceWhenRefCountReachesZero() { } @Test - public void cancelDestroyTask() { + void cancelDestroyTask() { ResourceInstance foo1 = holder.getInternal(SHARED_FOO); ResourceInstance sharedFoo = foo1; holder.releaseInternal(SHARED_FOO, foo1); @@ -148,7 +156,7 @@ public void cancelDestroyTask() { } @Test - public void releaseWrongInstance() { + void releaseWrongInstance() { ResourceInstance uncached = new ResourceInstance(); try { holder.releaseInternal(SHARED_FOO, uncached); @@ -167,7 +175,7 @@ public void releaseWrongInstance() { } @Test - public void overreleaseInstance() { + void overreleaseInstance() { ResourceInstance foo1 = holder.getInternal(SHARED_FOO); holder.releaseInternal(SHARED_FOO, foo1); try { @@ -179,7 +187,7 @@ public void overreleaseInstance() { } @Test - public void handleInstanceCloseError() { + void handleInstanceCloseError() { class ExceptionOnCloseResource implements SharedResourceHolder.Resource { @Override public ResourceInstance create() { From f22d1ca8dd27eadfba1bb23cd7d0d88997fae952 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 15:15:30 -0400 Subject: [PATCH 31/43] change tests --- .../http/BaseHttpServiceExceptionTest.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/BaseHttpServiceExceptionTest.java b/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/BaseHttpServiceExceptionTest.java index e88a32a9af..885cb7511d 100644 --- a/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/BaseHttpServiceExceptionTest.java +++ b/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/BaseHttpServiceExceptionTest.java @@ -21,10 +21,10 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.cloud.BaseServiceException; @@ -35,9 +35,9 @@ import java.net.SocketTimeoutException; import java.util.Collections; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class BaseHttpServiceExceptionTest { +class BaseHttpServiceExceptionTest { private static final int CODE = 1; private static final int CODE_NO_REASON = 2; @@ -53,7 +53,7 @@ private static class CustomServiceException extends BaseHttpServiceException { private static final long serialVersionUID = -195251309124875103L; - public CustomServiceException(int code, String message, String reason, boolean idempotent) { + CustomServiceException(int code, String message, String reason, boolean idempotent) { super(code, message, reason, idempotent, RETRYABLE_ERRORS); } @@ -63,7 +63,7 @@ public CustomServiceException(int code, String message, String reason, boolean i } @Test - public void testBaseServiceException() { + void testBaseServiceException() { BaseServiceException serviceException = new BaseHttpServiceException(CODE, MESSAGE, REASON, IDEMPOTENT, EMPTY_RETRYABLE_ERRORS); assertEquals(CODE, serviceException.getCode()); @@ -145,7 +145,7 @@ public void testBaseServiceException() { } @Test - public void testTranslateAndThrow() throws Exception { + void testTranslateAndThrow() throws Exception { BaseServiceException cause = new BaseHttpServiceException(CODE, MESSAGE, REASON, IDEMPOTENT, EMPTY_RETRYABLE_ERRORS); RetryHelper.RetryHelperException exceptionMock = From f7ea1bc6fe5cb21f1e610065b4826b05fd9c8b87 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 15:21:29 -0400 Subject: [PATCH 32/43] change tests --- .../cloud/http/CensusHttpModuleTest.java | 48 +++++++++---------- 1 file changed, 22 insertions(+), 26 deletions(-) diff --git a/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/CensusHttpModuleTest.java b/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/CensusHttpModuleTest.java index c04d0647fb..e766c02d55 100644 --- a/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/CensusHttpModuleTest.java +++ b/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/CensusHttpModuleTest.java @@ -21,6 +21,7 @@ import static org.easymock.EasyMock.createMockBuilder; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpExecuteInterceptor; @@ -41,25 +42,18 @@ import java.io.IOException; import java.util.EnumSet; import java.util.Random; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** Tests for {@link CensusHttpModule}. */ -@RunWith(JUnit4.class) -public class CensusHttpModuleTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class CensusHttpModuleTest { private final Tracer tracer = Tracing.getTracer(); private final CensusHttpModule censusHttpModule = new CensusHttpModule(tracer, false); private HttpRequest httpRequest; - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { httpRequest = new NetHttpTransport() .createRequestFactory() @@ -67,23 +61,23 @@ public void setUp() throws IOException { } @Test - public void tracerShouldNotBeNull() { + void tracerShouldNotBeNull() { assertThat(censusHttpModule.getTracer()).isNotNull(); } @Test - public void isRecordEventsShouldBeSet() { + void isRecordEventsShouldBeSet() { assertThat(censusHttpModule.isRecordEvents()).isEqualTo(false); } @Test - public void getHttpRequestInitializerShouldReturnCorrectClass() { + void getHttpRequestInitializerShouldReturnCorrectClass() { HttpRequestInitializer initializer = censusHttpModule.getHttpRequestInitializer(null); assertThat(initializer).isInstanceOf(CensusHttpModule.CensusHttpRequestInitializer.class); } @Test - public void implementationOfDefaultTextFormatSetter() { + void implementationOfDefaultTextFormatSetter() { String testKey = "testKey"; String testValue = "testValue"; TextFormat.Setter setter = @@ -93,14 +87,15 @@ public void implementationOfDefaultTextFormatSetter() { } @Test - public void censusHttpExecuteInterceptorDisallowNullRequest() throws IOException { + void censusHttpExecuteInterceptorDisallowNullRequest() { HttpExecuteInterceptor interceptor = censusHttpModule.new CensusHttpExecuteInterceptor(null); - thrown.expect(NullPointerException.class); - interceptor.intercept(null); + assertThrows( + NullPointerException.class, + () -> interceptor.intercept(null)); } @Test - public void censusHttpExecuteInterceptorShouldExecuteOriginal() throws IOException { + void censusHttpExecuteInterceptorShouldExecuteOriginal() throws IOException { HttpExecuteInterceptor mockInterceptor = createMock(HttpExecuteInterceptor.class); HttpExecuteInterceptor censusInterceptor = censusHttpModule.new CensusHttpExecuteInterceptor(mockInterceptor); @@ -111,7 +106,7 @@ public void censusHttpExecuteInterceptorShouldExecuteOriginal() throws IOExcepti } @Test - public void censusHttpExecuteInterceptorShouldInjectHeader() throws IOException { + void censusHttpExecuteInterceptorShouldInjectHeader() throws IOException { Random random = new Random(); SpanContext spanContext = SpanContext.create( @@ -135,14 +130,15 @@ public void censusHttpExecuteInterceptorShouldInjectHeader() throws IOException } @Test - public void censusHttpRequestInitializerDisallowNullRequest() throws IOException { + void censusHttpRequestInitializerDisallowNullRequest() { HttpRequestInitializer initializer = censusHttpModule.getHttpRequestInitializer(null); - thrown.expect(NullPointerException.class); - initializer.initialize(null); + assertThrows( + NullPointerException.class, + () -> initializer.initialize(null)); } @Test - public void censusHttpRequestInitializerShouldExecuteOriginal() throws IOException { + void censusHttpRequestInitializerShouldExecuteOriginal() throws IOException { HttpRequestInitializer mockOriginalInitializer = createMock(HttpRequestInitializer.class); HttpRequestInitializer censusInitializer = censusHttpModule.getHttpRequestInitializer(mockOriginalInitializer); @@ -153,7 +149,7 @@ public void censusHttpRequestInitializerShouldExecuteOriginal() throws IOExcepti } @Test - public void censusHttpRequestInitializerShouldSetInterceptor() throws IOException { + void censusHttpRequestInitializerShouldSetInterceptor() throws IOException { censusHttpModule.getHttpRequestInitializer(null).initialize(httpRequest); assertThat(httpRequest.getInterceptor()) .isInstanceOf(CensusHttpModule.CensusHttpExecuteInterceptor.class); From 1c7634d926c567f0cf2be52e4aa2b5f048494242 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 15:22:53 -0400 Subject: [PATCH 33/43] change tests --- .../cloud/http/HttpTransportOptionsTest.java | 40 +++++++++---------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java b/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java index 75ffc2bf17..254bfb8f28 100644 --- a/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java +++ b/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java @@ -16,11 +16,11 @@ package com.google.cloud.http; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; @@ -50,10 +50,10 @@ import java.util.Set; import java.util.regex.Pattern; import org.easymock.EasyMock; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class HttpTransportOptionsTest { +class HttpTransportOptionsTest { private static final HttpTransport MOCK_HTTP_TRANSPORT = new MockHttpTransport() { @Override @@ -88,8 +88,8 @@ public LowLevelHttpResponse execute() { private Credentials customCredentials; private HttpRequest defaultHttpRequest; - @Before - public void setup() throws IOException { + @BeforeEach + void setup() throws IOException { defaultHeaderProvider = EasyMock.createMock(HeaderProvider.class); EasyMock.expect(defaultHeaderProvider.getHeaders()).andReturn(new HashMap<>()); @@ -109,7 +109,7 @@ public void setup() throws IOException { } @Test - public void testBuilder() { + void testBuilder() { assertEquals(1234, OPTIONS.getConnectTimeout()); assertSame(MOCK_HTTP_TRANSPORT_FACTORY, OPTIONS.getHttpTransportFactory()); assertEquals(5678, OPTIONS.getReadTimeout()); @@ -119,19 +119,19 @@ public void testBuilder() { } @Test - public void testBaseEquals() { + void testBaseEquals() { assertEquals(OPTIONS, OPTIONS_COPY); assertNotEquals(DEFAULT_OPTIONS, OPTIONS); } @Test - public void testBaseHashCode() { + void testBaseHashCode() { assertEquals(OPTIONS.hashCode(), OPTIONS_COPY.hashCode()); assertNotEquals(DEFAULT_OPTIONS.hashCode(), OPTIONS.hashCode()); } @Test - public void testHeader() { + void testHeader() { String expectedHeaderPattern = "^gl-java/.+ gccl/.* gax/.+"; ServiceOptions serviceOptions = EasyMock.createMock(ServiceOptions.class); HeaderProvider headerProvider = @@ -145,7 +145,7 @@ public void testHeader() { } @Test - public void testHttpRequestInitializer_defaultUniverseDomainSettings_defaultCredentials() + void testHttpRequestInitializer_defaultUniverseDomainSettings_defaultCredentials() throws IOException { TestServiceOptions testServiceOptions = generateTestServiceOptions(Credentials.GOOGLE_DEFAULT_UNIVERSE, defaultCredentials); @@ -156,7 +156,7 @@ public void testHttpRequestInitializer_defaultUniverseDomainSettings_defaultCred } @Test - public void testHttpRequestInitializer_defaultUniverseDomainSettings_customCredentials() { + void testHttpRequestInitializer_defaultUniverseDomainSettings_customCredentials() { TestServiceOptions testServiceOptions = generateTestServiceOptions(Credentials.GOOGLE_DEFAULT_UNIVERSE, customCredentials); HttpRequestInitializer httpRequestInitializer = @@ -171,7 +171,7 @@ public void testHttpRequestInitializer_defaultUniverseDomainSettings_customCrede } @Test - public void testHttpRequestInitializer_customUniverseDomainSettings_defaultCredentials() { + void testHttpRequestInitializer_customUniverseDomainSettings_defaultCredentials() { TestServiceOptions testServiceOptions = generateTestServiceOptions(CUSTOM_UNIVERSE_DOMAIN, defaultCredentials); HttpRequestInitializer httpRequestInitializer = @@ -186,7 +186,7 @@ public void testHttpRequestInitializer_customUniverseDomainSettings_defaultCrede } @Test - public void testHttpRequestInitializer_customUniverseDomainSettings_customCredentials() + void testHttpRequestInitializer_customUniverseDomainSettings_customCredentials() throws IOException { TestServiceOptions testServiceOptions = generateTestServiceOptions(CUSTOM_UNIVERSE_DOMAIN, customCredentials); @@ -197,7 +197,7 @@ public void testHttpRequestInitializer_customUniverseDomainSettings_customCreden } @Test - public void testHttpRequestInitializer_defaultUniverseDomainSettings_noCredentials() + void testHttpRequestInitializer_defaultUniverseDomainSettings_noCredentials() throws IOException { NoCredentials noCredentials = NoCredentials.getInstance(); TestServiceOptions testServiceOptions = @@ -209,7 +209,7 @@ public void testHttpRequestInitializer_defaultUniverseDomainSettings_noCredentia } @Test - public void testHttpRequestInitializer_customUniverseDomainSettings_noCredentials() { + void testHttpRequestInitializer_customUniverseDomainSettings_noCredentials() { NoCredentials noCredentials = NoCredentials.getInstance(); TestServiceOptions testServiceOptions = generateTestServiceOptions(CUSTOM_UNIVERSE_DOMAIN, noCredentials); From 8ab4f9d7a661c311949b4e0990e48c4ba24766ce Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 15:26:20 -0400 Subject: [PATCH 34/43] remove junit4 rules and tests --- .../testing/junit4/MultipleAttemptsRule.java | 107 ---------- .../testing/junit4/StdErrCaptureRule.java | 56 ------ .../testing/junit4/StdOutCaptureRule.java | 56 ------ .../cloud/testing/junit4/StdXCaptureRule.java | 188 ------------------ .../testing/junit4/StdXCaptureRuleTest.java | 76 ------- .../tests/MultipleAttemptsRuleTest.java | 87 -------- .../junit4/tests/StdErrCaptureRuleTest.java | 36 ---- .../junit4/tests/StdOutCaptureRuleTest.java | 36 ---- 8 files changed, 642 deletions(-) delete mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/MultipleAttemptsRule.java delete mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdErrCaptureRule.java delete mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdOutCaptureRule.java delete mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRule.java delete mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRuleTest.java delete mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/MultipleAttemptsRuleTest.java delete mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdErrCaptureRuleTest.java delete mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdOutCaptureRuleTest.java diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/MultipleAttemptsRule.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/MultipleAttemptsRule.java deleted file mode 100644 index 86fd82c7b9..0000000000 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/MultipleAttemptsRule.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.cloud.testing.junit4; - -import static com.google.common.base.Preconditions.checkArgument; - -import java.util.ArrayList; -import java.util.List; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.MultipleFailureException; -import org.junit.runners.model.Statement; - -/** - * A JUnit rule that allows multiple attempts of a test execution before ultimately reporting - * failure for the test. Attempts will be attempted with an exponential backoff which defaults to a - * starting duration of 1 second. - * - *

If after the maximum number of attempts the test has still not succeeded, all failures will be - * propagated as the result of the test allowing all errors to be visible (regardless if they are - * the same failure or different ones). - * - *

To use this rule add the field declaration to your JUnit 4 Test class: - * - *

Note: It is important that the field is public - * - *

{@code
- * @Rule
- * public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3);
- * }
- * - * @see org.junit.Rule - */ -public final class MultipleAttemptsRule implements TestRule { - private final long initialBackoffMillis; - private final int maxAttemptCount; - - /** - * Construct a {@link MultipleAttemptsRule} which will attempt a test up to {@code attemptCount} - * times before ultimately reporting failure of the test. - * - *

The initialBackoffMillis will be set to 1000L. - * - * @param maxAttemptCount max number of attempts before reporting failure, must be greater than 0 - * @see #MultipleAttemptsRule(int, long) - */ - public MultipleAttemptsRule(int maxAttemptCount) { - this(maxAttemptCount, 1000L); - } - - /** - * Construct a {@link MultipleAttemptsRule} which will attempt a test up to {@code attemptCount} - * times before ultimately reporting failure of the test. - * - *

The {@code initialBackoffMillis} will be used as the first pause duration before - * reattempting the test. - * - * @param maxAttemptCount max number of attempts before reporting failure, must be greater than 0 - * @param initialBackoffMillis initial duration in millis to wait between attempts, must be - * greater than or equal to 0 - */ - public MultipleAttemptsRule(int maxAttemptCount, long initialBackoffMillis) { - checkArgument(maxAttemptCount > 0, "attemptCount must be > 0"); - checkArgument(initialBackoffMillis >= 0, "initialBackoffMillis must be >= 0"); - this.initialBackoffMillis = initialBackoffMillis; - this.maxAttemptCount = maxAttemptCount; - } - - @Override - public Statement apply(final Statement base, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - List failures = new ArrayList<>(); - - long retryIntervalMillis = initialBackoffMillis; - - for (int i = 1; i <= maxAttemptCount; i++) { - try { - base.evaluate(); - return; - } catch (Throwable t) { - failures.add(t); - Thread.sleep(retryIntervalMillis); - retryIntervalMillis *= 1.5f; - } - } - - MultipleFailureException.assertEmpty(failures); - } - }; - } -} diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdErrCaptureRule.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdErrCaptureRule.java deleted file mode 100644 index 1640d950e3..0000000000 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdErrCaptureRule.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.cloud.testing.junit4; - -import java.io.PrintStream; -import org.junit.Rule; - -/** - * A JUnit rule that allows the capturing stderr (i.e. {@link System#err} during the scope of a - * test. - * - *

Note: If some part of the system holds a reference System.err before this rule is loaded - * into the test lifecycle there is no way for this rule to capture the output. Ensure this rule is - * declared as high in your test file as possible, and ordered using {@link Rule#order()} before - * other Rules if necessary. - * - *

To use this rule add the field declaration to your JUnit 4 Test class: - * - *

Note: It is important that the field is public - * - *

{@code
- * @Rule
- * public StdErrCaptureRule stdErrCaptureRule = new StdErrCaptureRule();
- * }
- * - * @see org.junit.Rule - * @see Rule#order() - */ -public final class StdErrCaptureRule extends StdXCaptureRule { - - public StdErrCaptureRule() {} - - @Override - protected PrintStream getOriginal() { - return System.err; - } - - @Override - protected void set(PrintStream ps) { - System.setErr(ps); - } -} diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdOutCaptureRule.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdOutCaptureRule.java deleted file mode 100644 index 0a33997cde..0000000000 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdOutCaptureRule.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.cloud.testing.junit4; - -import java.io.PrintStream; -import org.junit.Rule; - -/** - * A JUnit rule that allows the capturing stdout (i.e. {@link System#out} during the scope of a - * test. - * - *

Note: If some part of the system holds a reference System.out before this rule is loaded - * into the test lifecycle there is no way for this rule to capture the output. Ensure this rule is - * declared as high in your test file as possible, and ordered using {@link Rule#order()} before - * other Rules if necessary. - * - *

To use this rule add the field declaration to your JUnit 4 Test class: - * - *

Note: It is important that the field is public - * - *

{@code
- * @Rule
- * public StdOutCaptureRule stdOutCaptureRule = new StdOutCaptureRule();
- * }
- * - * @see org.junit.Rule - * @see Rule#order() - */ -public final class StdOutCaptureRule extends StdXCaptureRule { - - public StdOutCaptureRule() {} - - @Override - protected PrintStream getOriginal() { - return System.out; - } - - @Override - protected void set(PrintStream ps) { - System.setOut(ps); - } -} diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRule.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRule.java deleted file mode 100644 index ba17e3e324..0000000000 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRule.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.cloud.testing.junit4; - -import com.google.common.base.Charsets; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -abstract class StdXCaptureRule implements TestRule { - - private final ByteArrayOutputStream byteArrayOutputStream; - - public StdXCaptureRule() { - byteArrayOutputStream = new ByteArrayOutputStream(); - } - - protected abstract PrintStream getOriginal(); - - protected abstract void set(PrintStream ps); - - /** - * Get a handle to the raw bytes written during the running test so far. - * - * @return A read-only {@link ByteArrayOutputStream} representing the raw bytes written so far. - *

Note the following behavior of the return value: - *

    - *
  1. Calling any "write" method call will result in an {@link IllegalStateException} - *
  2. Calls to {@link ByteArrayOutputStream#toByteArray()} will result in a new copy of the - * underlying array up to that point - *
  3. Calls to {@link ByteArrayOutputStream#flush()} will be silently ignored - *
  4. Calls to {@link ByteArrayOutputStream#close()} will be silently ignored - *
- */ - public ByteArrayOutputStream getCapturedOutput() { - return new ReadOnlyByteArrayOutputStream(byteArrayOutputStream); - } - - /** - * Return a UTF-8 {@link String} of all bytes written during the running test so far. - * - * @return UTF-8 {@link String} of all bytes written - */ - public String getCapturedOutputAsUtf8String() { - return new String(byteArrayOutputStream.toByteArray(), Charsets.UTF_8); - } - - @Override - public Statement apply(final Statement base, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - PrintStream originalOut = getOriginal(); - TeeOutputStream tee = new TeeOutputStream(System.out, byteArrayOutputStream); - boolean outReplaced = false; - try { - set(new PrintStream(tee)); - outReplaced = true; - base.evaluate(); - } finally { - if (outReplaced) { - set(originalOut); - } - } - } - }; - } - - private static final class TeeOutputStream extends OutputStream { - private final OutputStream left; - private final OutputStream right; - - public TeeOutputStream(OutputStream left, OutputStream right) { - this.left = left; - this.right = right; - } - - @Override - public void write(int b) throws IOException { - try { - left.write(b); - } finally { - right.write(b); - } - } - - @Override - public void flush() throws IOException { - try { - left.flush(); - } finally { - right.flush(); - } - } - } - - private static final class ReadOnlyByteArrayOutputStream extends ByteArrayOutputStream { - private final ByteArrayOutputStream delegate; - - public ReadOnlyByteArrayOutputStream(ByteArrayOutputStream delegate) { - this.delegate = delegate; - } - - @Override - public synchronized void write(int b) { - throw getIllegalStateException("write(b)"); - } - - @Override - public synchronized void write(byte[] b, int off, int len) { - throw getIllegalStateException("write(byte[], off, len)"); - } - - @Override - public synchronized void writeTo(OutputStream out) { - throw getIllegalStateException("writeOt(out)"); - } - - @Override - public synchronized void reset() { - throw getIllegalStateException("reset()"); - } - - @Override - public synchronized byte[] toByteArray() { - return delegate.toByteArray(); - } - - @Override - public void close() { - // ignore - } - - @Override - public synchronized int size() { - return delegate.size(); - } - - @Override - public synchronized String toString() { - return delegate.toString(); - } - - @Override - public synchronized String toString(String charsetName) throws UnsupportedEncodingException { - return delegate.toString(charsetName); - } - - @SuppressWarnings("deprecation") - @Override - public synchronized String toString(int hibyte) { - return delegate.toString(hibyte); - } - - @Override - public void flush() { - // ignore - } - - @Override - public void write(byte[] b) { - throw getIllegalStateException("write(byte[])"); - } - - private IllegalStateException getIllegalStateException(String desc) { - return new IllegalStateException(desc + " is forbidden"); - } - } -} diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRuleTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRuleTest.java deleted file mode 100644 index 17d167e1af..0000000000 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRuleTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.cloud.testing.junit4; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.io.PrintStream; -import org.junit.Test; - -public final class StdXCaptureRuleTest { - - @Test(expected = IllegalStateException.class) - public void returnedByteArrayOutputStreamIsReadOnly_writeByte() { - getStdXCaptureRule().getCapturedOutput().write(0); - } - - @Test(expected = IllegalStateException.class) - public void returnedByteArrayOutputStreamIsReadOnly_writeByteArray() throws IOException { - getStdXCaptureRule().getCapturedOutput().write(new byte[] {0}); - } - - @Test(expected = IllegalStateException.class) - public void returnedByteArrayOutputStreamIsReadOnly_writeByteArrayRange() { - getStdXCaptureRule().getCapturedOutput().write(new byte[] {0}, 0, 1); - } - - @Test(expected = IllegalStateException.class) - public void returnedByteArrayOutputStreamIsReadOnly_writeTo() throws IOException { - getStdXCaptureRule().getCapturedOutput().writeTo(System.out); - } - - @Test(expected = IllegalStateException.class) - public void returnedByteArrayOutputStreamIsReadOnly_reset() { - getStdXCaptureRule().getCapturedOutput().reset(); - } - - @Test - public void returnedByteArrayOutputStreamIsReadOnly_close() throws IOException { - getStdXCaptureRule().getCapturedOutput().close(); - } - - @Test - public void returnedByteArrayOutputStreamIsReadOnly_flush() throws IOException { - getStdXCaptureRule().getCapturedOutput().flush(); - } - - private static StdXCaptureRule getStdXCaptureRule() { - return new StdXCaptureRule() { - @Override - protected PrintStream getOriginal() { - fail("unexpected call"); - return null; - } - - @Override - protected void set(PrintStream ps) { - fail("unexpected call"); - } - }; - } -} diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/MultipleAttemptsRuleTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/MultipleAttemptsRuleTest.java deleted file mode 100644 index e1c98b1953..0000000000 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/MultipleAttemptsRuleTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.cloud.testing.junit4.tests; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import com.google.cloud.testing.junit4.MultipleAttemptsRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runners.model.MultipleFailureException; -import org.junit.runners.model.Statement; - -public final class MultipleAttemptsRuleTest { - - private static final int NUMBER_OF_ATTEMPTS = 5; - - @Rule public MultipleAttemptsRule rr = new MultipleAttemptsRule(NUMBER_OF_ATTEMPTS, 0); - - private int numberAttempted = 0; - - @Test - public void wontPassUntil5() { - numberAttempted += 1; - assertEquals(NUMBER_OF_ATTEMPTS, numberAttempted); - } - - @Test(expected = IllegalArgumentException.class) - public void errorConstructing_attemptLessThan1() { - new MultipleAttemptsRule(0); - } - - @Test - public void errorConstructing_attemptEquals1() { - new MultipleAttemptsRule(1); - } - - @Test(expected = IllegalArgumentException.class) - public void errorConstructing_attemptGreaterThanOrEqualTo1AndBackoffLessThan0() { - new MultipleAttemptsRule(1, -1); - } - - @Test - public void errorConstructing_attemptGreaterThanOrEqualTo1AndBackoffEqualTo0() { - new MultipleAttemptsRule(1, 0); - } - - @Test - public void allErrorPropagated() { - MultipleAttemptsRule rule = new MultipleAttemptsRule(3, 0); - Statement statement = - rule.apply( - new Statement() { - private int counter = 1; - - @Override - public void evaluate() { - fail("attempt " + counter++); - } - }, - null); - - try { - statement.evaluate(); - } catch (MultipleFailureException mfe) { - // pass - assertThat(mfe.getFailures()).hasSize(3); - } catch (Throwable throwable) { - fail("unexpected error: " + throwable.getMessage()); - } - } -} diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdErrCaptureRuleTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdErrCaptureRuleTest.java deleted file mode 100644 index 565bb08f12..0000000000 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdErrCaptureRuleTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.cloud.testing.junit4.tests; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.testing.junit4.StdErrCaptureRule; -import org.junit.Rule; -import org.junit.Test; - -public class StdErrCaptureRuleTest { - - @Rule public StdErrCaptureRule stdOutCap = new StdErrCaptureRule(); - - @Test - public void captureSuccessful() { - System.err.println("err world"); - String expected = "err world" + System.lineSeparator(); - String actual = stdOutCap.getCapturedOutputAsUtf8String(); - assertEquals(expected, actual); - } -} diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdOutCaptureRuleTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdOutCaptureRuleTest.java deleted file mode 100644 index 8230debded..0000000000 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdOutCaptureRuleTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.cloud.testing.junit4.tests; - -import static org.junit.Assert.assertEquals; - -import com.google.cloud.testing.junit4.StdOutCaptureRule; -import org.junit.Rule; -import org.junit.Test; - -public class StdOutCaptureRuleTest { - - @Rule public StdOutCaptureRule stdOutCap = new StdOutCaptureRule(); - - @Test - public void captureSuccessful() { - System.out.println("hello world"); - String expected = "hello world" + System.lineSeparator(); - String actual = stdOutCap.getCapturedOutputAsUtf8String(); - assertEquals(expected, actual); - } -} From aa2128689f91e3f3edf2a1ab5cca9acef05509e4 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 15:31:25 -0400 Subject: [PATCH 35/43] lint --- .../google/cloud/grpc/SharedResourceHolderTest.java | 4 ++-- .../com/google/cloud/http/CensusHttpModuleTest.java | 8 ++------ .../google/cloud/http/HttpTransportOptionsTest.java | 3 +-- .../java/com/google/cloud/BaseWriteChannelTest.java | 10 ++++------ .../java/com/google/cloud/ExceptionHandlerTest.java | 8 ++------ .../test/java/com/google/cloud/ServiceOptionsTest.java | 9 +++------ .../src/test/java/com/google/cloud/StringEnumTest.java | 3 +-- 7 files changed, 15 insertions(+), 30 deletions(-) diff --git a/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/SharedResourceHolderTest.java b/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/SharedResourceHolderTest.java index 574a64b414..3e1ceee9ef 100644 --- a/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/SharedResourceHolderTest.java +++ b/java-core/google-cloud-core-grpc/src/test/java/com/google/cloud/grpc/SharedResourceHolderTest.java @@ -42,8 +42,8 @@ /** * This class was copied from grpc-core to prevent dependence on an unstable API that may be subject - * to changes - * (SharedResourceHolderTest) + * to changes (SharedResourceHolderTest) * *

Unit tests for {@link SharedResourceHolder}. */ diff --git a/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/CensusHttpModuleTest.java b/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/CensusHttpModuleTest.java index e766c02d55..0ac860c820 100644 --- a/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/CensusHttpModuleTest.java +++ b/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/CensusHttpModuleTest.java @@ -89,9 +89,7 @@ void implementationOfDefaultTextFormatSetter() { @Test void censusHttpExecuteInterceptorDisallowNullRequest() { HttpExecuteInterceptor interceptor = censusHttpModule.new CensusHttpExecuteInterceptor(null); - assertThrows( - NullPointerException.class, - () -> interceptor.intercept(null)); + assertThrows(NullPointerException.class, () -> interceptor.intercept(null)); } @Test @@ -132,9 +130,7 @@ void censusHttpExecuteInterceptorShouldInjectHeader() throws IOException { @Test void censusHttpRequestInitializerDisallowNullRequest() { HttpRequestInitializer initializer = censusHttpModule.getHttpRequestInitializer(null); - assertThrows( - NullPointerException.class, - () -> initializer.initialize(null)); + assertThrows(NullPointerException.class, () -> initializer.initialize(null)); } @Test diff --git a/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java b/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java index 254bfb8f28..1697a0c43f 100644 --- a/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java +++ b/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java @@ -197,8 +197,7 @@ void testHttpRequestInitializer_customUniverseDomainSettings_customCredentials() } @Test - void testHttpRequestInitializer_defaultUniverseDomainSettings_noCredentials() - throws IOException { + void testHttpRequestInitializer_defaultUniverseDomainSettings_noCredentials() throws IOException { NoCredentials noCredentials = NoCredentials.getInstance(); TestServiceOptions testServiceOptions = generateTestServiceOptions(Credentials.GOOGLE_DEFAULT_UNIVERSE, noCredentials); diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseWriteChannelTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseWriteChannelTest.java index 0bc83b1eb1..847531f715 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseWriteChannelTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseWriteChannelTest.java @@ -17,12 +17,12 @@ package com.google.cloud; import static com.google.common.truth.Truth.assertThat; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.cloud.spi.ServiceRpcFactory; import java.io.IOException; @@ -100,9 +100,7 @@ void testClose() throws IOException { @Test public void testValidateOpen() throws IOException { channel.close(); - assertThrows( - ClosedChannelException.class, - () -> channel.write(ByteBuffer.allocate(42))); + assertThrows(ClosedChannelException.class, () -> channel.write(ByteBuffer.allocate(42))); } @Test diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/ExceptionHandlerTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/ExceptionHandlerTest.java index 1cc34425d7..f5efcdd3d1 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/ExceptionHandlerTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/ExceptionHandlerTest.java @@ -185,9 +185,7 @@ public RetryResult afterEval(Exception exception, RetryResult retryResult) { }; ExceptionHandler handler = ExceptionHandler.newBuilder().addInterceptors(interceptor).build(); - assertThrows( - NullPointerException.class, - () -> handler.shouldRetry(new Exception(), null)); + assertThrows(NullPointerException.class, () -> handler.shouldRetry(new Exception(), null)); } @Test @@ -208,8 +206,6 @@ public RetryResult afterEval(Exception exception, RetryResult retryResult) { }; ExceptionHandler handler = ExceptionHandler.newBuilder().addInterceptors(interceptor).build(); - assertThrows( - NullPointerException.class, - () -> handler.shouldRetry(new Exception(), null)); + assertThrows(NullPointerException.class, () -> handler.shouldRetry(new Exception(), null)); } } diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java index 48c1ae0b94..a82208d8e0 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java @@ -589,8 +589,7 @@ void testIsValidUniverseDomain_noUserUniverseDomainConfig_defaultCredentials() // No User Configuration = GDU, non Default Credentials = random.com // non-GDU Credentials could be any domain, the tests use random.com @Test - void testIsValidUniverseDomain_noUserUniverseDomainConfig_nonGDUCredentials() - throws IOException { + void testIsValidUniverseDomain_noUserUniverseDomainConfig_nonGDUCredentials() throws IOException { TestServiceOptions options = TestServiceOptions.newBuilder() .setProjectId("project-id") @@ -603,8 +602,7 @@ void testIsValidUniverseDomain_noUserUniverseDomainConfig_nonGDUCredentials() // User Configuration = random.com, Default Credentials = GDU // User Credentials could be set to any domain, the tests use random.com @Test - void testIsValidUniverseDomain_userUniverseDomainConfig_defaultCredentials() - throws IOException { + void testIsValidUniverseDomain_userUniverseDomainConfig_defaultCredentials() throws IOException { TestServiceOptions options = TestServiceOptions.newBuilder() .setProjectId("project-id") @@ -619,8 +617,7 @@ void testIsValidUniverseDomain_userUniverseDomainConfig_defaultCredentials() // User Credentials and non GDU Credentials could be set to any domain, // the tests use random.com @Test - void testIsValidUniverseDomain_userUniverseDomainConfig_nonGDUCredentials() - throws IOException { + void testIsValidUniverseDomain_userUniverseDomainConfig_nonGDUCredentials() throws IOException { TestServiceOptions options = TestServiceOptions.newBuilder() .setProjectId("project-id") diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/StringEnumTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/StringEnumTest.java index a5812776f8..3a74f6c5d2 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/StringEnumTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/StringEnumTest.java @@ -68,8 +68,7 @@ public static Letter[] values() { @Test void testNullClass() { assertThrows( - NullPointerException.class, - () -> new StringEnumType(null, Letter.CONSTRUCTOR)); + NullPointerException.class, () -> new StringEnumType(null, Letter.CONSTRUCTOR)); } @Test From 6b64111f52797846f173ab9148a943841df780b7 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 15:40:25 -0400 Subject: [PATCH 36/43] change to public --- .../src/test/java/com/google/cloud/BaseSerializationTest.java | 2 +- .../src/test/java/com/google/cloud/SerializationTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java index 036998f767..be297fea9f 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java @@ -35,7 +35,7 @@ * for proper serialization. Both methods can return {@code null} if no such object needs to be * tested. */ -abstract class BaseSerializationTest { +public abstract class BaseSerializationTest { /** Returns all objects for which correct serialization must be tested. */ protected abstract Serializable[] serializableObjects(); diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java index 20e164d417..6c35c665b5 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java @@ -25,7 +25,7 @@ import java.io.Serializable; import org.threeten.bp.Duration; -class SerializationTest extends BaseSerializationTest { +public class SerializationTest extends BaseSerializationTest { private static final BaseServiceException BASE_SERVICE_EXCEPTION = new BaseServiceException(ExceptionData.from(42, "message", "reason", false)); From bd6e6b4fd83d6ecd2c58fd912320e497bf8a6dd3 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Wed, 8 May 2024 16:54:16 -0400 Subject: [PATCH 37/43] Revert "remove junit4 rules and tests" This reverts commit 8ab4f9d7a661c311949b4e0990e48c4ba24766ce. --- .../testing/junit4/MultipleAttemptsRule.java | 107 ++++++++++ .../testing/junit4/StdErrCaptureRule.java | 56 ++++++ .../testing/junit4/StdOutCaptureRule.java | 56 ++++++ .../cloud/testing/junit4/StdXCaptureRule.java | 188 ++++++++++++++++++ .../testing/junit4/StdXCaptureRuleTest.java | 76 +++++++ .../tests/MultipleAttemptsRuleTest.java | 87 ++++++++ .../junit4/tests/StdErrCaptureRuleTest.java | 36 ++++ .../junit4/tests/StdOutCaptureRuleTest.java | 36 ++++ 8 files changed, 642 insertions(+) create mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/MultipleAttemptsRule.java create mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdErrCaptureRule.java create mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdOutCaptureRule.java create mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRule.java create mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRuleTest.java create mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/MultipleAttemptsRuleTest.java create mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdErrCaptureRuleTest.java create mode 100644 java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdOutCaptureRuleTest.java diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/MultipleAttemptsRule.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/MultipleAttemptsRule.java new file mode 100644 index 0000000000..86fd82c7b9 --- /dev/null +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/MultipleAttemptsRule.java @@ -0,0 +1,107 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.testing.junit4; + +import static com.google.common.base.Preconditions.checkArgument; + +import java.util.ArrayList; +import java.util.List; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.MultipleFailureException; +import org.junit.runners.model.Statement; + +/** + * A JUnit rule that allows multiple attempts of a test execution before ultimately reporting + * failure for the test. Attempts will be attempted with an exponential backoff which defaults to a + * starting duration of 1 second. + * + *

If after the maximum number of attempts the test has still not succeeded, all failures will be + * propagated as the result of the test allowing all errors to be visible (regardless if they are + * the same failure or different ones). + * + *

To use this rule add the field declaration to your JUnit 4 Test class: + * + *

Note: It is important that the field is public + * + *

{@code
+ * @Rule
+ * public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3);
+ * }
+ * + * @see org.junit.Rule + */ +public final class MultipleAttemptsRule implements TestRule { + private final long initialBackoffMillis; + private final int maxAttemptCount; + + /** + * Construct a {@link MultipleAttemptsRule} which will attempt a test up to {@code attemptCount} + * times before ultimately reporting failure of the test. + * + *

The initialBackoffMillis will be set to 1000L. + * + * @param maxAttemptCount max number of attempts before reporting failure, must be greater than 0 + * @see #MultipleAttemptsRule(int, long) + */ + public MultipleAttemptsRule(int maxAttemptCount) { + this(maxAttemptCount, 1000L); + } + + /** + * Construct a {@link MultipleAttemptsRule} which will attempt a test up to {@code attemptCount} + * times before ultimately reporting failure of the test. + * + *

The {@code initialBackoffMillis} will be used as the first pause duration before + * reattempting the test. + * + * @param maxAttemptCount max number of attempts before reporting failure, must be greater than 0 + * @param initialBackoffMillis initial duration in millis to wait between attempts, must be + * greater than or equal to 0 + */ + public MultipleAttemptsRule(int maxAttemptCount, long initialBackoffMillis) { + checkArgument(maxAttemptCount > 0, "attemptCount must be > 0"); + checkArgument(initialBackoffMillis >= 0, "initialBackoffMillis must be >= 0"); + this.initialBackoffMillis = initialBackoffMillis; + this.maxAttemptCount = maxAttemptCount; + } + + @Override + public Statement apply(final Statement base, Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + List failures = new ArrayList<>(); + + long retryIntervalMillis = initialBackoffMillis; + + for (int i = 1; i <= maxAttemptCount; i++) { + try { + base.evaluate(); + return; + } catch (Throwable t) { + failures.add(t); + Thread.sleep(retryIntervalMillis); + retryIntervalMillis *= 1.5f; + } + } + + MultipleFailureException.assertEmpty(failures); + } + }; + } +} diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdErrCaptureRule.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdErrCaptureRule.java new file mode 100644 index 0000000000..1640d950e3 --- /dev/null +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdErrCaptureRule.java @@ -0,0 +1,56 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.testing.junit4; + +import java.io.PrintStream; +import org.junit.Rule; + +/** + * A JUnit rule that allows the capturing stderr (i.e. {@link System#err} during the scope of a + * test. + * + *

Note: If some part of the system holds a reference System.err before this rule is loaded + * into the test lifecycle there is no way for this rule to capture the output. Ensure this rule is + * declared as high in your test file as possible, and ordered using {@link Rule#order()} before + * other Rules if necessary. + * + *

To use this rule add the field declaration to your JUnit 4 Test class: + * + *

Note: It is important that the field is public + * + *

{@code
+ * @Rule
+ * public StdErrCaptureRule stdErrCaptureRule = new StdErrCaptureRule();
+ * }
+ * + * @see org.junit.Rule + * @see Rule#order() + */ +public final class StdErrCaptureRule extends StdXCaptureRule { + + public StdErrCaptureRule() {} + + @Override + protected PrintStream getOriginal() { + return System.err; + } + + @Override + protected void set(PrintStream ps) { + System.setErr(ps); + } +} diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdOutCaptureRule.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdOutCaptureRule.java new file mode 100644 index 0000000000..0a33997cde --- /dev/null +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdOutCaptureRule.java @@ -0,0 +1,56 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.testing.junit4; + +import java.io.PrintStream; +import org.junit.Rule; + +/** + * A JUnit rule that allows the capturing stdout (i.e. {@link System#out} during the scope of a + * test. + * + *

Note: If some part of the system holds a reference System.out before this rule is loaded + * into the test lifecycle there is no way for this rule to capture the output. Ensure this rule is + * declared as high in your test file as possible, and ordered using {@link Rule#order()} before + * other Rules if necessary. + * + *

To use this rule add the field declaration to your JUnit 4 Test class: + * + *

Note: It is important that the field is public + * + *

{@code
+ * @Rule
+ * public StdOutCaptureRule stdOutCaptureRule = new StdOutCaptureRule();
+ * }
+ * + * @see org.junit.Rule + * @see Rule#order() + */ +public final class StdOutCaptureRule extends StdXCaptureRule { + + public StdOutCaptureRule() {} + + @Override + protected PrintStream getOriginal() { + return System.out; + } + + @Override + protected void set(PrintStream ps) { + System.setOut(ps); + } +} diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRule.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRule.java new file mode 100644 index 0000000000..ba17e3e324 --- /dev/null +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRule.java @@ -0,0 +1,188 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.testing.junit4; + +import com.google.common.base.Charsets; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.UnsupportedEncodingException; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + +abstract class StdXCaptureRule implements TestRule { + + private final ByteArrayOutputStream byteArrayOutputStream; + + public StdXCaptureRule() { + byteArrayOutputStream = new ByteArrayOutputStream(); + } + + protected abstract PrintStream getOriginal(); + + protected abstract void set(PrintStream ps); + + /** + * Get a handle to the raw bytes written during the running test so far. + * + * @return A read-only {@link ByteArrayOutputStream} representing the raw bytes written so far. + *

Note the following behavior of the return value: + *

    + *
  1. Calling any "write" method call will result in an {@link IllegalStateException} + *
  2. Calls to {@link ByteArrayOutputStream#toByteArray()} will result in a new copy of the + * underlying array up to that point + *
  3. Calls to {@link ByteArrayOutputStream#flush()} will be silently ignored + *
  4. Calls to {@link ByteArrayOutputStream#close()} will be silently ignored + *
+ */ + public ByteArrayOutputStream getCapturedOutput() { + return new ReadOnlyByteArrayOutputStream(byteArrayOutputStream); + } + + /** + * Return a UTF-8 {@link String} of all bytes written during the running test so far. + * + * @return UTF-8 {@link String} of all bytes written + */ + public String getCapturedOutputAsUtf8String() { + return new String(byteArrayOutputStream.toByteArray(), Charsets.UTF_8); + } + + @Override + public Statement apply(final Statement base, Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + PrintStream originalOut = getOriginal(); + TeeOutputStream tee = new TeeOutputStream(System.out, byteArrayOutputStream); + boolean outReplaced = false; + try { + set(new PrintStream(tee)); + outReplaced = true; + base.evaluate(); + } finally { + if (outReplaced) { + set(originalOut); + } + } + } + }; + } + + private static final class TeeOutputStream extends OutputStream { + private final OutputStream left; + private final OutputStream right; + + public TeeOutputStream(OutputStream left, OutputStream right) { + this.left = left; + this.right = right; + } + + @Override + public void write(int b) throws IOException { + try { + left.write(b); + } finally { + right.write(b); + } + } + + @Override + public void flush() throws IOException { + try { + left.flush(); + } finally { + right.flush(); + } + } + } + + private static final class ReadOnlyByteArrayOutputStream extends ByteArrayOutputStream { + private final ByteArrayOutputStream delegate; + + public ReadOnlyByteArrayOutputStream(ByteArrayOutputStream delegate) { + this.delegate = delegate; + } + + @Override + public synchronized void write(int b) { + throw getIllegalStateException("write(b)"); + } + + @Override + public synchronized void write(byte[] b, int off, int len) { + throw getIllegalStateException("write(byte[], off, len)"); + } + + @Override + public synchronized void writeTo(OutputStream out) { + throw getIllegalStateException("writeOt(out)"); + } + + @Override + public synchronized void reset() { + throw getIllegalStateException("reset()"); + } + + @Override + public synchronized byte[] toByteArray() { + return delegate.toByteArray(); + } + + @Override + public void close() { + // ignore + } + + @Override + public synchronized int size() { + return delegate.size(); + } + + @Override + public synchronized String toString() { + return delegate.toString(); + } + + @Override + public synchronized String toString(String charsetName) throws UnsupportedEncodingException { + return delegate.toString(charsetName); + } + + @SuppressWarnings("deprecation") + @Override + public synchronized String toString(int hibyte) { + return delegate.toString(hibyte); + } + + @Override + public void flush() { + // ignore + } + + @Override + public void write(byte[] b) { + throw getIllegalStateException("write(byte[])"); + } + + private IllegalStateException getIllegalStateException(String desc) { + return new IllegalStateException(desc + " is forbidden"); + } + } +} diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRuleTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRuleTest.java new file mode 100644 index 0000000000..17d167e1af --- /dev/null +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/StdXCaptureRuleTest.java @@ -0,0 +1,76 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.testing.junit4; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.io.PrintStream; +import org.junit.Test; + +public final class StdXCaptureRuleTest { + + @Test(expected = IllegalStateException.class) + public void returnedByteArrayOutputStreamIsReadOnly_writeByte() { + getStdXCaptureRule().getCapturedOutput().write(0); + } + + @Test(expected = IllegalStateException.class) + public void returnedByteArrayOutputStreamIsReadOnly_writeByteArray() throws IOException { + getStdXCaptureRule().getCapturedOutput().write(new byte[] {0}); + } + + @Test(expected = IllegalStateException.class) + public void returnedByteArrayOutputStreamIsReadOnly_writeByteArrayRange() { + getStdXCaptureRule().getCapturedOutput().write(new byte[] {0}, 0, 1); + } + + @Test(expected = IllegalStateException.class) + public void returnedByteArrayOutputStreamIsReadOnly_writeTo() throws IOException { + getStdXCaptureRule().getCapturedOutput().writeTo(System.out); + } + + @Test(expected = IllegalStateException.class) + public void returnedByteArrayOutputStreamIsReadOnly_reset() { + getStdXCaptureRule().getCapturedOutput().reset(); + } + + @Test + public void returnedByteArrayOutputStreamIsReadOnly_close() throws IOException { + getStdXCaptureRule().getCapturedOutput().close(); + } + + @Test + public void returnedByteArrayOutputStreamIsReadOnly_flush() throws IOException { + getStdXCaptureRule().getCapturedOutput().flush(); + } + + private static StdXCaptureRule getStdXCaptureRule() { + return new StdXCaptureRule() { + @Override + protected PrintStream getOriginal() { + fail("unexpected call"); + return null; + } + + @Override + protected void set(PrintStream ps) { + fail("unexpected call"); + } + }; + } +} diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/MultipleAttemptsRuleTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/MultipleAttemptsRuleTest.java new file mode 100644 index 0000000000..e1c98b1953 --- /dev/null +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/MultipleAttemptsRuleTest.java @@ -0,0 +1,87 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.testing.junit4.tests; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import com.google.cloud.testing.junit4.MultipleAttemptsRule; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runners.model.MultipleFailureException; +import org.junit.runners.model.Statement; + +public final class MultipleAttemptsRuleTest { + + private static final int NUMBER_OF_ATTEMPTS = 5; + + @Rule public MultipleAttemptsRule rr = new MultipleAttemptsRule(NUMBER_OF_ATTEMPTS, 0); + + private int numberAttempted = 0; + + @Test + public void wontPassUntil5() { + numberAttempted += 1; + assertEquals(NUMBER_OF_ATTEMPTS, numberAttempted); + } + + @Test(expected = IllegalArgumentException.class) + public void errorConstructing_attemptLessThan1() { + new MultipleAttemptsRule(0); + } + + @Test + public void errorConstructing_attemptEquals1() { + new MultipleAttemptsRule(1); + } + + @Test(expected = IllegalArgumentException.class) + public void errorConstructing_attemptGreaterThanOrEqualTo1AndBackoffLessThan0() { + new MultipleAttemptsRule(1, -1); + } + + @Test + public void errorConstructing_attemptGreaterThanOrEqualTo1AndBackoffEqualTo0() { + new MultipleAttemptsRule(1, 0); + } + + @Test + public void allErrorPropagated() { + MultipleAttemptsRule rule = new MultipleAttemptsRule(3, 0); + Statement statement = + rule.apply( + new Statement() { + private int counter = 1; + + @Override + public void evaluate() { + fail("attempt " + counter++); + } + }, + null); + + try { + statement.evaluate(); + } catch (MultipleFailureException mfe) { + // pass + assertThat(mfe.getFailures()).hasSize(3); + } catch (Throwable throwable) { + fail("unexpected error: " + throwable.getMessage()); + } + } +} diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdErrCaptureRuleTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdErrCaptureRuleTest.java new file mode 100644 index 0000000000..565bb08f12 --- /dev/null +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdErrCaptureRuleTest.java @@ -0,0 +1,36 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.testing.junit4.tests; + +import static org.junit.Assert.assertEquals; + +import com.google.cloud.testing.junit4.StdErrCaptureRule; +import org.junit.Rule; +import org.junit.Test; + +public class StdErrCaptureRuleTest { + + @Rule public StdErrCaptureRule stdOutCap = new StdErrCaptureRule(); + + @Test + public void captureSuccessful() { + System.err.println("err world"); + String expected = "err world" + System.lineSeparator(); + String actual = stdOutCap.getCapturedOutputAsUtf8String(); + assertEquals(expected, actual); + } +} diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdOutCaptureRuleTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdOutCaptureRuleTest.java new file mode 100644 index 0000000000..8230debded --- /dev/null +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/junit4/tests/StdOutCaptureRuleTest.java @@ -0,0 +1,36 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.testing.junit4.tests; + +import static org.junit.Assert.assertEquals; + +import com.google.cloud.testing.junit4.StdOutCaptureRule; +import org.junit.Rule; +import org.junit.Test; + +public class StdOutCaptureRuleTest { + + @Rule public StdOutCaptureRule stdOutCap = new StdOutCaptureRule(); + + @Test + public void captureSuccessful() { + System.out.println("hello world"); + String expected = "hello world" + System.lineSeparator(); + String actual = stdOutCap.getCapturedOutputAsUtf8String(); + assertEquals(expected, actual); + } +} From 905d3c457ee53d916357335361d26b533336fb5f Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Fri, 10 May 2024 08:47:31 -0400 Subject: [PATCH 38/43] Revert "change tests" This reverts commit db78162daba9de5fd8b149665255d51e98d14a49. --- .../java/com/google/cloud/BaseSerializationTest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java index be297fea9f..5dcd1726bb 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java @@ -17,8 +17,8 @@ package com.google.cloud; import static com.google.common.base.MoreObjects.firstNonNull; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -26,7 +26,7 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; -import org.junit.jupiter.api.Test; +import org.junit.Test; /** * Base class for serialization tests. To use this class in your tests override the {@code @@ -44,7 +44,7 @@ public abstract class BaseSerializationTest { protected abstract Restorable[] restorableObjects(); @Test - void testSerializableObjects() throws Exception { + public void testSerializableObjects() throws Exception { for (Serializable obj : firstNonNull(serializableObjects(), new Serializable[0])) { Object copy = serializeAndDeserialize(obj); assertEquals(obj, obj); @@ -57,7 +57,7 @@ void testSerializableObjects() throws Exception { } @Test - void testRestorableObjects() throws Exception { + public void testRestorableObjects() throws Exception { for (Restorable restorable : firstNonNull(restorableObjects(), new Restorable[0])) { RestorableState state = restorable.capture(); RestorableState deserializedState = serializeAndDeserialize(state); From c02f7a2ae7aeb3897361decc2ba2c8ede6448eae Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Fri, 10 May 2024 13:20:03 -0400 Subject: [PATCH 39/43] add comment to BaseSerializationTest --- .../src/test/java/com/google/cloud/BaseSerializationTest.java | 4 ++++ java-core/pom.xml | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java index 5dcd1726bb..422ecf7777 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java @@ -34,6 +34,10 @@ * {@code restorableObjects()} method to return all restorable objects whose state must be tested * for proper serialization. Both methods can return {@code null} if no such object needs to be * tested. + *

+ * This class has not migrated to Junit 5 because downstream libraries, e.g., java-logging, + * are extending this class and these libraries still use Junit 4. + * Migrating this class to Junit 5 will cause test failures in downstream libraries. */ public abstract class BaseSerializationTest { diff --git a/java-core/pom.xml b/java-core/pom.xml index 4b4daa8900..e2dd8a86be 100644 --- a/java-core/pom.xml +++ b/java-core/pom.xml @@ -37,6 +37,7 @@ pom import + org.junit junit-bom @@ -44,7 +45,6 @@ pom import - com.google.truth truth From 67cb1c6085f826396bdd62cd778590d701cb892d Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Fri, 10 May 2024 13:24:56 -0400 Subject: [PATCH 40/43] lint --- .../test/java/com/google/cloud/BaseSerializationTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java index 422ecf7777..bbc13770ae 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/BaseSerializationTest.java @@ -34,10 +34,10 @@ * {@code restorableObjects()} method to return all restorable objects whose state must be tested * for proper serialization. Both methods can return {@code null} if no such object needs to be * tested. - *

- * This class has not migrated to Junit 5 because downstream libraries, e.g., java-logging, - * are extending this class and these libraries still use Junit 4. - * Migrating this class to Junit 5 will cause test failures in downstream libraries. + * + *

This class has not migrated to Junit 5 because downstream libraries, e.g., java-logging, are + * extending this class and these libraries still use Junit 4. Migrating this class to Junit 5 will + * cause test failures in downstream libraries. */ public abstract class BaseSerializationTest { From d3d6af29aaab425fe3e7e72ef6899eb3b24df599 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Mon, 13 May 2024 09:23:40 -0400 Subject: [PATCH 41/43] add junit version in pom parent --- gapic-generator-java-pom-parent/pom.xml | 1 + java-core/pom.xml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/gapic-generator-java-pom-parent/pom.xml b/gapic-generator-java-pom-parent/pom.xml index 2157e1f410..71cf74980b 100644 --- a/gapic-generator-java-pom-parent/pom.xml +++ b/gapic-generator-java-pom-parent/pom.xml @@ -37,6 +37,7 @@ 2.27.1 3.0.0 1.6.9 + 5.10.2 diff --git a/java-core/pom.xml b/java-core/pom.xml index e2dd8a86be..1401604d60 100644 --- a/java-core/pom.xml +++ b/java-core/pom.xml @@ -41,7 +41,7 @@ org.junit junit-bom - 5.10.2 + ${junit.version} pom import From 74f94f224453b9e3f2e85f69b69a65a2aa926a83 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Tue, 14 May 2024 15:29:04 -0400 Subject: [PATCH 42/43] add junit to third party dependency --- java-core/pom.xml | 7 ------- java-shared-dependencies/third-party-dependencies/pom.xml | 7 +++++++ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/java-core/pom.xml b/java-core/pom.xml index 1401604d60..c495b742ec 100644 --- a/java-core/pom.xml +++ b/java-core/pom.xml @@ -38,13 +38,6 @@ import - - org.junit - junit-bom - ${junit.version} - pom - import - com.google.truth truth diff --git a/java-shared-dependencies/third-party-dependencies/pom.xml b/java-shared-dependencies/third-party-dependencies/pom.xml index e6dccf5fd2..07b9828ada 100644 --- a/java-shared-dependencies/third-party-dependencies/pom.xml +++ b/java-shared-dependencies/third-party-dependencies/pom.xml @@ -198,6 +198,13 @@ detector-resources-support ${google.cloud.opentelemetry.version} + + org.junit + junit-bom + ${junit.version} + pom + import + From 1bc09d94caf8992131ef326705b4590d50a16ac8 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Thu, 16 May 2024 14:44:18 -0400 Subject: [PATCH 43/43] code refactor according to code review --- .../com/google/cloud/ServiceOptionsTest.java | 3 +- .../java/com/google/cloud/TimestampTest.java | 59 +++++++------------ .../com/google/cloud/testing/VersionTest.java | 39 ++---------- 3 files changed, 28 insertions(+), 73 deletions(-) diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java index a82208d8e0..e4d22d9b5f 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java @@ -19,6 +19,7 @@ import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -385,7 +386,7 @@ void testBuilderNoCredentials() { assertEquals(NoCredentials.getInstance(), OPTIONS_NO_CREDENTIALS.getCredentials()); assertEquals(NoCredentials.getInstance(), OPTIONS_NO_CREDENTIALS.getCredentials()); assertNotEquals(NoCredentials.getInstance(), OPTIONS.getCredentials()); - assertNotEquals(null, NoCredentials.getInstance()); + assertNotNull(NoCredentials.getInstance()); assertSame(TEST_CLOCK, OPTIONS_NO_CREDENTIALS.getClock()); assertEquals("host", OPTIONS_NO_CREDENTIALS.getHost()); assertEquals("project-id", OPTIONS_NO_CREDENTIALS.getProjectId()); diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/TimestampTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/TimestampTest.java index 8a01d4b242..ba2ad5b701 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/TimestampTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/TimestampTest.java @@ -19,7 +19,7 @@ import static com.google.common.testing.SerializableTester.reserializeAndAssert; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.testing.EqualsTester; import java.util.Calendar; @@ -27,7 +27,6 @@ import java.util.GregorianCalendar; import java.util.TimeZone; import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** Unit tests for {@link com.google.cloud.Timestamp}. */ @@ -155,62 +154,44 @@ void toFromSqlTimestamp() { @Test void boundsSecondsMin() { - try { - Timestamp.ofTimeSecondsAndNanos(Timestamp.MIN_VALUE.getSeconds() - 1, 999999999); - Assertions.fail(); - } catch (IllegalArgumentException ex) { - assertNotNull(ex.getMessage()); - } + assertThrows( + IllegalArgumentException.class, + () -> Timestamp.ofTimeSecondsAndNanos(Timestamp.MIN_VALUE.getSeconds() - 1, 999999999)); } @Test void boundsSecondsMax() { - try { - Timestamp.ofTimeSecondsAndNanos(Timestamp.MAX_VALUE.getSeconds() + 1, 0); - Assertions.fail(); - } catch (IllegalArgumentException ex) { - assertNotNull(ex.getMessage()); - } + assertThrows( + IllegalArgumentException.class, + () -> Timestamp.ofTimeSecondsAndNanos(Timestamp.MAX_VALUE.getSeconds() + 1, 0)); } @Test void boundsNanosMin() { - try { - Timestamp.ofTimeSecondsAndNanos(TEST_TIME_SECONDS, -1); - Assertions.fail(); - } catch (IllegalArgumentException ex) { - assertNotNull(ex.getMessage()); - } + assertThrows( + IllegalArgumentException.class, + () -> Timestamp.ofTimeSecondsAndNanos(TEST_TIME_SECONDS, -1)); } @Test void boundsNanosMax() { - try { - Timestamp.ofTimeSecondsAndNanos(TEST_TIME_SECONDS, 1000000000); - Assertions.fail(); - } catch (IllegalArgumentException ex) { - assertNotNull(ex.getMessage()); - } + assertThrows( + IllegalArgumentException.class, + () -> Timestamp.ofTimeSecondsAndNanos(TEST_TIME_SECONDS, 1000000000)); } @Test void boundsSqlTimestampMin() { - try { - Timestamp.of(new java.sql.Timestamp((Timestamp.MIN_VALUE.getSeconds() - 1) * 1000)); - Assertions.fail(); - } catch (IllegalArgumentException ex) { - assertNotNull(ex.getMessage()); - } + assertThrows( + IllegalArgumentException.class, + () -> Timestamp.of(new java.sql.Timestamp((Timestamp.MIN_VALUE.getSeconds() - 1) * 1000))); } @Test void boundsSqlTimestampMax() { - try { - Timestamp.of(new java.sql.Timestamp((Timestamp.MAX_VALUE.getSeconds() + 1) * 1000)); - Assertions.fail(); - } catch (IllegalArgumentException ex) { - assertNotNull(ex.getMessage()); - } + assertThrows( + IllegalArgumentException.class, + () -> Timestamp.of(new java.sql.Timestamp((Timestamp.MAX_VALUE.getSeconds() + 1) * 1000))); } @Test @@ -297,7 +278,7 @@ void comparable() { } @Test - void serialization() throws Exception { + void serialization() { reserializeAndAssert(Timestamp.parseTimestamp("9999-12-31T23:59:59.999999999Z")); } } diff --git a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/VersionTest.java b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/VersionTest.java index 2d5e69fe46..2b5405c9bf 100644 --- a/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/VersionTest.java +++ b/java-core/google-cloud-core/src/test/java/com/google/cloud/testing/VersionTest.java @@ -17,11 +17,9 @@ package com.google.cloud.testing; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class VersionTest { @@ -40,52 +38,27 @@ void testFromString() { @Test void testFromStringWithAlphas() { - try { - Version.fromString("2016.01.hello"); - Assertions.fail(); - } catch (IllegalArgumentException ex) { - assertNotNull(ex.getMessage()); - } + assertThrows(IllegalArgumentException.class, () -> Version.fromString("2016.01.hello")); } @Test void testFromStringMissingPatch() { - try { - Version.fromString("2016.01"); - Assertions.fail(); - } catch (IllegalArgumentException ex) { - assertNotNull(ex.getMessage()); - } + assertThrows(IllegalArgumentException.class, () -> Version.fromString("2016.01")); } @Test void testFromStringMissingMinor() { - try { - Version.fromString("2016"); - Assertions.fail(); - } catch (IllegalArgumentException ex) { - assertNotNull(ex.getMessage()); - } + assertThrows(IllegalArgumentException.class, () -> Version.fromString("2016")); } @Test void testFromStringEmpty() { - try { - Version.fromString(""); - Assertions.fail(); - } catch (IllegalArgumentException ex) { - assertNotNull(ex.getMessage()); - } + assertThrows(IllegalArgumentException.class, () -> Version.fromString("")); } @Test void testFromStringNull() { - try { - Version.fromString(null); - Assertions.fail(); - } catch (NullPointerException ex) { - assertNull(ex.getMessage()); - } + assertThrows(NullPointerException.class, () -> Version.fromString(null)); } @Test