diff --git a/airbyte-bootloader/src/test/java/io/airbyte/bootloader/BootloaderAppTest.java b/airbyte-bootloader/src/test/java/io/airbyte/bootloader/BootloaderAppTest.java index 38366c889537..54455dae445d 100644 --- a/airbyte-bootloader/src/test/java/io/airbyte/bootloader/BootloaderAppTest.java +++ b/airbyte-bootloader/src/test/java/io/airbyte/bootloader/BootloaderAppTest.java @@ -52,8 +52,9 @@ import uk.org.webcompere.systemstubs.jupiter.SystemStub; import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; +@SuppressWarnings("PMD.AvoidUsingHardCodedIP") @ExtendWith(SystemStubsExtension.class) -public class BootloaderAppTest { +class BootloaderAppTest { private PostgreSQLContainer container; private DataSource configsDataSource; diff --git a/airbyte-bootloader/src/test/java/io/airbyte/bootloader/SecretMigratorTest.java b/airbyte-bootloader/src/test/java/io/airbyte/bootloader/SecretMigratorTest.java index a023bb75184f..2557031ccc5f 100644 --- a/airbyte-bootloader/src/test/java/io/airbyte/bootloader/SecretMigratorTest.java +++ b/airbyte-bootloader/src/test/java/io/airbyte/bootloader/SecretMigratorTest.java @@ -34,7 +34,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class SecretMigratorTest { +class SecretMigratorTest { private final UUID workspaceId = UUID.randomUUID(); @@ -55,7 +55,7 @@ void setup() { } @Test - public void testMigrateSecret() throws JsonValidationException, IOException { + void testMigrateSecret() throws JsonValidationException, IOException { final JsonNode sourceSpec = Jsons.jsonNode("sourceSpec"); final UUID sourceDefinitionId = UUID.randomUUID(); final StandardSourceDefinition standardSourceDefinition = new StandardSourceDefinition() diff --git a/airbyte-commons/src/main/java/io/airbyte/commons/concurrency/GracefulShutdownHandler.java b/airbyte-commons/src/main/java/io/airbyte/commons/concurrency/GracefulShutdownHandler.java index 265d3bd11ee8..809ecf22d00d 100644 --- a/airbyte-commons/src/main/java/io/airbyte/commons/concurrency/GracefulShutdownHandler.java +++ b/airbyte-commons/src/main/java/io/airbyte/commons/concurrency/GracefulShutdownHandler.java @@ -18,7 +18,7 @@ public class GracefulShutdownHandler extends Thread { public GracefulShutdownHandler(final Duration terminateWaitDuration, final ExecutorService... threadPools) { this.terminateWaitDuration = terminateWaitDuration; - this.threadPools = threadPools; + this.threadPools = threadPools.clone(); } @Override diff --git a/airbyte-commons/src/main/java/io/airbyte/commons/json/JsonSchemas.java b/airbyte-commons/src/main/java/io/airbyte/commons/json/JsonSchemas.java index 30b1fbb86696..2273ad8f4021 100644 --- a/airbyte-commons/src/main/java/io/airbyte/commons/json/JsonSchemas.java +++ b/airbyte-commons/src/main/java/io/airbyte/commons/json/JsonSchemas.java @@ -167,6 +167,7 @@ public static List> collectPathsThatMeetCondition(final Js * the node from the root of the object passed at the root level invocation * */ + @SuppressWarnings("PMD.ForLoopCanBeForeach") private static void traverseJsonSchemaInternal(final JsonNode jsonSchemaNode, final List path, final BiConsumer> consumer) { diff --git a/airbyte-commons/src/main/java/io/airbyte/commons/json/Jsons.java b/airbyte-commons/src/main/java/io/airbyte/commons/json/Jsons.java index 3ed694a98256..b221c36aea9b 100644 --- a/airbyte-commons/src/main/java/io/airbyte/commons/json/Jsons.java +++ b/airbyte-commons/src/main/java/io/airbyte/commons/json/Jsons.java @@ -34,6 +34,7 @@ import java.util.function.BiConsumer; import java.util.stream.Collectors; +@SuppressWarnings("PMD.AvoidReassigningParameters") public class Jsons { // Object Mapper is thread-safe @@ -222,6 +223,7 @@ public static int getIntOrZero(final JsonNode json, final List keys) { /** * Flattens an ObjectNode, or dumps it into a {null: value} map if it's not an object. */ + @SuppressWarnings("PMD.ForLoopCanBeForeach") public static Map flatten(final JsonNode node) { if (node.isObject()) { final Map output = new HashMap<>(); diff --git a/airbyte-commons/src/test/java/io/airbyte/commons/concurrency/GracefulShutdownHandlerTest.java b/airbyte-commons/src/test/java/io/airbyte/commons/concurrency/GracefulShutdownHandlerTest.java index f14a7bb5ea19..dad814168d17 100644 --- a/airbyte-commons/src/test/java/io/airbyte/commons/concurrency/GracefulShutdownHandlerTest.java +++ b/airbyte-commons/src/test/java/io/airbyte/commons/concurrency/GracefulShutdownHandlerTest.java @@ -14,7 +14,7 @@ class GracefulShutdownHandlerTest { @Test - public void testRun() throws InterruptedException { + void testRun() throws InterruptedException { final ExecutorService executorService = mock(ExecutorService.class); final GracefulShutdownHandler gracefulShutdownHandler = new GracefulShutdownHandler(Duration.ofSeconds(30), executorService); gracefulShutdownHandler.start(); diff --git a/airbyte-commons/src/test/java/io/airbyte/commons/enums/EnumsTest.java b/airbyte-commons/src/test/java/io/airbyte/commons/enums/EnumsTest.java index 7f8ccf618f0c..e96589e6ea90 100644 --- a/airbyte-commons/src/test/java/io/airbyte/commons/enums/EnumsTest.java +++ b/airbyte-commons/src/test/java/io/airbyte/commons/enums/EnumsTest.java @@ -34,12 +34,12 @@ enum E4 { } @Test - public void testConversion() { + void testConversion() { Assertions.assertEquals(E2.TEST, convertTo(E1.TEST, E2.class)); } @Test - public void testConversionFails() { + void testConversionFails() { Assertions.assertThrows(IllegalArgumentException.class, () -> convertTo(E1.TEST2, E2.class)); } diff --git a/airbyte-commons/src/test/java/io/airbyte/commons/io/IOsTest.java b/airbyte-commons/src/test/java/io/airbyte/commons/io/IOsTest.java index bf950894cd9f..f17902f48828 100644 --- a/airbyte-commons/src/test/java/io/airbyte/commons/io/IOsTest.java +++ b/airbyte-commons/src/test/java/io/airbyte/commons/io/IOsTest.java @@ -47,20 +47,20 @@ void testWriteBytes() throws IOException { } @Test - public void testWriteFileToRandomDir() throws IOException { + void testWriteFileToRandomDir() throws IOException { final String contents = "something to remember"; final String tmpFilePath = IOs.writeFileToRandomTmpDir("file.txt", contents); assertEquals(contents, Files.readString(Path.of(tmpFilePath))); } @Test - public void testGetTailDoesNotExist() throws IOException { + void testGetTailDoesNotExist() throws IOException { final List tail = IOs.getTail(100, Path.of(RandomStringUtils.randomAlphanumeric(100))); assertEquals(Collections.emptyList(), tail); } @Test - public void testGetTailExists() throws IOException { + void testGetTailExists() throws IOException { final Path stdoutFile = Files.createTempFile("job-history-handler-test", "stdout"); final List head = List.of( diff --git a/airbyte-commons/src/test/java/io/airbyte/commons/json/JsonSchemasTest.java b/airbyte-commons/src/test/java/io/airbyte/commons/json/JsonSchemasTest.java index 9a814017a20c..42b2ea12dc33 100644 --- a/airbyte-commons/src/test/java/io/airbyte/commons/json/JsonSchemasTest.java +++ b/airbyte-commons/src/test/java/io/airbyte/commons/json/JsonSchemasTest.java @@ -21,6 +21,7 @@ import org.mockito.InOrder; import org.mockito.Mockito; +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") class JsonSchemasTest { @Test diff --git a/airbyte-commons/src/test/java/io/airbyte/commons/lang/CloseableShutdownHookTest.java b/airbyte-commons/src/test/java/io/airbyte/commons/lang/CloseableShutdownHookTest.java index 2d3da2360122..cb7568ce3427 100644 --- a/airbyte-commons/src/test/java/io/airbyte/commons/lang/CloseableShutdownHookTest.java +++ b/airbyte-commons/src/test/java/io/airbyte/commons/lang/CloseableShutdownHookTest.java @@ -11,7 +11,7 @@ import java.io.InputStream; import org.junit.jupiter.api.Test; -public class CloseableShutdownHookTest { +class CloseableShutdownHookTest { @Test void testRegisteringShutdownHook() throws Exception { diff --git a/airbyte-commons/src/test/java/io/airbyte/commons/lang/ExceptionsTest.java b/airbyte-commons/src/test/java/io/airbyte/commons/lang/ExceptionsTest.java index 05be8afcaeaa..840744f683c8 100644 --- a/airbyte-commons/src/test/java/io/airbyte/commons/lang/ExceptionsTest.java +++ b/airbyte-commons/src/test/java/io/airbyte/commons/lang/ExceptionsTest.java @@ -12,6 +12,7 @@ import java.util.List; import org.junit.jupiter.api.Test; +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") class ExceptionsTest { @Test diff --git a/airbyte-commons/src/test/java/io/airbyte/commons/logging/Log4j2ConfigTest.java b/airbyte-commons/src/test/java/io/airbyte/commons/logging/Log4j2ConfigTest.java index 35248eee2d13..3879bfd37879 100644 --- a/airbyte-commons/src/test/java/io/airbyte/commons/logging/Log4j2ConfigTest.java +++ b/airbyte-commons/src/test/java/io/airbyte/commons/logging/Log4j2ConfigTest.java @@ -20,7 +20,7 @@ import org.slf4j.LoggerFactory; import org.slf4j.MDC; -public class Log4j2ConfigTest { +class Log4j2ConfigTest { private static final Path TEST_ROOT = Path.of("/tmp/airbyte_tests"); private Path root; diff --git a/airbyte-commons/src/test/java/io/airbyte/commons/logging/MdcScopeTest.java b/airbyte-commons/src/test/java/io/airbyte/commons/logging/MdcScopeTest.java index 3daf211c5967..d9a101b8056d 100644 --- a/airbyte-commons/src/test/java/io/airbyte/commons/logging/MdcScopeTest.java +++ b/airbyte-commons/src/test/java/io/airbyte/commons/logging/MdcScopeTest.java @@ -4,7 +4,6 @@ package io.airbyte.commons.logging; -import java.util.HashMap; import java.util.Map; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -12,54 +11,31 @@ import org.junit.jupiter.api.Test; import org.slf4j.MDC; -public class MdcScopeTest { +class MdcScopeTest { - private static final Map originalMap = new HashMap<>() { + private static final Map originalMap = Map.of("test", "entry", "testOverride", "should be overrided"); - { - put("test", "entry"); - put("testOverride", "should be overrided"); - } - - }; - - private static final Map modificationInMDC = new HashMap<>() { - - { - put("new", "will be added"); - put("testOverride", "will override"); - } - - }; + private static final Map modificationInMDC = Map.of("new", "will be added", "testOverride", "will override"); @BeforeEach - public void init() { + void init() { MDC.setContextMap(originalMap); } @Test @DisplayName("The MDC context is properly overrided") - public void testMDCModified() { + void testMDCModified() { try (final MdcScope mdcScope = new MdcScope(modificationInMDC)) { final Map mdcState = MDC.getCopyOfContextMap(); Assertions.assertThat(mdcState).containsExactlyInAnyOrderEntriesOf( - new HashMap() { - - { - put("test", "entry"); - put("new", "will be added"); - put("testOverride", "will override"); - } - - }); - + Map.of("test", "entry", "new", "will be added", "testOverride", "will override")); } } @Test @DisplayName("The MDC context is properly restored") - public void testMDCRestore() { + void testMDCRestore() { try (final MdcScope mdcScope = new MdcScope(modificationInMDC)) {} final Map mdcState = MDC.getCopyOfContextMap(); diff --git a/airbyte-commons/src/test/java/io/airbyte/commons/text/NamesTest.java b/airbyte-commons/src/test/java/io/airbyte/commons/text/NamesTest.java index 6b175b2881e7..6428dad4d9c0 100644 --- a/airbyte-commons/src/test/java/io/airbyte/commons/text/NamesTest.java +++ b/airbyte-commons/src/test/java/io/airbyte/commons/text/NamesTest.java @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test; -public class NamesTest { +class NamesTest { @Test void testToAlphanumericAndUnderscore() { diff --git a/airbyte-commons/src/test/java/io/airbyte/commons/version/AirbyteVersionTest.java b/airbyte-commons/src/test/java/io/airbyte/commons/version/AirbyteVersionTest.java index fc3ae4af3846..5c2a49e1291e 100644 --- a/airbyte-commons/src/test/java/io/airbyte/commons/version/AirbyteVersionTest.java +++ b/airbyte-commons/src/test/java/io/airbyte/commons/version/AirbyteVersionTest.java @@ -11,10 +11,10 @@ import org.junit.jupiter.api.Test; -public class AirbyteVersionTest { +class AirbyteVersionTest { @Test - public void testParseVersion() { + void testParseVersion() { final AirbyteVersion version = new AirbyteVersion("6.7.8"); assertEquals("6", version.getMajorVersion()); assertEquals("7", version.getMinorVersion()); @@ -22,7 +22,7 @@ public void testParseVersion() { } @Test - public void testParseVersionWithLabel() { + void testParseVersionWithLabel() { final AirbyteVersion version = new AirbyteVersion("6.7.8-omega"); assertEquals("6", version.getMajorVersion()); assertEquals("7", version.getMinorVersion()); @@ -30,7 +30,7 @@ public void testParseVersionWithLabel() { } @Test - public void testCompatibleVersionCompareTo() { + void testCompatibleVersionCompareTo() { assertEquals(0, new AirbyteVersion("6.7.8-omega").compatibleVersionCompareTo(new AirbyteVersion("6.7.8-gamma"))); assertEquals(0, new AirbyteVersion("6.7.8-alpha").compatibleVersionCompareTo(new AirbyteVersion("6.7.9-alpha"))); assertTrue(0 < new AirbyteVersion("6.8.0-alpha").compatibleVersionCompareTo(new AirbyteVersion("6.7.8-alpha"))); @@ -42,7 +42,7 @@ public void testCompatibleVersionCompareTo() { } @Test - public void testPatchVersionCompareTo() { + void testPatchVersionCompareTo() { assertEquals(0, new AirbyteVersion("6.7.8-omega").patchVersionCompareTo(new AirbyteVersion("6.7.8-gamma"))); assertTrue(0 > new AirbyteVersion("6.7.8-alpha").patchVersionCompareTo(new AirbyteVersion("6.7.9-alpha"))); assertTrue(0 > new AirbyteVersion("6.7.8-alpha").patchVersionCompareTo(new AirbyteVersion("6.7.11-alpha"))); @@ -55,7 +55,7 @@ public void testPatchVersionCompareTo() { } @Test - public void testGreaterThan() { + void testGreaterThan() { assertFalse(new AirbyteVersion("6.7.8-omega").greaterThan(new AirbyteVersion("6.7.8-gamma"))); assertFalse(new AirbyteVersion("6.7.8-alpha").greaterThan(new AirbyteVersion("6.7.9-alpha"))); assertFalse(new AirbyteVersion("6.7.8-alpha").greaterThan(new AirbyteVersion("6.7.11-alpha"))); @@ -68,7 +68,7 @@ public void testGreaterThan() { } @Test - public void testLessThan() { + void testLessThan() { assertFalse(new AirbyteVersion("6.7.8-omega").lessThan(new AirbyteVersion("6.7.8-gamma"))); assertTrue(new AirbyteVersion("6.7.8-alpha").lessThan(new AirbyteVersion("6.7.9-alpha"))); assertTrue(new AirbyteVersion("6.7.8-alpha").lessThan(new AirbyteVersion("6.7.11-alpha"))); @@ -81,13 +81,13 @@ public void testLessThan() { } @Test - public void testInvalidVersions() { + void testInvalidVersions() { assertThrows(NullPointerException.class, () -> new AirbyteVersion(null)); assertThrows(IllegalArgumentException.class, () -> new AirbyteVersion("0.6")); } @Test - public void testSerialize() { + void testSerialize() { final var devVersion = "dev"; assertEquals(devVersion, new AirbyteVersion(devVersion).serialize()); @@ -96,13 +96,13 @@ public void testSerialize() { } @Test - public void testCheckVersion() { + void testCheckVersion() { AirbyteVersion.assertIsCompatible(new AirbyteVersion("3.2.1"), new AirbyteVersion("3.2.1")); assertThrows(IllegalStateException.class, () -> AirbyteVersion.assertIsCompatible(new AirbyteVersion("1.2.3"), new AirbyteVersion("3.2.1"))); } @Test - public void testCheckOnlyPatchVersion() { + void testCheckOnlyPatchVersion() { assertFalse(new AirbyteVersion("6.7.8").checkOnlyPatchVersionIsUpdatedComparedTo(new AirbyteVersion("6.7.8"))); assertFalse(new AirbyteVersion("6.9.8").checkOnlyPatchVersionIsUpdatedComparedTo(new AirbyteVersion("6.8.9"))); assertFalse(new AirbyteVersion("7.7.8").checkOnlyPatchVersionIsUpdatedComparedTo(new AirbyteVersion("6.7.11"))); diff --git a/airbyte-config/config-models/src/main/java/io/airbyte/config/EnvConfigs.java b/airbyte-config/config-models/src/main/java/io/airbyte/config/EnvConfigs.java index adb6e69edec3..a0daeef82c01 100644 --- a/airbyte-config/config-models/src/main/java/io/airbyte/config/EnvConfigs.java +++ b/airbyte-config/config-models/src/main/java/io/airbyte/config/EnvConfigs.java @@ -710,6 +710,7 @@ public String getMetricClient() { return getEnvOrDefault(METRIC_CLIENT, ""); } + @Override public String getOtelCollectorEndpoint() { return getEnvOrDefault(OTEL_COLLECTOR_ENDPOINT, ""); } diff --git a/airbyte-config/config-models/src/test/java/io/airbyte/config/helpers/StateMessageHelperTest.java b/airbyte-config/config-models/src/test/java/io/airbyte/config/helpers/StateMessageHelperTest.java index fc9f50f3bc53..61d8faa90343 100644 --- a/airbyte-config/config-models/src/test/java/io/airbyte/config/helpers/StateMessageHelperTest.java +++ b/airbyte-config/config-models/src/test/java/io/airbyte/config/helpers/StateMessageHelperTest.java @@ -22,32 +22,32 @@ import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; -public class StateMessageHelperTest { +class StateMessageHelperTest { private static final boolean USE_STREAM_CAPABLE_STATE = true; private static final boolean DONT_USE_STREAM_CAPABALE_STATE = false; @Test - public void testEmpty() { + void testEmpty() { final Optional stateWrapper = StateMessageHelper.getTypedState(null, USE_STREAM_CAPABLE_STATE); Assertions.assertThat(stateWrapper).isEmpty(); } @Test - public void testEmptyList() { + void testEmptyList() { final Optional stateWrapper = StateMessageHelper.getTypedState(Jsons.arrayNode(), USE_STREAM_CAPABLE_STATE); Assertions.assertThat(stateWrapper).isEmpty(); } @Test - public void testLegacy() { + void testLegacy() { final Optional stateWrapper = StateMessageHelper.getTypedState(Jsons.emptyObject(), USE_STREAM_CAPABLE_STATE); Assertions.assertThat(stateWrapper).isNotEmpty(); Assertions.assertThat(stateWrapper.get().getStateType()).isEqualTo(StateType.LEGACY); } @Test - public void testLegacyInList() { + void testLegacyInList() { final JsonNode jsonState = Jsons.jsonNode(List.of(Map.of("Any", "value"))); final Optional stateWrapper = StateMessageHelper.getTypedState(jsonState, USE_STREAM_CAPABLE_STATE); @@ -57,7 +57,7 @@ public void testLegacyInList() { } @Test - public void testLegacyInNewFormat() { + void testLegacyInNewFormat() { final AirbyteStateMessage stateMessage = new AirbyteStateMessage() .withType(AirbyteStateType.LEGACY) .withData(Jsons.emptyObject()); @@ -67,7 +67,7 @@ public void testLegacyInNewFormat() { } @Test - public void testGlobal() { + void testGlobal() { final AirbyteStateMessage stateMessage = new AirbyteStateMessage() .withType(AirbyteStateType.GLOBAL) .withGlobal( @@ -84,7 +84,7 @@ public void testGlobal() { } @Test - public void testGlobalForceLegacy() { + void testGlobalForceLegacy() { final JsonNode legacyState = Jsons.jsonNode(1); final AirbyteStateMessage stateMessage = new AirbyteStateMessage() .withType(AirbyteStateType.GLOBAL) @@ -103,7 +103,7 @@ public void testGlobalForceLegacy() { } @Test - public void testStream() { + void testStream() { final AirbyteStateMessage stateMessage1 = new AirbyteStateMessage() .withType(AirbyteStateType.STREAM) .withStream( @@ -120,7 +120,7 @@ public void testStream() { } @Test - public void testStreamForceLegacy() { + void testStreamForceLegacy() { final JsonNode firstEmittedLegacyState = Jsons.jsonNode(1); final AirbyteStateMessage stateMessage1 = new AirbyteStateMessage() .withType(AirbyteStateType.STREAM) @@ -141,7 +141,7 @@ public void testStreamForceLegacy() { } @Test - public void testInvalidMixedState() { + void testInvalidMixedState() { final AirbyteStateMessage stateMessage1 = new AirbyteStateMessage() .withType(AirbyteStateType.STREAM) .withStream( @@ -161,7 +161,7 @@ public void testInvalidMixedState() { } @Test - public void testDuplicatedGlobalState() { + void testDuplicatedGlobalState() { final AirbyteStateMessage stateMessage1 = new AirbyteStateMessage() .withType(AirbyteStateType.GLOBAL) .withGlobal( @@ -185,7 +185,7 @@ public void testDuplicatedGlobalState() { } @Test - public void testLegacyStateConversion() { + void testLegacyStateConversion() { final StateWrapper stateWrapper = new StateWrapper() .withStateType(StateType.LEGACY) .withLegacyState(Jsons.deserialize("{\"json\": \"blob\"}")); @@ -196,7 +196,7 @@ public void testLegacyStateConversion() { } @Test - public void testGlobalStateConversion() { + void testGlobalStateConversion() { final StateWrapper stateWrapper = new StateWrapper() .withStateType(StateType.GLOBAL) .withGlobal( @@ -225,7 +225,7 @@ public void testGlobalStateConversion() { } @Test - public void testStreamStateConversion() { + void testStreamStateConversion() { final StateWrapper stateWrapper = new StateWrapper() .withStateType(StateType.STREAM) .withStateMessages(Arrays.asList( diff --git a/airbyte-config/config-persistence/src/test/java/io/airbyte/config/persistence/StatePersistenceTest.java b/airbyte-config/config-persistence/src/test/java/io/airbyte/config/persistence/StatePersistenceTest.java index 8985cccec6d4..04d6e9e4f6e1 100644 --- a/airbyte-config/config-persistence/src/test/java/io/airbyte/config/persistence/StatePersistenceTest.java +++ b/airbyte-config/config-persistence/src/test/java/io/airbyte/config/persistence/StatePersistenceTest.java @@ -45,19 +45,19 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class StatePersistenceTest extends BaseDatabaseConfigPersistenceTest { +class StatePersistenceTest extends BaseDatabaseConfigPersistenceTest { private ConfigRepository configRepository; private StatePersistence statePersistence; private UUID connectionId; @Test - public void testReadingNonExistingState() throws IOException { + void testReadingNonExistingState() throws IOException { Assertions.assertTrue(statePersistence.getCurrentState(UUID.randomUUID()).isEmpty()); } @Test - public void testLegacyReadWrite() throws IOException { + void testLegacyReadWrite() throws IOException { final StateWrapper state0 = new StateWrapper() .withStateType(StateType.LEGACY) .withLegacyState(Jsons.deserialize("{\"woot\": \"legacy states is passthrough\"}")); @@ -87,7 +87,7 @@ public void testLegacyReadWrite() throws IOException { } @Test - public void testLegacyMigrationToGlobal() throws IOException { + void testLegacyMigrationToGlobal() throws IOException { final StateWrapper state0 = new StateWrapper() .withStateType(StateType.LEGACY) .withLegacyState(Jsons.deserialize("{\"woot\": \"legacy states is passthrough\"}")); @@ -113,7 +113,7 @@ public void testLegacyMigrationToGlobal() throws IOException { } @Test - public void testLegacyMigrationToStream() throws IOException { + void testLegacyMigrationToStream() throws IOException { final StateWrapper state0 = new StateWrapper() .withStateType(StateType.LEGACY) .withLegacyState(Jsons.deserialize("{\"woot\": \"legacy states is passthrough\"}")); @@ -139,7 +139,7 @@ public void testLegacyMigrationToStream() throws IOException { } @Test - public void testGlobalReadWrite() throws IOException { + void testGlobalReadWrite() throws IOException { final StateWrapper state0 = new StateWrapper() .withStateType(StateType.GLOBAL) .withGlobal(new AirbyteStateMessage() @@ -183,7 +183,7 @@ public void testGlobalReadWrite() throws IOException { } @Test - public void testGlobalPartialReset() throws IOException { + void testGlobalPartialReset() throws IOException { final StateWrapper state0 = new StateWrapper() .withStateType(StateType.GLOBAL) .withGlobal(new AirbyteStateMessage() @@ -242,7 +242,7 @@ public void testGlobalPartialReset() throws IOException { } @Test - public void testGlobalFullReset() throws IOException { + void testGlobalFullReset() throws IOException { final StateWrapper state0 = new StateWrapper() .withStateType(StateType.GLOBAL) .withGlobal(new AirbyteStateMessage() @@ -278,7 +278,7 @@ public void testGlobalFullReset() throws IOException { } @Test - public void testGlobalStateAllowsEmptyNameAndNamespace() throws IOException { + void testGlobalStateAllowsEmptyNameAndNamespace() throws IOException { final StateWrapper state0 = new StateWrapper() .withStateType(StateType.GLOBAL) .withGlobal(new AirbyteStateMessage() @@ -299,7 +299,7 @@ public void testGlobalStateAllowsEmptyNameAndNamespace() throws IOException { } @Test - public void testStreamReadWrite() throws IOException { + void testStreamReadWrite() throws IOException { final StateWrapper state0 = new StateWrapper() .withStateType(StateType.STREAM) .withStateMessages(Arrays.asList( @@ -335,7 +335,7 @@ public void testStreamReadWrite() throws IOException { } @Test - public void testStreamPartialUpdates() throws IOException { + void testStreamPartialUpdates() throws IOException { final StateWrapper state0 = new StateWrapper() .withStateType(StateType.STREAM) .withStateMessages(Arrays.asList( @@ -403,7 +403,7 @@ public void testStreamPartialUpdates() throws IOException { } @Test - public void testStreamFullReset() throws IOException { + void testStreamFullReset() throws IOException { final StateWrapper state0 = new StateWrapper() .withStateType(StateType.STREAM) .withStateMessages(Arrays.asList( @@ -440,7 +440,7 @@ public void testStreamFullReset() throws IOException { } @Test - public void testInconsistentTypeUpdates() throws IOException { + void testInconsistentTypeUpdates() throws IOException { final StateWrapper streamState = new StateWrapper() .withStateType(StateType.STREAM) .withStateMessages(Arrays.asList( @@ -484,7 +484,7 @@ public void testInconsistentTypeUpdates() throws IOException { } @Test - public void testEnumsConversion() { + void testEnumsConversion() { // Making sure StateType we write to the DB and the StateType from the protocols are aligned. // Otherwise, we'll have to dig through runtime errors. Assertions.assertTrue(Enums.isCompatible( @@ -493,7 +493,7 @@ public void testEnumsConversion() { } @Test - public void testStatePersistenceLegacyReadConsistency() throws IOException { + void testStatePersistenceLegacyReadConsistency() throws IOException { final JsonNode jsonState = Jsons.deserialize("{\"my\": \"state\"}"); final State state = new State().withState(jsonState); configRepository.updateConnectionState(connectionId, state); @@ -504,7 +504,7 @@ public void testStatePersistenceLegacyReadConsistency() throws IOException { } @Test - public void testStatePersistenceLegacyWriteConsistency() throws IOException { + void testStatePersistenceLegacyWriteConsistency() throws IOException { final JsonNode jsonState = Jsons.deserialize("{\"my\": \"state\"}"); final StateWrapper stateWrapper = new StateWrapper().withStateType(StateType.LEGACY).withLegacyState(jsonState); statePersistence.updateOrCreateState(connectionId, stateWrapper); @@ -521,7 +521,7 @@ public void testStatePersistenceLegacyWriteConsistency() throws IOException { } @BeforeEach - public void beforeEach() throws DatabaseInitializationException, IOException, JsonValidationException { + void beforeEach() throws DatabaseInitializationException, IOException, JsonValidationException { dataSource = DatabaseConnectionHelper.createDataSource(container); dslContext = DSLContextFactory.create(dataSource, SQLDialect.POSTGRES); flyway = FlywayFactory.create(dataSource, DatabaseConfigPersistenceLoadDataTest.class.getName(), @@ -533,7 +533,7 @@ public void beforeEach() throws DatabaseInitializationException, IOException, Js } @AfterEach - public void afterEach() { + void afterEach() { // Making sure we reset between tests dslContext.dropSchemaIfExists("public").cascade().execute(); dslContext.createSchema("public").execute(); diff --git a/airbyte-config/config-persistence/src/test/java/io/airbyte/config/persistence/split_secrets/VaultSecretPersistenceTest.java b/airbyte-config/config-persistence/src/test/java/io/airbyte/config/persistence/split_secrets/VaultSecretPersistenceTest.java index 44251c5b6070..4780d87559cc 100644 --- a/airbyte-config/config-persistence/src/test/java/io/airbyte/config/persistence/split_secrets/VaultSecretPersistenceTest.java +++ b/airbyte-config/config-persistence/src/test/java/io/airbyte/config/persistence/split_secrets/VaultSecretPersistenceTest.java @@ -14,7 +14,7 @@ import org.junit.jupiter.api.Test; import org.testcontainers.vault.VaultContainer; -public class VaultSecretPersistenceTest { +class VaultSecretPersistenceTest { private VaultSecretPersistence persistence; private String baseCoordinate; diff --git a/airbyte-db/db-lib/src/main/java/io/airbyte/db/AbstractDatabase.java b/airbyte-db/db-lib/src/main/java/io/airbyte/db/AbstractDatabase.java index 555a5fb73053..09294be10b25 100644 --- a/airbyte-db/db-lib/src/main/java/io/airbyte/db/AbstractDatabase.java +++ b/airbyte-db/db-lib/src/main/java/io/airbyte/db/AbstractDatabase.java @@ -13,7 +13,7 @@ * not the responsibility of this class to close the provided {@link javax.sql.DataSource}. This is * to avoid accidentally closing a shared resource. */ -public abstract class AbstractDatabase { +public class AbstractDatabase { private JsonNode sourceConfig; private JsonNode databaseConfig; diff --git a/airbyte-db/db-lib/src/main/java/io/airbyte/db/check/DatabaseAvailabilityCheck.java b/airbyte-db/db-lib/src/main/java/io/airbyte/db/check/DatabaseAvailabilityCheck.java index 70230e6ca499..e79b5a29523e 100644 --- a/airbyte-db/db-lib/src/main/java/io/airbyte/db/check/DatabaseAvailabilityCheck.java +++ b/airbyte-db/db-lib/src/main/java/io/airbyte/db/check/DatabaseAvailabilityCheck.java @@ -28,6 +28,7 @@ public interface DatabaseAvailabilityCheck extends DatabaseCheck { * * @throws DatabaseCheckException if unable to perform the check. */ + @Override default void check() throws DatabaseCheckException { var initialized = false; var totalTime = 0; diff --git a/airbyte-db/db-lib/src/main/java/io/airbyte/db/factory/FlywayFactory.java b/airbyte-db/db-lib/src/main/java/io/airbyte/db/factory/FlywayFactory.java index 5be30133ea27..c1a499129b26 100644 --- a/airbyte-db/db-lib/src/main/java/io/airbyte/db/factory/FlywayFactory.java +++ b/airbyte-db/db-lib/src/main/java/io/airbyte/db/factory/FlywayFactory.java @@ -12,6 +12,7 @@ * instances. This class will be removed once the project has been converted to leverage an * application framework to manage the creation and injection of {@link Flyway} objects. */ +@SuppressWarnings("PMD.AvoidUsingHardCodedIP") public class FlywayFactory { static final String MIGRATION_TABLE_FORMAT = "airbyte_%s_migrations"; diff --git a/airbyte-db/db-lib/src/main/java/io/airbyte/db/instance/jobs/JobsFlywayMigrationDatabase.java b/airbyte-db/db-lib/src/main/java/io/airbyte/db/instance/jobs/JobsFlywayMigrationDatabase.java index 31cf5ccf0e46..b9e21c339bb3 100644 --- a/airbyte-db/db-lib/src/main/java/io/airbyte/db/instance/jobs/JobsFlywayMigrationDatabase.java +++ b/airbyte-db/db-lib/src/main/java/io/airbyte/db/instance/jobs/JobsFlywayMigrationDatabase.java @@ -45,6 +45,7 @@ protected String[] getMigrationFileLocations() { return new String[] {JobsDatabaseMigrator.MIGRATION_FILE_LOCATION}; } + @Override protected void initializeDatabase(final DSLContext dslContext) throws DatabaseInitializationException, IOException { final String initialSchema = MoreResources.readResource(DatabaseConstants.JOBS_SCHEMA_PATH); DatabaseCheckFactory.createJobsDatabaseInitializer(dslContext, DatabaseConstants.DEFAULT_CONNECTION_TIMEOUT_MS, initialSchema).initialize(); diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/PgLsnTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/PgLsnTest.java index a7cb7e563ea0..352e8b778742 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/PgLsnTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/PgLsnTest.java @@ -10,6 +10,7 @@ import java.util.Map; import org.junit.jupiter.api.Test; +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") class PgLsnTest { private static final Map TEST_LSNS = ImmutableMap.builder() diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/init/impl/JobsDatabaseInitializerTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/init/impl/JobsDatabaseInitializerTest.java index 72271eb0cef7..22ce7eb496f1 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/init/impl/JobsDatabaseInitializerTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/init/impl/JobsDatabaseInitializerTest.java @@ -20,7 +20,7 @@ /** * Test suite for the {@link JobsDatabaseInitializer} class. */ -public class JobsDatabaseInitializerTest extends CommonDatabaseInitializerTest { +class JobsDatabaseInitializerTest extends CommonDatabaseInitializerTest { @Test void testInitializingSchema() throws IOException { diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/ConfigsDatabaseMigratorTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/ConfigsDatabaseMigratorTest.java index 81d01f0feba8..5d82e2d15f59 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/ConfigsDatabaseMigratorTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/ConfigsDatabaseMigratorTest.java @@ -11,12 +11,13 @@ import org.flywaydb.core.Flyway; import org.junit.jupiter.api.Test; -public class ConfigsDatabaseMigratorTest extends AbstractConfigsDatabaseTest { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class ConfigsDatabaseMigratorTest extends AbstractConfigsDatabaseTest { private static final String SCHEMA_DUMP_FILE = "src/main/resources/configs_database/schema_dump.txt"; @Test - public void dumpSchema() throws IOException { + void dumpSchema() throws IOException { final Flyway flyway = FlywayFactory.create(getDataSource(), getClass().getSimpleName(), ConfigsDatabaseMigrator.DB_IDENTIFIER, ConfigsDatabaseMigrator.MIGRATION_FILE_LOCATION); final DatabaseMigrator migrator = new ConfigsDatabaseMigrator(database, flyway); diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_30_22_001__Store_last_sync_state_test.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_30_22_001__Store_last_sync_state_test.java index 431c7e95dfd4..115098ad53c3 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_30_22_001__Store_last_sync_state_test.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_30_22_001__Store_last_sync_state_test.java @@ -54,6 +54,7 @@ import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.Timeout; +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class V0_30_22_001__Store_last_sync_state_test extends AbstractConfigsDatabaseTest { @@ -88,13 +89,13 @@ class V0_30_22_001__Store_last_sync_state_test extends AbstractConfigsDatabaseTe @BeforeEach @Timeout(value = 2, unit = TimeUnit.MINUTES) - public void setupJobDatabase() throws DatabaseInitializationException, IOException { + void setupJobDatabase() throws DatabaseInitializationException, IOException { jobDatabase = new JobsDatabaseTestProvider(dslContext, null).create(false); } @Test @Order(10) - public void testGetJobsDatabase() { + void testGetJobsDatabase() { assertTrue(V0_30_22_001__Store_last_sync_state.getJobsDatabase("", "", "").isEmpty()); // when there is database environment variable, return the database @@ -109,7 +110,7 @@ public void testGetJobsDatabase() { @Test @Order(20) - public void testGetStandardSyncStates() throws Exception { + void testGetStandardSyncStates() throws Exception { jobDatabase.query(ctx -> { // Connection 1 has 1 job, no attempt. // This is to test that connection without no state is not returned. @@ -146,7 +147,7 @@ public void testGetStandardSyncStates() throws Exception { @Test @Order(30) - public void testCopyData() throws SQLException { + void testCopyData() throws SQLException { final Set newConnectionStates = Collections.singleton( new StandardSyncState() @@ -179,7 +180,7 @@ public void testCopyData() throws SQLException { */ @Test @Order(40) - public void testMigration() throws Exception { + void testMigration() throws Exception { jobDatabase.query(ctx -> ctx.deleteFrom(TABLE_AIRBYTE_CONFIGS) .where(COLUMN_CONFIG_TYPE.eq(ConfigSchema.STANDARD_SYNC_STATE.name())) .execute()); diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_32_8_001__AirbyteConfigDatabaseDenormalization_Test.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_32_8_001__AirbyteConfigDatabaseDenormalization_Test.java index a33cdabb49ca..6b4340ce227b 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_32_8_001__AirbyteConfigDatabaseDenormalization_Test.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_32_8_001__AirbyteConfigDatabaseDenormalization_Test.java @@ -60,10 +60,10 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class V0_32_8_001__AirbyteConfigDatabaseDenormalization_Test extends AbstractConfigsDatabaseTest { +class V0_32_8_001__AirbyteConfigDatabaseDenormalization_Test extends AbstractConfigsDatabaseTest { @Test - public void testCompleteMigration() throws IOException, SQLException { + void testCompleteMigration() throws IOException, SQLException { final DSLContext context = getDslContext(); SetupForNormalizedTablesTest.setup(context); diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_14_001__AddTombstoneToActorDefinitionTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_14_001__AddTombstoneToActorDefinitionTest.java index d6befad631d3..acc8fe384b1c 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_14_001__AddTombstoneToActorDefinitionTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_14_001__AddTombstoneToActorDefinitionTest.java @@ -16,10 +16,10 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class V0_35_14_001__AddTombstoneToActorDefinitionTest extends AbstractConfigsDatabaseTest { +class V0_35_14_001__AddTombstoneToActorDefinitionTest extends AbstractConfigsDatabaseTest { @Test - public void test() throws SQLException, IOException { + void test() throws SQLException, IOException { final DSLContext context = getDslContext(); // necessary to add actor_definition table diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_15_001__AddReleaseStageAndReleaseDateToActorDefinition_Test.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_15_001__AddReleaseStageAndReleaseDateToActorDefinition_Test.java index 6427c3402101..97387294c031 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_15_001__AddReleaseStageAndReleaseDateToActorDefinition_Test.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_15_001__AddReleaseStageAndReleaseDateToActorDefinition_Test.java @@ -16,10 +16,10 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class V0_35_15_001__AddReleaseStageAndReleaseDateToActorDefinition_Test extends AbstractConfigsDatabaseTest { +class V0_35_15_001__AddReleaseStageAndReleaseDateToActorDefinition_Test extends AbstractConfigsDatabaseTest { @Test - public void test() throws SQLException, IOException { + void test() throws SQLException, IOException { final DSLContext context = getDslContext(); // necessary to add actor_definition table diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_1_001__RemoveForeignKeyFromActorOauth_Test.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_1_001__RemoveForeignKeyFromActorOauth_Test.java index cb68168e9b51..d86017062e42 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_1_001__RemoveForeignKeyFromActorOauth_Test.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_1_001__RemoveForeignKeyFromActorOauth_Test.java @@ -30,10 +30,10 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class V0_35_1_001__RemoveForeignKeyFromActorOauth_Test extends AbstractConfigsDatabaseTest { +class V0_35_1_001__RemoveForeignKeyFromActorOauth_Test extends AbstractConfigsDatabaseTest { @Test - public void testCompleteMigration() throws IOException, SQLException { + void testCompleteMigration() throws IOException, SQLException { final DSLContext context = getDslContext(); SetupForNormalizedTablesTest.setup(context); diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_26_001__PersistDiscoveredCatalogTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_26_001__PersistDiscoveredCatalogTest.java index 6411f8573369..2bed6b31778e 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_26_001__PersistDiscoveredCatalogTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_26_001__PersistDiscoveredCatalogTest.java @@ -19,7 +19,7 @@ class V0_35_26_001__PersistDiscoveredCatalogTest extends AbstractConfigsDatabaseTest { @Test - public void test() throws SQLException, IOException { + void test() throws SQLException, IOException { final DSLContext context = getDslContext(); V0_32_8_001__AirbyteConfigDatabaseDenormalization.migrate(context); V0_35_26_001__PersistDiscoveredCatalog.migrate(context); diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_28_001__AddActorCatalogMetadataColumnsTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_28_001__AddActorCatalogMetadataColumnsTest.java index 4572f584db8e..e178e94182d9 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_28_001__AddActorCatalogMetadataColumnsTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_28_001__AddActorCatalogMetadataColumnsTest.java @@ -16,10 +16,10 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class V0_35_28_001__AddActorCatalogMetadataColumnsTest extends AbstractConfigsDatabaseTest { +class V0_35_28_001__AddActorCatalogMetadataColumnsTest extends AbstractConfigsDatabaseTest { @Test - public void test() throws SQLException, IOException { + void test() throws SQLException, IOException { final DSLContext context = getDslContext(); V0_32_8_001__AirbyteConfigDatabaseDenormalization.migrate(context); V0_35_26_001__PersistDiscoveredCatalog.migrate(context); diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_3_001__DropAirbyteConfigsTableTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_3_001__DropAirbyteConfigsTableTest.java index e9c60679d81d..466d2fb25e94 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_3_001__DropAirbyteConfigsTableTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_3_001__DropAirbyteConfigsTableTest.java @@ -15,10 +15,10 @@ import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; -public class V0_35_3_001__DropAirbyteConfigsTableTest extends AbstractConfigsDatabaseTest { +class V0_35_3_001__DropAirbyteConfigsTableTest extends AbstractConfigsDatabaseTest { @Test - public void test() throws IOException, SQLException { + void test() throws IOException, SQLException { final DSLContext context = getDslContext(); assertTrue(airbyteConfigsExists(context)); V0_35_3_001__DropAirbyteConfigsTable.dropTable(context); diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_59_001__AddPublicToActorDefinitionTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_59_001__AddPublicToActorDefinitionTest.java index bb24b17fd54b..74552e7ca459 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_59_001__AddPublicToActorDefinitionTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_59_001__AddPublicToActorDefinitionTest.java @@ -16,10 +16,10 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class V0_35_59_001__AddPublicToActorDefinitionTest extends AbstractConfigsDatabaseTest { +class V0_35_59_001__AddPublicToActorDefinitionTest extends AbstractConfigsDatabaseTest { @Test - public void test() throws SQLException, IOException { + void test() throws SQLException, IOException { final DSLContext context = getDslContext(); // necessary to add actor_definition table diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_59_002__AddActorDefinitionWorkspaceGrantTableTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_59_002__AddActorDefinitionWorkspaceGrantTableTest.java index 8a48a40c79d6..49566c357701 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_59_002__AddActorDefinitionWorkspaceGrantTableTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_59_002__AddActorDefinitionWorkspaceGrantTableTest.java @@ -16,10 +16,10 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class V0_35_59_002__AddActorDefinitionWorkspaceGrantTableTest extends AbstractConfigsDatabaseTest { +class V0_35_59_002__AddActorDefinitionWorkspaceGrantTableTest extends AbstractConfigsDatabaseTest { @Test - public void test() throws SQLException, IOException { + void test() throws SQLException, IOException { final DSLContext context = getDslContext(); V0_32_8_001__AirbyteConfigDatabaseDenormalization.migrate(context); diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_59_003__AddCustomToActorDefinitionTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_59_003__AddCustomToActorDefinitionTest.java index 2e8ecf304059..d9222296e423 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_59_003__AddCustomToActorDefinitionTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_35_59_003__AddCustomToActorDefinitionTest.java @@ -19,7 +19,7 @@ class V0_35_59_003__AddCustomToActorDefinitionTest extends AbstractConfigsDatabaseTest { @Test - public void test() throws SQLException, IOException { + void test() throws SQLException, IOException { final DSLContext context = getDslContext(); // necessary to add actor_definition table diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_39_17_001__AddStreamDescriptorsToStateTableTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_39_17_001__AddStreamDescriptorsToStateTableTest.java index 901fedacda7b..837900ccda8b 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_39_17_001__AddStreamDescriptorsToStateTableTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/configs/migrations/V0_39_17_001__AddStreamDescriptorsToStateTableTest.java @@ -22,7 +22,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class V0_39_17_001__AddStreamDescriptorsToStateTableTest extends AbstractConfigsDatabaseTest { +class V0_39_17_001__AddStreamDescriptorsToStateTableTest extends AbstractConfigsDatabaseTest { private final String STATE_TABLE = "State"; @@ -30,7 +30,7 @@ public class V0_39_17_001__AddStreamDescriptorsToStateTableTest extends Abstract private UUID connection2; @Test - public void testSimpleMigration() { + void testSimpleMigration() { final DSLContext context = getDslContext(); // Adding a couple of states @@ -76,7 +76,7 @@ public void testSimpleMigration() { } @Test - public void testUniquenessConstraint() { + void testUniquenessConstraint() { devConfigsDbMigrator.migrate(); final DSLContext context = getDslContext(); @@ -124,10 +124,11 @@ public void testUniquenessConstraint() { } @BeforeEach - public void beforeEach() { - Flyway flyway = FlywayFactory.create(dataSource, "V0_39_17_001__AddStreamDescriptorsToStateTableTest", ConfigsDatabaseMigrator.DB_IDENTIFIER, - ConfigsDatabaseMigrator.MIGRATION_FILE_LOCATION); - ConfigsDatabaseMigrator configsDbMigrator = new ConfigsDatabaseMigrator(database, flyway); + void beforeEach() { + final Flyway flyway = + FlywayFactory.create(dataSource, "V0_39_17_001__AddStreamDescriptorsToStateTableTest", ConfigsDatabaseMigrator.DB_IDENTIFIER, + ConfigsDatabaseMigrator.MIGRATION_FILE_LOCATION); + final ConfigsDatabaseMigrator configsDbMigrator = new ConfigsDatabaseMigrator(database, flyway); devConfigsDbMigrator = new DevDatabaseMigrator(configsDbMigrator); devConfigsDbMigrator.createBaseline(); @@ -135,7 +136,7 @@ public void beforeEach() { } @AfterEach - public void afterEach() { + void afterEach() { // Making sure we reset between tests dslContext.dropSchemaIfExists("public").cascade().execute(); dslContext.createSchema("public").execute(); @@ -145,9 +146,9 @@ public void afterEach() { private void injectMockData() { final DSLContext context = getDslContext(); - UUID workspaceId = UUID.randomUUID(); - UUID actorId = UUID.randomUUID(); - UUID actorDefinitionId = UUID.randomUUID(); + final UUID workspaceId = UUID.randomUUID(); + final UUID actorId = UUID.randomUUID(); + final UUID actorDefinitionId = UUID.randomUUID(); connection1 = UUID.randomUUID(); connection2 = UUID.randomUUID(); diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/development/MigrationDevHelperTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/development/MigrationDevHelperTest.java index c646bf719c5b..1577bfe98065 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/development/MigrationDevHelperTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/development/MigrationDevHelperTest.java @@ -11,35 +11,36 @@ import org.flywaydb.core.api.MigrationVersion; import org.junit.jupiter.api.Test; +@SuppressWarnings({"PMD.AvoidUsingHardCodedIP", "PMD.JUnitTestsShouldIncludeAssert"}) class MigrationDevHelperTest { @Test - public void testGetCurrentAirbyteVersion() { + void testGetCurrentAirbyteVersion() { // Test that this method will not throw any exception. MigrationDevHelper.getCurrentAirbyteVersion(); } @Test - public void testGetAirbyteVersion() { + void testGetAirbyteVersion() { final MigrationVersion migrationVersion = MigrationVersion.fromVersion("0.11.3.010"); final AirbyteVersion airbyteVersion = MigrationDevHelper.getAirbyteVersion(migrationVersion); assertEquals("0.11.3", airbyteVersion.serialize()); } @Test - public void testFormatAirbyteVersion() { + void testFormatAirbyteVersion() { final AirbyteVersion airbyteVersion = new AirbyteVersion("0.11.3-alpha"); assertEquals("0_11_3", MigrationDevHelper.formatAirbyteVersion(airbyteVersion)); } @Test - public void testGetMigrationId() { + void testGetMigrationId() { final MigrationVersion migrationVersion = MigrationVersion.fromVersion("0.11.3.010"); assertEquals("010", MigrationDevHelper.getMigrationId(migrationVersion)); } @Test - public void testGetNextMigrationVersion() { + void testGetNextMigrationVersion() { // Migration version does not exist assertEquals("0.11.3.001", MigrationDevHelper.getNextMigrationVersion( new AirbyteVersion("0.11.3-alpha"), diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/jobs/JobsDatabaseMigratorTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/jobs/JobsDatabaseMigratorTest.java index eef7326110fa..668b734479d1 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/jobs/JobsDatabaseMigratorTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/jobs/JobsDatabaseMigratorTest.java @@ -11,12 +11,13 @@ import org.flywaydb.core.Flyway; import org.junit.jupiter.api.Test; -public class JobsDatabaseMigratorTest extends AbstractJobsDatabaseTest { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class JobsDatabaseMigratorTest extends AbstractJobsDatabaseTest { private static final String SCHEMA_DUMP_FILE = "src/main/resources/jobs_database/schema_dump.txt"; @Test - public void dumpSchema() throws IOException { + void dumpSchema() throws IOException { final Flyway flyway = FlywayFactory.create(getDataSource(), getClass().getSimpleName(), JobsDatabaseMigrator.DB_IDENTIFIER, JobsDatabaseMigrator.MIGRATION_FILE_LOCATION); final DatabaseMigrator migrator = new JobsDatabaseMigrator(database, flyway); diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/jobs/migrations/V0_35_40_001_MigrateFailureReasonEnumValues_Test.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/jobs/migrations/V0_35_40_001_MigrateFailureReasonEnumValues_Test.java index 481af60f362c..7092e0534df0 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/jobs/migrations/V0_35_40_001_MigrateFailureReasonEnumValues_Test.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/jobs/migrations/V0_35_40_001_MigrateFailureReasonEnumValues_Test.java @@ -29,7 +29,7 @@ import org.jooq.impl.SQLDataType; import org.junit.jupiter.api.Test; -public class V0_35_40_001_MigrateFailureReasonEnumValues_Test extends AbstractJobsDatabaseTest { +class V0_35_40_001_MigrateFailureReasonEnumValues_Test extends AbstractJobsDatabaseTest { private static int currJobId = 1; private static final long timeNowMillis = System.currentTimeMillis(); @@ -98,7 +98,7 @@ public class V0_35_40_001_MigrateFailureReasonEnumValues_Test extends AbstractJo getFailureSummary(fixedOriginReplicationWorker, unrecognizedValue); @Test - public void test() throws Exception { + void test() throws Exception { final DSLContext ctx = getDslContext(); V0_35_5_001__Add_failureSummary_col_to_Attempts.migrate(ctx); diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/jobs/migrations/V0_35_5_001__Add_failureSummary_col_to_AttemptsTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/jobs/migrations/V0_35_5_001__Add_failureSummary_col_to_AttemptsTest.java index 8820d580c23c..7391d535622b 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/jobs/migrations/V0_35_5_001__Add_failureSummary_col_to_AttemptsTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/jobs/migrations/V0_35_5_001__Add_failureSummary_col_to_AttemptsTest.java @@ -12,10 +12,10 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class V0_35_5_001__Add_failureSummary_col_to_AttemptsTest extends AbstractJobsDatabaseTest { +class V0_35_5_001__Add_failureSummary_col_to_AttemptsTest extends AbstractJobsDatabaseTest { @Test - public void test() throws SQLException, IOException { + void test() throws SQLException, IOException { final DSLContext context = getDslContext(); Assertions.assertFalse(failureSummaryColumnExists(context)); V0_35_5_001__Add_failureSummary_col_to_Attempts.addFailureSummaryColumn(context); diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/toys/ToysDatabaseMigratorTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/toys/ToysDatabaseMigratorTest.java index 87e353d786f4..a60031a21900 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/toys/ToysDatabaseMigratorTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/instance/toys/ToysDatabaseMigratorTest.java @@ -31,7 +31,7 @@ public Database getDatabase(final DataSource dataSource, final DSLContext dslCon } @Test - public void testMigration() throws Exception { + void testMigration() throws Exception { final DataSource dataSource = getDataSource(); initializeDatabase(getDslContext()); diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/TestDefaultJdbcDatabase.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/TestDefaultJdbcDatabase.java index 7cf0e1c27605..7ff9bf80e4fc 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/TestDefaultJdbcDatabase.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/TestDefaultJdbcDatabase.java @@ -27,7 +27,7 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.utility.MountableFile; -public class TestDefaultJdbcDatabase { +class TestDefaultJdbcDatabase { private static final List RECORDS_AS_JSON = Lists.newArrayList( Jsons.jsonNode(ImmutableMap.of("id", 1, "name", "picard")), diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/TestJdbcUtils.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/TestJdbcUtils.java index a0e0c8e006eb..01cb72b01cce 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/TestJdbcUtils.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/TestJdbcUtils.java @@ -41,7 +41,8 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.utility.MountableFile; -public class TestJdbcUtils { +@SuppressWarnings("PMD.CheckResultSet") +class TestJdbcUtils { private String dbName; diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/TestStreamingJdbcDatabase.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/TestStreamingJdbcDatabase.java index 88c09cd7b96b..a5abecd99857 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/TestStreamingJdbcDatabase.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/TestStreamingJdbcDatabase.java @@ -39,7 +39,7 @@ import org.testcontainers.utility.MountableFile; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class TestStreamingJdbcDatabase { +class TestStreamingJdbcDatabase { private static PostgreSQLContainer PSQL_DB; private final JdbcSourceOperations sourceOperations = JdbcUtils.getDefaultSourceOperations(); diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/AdaptiveStreamingQueryConfigTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/AdaptiveStreamingQueryConfigTest.java index cc9bcdf41b41..85f2df9dd93f 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/AdaptiveStreamingQueryConfigTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/AdaptiveStreamingQueryConfigTest.java @@ -18,7 +18,7 @@ class AdaptiveStreamingQueryConfigTest { @Test - public void testFetchSizeUpdate() throws SQLException { + void testFetchSizeUpdate() throws SQLException { final AdaptiveStreamingQueryConfig queryConfig = new AdaptiveStreamingQueryConfig(); final ResultSet resultSet = mock(ResultSet.class); for (int i = 0; i < FetchSizeConstants.INITIAL_SAMPLE_SIZE - 1; ++i) { diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/BaseSizeEstimatorTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/BaseSizeEstimatorTest.java index dadfd5bc00bf..63a931cfdf70 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/BaseSizeEstimatorTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/BaseSizeEstimatorTest.java @@ -14,7 +14,7 @@ class BaseSizeEstimatorTest { @Test - public void testGetEstimatedByteSize() { + void testGetEstimatedByteSize() { assertEquals(0L, BaseSizeEstimator.getEstimatedByteSize(null)); assertEquals(28L, BaseSizeEstimator.getEstimatedByteSize("12345")); assertEquals(60L, BaseSizeEstimator.getEstimatedByteSize(Jsons.jsonNode(Map.of("key", "value")))); @@ -41,7 +41,7 @@ public void setMeanByteSize(final double meanByteSize) { } @Test - public void testGetBoundedFetchSize() { + void testGetBoundedFetchSize() { final long bufferByteSize = 120; final int minFetchSize = 10; final int defaultFetchSize = 20; diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/InitialSizeEstimatorTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/InitialSizeEstimatorTest.java index 007839ae67fa..d33045c5d5d9 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/InitialSizeEstimatorTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/InitialSizeEstimatorTest.java @@ -12,7 +12,7 @@ class InitialSizeEstimatorTest { @Test - public void testIt() { + void testIt() { final long bufferByteSize = 120; final int initialSampleSize = 5; final int minFetchSize = 1; diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/SamplingSizeEstimatorTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/SamplingSizeEstimatorTest.java index 8b7ae22188c4..2786bbe306f2 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/SamplingSizeEstimatorTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/SamplingSizeEstimatorTest.java @@ -12,7 +12,7 @@ class SamplingSizeEstimatorTest { @Test - public void testIt() { + void testIt() { final long bufferByteSize = 120; final int sampleFrequency = 3; final long initialByteSize = 10; diff --git a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/TwoStageSizeEstimatorTest.java b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/TwoStageSizeEstimatorTest.java index ea922fb78e3e..61cc26ae990b 100644 --- a/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/TwoStageSizeEstimatorTest.java +++ b/airbyte-db/db-lib/src/test/java/io/airbyte/db/jdbc/streaming/TwoStageSizeEstimatorTest.java @@ -11,7 +11,7 @@ class TwoStageSizeEstimatorTest { @Test - public void testDelegationSwitch() { + void testDelegationSwitch() { final TwoStageSizeEstimator sizeEstimator = TwoStageSizeEstimator.getInstance(); for (int i = 0; i < FetchSizeConstants.INITIAL_SAMPLE_SIZE; ++i) { sizeEstimator.accept("1"); @@ -25,7 +25,7 @@ public void testDelegationSwitch() { } @Test - public void testGetTargetBufferByteSize() { + void testGetTargetBufferByteSize() { assertEquals(FetchSizeConstants.MIN_BUFFER_BYTE_SIZE, TwoStageSizeEstimator.getTargetBufferByteSize(null)); assertEquals(FetchSizeConstants.MIN_BUFFER_BYTE_SIZE, diff --git a/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/DogStatsDMetricClientTest.java b/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/DogStatsDMetricClientTest.java index 626a520176ab..93a7163eba0c 100644 --- a/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/DogStatsDMetricClientTest.java +++ b/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/DogStatsDMetricClientTest.java @@ -10,7 +10,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -public class DogStatsDMetricClientTest { +class DogStatsDMetricClientTest { DogStatsDMetricClient dogStatsDMetricClient; @@ -27,7 +27,7 @@ void tearDown() { @Test @DisplayName("there should be no exception if we attempt to emit metrics while publish is false") - public void testPublishTrueNoEmitError() { + void testPublishTrueNoEmitError() { Assertions.assertDoesNotThrow(() -> { dogStatsDMetricClient.gauge(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS, 1); }); @@ -35,7 +35,7 @@ public void testPublishTrueNoEmitError() { @Test @DisplayName("there should be no exception if we attempt to emit metrics while publish is true") - public void testPublishFalseNoEmitError() { + void testPublishFalseNoEmitError() { Assertions.assertDoesNotThrow(() -> { dogStatsDMetricClient.gauge(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS, 1); }); @@ -43,7 +43,7 @@ public void testPublishFalseNoEmitError() { @Test @DisplayName("there should be no exception if we attempt to emit metrics without initializing") - public void testNoInitializeNoEmitError() { + void testNoInitializeNoEmitError() { Assertions.assertDoesNotThrow(() -> { dogStatsDMetricClient.gauge(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS, 1); }); diff --git a/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/DogStatsDMetricSingletonTest.java b/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/DogStatsDMetricSingletonTest.java index 1d26a025ef11..93f517c934c9 100644 --- a/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/DogStatsDMetricSingletonTest.java +++ b/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/DogStatsDMetricSingletonTest.java @@ -9,7 +9,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -public class DogStatsDMetricSingletonTest { +class DogStatsDMetricSingletonTest { @AfterEach void tearDown() { @@ -18,7 +18,7 @@ void tearDown() { @Test @DisplayName("there should be no exception if we attempt to emit metrics while publish is false") - public void testPublishTrueNoEmitError() { + void testPublishTrueNoEmitError() { Assertions.assertDoesNotThrow(() -> { DogStatsDMetricSingleton.initialize(MetricEmittingApps.WORKER, new DatadogClientConfiguration("localhost", "1000", false)); DogStatsDMetricSingleton.gauge(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS, 1); @@ -27,7 +27,7 @@ public void testPublishTrueNoEmitError() { @Test @DisplayName("there should be no exception if we attempt to emit metrics while publish is true") - public void testPublishFalseNoEmitError() { + void testPublishFalseNoEmitError() { Assertions.assertDoesNotThrow(() -> { DogStatsDMetricSingleton.initialize(MetricEmittingApps.WORKER, new DatadogClientConfiguration("localhost", "1000", true)); DogStatsDMetricSingleton.gauge(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS, 1); @@ -36,7 +36,7 @@ public void testPublishFalseNoEmitError() { @Test @DisplayName("there should be no exception if we attempt to emit metrics without initializing") - public void testNoInitializeNoEmitError() { + void testNoInitializeNoEmitError() { Assertions.assertDoesNotThrow(() -> { DogStatsDMetricSingleton.gauge(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS, 1); }); diff --git a/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/MetricClientFactoryTest.java b/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/MetricClientFactoryTest.java index 7c94ecbbd4db..7fd44dc60404 100644 --- a/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/MetricClientFactoryTest.java +++ b/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/MetricClientFactoryTest.java @@ -12,7 +12,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -public class MetricClientFactoryTest { +class MetricClientFactoryTest { @AfterEach void tearDown() { @@ -21,14 +21,14 @@ void tearDown() { @Test @DisplayName("Should not throw error if calling get without calling create;") - public void testMetricClientFactoryGetMetricOnlyDoNotThrow() { - MetricClient metricClient = MetricClientFactory.getMetricClient(); + void testMetricClientFactoryGetMetricOnlyDoNotThrow() { + final MetricClient metricClient = MetricClientFactory.getMetricClient(); assertThat(metricClient, instanceOf(NotImplementedMetricClient.class)); } @Test @DisplayName("Should not throw error if MetricClientFactory creates a metric client on the first call;") - public void testMetricClientFactoryCreateSuccess() { + void testMetricClientFactoryCreateSuccess() { Assertions.assertDoesNotThrow(() -> { MetricClientFactory.initialize(MetricEmittingApps.METRICS_REPORTER); }); @@ -36,7 +36,7 @@ public void testMetricClientFactoryCreateSuccess() { @Test @DisplayName("Should throw error if MetricClientFactory create a metric client multiple times;") - public void testMetricClientFactoryCreateMultipleTimesThrows() { + void testMetricClientFactoryCreateMultipleTimesThrows() { Assertions.assertThrows(RuntimeException.class, () -> { MetricClientFactory.initialize(MetricEmittingApps.METRICS_REPORTER); MetricClientFactory.initialize(MetricEmittingApps.METRICS_REPORTER); diff --git a/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/OpenTelemetryMetricClientTest.java b/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/OpenTelemetryMetricClientTest.java index a6f7ad704f07..93be1136a007 100644 --- a/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/OpenTelemetryMetricClientTest.java +++ b/airbyte-metrics/metrics-lib/src/test/java/io/airbyte/metrics/lib/OpenTelemetryMetricClientTest.java @@ -33,9 +33,9 @@ class OpenTelemetryMetricClientTest { void setUp() { openTelemetryMetricClient = new OpenTelemetryMetricClient(); - Resource resource = Resource.getDefault().toBuilder().put(SERVICE_NAME, METRIC_EMITTING_APP.getApplicationName()).build(); + final Resource resource = Resource.getDefault().toBuilder().put(SERVICE_NAME, METRIC_EMITTING_APP.getApplicationName()).build(); metricExporter = InMemoryMetricExporter.create(); - SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder() + final SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder() .setResource(resource) .build(); openTelemetryMetricClient.initialize(METRIC_EMITTING_APP, metricExporter, sdkTracerProvider, resource); @@ -50,12 +50,12 @@ void tearDown() { @Test @DisplayName("Should send out count metric with correct metric name, description and value") - public void testCountSuccess() { + void testCountSuccess() { openTelemetryMetricClient.count(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS, 1); metricProvider.forceFlush(); - List metricDataList = metricExporter.getFinishedMetricItems(); - MetricData data = Iterables.getOnlyElement(metricDataList); + final List metricDataList = metricExporter.getFinishedMetricItems(); + final MetricData data = Iterables.getOnlyElement(metricDataList); assertThat(data.getName()).isEqualTo(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS.getMetricName()); assertThat(data.getDescription()).isEqualTo(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS.getMetricDescription()); @@ -64,12 +64,12 @@ public void testCountSuccess() { @Test @DisplayName("Tags should be passed into metrics") - public void testCountWithTagSuccess() { + void testCountWithTagSuccess() { openTelemetryMetricClient.count(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS, 1, TAG); metricProvider.forceFlush(); - List metricDataList = metricExporter.getFinishedMetricItems(); - MetricData data = Iterables.getOnlyElement(metricDataList); + final List metricDataList = metricExporter.getFinishedMetricItems(); + final MetricData data = Iterables.getOnlyElement(metricDataList); assertThat(data.getName()).isEqualTo(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS.getMetricName()); assertThat(data.getDescription()).isEqualTo(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS.getMetricDescription()); @@ -80,12 +80,12 @@ public void testCountWithTagSuccess() { @Test @DisplayName("Should send out gauge metric with correct metric name, description and value") - public void testGaugeSuccess() throws Exception { + void testGaugeSuccess() throws Exception { openTelemetryMetricClient.gauge(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS, 1); metricProvider.forceFlush(); - List metricDataList = metricExporter.getFinishedMetricItems(); - MetricData data = Iterables.getOnlyElement(metricDataList); + final List metricDataList = metricExporter.getFinishedMetricItems(); + final MetricData data = Iterables.getOnlyElement(metricDataList); assertThat(data.getName()).isEqualTo(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS.getMetricName()); assertThat(data.getDescription()).isEqualTo(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS.getMetricDescription()); @@ -94,13 +94,13 @@ public void testGaugeSuccess() throws Exception { @Test @DisplayName("Should send out histogram metric with correct metric name, description and value") - public void testHistogramSuccess() { + void testHistogramSuccess() { openTelemetryMetricClient.distribution(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS, 10); openTelemetryMetricClient.distribution(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS, 30); metricProvider.forceFlush(); - List metricDataList = metricExporter.getFinishedMetricItems(); - MetricData data = Iterables.getOnlyElement(metricDataList); + final List metricDataList = metricExporter.getFinishedMetricItems(); + final MetricData data = Iterables.getOnlyElement(metricDataList); assertThat(data.getName()).isEqualTo(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS.getMetricName()); assertThat(data.getDescription()).isEqualTo(OssMetricsRegistry.KUBE_POD_PROCESS_CREATE_TIME_MILLISECS.getMetricDescription()); diff --git a/airbyte-notification/src/main/java/io/airbyte/notification/CustomerioNotificationClient.java b/airbyte-notification/src/main/java/io/airbyte/notification/CustomerioNotificationClient.java index 2d2559be4526..384d3d9701a9 100644 --- a/airbyte-notification/src/main/java/io/airbyte/notification/CustomerioNotificationClient.java +++ b/airbyte-notification/src/main/java/io/airbyte/notification/CustomerioNotificationClient.java @@ -139,6 +139,7 @@ private static boolean isSuccessfulHttpResponse(final int httpStatusCode) { return httpStatusCode / 100 == 2; } + @Override public String renderTemplate(final String templateFile, final String... data) throws IOException { final String template = MoreResources.readResource(templateFile); return String.format(template, data); diff --git a/airbyte-notification/src/test/java/io/airbyte/notification/SlackNotificationClientTest.java b/airbyte-notification/src/test/java/io/airbyte/notification/SlackNotificationClientTest.java index 51b0a4a2f445..6795cfd8871d 100644 --- a/airbyte-notification/src/test/java/io/airbyte/notification/SlackNotificationClientTest.java +++ b/airbyte-notification/src/test/java/io/airbyte/notification/SlackNotificationClientTest.java @@ -30,7 +30,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class SlackNotificationClientTest { +class SlackNotificationClientTest { private static final Logger LOGGER = LoggerFactory.getLogger(SlackNotificationClientTest.class); private static final UUID WORKSPACE_ID = UUID.randomUUID(); diff --git a/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/AmazonSellerPartnerOAuthFlow.java b/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/AmazonSellerPartnerOAuthFlow.java index 83f7a4d62d7a..f9fdc914efa7 100644 --- a/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/AmazonSellerPartnerOAuthFlow.java +++ b/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/AmazonSellerPartnerOAuthFlow.java @@ -22,10 +22,12 @@ public class AmazonSellerPartnerOAuthFlow extends BaseOAuth2Flow { private static final String AUTHORIZE_URL = "https://sellercentral.amazon.com/apps/authorize/consent"; private static final String ACCESS_TOKEN_URL = "https://api.amazon.com/auth/o2/token"; + @Override protected String getClientIdUnsafe(final JsonNode oauthConfig) { return getConfigValueUnsafe(oauthConfig, "lwa_app_id"); } + @Override protected String getClientSecretUnsafe(final JsonNode oauthConfig) { return getConfigValueUnsafe(oauthConfig, "lwa_client_secret"); } @@ -70,7 +72,7 @@ protected String formatConsentUrl(final UUID definitionId, } @Override - protected String extractCodeParameter(Map queryParams) throws IOException { + protected String extractCodeParameter(final Map queryParams) throws IOException { if (queryParams.containsKey("spapi_oauth_code")) { return (String) queryParams.get("spapi_oauth_code"); } else { diff --git a/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/DestinationSnowflakeOAuthFlow.java b/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/DestinationSnowflakeOAuthFlow.java index 038f5885af2e..20df4a7af93b 100644 --- a/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/DestinationSnowflakeOAuthFlow.java +++ b/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/DestinationSnowflakeOAuthFlow.java @@ -29,16 +29,16 @@ public class DestinationSnowflakeOAuthFlow extends BaseOAuth2Flow { private static final String ACCESS_TOKEN_URL = "https://%s/oauth/token-request"; public DestinationSnowflakeOAuthFlow( - ConfigRepository configRepository, - HttpClient httpClient) { + final ConfigRepository configRepository, + final HttpClient httpClient) { super(configRepository, httpClient); } @Override - protected String formatConsentUrl(UUID definitionId, - String clientId, - String redirectUrl, - JsonNode inputOAuthConfiguration) + protected String formatConsentUrl(final UUID definitionId, + final String clientId, + final String redirectUrl, + final JsonNode inputOAuthConfiguration) throws IOException { try { return new URIBuilder( @@ -55,20 +55,20 @@ protected String formatConsentUrl(UUID definitionId, } @Override - protected String getAccessTokenUrl(JsonNode inputOAuthConfiguration) { + protected String getAccessTokenUrl(final JsonNode inputOAuthConfiguration) { return String.format(ACCESS_TOKEN_URL, extractTokenUrl(inputOAuthConfiguration)); } @Override - protected String extractCodeParameter(Map queryParams) throws IOException { + protected String extractCodeParameter(final Map queryParams) throws IOException { return super.extractCodeParameter(queryParams); } @Override - protected Map getAccessTokenQueryParameters(String clientId, - String clientSecret, - String authCode, - String redirectUrl) { + protected Map getAccessTokenQueryParameters(final String clientId, + final String clientSecret, + final String authCode, + final String redirectUrl) { return ImmutableMap.builder() // required .put("grant_type", "authorization_code") @@ -112,6 +112,7 @@ protected Map completeOAuthFlow(final String clientId, /** * Extract all OAuth outputs from distant API response and store them in a flat map. */ + @Override protected Map extractOAuthOutput(final JsonNode data, final String accessTokenUrl) throws IOException { final Map result = new HashMap<>(); @@ -132,13 +133,13 @@ protected Map extractOAuthOutput(final JsonNode data, final Stri return result; } - private String extractAuthorizeUrl(JsonNode inputOAuthConfiguration) { - var url = inputOAuthConfiguration.get("host"); + private String extractAuthorizeUrl(final JsonNode inputOAuthConfiguration) { + final var url = inputOAuthConfiguration.get("host"); return url == null ? StringUtils.EMPTY : url.asText(); } - private String extractTokenUrl(JsonNode inputOAuthConfiguration) { - var url = inputOAuthConfiguration.get("host"); + private String extractTokenUrl(final JsonNode inputOAuthConfiguration) { + final var url = inputOAuthConfiguration.get("host"); // var url = inputOAuthConfiguration.get("token_url"); return url == null ? StringUtils.EMPTY : url.asText(); } diff --git a/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/DriftOAuthFlow.java b/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/DriftOAuthFlow.java index 7558d2b68c02..b971e44a58ea 100644 --- a/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/DriftOAuthFlow.java +++ b/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/DriftOAuthFlow.java @@ -36,7 +36,8 @@ public DriftOAuthFlow(final ConfigRepository configRepository, final HttpClient } @Override - protected String formatConsentUrl(UUID definitionId, String clientId, String redirectUrl, JsonNode inputOAuthConfiguration) throws IOException { + protected String formatConsentUrl(final UUID definitionId, final String clientId, final String redirectUrl, final JsonNode inputOAuthConfiguration) + throws IOException { final URIBuilder builder = new URIBuilder() .setScheme("https") .setHost("dev.drift.com") @@ -47,13 +48,13 @@ protected String formatConsentUrl(UUID definitionId, String clientId, String red .addParameter("state", getState()); try { return builder.build().toString(); - } catch (URISyntaxException e) { + } catch (final URISyntaxException e) { throw new IOException("Failed to format Consent URL for OAuth flow", e); } } @Override - protected String extractCodeParameter(Map queryParams) throws IOException { + protected String extractCodeParameter(final Map queryParams) throws IOException { if (queryParams.containsKey("code")) { return (String) queryParams.get("code"); } else { @@ -67,7 +68,10 @@ protected String getAccessTokenUrl(final JsonNode inputOAuthConfiguration) { } @Override - protected Map getAccessTokenQueryParameters(String clientId, String clientSecret, String authCode, String redirectUrl) { + protected Map getAccessTokenQueryParameters(final String clientId, + final String clientSecret, + final String authCode, + final String redirectUrl) { return ImmutableMap.builder() .put("client_id", clientId) .put("client_secret", clientSecret) @@ -76,7 +80,8 @@ protected Map getAccessTokenQueryParameters(String clientId, Str .build(); } - protected Map extractOAuthOutput(final JsonNode data, String accessTokenUrl) throws IOException { + @Override + protected Map extractOAuthOutput(final JsonNode data, final String accessTokenUrl) throws IOException { final Map result = new HashMap<>(); if (data.has("access_token")) { result.put("access_token", data.get("access_token").asText()); diff --git a/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/LeverOAuthFlow.java b/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/LeverOAuthFlow.java index 0b70f3801170..cf00dce751d5 100644 --- a/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/LeverOAuthFlow.java +++ b/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/LeverOAuthFlow.java @@ -34,15 +34,19 @@ public class LeverOAuthFlow extends BaseOAuth2Flow { "users:read:admin", "offline_access"); - public LeverOAuthFlow(ConfigRepository configRepository, HttpClient httpClient) { + public LeverOAuthFlow(final ConfigRepository configRepository, final HttpClient httpClient) { super(configRepository, httpClient); } - private String getAudience(JsonNode inputOAuthConfiguration) { + private String getAudience(final JsonNode inputOAuthConfiguration) { return String.format("%s/v1/", getBaseApiUrl(inputOAuthConfiguration)); } - protected Map getAccessTokenQueryParameters(String clientId, String clientSecret, String authCode, String redirectUrl) { + @Override + protected Map getAccessTokenQueryParameters(final String clientId, + final String clientSecret, + final String authCode, + final String redirectUrl) { return ImmutableMap.builder() // required .put("client_id", clientId) @@ -57,12 +61,13 @@ protected Map getAccessTokenQueryParameters(String clientId, Str * Returns the URL where to retrieve the access token from. */ @Override - protected String getAccessTokenUrl(JsonNode inputOAuthConfiguration) { + protected String getAccessTokenUrl(final JsonNode inputOAuthConfiguration) { return String.format(ACCESS_TOKEN_URL, getBaseAuthUrl(inputOAuthConfiguration)); } @Override - protected String formatConsentUrl(UUID definitionId, String clientId, String redirectUrl, JsonNode inputOAuthConfiguration) throws IOException { + protected String formatConsentUrl(final UUID definitionId, final String clientId, final String redirectUrl, final JsonNode inputOAuthConfiguration) + throws IOException { try { return URLDecoder.decode((new URIBuilder(String.format(AUTHORIZE_URL, getBaseAuthUrl(inputOAuthConfiguration))) @@ -73,12 +78,12 @@ protected String formatConsentUrl(UUID definitionId, String clientId, String red .addParameter("scope", SCOPES) .addParameter("audience", getAudience(inputOAuthConfiguration)) .addParameter("prompt", "consent").build().toString()), StandardCharsets.UTF_8); - } catch (URISyntaxException e) { + } catch (final URISyntaxException e) { throw new IOException("Failed to format Consent URL for OAuth flow", e); } } - private String getBaseAuthUrl(JsonNode inputOAuthConfiguration) { + private String getBaseAuthUrl(final JsonNode inputOAuthConfiguration) { if (isProduction(inputOAuthConfiguration)) { return "http1s://auth.lever.co"; } else { @@ -86,7 +91,7 @@ private String getBaseAuthUrl(JsonNode inputOAuthConfiguration) { } } - private String getBaseApiUrl(JsonNode inputOAuthConfiguration) { + private String getBaseApiUrl(final JsonNode inputOAuthConfiguration) { if (isProduction(inputOAuthConfiguration)) { return "https://api.lever.co/"; } else { @@ -94,8 +99,8 @@ private String getBaseApiUrl(JsonNode inputOAuthConfiguration) { } } - private boolean isProduction(JsonNode inputOAuthConfiguration) { - var environment = inputOAuthConfiguration.get("environment"); + private boolean isProduction(final JsonNode inputOAuthConfiguration) { + final var environment = inputOAuthConfiguration.get("environment"); return environment != null && environment.asText().toLowerCase(Locale.ROOT).equals("production"); } diff --git a/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/TikTokMarketingOAuthFlow.java b/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/TikTokMarketingOAuthFlow.java index 1d7b8b83172d..4f0c5116b628 100644 --- a/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/TikTokMarketingOAuthFlow.java +++ b/airbyte-oauth/src/main/java/io/airbyte/oauth/flows/TikTokMarketingOAuthFlow.java @@ -26,10 +26,12 @@ public class TikTokMarketingOAuthFlow extends BaseOAuth2Flow { private static final String ACCESS_TOKEN_URL = "https://ads.tiktok.com/open_api/v1.2/oauth2/access_token/"; + @Override protected String getClientIdUnsafe(final JsonNode oauthConfig) { return getConfigValueUnsafe(oauthConfig, "app_id"); } + @Override protected String getClientSecretUnsafe(final JsonNode oauthConfig) { return getConfigValueUnsafe(oauthConfig, "secret"); } @@ -67,10 +69,10 @@ protected String formatConsentUrl(final UUID definitionId, } @Override - protected Map getAccessTokenQueryParameters(String appId, - String secret, - String authCode, - String redirectUrl) { + protected Map getAccessTokenQueryParameters(final String appId, + final String secret, + final String authCode, + final String redirectUrl) { return ImmutableMap.builder() // required .put("auth_code", authCode) diff --git a/airbyte-oauth/src/test-integration/java/io/airbyte/oauth/flows/OAuthFlowIntegrationTest.java b/airbyte-oauth/src/test-integration/java/io/airbyte/oauth/flows/OAuthFlowIntegrationTest.java index 19071d07def3..cbe3d50406e9 100644 --- a/airbyte-oauth/src/test-integration/java/io/airbyte/oauth/flows/OAuthFlowIntegrationTest.java +++ b/airbyte-oauth/src/test-integration/java/io/airbyte/oauth/flows/OAuthFlowIntegrationTest.java @@ -25,6 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@SuppressWarnings("PMD.AvoidReassigningParameters") public abstract class OAuthFlowIntegrationTest { /** diff --git a/airbyte-oauth/src/test/java/io/airbyte/oauth/MoreOAuthParametersTest.java b/airbyte-oauth/src/test/java/io/airbyte/oauth/MoreOAuthParametersTest.java index 125ea735e744..4d442d58c912 100644 --- a/airbyte-oauth/src/test/java/io/airbyte/oauth/MoreOAuthParametersTest.java +++ b/airbyte-oauth/src/test/java/io/airbyte/oauth/MoreOAuthParametersTest.java @@ -16,7 +16,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -public class MoreOAuthParametersTest { +class MoreOAuthParametersTest { @Test void testFlattenConfig() { diff --git a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/BaseOAuthFlowTest.java b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/BaseOAuthFlowTest.java index 81505d35e5b0..9400588a9731 100644 --- a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/BaseOAuthFlowTest.java +++ b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/BaseOAuthFlowTest.java @@ -51,7 +51,7 @@ protected ConfigRepository getConfigRepository() { } @BeforeEach - public void setup() throws JsonValidationException, IOException { + void setup() throws JsonValidationException, IOException { httpClient = mock(HttpClient.class); configRepository = mock(ConfigRepository.class); oauthFlow = getOAuthFlow(); @@ -210,12 +210,12 @@ protected OAuthConfigSpecification getOAuthConfigSpecification() { } @Test - public void testGetDefaultOutputPath() { + void testGetDefaultOutputPath() { assertEquals(getExpectedOutputPath(), oauthFlow.getDefaultOAuthOutputPath()); } @Test - public void testValidateInputOAuthConfigurationFailure() { + void testValidateInputOAuthConfigurationFailure() { final JsonNode invalidInputOAuthConfiguration = Jsons.jsonNode(Map.of("UnexpectedRandomField", 42)); assertThrows(JsonValidationException.class, () -> oauthFlow.getSourceConsentUrl(workspaceId, definitionId, REDIRECT_URL, invalidInputOAuthConfiguration, getoAuthConfigSpecification())); @@ -228,7 +228,7 @@ public void testValidateInputOAuthConfigurationFailure() { } @Test - public void testGetConsentUrlEmptyOAuthParameters() throws JsonValidationException, IOException { + void testGetConsentUrlEmptyOAuthParameters() throws JsonValidationException, IOException { when(configRepository.listSourceOAuthParam()).thenReturn(List.of()); when(configRepository.listDestinationOAuthParam()).thenReturn(List.of()); assertThrows(ConfigNotFoundException.class, @@ -239,7 +239,7 @@ public void testGetConsentUrlEmptyOAuthParameters() throws JsonValidationExcepti } @Test - public void testGetConsentUrlIncompleteOAuthParameters() throws IOException, JsonValidationException { + void testGetConsentUrlIncompleteOAuthParameters() throws IOException, JsonValidationException { when(configRepository.listSourceOAuthParam()).thenReturn(List.of(new SourceOAuthParameter() .withOauthParameterId(UUID.randomUUID()) .withSourceDefinitionId(definitionId) @@ -258,7 +258,7 @@ public void testGetConsentUrlIncompleteOAuthParameters() throws IOException, Jso } @Test - public void testGetSourceConsentUrlEmptyOAuthSpec() throws IOException, ConfigNotFoundException, JsonValidationException { + void testGetSourceConsentUrlEmptyOAuthSpec() throws IOException, ConfigNotFoundException, JsonValidationException { if (hasDependencyOnConnectorConfigValues()) { assertThrows(IOException.class, () -> oauthFlow.getSourceConsentUrl(workspaceId, definitionId, REDIRECT_URL, Jsons.emptyObject(), null), "OAuth Flow Implementations with dependencies on connector config can't be supported without OAuthConfigSpecifications"); @@ -269,7 +269,7 @@ public void testGetSourceConsentUrlEmptyOAuthSpec() throws IOException, ConfigNo } @Test - public void testGetDestinationConsentUrlEmptyOAuthSpec() throws IOException, ConfigNotFoundException, JsonValidationException { + void testGetDestinationConsentUrlEmptyOAuthSpec() throws IOException, ConfigNotFoundException, JsonValidationException { if (hasDependencyOnConnectorConfigValues()) { assertThrows(IOException.class, () -> oauthFlow.getDestinationConsentUrl(workspaceId, definitionId, REDIRECT_URL, Jsons.emptyObject(), null), "OAuth Flow Implementations with dependencies on connector config can't be supported without OAuthConfigSpecifications"); @@ -280,27 +280,27 @@ public void testGetDestinationConsentUrlEmptyOAuthSpec() throws IOException, Con } @Test - public void testGetSourceConsentUrl() throws IOException, ConfigNotFoundException, JsonValidationException { + void testGetSourceConsentUrl() throws IOException, ConfigNotFoundException, JsonValidationException { final String consentUrl = oauthFlow.getSourceConsentUrl(workspaceId, definitionId, REDIRECT_URL, getInputOAuthConfiguration(), getoAuthConfigSpecification()); assertEquals(getExpectedConsentUrl(), consentUrl); } @Test - public void testGetDestinationConsentUrl() throws IOException, ConfigNotFoundException, JsonValidationException { + void testGetDestinationConsentUrl() throws IOException, ConfigNotFoundException, JsonValidationException { final String consentUrl = oauthFlow.getDestinationConsentUrl(workspaceId, definitionId, REDIRECT_URL, getInputOAuthConfiguration(), getoAuthConfigSpecification()); assertEquals(getExpectedConsentUrl(), consentUrl); } @Test - public void testCompleteOAuthMissingCode() { + void testCompleteOAuthMissingCode() { final Map queryParams = Map.of(); assertThrows(IOException.class, () -> oauthFlow.completeSourceOAuth(workspaceId, definitionId, queryParams, REDIRECT_URL)); } @Test - public void testDeprecatedCompleteSourceOAuth() throws IOException, InterruptedException, ConfigNotFoundException { + void testDeprecatedCompleteSourceOAuth() throws IOException, InterruptedException, ConfigNotFoundException { final Map returnedCredentials = getExpectedOutput(); final HttpResponse response = mock(HttpResponse.class); when(response.body()).thenReturn(Jsons.serialize(returnedCredentials)); @@ -325,7 +325,7 @@ public void testDeprecatedCompleteSourceOAuth() throws IOException, InterruptedE } @Test - public void testDeprecatedCompleteDestinationOAuth() throws IOException, ConfigNotFoundException, InterruptedException { + void testDeprecatedCompleteDestinationOAuth() throws IOException, ConfigNotFoundException, InterruptedException { final Map returnedCredentials = getExpectedOutput(); final HttpResponse response = mock(HttpResponse.class); when(response.body()).thenReturn(Jsons.serialize(returnedCredentials)); @@ -350,7 +350,7 @@ public void testDeprecatedCompleteDestinationOAuth() throws IOException, ConfigN } @Test - public void testEmptyOutputCompleteSourceOAuth() throws IOException, InterruptedException, ConfigNotFoundException, JsonValidationException { + void testEmptyOutputCompleteSourceOAuth() throws IOException, InterruptedException, ConfigNotFoundException, JsonValidationException { final HttpResponse response = mock(HttpResponse.class); when(response.body()).thenReturn(getMockedResponse()); when(httpClient.send(any(), any())).thenReturn(response); @@ -362,7 +362,7 @@ public void testEmptyOutputCompleteSourceOAuth() throws IOException, Interrupted } @Test - public void testEmptyOutputCompleteDestinationOAuth() throws IOException, InterruptedException, ConfigNotFoundException, JsonValidationException { + void testEmptyOutputCompleteDestinationOAuth() throws IOException, InterruptedException, ConfigNotFoundException, JsonValidationException { final HttpResponse response = mock(HttpResponse.class); when(response.body()).thenReturn(getMockedResponse()); when(httpClient.send(any(), any())).thenReturn(response); @@ -374,7 +374,7 @@ public void testEmptyOutputCompleteDestinationOAuth() throws IOException, Interr } @Test - public void testEmptyInputCompleteSourceOAuth() throws IOException, InterruptedException, ConfigNotFoundException, JsonValidationException { + void testEmptyInputCompleteSourceOAuth() throws IOException, InterruptedException, ConfigNotFoundException, JsonValidationException { final HttpResponse response = mock(HttpResponse.class); when(response.body()).thenReturn(getMockedResponse()); when(httpClient.send(any(), any())).thenReturn(response); @@ -388,7 +388,7 @@ public void testEmptyInputCompleteSourceOAuth() throws IOException, InterruptedE } @Test - public void testEmptyInputCompleteDestinationOAuth() throws IOException, InterruptedException, ConfigNotFoundException, JsonValidationException { + void testEmptyInputCompleteDestinationOAuth() throws IOException, InterruptedException, ConfigNotFoundException, JsonValidationException { final HttpResponse response = mock(HttpResponse.class); when(response.body()).thenReturn(getMockedResponse()); when(httpClient.send(any(), any())).thenReturn(response); @@ -402,7 +402,7 @@ public void testEmptyInputCompleteDestinationOAuth() throws IOException, Interru } @Test - public void testCompleteSourceOAuth() throws IOException, InterruptedException, ConfigNotFoundException, JsonValidationException { + void testCompleteSourceOAuth() throws IOException, InterruptedException, ConfigNotFoundException, JsonValidationException { final HttpResponse response = mock(HttpResponse.class); when(response.body()).thenReturn(getMockedResponse()); when(httpClient.send(any(), any())).thenReturn(response); @@ -416,7 +416,7 @@ public void testCompleteSourceOAuth() throws IOException, InterruptedException, } @Test - public void testCompleteDestinationOAuth() throws IOException, InterruptedException, ConfigNotFoundException, JsonValidationException { + void testCompleteDestinationOAuth() throws IOException, InterruptedException, ConfigNotFoundException, JsonValidationException { final HttpResponse response = mock(HttpResponse.class); when(response.body()).thenReturn(getMockedResponse()); when(httpClient.send(any(), any())).thenReturn(response); @@ -430,7 +430,7 @@ public void testCompleteDestinationOAuth() throws IOException, InterruptedExcept } @Test - public void testValidateOAuthOutputFailure() throws IOException, InterruptedException, ConfigNotFoundException, JsonValidationException { + void testValidateOAuthOutputFailure() throws IOException, InterruptedException, ConfigNotFoundException, JsonValidationException { final HttpResponse response = mock(HttpResponse.class); when(response.body()).thenReturn(getMockedResponse()); when(httpClient.send(any(), any())).thenReturn(response); diff --git a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/MicrosoftBingAdsOAuthFlowTest.java b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/MicrosoftBingAdsOAuthFlowTest.java index 9242e5acc738..267edfb21a4d 100644 --- a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/MicrosoftBingAdsOAuthFlowTest.java +++ b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/MicrosoftBingAdsOAuthFlowTest.java @@ -10,7 +10,8 @@ import java.util.Map; import org.junit.jupiter.api.Test; -public class MicrosoftBingAdsOAuthFlowTest extends BaseOAuthFlowTest { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class MicrosoftBingAdsOAuthFlowTest extends BaseOAuthFlowTest { @Override protected BaseOAuthFlow getOAuthFlow() { @@ -33,15 +34,19 @@ protected JsonNode getUserInputFromConnectorConfigSpecification() { } @Test - public void testEmptyInputCompleteDestinationOAuth() {} + @Override + void testEmptyInputCompleteDestinationOAuth() {} @Test - public void testDeprecatedCompleteDestinationOAuth() {} + @Override + void testDeprecatedCompleteDestinationOAuth() {} @Test - public void testDeprecatedCompleteSourceOAuth() {} + @Override + void testDeprecatedCompleteSourceOAuth() {} @Test - public void testEmptyInputCompleteSourceOAuth() {} + @Override + void testEmptyInputCompleteSourceOAuth() {} } diff --git a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/MicrosoftTeamsOAuthFlowTest.java b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/MicrosoftTeamsOAuthFlowTest.java index 5b04e4b8bcc6..d887b97a0612 100644 --- a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/MicrosoftTeamsOAuthFlowTest.java +++ b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/MicrosoftTeamsOAuthFlowTest.java @@ -10,7 +10,8 @@ import java.util.Map; import org.junit.jupiter.api.Test; -public class MicrosoftTeamsOAuthFlowTest extends BaseOAuthFlowTest { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class MicrosoftTeamsOAuthFlowTest extends BaseOAuthFlowTest { @Override protected BaseOAuthFlow getOAuthFlow() { @@ -33,9 +34,11 @@ protected JsonNode getUserInputFromConnectorConfigSpecification() { } @Test - public void testEmptyInputCompleteSourceOAuth() {} + @Override + void testEmptyInputCompleteSourceOAuth() {} @Test - public void testEmptyInputCompleteDestinationOAuth() {} + @Override + void testEmptyInputCompleteDestinationOAuth() {} } diff --git a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/MondayOAuthFlowTest.java b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/MondayOAuthFlowTest.java index 989cae7fdd2c..3c318fb2ec65 100644 --- a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/MondayOAuthFlowTest.java +++ b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/MondayOAuthFlowTest.java @@ -11,7 +11,8 @@ import java.util.Map; import org.junit.jupiter.api.Test; -public class MondayOAuthFlowTest extends BaseOAuthFlowTest { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class MondayOAuthFlowTest extends BaseOAuthFlowTest { @Override protected BaseOAuthFlow getOAuthFlow() { @@ -34,16 +35,20 @@ protected JsonNode getUserInputFromConnectorConfigSpecification() { } @Test - public void testGetSourceConsentUrlEmptyOAuthSpec() {} + @Override + void testGetSourceConsentUrlEmptyOAuthSpec() {} @Test - public void testGetDestinationConsentUrlEmptyOAuthSpec() {} + @Override + void testGetDestinationConsentUrlEmptyOAuthSpec() {} @Test - public void testDeprecatedCompleteDestinationOAuth() {} + @Override + void testDeprecatedCompleteDestinationOAuth() {} @Test - public void testDeprecatedCompleteSourceOAuth() {} + @Override + void testDeprecatedCompleteSourceOAuth() {} @Override protected Map getExpectedOutput() { diff --git a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/SnowflakeOAuthFlowTest.java b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/SnowflakeOAuthFlowTest.java index 314388cfa328..e217b569aa67 100644 --- a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/SnowflakeOAuthFlowTest.java +++ b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/SnowflakeOAuthFlowTest.java @@ -12,7 +12,8 @@ import java.util.Map; import org.junit.jupiter.api.Test; -public class SnowflakeOAuthFlowTest extends BaseOAuthFlowTest { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class SnowflakeOAuthFlowTest extends BaseOAuthFlowTest { @Override protected BaseOAuthFlow getOAuthFlow() { @@ -45,6 +46,7 @@ protected Map getExpectedFilteredOutput() { "client_id", MoreOAuthParameters.SECRET_MASK); } + @Override protected JsonNode getOAuthParamConfig() { return Jsons.jsonNode(ImmutableMap.builder() .put("client_id", "test_client_id") @@ -59,24 +61,25 @@ protected JsonNode getInputOAuthConfiguration() { .build()); } + @Override protected JsonNode getUserInputFromConnectorConfigSpecification() { return getJsonSchema(Map.of("host", Map.of("type", "string"))); } @Test @Override - public void testGetSourceConsentUrlEmptyOAuthSpec() {} + void testGetSourceConsentUrlEmptyOAuthSpec() {} @Test @Override - public void testGetDestinationConsentUrlEmptyOAuthSpec() {} + void testGetDestinationConsentUrlEmptyOAuthSpec() {} @Test @Override - public void testDeprecatedCompleteDestinationOAuth() {} + void testDeprecatedCompleteDestinationOAuth() {} @Test @Override - public void testDeprecatedCompleteSourceOAuth() {} + void testDeprecatedCompleteSourceOAuth() {} } diff --git a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/TikTokMarketingOAuthFlowTest.java b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/TikTokMarketingOAuthFlowTest.java index c2e332c91671..a7f4fcd86428 100644 --- a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/TikTokMarketingOAuthFlowTest.java +++ b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/TikTokMarketingOAuthFlowTest.java @@ -12,7 +12,8 @@ import java.util.Map; import org.junit.jupiter.api.Test; -public class TikTokMarketingOAuthFlowTest extends BaseOAuthFlowTest { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class TikTokMarketingOAuthFlowTest extends BaseOAuthFlowTest { @Override protected BaseOAuthFlow getOAuthFlow() { @@ -63,10 +64,10 @@ protected Map getExpectedFilteredOutput() { @Test @Override - public void testDeprecatedCompleteDestinationOAuth() {} + void testDeprecatedCompleteDestinationOAuth() {} @Test @Override - public void testDeprecatedCompleteSourceOAuth() {} + void testDeprecatedCompleteSourceOAuth() {} } diff --git a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/TrelloOAuthFlowTest.java b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/TrelloOAuthFlowTest.java index dda1c316d28d..c58e06eef9ac 100644 --- a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/TrelloOAuthFlowTest.java +++ b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/TrelloOAuthFlowTest.java @@ -28,7 +28,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class TrelloOAuthFlowTest { +class TrelloOAuthFlowTest { private static final String REDIRECT_URL = "https://airbyte.io"; @@ -39,7 +39,7 @@ public class TrelloOAuthFlowTest { private HttpTransport transport; @BeforeEach - public void setup() throws IOException, JsonValidationException { + void setup() throws IOException, JsonValidationException { workspaceId = UUID.randomUUID(); definitionId = UUID.randomUUID(); @@ -74,14 +74,14 @@ public LowLevelHttpResponse execute() throws IOException { } @Test - public void testGetSourceConsentUrl() throws IOException, InterruptedException, ConfigNotFoundException { + void testGetSourceConsentUrl() throws IOException, InterruptedException, ConfigNotFoundException { final String consentUrl = trelloOAuthFlow.getSourceConsentUrl(workspaceId, definitionId, REDIRECT_URL, Jsons.emptyObject(), null); assertEquals("https://trello.com/1/OAuthAuthorizeToken?oauth_token=test_token", consentUrl); } @Test - public void testCompleteSourceAuth() throws IOException, InterruptedException, ConfigNotFoundException { + void testCompleteSourceAuth() throws IOException, InterruptedException, ConfigNotFoundException { final Map expectedParams = Map.of( "key", "test_client_id", "token", "test_token", diff --git a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/ZendeskSunshineOAuthFlowTest.java b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/ZendeskSunshineOAuthFlowTest.java index f1400be41417..1c47f6b2cb23 100644 --- a/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/ZendeskSunshineOAuthFlowTest.java +++ b/airbyte-oauth/src/test/java/io/airbyte/oauth/flows/ZendeskSunshineOAuthFlowTest.java @@ -11,7 +11,8 @@ import java.util.Map; import org.junit.jupiter.api.Test; -public class ZendeskSunshineOAuthFlowTest extends BaseOAuthFlowTest { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class ZendeskSunshineOAuthFlowTest extends BaseOAuthFlowTest { @Override protected BaseOAuthFlow getOAuthFlow() { @@ -34,37 +35,48 @@ protected JsonNode getUserInputFromConnectorConfigSpecification() { } @Test - public void testEmptyOutputCompleteSourceOAuth() {} + @Override + void testEmptyOutputCompleteSourceOAuth() {} @Test - public void testGetSourceConsentUrlEmptyOAuthSpec() {} + @Override + void testGetSourceConsentUrlEmptyOAuthSpec() {} @Test - public void testValidateOAuthOutputFailure() {} + @Override + void testValidateOAuthOutputFailure() {} @Test - public void testCompleteSourceOAuth() {} + @Override + void testCompleteSourceOAuth() {} @Test - public void testEmptyInputCompleteDestinationOAuth() {} + @Override + void testEmptyInputCompleteDestinationOAuth() {} @Test - public void testDeprecatedCompleteDestinationOAuth() {} + @Override + void testDeprecatedCompleteDestinationOAuth() {} @Test - public void testDeprecatedCompleteSourceOAuth() {} + @Override + void testDeprecatedCompleteSourceOAuth() {} @Test - public void testEmptyOutputCompleteDestinationOAuth() {} + @Override + void testEmptyOutputCompleteDestinationOAuth() {} @Test - public void testCompleteDestinationOAuth() {} + @Override + void testCompleteDestinationOAuth() {} @Test - public void testGetDestinationConsentUrlEmptyOAuthSpec() {} + @Override + void testGetDestinationConsentUrlEmptyOAuthSpec() {} @Test - public void testEmptyInputCompleteSourceOAuth() {} + @Override + void testEmptyInputCompleteSourceOAuth() {} @Override protected Map getExpectedOutput() { diff --git a/airbyte-scheduler/client/src/main/java/io/airbyte/scheduler/client/TemporalEventRunner.java b/airbyte-scheduler/client/src/main/java/io/airbyte/scheduler/client/TemporalEventRunner.java index 90846af5cb98..76fc960f13b2 100644 --- a/airbyte-scheduler/client/src/main/java/io/airbyte/scheduler/client/TemporalEventRunner.java +++ b/airbyte-scheduler/client/src/main/java/io/airbyte/scheduler/client/TemporalEventRunner.java @@ -17,34 +17,42 @@ public class TemporalEventRunner implements EventRunner { private final TemporalClient temporalClient; + @Override public void createConnectionManagerWorkflow(final UUID connectionId) { temporalClient.submitConnectionUpdaterAsync(connectionId); } + @Override public ManualOperationResult startNewManualSync(final UUID connectionId) { return temporalClient.startNewManualSync(connectionId); } + @Override public ManualOperationResult startNewCancellation(final UUID connectionId) { return temporalClient.startNewCancellation(connectionId); } + @Override public ManualOperationResult resetConnection(final UUID connectionId, final List streamsToReset) { return temporalClient.resetConnection(connectionId, streamsToReset); } + @Override public ManualOperationResult synchronousResetConnection(final UUID connectionId, final List streamsToReset) { return temporalClient.synchronousResetConnection(connectionId, streamsToReset); } + @Override public void deleteConnection(final UUID connectionId) { temporalClient.deleteConnection(connectionId); } + @Override public void migrateSyncIfNeeded(final Set connectionIds) { temporalClient.migrateSyncIfNeeded(connectionIds); } + @Override public void update(final UUID connectionId) { temporalClient.update(connectionId); } diff --git a/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/DefaultJobPersistence.java b/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/DefaultJobPersistence.java index 0855bb0ca4a4..682d56c25a99 100644 --- a/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/DefaultJobPersistence.java +++ b/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/DefaultJobPersistence.java @@ -877,6 +877,7 @@ private static void registerImportMetadata(final DSLContext ctx, final String ai /** * Read @param jsonSchema and @returns a list of properties (converted as Field objects) */ + @SuppressWarnings("PMD.ForLoopCanBeForeach") private static List> getFields(final JsonNode jsonSchema) { final List> result = new ArrayList<>(); final JsonNode properties = jsonSchema.get("properties"); diff --git a/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/job_factory/DefaultSyncJobFactory.java b/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/job_factory/DefaultSyncJobFactory.java index 7414547d6bc4..86f0c43d7be9 100644 --- a/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/job_factory/DefaultSyncJobFactory.java +++ b/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/job_factory/DefaultSyncJobFactory.java @@ -39,6 +39,7 @@ public DefaultSyncJobFactory(final boolean connectorSpecificResourceDefaultsEnab this.oAuthConfigSupplier = oAuthConfigSupplier; } + @Override public Long create(final UUID connectionId) { try { final StandardSync standardSync = configRepository.getStandardSync(connectionId); diff --git a/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/job_tracker/JobTracker.java b/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/job_tracker/JobTracker.java index da3701bc3222..5088749f73fb 100644 --- a/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/job_tracker/JobTracker.java +++ b/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/job_tracker/JobTracker.java @@ -208,6 +208,7 @@ protected static Map configToMetadata(final String jsonPath, fin * flattened map. If config is _not_ an object (i.e. it's a primitive string/number/etc, or it's an * array) then returns a map of {null: toMetadataValue(config)}. */ + @SuppressWarnings("PMD.ForLoopCanBeForeach") private static Map configToMetadata(final JsonNode config, final JsonNode schema) { if (schema.hasNonNull("const") || schema.hasNonNull("enum")) { // If this schema is a const or an enum, then just dump it into a map: diff --git a/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/job_tracker/TrackingMetadata.java b/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/job_tracker/TrackingMetadata.java index 4c5aeeb00351..7bbe227b19c0 100644 --- a/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/job_tracker/TrackingMetadata.java +++ b/airbyte-scheduler/scheduler-persistence/src/main/java/io/airbyte/scheduler/persistence/job_tracker/TrackingMetadata.java @@ -142,19 +142,16 @@ private static ArrayNode failureReasonsListAsJson(final List fail private static JsonNode failureReasonAsJson(final FailureReason failureReason) { // we want the json to always include failureOrigin and failureType, even when they are null - return Jsons.jsonNode(new LinkedHashMap() { - - { - put("failureOrigin", failureReason.getFailureOrigin()); - put("failureType", failureReason.getFailureType()); - put("internalMessage", failureReason.getInternalMessage()); - put("externalMessage", failureReason.getExternalMessage()); - put("metadata", failureReason.getMetadata()); - put("retryable", failureReason.getRetryable()); - put("timestamp", failureReason.getTimestamp()); - } - - }); + final LinkedHashMap linkedHashMap = new LinkedHashMap<>(); + linkedHashMap.put("failureOrigin", failureReason.getFailureOrigin()); + linkedHashMap.put("failureType", failureReason.getFailureType()); + linkedHashMap.put("internalMessage", failureReason.getInternalMessage()); + linkedHashMap.put("externalMessage", failureReason.getExternalMessage()); + linkedHashMap.put("metadata", failureReason.getMetadata()); + linkedHashMap.put("retryable", failureReason.getRetryable()); + linkedHashMap.put("timestamp", failureReason.getTimestamp()); + + return Jsons.jsonNode(linkedHashMap); } } diff --git a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/DefaultJobCreatorTest.java b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/DefaultJobCreatorTest.java index fc9a1d0e8e8a..242f7ebd3da1 100644 --- a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/DefaultJobCreatorTest.java +++ b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/DefaultJobCreatorTest.java @@ -50,7 +50,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class DefaultJobCreatorTest { +class DefaultJobCreatorTest { private static final String STREAM1_NAME = "stream1"; private static final String STREAM2_NAME = "stream2"; diff --git a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/DefaultJobPersistenceTest.java b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/DefaultJobPersistenceTest.java index cbee507bf041..19d72139f483 100644 --- a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/DefaultJobPersistenceTest.java +++ b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/DefaultJobPersistenceTest.java @@ -78,6 +78,7 @@ import org.junit.jupiter.params.provider.CsvSource; import org.testcontainers.containers.PostgreSQLContainer; +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") @DisplayName("DefaultJobPersistance") class DefaultJobPersistenceTest { @@ -110,7 +111,7 @@ class DefaultJobPersistenceTest { private DSLContext dslContext; @BeforeAll - public static void dbSetup() { + static void dbSetup() { container = new PostgreSQLContainer<>("postgres:13-alpine") .withDatabaseName("airbyte") .withUsername("docker") @@ -119,7 +120,7 @@ public static void dbSetup() { } @AfterAll - public static void dbDown() { + static void dbDown() { container.close(); } @@ -174,7 +175,7 @@ private static Job createJob( @SuppressWarnings("unchecked") @BeforeEach - public void setup() throws Exception { + void setup() throws Exception { dataSource = DatabaseConnectionHelper.createDataSource(container); dslContext = DSLContextFactory.create(dataSource, SQLDialect.POSTGRES); final TestDatabaseProviders databaseProviders = new TestDatabaseProviders(dataSource, dslContext); @@ -297,7 +298,7 @@ void testGetLastSyncJobWithMultipleAttempts() throws IOException { @Test @DisplayName("Should extract a Job model from a JOOQ result set") - public void testGetJobFromRecord() throws IOException, SQLException { + void testGetJobFromRecord() throws IOException, SQLException { final long jobId = jobPersistence.enqueueJob(SCOPE, SPEC_JOB_CONFIG).orElseThrow(); final Optional actual = DefaultJobPersistence.getJobFromResult(getJobRecord(jobId)); @@ -728,7 +729,7 @@ class EnqueueJob { @Test @DisplayName("Should create initial job without attempt") - public void testCreateJobAndGetWithoutAttemptJob() throws IOException { + void testCreateJobAndGetWithoutAttemptJob() throws IOException { final long jobId = jobPersistence.enqueueJob(SCOPE, SPEC_JOB_CONFIG).orElseThrow(); final Job actual = jobPersistence.getJob(jobId); @@ -738,7 +739,7 @@ public void testCreateJobAndGetWithoutAttemptJob() throws IOException { @Test @DisplayName("Should not create a second job if a job under the same scope is in a non-terminal state") - public void testCreateJobNoQueueing() throws IOException { + void testCreateJobNoQueueing() throws IOException { final Optional jobId1 = jobPersistence.enqueueJob(SCOPE, SYNC_JOB_CONFIG); final Optional jobId2 = jobPersistence.enqueueJob(SCOPE, SYNC_JOB_CONFIG); @@ -752,7 +753,7 @@ public void testCreateJobNoQueueing() throws IOException { @Test @DisplayName("Should create a second job if a previous job under the same scope has failed") - public void testCreateJobIfPrevJobFailed() throws IOException { + void testCreateJobIfPrevJobFailed() throws IOException { final Optional jobId1 = jobPersistence.enqueueJob(SCOPE, SYNC_JOB_CONFIG); assertTrue(jobId1.isPresent()); @@ -806,7 +807,7 @@ class GetLastReplicationJob { @Test @DisplayName("Should return nothing if no job exists") - public void testGetLastSyncJobForConnectionIdEmpty() throws IOException { + void testGetLastSyncJobForConnectionIdEmpty() throws IOException { final Optional actual = jobPersistence.getLastReplicationJob(CONNECTION_ID); assertTrue(actual.isEmpty()); @@ -814,7 +815,7 @@ public void testGetLastSyncJobForConnectionIdEmpty() throws IOException { @Test @DisplayName("Should return the last enqueued job") - public void testGetLastSyncJobForConnectionId() throws IOException { + void testGetLastSyncJobForConnectionId() throws IOException { final long jobId1 = jobPersistence.enqueueJob(SCOPE, SYNC_JOB_CONFIG).orElseThrow(); jobPersistence.succeedAttempt(jobId1, jobPersistence.createAttempt(jobId1, LOG_PATH)); @@ -836,7 +837,7 @@ class GetFirstReplicationJob { @Test @DisplayName("Should return nothing if no job exists") - public void testGetFirstSyncJobForConnectionIdEmpty() throws IOException { + void testGetFirstSyncJobForConnectionIdEmpty() throws IOException { final Optional actual = jobPersistence.getFirstReplicationJob(CONNECTION_ID); assertTrue(actual.isEmpty()); @@ -844,7 +845,7 @@ public void testGetFirstSyncJobForConnectionIdEmpty() throws IOException { @Test @DisplayName("Should return the first job") - public void testGetFirstSyncJobForConnectionId() throws IOException { + void testGetFirstSyncJobForConnectionId() throws IOException { final long jobId1 = jobPersistence.enqueueJob(SCOPE, SYNC_JOB_CONFIG).orElseThrow(); jobPersistence.succeedAttempt(jobId1, jobPersistence.createAttempt(jobId1, LOG_PATH)); final List attemptsWithJobInfo = jobPersistence.listAttemptsWithJobInfo(SYNC_JOB_CONFIG.getConfigType(), Instant.EPOCH); @@ -868,7 +869,7 @@ class GetNextJob { @Test @DisplayName("Should always return oldest pending job") - public void testGetOldestPendingJob() throws IOException { + void testGetOldestPendingJob() throws IOException { final long jobId = createJobAt(NOW); createJobAt(NOW.plusSeconds(1000)); @@ -880,7 +881,7 @@ public void testGetOldestPendingJob() throws IOException { @Test @DisplayName("Should return nothing if no jobs pending") - public void testGetOldestPendingJobOnlyPendingJobs() throws IOException { + void testGetOldestPendingJobOnlyPendingJobs() throws IOException { final long jobId = jobPersistence.enqueueJob(SCOPE, SPEC_JOB_CONFIG).orElseThrow(); jobPersistence.cancelJob(jobId); @@ -913,7 +914,7 @@ void testGetNextJobWithMultipleAttempts() throws IOException { @Test @DisplayName("Should return oldest pending job even if another job with same scope failed") - public void testGetOldestPendingJobWithOtherJobWithSameScopeFailed() throws IOException { + void testGetOldestPendingJobWithOtherJobWithSameScopeFailed() throws IOException { // create a job and set it to incomplete. final long jobId = createJobAt(NOW.minusSeconds(1000)); jobPersistence.createAttempt(jobId, LOG_PATH); @@ -930,7 +931,7 @@ public void testGetOldestPendingJobWithOtherJobWithSameScopeFailed() throws IOEx @Test @DisplayName("Should return oldest pending job even if another job with same scope cancelled") - public void testGetOldestPendingJobWithOtherJobWithSameScopeCancelled() throws IOException { + void testGetOldestPendingJobWithOtherJobWithSameScopeCancelled() throws IOException { // create a job and set it to incomplete. final long jobId = createJobAt(NOW.minusSeconds(1000)); jobPersistence.cancelJob(jobId); @@ -946,7 +947,7 @@ public void testGetOldestPendingJobWithOtherJobWithSameScopeCancelled() throws I @Test @DisplayName("Should return oldest pending job even if another job with same scope succeeded") - public void testGetOldestPendingJobWithOtherJobWithSameScopeSucceeded() throws IOException { + void testGetOldestPendingJobWithOtherJobWithSameScopeSucceeded() throws IOException { // create a job and set it to incomplete. final long jobId = createJobAt(NOW.minusSeconds(1000)); final int attemptNumber = jobPersistence.createAttempt(jobId, LOG_PATH); @@ -963,7 +964,7 @@ public void testGetOldestPendingJobWithOtherJobWithSameScopeSucceeded() throws I @Test @DisplayName("Should not return pending job if job with same scope is running") - public void testGetOldestPendingJobWithOtherJobWithSameScopeRunning() throws IOException { + void testGetOldestPendingJobWithOtherJobWithSameScopeRunning() throws IOException { // create a job and set it to running. final long jobId = createJobAt(NOW.minusSeconds(1000)); jobPersistence.createAttempt(jobId, LOG_PATH); @@ -978,7 +979,7 @@ public void testGetOldestPendingJobWithOtherJobWithSameScopeRunning() throws IOE @Test @DisplayName("Should not return pending job if job with same scope is incomplete") - public void testGetOldestPendingJobWithOtherJobWithSameScopeIncomplete() throws IOException { + void testGetOldestPendingJobWithOtherJobWithSameScopeIncomplete() throws IOException { // create a job and set it to incomplete. final long jobId = createJobAt(NOW.minusSeconds(1000)); final int attemptNumber = jobPersistence.createAttempt(jobId, LOG_PATH); @@ -1002,7 +1003,7 @@ class ListJobs { @Test @DisplayName("Should return the correct page of results with multiple pages of history") - public void testListJobsByPage() throws IOException { + void testListJobsByPage() throws IOException { final List ids = new ArrayList(); for (int i = 0; i < 100; i++) { final long jobId = jobPersistence.enqueueJob(CONNECTION_ID.toString(), SPEC_JOB_CONFIG).orElseThrow(); @@ -1018,7 +1019,7 @@ public void testListJobsByPage() throws IOException { @Test @DisplayName("Should return the results in the correct sort order") - public void testListJobsSortsDescending() throws IOException { + void testListJobsSortsDescending() throws IOException { final List ids = new ArrayList(); for (int i = 0; i < 100; i++) { // These have strictly the same created_at due to the setup() above, so should come back sorted by @@ -1036,7 +1037,7 @@ public void testListJobsSortsDescending() throws IOException { @Test @DisplayName("Should list all jobs") - public void testListJobs() throws IOException { + void testListJobs() throws IOException { final long jobId = jobPersistence.enqueueJob(SCOPE, SPEC_JOB_CONFIG).orElseThrow(); final List actualList = jobPersistence.listJobs(SPEC_JOB_CONFIG.getConfigType(), CONNECTION_ID.toString(), 9999, 0); @@ -1050,7 +1051,7 @@ public void testListJobs() throws IOException { @Test @DisplayName("Should list all jobs with all attempts") - public void testListJobsWithMultipleAttempts() throws IOException { + void testListJobsWithMultipleAttempts() throws IOException { final long jobId = jobPersistence.enqueueJob(SCOPE, SPEC_JOB_CONFIG).orElseThrow(); final int attemptNumber0 = jobPersistence.createAttempt(jobId, LOG_PATH); @@ -1079,7 +1080,7 @@ public void testListJobsWithMultipleAttempts() throws IOException { @Test @DisplayName("Should list all jobs with all attempts in descending order") - public void testListJobsWithMultipleAttemptsInDescOrder() throws IOException { + void testListJobsWithMultipleAttemptsInDescOrder() throws IOException { // create first job with multiple attempts final var jobId1 = jobPersistence.enqueueJob(SCOPE, SPEC_JOB_CONFIG).orElseThrow(); final var job1Attempt1 = jobPersistence.createAttempt(jobId1, LOG_PATH); @@ -1110,7 +1111,7 @@ class ListJobsWithStatus { @Test @DisplayName("Should only list jobs with requested status") - public void testListJobsWithStatus() throws IOException { + void testListJobsWithStatus() throws IOException { // not failed. jobPersistence.enqueueJob(SCOPE, SPEC_JOB_CONFIG); // failed @@ -1135,7 +1136,7 @@ public void testListJobsWithStatus() throws IOException { @Test @DisplayName("Should only list jobs with requested status and config type") - public void testListJobsWithStatusAndConfigType() throws IOException, InterruptedException { + void testListJobsWithStatusAndConfigType() throws IOException, InterruptedException { // not failed. final long pendingSpecJobId = jobPersistence.enqueueJob(SPEC_SCOPE, SPEC_JOB_CONFIG).orElseThrow(); final long pendingSyncJobId = jobPersistence.enqueueJob(SYNC_SCOPE, SYNC_JOB_CONFIG).orElseThrow(); @@ -1177,7 +1178,7 @@ public void testListJobsWithStatusAndConfigType() throws IOException, Interrupte @Test @DisplayName("Should only list jobs for the requested connection and with the requested statuses and config types") - public void testListJobsWithStatusesAndConfigTypesForConnection() throws IOException, InterruptedException { + void testListJobsWithStatusesAndConfigTypesForConnection() throws IOException, InterruptedException { final UUID desiredConnectionId = UUID.randomUUID(); final UUID otherConnectionId = UUID.randomUUID(); @@ -1428,7 +1429,7 @@ class ListJobStatusAndTimestampWithConnection { @Test @DisplayName("Should list only job statuses and timestamps of specified connection id") - public void testConnectionIdFiltering() throws IOException { + void testConnectionIdFiltering() throws IOException { jobPersistence = new DefaultJobPersistence(jobDatabase, timeSupplier, DEFAULT_MINIMUM_AGE_IN_DAYS, DEFAULT_EXCESSIVE_NUMBER_OF_JOBS, DEFAULT_MINIMUM_RECENCY_COUNT); @@ -1453,7 +1454,7 @@ public void testConnectionIdFiltering() throws IOException { @Test @DisplayName("Should list jobs statuses filtered by different timestamps") - public void testTimestampFiltering() throws IOException { + void testTimestampFiltering() throws IOException { jobPersistence = new DefaultJobPersistence(jobDatabase, timeSupplier, DEFAULT_MINIMUM_AGE_IN_DAYS, DEFAULT_EXCESSIVE_NUMBER_OF_JOBS, DEFAULT_MINIMUM_RECENCY_COUNT); @@ -1506,7 +1507,7 @@ public void testTimestampFiltering() throws IOException { @Test @DisplayName("Should list jobs statuses of differing status types") - public void testMultipleJobStatusTypes() throws IOException { + void testMultipleJobStatusTypes() throws IOException { final Supplier timeSupplier = incrementingSecondSupplier(NOW); jobPersistence = new DefaultJobPersistence(jobDatabase, timeSupplier, DEFAULT_MINIMUM_AGE_IN_DAYS, DEFAULT_EXCESSIVE_NUMBER_OF_JOBS, DEFAULT_MINIMUM_RECENCY_COUNT); @@ -1539,7 +1540,7 @@ public void testMultipleJobStatusTypes() throws IOException { @Test @DisplayName("Should list jobs statuses of differing job config types") - public void testMultipleConfigTypes() throws IOException { + void testMultipleConfigTypes() throws IOException { final Set configTypes = Sets.newHashSet(ConfigType.GET_SPEC, ConfigType.CHECK_CONNECTION_DESTINATION); final Supplier timeSupplier = incrementingSecondSupplier(NOW); jobPersistence = new DefaultJobPersistence(jobDatabase, timeSupplier, DEFAULT_MINIMUM_AGE_IN_DAYS, DEFAULT_EXCESSIVE_NUMBER_OF_JOBS, diff --git a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/JobCleanerTest.java b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/JobCleanerTest.java index 5b9688ee3d94..587f21aa5928 100644 --- a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/JobCleanerTest.java +++ b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/JobCleanerTest.java @@ -29,7 +29,7 @@ class JobCleanerTest { Path folder; @Test - public void testNotDeletingFilesInMinimum() throws IOException { + void testNotDeletingFilesInMinimum() throws IOException { createFile(folder.resolve("1"), "A", 1, 10); final JobPersistence jobPersistence = mock(JobPersistence.class); @@ -48,7 +48,7 @@ public void testNotDeletingFilesInMinimum() throws IOException { } @Test - public void testDeletingOldFiles() throws IOException { + void testDeletingOldFiles() throws IOException { createFile(folder.resolve("1"), "A", 1, 100); final JobPersistence jobPersistence = mock(JobPersistence.class); @@ -69,7 +69,7 @@ public void testDeletingOldFiles() throws IOException { } @Test - public void testDeletingLargeFiles() throws IOException { + void testDeletingLargeFiles() throws IOException { createFile(folder.resolve("1"), "A", 1, 10); createFile(folder.resolve("1"), "B", 1, 10); createFile(folder.resolve("1"), "C", 1, 10); @@ -92,7 +92,7 @@ public void testDeletingLargeFiles() throws IOException { } @Test - public void testNotDeletingRunning() throws IOException { + void testNotDeletingRunning() throws IOException { createFile(folder.resolve("1"), "A", 1, 10); createFile(folder.resolve("1"), "B", 1, 10); createFile(folder.resolve("1"), "C", 1, 10); diff --git a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/WebUrlHelperTest.java b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/WebUrlHelperTest.java index d5e80775b737..66418954f338 100644 --- a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/WebUrlHelperTest.java +++ b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/WebUrlHelperTest.java @@ -8,7 +8,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class WebUrlHelperTest { +class WebUrlHelperTest { private static final UUID WORKSPACE_ID = UUID.randomUUID(); private static final UUID CONNECTION_ID = UUID.randomUUID(); diff --git a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/WorkspaceHelperTest.java b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/WorkspaceHelperTest.java index a4d31b9e6a2a..37f3fafe5f89 100644 --- a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/WorkspaceHelperTest.java +++ b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/WorkspaceHelperTest.java @@ -78,7 +78,7 @@ class WorkspaceHelperTest { WorkspaceHelper workspaceHelper; @BeforeEach - public void setup() throws IOException, JsonValidationException, ConfigNotFoundException { + void setup() throws IOException, JsonValidationException, ConfigNotFoundException { jobPersistence = mock(JobPersistence.class); configRepository = mock(ConfigRepository.class); @@ -95,7 +95,7 @@ public void setup() throws IOException, JsonValidationException, ConfigNotFoundE } @Test - public void testMissingObjectsRuntimeException() { + void testMissingObjectsRuntimeException() { assertThrows(RuntimeException.class, () -> workspaceHelper.getWorkspaceForSourceIdIgnoreExceptions(UUID.randomUUID())); assertThrows(RuntimeException.class, () -> workspaceHelper.getWorkspaceForDestinationIdIgnoreExceptions(UUID.randomUUID())); assertThrows(RuntimeException.class, () -> workspaceHelper.getWorkspaceForConnectionIdIgnoreExceptions(UUID.randomUUID())); @@ -105,7 +105,7 @@ public void testMissingObjectsRuntimeException() { } @Test - public void testMissingObjectsProperException() { + void testMissingObjectsProperException() { assertThrows(ConfigNotFoundException.class, () -> workspaceHelper.getWorkspaceForSourceId(UUID.randomUUID())); assertThrows(ConfigNotFoundException.class, () -> workspaceHelper.getWorkspaceForDestinationId(UUID.randomUUID())); assertThrows(ConfigNotFoundException.class, () -> workspaceHelper.getWorkspaceForConnectionId(UUID.randomUUID())); @@ -116,7 +116,7 @@ public void testMissingObjectsProperException() { @Test @DisplayName("Validate that source caching is working") - public void testSource() throws IOException, JsonValidationException, ConfigNotFoundException { + void testSource() throws IOException, JsonValidationException, ConfigNotFoundException { final UUID retrievedWorkspace = workspaceHelper.getWorkspaceForSourceIdIgnoreExceptions(SOURCE_ID); assertEquals(WORKSPACE_ID, retrievedWorkspace); verify(configRepository, times(1)).getSourceConnection(SOURCE_ID); @@ -128,7 +128,7 @@ public void testSource() throws IOException, JsonValidationException, ConfigNotF @Test @DisplayName("Validate that destination caching is working") - public void testDestination() throws IOException, JsonValidationException, ConfigNotFoundException { + void testDestination() throws IOException, JsonValidationException, ConfigNotFoundException { final UUID retrievedWorkspace = workspaceHelper.getWorkspaceForDestinationIdIgnoreExceptions(DEST_ID); assertEquals(WORKSPACE_ID, retrievedWorkspace); verify(configRepository, times(1)).getDestinationConnection(DEST_ID); @@ -139,7 +139,7 @@ public void testDestination() throws IOException, JsonValidationException, Confi } @Test - public void testConnection() throws IOException, JsonValidationException, ConfigNotFoundException { + void testConnection() throws IOException, JsonValidationException, ConfigNotFoundException { // test retrieving by connection id final UUID retrievedWorkspace = workspaceHelper.getWorkspaceForConnectionIdIgnoreExceptions(CONNECTION_ID); assertEquals(WORKSPACE_ID, retrievedWorkspace); @@ -155,7 +155,7 @@ public void testConnection() throws IOException, JsonValidationException, Config } @Test - public void testOperation() throws IOException, JsonValidationException, ConfigNotFoundException { + void testOperation() throws IOException, JsonValidationException, ConfigNotFoundException { // test retrieving by connection id final UUID retrievedWorkspace = workspaceHelper.getWorkspaceForOperationIdIgnoreExceptions(OPERATION_ID); assertEquals(WORKSPACE_ID, retrievedWorkspace); @@ -166,7 +166,7 @@ public void testOperation() throws IOException, JsonValidationException, ConfigN } @Test - public void testConnectionAndJobs() throws IOException { + void testConnectionAndJobs() throws IOException { // test jobs final long jobId = 123; final Job job = new Job( diff --git a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/JobErrorReporterTest.java b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/JobErrorReporterTest.java index 8580a440a7fd..0cc6fc146e8f 100644 --- a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/JobErrorReporterTest.java +++ b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/JobErrorReporterTest.java @@ -26,7 +26,7 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -public class JobErrorReporterTest { +class JobErrorReporterTest { private static final UUID WORKSPACE_ID = UUID.randomUUID(); private static final UUID CONNECTION_ID = UUID.randomUUID(); diff --git a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/JobErrorReportingClientFactoryTest.java b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/JobErrorReportingClientFactoryTest.java index b6ebd65ad6a5..ae3f7cede3e6 100644 --- a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/JobErrorReportingClientFactoryTest.java +++ b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/JobErrorReportingClientFactoryTest.java @@ -11,7 +11,7 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -public class JobErrorReportingClientFactoryTest { +class JobErrorReportingClientFactoryTest { @Test void testCreateErrorReportingClientLogging() { diff --git a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/SentryExceptionHelperTest.java b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/SentryExceptionHelperTest.java index df49a4d55672..78c34b295d0d 100644 --- a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/SentryExceptionHelperTest.java +++ b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/SentryExceptionHelperTest.java @@ -13,7 +13,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class SentryExceptionHelperTest { +class SentryExceptionHelperTest { final SentryExceptionHelper exceptionHelper = new SentryExceptionHelper(); diff --git a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/SentryJobErrorReportingClientTest.java b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/SentryJobErrorReportingClientTest.java index cff663df1b19..69d6f16f1d04 100644 --- a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/SentryJobErrorReportingClientTest.java +++ b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_error_reporter/SentryJobErrorReportingClientTest.java @@ -32,7 +32,7 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -public class SentryJobErrorReportingClientTest { +class SentryJobErrorReportingClientTest { private static final UUID WORKSPACE_ID = UUID.randomUUID(); private static final String WORKSPACE_NAME = "My Workspace"; diff --git a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_factory/OAuthConfigSupplierTest.java b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_factory/OAuthConfigSupplierTest.java index a402327b48ec..39f13dc22f18 100644 --- a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_factory/OAuthConfigSupplierTest.java +++ b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_factory/OAuthConfigSupplierTest.java @@ -33,11 +33,11 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class OAuthConfigSupplierTest { +class OAuthConfigSupplierTest { - public static final String API_CLIENT = "api_client"; - public static final String CREDENTIALS = "credentials"; - public static final String PROPERTIES = "properties"; + static final String API_CLIENT = "api_client"; + static final String CREDENTIALS = "credentials"; + static final String PROPERTIES = "properties"; private ConfigRepository configRepository; private TrackingClient trackingClient; @@ -45,7 +45,7 @@ public class OAuthConfigSupplierTest { private UUID sourceDefinitionId; @BeforeEach - public void setup() throws JsonValidationException, ConfigNotFoundException, IOException { + void setup() throws JsonValidationException, ConfigNotFoundException, IOException { configRepository = mock(ConfigRepository.class); trackingClient = mock(TrackingClient.class); oAuthConfigSupplier = new OAuthConfigSupplier(configRepository, trackingClient); @@ -56,7 +56,7 @@ public void setup() throws JsonValidationException, ConfigNotFoundException, IOE } @Test - public void testNoOAuthInjectionBecauseEmptyParams() throws IOException { + void testNoOAuthInjectionBecauseEmptyParams() throws IOException { final JsonNode config = generateJsonConfig(); final UUID workspaceId = UUID.randomUUID(); final JsonNode actualConfig = oAuthConfigSupplier.injectSourceOAuthParameters(sourceDefinitionId, workspaceId, Jsons.clone(config)); @@ -65,7 +65,7 @@ public void testNoOAuthInjectionBecauseEmptyParams() throws IOException { } @Test - public void testNoOAuthInjectionBecauseMissingPredicateKey() throws IOException, JsonValidationException, ConfigNotFoundException { + void testNoOAuthInjectionBecauseMissingPredicateKey() throws IOException, JsonValidationException, ConfigNotFoundException { setupStandardDefinitionMock(createAdvancedAuth() .withPredicateKey(List.of("some_random_fields", "auth_type")) .withPredicateValue("oauth")); @@ -78,7 +78,7 @@ public void testNoOAuthInjectionBecauseMissingPredicateKey() throws IOException, } @Test - public void testNoOAuthInjectionBecauseWrongPredicateValue() throws IOException, JsonValidationException, ConfigNotFoundException { + void testNoOAuthInjectionBecauseWrongPredicateValue() throws IOException, JsonValidationException, ConfigNotFoundException { setupStandardDefinitionMock(createAdvancedAuth() .withPredicateKey(List.of(CREDENTIALS, "auth_type")) .withPredicateValue("wrong_auth_type")); @@ -91,7 +91,7 @@ public void testNoOAuthInjectionBecauseWrongPredicateValue() throws IOException, } @Test - public void testOAuthInjection() throws JsonValidationException, IOException { + void testOAuthInjection() throws JsonValidationException, IOException { final JsonNode config = generateJsonConfig(); final UUID workspaceId = UUID.randomUUID(); final Map oauthParameters = generateOAuthParameters(); @@ -103,7 +103,7 @@ public void testOAuthInjection() throws JsonValidationException, IOException { } @Test - public void testOAuthInjectionWithoutPredicate() throws JsonValidationException, IOException, ConfigNotFoundException { + void testOAuthInjectionWithoutPredicate() throws JsonValidationException, IOException, ConfigNotFoundException { setupStandardDefinitionMock(createAdvancedAuth() .withPredicateKey(null) .withPredicateValue(null)); @@ -118,7 +118,7 @@ public void testOAuthInjectionWithoutPredicate() throws JsonValidationException, } @Test - public void testOAuthInjectionWithoutPredicateValue() throws JsonValidationException, IOException, ConfigNotFoundException { + void testOAuthInjectionWithoutPredicateValue() throws JsonValidationException, IOException, ConfigNotFoundException { setupStandardDefinitionMock(createAdvancedAuth() .withPredicateKey(List.of(CREDENTIALS, "auth_type")) .withPredicateValue("")); @@ -133,7 +133,7 @@ public void testOAuthInjectionWithoutPredicateValue() throws JsonValidationExcep } @Test - public void testOAuthFullInjectionBecauseNoOAuthSpec() throws JsonValidationException, IOException, ConfigNotFoundException { + void testOAuthFullInjectionBecauseNoOAuthSpec() throws JsonValidationException, IOException, ConfigNotFoundException { final JsonNode config = generateJsonConfig(); final UUID workspaceId = UUID.randomUUID(); final Map oauthParameters = generateOAuthParameters(); @@ -155,7 +155,7 @@ public void testOAuthFullInjectionBecauseNoOAuthSpec() throws JsonValidationExce } @Test - public void testOAuthInjectionScopedToWorkspace() throws JsonValidationException, IOException { + void testOAuthInjectionScopedToWorkspace() throws JsonValidationException, IOException { final JsonNode config = generateJsonConfig(); final UUID workspaceId = UUID.randomUUID(); final Map oauthParameters = generateOAuthParameters(); @@ -177,7 +177,7 @@ public void testOAuthInjectionScopedToWorkspace() throws JsonValidationException } @Test - public void testOAuthFullInjectionBecauseNoOAuthSpecNestedParameters() throws JsonValidationException, IOException, ConfigNotFoundException { + void testOAuthFullInjectionBecauseNoOAuthSpecNestedParameters() throws JsonValidationException, IOException, ConfigNotFoundException { // Until https://github.com/airbytehq/airbyte/issues/7624 is solved, we need to handle nested oauth // parameters final JsonNode config = generateJsonConfig(); @@ -196,7 +196,7 @@ public void testOAuthFullInjectionBecauseNoOAuthSpecNestedParameters() throws Js } @Test - public void testOAuthInjectionNestedParameters() throws JsonValidationException, IOException { + void testOAuthInjectionNestedParameters() throws JsonValidationException, IOException { // Until https://github.com/airbytehq/airbyte/issues/7624 is solved, we need to handle nested oauth // parameters final JsonNode config = generateJsonConfig(); diff --git a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_tracker/JobTrackerTest.java b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_tracker/JobTrackerTest.java index f9edbf365ab7..b00582ca14c0 100644 --- a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_tracker/JobTrackerTest.java +++ b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_tracker/JobTrackerTest.java @@ -64,6 +64,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") class JobTrackerTest { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @@ -344,47 +345,35 @@ void testAsynchronousAttempt(final ConfigType configType, final Map additionalExpectedMetadata) throws ConfigNotFoundException, IOException, JsonValidationException { - final JsonNode configFailureJson = Jsons.jsonNode(new LinkedHashMap() { - - { - put("failureOrigin", "source"); - put("failureType", "config_error"); - put("internalMessage", "Internal config error error msg"); - put("externalMessage", "Config error related msg"); - put("metadata", ImmutableMap.of("some", "metadata")); - put("retryable", true); - put("timestamp", 1010); - } - - }); - - final JsonNode systemFailureJson = Jsons.jsonNode(new LinkedHashMap() { - - { - put("failureOrigin", "replication"); - put("failureType", "system_error"); - put("internalMessage", "Internal system error error msg"); - put("externalMessage", "System error related msg"); - put("metadata", ImmutableMap.of("some", "metadata")); - put("retryable", true); - put("timestamp", 1100); - } - - }); - - final JsonNode unknownFailureJson = Jsons.jsonNode(new LinkedHashMap() { - - { - put("failureOrigin", null); - put("failureType", null); - put("internalMessage", "Internal unknown error error msg"); - put("externalMessage", "Unknown error related msg"); - put("metadata", ImmutableMap.of("some", "metadata")); - put("retryable", true); - put("timestamp", 1110); - } - - }); + final LinkedHashMap linkedHashMap = new LinkedHashMap<>(); + linkedHashMap.put("failureOrigin", "source"); + linkedHashMap.put("failureType", "config_error"); + linkedHashMap.put("internalMessage", "Internal config error error msg"); + linkedHashMap.put("externalMessage", "Config error related msg"); + linkedHashMap.put("metadata", ImmutableMap.of("some", "metadata")); + linkedHashMap.put("retryable", true); + linkedHashMap.put("timestamp", 1010); + final JsonNode configFailureJson = Jsons.jsonNode(linkedHashMap); + + final LinkedHashMap linkedHashMap1 = new LinkedHashMap<>(); + linkedHashMap1.put("failureOrigin", "replication"); + linkedHashMap1.put("failureType", "system_error"); + linkedHashMap1.put("internalMessage", "Internal system error error msg"); + linkedHashMap1.put("externalMessage", "System error related msg"); + linkedHashMap1.put("metadata", ImmutableMap.of("some", "metadata")); + linkedHashMap1.put("retryable", true); + linkedHashMap1.put("timestamp", 1100); + final JsonNode systemFailureJson = Jsons.jsonNode(linkedHashMap1); + + final LinkedHashMap linkedHashMap2 = new LinkedHashMap<>(); + linkedHashMap2.put("failureOrigin", null); + linkedHashMap2.put("failureType", null); + linkedHashMap2.put("internalMessage", "Internal unknown error error msg"); + linkedHashMap2.put("externalMessage", "Unknown error related msg"); + linkedHashMap2.put("metadata", ImmutableMap.of("some", "metadata")); + linkedHashMap2.put("retryable", true); + linkedHashMap2.put("timestamp", 1110); + final JsonNode unknownFailureJson = Jsons.jsonNode(linkedHashMap2); final Map failureMetadata = ImmutableMap.of( "failure_reasons", Jsons.arrayNode().addAll(Arrays.asList(configFailureJson, systemFailureJson, unknownFailureJson)).toString(), diff --git a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_tracker/TrackingMetadataTest.java b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_tracker/TrackingMetadataTest.java index 756593ad313e..84322e8f4ef7 100644 --- a/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_tracker/TrackingMetadataTest.java +++ b/airbyte-scheduler/scheduler-persistence/src/test/java/io/airbyte/scheduler/persistence/job_tracker/TrackingMetadataTest.java @@ -18,7 +18,7 @@ class TrackingMetadataTest { @Test - public void testNulls() { + void testNulls() { final UUID connectionId = UUID.randomUUID(); final StandardSync standardSync = mock(StandardSync.class); diff --git a/airbyte-server/src/main/java/io/airbyte/server/ConfigDumpImporter.java b/airbyte-server/src/main/java/io/airbyte/server/ConfigDumpImporter.java index 7535a019b2ac..7e19691bc8fe 100644 --- a/airbyte-server/src/main/java/io/airbyte/server/ConfigDumpImporter.java +++ b/airbyte-server/src/main/java/io/airbyte/server/ConfigDumpImporter.java @@ -58,6 +58,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@SuppressWarnings("PMD.AvoidReassigningLoopVariables") public class ConfigDumpImporter { private static final Logger LOGGER = LoggerFactory.getLogger(ConfigDumpImporter.class); diff --git a/airbyte-server/src/test/java/io/airbyte/server/ConfigDumpImporterTest.java b/airbyte-server/src/test/java/io/airbyte/server/ConfigDumpImporterTest.java index c2083d2d1e92..5c43d0cbfde2 100644 --- a/airbyte-server/src/test/java/io/airbyte/server/ConfigDumpImporterTest.java +++ b/airbyte-server/src/test/java/io/airbyte/server/ConfigDumpImporterTest.java @@ -45,7 +45,7 @@ class ConfigDumpImporterTest { - public static final AirbyteVersion TEST_VERSION = new AirbyteVersion("0.0.1-test-version"); + static final AirbyteVersion TEST_VERSION = new AirbyteVersion("0.0.1-test-version"); private ConfigRepository configRepository; private SecretsRepositoryReader secretsRepositoryReader; @@ -61,7 +61,7 @@ class ConfigDumpImporterTest { private ConnectorSpecification emptyConnectorSpec; @BeforeEach - public void setup() throws IOException, JsonValidationException, ConfigNotFoundException { + void setup() throws IOException, JsonValidationException, ConfigNotFoundException { configRepository = mock(ConfigRepository.class); secretsRepositoryReader = mock(SecretsRepositoryReader.class); secretsRepositoryWriter = mock(SecretsRepositoryWriter.class); @@ -149,7 +149,7 @@ public void setup() throws IOException, JsonValidationException, ConfigNotFoundE } @Test - public void testImportIntoWorkspaceWithConflicts() throws JsonValidationException, ConfigNotFoundException, IOException { + void testImportIntoWorkspaceWithConflicts() throws JsonValidationException, ConfigNotFoundException, IOException { when(secretsRepositoryReader.listSourceConnectionWithSecrets()) .thenReturn(List.of(sourceConnection, new SourceConnection() @@ -185,7 +185,7 @@ public void testImportIntoWorkspaceWithConflicts() throws JsonValidationExceptio } @Test - public void testImportIntoWorkspaceWithoutConflicts() throws JsonValidationException, ConfigNotFoundException, IOException { + void testImportIntoWorkspaceWithoutConflicts() throws JsonValidationException, ConfigNotFoundException, IOException { when(secretsRepositoryReader.listSourceConnectionWithSecrets()) // First called for export .thenReturn(List.of(sourceConnection, @@ -235,7 +235,7 @@ public void testImportIntoWorkspaceWithoutConflicts() throws JsonValidationExcep } @Test - public void testReplaceDeploymentMetadata() throws Exception { + void testReplaceDeploymentMetadata() throws Exception { final UUID oldDeploymentUuid = UUID.randomUUID(); final UUID newDeploymentUuid = UUID.randomUUID(); diff --git a/airbyte-server/src/test/java/io/airbyte/server/RequestLoggerTest.java b/airbyte-server/src/test/java/io/airbyte/server/RequestLoggerTest.java index b5f33a416eec..46498b4e0b60 100644 --- a/airbyte-server/src/test/java/io/airbyte/server/RequestLoggerTest.java +++ b/airbyte-server/src/test/java/io/airbyte/server/RequestLoggerTest.java @@ -36,8 +36,9 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.MDC; +@SuppressWarnings({"PMD.AvoidPrintStackTrace", "PMD.JUnitTestsShouldIncludeAssert"}) @ExtendWith(MockitoExtension.class) -public class RequestLoggerTest { +class RequestLoggerTest { private static final String VALID_JSON_OBJECT = "{\"valid\":1}"; private static final String INVALID_JSON_OBJECT = "invalid"; @@ -56,7 +57,7 @@ public class RequestLoggerTest { private Path logPath; @BeforeEach - public void init() throws IOException { + void init() throws IOException { Mockito.when(mServletRequest.getMethod()) .thenReturn(METHOD); Mockito.when(mServletRequest.getRemoteAddr()) @@ -75,7 +76,7 @@ public void init() throws IOException { @Nested @DisplayName("Formats logs correctly") - public class RequestLoggerFormatsLogsCorrectly { + class RequestLoggerFormatsLogsCorrectly { private static final int ERROR_CODE = 401; private static final int SUCCESS_CODE = 200; @@ -108,7 +109,7 @@ static Stream logScenarios() { @ParameterizedTest @MethodSource("logScenarios") @DisplayName("Check that the proper log is produced based on the scenario") - public void test(final String requestBody, final String contentType, final int status, final String expectedLog) throws IOException { + void test(final String requestBody, final String contentType, final int status, final String expectedLog) throws IOException { // We have to instanciate the logger here, because the MDC config has been changed to log in a // temporary file. requestLogger = new RequestLogger(MDC.getCopyOfContextMap(), mServletRequest); @@ -139,7 +140,7 @@ public void test(final String requestBody, final String contentType, final int s @Nested @DisplayName("Logs correct requestBody") - public class RequestLoggerCorrectRequestBody { + class RequestLoggerCorrectRequestBody { /** * This is a complex test that was written to prove that our requestLogger had a concurrency bug @@ -160,7 +161,7 @@ public class RequestLoggerCorrectRequestBody { * some request bodies are overwritten before they can be logged. */ @Test - public void testRequestBodyConsistency() { + void testRequestBodyConsistency() { Mockito.when(mServletRequest.getHeader("Content-Type")) .thenReturn(ACCEPTED_CONTENT_TYPE); @@ -204,13 +205,14 @@ private RequestResponseRunnable createRunnableTestCase(final RequestLogger reque } @RequiredArgsConstructor - public class RequestResponseRunnable implements Runnable { + class RequestResponseRunnable implements Runnable { private final RequestLogger requestLogger; private final String expectedRequestBody; private final ContainerRequestContext mRequestContext; private final ContainerResponseContext mResponseContext; + @Override public void run() { try { requestLogger.filter(mRequestContext); @@ -222,7 +224,7 @@ public void run() { } // search all log lines to see if this thread's request body was logged - public Boolean requestBodyWasLogged() { + Boolean requestBodyWasLogged() { return IOs.readFile(logPath).lines().anyMatch(line -> line.contains(expectedRequestBody)); } diff --git a/airbyte-server/src/test/java/io/airbyte/server/apis/ConfigurationApiTest.java b/airbyte-server/src/test/java/io/airbyte/server/apis/ConfigurationApiTest.java index 36f6b211ad9d..ef0b6c320188 100644 --- a/airbyte-server/src/test/java/io/airbyte/server/apis/ConfigurationApiTest.java +++ b/airbyte-server/src/test/java/io/airbyte/server/apis/ConfigurationApiTest.java @@ -28,7 +28,7 @@ import org.flywaydb.core.Flyway; import org.junit.jupiter.api.Test; -public class ConfigurationApiTest { +class ConfigurationApiTest { @Test void testImportDefinitions() { diff --git a/airbyte-server/src/test/java/io/airbyte/server/converters/OauthModelConverterTest.java b/airbyte-server/src/test/java/io/airbyte/server/converters/OauthModelConverterTest.java index dba588aeca06..c96a23d1bab1 100644 --- a/airbyte-server/src/test/java/io/airbyte/server/converters/OauthModelConverterTest.java +++ b/airbyte-server/src/test/java/io/airbyte/server/converters/OauthModelConverterTest.java @@ -44,7 +44,7 @@ private static Stream testProvider() { @ParameterizedTest @MethodSource("testProvider") - public void testIt(final List> initParams, final List> outputParams, final List rootObject) { + void testIt(final List> initParams, final List> outputParams, final List rootObject) { final ConnectorSpecification input = new ConnectorSpecification().withAuthSpecification( new AuthSpecification() .withAuthType(AuthSpecification.AuthType.OAUTH_2_0) diff --git a/airbyte-server/src/test/java/io/airbyte/server/handlers/ArchiveHandlerTest.java b/airbyte-server/src/test/java/io/airbyte/server/handlers/ArchiveHandlerTest.java index 836d8e36be10..02e80e50082d 100644 --- a/airbyte-server/src/test/java/io/airbyte/server/handlers/ArchiveHandlerTest.java +++ b/airbyte-server/src/test/java/io/airbyte/server/handlers/ArchiveHandlerTest.java @@ -78,7 +78,7 @@ import org.testcontainers.shaded.com.google.common.collect.ImmutableMap; import org.testcontainers.shaded.org.apache.commons.io.FileUtils; -public class ArchiveHandlerTest { +class ArchiveHandlerTest { private static final Logger LOGGER = LoggerFactory.getLogger(ArchiveHandlerTest.class); @@ -104,12 +104,13 @@ public NoOpFileTtlManager() { super(1L, TimeUnit.MINUTES, 1L); } + @Override public void register(final Path path) {} } @BeforeAll - public static void dbSetup() { + static void dbSetup() { container = new PostgreSQLContainer<>("postgres:13-alpine") .withDatabaseName("airbyte") .withUsername("docker") @@ -118,12 +119,12 @@ public static void dbSetup() { } @AfterAll - public static void dbDown() { + static void dbDown() { container.close(); } @BeforeEach - public void setup() throws Exception { + void setup() throws Exception { dataSource = DatabaseConnectionHelper.createDataSource(container); dslContext = DSLContextFactory.create(dataSource, SQLDialect.POSTGRES); final TestDatabaseProviders databaseProviders = new TestDatabaseProviders(dataSource, dslContext); diff --git a/airbyte-server/src/test/java/io/airbyte/server/handlers/JobHistoryHandlerTest.java b/airbyte-server/src/test/java/io/airbyte/server/handlers/JobHistoryHandlerTest.java index 8b439621f02f..521b5cf18079 100644 --- a/airbyte-server/src/test/java/io/airbyte/server/handlers/JobHistoryHandlerTest.java +++ b/airbyte-server/src/test/java/io/airbyte/server/handlers/JobHistoryHandlerTest.java @@ -41,7 +41,7 @@ import org.junit.jupiter.api.Test; @DisplayName("Job History Handler") -public class JobHistoryHandlerTest { +class JobHistoryHandlerTest { private static final long JOB_ID = 100L; private static final long ATTEMPT_ID = 1002L; @@ -113,7 +113,7 @@ private static Attempt createSuccessfulAttempt(final long jobId, final long time } @BeforeEach - public void setUp() throws IOException, JsonValidationException, ConfigNotFoundException { + void setUp() throws IOException, JsonValidationException, ConfigNotFoundException { testJobAttempt = createSuccessfulAttempt(JOB_ID, CREATED_AT); testJob = new Job(JOB_ID, JOB_CONFIG.getConfigType(), JOB_CONFIG_ID, JOB_CONFIG, ImmutableList.of(testJobAttempt), JOB_STATUS, null, CREATED_AT, CREATED_AT); @@ -135,7 +135,7 @@ class ListJobs { @Test @DisplayName("Should return jobs with/without attempts in descending order") - public void testListJobs() throws IOException { + void testListJobs() throws IOException { final var successfulJob = testJob; final int pagesize = 25; final int rowOffset = 0; @@ -165,7 +165,7 @@ public void testListJobs() throws IOException { @Test @DisplayName("Should return jobs in descending order regardless of type") - public void testListJobsFor() throws IOException { + void testListJobsFor() throws IOException { final var firstJob = testJob; final int pagesize = 25; final int rowOffset = 0; @@ -209,7 +209,7 @@ public void testListJobsFor() throws IOException { @Test @DisplayName("Should return the right job info") - public void testGetJobInfo() throws IOException { + void testGetJobInfo() throws IOException { when(jobPersistence.getJob(JOB_ID)).thenReturn(testJob); final JobIdRequestBody requestBody = new JobIdRequestBody().id(JOB_ID); @@ -222,7 +222,7 @@ public void testGetJobInfo() throws IOException { @Test @DisplayName("Should return the right info to debug this job") - public void testGetDebugJobInfo() throws IOException, JsonValidationException, ConfigNotFoundException, URISyntaxException { + void testGetDebugJobInfo() throws IOException, JsonValidationException, ConfigNotFoundException, URISyntaxException { standardSourceDefinition = SourceDefinitionHelpers.generateSourceDefinition(); final SourceConnection source = SourceHelpers.generateSource(UUID.randomUUID()); sourceRead = SourceHelpers.getSourceRead(source, standardSourceDefinition); @@ -253,7 +253,7 @@ public void testGetDebugJobInfo() throws IOException, JsonValidationException, C @Test @DisplayName("Should have compatible config enums") - public void testEnumConversion() { + void testEnumConversion() { assertTrue(Enums.isCompatible(JobConfig.ConfigType.class, JobConfigType.class)); } diff --git a/airbyte-server/src/test/java/io/airbyte/server/handlers/LogsHandlerTest.java b/airbyte-server/src/test/java/io/airbyte/server/handlers/LogsHandlerTest.java index 6c95d8591a13..3ae3065d7549 100644 --- a/airbyte-server/src/test/java/io/airbyte/server/handlers/LogsHandlerTest.java +++ b/airbyte-server/src/test/java/io/airbyte/server/handlers/LogsHandlerTest.java @@ -21,7 +21,7 @@ class LogsHandlerTest { @Test - public void testServerLogs() { + void testServerLogs() { final Configs configs = mock(Configs.class); when(configs.getWorkspaceRoot()).thenReturn(Path.of("/workspace")); when(configs.getWorkerEnvironment()).thenReturn(WorkerEnvironment.DOCKER); @@ -35,7 +35,7 @@ public void testServerLogs() { } @Test - public void testSchedulerLogs() { + void testSchedulerLogs() { final Configs configs = mock(Configs.class); when(configs.getWorkspaceRoot()).thenReturn(Path.of("/workspace")); when(configs.getWorkerEnvironment()).thenReturn(WorkerEnvironment.DOCKER); diff --git a/airbyte-server/src/test/java/io/airbyte/server/handlers/OpenApiConfigHandlerTest.java b/airbyte-server/src/test/java/io/airbyte/server/handlers/OpenApiConfigHandlerTest.java index c0759d9e150b..5b7311433e9b 100644 --- a/airbyte-server/src/test/java/io/airbyte/server/handlers/OpenApiConfigHandlerTest.java +++ b/airbyte-server/src/test/java/io/airbyte/server/handlers/OpenApiConfigHandlerTest.java @@ -15,7 +15,7 @@ class OpenApiConfigHandlerTest { @Test - public void testGetFile() throws IOException { + void testGetFile() throws IOException { final List lines = Files.readLines(new OpenApiConfigHandler().getFile(), Charset.defaultCharset()); assertTrue(lines.get(0).contains("openapi")); } diff --git a/airbyte-server/src/test/java/io/airbyte/server/handlers/StateHandlerTest.java b/airbyte-server/src/test/java/io/airbyte/server/handlers/StateHandlerTest.java index e99303875ce5..13f2f79e6388 100644 --- a/airbyte-server/src/test/java/io/airbyte/server/handlers/StateHandlerTest.java +++ b/airbyte-server/src/test/java/io/airbyte/server/handlers/StateHandlerTest.java @@ -32,7 +32,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class StateHandlerTest { +class StateHandlerTest { public static final UUID CONNECTION_ID = UUID.randomUUID(); private static final JsonNode JSON_BLOB = Jsons.deserialize("{\"users\": 10}"); diff --git a/airbyte-server/src/test/java/io/airbyte/server/handlers/WebBackendConnectionsHandlerTest.java b/airbyte-server/src/test/java/io/airbyte/server/handlers/WebBackendConnectionsHandlerTest.java index 34d741b27fc6..e41293a46425 100644 --- a/airbyte-server/src/test/java/io/airbyte/server/handlers/WebBackendConnectionsHandlerTest.java +++ b/airbyte-server/src/test/java/io/airbyte/server/handlers/WebBackendConnectionsHandlerTest.java @@ -117,7 +117,7 @@ class WebBackendConnectionsHandlerTest { private ConfigRepository configRepository; @BeforeEach - public void setup() throws IOException, JsonValidationException, ConfigNotFoundException { + void setup() throws IOException, JsonValidationException, ConfigNotFoundException { connectionsHandler = mock(ConnectionsHandler.class); stateHandler = mock(StateHandler.class); operationsHandler = mock(OperationsHandler.class); @@ -253,7 +253,7 @@ public void setup() throws IOException, JsonValidationException, ConfigNotFoundE } @Test - public void testGetWorkspaceState() throws IOException { + void testGetWorkspaceState() throws IOException { final UUID uuid = UUID.randomUUID(); final WebBackendWorkspaceState request = new WebBackendWorkspaceState().workspaceId(uuid); when(configRepository.countSourcesForWorkspace(uuid)).thenReturn(5); @@ -266,7 +266,7 @@ public void testGetWorkspaceState() throws IOException { } @Test - public void testGetWorkspaceStateEmpty() throws IOException { + void testGetWorkspaceStateEmpty() throws IOException { final UUID uuid = UUID.randomUUID(); final WebBackendWorkspaceState request = new WebBackendWorkspaceState().workspaceId(uuid); when(configRepository.countSourcesForWorkspace(uuid)).thenReturn(0); @@ -279,7 +279,7 @@ public void testGetWorkspaceStateEmpty() throws IOException { } @Test - public void testWebBackendListConnectionsForWorkspace() throws ConfigNotFoundException, IOException, JsonValidationException { + void testWebBackendListConnectionsForWorkspace() throws ConfigNotFoundException, IOException, JsonValidationException { final WorkspaceIdRequestBody workspaceIdRequestBody = new WorkspaceIdRequestBody(); workspaceIdRequestBody.setWorkspaceId(sourceRead.getWorkspaceId()); @@ -296,7 +296,7 @@ public void testWebBackendListConnectionsForWorkspace() throws ConfigNotFoundExc } @Test - public void testWebBackendListAllConnectionsForWorkspace() throws ConfigNotFoundException, IOException, JsonValidationException { + void testWebBackendListAllConnectionsForWorkspace() throws ConfigNotFoundException, IOException, JsonValidationException { final WorkspaceIdRequestBody workspaceIdRequestBody = new WorkspaceIdRequestBody(); workspaceIdRequestBody.setWorkspaceId(sourceRead.getWorkspaceId()); @@ -313,7 +313,7 @@ public void testWebBackendListAllConnectionsForWorkspace() throws ConfigNotFound } @Test - public void testWebBackendSearchConnections() throws ConfigNotFoundException, IOException, JsonValidationException { + void testWebBackendSearchConnections() throws ConfigNotFoundException, IOException, JsonValidationException { final ConnectionReadList connectionReadList = new ConnectionReadList(); connectionReadList.setConnections(Collections.singletonList(connectionRead)); final ConnectionIdRequestBody connectionIdRequestBody = new ConnectionIdRequestBody(); @@ -334,7 +334,7 @@ public void testWebBackendSearchConnections() throws ConfigNotFoundException, IO } @Test - public void testWebBackendGetConnection() throws ConfigNotFoundException, IOException, JsonValidationException { + void testWebBackendGetConnection() throws ConfigNotFoundException, IOException, JsonValidationException { final ConnectionIdRequestBody connectionIdRequestBody = new ConnectionIdRequestBody(); connectionIdRequestBody.setConnectionId(connectionRead.getConnectionId()); @@ -349,7 +349,7 @@ public void testWebBackendGetConnection() throws ConfigNotFoundException, IOExce assertEquals(expected, WebBackendConnectionRead); } - public WebBackendConnectionRead testWebBackendGetConnection(final boolean withCatalogRefresh) + WebBackendConnectionRead testWebBackendGetConnection(final boolean withCatalogRefresh) throws JsonValidationException, ConfigNotFoundException, IOException { final ConnectionIdRequestBody connectionIdRequestBody = new ConnectionIdRequestBody(); connectionIdRequestBody.setConnectionId(connectionRead.getConnectionId()); @@ -367,7 +367,7 @@ public WebBackendConnectionRead testWebBackendGetConnection(final boolean withCa } @Test - public void testWebBackendGetConnectionWithDiscovery() throws ConfigNotFoundException, IOException, JsonValidationException { + void testWebBackendGetConnectionWithDiscovery() throws ConfigNotFoundException, IOException, JsonValidationException { when(connectionsHandler.getDiff(any(), any())).thenReturn(expectedWithNewSchema.getCatalogDiff()); final WebBackendConnectionRead result = testWebBackendGetConnection(true); verify(schedulerHandler).discoverSchemaForSourceFromSourceId(any()); @@ -375,7 +375,7 @@ public void testWebBackendGetConnectionWithDiscovery() throws ConfigNotFoundExce } @Test - public void testWebBackendGetConnectionNoRefreshCatalog() + void testWebBackendGetConnectionNoRefreshCatalog() throws JsonValidationException, ConfigNotFoundException, IOException { final WebBackendConnectionRead result = testWebBackendGetConnection(false); verify(schedulerHandler, never()).discoverSchemaForSourceFromSourceId(any()); @@ -383,7 +383,7 @@ public void testWebBackendGetConnectionNoRefreshCatalog() } @Test - public void testToConnectionCreate() throws IOException { + void testToConnectionCreate() throws IOException { final SourceConnection source = SourceHelpers.generateSource(UUID.randomUUID()); final StandardSync standardSync = ConnectionHelpers.generateSyncWithSourceId(source.getSourceId()); @@ -431,7 +431,7 @@ public void testToConnectionCreate() throws IOException { // TODO: remove withRefreshedCatalog param from this test when param is removed from code @Test - public void testToConnectionUpdate() throws IOException { + void testToConnectionUpdate() throws IOException { final SourceConnection source = SourceHelpers.generateSource(UUID.randomUUID()); final StandardSync standardSync = ConnectionHelpers.generateSyncWithSourceId(source.getSourceId()); @@ -471,7 +471,7 @@ public void testToConnectionUpdate() throws IOException { } @Test - public void testForConnectionCreateCompleteness() { + void testForConnectionCreateCompleteness() { final Set handledMethods = Set.of("name", "namespaceDefinition", "namespaceFormat", "prefix", "sourceId", "destinationId", "operationIds", "syncCatalog", "schedule", "status", "resourceRequirements", "sourceCatalogId"); @@ -492,7 +492,7 @@ public void testForConnectionCreateCompleteness() { } @Test - public void testForConnectionUpdateCompleteness() { + void testForConnectionUpdateCompleteness() { final Set handledMethods = Set.of("schedule", "connectionId", "syncCatalog", "namespaceDefinition", "namespaceFormat", "prefix", "status", "operationIds", "resourceRequirements", "name", "sourceCatalogId"); @@ -875,7 +875,7 @@ void testUpdateConnectionNoStreamsToReset() throws JsonValidationException, Conf } @Test - public void testUpdateConnectionWithSkipReset() throws JsonValidationException, ConfigNotFoundException, IOException { + void testUpdateConnectionWithSkipReset() throws JsonValidationException, ConfigNotFoundException, IOException { final WebBackendConnectionUpdate updateBody = new WebBackendConnectionUpdate() .namespaceDefinition(expected.getNamespaceDefinition()) .namespaceFormat(expected.getNamespaceFormat()) @@ -918,7 +918,7 @@ public void testUpdateConnectionWithSkipReset() throws JsonValidationException, } @Test - public void testUpdateSchemaWithDiscoveryFromEmpty() { + void testUpdateSchemaWithDiscoveryFromEmpty() { final AirbyteCatalog original = new AirbyteCatalog().streams(List.of()); final AirbyteCatalog discovered = ConnectionHelpers.generateBasicApiCatalog(); discovered.getStreams().get(0).getStream() @@ -951,7 +951,7 @@ public void testUpdateSchemaWithDiscoveryFromEmpty() { } @Test - public void testUpdateSchemaWithDiscoveryResetStream() { + void testUpdateSchemaWithDiscoveryResetStream() { final AirbyteCatalog original = ConnectionHelpers.generateBasicApiCatalog(); original.getStreams().get(0).getStream() .name("random-stream") @@ -1001,7 +1001,7 @@ public void testUpdateSchemaWithDiscoveryResetStream() { } @Test - public void testUpdateSchemaWithDiscoveryMergeNewStream() { + void testUpdateSchemaWithDiscoveryMergeNewStream() { final AirbyteCatalog original = ConnectionHelpers.generateBasicApiCatalog(); original.getStreams().get(0).getStream() .name("stream1") @@ -1078,7 +1078,7 @@ public void testUpdateSchemaWithDiscoveryMergeNewStream() { } @Test - public void testUpdateSchemaWithNamespacedStreams() { + void testUpdateSchemaWithNamespacedStreams() { final AirbyteCatalog original = ConnectionHelpers.generateBasicApiCatalog(); final AirbyteStreamAndConfiguration stream1Config = original.getStreams().get(0); final AirbyteStream stream1 = stream1Config.getStream(); @@ -1126,7 +1126,7 @@ public void testUpdateSchemaWithNamespacedStreams() { } @Test - public void testGetStreamsToReset() { + void testGetStreamsToReset() { final StreamTransform streamTransformAdd = new StreamTransform().transformType(TransformTypeEnum.ADD_STREAM).streamDescriptor(new StreamDescriptor().name("added_stream")); final StreamTransform streamTransformRemove = diff --git a/airbyte-server/src/test/java/io/airbyte/server/handlers/WorkspacesHandlerTest.java b/airbyte-server/src/test/java/io/airbyte/server/handlers/WorkspacesHandlerTest.java index 018f947ba7f9..9685c5a2b1f3 100644 --- a/airbyte-server/src/test/java/io/airbyte/server/handlers/WorkspacesHandlerTest.java +++ b/airbyte-server/src/test/java/io/airbyte/server/handlers/WorkspacesHandlerTest.java @@ -392,7 +392,7 @@ void testUpdateWorkspaceNoNameUpdate() throws JsonValidationException, ConfigNot } @Test - public void testSetFeedbackDone() throws JsonValidationException, ConfigNotFoundException, IOException { + void testSetFeedbackDone() throws JsonValidationException, ConfigNotFoundException, IOException { final WorkspaceGiveFeedback workspaceGiveFeedback = new WorkspaceGiveFeedback() .workspaceId(UUID.randomUUID()); diff --git a/airbyte-test-utils/src/test/java/io/airbyte/test/example/IntegrationTestExample.java b/airbyte-test-utils/src/test/java/io/airbyte/test/example/IntegrationTestExample.java index c6d6f3062c6b..edf45c5edc9e 100644 --- a/airbyte-test-utils/src/test/java/io/airbyte/test/example/IntegrationTestExample.java +++ b/airbyte-test-utils/src/test/java/io/airbyte/test/example/IntegrationTestExample.java @@ -13,10 +13,11 @@ */ @IntegrationTest @Slf4j -public class IntegrationTestExample { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class IntegrationTestExample { @Test - public void longTest() { + void longTest() { log.error("Start test - integration"); log.error("end test - integration"); } diff --git a/airbyte-test-utils/src/test/java/io/airbyte/test/example/SlowIntegrationTestExample.java b/airbyte-test-utils/src/test/java/io/airbyte/test/example/SlowIntegrationTestExample.java index 5bbc0ee9452e..d82dd5347751 100644 --- a/airbyte-test-utils/src/test/java/io/airbyte/test/example/SlowIntegrationTestExample.java +++ b/airbyte-test-utils/src/test/java/io/airbyte/test/example/SlowIntegrationTestExample.java @@ -13,10 +13,11 @@ */ @IntegrationTest @Slf4j -public class SlowIntegrationTestExample { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class SlowIntegrationTestExample { @Test - public void longTest() { + void longTest() { log.error("Start test - slow integration"); log.error("end test - slow integration"); } diff --git a/airbyte-test-utils/src/test/java/io/airbyte/test/utils/DatabaseConnectionHelperTest.java b/airbyte-test-utils/src/test/java/io/airbyte/test/utils/DatabaseConnectionHelperTest.java index 1c46a6353e9e..e3f74b1ac29d 100644 --- a/airbyte-test-utils/src/test/java/io/airbyte/test/utils/DatabaseConnectionHelperTest.java +++ b/airbyte-test-utils/src/test/java/io/airbyte/test/utils/DatabaseConnectionHelperTest.java @@ -16,14 +16,14 @@ import org.junit.jupiter.api.Test; import org.testcontainers.containers.PostgreSQLContainer; -public class DatabaseConnectionHelperTest { +class DatabaseConnectionHelperTest { private static final String DATABASE_NAME = "airbyte_test_database"; protected static PostgreSQLContainer container; @BeforeAll - public static void dbSetup() { + static void dbSetup() { container = new PostgreSQLContainer<>("postgres:13-alpine") .withDatabaseName(DATABASE_NAME) .withUsername("docker") @@ -32,7 +32,7 @@ public static void dbSetup() { } @AfterAll - public static void dbDown() { + static void dbDown() { container.close(); } diff --git a/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/AdvancedAcceptanceTests.java b/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/AdvancedAcceptanceTests.java index 85d91c6aaf77..e2c3ba7b58f7 100644 --- a/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/AdvancedAcceptanceTests.java +++ b/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/AdvancedAcceptanceTests.java @@ -80,7 +80,7 @@ */ @SuppressWarnings({"rawtypes", "ConstantConditions"}) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class AdvancedAcceptanceTests { +class AdvancedAcceptanceTests { private static final Logger LOGGER = LoggerFactory.getLogger(AdvancedAcceptanceTests.class); @@ -90,7 +90,7 @@ public class AdvancedAcceptanceTests { @SuppressWarnings("UnstableApiUsage") @BeforeAll - public static void init() throws URISyntaxException, IOException, InterruptedException, ApiException { + static void init() throws URISyntaxException, IOException, InterruptedException, ApiException { apiClient = new AirbyteApiClient( new ApiClient().setScheme("http") .setHost("localhost") @@ -114,23 +114,23 @@ public static void init() throws URISyntaxException, IOException, InterruptedExc } @AfterAll - public static void end() { + static void end() { testHarness.stopDbAndContainers(); } @BeforeEach - public void setup() throws URISyntaxException, IOException, SQLException { + void setup() throws URISyntaxException, IOException, SQLException { testHarness.setup(); } @AfterEach - public void tearDown() { + void tearDown() { testHarness.cleanup(); } @RetryingTest(3) @Order(1) - public void testManualSync() throws Exception { + void testManualSync() throws Exception { final String connectionName = "test-connection"; final UUID sourceId = testHarness.createPostgresSource().getSourceId(); final UUID destinationId = testHarness.createDestination().getDestinationId(); @@ -148,7 +148,7 @@ public void testManualSync() throws Exception { @RetryingTest(3) @Order(2) - public void testCheckpointing() throws Exception { + void testCheckpointing() throws Exception { final SourceDefinitionRead sourceDefinition = testHarness.createE2eSourceDefinition(); final DestinationDefinitionRead destinationDefinition = testHarness.createE2eDestinationDefinition(); @@ -213,7 +213,7 @@ public void testCheckpointing() throws Exception { @RetryingTest(3) @Order(3) - public void testRedactionOfSensitiveRequestBodies() throws Exception { + void testRedactionOfSensitiveRequestBodies() throws Exception { // check that the source password is not present in the logs final List serverLogLines = java.nio.file.Files.readAllLines( apiClient.getLogsApi().getLogs(new LogsRequestBody().logType(LogType.SERVER)).toPath(), @@ -237,7 +237,7 @@ public void testRedactionOfSensitiveRequestBodies() throws Exception { // verify that when the worker uses backpressure from pipes that no records are lost. @RetryingTest(3) @Order(4) - public void testBackpressure() throws Exception { + void testBackpressure() throws Exception { final SourceDefinitionRead sourceDefinition = testHarness.createE2eSourceDefinition(); final DestinationDefinitionRead destinationDefinition = testHarness.createE2eDestinationDefinition(); diff --git a/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/BasicAcceptanceTests.java b/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/BasicAcceptanceTests.java index 6883bec7f507..6ae45c1525ac 100644 --- a/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/BasicAcceptanceTests.java +++ b/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/BasicAcceptanceTests.java @@ -118,7 +118,8 @@ */ @DisabledIfEnvironmentVariable(named = "KUBE", matches = "true") -public class BasicAcceptanceTests { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class BasicAcceptanceTests { private static final Logger LOGGER = LoggerFactory.getLogger(BasicAcceptanceTests.class); @@ -133,7 +134,7 @@ public class BasicAcceptanceTests { private static PostgreSQLContainer sourcePsql; @BeforeAll - public static void init() throws URISyntaxException, IOException, InterruptedException, ApiException { + static void init() throws URISyntaxException, IOException, InterruptedException, ApiException { apiClient = new AirbyteApiClient( new ApiClient().setScheme("http") .setHost("localhost") @@ -163,23 +164,23 @@ public static void init() throws URISyntaxException, IOException, InterruptedExc } @AfterAll - public static void end() { + static void end() { testHarness.stopDbAndContainers(); } @BeforeEach - public void setup() throws SQLException, URISyntaxException, IOException { + void setup() throws SQLException, URISyntaxException, IOException { testHarness.setup(); } @AfterEach - public void tearDown() { + void tearDown() { testHarness.cleanup(); } @Test @Order(-2) - public void testGetDestinationSpec() throws ApiException { + void testGetDestinationSpec() throws ApiException { final UUID destinationDefinitionId = testHarness.getDestinationDefId(); final DestinationDefinitionSpecificationRead spec = apiClient.getDestinationDefinitionSpecificationApi() .getDestinationDefinitionSpecification( @@ -190,7 +191,7 @@ public void testGetDestinationSpec() throws ApiException { @Test @Order(-1) - public void testFailedGet404() { + void testFailedGet404() { final var e = assertThrows(ApiException.class, () -> apiClient.getDestinationDefinitionSpecificationApi() .getDestinationDefinitionSpecification( new DestinationDefinitionIdWithWorkspaceId().destinationDefinitionId(UUID.randomUUID()).workspaceId(UUID.randomUUID()))); @@ -199,7 +200,7 @@ public void testFailedGet404() { @Test @Order(0) - public void testGetSourceSpec() throws ApiException { + void testGetSourceSpec() throws ApiException { final UUID sourceDefId = testHarness.getPostgresSourceDefinitionId(); final SourceDefinitionSpecificationRead spec = apiClient.getSourceDefinitionSpecificationApi() .getSourceDefinitionSpecification(new SourceDefinitionIdWithWorkspaceId().sourceDefinitionId(sourceDefId).workspaceId(UUID.randomUUID())); @@ -209,7 +210,7 @@ public void testGetSourceSpec() throws ApiException { @Test @Order(1) - public void testCreateDestination() throws ApiException { + void testCreateDestination() throws ApiException { final UUID destinationDefId = testHarness.getDestinationDefId(); final JsonNode destinationConfig = testHarness.getDestinationDbConfig(); final String name = "AccTestDestinationDb-" + UUID.randomUUID(); @@ -228,7 +229,7 @@ public void testCreateDestination() throws ApiException { @Test @Order(2) - public void testDestinationCheckConnection() throws ApiException { + void testDestinationCheckConnection() throws ApiException { final UUID destinationId = testHarness.createDestination().getDestinationId(); final CheckConnectionRead.StatusEnum checkOperationStatus = apiClient.getDestinationApi() @@ -240,7 +241,7 @@ public void testDestinationCheckConnection() throws ApiException { @Test @Order(3) - public void testCreateSource() throws ApiException { + void testCreateSource() throws ApiException { final String dbName = "acc-test-db"; final UUID postgresSourceDefinitionId = testHarness.getPostgresSourceDefinitionId(); final JsonNode sourceDbConfig = testHarness.getSourceDbConfig(); @@ -262,7 +263,7 @@ public void testCreateSource() throws ApiException { @Test @Order(4) - public void testSourceCheckConnection() throws ApiException { + void testSourceCheckConnection() throws ApiException { final UUID sourceId = testHarness.createPostgresSource().getSourceId(); final CheckConnectionRead checkConnectionRead = apiClient.getSourceApi().checkConnectionToSource(new SourceIdRequestBody().sourceId(sourceId)); @@ -275,7 +276,7 @@ public void testSourceCheckConnection() throws ApiException { @Test @Order(5) - public void testDiscoverSourceSchema() throws ApiException { + void testDiscoverSourceSchema() throws ApiException { final UUID sourceId = testHarness.createPostgresSource().getSourceId(); final AirbyteCatalog actual = testHarness.discoverSourceSchema(sourceId); @@ -312,7 +313,7 @@ public void testDiscoverSourceSchema() throws ApiException { @Test @Order(6) - public void testCreateConnection() throws ApiException { + void testCreateConnection() throws ApiException { final UUID sourceId = testHarness.createPostgresSource().getSourceId(); final AirbyteCatalog catalog = testHarness.discoverSourceSchema(sourceId); final UUID destinationId = testHarness.createDestination().getDestinationId(); @@ -336,7 +337,7 @@ public void testCreateConnection() throws ApiException { @Test @Order(7) - public void testCancelSync() throws Exception { + void testCancelSync() throws Exception { final SourceDefinitionRead sourceDefinition = testHarness.createE2eSourceDefinition(); final SourceRead source = testHarness.createSource( @@ -371,7 +372,7 @@ public void testCancelSync() throws Exception { @Test @Order(8) - public void testScheduledSync() throws Exception { + void testScheduledSync() throws Exception { final String connectionName = "test-connection"; final UUID sourceId = testHarness.createPostgresSource().getSourceId(); final UUID destinationId = testHarness.createDestination().getDestinationId(); @@ -404,7 +405,7 @@ public void testScheduledSync() throws Exception { @Test @Order(9) - public void testMultipleSchemasAndTablesSync() throws Exception { + void testMultipleSchemasAndTablesSync() throws Exception { // create tables in another schema PostgreSQLContainerHelper.runSqlScript(MountableFile.forClasspathResource("postgres_second_schema_multiple_tables.sql"), sourcePsql); @@ -426,7 +427,7 @@ public void testMultipleSchemasAndTablesSync() throws Exception { @Test @Order(10) - public void testMultipleSchemasSameTablesSync() throws Exception { + void testMultipleSchemasSameTablesSync() throws Exception { // create tables in another schema PostgreSQLContainerHelper.runSqlScript(MountableFile.forClasspathResource("postgres_separate_schema_same_table.sql"), sourcePsql); @@ -449,7 +450,7 @@ public void testMultipleSchemasSameTablesSync() throws Exception { @Test @Order(11) - public void testIncrementalDedupeSync() throws Exception { + void testIncrementalDedupeSync() throws Exception { final String connectionName = "test-connection"; final UUID sourceId = testHarness.createPostgresSource().getSourceId(); final UUID destinationId = testHarness.createDestination().getDestinationId(); @@ -493,7 +494,7 @@ public void testIncrementalDedupeSync() throws Exception { @Test @Order(12) - public void testIncrementalSync() throws Exception { + void testIncrementalSync() throws Exception { LOGGER.info("Starting testIncrementalSync()"); final String connectionName = "test-connection"; final UUID sourceId = testHarness.createPostgresSource().getSourceId(); @@ -570,7 +571,7 @@ public void testIncrementalSync() throws Exception { @Test @Order(13) - public void testDeleteConnection() throws Exception { + void testDeleteConnection() throws Exception { final String connectionName = "test-connection"; final UUID sourceId = testHarness.createPostgresSource().getSourceId(); final UUID destinationId = testHarness.createDestination().getDestinationId(); @@ -628,7 +629,7 @@ public void testDeleteConnection() throws Exception { @Test @Order(14) - public void testUpdateConnectionWhenWorkflowUnreachable() throws Exception { + void testUpdateConnectionWhenWorkflowUnreachable() throws Exception { // This test only covers the specific behavior of updating a connection that does not have an // underlying temporal workflow. // Also, this test doesn't verify correctness of the schedule update applied, as adding the ability @@ -666,7 +667,7 @@ public void testUpdateConnectionWhenWorkflowUnreachable() throws Exception { @Test @Order(15) - public void testManualSyncRepairsWorkflowWhenWorkflowUnreachable() throws Exception { + void testManualSyncRepairsWorkflowWhenWorkflowUnreachable() throws Exception { // This test only covers the specific behavior of updating a connection that does not have an // underlying temporal workflow. final String connectionName = "test-connection"; @@ -716,7 +717,7 @@ public void testManualSyncRepairsWorkflowWhenWorkflowUnreachable() throws Except @Test @Order(16) - public void testResetConnectionRepairsWorkflowWhenWorkflowUnreachable() throws Exception { + void testResetConnectionRepairsWorkflowWhenWorkflowUnreachable() throws Exception { // This test only covers the specific behavior of updating a connection that does not have an // underlying temporal workflow. final String connectionName = "test-connection"; @@ -742,7 +743,7 @@ public void testResetConnectionRepairsWorkflowWhenWorkflowUnreachable() throws E @Test @Order(17) - public void testResetCancelsRunningSync() throws Exception { + void testResetCancelsRunningSync() throws Exception { final SourceDefinitionRead sourceDefinition = testHarness.createE2eSourceDefinition(); final SourceRead source = testHarness.createSource( @@ -782,7 +783,7 @@ public void testResetCancelsRunningSync() throws Exception { } @Test - public void testSyncAfterUpgradeToPerStreamState(final TestInfo testInfo) throws Exception { + void testSyncAfterUpgradeToPerStreamState(final TestInfo testInfo) throws Exception { LOGGER.info("Starting {}", testInfo.getDisplayName()); final String connectionName = "test-connection"; final SourceRead source = testHarness.createPostgresSource(); @@ -871,7 +872,7 @@ public void testSyncAfterUpgradeToPerStreamState(final TestInfo testInfo) throws } @Test - public void testSyncAfterUpgradeToPerStreamStateWithNoNewData(final TestInfo testInfo) throws Exception { + void testSyncAfterUpgradeToPerStreamStateWithNoNewData(final TestInfo testInfo) throws Exception { LOGGER.info("Starting {}", testInfo.getDisplayName()); final String connectionName = "test-connection"; final SourceRead source = testHarness.createPostgresSource(); @@ -929,7 +930,7 @@ public void testSyncAfterUpgradeToPerStreamStateWithNoNewData(final TestInfo tes } @Test - public void testResetAllWhenSchemaIsModified() throws Exception { + void testResetAllWhenSchemaIsModified() throws Exception { final String sourceTable1 = "test_table1"; final String sourceTable2 = "test_table2"; final String sourceTable3 = "test_table3"; @@ -1070,7 +1071,7 @@ private void prettyPrintTables(final DSLContext ctx, final String... tables) { } @Test - public void testIncrementalSyncMultipleStreams() throws Exception { + void testIncrementalSyncMultipleStreams() throws Exception { LOGGER.info("Starting testIncrementalSyncMultipleStreams()"); PostgreSQLContainerHelper.runSqlScript(MountableFile.forClasspathResource("postgres_second_schema_multiple_tables.sql"), sourcePsql); @@ -1163,7 +1164,7 @@ public void testIncrementalSyncMultipleStreams() throws Exception { } @Test - public void testMultipleSchemasAndTablesSyncAndReset() throws Exception { + void testMultipleSchemasAndTablesSyncAndReset() throws Exception { // create tables in another schema PostgreSQLContainerHelper.runSqlScript(MountableFile.forClasspathResource("postgres_second_schema_multiple_tables.sql"), sourcePsql); @@ -1187,7 +1188,7 @@ public void testMultipleSchemasAndTablesSyncAndReset() throws Exception { } @Test - public void testPartialResetResetAllWhenSchemaIsModified(final TestInfo testInfo) throws Exception { + void testPartialResetResetAllWhenSchemaIsModified(final TestInfo testInfo) throws Exception { LOGGER.info("Running: " + testInfo.getDisplayName()); // Add Table @@ -1340,7 +1341,7 @@ private JobRead waitUntilTheNextJobIsStarted(final UUID connectionId) throws Exc // See relevant issue: https://github.com/airbytehq/airbyte/issues/8397 @Test @Disabled - public void testFailureTimeout() throws Exception { + void testFailureTimeout() throws Exception { final SourceDefinitionRead sourceDefinition = testHarness.createE2eSourceDefinition(); final DestinationDefinitionRead destinationDefinition = testHarness.createE2eDestinationDefinition(); diff --git a/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/CdcAcceptanceTests.java b/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/CdcAcceptanceTests.java index 0fd69cc15766..45a47cecc97c 100644 --- a/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/CdcAcceptanceTests.java +++ b/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/CdcAcceptanceTests.java @@ -81,7 +81,8 @@ */ @DisabledIfEnvironmentVariable(named = "KUBE", matches = "true") -public class CdcAcceptanceTests { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class CdcAcceptanceTests { record DestinationCdcRecordMatcher(JsonNode sourceRecord, Instant minUpdatedAt, Optional minDeletedAt) {} @@ -115,7 +116,7 @@ record DestinationCdcRecordMatcher(JsonNode sourceRecord, Instant minUpdatedAt, private AirbyteAcceptanceTestHarness testHarness; @BeforeAll - public static void init() throws URISyntaxException, IOException, InterruptedException, ApiException { + static void init() throws URISyntaxException, IOException, InterruptedException, ApiException { apiClient = new AirbyteApiClient( new ApiClient().setScheme("http") .setHost("localhost") @@ -142,19 +143,19 @@ public static void init() throws URISyntaxException, IOException, InterruptedExc } @BeforeEach - public void setup() throws URISyntaxException, IOException, InterruptedException, ApiException, SQLException { + void setup() throws URISyntaxException, IOException, InterruptedException, ApiException, SQLException { testHarness = new AirbyteAcceptanceTestHarness(apiClient, workspaceId, POSTGRES_INIT_SQL_FILE); testHarness.setup(); } @AfterEach - public void end() { + void end() { testHarness.cleanup(); testHarness.stopDbAndContainers(); } @Test - public void testIncrementalCdcSync(final TestInfo testInfo) throws Exception { + void testIncrementalCdcSync(final TestInfo testInfo) throws Exception { LOGGER.info("Starting {}", testInfo.getDisplayName()); final UUID connectionId = createCdcConnection(); @@ -250,7 +251,7 @@ public void testIncrementalCdcSync(final TestInfo testInfo) throws Exception { // tests that incremental syncs still work properly even when using a destination connector that was // built on the old protocol that did not have any per-stream state fields @Test - public void testIncrementalCdcSyncWithLegacyDestinationConnector(final TestInfo testInfo) throws Exception { + void testIncrementalCdcSyncWithLegacyDestinationConnector(final TestInfo testInfo) throws Exception { LOGGER.info("Starting {}", testInfo.getDisplayName()); final UUID postgresDestDefId = testHarness.getPostgresDestinationDefinitionId(); // Fetch the current/most recent source definition version @@ -271,7 +272,7 @@ public void testIncrementalCdcSyncWithLegacyDestinationConnector(final TestInfo } @Test - public void testDeleteRecordCdcSync(final TestInfo testInfo) throws Exception { + void testDeleteRecordCdcSync(final TestInfo testInfo) throws Exception { LOGGER.info("Starting {}", testInfo.getDisplayName()); final UUID connectionId = createCdcConnection(); @@ -310,7 +311,7 @@ public void testDeleteRecordCdcSync(final TestInfo testInfo) throws Exception { } @Test - public void testPartialResetFromSchemaUpdate(final TestInfo testInfo) throws Exception { + void testPartialResetFromSchemaUpdate(final TestInfo testInfo) throws Exception { LOGGER.info("Starting {}", testInfo.getDisplayName()); final UUID connectionId = createCdcConnection(); @@ -353,7 +354,7 @@ public void testPartialResetFromSchemaUpdate(final TestInfo testInfo) throws Exc } @Test - public void testPartialResetFromStreamSelection(final TestInfo testInfo) throws Exception { + void testPartialResetFromStreamSelection(final TestInfo testInfo) throws Exception { LOGGER.info("Starting {}", testInfo.getDisplayName()); final UUID connectionId = createCdcConnection(); diff --git a/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/ContainerOrchestratorAcceptanceTests.java b/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/ContainerOrchestratorAcceptanceTests.java index 766d925fd07d..96d4e52ad0a1 100644 --- a/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/ContainerOrchestratorAcceptanceTests.java +++ b/airbyte-tests/src/acceptanceTests/java/io/airbyte/test/acceptance/ContainerOrchestratorAcceptanceTests.java @@ -53,7 +53,7 @@ @SuppressWarnings({"rawtypes", "ConstantConditions"}) @EnabledIfEnvironmentVariable(named = "KUBE", matches = "true") -public class ContainerOrchestratorAcceptanceTests { +class ContainerOrchestratorAcceptanceTests { private static final Logger LOGGER = LoggerFactory.getLogger(ContainerOrchestratorAcceptanceTests.class); @@ -64,7 +64,7 @@ public class ContainerOrchestratorAcceptanceTests { @SuppressWarnings("UnstableApiUsage") @BeforeAll - public static void init() throws URISyntaxException, IOException, InterruptedException, ApiException { + static void init() throws URISyntaxException, IOException, InterruptedException, ApiException { apiClient = new AirbyteApiClient( new ApiClient().setScheme("http") .setHost("localhost") @@ -89,22 +89,17 @@ public static void init() throws URISyntaxException, IOException, InterruptedExc } @AfterAll - public static void end() { + static void end() { testHarness.stopDbAndContainers(); } @BeforeEach - public void setup() throws URISyntaxException, IOException, SQLException { + void setup() throws URISyntaxException, IOException, SQLException { testHarness.setup(); } - @AfterEach - public void tearDown() { - testHarness.cleanup(); - } - @Test - public void testDowntimeDuringSync() throws Exception { + void testDowntimeDuringSync() throws Exception { final String connectionName = "test-connection"; final UUID sourceId = testHarness.createPostgresSource().getSourceId(); final UUID destinationId = testHarness.createDestination().getDestinationId(); @@ -118,7 +113,7 @@ public void testDowntimeDuringSync() throws Exception { testHarness.createConnection(connectionName, sourceId, destinationId, List.of(), catalog, null).getConnectionId(); LOGGER.info("Run manual sync..."); - JobInfoRead connectionSyncRead = apiClient.getConnectionApi().syncConnection(new ConnectionIdRequestBody().connectionId(connectionId)); + final JobInfoRead connectionSyncRead = apiClient.getConnectionApi().syncConnection(new ConnectionIdRequestBody().connectionId(connectionId)); LOGGER.info("Waiting for job to run..."); waitWhileJobHasStatus(apiClient.getJobsApi(), connectionSyncRead.getJob(), Set.of(JobStatus.PENDING)); @@ -140,8 +135,13 @@ public void testDowntimeDuringSync() throws Exception { assertEquals(1, numAttempts); } + @AfterEach + void tearDown() { + testHarness.cleanup(); + } + @Test - public void testCancelSyncWithInterruption() throws Exception { + void testCancelSyncWithInterruption() throws Exception { final String connectionName = "test-connection"; final UUID sourceId = testHarness.createPostgresSource().getSourceId(); final UUID destinationId = testHarness.createDestination().getDestinationId(); @@ -164,7 +164,7 @@ public void testCancelSyncWithInterruption() throws Exception { } @Test - public void testCancelSyncWhenCancelledWhenWorkerIsNotRunning() throws Exception { + void testCancelSyncWhenCancelledWhenWorkerIsNotRunning() throws Exception { final String connectionName = "test-connection"; final UUID sourceId = testHarness.createPostgresSource().getSourceId(); final UUID destinationId = testHarness.createDestination().getDestinationId(); diff --git a/airbyte-tests/src/automaticMigrationAcceptanceTest/java/io/airbyte/test/automaticMigrationAcceptance/MigrationAcceptanceTest.java b/airbyte-tests/src/automaticMigrationAcceptanceTest/java/io/airbyte/test/automaticMigrationAcceptance/MigrationAcceptanceTest.java index 8329fe5d0d0d..110233c4f0dc 100644 --- a/airbyte-tests/src/automaticMigrationAcceptanceTest/java/io/airbyte/test/automaticMigrationAcceptance/MigrationAcceptanceTest.java +++ b/airbyte-tests/src/automaticMigrationAcceptanceTest/java/io/airbyte/test/automaticMigrationAcceptance/MigrationAcceptanceTest.java @@ -64,7 +64,8 @@ * When running this test consecutively locally, it might be necessary to run `docker volume prune` * to remove hanging volumes. */ -public class MigrationAcceptanceTest { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class MigrationAcceptanceTest { private static final Logger LOGGER = LoggerFactory.getLogger(MigrationAcceptanceTest.class); @@ -78,7 +79,7 @@ public class MigrationAcceptanceTest { private static final String TEST_LOCAL_DOCKER_MOUNT = "/tmp/airbyte_local_migration_test"; @Test - public void testAutomaticMigration() throws Exception { + void testAutomaticMigration() throws Exception { // run version 17 (the oldest version of airbyte that supports auto migration) final File version17DockerComposeFile = MoreResources.readResourceAsFile("docker-compose-migration-test-0-17-0-alpha.yaml"); final Properties version17EnvVariables = MoreProperties diff --git a/airbyte-workers/src/main/java/io/airbyte/workers/general/DbtTransformationWorker.java b/airbyte-workers/src/main/java/io/airbyte/workers/general/DbtTransformationWorker.java index 97150e4fadfe..656c539e45a7 100644 --- a/airbyte-workers/src/main/java/io/airbyte/workers/general/DbtTransformationWorker.java +++ b/airbyte-workers/src/main/java/io/airbyte/workers/general/DbtTransformationWorker.java @@ -15,6 +15,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@SuppressWarnings("PMD.AvoidPrintStackTrace") public class DbtTransformationWorker implements Worker { private static final Logger LOGGER = LoggerFactory.getLogger(DbtTransformationWorker.class); diff --git a/airbyte-workers/src/main/java/io/airbyte/workers/general/DefaultNormalizationWorker.java b/airbyte-workers/src/main/java/io/airbyte/workers/general/DefaultNormalizationWorker.java index c5142eaf9c69..f962943281e9 100644 --- a/airbyte-workers/src/main/java/io/airbyte/workers/general/DefaultNormalizationWorker.java +++ b/airbyte-workers/src/main/java/io/airbyte/workers/general/DefaultNormalizationWorker.java @@ -18,6 +18,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@SuppressWarnings("PMD.AvoidPrintStackTrace") public class DefaultNormalizationWorker implements NormalizationWorker { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultNormalizationWorker.class); diff --git a/airbyte-workers/src/main/java/io/airbyte/workers/general/DefaultReplicationWorker.java b/airbyte-workers/src/main/java/io/airbyte/workers/general/DefaultReplicationWorker.java index 4a45bf15de11..1fb914a65747 100644 --- a/airbyte-workers/src/main/java/io/airbyte/workers/general/DefaultReplicationWorker.java +++ b/airbyte-workers/src/main/java/io/airbyte/workers/general/DefaultReplicationWorker.java @@ -62,6 +62,7 @@ * next replication can pick up where it left off instead of starting from the beginning) * */ +@SuppressWarnings("PMD.AvoidPrintStackTrace") public class DefaultReplicationWorker implements ReplicationWorker { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultReplicationWorker.class); @@ -366,9 +367,9 @@ private static Runnable getReplicationRunnable(final AirbyteSource source, }; } - private static void validateSchema(RecordSchemaValidator recordSchemaValidator, - Map, Integer>> validationErrors, - AirbyteMessage message) { + private static void validateSchema(final RecordSchemaValidator recordSchemaValidator, + final Map, Integer>> validationErrors, + final AirbyteMessage message) { if (message.getRecord() == null) { return; } diff --git a/airbyte-workers/src/main/java/io/airbyte/workers/internal/state_aggregator/DefaultStateAggregator.java b/airbyte-workers/src/main/java/io/airbyte/workers/internal/state_aggregator/DefaultStateAggregator.java index 18fcf6efcdba..5eabc899bc4e 100644 --- a/airbyte-workers/src/main/java/io/airbyte/workers/internal/state_aggregator/DefaultStateAggregator.java +++ b/airbyte-workers/src/main/java/io/airbyte/workers/internal/state_aggregator/DefaultStateAggregator.java @@ -16,7 +16,7 @@ public class DefaultStateAggregator implements StateAggregator { private final StateAggregator singleStateAggregator = new SingleStateAggregator(); private final boolean useStreamCapableState; - public DefaultStateAggregator(boolean useStreamCapableState) { + public DefaultStateAggregator(final boolean useStreamCapableState) { this.useStreamCapableState = useStreamCapableState; } @@ -50,15 +50,18 @@ private StateAggregator getStateAggregator() { * We can not have 2 different state types given to the same instance of this class. This method set * the type if it is not. If the state type doesn't exist in the message, it is set to LEGACY */ - private void checkTypeOrSetType(AirbyteStateType inputStateType) { + private void checkTypeOrSetType(final AirbyteStateType inputStateType) { + final AirbyteStateType validatedStateType; if (inputStateType == null) { - inputStateType = AirbyteStateType.LEGACY; + validatedStateType = AirbyteStateType.LEGACY; + } else { + validatedStateType = inputStateType; } if (this.stateType == null) { - this.stateType = inputStateType; + this.stateType = validatedStateType; } - Preconditions.checkArgument(this.stateType == inputStateType, - "Input state type " + inputStateType + " does not match the aggregator's current state type " + this.stateType); + Preconditions.checkArgument(this.stateType == validatedStateType, + "Input state type " + validatedStateType + " does not match the aggregator's current state type " + this.stateType); } } diff --git a/airbyte-workers/src/main/java/io/airbyte/workers/process/KubePodProcess.java b/airbyte-workers/src/main/java/io/airbyte/workers/process/KubePodProcess.java index 865f86e38ec2..66e299dd3d2d 100644 --- a/airbyte-workers/src/main/java/io/airbyte/workers/process/KubePodProcess.java +++ b/airbyte-workers/src/main/java/io/airbyte/workers/process/KubePodProcess.java @@ -94,6 +94,9 @@ * See the constructor for more information. */ +// Suppressing AvoidPrintStackTrace PMD warnings because +// it is required for the connectors +@SuppressWarnings("PMD.AvoidPrintStackTrace") // TODO(Davin): Better test for this. See https://github.com/airbytehq/airbyte/issues/3700. public class KubePodProcess extends Process implements KubePod { diff --git a/airbyte-workers/src/main/java/io/airbyte/workers/process/WorkerHeartbeatServer.java b/airbyte-workers/src/main/java/io/airbyte/workers/process/WorkerHeartbeatServer.java index d7f012b2b3ca..ba1abaf8b380 100644 --- a/airbyte-workers/src/main/java/io/airbyte/workers/process/WorkerHeartbeatServer.java +++ b/airbyte-workers/src/main/java/io/airbyte/workers/process/WorkerHeartbeatServer.java @@ -55,14 +55,17 @@ protected Server getServer() { public static class WorkerHeartbeatServlet extends HttpServlet { + @Override public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException { this.serveDefaultRequest(response); } + @Override public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException { this.serveDefaultRequest(response); } + @Override public void doOptions(final HttpServletRequest request, final HttpServletResponse response) throws IOException { this.addCorsHeaders(response); } diff --git a/airbyte-workers/src/main/java/io/airbyte/workers/temporal/check/connection/CheckConnectionActivityImpl.java b/airbyte-workers/src/main/java/io/airbyte/workers/temporal/check/connection/CheckConnectionActivityImpl.java index f37011753113..b76479cc0003 100644 --- a/airbyte-workers/src/main/java/io/airbyte/workers/temporal/check/connection/CheckConnectionActivityImpl.java +++ b/airbyte-workers/src/main/java/io/airbyte/workers/temporal/check/connection/CheckConnectionActivityImpl.java @@ -56,6 +56,7 @@ public CheckConnectionActivityImpl(final WorkerConfigs workerConfigs, this.airbyteVersion = airbyteVersion; } + @Override public ConnectorJobOutput runWithJobOutput(final CheckConnectionInput args) { final JsonNode fullConfig = secretsHydrator.hydrate(args.getConnectionConfiguration().getConnectionConfiguration()); @@ -78,6 +79,7 @@ public ConnectorJobOutput runWithJobOutput(final CheckConnectionInput args) { return temporalAttemptExecution.get(); } + @Override public StandardCheckConnectionOutput run(final CheckConnectionInput args) { final ConnectorJobOutput output = runWithJobOutput(args); if (output.getFailureReason() != null) { diff --git a/airbyte-workers/src/main/java/io/airbyte/workers/temporal/discover/catalog/DiscoverCatalogActivityImpl.java b/airbyte-workers/src/main/java/io/airbyte/workers/temporal/discover/catalog/DiscoverCatalogActivityImpl.java index 69903615e9a0..71fc7981bee1 100644 --- a/airbyte-workers/src/main/java/io/airbyte/workers/temporal/discover/catalog/DiscoverCatalogActivityImpl.java +++ b/airbyte-workers/src/main/java/io/airbyte/workers/temporal/discover/catalog/DiscoverCatalogActivityImpl.java @@ -57,10 +57,10 @@ public DiscoverCatalogActivityImpl(final WorkerConfigs workerConfigs, this.airbyteVersion = airbyteVersion; } + @Override public ConnectorJobOutput run(final JobRunConfig jobRunConfig, final IntegrationLauncherConfig launcherConfig, final StandardDiscoverCatalogInput config) { - final JsonNode fullConfig = secretsHydrator.hydrate(config.getConnectionConfiguration()); final StandardDiscoverCatalogInput input = new StandardDiscoverCatalogInput() diff --git a/airbyte-workers/src/main/java/io/airbyte/workers/temporal/spec/SpecActivityImpl.java b/airbyte-workers/src/main/java/io/airbyte/workers/temporal/spec/SpecActivityImpl.java index 41d19deb7e50..a919e5984351 100644 --- a/airbyte-workers/src/main/java/io/airbyte/workers/temporal/spec/SpecActivityImpl.java +++ b/airbyte-workers/src/main/java/io/airbyte/workers/temporal/spec/SpecActivityImpl.java @@ -51,6 +51,7 @@ public SpecActivityImpl(final WorkerConfigs workerConfigs, this.airbyteVersion = airbyteVersion; } + @Override public ConnectorJobOutput run(final JobRunConfig jobRunConfig, final IntegrationLauncherConfig launcherConfig) { final Supplier inputSupplier = () -> new JobGetSpecConfig().withDockerImage(launcherConfig.getDockerImage()); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/RecordSchemaValidatorTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/RecordSchemaValidatorTest.java index 774a4545003e..e3365e466f41 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/RecordSchemaValidatorTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/RecordSchemaValidatorTest.java @@ -15,7 +15,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class RecordSchemaValidatorTest { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class RecordSchemaValidatorTest { private StandardSyncInput syncInput; private static final String STREAM_NAME = "user_preferences"; diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/WorkerConfigsTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/WorkerConfigsTest.java index 154f67eed04e..f43b80ec7962 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/WorkerConfigsTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/WorkerConfigsTest.java @@ -17,7 +17,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -public class WorkerConfigsTest { +class WorkerConfigsTest { private static final Map DEFAULT_NODE_SELECTORS = ImmutableMap.of("job", "default"); private static final Map SPEC_NODE_SELECTORS = ImmutableMap.of("job", "spec"); @@ -46,7 +46,7 @@ public class WorkerConfigsTest { private Configs configs; @BeforeEach - public void setup() { + void setup() { configs = mock(EnvConfigs.class); when(configs.getJobKubeNodeSelectors()).thenReturn(DEFAULT_NODE_SELECTORS); when(configs.getJobMainContainerCpuRequest()).thenReturn(DEFAULT_CPU_REQUEST); @@ -57,7 +57,7 @@ public void setup() { @Test @DisplayName("default workerConfigs use default node selectors") - public void testDefaultNodeSelectors() { + void testDefaultNodeSelectors() { final WorkerConfigs defaultWorkerConfigs = new WorkerConfigs(configs); Assertions.assertEquals(DEFAULT_NODE_SELECTORS, defaultWorkerConfigs.getworkerKubeNodeSelectors()); @@ -65,7 +65,7 @@ public void testDefaultNodeSelectors() { @Test @DisplayName("spec, check, and discover workerConfigs use job-specific node selectors if set") - public void testCustomNodeSelectors() { + void testCustomNodeSelectors() { when(configs.getCheckJobKubeNodeSelectors()).thenReturn(CHECK_NODE_SELECTORS); when(configs.getSpecJobKubeNodeSelectors()).thenReturn(SPEC_NODE_SELECTORS); when(configs.getDiscoverJobKubeNodeSelectors()).thenReturn(DISCOVER_NODE_SELECTORS); @@ -81,7 +81,7 @@ public void testCustomNodeSelectors() { @Test @DisplayName("spec, check, and discover workerConfigs use default node selectors when custom selectors are not set") - public void testNodeSelectorsFallbackToDefault() { + void testNodeSelectorsFallbackToDefault() { when(configs.getCheckJobKubeNodeSelectors()).thenReturn(null); when(configs.getSpecJobKubeNodeSelectors()).thenReturn(null); when(configs.getDiscoverJobKubeNodeSelectors()).thenReturn(null); @@ -97,7 +97,7 @@ public void testNodeSelectorsFallbackToDefault() { @Test @DisplayName("default workerConfigs use default resourceRequirements") - public void testDefaultResourceRequirements() { + void testDefaultResourceRequirements() { final WorkerConfigs defaultWorkerConfigs = new WorkerConfigs(configs); Assertions.assertEquals(DEFAULT_RESOURCE_REQUIREMENTS, defaultWorkerConfigs.getResourceRequirements()); @@ -105,7 +105,7 @@ public void testDefaultResourceRequirements() { @Test @DisplayName("replication workerConfigs use replication-specific resourceRequirements") - public void testCustomResourceRequirements() { + void testCustomResourceRequirements() { when(configs.getReplicationOrchestratorCpuRequest()).thenReturn(REPLICATION_CPU_REQUEST); when(configs.getReplicationOrchestratorCpuLimit()).thenReturn(REPLICATION_CPU_LIMIT); when(configs.getReplicationOrchestratorMemoryRequest()).thenReturn(REPLICATION_MEMORY_REQUEST); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/WorkerUtilsTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/WorkerUtilsTest.java index dd1b07d3b91b..39da15dd4cf1 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/WorkerUtilsTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/WorkerUtilsTest.java @@ -31,6 +31,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") class WorkerUtilsTest { private static final Logger LOGGER = LoggerFactory.getLogger(GentleCloseWithHeartbeat.class); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/general/DefaultCheckConnectionWorkerTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/general/DefaultCheckConnectionWorkerTest.java index c326235e5eb3..38630c595283 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/general/DefaultCheckConnectionWorkerTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/general/DefaultCheckConnectionWorkerTest.java @@ -42,7 +42,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class DefaultCheckConnectionWorkerTest { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class DefaultCheckConnectionWorkerTest { private static final Path TEST_ROOT = Path.of("/tmp/airbyte_tests"); private static final JsonNode CREDS = Jsons.jsonNode(ImmutableMap.builder().put("apiKey", "123").build()); @@ -57,7 +58,7 @@ public class DefaultCheckConnectionWorkerTest { private AirbyteStreamFactory traceMessageStreamFactory; @BeforeEach - public void setup() throws IOException, WorkerException { + void setup() throws IOException, WorkerException { workerConfigs = WorkerConfigs.buildCheckWorkerConfigs(new EnvConfigs()); input = new StandardCheckConnectionInput().withConnectionConfiguration(CREDS); @@ -85,12 +86,12 @@ public void setup() throws IOException, WorkerException { } @Test - public void testEnums() { + void testEnums() { Enums.isCompatible(AirbyteConnectionStatus.Status.class, Status.class); } @Test - public void testSuccessfulConnection() throws WorkerException { + void testSuccessfulConnection() throws WorkerException { final DefaultCheckConnectionWorker worker = new DefaultCheckConnectionWorker(workerConfigs, integrationLauncher, successStreamFactory); final ConnectorJobOutput output = worker.run(input, jobRoot); @@ -103,7 +104,7 @@ public void testSuccessfulConnection() throws WorkerException { } @Test - public void testFailedConnection() throws WorkerException { + void testFailedConnection() throws WorkerException { final DefaultCheckConnectionWorker worker = new DefaultCheckConnectionWorker(workerConfigs, integrationLauncher, failureStreamFactory); final ConnectorJobOutput output = worker.run(input, jobRoot); @@ -116,7 +117,7 @@ public void testFailedConnection() throws WorkerException { } @Test - public void testProcessFail() { + void testProcessFail() { when(process.exitValue()).thenReturn(1); final DefaultCheckConnectionWorker worker = new DefaultCheckConnectionWorker(workerConfigs, integrationLauncher, failureStreamFactory); @@ -124,7 +125,7 @@ public void testProcessFail() { } @Test - public void testProcessFailWithTraceMessage() throws WorkerException { + void testProcessFailWithTraceMessage() throws WorkerException { when(process.exitValue()).thenReturn(1); final DefaultCheckConnectionWorker worker = new DefaultCheckConnectionWorker(workerConfigs, integrationLauncher, traceMessageStreamFactory); @@ -138,7 +139,7 @@ public void testProcessFailWithTraceMessage() throws WorkerException { } @Test - public void testExceptionThrownInRun() throws WorkerException { + void testExceptionThrownInRun() throws WorkerException { doThrow(new RuntimeException()).when(integrationLauncher).check(jobRoot, WorkerConstants.SOURCE_CONFIG_JSON_FILENAME, Jsons.serialize(CREDS)); final DefaultCheckConnectionWorker worker = new DefaultCheckConnectionWorker(workerConfigs, integrationLauncher, failureStreamFactory); @@ -147,7 +148,7 @@ public void testExceptionThrownInRun() throws WorkerException { } @Test - public void testCancel() throws WorkerException { + void testCancel() throws WorkerException { final DefaultCheckConnectionWorker worker = new DefaultCheckConnectionWorker(workerConfigs, integrationLauncher, successStreamFactory); worker.run(input, jobRoot); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/general/DefaultDiscoverCatalogWorkerTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/general/DefaultDiscoverCatalogWorkerTest.java index 299db6c823f4..5d99f6175756 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/general/DefaultDiscoverCatalogWorkerTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/general/DefaultDiscoverCatalogWorkerTest.java @@ -4,6 +4,10 @@ package io.airbyte.workers.general; +/* + * Copyright (c) 2022 Airbyte, Inc., all rights reserved. + */ + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -45,7 +49,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class DefaultDiscoverCatalogWorkerTest { +class DefaultDiscoverCatalogWorkerTest { private static final JsonNode CREDENTIALS = Jsons.jsonNode(ImmutableMap.builder().put("apiKey", "123").build()); private static final StandardDiscoverCatalogInput INPUT = new StandardDiscoverCatalogInput().withConnectionConfiguration(CREDENTIALS); @@ -67,7 +71,7 @@ public class DefaultDiscoverCatalogWorkerTest { private AirbyteStreamFactory streamFactory; @BeforeEach - public void setup() throws Exception { + void setup() throws Exception { workerConfigs = new WorkerConfigs(new EnvConfigs()); jobRoot = Files.createTempDirectory(Files.createDirectories(TEST_ROOT), ""); integrationLauncher = mock(IntegrationLauncher.class, RETURNS_DEEP_STUBS); @@ -85,7 +89,7 @@ public void setup() throws Exception { @SuppressWarnings("BusyWait") @Test - public void testDiscoverSchema() throws Exception { + void testDiscoverSchema() throws Exception { final DefaultDiscoverCatalogWorker worker = new DefaultDiscoverCatalogWorker(workerConfigs, integrationLauncher, streamFactory); final ConnectorJobOutput output = worker.run(INPUT, jobRoot); @@ -104,7 +108,7 @@ public void testDiscoverSchema() throws Exception { @SuppressWarnings("BusyWait") @Test - public void testDiscoverSchemaProcessFail() throws Exception { + void testDiscoverSchemaProcessFail() throws Exception { when(process.exitValue()).thenReturn(1); final DefaultDiscoverCatalogWorker worker = new DefaultDiscoverCatalogWorker(workerConfigs, integrationLauncher, streamFactory); @@ -121,7 +125,7 @@ public void testDiscoverSchemaProcessFail() throws Exception { @SuppressWarnings("BusyWait") @Test - public void testDiscoverSchemaProcessFailWithTraceMessage() throws Exception { + void testDiscoverSchemaProcessFailWithTraceMessage() throws Exception { final AirbyteStreamFactory traceStreamFactory = noop -> Lists.newArrayList( AirbyteMessageUtils.createTraceMessage("some error from the connector", 123.0)).stream(); @@ -146,7 +150,7 @@ public void testDiscoverSchemaProcessFailWithTraceMessage() throws Exception { } @Test - public void testDiscoverSchemaException() throws WorkerException { + void testDiscoverSchemaException() throws WorkerException { when(integrationLauncher.discover(jobRoot, WorkerConstants.SOURCE_CONFIG_JSON_FILENAME, Jsons.serialize(CREDENTIALS))) .thenThrow(new RuntimeException()); @@ -155,7 +159,7 @@ public void testDiscoverSchemaException() throws WorkerException { } @Test - public void testCancel() throws WorkerException { + void testCancel() throws WorkerException { final DefaultDiscoverCatalogWorker worker = new DefaultDiscoverCatalogWorker(workerConfigs, integrationLauncher, streamFactory); worker.run(INPUT, jobRoot); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/general/DefaultGetSpecWorkerTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/general/DefaultGetSpecWorkerTest.java index b481d3f1e0a9..a98ac3ecd7dc 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/general/DefaultGetSpecWorkerTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/general/DefaultGetSpecWorkerTest.java @@ -49,7 +49,7 @@ class DefaultGetSpecWorkerTest { private JobGetSpecConfig config; @BeforeEach - public void setup() throws IOException, WorkerException { + void setup() throws IOException, WorkerException { jobRoot = Files.createTempDirectory(Files.createDirectories(TEST_ROOT), ""); config = new JobGetSpecConfig().withDockerImage(DUMMY_IMAGE_NAME); integrationLauncher = mock(IntegrationLauncher.class, RETURNS_DEEP_STUBS); @@ -61,7 +61,7 @@ public void setup() throws IOException, WorkerException { } @Test - public void testSuccessfulRun() throws IOException, InterruptedException, WorkerException { + void testSuccessfulRun() throws IOException, InterruptedException, WorkerException { final String expectedSpecString = MoreResources.readResource("valid_spec.json"); final AirbyteMessage message = new AirbyteMessage() @@ -80,7 +80,7 @@ public void testSuccessfulRun() throws IOException, InterruptedException, Worker } @Test - public void testFailureOnInvalidSpec() throws InterruptedException { + void testFailureOnInvalidSpec() throws InterruptedException { final String expectedSpecString = "{\"key\":\"value\"}"; when(process.getInputStream()).thenReturn(new ByteArrayInputStream(expectedSpecString.getBytes(Charsets.UTF_8))); when(process.waitFor(anyLong(), any())).thenReturn(true); @@ -95,7 +95,7 @@ public void testFailureOnInvalidSpec() throws InterruptedException { } @Test - public void testFailureOnNonzeroExitCode() throws InterruptedException, IOException { + void testFailureOnNonzeroExitCode() throws InterruptedException, IOException { final String expectedSpecString = MoreResources.readResource("valid_spec.json"); final AirbyteMessage message = new AirbyteMessage() @@ -115,7 +115,7 @@ public void testFailureOnNonzeroExitCode() throws InterruptedException, IOExcept } @Test - public void testFailureOnNonzeroExitCodeWithTraceMessage() throws WorkerException, InterruptedException { + void testFailureOnNonzeroExitCodeWithTraceMessage() throws WorkerException, InterruptedException { final AirbyteMessage message = AirbyteMessageUtils.createTraceMessage("some error from the connector", 123.0); when(process.getInputStream()).thenReturn(new ByteArrayInputStream(Jsons.serialize(message).getBytes(Charsets.UTF_8))); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/helper/FailureHelperTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/helper/FailureHelperTest.java index 689ee4c34bcd..95a6b61a2870 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/helper/FailureHelperTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/helper/FailureHelperTest.java @@ -16,7 +16,7 @@ import java.util.Set; import org.junit.jupiter.api.Test; -public class FailureHelperTest { +class FailureHelperTest { private static final FailureReason TRACE_FAILURE_REASON = new FailureReason() .withInternalMessage("internal message") @@ -45,7 +45,7 @@ public class FailureHelperTest { .withAdditionalProperty("attempt", 1)); @Test - public void testGenericFailureFromTrace() throws Exception { + void testGenericFailureFromTrace() throws Exception { final AirbyteTraceMessage traceMessage = AirbyteMessageUtils.createErrorTraceMessage("trace message error", Double.valueOf(123), AirbyteErrorTraceMessage.FailureType.CONFIG_ERROR); final FailureReason failureReason = FailureHelper.genericFailure(traceMessage, Long.valueOf(12345), 1); @@ -53,14 +53,14 @@ public void testGenericFailureFromTrace() throws Exception { } @Test - public void testGenericFailureFromTraceNoFailureType() throws Exception { + void testGenericFailureFromTraceNoFailureType() throws Exception { final AirbyteTraceMessage traceMessage = AirbyteMessageUtils.createErrorTraceMessage("trace message error", Double.valueOf(123)); final FailureReason failureReason = FailureHelper.genericFailure(traceMessage, Long.valueOf(12345), 1); assertEquals(failureReason.getFailureType(), FailureType.SYSTEM_ERROR); } @Test - public void testOrderedFailures() throws Exception { + void testOrderedFailures() throws Exception { final List failureReasonList = FailureHelper.orderedFailures(Set.of(TRACE_FAILURE_REASON_2, TRACE_FAILURE_REASON, EXCEPTION_FAILURE_REASON)); assertEquals(failureReasonList.get(0), TRACE_FAILURE_REASON); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/internal/AirbyteMessageTrackerTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/internal/AirbyteMessageTrackerTest.java index b54e1892b7d6..892be63cc865 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/internal/AirbyteMessageTrackerTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/internal/AirbyteMessageTrackerTest.java @@ -39,12 +39,12 @@ class AirbyteMessageTrackerTest { private StateAggregator mStateAggregator; @BeforeEach - public void setup() { + void setup() { this.messageTracker = new AirbyteMessageTracker(mStateDeltaTracker, mStateAggregator); } @Test - public void testGetTotalRecordsStatesAndBytesEmitted() { + void testGetTotalRecordsStatesAndBytesEmitted() { final AirbyteMessage r1 = AirbyteMessageUtils.createRecordMessage(STREAM_1, 123); final AirbyteMessage s1 = AirbyteMessageUtils.createStateMessage(1); final AirbyteMessage s2 = AirbyteMessageUtils.createStateMessage(2); @@ -61,7 +61,7 @@ public void testGetTotalRecordsStatesAndBytesEmitted() { } @Test - public void testRetainsLatestSourceAndDestinationState() { + void testRetainsLatestSourceAndDestinationState() { final int s1Value = 111; final int s2Value = 222; final int s3Value = 333; @@ -86,13 +86,13 @@ public void testRetainsLatestSourceAndDestinationState() { } @Test - public void testReturnEmptyStateIfNoneEverAccepted() { + void testReturnEmptyStateIfNoneEverAccepted() { assertTrue(messageTracker.getSourceOutputState().isEmpty()); assertTrue(messageTracker.getDestinationOutputState().isEmpty()); } @Test - public void testEmittedRecordsByStream() { + void testEmittedRecordsByStream() { final AirbyteMessage r1 = AirbyteMessageUtils.createRecordMessage(STREAM_1, 1); final AirbyteMessage r2 = AirbyteMessageUtils.createRecordMessage(STREAM_2, 2); final AirbyteMessage r3 = AirbyteMessageUtils.createRecordMessage(STREAM_3, 3); @@ -113,7 +113,7 @@ public void testEmittedRecordsByStream() { } @Test - public void testEmittedBytesByStream() { + void testEmittedBytesByStream() { final AirbyteMessage r1 = AirbyteMessageUtils.createRecordMessage(STREAM_1, 1); final AirbyteMessage r2 = AirbyteMessageUtils.createRecordMessage(STREAM_2, 2); final AirbyteMessage r3 = AirbyteMessageUtils.createRecordMessage(STREAM_3, 3); @@ -138,7 +138,7 @@ public void testEmittedBytesByStream() { } @Test - public void testGetCommittedRecordsByStream() { + void testGetCommittedRecordsByStream() { final AirbyteMessage r1 = AirbyteMessageUtils.createRecordMessage(STREAM_1, 1); final AirbyteMessage r2 = AirbyteMessageUtils.createRecordMessage(STREAM_2, 2); final AirbyteMessage r3 = AirbyteMessageUtils.createRecordMessage(STREAM_3, 3); @@ -181,7 +181,7 @@ public void testGetCommittedRecordsByStream() { } @Test - public void testGetCommittedRecordsByStream_emptyWhenAddStateThrowsException() throws Exception { + void testGetCommittedRecordsByStream_emptyWhenAddStateThrowsException() throws Exception { Mockito.doThrow(new StateDeltaTrackerException("induced exception")).when(mStateDeltaTracker).addState(Mockito.anyInt(), Mockito.anyMap()); final AirbyteMessage r1 = AirbyteMessageUtils.createRecordMessage(STREAM_1, 1); @@ -195,7 +195,7 @@ public void testGetCommittedRecordsByStream_emptyWhenAddStateThrowsException() t } @Test - public void testGetCommittedRecordsByStream_emptyWhenCommitStateHashThrowsException() throws Exception { + void testGetCommittedRecordsByStream_emptyWhenCommitStateHashThrowsException() throws Exception { Mockito.doThrow(new StateDeltaTrackerException("induced exception")).when(mStateDeltaTracker).commitStateHash(Mockito.anyInt()); final AirbyteMessage r1 = AirbyteMessageUtils.createRecordMessage(STREAM_1, 1); @@ -209,7 +209,7 @@ public void testGetCommittedRecordsByStream_emptyWhenCommitStateHashThrowsExcept } @Test - public void testTotalRecordsCommitted() { + void testTotalRecordsCommitted() { final AirbyteMessage r1 = AirbyteMessageUtils.createRecordMessage(STREAM_1, 1); final AirbyteMessage r2 = AirbyteMessageUtils.createRecordMessage(STREAM_2, 2); final AirbyteMessage r3 = AirbyteMessageUtils.createRecordMessage(STREAM_3, 3); @@ -245,7 +245,7 @@ public void testTotalRecordsCommitted() { } @Test - public void testGetTotalRecordsCommitted_emptyWhenAddStateThrowsException() throws Exception { + void testGetTotalRecordsCommitted_emptyWhenAddStateThrowsException() throws Exception { Mockito.doThrow(new StateDeltaTrackerException("induced exception")).when(mStateDeltaTracker).addState(Mockito.anyInt(), Mockito.anyMap()); final AirbyteMessage r1 = AirbyteMessageUtils.createRecordMessage(STREAM_1, 1); @@ -259,7 +259,7 @@ public void testGetTotalRecordsCommitted_emptyWhenAddStateThrowsException() thro } @Test - public void testGetTotalRecordsCommitted_emptyWhenCommitStateHashThrowsException() throws Exception { + void testGetTotalRecordsCommitted_emptyWhenCommitStateHashThrowsException() throws Exception { Mockito.doThrow(new StateDeltaTrackerException("induced exception")).when(mStateDeltaTracker).commitStateHash(Mockito.anyInt()); final AirbyteMessage r1 = AirbyteMessageUtils.createRecordMessage(STREAM_1, 1); @@ -273,7 +273,7 @@ public void testGetTotalRecordsCommitted_emptyWhenCommitStateHashThrowsException } @Test - public void testGetFirstDestinationAndSourceMessages() throws Exception { + void testGetFirstDestinationAndSourceMessages() throws Exception { final AirbyteMessage sourceMessage1 = AirbyteMessageUtils.createTraceMessage("source trace 1", Double.valueOf(123)); final AirbyteMessage sourceMessage2 = AirbyteMessageUtils.createTraceMessage("source trace 2", Double.valueOf(124)); final AirbyteMessage destMessage1 = AirbyteMessageUtils.createTraceMessage("dest trace 1", Double.valueOf(125)); @@ -288,13 +288,13 @@ public void testGetFirstDestinationAndSourceMessages() throws Exception { } @Test - public void testGetFirstDestinationAndSourceMessagesWithNulls() throws Exception { + void testGetFirstDestinationAndSourceMessagesWithNulls() throws Exception { assertEquals(messageTracker.getFirstDestinationErrorTraceMessage(), null); assertEquals(messageTracker.getFirstSourceErrorTraceMessage(), null); } @Test - public void testErrorTraceMessageFailureWithMultipleTraceErrors() throws Exception { + void testErrorTraceMessageFailureWithMultipleTraceErrors() throws Exception { final AirbyteMessage sourceMessage1 = AirbyteMessageUtils.createTraceMessage("source trace 1", Double.valueOf(123)); final AirbyteMessage sourceMessage2 = AirbyteMessageUtils.createTraceMessage("source trace 2", Double.valueOf(124)); final AirbyteMessage destMessage1 = AirbyteMessageUtils.createTraceMessage("dest trace 1", Double.valueOf(125)); @@ -310,7 +310,7 @@ public void testErrorTraceMessageFailureWithMultipleTraceErrors() throws Excepti } @Test - public void testErrorTraceMessageFailureWithOneTraceError() throws Exception { + void testErrorTraceMessageFailureWithOneTraceError() throws Exception { final AirbyteMessage destMessage = AirbyteMessageUtils.createTraceMessage("dest trace 1", Double.valueOf(125)); messageTracker.acceptFromDestination(destMessage); @@ -319,7 +319,7 @@ public void testErrorTraceMessageFailureWithOneTraceError() throws Exception { } @Test - public void testErrorTraceMessageFailureWithNoTraceErrors() throws Exception { + void testErrorTraceMessageFailureWithNoTraceErrors() throws Exception { assertEquals(messageTracker.errorTraceMessageFailure(Long.valueOf(123), 1), null); } diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/internal/DefaultAirbyteDestinationTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/internal/DefaultAirbyteDestinationTest.java index 17c013aae2db..ed0131e36400 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/internal/DefaultAirbyteDestinationTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/internal/DefaultAirbyteDestinationTest.java @@ -46,9 +46,13 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") class DefaultAirbyteDestinationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultAirbyteDestinationTest.class); private static final Path TEST_ROOT = Path.of("/tmp/airbyte_tests"); private static final String JOB_ROOT_PREFIX = "workspace"; private static final String STREAM_NAME = "user_preferences"; @@ -68,7 +72,7 @@ class DefaultAirbyteDestinationTest { logJobRoot = Files.createTempDirectory(Path.of("/tmp"), "mdc_test"); LogClientSingleton.getInstance().setJobMdc(WorkerEnvironment.DOCKER, LogConfigs.EMPTY, logJobRoot); } catch (final IOException e) { - e.printStackTrace(); + LOGGER.error(e.toString()); } } @@ -80,7 +84,7 @@ class DefaultAirbyteDestinationTest { private ByteArrayOutputStream outputStream; @BeforeEach - public void setup() throws IOException, WorkerException { + void setup() throws IOException, WorkerException { workerConfigs = new WorkerConfigs(new EnvConfigs()); jobRoot = Files.createTempDirectory(Files.createDirectories(TEST_ROOT), JOB_ROOT_PREFIX); @@ -107,7 +111,7 @@ public void setup() throws IOException, WorkerException { } @AfterEach - public void tearDown() throws IOException { + void tearDown() throws IOException { // The log file needs to be present and empty final Path logFile = logJobRoot.resolve(LogClientSingleton.LOG_FILENAME); if (Files.exists(logFile)) { @@ -118,7 +122,7 @@ public void tearDown() throws IOException { @SuppressWarnings("BusyWait") @Test - public void testSuccessfulLifecycle() throws Exception { + void testSuccessfulLifecycle() throws Exception { final AirbyteDestination destination = new DefaultAirbyteDestination(workerConfigs, integrationLauncher, streamFactory); destination.start(DESTINATION_CONFIG, jobRoot); @@ -156,7 +160,7 @@ public void testSuccessfulLifecycle() throws Exception { } @Test - public void testTaggedLogs() throws Exception { + void testTaggedLogs() throws Exception { final AirbyteDestination destination = new DefaultAirbyteDestination(workerConfigs, integrationLauncher, streamFactory); destination.start(DESTINATION_CONFIG, jobRoot); @@ -185,7 +189,7 @@ public void testTaggedLogs() throws Exception { } @Test - public void testCloseNotifiesLifecycle() throws Exception { + void testCloseNotifiesLifecycle() throws Exception { final AirbyteDestination destination = new DefaultAirbyteDestination(workerConfigs, integrationLauncher); destination.start(DESTINATION_CONFIG, jobRoot); @@ -197,7 +201,7 @@ public void testCloseNotifiesLifecycle() throws Exception { } @Test - public void testNonzeroExitCodeThrowsException() throws Exception { + void testNonzeroExitCodeThrowsException() throws Exception { final AirbyteDestination destination = new DefaultAirbyteDestination(workerConfigs, integrationLauncher); destination.start(DESTINATION_CONFIG, jobRoot); @@ -207,7 +211,7 @@ public void testNonzeroExitCodeThrowsException() throws Exception { } @Test - public void testGetExitValue() throws Exception { + void testGetExitValue() throws Exception { final AirbyteDestination destination = new DefaultAirbyteDestination(workerConfigs, integrationLauncher); destination.start(DESTINATION_CONFIG, jobRoot); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/internal/DefaultAirbyteSourceTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/internal/DefaultAirbyteSourceTest.java index 9c1b5e55c84f..976a5c3086d8 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/internal/DefaultAirbyteSourceTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/internal/DefaultAirbyteSourceTest.java @@ -49,9 +49,13 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") class DefaultAirbyteSourceTest { + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultAirbyteSourceTest.class); private static final String NAMESPACE = "unused"; private static final Path TEST_ROOT = Path.of("/tmp/airbyte_tests"); private static final String STREAM_NAME = "user_preferences"; @@ -82,7 +86,7 @@ class DefaultAirbyteSourceTest { logJobRoot = Files.createTempDirectory(Path.of("/tmp"), "mdc_test"); LogClientSingleton.getInstance().setJobMdc(WorkerEnvironment.DOCKER, LogConfigs.EMPTY, logJobRoot); } catch (final IOException e) { - e.printStackTrace(); + LOGGER.error(e.toString()); } } @@ -94,7 +98,7 @@ class DefaultAirbyteSourceTest { private HeartbeatMonitor heartbeatMonitor; @BeforeEach - public void setup() throws IOException, WorkerException { + void setup() throws IOException, WorkerException { workerConfigs = new WorkerConfigs(new EnvConfigs()); jobRoot = Files.createTempDirectory(Files.createDirectories(TEST_ROOT), "test"); @@ -120,7 +124,7 @@ public void setup() throws IOException, WorkerException { } @AfterEach - public void tearDown() throws IOException { + void tearDown() throws IOException { // The log file needs to be present and empty final Path logFile = logJobRoot.resolve(LogClientSingleton.LOG_FILENAME); if (Files.exists(logFile)) { @@ -131,7 +135,7 @@ public void tearDown() throws IOException { @SuppressWarnings({"OptionalGetWithoutIsPresent", "BusyWait"}) @Test - public void testSuccessfulLifecycle() throws Exception { + void testSuccessfulLifecycle() throws Exception { when(process.getErrorStream()).thenReturn(new ByteArrayInputStream("qwer".getBytes(StandardCharsets.UTF_8))); when(heartbeatMonitor.isBeating()).thenReturn(true).thenReturn(false); @@ -165,7 +169,7 @@ public void testSuccessfulLifecycle() throws Exception { } @Test - public void testTaggedLogs() throws Exception { + void testTaggedLogs() throws Exception { when(process.getErrorStream()).thenReturn(new ByteArrayInputStream(("rewq").getBytes(StandardCharsets.UTF_8))); @@ -196,7 +200,7 @@ public void testTaggedLogs() throws Exception { } @Test - public void testNonzeroExitCodeThrows() throws Exception { + void testNonzeroExitCodeThrows() throws Exception { final AirbyteSource tap = new DefaultAirbyteSource(workerConfigs, integrationLauncher, streamFactory, heartbeatMonitor); tap.start(SOURCE_CONFIG, jobRoot); @@ -206,7 +210,7 @@ public void testNonzeroExitCodeThrows() throws Exception { } @Test - public void testGetExitValue() throws Exception { + void testGetExitValue() throws Exception { final AirbyteSource source = new DefaultAirbyteSource(workerConfigs, integrationLauncher, streamFactory, heartbeatMonitor); source.start(SOURCE_CONFIG, jobRoot); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/internal/DefaultAirbyteStreamFactoryTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/internal/DefaultAirbyteStreamFactoryTest.java index a77ebcd3b744..226fd06fdc4b 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/internal/DefaultAirbyteStreamFactoryTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/internal/DefaultAirbyteStreamFactoryTest.java @@ -39,14 +39,14 @@ class DefaultAirbyteStreamFactoryTest { private Logger logger; @BeforeEach - public void setup() { + void setup() { protocolPredicate = mock(AirbyteProtocolPredicate.class); when(protocolPredicate.test(any())).thenReturn(true); logger = mock(Logger.class); } @Test - public void testValid() { + void testValid() { final AirbyteMessage record1 = AirbyteMessageUtils.createRecordMessage(STREAM_NAME, FIELD_NAME, "green"); final Stream messageStream = stringToMessageStream(Jsons.serialize(record1)); @@ -57,7 +57,7 @@ public void testValid() { } @Test - public void testLoggingLine() { + void testLoggingLine() { final String invalidRecord = "invalid line"; final Stream messageStream = stringToMessageStream(invalidRecord); @@ -68,7 +68,7 @@ public void testLoggingLine() { } @Test - public void testLoggingLevel() { + void testLoggingLevel() { final AirbyteMessage logMessage = AirbyteMessageUtils.createLogMessage(AirbyteLogMessage.Level.WARN, "warning"); final Stream messageStream = stringToMessageStream(Jsons.serialize(logMessage)); @@ -79,7 +79,7 @@ public void testLoggingLevel() { } @Test - public void testFailValidation() { + void testFailValidation() { final String invalidRecord = "{ \"fish\": \"tuna\"}"; when(protocolPredicate.test(Jsons.deserialize(invalidRecord))).thenReturn(false); @@ -92,7 +92,7 @@ public void testFailValidation() { } @Test - public void testFailDeserialization() { + void testFailDeserialization() { final String invalidRecord = "{ \"type\": \"abc\"}"; when(protocolPredicate.test(Jsons.deserialize(invalidRecord))).thenReturn(true); @@ -106,7 +106,7 @@ public void testFailDeserialization() { @Test @Disabled - public void testMissingNewLineBetweenValidRecords() { + void testMissingNewLineBetweenValidRecords() { final AirbyteMessage record1 = AirbyteMessageUtils.createRecordMessage(STREAM_NAME, FIELD_NAME, "green"); final AirbyteMessage record2 = AirbyteMessageUtils.createRecordMessage(STREAM_NAME, FIELD_NAME, "yellow"); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/internal/EmptyAirbyteSourceTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/internal/EmptyAirbyteSourceTest.java index be2b61c9afd7..5455606f367e 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/internal/EmptyAirbyteSourceTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/internal/EmptyAirbyteSourceTest.java @@ -28,7 +28,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class EmptyAirbyteSourceTest { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class EmptyAirbyteSourceTest { private EmptyAirbyteSource emptyAirbyteSource; private final AirbyteMessage EMPTY_MESSAGE = @@ -42,26 +43,26 @@ public class EmptyAirbyteSourceTest { new ConfiguredAirbyteStream().withStream(new AirbyteStream().withName("c")))); @BeforeEach - public void init() { + void init() { emptyAirbyteSource = new EmptyAirbyteSource(true); } @Test - public void testLegacy() throws Exception { + void testLegacy() throws Exception { emptyAirbyteSource.start(new WorkerSourceConfig(), null); legacyStateResult(); } @Test - public void testLegacyWithEmptyConfig() throws Exception { + void testLegacyWithEmptyConfig() throws Exception { emptyAirbyteSource.start(new WorkerSourceConfig().withSourceConnectionConfiguration(Jsons.emptyObject()), null); legacyStateResult(); } @Test - public void testLegacyWithWrongConfigFormat() throws Exception { + void testLegacyWithWrongConfigFormat() throws Exception { emptyAirbyteSource.start(new WorkerSourceConfig().withSourceConnectionConfiguration(Jsons.jsonNode( Map.of("not", "expected"))), null); @@ -69,7 +70,7 @@ public void testLegacyWithWrongConfigFormat() throws Exception { } @Test - public void testEmptyListOfStreams() throws Exception { + void testEmptyListOfStreams() throws Exception { final ResetSourceConfiguration resetSourceConfiguration = new ResetSourceConfiguration() .withStreamsToReset(new ArrayList<>()); final WorkerSourceConfig workerSourceConfig = new WorkerSourceConfig() @@ -82,14 +83,14 @@ public void testEmptyListOfStreams() throws Exception { } @Test - public void nonStartedSource() { + void nonStartedSource() { final Throwable thrown = Assertions.catchThrowable(() -> emptyAirbyteSource.attemptRead()); Assertions.assertThat(thrown) .isInstanceOf(IllegalStateException.class); } @Test - public void testGlobal() throws Exception { + void testGlobal() throws Exception { final List streamDescriptors = getProtocolStreamDescriptorFromName(Lists.newArrayList("a", "b", "c")); final List streamToReset = getConfigStreamDescriptorFromName(Lists.newArrayList("a", "b", "c")); @@ -142,7 +143,7 @@ public void testGlobal() throws Exception { } @Test - public void testGlobalPartial() throws Exception { + void testGlobalPartial() throws Exception { final String NOT_RESET_STREAM_NAME = "c"; final List streamDescriptors = getProtocolStreamDescriptorFromName(Lists.newArrayList("a", "b", NOT_RESET_STREAM_NAME)); @@ -186,7 +187,7 @@ public void testGlobalPartial() throws Exception { } @Test - public void testGlobalNewStream() throws Exception { + void testGlobalNewStream() throws Exception { final String NEW_STREAM = "c"; final List streamDescriptors = getProtocolStreamDescriptorFromName(Lists.newArrayList("a", "b")); @@ -228,7 +229,7 @@ public void testGlobalNewStream() throws Exception { } @Test - public void testPerStream() throws Exception { + void testPerStream() throws Exception { final List streamDescriptors = getProtocolStreamDescriptorFromName(Lists.newArrayList("a", "b", "c")); final List streamToReset = getConfigStreamDescriptorFromName(Lists.newArrayList("a", "b", "c")); @@ -252,7 +253,7 @@ public void testPerStream() throws Exception { } @Test - public void testPerStreamWithExtraState() throws Exception { + void testPerStreamWithExtraState() throws Exception { // This should never happen but nothing keeps us from processing the reset and not fail final List streamDescriptors = getProtocolStreamDescriptorFromName(Lists.newArrayList("a", "b", "c", "d")); @@ -277,7 +278,7 @@ public void testPerStreamWithExtraState() throws Exception { } @Test - public void testPerStreamWithMissingState() throws Exception { + void testPerStreamWithMissingState() throws Exception { final String NEW_STREAM = "c"; final List streamDescriptors = getProtocolStreamDescriptorFromName(Lists.newArrayList("a", "b")); @@ -305,7 +306,7 @@ public void testPerStreamWithMissingState() throws Exception { // In the LEGACY state, if the list of streams passed in to be reset does not include every stream // in the Catalog, then something has gone wrong and we should throw an error @Test - public void testLegacyWithMissingCatalogStream() { + void testLegacyWithMissingCatalogStream() { final List streamToReset = getConfigStreamDescriptorFromName(Lists.newArrayList("a", "b", "c")); @@ -332,7 +333,7 @@ public void testLegacyWithMissingCatalogStream() { // If there are extra streams to reset that do not exist in the Catalog, the reset should work // properly with all streams being reset @Test - public void testLegacyWithResettingExtraStreamNotInCatalog() throws Exception { + void testLegacyWithResettingExtraStreamNotInCatalog() throws Exception { final List streamToResetWithExtra = getConfigStreamDescriptorFromName(Lists.newArrayList("a", "b", "c", "d")); final ResetSourceConfiguration resetSourceConfiguration = new ResetSourceConfiguration() @@ -370,7 +371,7 @@ public void testLegacyWithResettingExtraStreamNotInCatalog() throws Exception { } @Test - public void testLegacyWithNewConfig() throws Exception { + void testLegacyWithNewConfig() throws Exception { final List streamToReset = getConfigStreamDescriptorFromName(Lists.newArrayList("a", "b", "c")); final ResetSourceConfiguration resetSourceConfiguration = new ResetSourceConfiguration() @@ -407,7 +408,7 @@ public void testLegacyWithNewConfig() throws Exception { } @Test - public void testLegacyWithNullState() throws Exception { + void testLegacyWithNullState() throws Exception { final List streamToReset = getConfigStreamDescriptorFromName(Lists.newArrayList("a", "b", "c")); final ResetSourceConfiguration resetSourceConfiguration = new ResetSourceConfiguration() diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/internal/StateDeltaTrackerTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/internal/StateDeltaTrackerTest.java index 28425aa6de4a..3df44d94a5fd 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/internal/StateDeltaTrackerTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/internal/StateDeltaTrackerTest.java @@ -12,7 +12,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class StateDeltaTrackerTest { +class StateDeltaTrackerTest { private static final int STATE_1_HASH = 1; private static final int STATE_2_HASH = 2; @@ -40,7 +40,7 @@ public class StateDeltaTrackerTest { private StateDeltaTracker stateDeltaTracker; @BeforeEach - public void setup() throws Exception { + void setup() throws Exception { final Map state1Counts = new HashMap<>(); state1Counts.put(STREAM_INDEX_1, STATE_1_STREAM_1_COUNT); state1Counts.put(STREAM_INDEX_2, STATE_1_STREAM_2_COUNT); @@ -60,13 +60,13 @@ public void setup() throws Exception { } @Test - public void testAddState_throwsExceptionWhenCapacityExceeded() { + void testAddState_throwsExceptionWhenCapacityExceeded() { Assertions.assertThrows(StateDeltaTrackerException.class, () -> stateDeltaTracker.addState(4, Collections.singletonMap((short) 444, 44L))); Assertions.assertTrue(stateDeltaTracker.capacityExceeded); } @Test - public void testCommitStateHash_throwsExceptionWhenStateHashConflict() throws Exception { + void testCommitStateHash_throwsExceptionWhenStateHashConflict() throws Exception { stateDeltaTracker.commitStateHash(STATE_1_HASH); stateDeltaTracker.commitStateHash(STATE_2_HASH); @@ -74,18 +74,18 @@ public void testCommitStateHash_throwsExceptionWhenStateHashConflict() throws Ex } @Test - public void testCommitStateHash_throwsExceptionIfCapacityExceededEarlier() { + void testCommitStateHash_throwsExceptionIfCapacityExceededEarlier() { stateDeltaTracker.capacityExceeded = true; Assertions.assertThrows(StateDeltaTrackerException.class, () -> stateDeltaTracker.commitStateHash(STATE_1_HASH)); } @Test - public void testCommitStateHash_throwsExceptionIfCommitStateHashCalledBeforeAddingState() { + void testCommitStateHash_throwsExceptionIfCommitStateHashCalledBeforeAddingState() { Assertions.assertThrows(StateDeltaTrackerException.class, () -> stateDeltaTracker.commitStateHash(NEVER_ADDED_STATE_HASH)); } @Test - public void testGetCommittedRecordsByStream() throws Exception { + void testGetCommittedRecordsByStream() throws Exception { // before anything is committed, returned map should be empty and deltas should contain three states final Map expected = new HashMap<>(); Assertions.assertEquals(expected, stateDeltaTracker.getStreamToCommittedRecords()); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/internal/state_aggregator/StateAggregatorTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/internal/state_aggregator/StateAggregatorTest.java index 627030a6615a..bd591be29b13 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/internal/state_aggregator/StateAggregatorTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/internal/state_aggregator/StateAggregatorTest.java @@ -25,20 +25,21 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; -public class StateAggregatorTest { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class StateAggregatorTest { StateAggregator stateAggregator; boolean USE_STREAM_CAPABLE_STATE = true; boolean DONT_USE_STREAM_CAPABLE_STATE = false; @BeforeEach - public void init() { + void init() { stateAggregator = new DefaultStateAggregator(DONT_USE_STREAM_CAPABLE_STATE); } @ParameterizedTest @EnumSource(AirbyteStateType.class) - public void testCantMixType(final AirbyteStateType stateType) { + void testCantMixType(final AirbyteStateType stateType) { final Stream allTypes = Arrays.stream(AirbyteStateType.values()); stateAggregator.ingest(getEmptyMessage(stateType)); @@ -48,7 +49,7 @@ public void testCantMixType(final AirbyteStateType stateType) { } @Test - public void testCantMixNullType() { + void testCantMixNullType() { final List allIncompatibleTypes = Lists.newArrayList(GLOBAL, STREAM); stateAggregator.ingest(getEmptyMessage(null)); @@ -59,7 +60,7 @@ public void testCantMixNullType() { } @Test - public void testNullState() { + void testNullState() { final AirbyteStateMessage state1 = getNullMessage(1); final AirbyteStateMessage state2 = getNullMessage(2); @@ -73,7 +74,7 @@ public void testNullState() { } @Test - public void testLegacyState() { + void testLegacyState() { final AirbyteStateMessage state1 = getLegacyMessage(1); final AirbyteStateMessage state2 = getLegacyMessage(2); @@ -87,7 +88,7 @@ public void testLegacyState() { } @Test - public void testGlobalState() { + void testGlobalState() { final AirbyteStateMessage state1 = getGlobalMessage(1); final AirbyteStateMessage state2 = getGlobalMessage(2); @@ -101,7 +102,7 @@ public void testGlobalState() { } @Test - public void testStreamStateWithFeatureFlagOff() { + void testStreamStateWithFeatureFlagOff() { final AirbyteStateMessage state1 = getStreamMessage("a", 1); final AirbyteStateMessage state2 = getStreamMessage("b", 2); final AirbyteStateMessage state3 = getStreamMessage("b", 3); @@ -120,7 +121,7 @@ public void testStreamStateWithFeatureFlagOff() { } @Test - public void testStreamStateWithFeatureFlagOn() { + void testStreamStateWithFeatureFlagOn() { final AirbyteStateMessage state1 = getStreamMessage("a", 1); final AirbyteStateMessage state2 = getStreamMessage("b", 2); final AirbyteStateMessage state3 = getStreamMessage("b", 3); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/normalization/DefaultNormalizationRunnerTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/normalization/DefaultNormalizationRunnerTest.java index d82ba3831e8b..de2641d5a0f0 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/normalization/DefaultNormalizationRunnerTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/normalization/DefaultNormalizationRunnerTest.java @@ -39,6 +39,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("PMD.AvoidPrintStackTrace") class DefaultNormalizationRunnerTest { private static final String JOB_ID = "0"; @@ -93,7 +94,7 @@ void setup() throws IOException, WorkerException { } @AfterEach - public void tearDown() throws IOException { + void tearDown() throws IOException { // The log file needs to be present and empty final Path logFile = logJobRoot.resolve(LogClientSingleton.LOG_FILENAME); if (Files.exists(logFile)) { @@ -136,7 +137,7 @@ void testLog() throws Exception { } @Test - public void testClose() throws Exception { + void testClose() throws Exception { when(process.isAlive()).thenReturn(true).thenReturn(false); final NormalizationRunner runner = @@ -149,7 +150,7 @@ public void testClose() throws Exception { } @Test - public void testFailure() { + void testFailure() { doThrow(new RuntimeException()).when(process).exitValue(); final NormalizationRunner runner = diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/process/DockerProcessFactoryTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/process/DockerProcessFactoryTest.java index 347b09e01f86..f77325797215 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/process/DockerProcessFactoryTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/process/DockerProcessFactoryTest.java @@ -42,7 +42,7 @@ class DockerProcessFactoryTest { * when jq is not installed. */ @Test - public void testJqExists() throws IOException { + void testJqExists() throws IOException { final Process process = new ProcessBuilder("jq", "--version").start(); final StringBuilder out = new StringBuilder(); final StringBuilder err = new StringBuilder(); @@ -61,7 +61,7 @@ public void testJqExists() throws IOException { * turned on in gradle. */ @Test - public void testImageExists() throws IOException, WorkerException { + void testImageExists() throws IOException, WorkerException { final Path workspaceRoot = Files.createTempDirectory(Files.createDirectories(TEST_ROOT), "process_factory"); final DockerProcessFactory processFactory = new DockerProcessFactory(new WorkerConfigs(new EnvConfigs()), workspaceRoot, null, null, null); @@ -69,7 +69,7 @@ public void testImageExists() throws IOException, WorkerException { } @Test - public void testImageDoesNotExist() throws IOException, WorkerException { + void testImageDoesNotExist() throws IOException, WorkerException { final Path workspaceRoot = Files.createTempDirectory(Files.createDirectories(TEST_ROOT), "process_factory"); final DockerProcessFactory processFactory = new DockerProcessFactory(new WorkerConfigs(new EnvConfigs()), workspaceRoot, null, null, null); @@ -77,7 +77,7 @@ public void testImageDoesNotExist() throws IOException, WorkerException { } @Test - public void testFileWriting() throws IOException, WorkerException { + void testFileWriting() throws IOException, WorkerException { final Path workspaceRoot = Files.createTempDirectory(Files.createDirectories(TEST_ROOT), "process_factory"); final Path jobRoot = workspaceRoot.resolve("job"); @@ -95,7 +95,7 @@ public void testFileWriting() throws IOException, WorkerException { * Tests that the env var map passed in is accessible within the process. */ @Test - public void testEnvMapSet() throws IOException, WorkerException, InterruptedException { + void testEnvMapSet() throws IOException, WorkerException, InterruptedException { final Path workspaceRoot = Files.createTempDirectory(Files.createDirectories(TEST_ROOT), "process_factory"); final Path jobRoot = workspaceRoot.resolve("job"); @@ -160,7 +160,7 @@ private void waitForDockerToInitialize(final ProcessFactory processFactory, fina "-c", "echo ENV_VAR_1=$ENV_VAR_1"); p.waitFor(); - int exitStatus = p.exitValue(); + final int exitStatus = p.exitValue(); if (exitStatus == 0) { log.info("Successfully ran test docker command."); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/process/KubePodProcessTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/process/KubePodProcessTest.java index f49e6b5acc54..5d324690da0c 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/process/KubePodProcessTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/process/KubePodProcessTest.java @@ -24,7 +24,7 @@ // Disabled until we start minikube on the node. @Disabled -public class KubePodProcessTest { +class KubePodProcessTest { private static final KubernetesClient K8s = new DefaultKubernetesClient(); @@ -35,7 +35,7 @@ public class KubePodProcessTest { private static final String TEST_IMAGE_NO_VAR_NAME = "worker-test:no-var"; @BeforeAll - public static void setup() { + static void setup() { final var varDockerfile = Resources.getResource(TEST_IMAGE_WITH_VAR_PATH); DockerUtils.buildImage(varDockerfile.getPath(), TEST_IMAGE_WITH_VAR_NAME); @@ -48,13 +48,13 @@ class GetPodIp { @Test @DisplayName("Should error when the given pod does not exists.") - public void testGetPodIpNoPod() { + void testGetPodIpNoPod() { assertThrows(RuntimeException.class, () -> KubePodProcess.getPodIP(K8s, "pod-does-not-exist", "default")); } @Test @DisplayName("Should return the correct pod ip.") - public void testGetPodIpGoodPod() throws InterruptedException { + void testGetPodIpGoodPod() throws InterruptedException { final var sleep = new ContainerBuilder() .withImage("busybox") .withName("sleep") diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/process/ProcessFactoryTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/process/ProcessFactoryTest.java index 55b3e5129e86..b8924253bee6 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/process/ProcessFactoryTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/process/ProcessFactoryTest.java @@ -7,7 +7,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class ProcessFactoryTest { +class ProcessFactoryTest { @Test void getPodNameNormal() { diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/TemporalClientTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/TemporalClientTest.java index 267099a66d2a..b2e8564717b5 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/TemporalClientTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/TemporalClientTest.java @@ -245,7 +245,7 @@ void testSubmitSync() { } @Test - public void testSynchronousResetConnection() throws IOException { + void testSynchronousResetConnection() throws IOException { final ConnectionManagerWorkflow mConnectionManagerWorkflow = mock(ConnectionManagerWorkflow.class); final WorkflowState mWorkflowState = mock(WorkflowState.class); when(mConnectionManagerWorkflow.getState()).thenReturn(mWorkflowState); @@ -281,7 +281,7 @@ class TestMigration { @DisplayName("Test that the migration is properly done if needed") @Test - public void migrateCalled() { + void migrateCalled() { final UUID nonMigratedId = UUID.randomUUID(); final UUID migratedId = UUID.randomUUID(); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/TemporalUtilsTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/TemporalUtilsTest.java index d203c88dab06..28da3a3649d0 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/TemporalUtilsTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/TemporalUtilsTest.java @@ -48,6 +48,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") class TemporalUtilsTest { private static final String TASK_QUEUE = "default"; @@ -190,7 +191,7 @@ void testHeartbeatWithContext() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(2); worker.registerActivitiesImplementations(new HeartbeatWorkflow.HeartbeatActivityImpl(() -> { - ActivityExecutionContext context = Activity.getExecutionContext(); + final ActivityExecutionContext context = Activity.getExecutionContext(); TemporalUtils.withBackgroundHeartbeat( // TODO (itaseski) figure out how to decrease heartbeat intervals using reflection () -> { @@ -231,7 +232,7 @@ void testHeartbeatWithContextAndCallbackRef() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(2); worker.registerActivitiesImplementations(new HeartbeatWorkflow.HeartbeatActivityImpl(() -> { - ActivityExecutionContext context = Activity.getExecutionContext(); + final ActivityExecutionContext context = Activity.getExecutionContext(); TemporalUtils.withBackgroundHeartbeat( // TODO (itaseski) figure out how to decrease heartbeat intervals using reflection new AtomicReference<>(() -> {}), @@ -311,6 +312,7 @@ public Activity1Impl(final VoidCallable callable) { this.callable = callable; } + @Override public void activity() { LOGGER.info("before: {}", ACTIVITY1); try { @@ -377,9 +379,10 @@ public Activity1Impl(final AtomicInteger timesReachedEnd) { this.timesReachedEnd = timesReachedEnd; } - public void activity(String arg) { + @Override + public void activity(final String arg) { LOGGER.info("before: {}", ACTIVITY1); - ActivityExecutionContext context = Activity.getExecutionContext(); + final ActivityExecutionContext context = Activity.getExecutionContext(); TemporalUtils.withBackgroundHeartbeat( new AtomicReference<>(null), () -> { diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/check/connection/CheckConnectionWorkflowTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/check/connection/CheckConnectionWorkflowTest.java index b1681681599b..e9f44295d7bc 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/check/connection/CheckConnectionWorkflowTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/check/connection/CheckConnectionWorkflowTest.java @@ -7,10 +7,11 @@ import io.temporal.testing.WorkflowReplayer; import org.junit.jupiter.api.Test; -public class CheckConnectionWorkflowTest { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class CheckConnectionWorkflowTest { @Test - public void replayOldWorkflow() throws Exception { + void replayOldWorkflow() throws Exception { // This test ensures that a new version of the workflow doesn't break an in-progress execution // This JSON file is exported from Temporal directly (e.g. // `http://${temporal-ui}/namespaces/default/workflows/${uuid}/${uuid}/history`) and export diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/ConnectionManagerWorkflowTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/ConnectionManagerWorkflowTest.java index f83e797c11cb..f63b2d275680 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/ConnectionManagerWorkflowTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/ConnectionManagerWorkflowTest.java @@ -86,7 +86,7 @@ * repeated cases, just in case there's a regression where a race condition is added back to a test. */ @Slf4j -public class ConnectionManagerWorkflowTest { +class ConnectionManagerWorkflowTest { private static final long JOB_ID = 1L; private static final int ATTEMPT_ID = 1; @@ -113,7 +113,7 @@ public class ConnectionManagerWorkflowTest { private WorkflowClient client; private ConnectionManagerWorkflow workflow; - public static Stream getMaxAttemptForResetRetry() { + static Stream getMaxAttemptForResetRetry() { return Stream.of( Arguments.of(3), // "The max attempt is 3, it will test that after a failed reset attempt the next attempt will also // be a @@ -124,7 +124,7 @@ public static Stream getMaxAttemptForResetRetry() { } @BeforeEach - public void setUp() { + void setUp() { Mockito.reset(mConfigFetchActivity); Mockito.reset(mCheckConnectionActivity); Mockito.reset(mConnectionDeletionActivity); @@ -162,7 +162,7 @@ public void setUp() { } @AfterEach - public void tearDown() { + void tearDown() { testEnv.shutdown(); TestStateListener.reset(); } @@ -182,7 +182,7 @@ private void mockResetJobInput() { class AsynchronousWorkflow { @BeforeEach - public void setup() { + void setup() { setupSpecificChildWorkflow(EmptySyncWorkflow.class); } @@ -190,7 +190,7 @@ public void setup() { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that a successful workflow retries and waits") - public void runSuccess() throws InterruptedException { + void runSuccess() throws InterruptedException { Mockito.when(mConfigFetchActivity.getTimeToWait(Mockito.any())) .thenReturn(new ScheduleRetrieverOutput(SCHEDULE_WAIT)); @@ -233,7 +233,7 @@ public void runSuccess() throws InterruptedException { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test workflow does not wait to run after a failure") - public void retryAfterFail() throws InterruptedException { + void retryAfterFail() throws InterruptedException { Mockito.when(mConfigFetchActivity.getTimeToWait(Mockito.any())) .thenReturn(new ScheduleRetrieverOutput(SCHEDULE_WAIT)); @@ -274,7 +274,7 @@ public void retryAfterFail() throws InterruptedException { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test workflow which receives a manual run signal stops waiting") - public void manualRun() throws InterruptedException { + void manualRun() throws InterruptedException { final UUID testId = UUID.randomUUID(); final TestStateListener testStateListener = new TestStateListener(); @@ -322,7 +322,7 @@ public void manualRun() throws InterruptedException { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test workflow which receives an update signal stops waiting, doesn't run, and doesn't update the job status") - public void updatedSignalReceived() throws InterruptedException { + void updatedSignalReceived() throws InterruptedException { final UUID testId = UUID.randomUUID(); final TestStateListener testStateListener = new TestStateListener(); @@ -370,7 +370,7 @@ public void updatedSignalReceived() throws InterruptedException { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that cancelling a non-running workflow doesn't do anything") - public void cancelNonRunning() throws InterruptedException { + void cancelNonRunning() throws InterruptedException { final UUID testId = UUID.randomUUID(); final TestStateListener testStateListener = new TestStateListener(); @@ -413,7 +413,7 @@ public void cancelNonRunning() throws InterruptedException { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that the sync is properly deleted") - public void deleteSync() throws InterruptedException { + void deleteSync() throws InterruptedException { final UUID testId = UUID.randomUUID(); final TestStateListener testStateListener = new TestStateListener(); @@ -462,7 +462,7 @@ public void deleteSync() throws InterruptedException { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that fresh workflow cleans the job state") - public void testStartFromCleanJobState() throws InterruptedException { + void testStartFromCleanJobState() throws InterruptedException { final ConnectionUpdaterInput input = ConnectionUpdaterInput.builder() .connectionId(UUID.randomUUID()) .jobId(null) @@ -485,7 +485,7 @@ public void testStartFromCleanJobState() throws InterruptedException { class SynchronousWorkflow { @BeforeEach - public void setup() { + void setup() { setupSpecificChildWorkflow(SleepingSyncWorkflow.class); } @@ -493,7 +493,7 @@ public void setup() { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test workflow which receives a manual sync while running a scheduled sync does nothing") - public void manualRun() throws InterruptedException { + void manualRun() throws InterruptedException { Mockito.when(mConfigFetchActivity.getTimeToWait(Mockito.any())) .thenReturn(new ScheduleRetrieverOutput(SCHEDULE_WAIT)); @@ -533,7 +533,7 @@ public void manualRun() throws InterruptedException { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that cancelling a running workflow cancels the sync") - public void cancelRunning() throws InterruptedException { + void cancelRunning() throws InterruptedException { final UUID testId = UUID.randomUUID(); final TestStateListener testStateListener = new TestStateListener(); @@ -582,7 +582,7 @@ public void cancelRunning() throws InterruptedException { @Timeout(value = 40, unit = TimeUnit.SECONDS) @DisplayName("Test that deleting a running workflow cancels the sync") - public void deleteRunning() throws InterruptedException { + void deleteRunning() throws InterruptedException { final UUID testId = UUID.randomUUID(); final TestStateListener testStateListener = new TestStateListener(); @@ -636,7 +636,7 @@ public void deleteRunning() throws InterruptedException { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that resetting a non-running workflow starts a reset job") - public void resetStart() throws InterruptedException { + void resetStart() throws InterruptedException { final UUID testId = UUID.randomUUID(); final TestStateListener testStateListener = new TestStateListener(); @@ -668,7 +668,7 @@ public void resetStart() throws InterruptedException { @Timeout(value = 60, unit = TimeUnit.SECONDS) @DisplayName("Test that resetting a running workflow cancels the running workflow") - public void resetCancelRunningWorkflow() throws InterruptedException { + void resetCancelRunningWorkflow() throws InterruptedException { final UUID testId = UUID.randomUUID(); final TestStateListener testStateListener = new TestStateListener(); @@ -712,7 +712,7 @@ public void resetCancelRunningWorkflow() throws InterruptedException { @Timeout(value = 60, unit = TimeUnit.SECONDS) @DisplayName("Test that cancelling a reset deletes streamsToReset from stream_resets table") - public void cancelResetRemovesStreamsToReset() throws InterruptedException { + void cancelResetRemovesStreamsToReset() throws InterruptedException { final UUID connectionId = UUID.randomUUID(); final UUID testId = UUID.randomUUID(); final TestStateListener testStateListener = new TestStateListener(); @@ -739,7 +739,7 @@ public void cancelResetRemovesStreamsToReset() throws InterruptedException { @Test @DisplayName("Test that running workflow which receives an update signal waits for the current run and reports the job status") - public void updatedSignalReceivedWhileRunning() throws InterruptedException { + void updatedSignalReceivedWhileRunning() throws InterruptedException { final UUID testId = UUID.randomUUID(); final TestStateListener testStateListener = new TestStateListener(); @@ -801,7 +801,7 @@ class AutoDisableConnection { private static final int ATTEMPT_ID = 222; @BeforeEach - public void setup() { + void setup() { testEnv = TestWorkflowEnvironment.newInstance(); final Worker managerWorker = testEnv.newWorker(TemporalJobType.CONNECTION_UPDATER.name()); @@ -820,7 +820,7 @@ public void setup() { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that auto disable activity is touched during failure") - public void testAutoDisableOnFailure() throws InterruptedException { + void testAutoDisableOnFailure() throws InterruptedException { final Worker syncWorker = testEnv.newWorker(TemporalJobType.SYNC.name()); syncWorker.registerWorkflowImplementationTypes(SourceAndDestinationFailureSyncWorkflow.class); @@ -857,7 +857,7 @@ public void testAutoDisableOnFailure() throws InterruptedException { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that auto disable activity is not touched during job success") - public void testNoAutoDisableOnSuccess() throws InterruptedException { + void testNoAutoDisableOnSuccess() throws InterruptedException { final Worker syncWorker = testEnv.newWorker(TemporalJobType.SYNC.name()); syncWorker.registerWorkflowImplementationTypes(EmptySyncWorkflow.class); @@ -896,7 +896,7 @@ class SyncWorkflowReplicationFailuresRecorded { private static final int ATTEMPT_ID = 222; @BeforeEach - public void setup() { + void setup() { testEnv = TestWorkflowEnvironment.newInstance(); final Worker managerWorker = testEnv.newWorker(TemporalJobType.CONNECTION_UPDATER.name()); @@ -915,7 +915,7 @@ public void setup() { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that Source CHECK failures are recorded") - public void testSourceCheckFailuresRecorded() throws InterruptedException { + void testSourceCheckFailuresRecorded() throws InterruptedException { Mockito.when(mJobCreationAndStatusUpdateActivity.createNewJob(Mockito.any())) .thenReturn(new JobCreationOutput(JOB_ID)); Mockito.when(mJobCreationAndStatusUpdateActivity.createNewAttemptNumber(Mockito.any())) @@ -954,7 +954,7 @@ public void testSourceCheckFailuresRecorded() throws InterruptedException { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that Source CHECK failure reasons are recorded") - public void testSourceCheckFailureReasonsRecorded() throws InterruptedException { + void testSourceCheckFailureReasonsRecorded() throws InterruptedException { Mockito.when(mJobCreationAndStatusUpdateActivity.createNewJob(Mockito.any())) .thenReturn(new JobCreationOutput(JOB_ID)); Mockito.when(mJobCreationAndStatusUpdateActivity.createNewAttemptNumber(Mockito.any())) @@ -993,7 +993,7 @@ public void testSourceCheckFailureReasonsRecorded() throws InterruptedException @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that Destination CHECK failures are recorded") - public void testDestinationCheckFailuresRecorded() throws InterruptedException { + void testDestinationCheckFailuresRecorded() throws InterruptedException { Mockito.when(mJobCreationAndStatusUpdateActivity.createNewJob(Mockito.any())) .thenReturn(new JobCreationOutput(JOB_ID)); Mockito.when(mJobCreationAndStatusUpdateActivity.createNewAttemptNumber(Mockito.any())) @@ -1037,7 +1037,7 @@ public void testDestinationCheckFailuresRecorded() throws InterruptedException { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that Destination CHECK failure reasons are recorded") - public void testDestinationCheckFailureReasonsRecorded() throws InterruptedException { + void testDestinationCheckFailureReasonsRecorded() throws InterruptedException { Mockito.when(mJobCreationAndStatusUpdateActivity.createNewJob(Mockito.any())) .thenReturn(new JobCreationOutput(JOB_ID)); Mockito.when(mJobCreationAndStatusUpdateActivity.createNewAttemptNumber(Mockito.any())) @@ -1081,7 +1081,7 @@ public void testDestinationCheckFailureReasonsRecorded() throws InterruptedExcep @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that reset workflows do not CHECK the source") - public void testSourceCheckSkippedWhenReset() throws InterruptedException { + void testSourceCheckSkippedWhenReset() throws InterruptedException { Mockito.when(mJobCreationAndStatusUpdateActivity.createNewJob(Mockito.any())) .thenReturn(new JobCreationOutput(JOB_ID)); Mockito.when(mJobCreationAndStatusUpdateActivity.createNewAttemptNumber(Mockito.any())) @@ -1122,7 +1122,7 @@ public void testSourceCheckSkippedWhenReset() throws InterruptedException { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that source and destination failures are recorded") - public void testSourceAndDestinationFailuresRecorded() throws InterruptedException { + void testSourceAndDestinationFailuresRecorded() throws InterruptedException { final Worker syncWorker = testEnv.newWorker(TemporalJobType.SYNC.name()); syncWorker.registerWorkflowImplementationTypes(SourceAndDestinationFailureSyncWorkflow.class); @@ -1158,7 +1158,7 @@ public void testSourceAndDestinationFailuresRecorded() throws InterruptedExcepti @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that normalization failure is recorded") - public void testNormalizationFailure() throws InterruptedException { + void testNormalizationFailure() throws InterruptedException { final Worker syncWorker = testEnv.newWorker(TemporalJobType.SYNC.name()); syncWorker.registerWorkflowImplementationTypes(NormalizationFailureSyncWorkflow.class); @@ -1192,7 +1192,7 @@ public void testNormalizationFailure() throws InterruptedException { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that dbt failure is recorded") - public void testDbtFailureRecorded() throws InterruptedException { + void testDbtFailureRecorded() throws InterruptedException { final Worker syncWorker = testEnv.newWorker(TemporalJobType.SYNC.name()); syncWorker.registerWorkflowImplementationTypes(DbtFailureSyncWorkflow.class); @@ -1226,7 +1226,7 @@ public void testDbtFailureRecorded() throws InterruptedException { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that persistence failure is recorded") - public void testPersistenceFailureRecorded() throws InterruptedException { + void testPersistenceFailureRecorded() throws InterruptedException { final Worker syncWorker = testEnv.newWorker(TemporalJobType.SYNC.name()); syncWorker.registerWorkflowImplementationTypes(PersistFailureSyncWorkflow.class); @@ -1260,7 +1260,7 @@ public void testPersistenceFailureRecorded() throws InterruptedException { @Timeout(value = 10, unit = TimeUnit.SECONDS) @DisplayName("Test that replication worker failure is recorded") - public void testReplicationFailureRecorded() throws InterruptedException { + void testReplicationFailureRecorded() throws InterruptedException { final Worker syncWorker = testEnv.newWorker(TemporalJobType.SYNC.name()); syncWorker.registerWorkflowImplementationTypes(ReplicateFailureSyncWorkflow.class); @@ -1297,11 +1297,11 @@ public void testReplicationFailureRecorded() throws InterruptedException { class FailedActivityWorkflow { @BeforeEach - public void setup() { + void setup() { setupSpecificChildWorkflow(SleepingSyncWorkflow.class); } - public static Stream getSetupFailingActivity() { + static Stream getSetupFailingActivity() { return Stream.of( Arguments.of(new Thread(() -> Mockito.when(mJobCreationAndStatusUpdateActivity.createNewJob(Mockito.any())) .thenThrow(ApplicationFailure.newNonRetryableFailure("", "")))), @@ -1392,7 +1392,7 @@ private class HasFailureFromOrigin implements ArgumentMatcher jobs = new ArrayList<>(Collections.nCopies(MAX_FAILURE_JOBS_IN_A_ROW / 2, FAILED_JOB)); jobs.add(SUCCEEDED_JOB); @@ -113,7 +113,7 @@ public void testWarningNotificationsForAutoDisablingMaxNumFailures() throws IOEx @Test @DisplayName("Test that a notification warning is sent after only failed jobs in last `MAX_DAYS_OF_STRAIGHT_FAILURE / 2` days") - public void testWarningNotificationsForAutoDisablingMaxDaysOfFailure() throws IOException { + void testWarningNotificationsForAutoDisablingMaxDaysOfFailure() throws IOException { Mockito.when(mConfigs.getMaxDaysOfOnlyFailedJobsBeforeConnectionDisable()).thenReturn(MAX_DAYS_OF_ONLY_FAILED_JOBS); Mockito.when(mJobPersistence.listJobStatusAndTimestampWithConnection(CONNECTION_ID, REPLICATION_TYPES, CURR_INSTANT.minus(MAX_DAYS_OF_ONLY_FAILED_JOBS, ChronoUnit.DAYS))) @@ -132,7 +132,7 @@ public void testWarningNotificationsForAutoDisablingMaxDaysOfFailure() throws IO @Test @DisplayName("Test that a notification warning is not sent after one was just sent for failing multiple days") - public void testWarningNotificationsDoesNotSpam() throws IOException { + void testWarningNotificationsDoesNotSpam() throws IOException { final List jobs = new ArrayList<>(Collections.nCopies(2, FAILED_JOB)); final long mJobCreateOrUpdatedInSeconds = CURR_INSTANT.getEpochSecond() - TimeUnit.DAYS.toSeconds(MAX_DAYS_OF_ONLY_FAILED_JOBS_BEFORE_WARNING); @@ -153,7 +153,7 @@ public void testWarningNotificationsDoesNotSpam() throws IOException { @Test @DisplayName("Test that a notification warning is not sent after one was just sent for consecutive failures") - public void testWarningNotificationsDoesNotSpamAfterConsecutiveFailures() throws IOException { + void testWarningNotificationsDoesNotSpamAfterConsecutiveFailures() throws IOException { final List jobs = new ArrayList<>(Collections.nCopies(MAX_FAILURE_JOBS_IN_A_ROW - 1, FAILED_JOB)); final long mJobCreateOrUpdatedInSeconds = CURR_INSTANT.getEpochSecond() - TimeUnit.DAYS.toSeconds(MAX_DAYS_OF_ONLY_FAILED_JOBS_BEFORE_WARNING); @@ -174,7 +174,7 @@ public void testWarningNotificationsDoesNotSpamAfterConsecutiveFailures() throws @Test @DisplayName("Test that the connection is _not_ disabled and no warning is sent after only failed jobs and oldest job is less than `MAX_DAYS_OF_STRAIGHT_FAILURE / 2 `days old") - public void testOnlyFailuresButFirstJobYoungerThanMaxDaysWarning() throws IOException { + void testOnlyFailuresButFirstJobYoungerThanMaxDaysWarning() throws IOException { Mockito.when(mConfigs.getMaxDaysOfOnlyFailedJobsBeforeConnectionDisable()).thenReturn(MAX_DAYS_OF_ONLY_FAILED_JOBS); Mockito.when(mJobPersistence.listJobStatusAndTimestampWithConnection(CONNECTION_ID, REPLICATION_TYPES, CURR_INSTANT.minus(MAX_DAYS_OF_ONLY_FAILED_JOBS, ChronoUnit.DAYS))) @@ -194,7 +194,7 @@ public void testOnlyFailuresButFirstJobYoungerThanMaxDaysWarning() throws IOExce @Test @DisplayName("Test that the connection is disabled after MAX_FAILURE_JOBS_IN_A_ROW straight failures") - public void testMaxFailuresInARow() throws IOException, JsonValidationException, ConfigNotFoundException { + void testMaxFailuresInARow() throws IOException, JsonValidationException, ConfigNotFoundException { // from most recent to least recent: MAX_FAILURE_JOBS_IN_A_ROW and 1 success final List jobs = new ArrayList<>(Collections.nCopies(MAX_FAILURE_JOBS_IN_A_ROW, FAILED_JOB)); jobs.add(SUCCEEDED_JOB); @@ -213,7 +213,7 @@ public void testMaxFailuresInARow() throws IOException, JsonValidationException, @Test @DisplayName("Test that the connection is _not_ disabled after MAX_FAILURE_JOBS_IN_A_ROW - 1 straight failures") - public void testLessThanMaxFailuresInARow() throws IOException { + void testLessThanMaxFailuresInARow() throws IOException { // from most recent to least recent: MAX_FAILURE_JOBS_IN_A_ROW-1 and 1 success final List jobs = new ArrayList<>(Collections.nCopies(MAX_FAILURE_JOBS_IN_A_ROW - 1, FAILED_JOB)); jobs.add(SUCCEEDED_JOB); @@ -235,7 +235,7 @@ public void testLessThanMaxFailuresInARow() throws IOException { @Test @DisplayName("Test that the connection is _not_ disabled after 0 jobs in last MAX_DAYS_OF_STRAIGHT_FAILURE days") - public void testNoRuns() throws IOException { + void testNoRuns() throws IOException { Mockito.when(mJobPersistence.listJobStatusAndTimestampWithConnection(CONNECTION_ID, REPLICATION_TYPES, CURR_INSTANT.minus(MAX_DAYS_OF_ONLY_FAILED_JOBS, ChronoUnit.DAYS))).thenReturn(Collections.emptyList()); @@ -249,7 +249,7 @@ public void testNoRuns() throws IOException { @Test @DisplayName("Test that the connection is disabled after only failed jobs in last MAX_DAYS_OF_STRAIGHT_FAILURE days") - public void testOnlyFailuresInMaxDays() throws IOException, JsonValidationException, ConfigNotFoundException { + void testOnlyFailuresInMaxDays() throws IOException, JsonValidationException, ConfigNotFoundException { Mockito.when(mConfigs.getMaxDaysOfOnlyFailedJobsBeforeConnectionDisable()).thenReturn(MAX_DAYS_OF_ONLY_FAILED_JOBS); Mockito.when(mJobPersistence.listJobStatusAndTimestampWithConnection(CONNECTION_ID, REPLICATION_TYPES, CURR_INSTANT.minus(MAX_DAYS_OF_ONLY_FAILED_JOBS, ChronoUnit.DAYS))) @@ -270,7 +270,7 @@ public void testOnlyFailuresInMaxDays() throws IOException, JsonValidationExcept @Test @DisplayName("Test that the connection is _not_ disabled after only cancelled jobs") - public void testIgnoreOnlyCancelledRuns() throws IOException { + void testIgnoreOnlyCancelledRuns() throws IOException { Mockito.when(mJobPersistence.listJobStatusAndTimestampWithConnection(CONNECTION_ID, REPLICATION_TYPES, CURR_INSTANT.minus(MAX_DAYS_OF_ONLY_FAILED_JOBS, ChronoUnit.DAYS))) .thenReturn(Collections.singletonList(CANCELLED_JOB)); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/ConfigFetchActivityTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/ConfigFetchActivityTest.java index 9fe9c525b00a..c76a480aa496 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/ConfigFetchActivityTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/ConfigFetchActivityTest.java @@ -34,7 +34,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class ConfigFetchActivityTest { +class ConfigFetchActivityTest { @Mock private ConfigRepository mConfigRepository; @@ -94,8 +94,8 @@ public class ConfigFetchActivityTest { class TimeToWaitTest { @Test - @DisplayName("Test that the job gets scheduled if it is not manual and if it is the first run with legacy schedule schema") - public void testFirstJobNonManual() throws IOException, JsonValidationException, ConfigNotFoundException { + @DisplayName("Test that the job get scheduled if it is not manual and if it is the first run") + void testFirstJobNonManual() throws IOException, JsonValidationException, ConfigNotFoundException { configFetchActivity = new ConfigFetchActivityImpl(mConfigRepository, mJobPersistence, mConfigs, () -> Instant.now().getEpochSecond()); Mockito.when(mJobPersistence.getLastReplicationJob(connectionId)) .thenReturn(Optional.empty()); @@ -112,8 +112,8 @@ public void testFirstJobNonManual() throws IOException, JsonValidationException, } @Test - @DisplayName("Test that the job will wait for a long time if it is manual in the legacy schedule schema") - public void testManual() throws IOException, JsonValidationException, ConfigNotFoundException { + @DisplayName("Test that the job will wait for a long time if it is manual") + void testManual() throws IOException, JsonValidationException, ConfigNotFoundException { configFetchActivity = new ConfigFetchActivityImpl(mConfigRepository, mJobPersistence, mConfigs, () -> Instant.now().getEpochSecond()); Mockito.when(mConfigRepository.getStandardSync(connectionId)) @@ -129,7 +129,7 @@ public void testManual() throws IOException, JsonValidationException, ConfigNotF @Test @DisplayName("Test that the job will wait for a long time if it is disabled") - public void testDisable() throws IOException, JsonValidationException, ConfigNotFoundException { + void testDisable() throws IOException, JsonValidationException, ConfigNotFoundException { configFetchActivity = new ConfigFetchActivityImpl(mConfigRepository, mJobPersistence, mConfigs, () -> Instant.now().getEpochSecond()); Mockito.when(mConfigRepository.getStandardSync(connectionId)) @@ -145,7 +145,7 @@ public void testDisable() throws IOException, JsonValidationException, ConfigNot @Test @DisplayName("Test that the connection will wait for a long time if it is deleted") - public void testDeleted() throws IOException, JsonValidationException, ConfigNotFoundException { + void testDeleted() throws IOException, JsonValidationException, ConfigNotFoundException { configFetchActivity = new ConfigFetchActivityImpl(mConfigRepository, mJobPersistence, mConfigs, () -> Instant.now().getEpochSecond()); Mockito.when(mConfigRepository.getStandardSync(connectionId)) @@ -160,8 +160,8 @@ public void testDeleted() throws IOException, JsonValidationException, ConfigNot } @Test - @DisplayName("Test we will wait the required amount of time with legacy config") - public void testWait() throws IOException, JsonValidationException, ConfigNotFoundException { + @DisplayName("Test we will wait the required amount of time") + void testWait() throws IOException, JsonValidationException, ConfigNotFoundException { configFetchActivity = new ConfigFetchActivityImpl(mConfigRepository, mJobPersistence, mConfigs, () -> 60L * 3); Mockito.when(mJob.getStartedAtInSecond()) @@ -182,8 +182,8 @@ public void testWait() throws IOException, JsonValidationException, ConfigNotFou } @Test - @DisplayName("Test we will not wait if we are late in the legacy schedule schema") - public void testNotWaitIfLate() throws IOException, JsonValidationException, ConfigNotFoundException { + @DisplayName("Test we will not wait if we are late") + void testNotWaitIfLate() throws IOException, JsonValidationException, ConfigNotFoundException { configFetchActivity = new ConfigFetchActivityImpl(mConfigRepository, mJobPersistence, mConfigs, () -> 60L * 10); Mockito.when(mJob.getStartedAtInSecond()) diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/ConnectionDeletionActivityTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/ConnectionDeletionActivityTest.java index 8c9c318b97a4..b38f5bd1157d 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/ConnectionDeletionActivityTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/ConnectionDeletionActivityTest.java @@ -21,7 +21,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class ConnectionDeletionActivityTest { +class ConnectionDeletionActivityTest { @Mock private ConnectionHelper mConnectionHelper; @@ -33,7 +33,7 @@ public class ConnectionDeletionActivityTest { @Test @DisplayName("Test that the proper helper method is called") - public void testSuccess() throws JsonValidationException, ConfigNotFoundException, IOException { + void testSuccess() throws JsonValidationException, ConfigNotFoundException, IOException { connectionDeletionActivity.deleteConnection(input); Mockito.verify(mConnectionHelper).deleteConnection(input.getConnectionId()); @@ -41,7 +41,7 @@ public void testSuccess() throws JsonValidationException, ConfigNotFoundExceptio @Test @DisplayName("Test that exception are properly wrapped") - public void testWrapException() throws JsonValidationException, ConfigNotFoundException, IOException { + void testWrapException() throws JsonValidationException, ConfigNotFoundException, IOException { Mockito.doThrow(new JsonValidationException(""), new ConfigNotFoundException("", ""), new IOException()) .when(mConnectionHelper).deleteConnection(input.getConnectionId()); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/JobCreationAndStatusUpdateActivityTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/JobCreationAndStatusUpdateActivityTest.java index f0952255bf8d..e5fc9408b7c8 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/JobCreationAndStatusUpdateActivityTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/JobCreationAndStatusUpdateActivityTest.java @@ -72,7 +72,8 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class JobCreationAndStatusUpdateActivityTest { +@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") +class JobCreationAndStatusUpdateActivityTest { @Mock private SyncJobFactory mJobFactory; @@ -141,7 +142,7 @@ class Creation { @Test @DisplayName("Test job creation") - public void createJob() throws JsonValidationException, ConfigNotFoundException, IOException { + void createJob() throws JsonValidationException, ConfigNotFoundException, IOException { Mockito.when(mJobFactory.create(CONNECTION_ID)) .thenReturn(JOB_ID); Mockito.when(mConfigRepository.getStandardSync(CONNECTION_ID)) @@ -154,7 +155,7 @@ public void createJob() throws JsonValidationException, ConfigNotFoundException, @Test @DisplayName("Test reset job creation") - public void createResetJob() throws JsonValidationException, ConfigNotFoundException, IOException { + void createResetJob() throws JsonValidationException, ConfigNotFoundException, IOException { final StandardSync standardSync = new StandardSync().withDestinationId(DESTINATION_ID); Mockito.when(mConfigRepository.getStandardSync(CONNECTION_ID)).thenReturn(standardSync); final DestinationConnection destination = new DestinationConnection().withDestinationDefinitionId(DESTINATION_DEFINITION_ID); @@ -176,7 +177,7 @@ public void createResetJob() throws JsonValidationException, ConfigNotFoundExcep @Test @DisplayName("Test attempt creation") - public void createAttempt() throws IOException { + void createAttempt() throws IOException { final Job mJob = Mockito.mock(Job.class); Mockito.when(mJobPersistence.getJob(JOB_ID)) @@ -212,7 +213,7 @@ public void createAttempt() throws IOException { @Test @DisplayName("Test exception errors are properly wrapped") - public void createAttemptThrowException() throws IOException { + void createAttemptThrowException() throws IOException { Mockito.when(mJobPersistence.getJob(JOB_ID)) .thenThrow(new IOException()); @@ -224,7 +225,7 @@ public void createAttemptThrowException() throws IOException { @Test @DisplayName("Test attempt creation") - public void createAttemptNumber() throws IOException { + void createAttemptNumber() throws IOException { final Job mJob = Mockito.mock(Job.class); Mockito.when(mJobPersistence.getJob(JOB_ID)) @@ -260,7 +261,7 @@ public void createAttemptNumber() throws IOException { @Test @DisplayName("Test exception errors are properly wrapped") - public void createAttemptNumberThrowException() throws IOException { + void createAttemptNumberThrowException() throws IOException { Mockito.when(mJobPersistence.getJob(JOB_ID)) .thenThrow(new IOException()); @@ -276,7 +277,7 @@ public void createAttemptNumberThrowException() throws IOException { class Update { @Test - public void setJobSuccess() throws IOException { + void setJobSuccess() throws IOException { jobCreationAndStatusUpdateActivity.jobSuccess(new JobSuccessInput(JOB_ID, ATTEMPT_ID, standardSyncOutput)); Mockito.verify(mJobPersistence).writeOutput(JOB_ID, ATTEMPT_ID, jobOutput); @@ -286,7 +287,7 @@ public void setJobSuccess() throws IOException { } @Test - public void setJobSuccessWrapException() throws IOException { + void setJobSuccessWrapException() throws IOException { Mockito.doThrow(new IOException()) .when(mJobPersistence).succeedAttempt(JOB_ID, ATTEMPT_ID); @@ -296,7 +297,7 @@ public void setJobSuccessWrapException() throws IOException { } @Test - public void setJobFailure() throws IOException { + void setJobFailure() throws IOException { final Attempt mAttempt = Mockito.mock(Attempt.class); Mockito.when(mAttempt.getFailureSummary()).thenReturn(Optional.of(failureSummary)); @@ -316,7 +317,7 @@ public void setJobFailure() throws IOException { } @Test - public void setJobFailureWrapException() throws IOException { + void setJobFailureWrapException() throws IOException { Mockito.doThrow(new IOException()) .when(mJobPersistence).failJob(JOB_ID); @@ -326,7 +327,7 @@ public void setJobFailureWrapException() throws IOException { } @Test - public void setAttemptFailure() throws IOException { + void setAttemptFailure() throws IOException { jobCreationAndStatusUpdateActivity.attemptFailure(new AttemptFailureInput(JOB_ID, ATTEMPT_ID, standardSyncOutput, failureSummary)); Mockito.verify(mJobPersistence).failAttempt(JOB_ID, ATTEMPT_ID); @@ -335,7 +336,7 @@ public void setAttemptFailure() throws IOException { } @Test - public void setAttemptFailureWrapException() throws IOException { + void setAttemptFailureWrapException() throws IOException { Mockito.doThrow(new IOException()) .when(mJobPersistence).failAttempt(JOB_ID, ATTEMPT_ID); @@ -347,7 +348,7 @@ public void setAttemptFailureWrapException() throws IOException { } @Test - public void setJobCancelled() throws IOException { + void setJobCancelled() throws IOException { jobCreationAndStatusUpdateActivity.jobCancelled(new JobCancelledInput(JOB_ID, ATTEMPT_ID, failureSummary)); // attempt must be failed before job is cancelled, or else job state machine is not respected @@ -358,7 +359,7 @@ public void setJobCancelled() throws IOException { } @Test - public void setJobCancelledWrapException() throws IOException { + void setJobCancelledWrapException() throws IOException { Mockito.doThrow(new IOException()) .when(mJobPersistence).cancelJob(JOB_ID); @@ -368,7 +369,7 @@ public void setJobCancelledWrapException() throws IOException { } @Test - public void ensureCleanJobState() throws IOException { + void ensureCleanJobState() throws IOException { final Attempt failedAttempt = new Attempt(0, 1, Path.of(""), null, AttemptStatus.FAILED, null, 2L, 3L, 3L); final int runningAttemptNumber = 1; final Attempt runningAttempt = new Attempt(runningAttemptNumber, 1, Path.of(""), null, AttemptStatus.RUNNING, null, 4L, 5L, null); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/StreamResetActivityTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/StreamResetActivityTest.java index 51cf07424431..cd7f41d18ebf 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/StreamResetActivityTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/scheduling/activities/StreamResetActivityTest.java @@ -26,7 +26,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class StreamResetActivityTest { +class StreamResetActivityTest { @Mock private StreamResetPersistence streamResetPersistence; @@ -38,7 +38,7 @@ public class StreamResetActivityTest { private final DeleteStreamResetRecordsForJobInput noJobIdInput = new DeleteStreamResetRecordsForJobInput(UUID.randomUUID(), null); @Test - public void testDeleteStreamResetRecordsForJob() throws IOException { + void testDeleteStreamResetRecordsForJob() throws IOException { final Job jobMock = mock(Job.class, RETURNS_DEEP_STUBS); when(jobPersistence.getJob(input.getJobId())).thenReturn(jobMock); @@ -50,7 +50,7 @@ public void testDeleteStreamResetRecordsForJob() throws IOException { } @Test - public void testIncorrectConfigType() throws IOException { + void testIncorrectConfigType() throws IOException { final Job jobMock = mock(Job.class, RETURNS_DEEP_STUBS); when(jobPersistence.getJob(input.getJobId())).thenReturn(jobMock); @@ -60,7 +60,7 @@ public void testIncorrectConfigType() throws IOException { } @Test - public void testNoJobId() throws IOException { + void testNoJobId() throws IOException { streamResetActivity.deleteStreamResetRecordsForJob(noJobIdInput); Mockito.verify(jobPersistence, never()).getJob(Mockito.anyLong()); Mockito.verify(streamResetPersistence, never()).deleteStreamResets(Mockito.any(UUID.class), Mockito.anyList()); diff --git a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/sync/PersistStateActivityTest.java b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/sync/PersistStateActivityTest.java index b7c9c0c329c3..0d44e26d9c4e 100644 --- a/airbyte-workers/src/test/java/io/airbyte/workers/temporal/sync/PersistStateActivityTest.java +++ b/airbyte-workers/src/test/java/io/airbyte/workers/temporal/sync/PersistStateActivityTest.java @@ -35,7 +35,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class PersistStateActivityTest { +class PersistStateActivityTest { private final static UUID CONNECTION_ID = UUID.randomUUID(); @@ -49,14 +49,14 @@ public class PersistStateActivityTest { PersistStateActivityImpl persistStateActivity; @Test - public void testPersistEmpty() { + void testPersistEmpty() { persistStateActivity.persist(CONNECTION_ID, new StandardSyncOutput(), new ConfiguredAirbyteCatalog()); Mockito.verifyNoInteractions(statePersistence); } @Test - public void testPersist() throws IOException { + void testPersist() throws IOException { Mockito.when(featureFlags.useStreamCapableState()).thenReturn(true); final JsonNode jsonState = Jsons.jsonNode(Map.ofEntries( @@ -75,7 +75,7 @@ public void testPersist() throws IOException { // This test is to ensure that we correctly throw an error if not every stream in the configured // catalog has a state message when migrating from Legacy to Per-Stream @Test - public void testPersistWithInvalidStateDuringMigration() throws IOException { + void testPersistWithInvalidStateDuringMigration() throws IOException { final ConfiguredAirbyteStream stream = new ConfiguredAirbyteStream().withStream(new AirbyteStream().withName("a").withNamespace("a1")); final ConfiguredAirbyteStream stream2 = new ConfiguredAirbyteStream().withStream(new AirbyteStream().withName("b")); @@ -95,7 +95,7 @@ public void testPersistWithInvalidStateDuringMigration() throws IOException { } @Test - public void testPersistWithValidStateDuringMigration() throws IOException { + void testPersistWithValidStateDuringMigration() throws IOException { final ConfiguredAirbyteStream stream = new ConfiguredAirbyteStream().withStream(new AirbyteStream().withName("a").withNamespace("a1")); final ConfiguredAirbyteStream stream2 = new ConfiguredAirbyteStream().withStream(new AirbyteStream().withName("b")); @@ -121,7 +121,7 @@ public void testPersistWithValidStateDuringMigration() throws IOException { // Global stream states do not need to be validated during the migration to per-stream state @Test - public void testPersistWithGlobalStateDuringMigration() throws IOException { + void testPersistWithGlobalStateDuringMigration() throws IOException { final ConfiguredAirbyteStream stream = new ConfiguredAirbyteStream().withStream(new AirbyteStream().withName("a").withNamespace("a1")); final ConfiguredAirbyteStream stream2 = new ConfiguredAirbyteStream().withStream(new AirbyteStream().withName("b")); diff --git a/tools/gradle/pmd/rules.xml b/tools/gradle/pmd/rules.xml index c1561d3f8a56..5bb16f9750c8 100644 --- a/tools/gradle/pmd/rules.xml +++ b/tools/gradle/pmd/rules.xml @@ -9,6 +9,7 @@ .*/generated/.* .*/airbyte-integrations/.* + .*/test-integration/.* @@ -16,21 +17,8 @@ - - - - - - - - - - - - -