diff --git a/src/test/java/io/aiven/connect/jdbc/JdbcSourceConnectorTest.java b/src/test/java/io/aiven/connect/jdbc/JdbcSourceConnectorTest.java index 905960fe..1cec67f5 100644 --- a/src/test/java/io/aiven/connect/jdbc/JdbcSourceConnectorTest.java +++ b/src/test/java/io/aiven/connect/jdbc/JdbcSourceConnectorTest.java @@ -38,7 +38,6 @@ import io.aiven.connect.jdbc.util.TableId; import org.easymock.EasyMock; -import org.easymock.Mock; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -48,9 +47,8 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(PowerMockRunner.class) @PrepareForTest({JdbcSourceConnector.class, DatabaseDialect.class}) @@ -61,9 +59,6 @@ public class JdbcSourceConnectorTest { private EmbeddedDerby db; private Map connProps; - @Mock - private DatabaseDialect dialect; - @Before public void setup() { connector = new JdbcSourceConnector(); @@ -82,27 +77,26 @@ public void tearDown() throws Exception { @Test public void testTaskClass() { - assertEquals(JdbcSourceTask.class, connector.taskClass()); + assertThat(connector.taskClass()).isEqualTo(JdbcSourceTask.class); } - @Test(expected = ConnectException.class) - public void testMissingUrlConfig() throws Exception { + @Test + public void testMissingUrlConfig() { final HashMap connProps = new HashMap<>(); connProps.put(JdbcSourceConnectorConfig.MODE_CONFIG, JdbcSourceConnectorConfig.MODE_BULK); - connector.start(connProps); + assertThatThrownBy(() -> connector.start(connProps)).isInstanceOf(ConnectException.class); } - @Test(expected = ConnectException.class) - public void testMissingModeConfig() throws Exception { - final HashMap connProps = new HashMap<>(); - connProps.put(JdbcConfig.CONNECTION_URL_CONFIG, db.getUrl()); - connector.start(Collections.emptyMap()); + @Test + public void testMissingModeConfig() { + assertThatThrownBy(() -> connector.start(Collections.emptyMap())).isInstanceOf(ConnectException.class); } - @Test(expected = ConnectException.class) - public void testStartConnectionFailure() throws Exception { + @Test + public void testStartConnectionFailure() { // Invalid URL - connector.start(Collections.singletonMap(JdbcConfig.CONNECTION_URL_CONFIG, "jdbc:foo")); + final Map connProps = Collections.singletonMap(JdbcConfig.CONNECTION_URL_CONFIG, "jdbc:foo"); + assertThatThrownBy(() -> connector.start(connProps)).isInstanceOf(ConnectException.class); } @Test @@ -138,15 +132,16 @@ public void testStartStop() throws Exception { @Test public void testPartitioningOneTable() throws Exception { - // Tests simplest case where we have exactly 1 table and also ensures we return fewer tasks + // Tests the simplest case where we have exactly 1 table and also ensures we return fewer tasks // if there aren't enough tables for the max # of tasks db.createTable("test", "id", "INT NOT NULL"); connector.start(connProps); final List> configs = connector.taskConfigs(10); - assertEquals(1, configs.size()); + assertThat(configs).hasSize(1); assertTaskConfigsHaveParentConfigs(configs); - assertEquals(tables("test"), configs.get(0).get(JdbcSourceTaskConfig.TABLES_CONFIG)); - assertNull(configs.get(0).get(JdbcSourceTaskConfig.QUERY_CONFIG)); + assertThat(configs.get(0)) + .containsEntry(JdbcSourceTaskConfig.TABLES_CONFIG, tables("test")) + .doesNotContainKey(JdbcSourceTaskConfig.QUERY_CONFIG); connector.stop(); } @@ -159,15 +154,18 @@ public void testPartitioningManyTables() throws Exception { db.createTable("test4", "id", "INT NOT NULL"); connector.start(connProps); final List> configs = connector.taskConfigs(3); - assertEquals(3, configs.size()); + assertThat(configs).hasSize(3); assertTaskConfigsHaveParentConfigs(configs); - assertEquals(tables("test1", "test2"), configs.get(0).get(JdbcSourceTaskConfig.TABLES_CONFIG)); - assertNull(configs.get(0).get(JdbcSourceTaskConfig.QUERY_CONFIG)); - assertEquals(tables("test3"), configs.get(1).get(JdbcSourceTaskConfig.TABLES_CONFIG)); - assertNull(configs.get(1).get(JdbcSourceTaskConfig.QUERY_CONFIG)); - assertEquals(tables("test4"), configs.get(2).get(JdbcSourceTaskConfig.TABLES_CONFIG)); - assertNull(configs.get(2).get(JdbcSourceTaskConfig.QUERY_CONFIG)); + assertThat(configs.get(0)) + .containsEntry(JdbcSourceTaskConfig.TABLES_CONFIG, tables("test1", "test2")) + .doesNotContainKey(JdbcSourceTaskConfig.QUERY_CONFIG); + assertThat(configs.get(1)) + .containsEntry(JdbcSourceTaskConfig.TABLES_CONFIG, tables("test3")) + .doesNotContainKey(JdbcSourceTaskConfig.QUERY_CONFIG); + assertThat(configs.get(2)) + .containsEntry(JdbcSourceTaskConfig.TABLES_CONFIG, tables("test4")) + .doesNotContainKey(JdbcSourceTaskConfig.QUERY_CONFIG); connector.stop(); } @@ -182,15 +180,18 @@ public void testPartitioningUnqualifiedTables() throws Exception { db.createTable("test4", "id", "INT NOT NULL"); connector.start(connProps); final List> configs = connector.taskConfigs(3); - assertEquals(3, configs.size()); + assertThat(configs).hasSize(3); assertTaskConfigsHaveParentConfigs(configs); - assertEquals(unqualifiedTables("test1", "test2"), configs.get(0).get(JdbcSourceTaskConfig.TABLES_CONFIG)); - assertNull(configs.get(0).get(JdbcSourceTaskConfig.QUERY_CONFIG)); - assertEquals(unqualifiedTables("test3"), configs.get(1).get(JdbcSourceTaskConfig.TABLES_CONFIG)); - assertNull(configs.get(1).get(JdbcSourceTaskConfig.QUERY_CONFIG)); - assertEquals(unqualifiedTables("test4"), configs.get(2).get(JdbcSourceTaskConfig.TABLES_CONFIG)); - assertNull(configs.get(2).get(JdbcSourceTaskConfig.QUERY_CONFIG)); + assertThat(configs.get(0)) + .containsEntry(JdbcSourceTaskConfig.TABLES_CONFIG, unqualifiedTables("test1", "test2")) + .doesNotContainKey(JdbcSourceTaskConfig.QUERY_CONFIG); + assertThat(configs.get(1)) + .containsEntry(JdbcSourceTaskConfig.TABLES_CONFIG, unqualifiedTables("test3")) + .doesNotContainKey(JdbcSourceTaskConfig.QUERY_CONFIG); + assertThat(configs.get(2)) + .containsEntry(JdbcSourceTaskConfig.TABLES_CONFIG, unqualifiedTables("test4")) + .doesNotContainKey(JdbcSourceTaskConfig.QUERY_CONFIG); connector.stop(); } @@ -204,11 +205,12 @@ public void testPartitioningQuery() throws Exception { connProps.put(JdbcSourceConnectorConfig.QUERY_CONFIG, sampleQuery); connector.start(connProps); final List> configs = connector.taskConfigs(3); - assertEquals(1, configs.size()); + assertThat(configs).hasSize(1); assertTaskConfigsHaveParentConfigs(configs); - assertEquals("", configs.get(0).get(JdbcSourceTaskConfig.TABLES_CONFIG)); - assertEquals(sampleQuery, configs.get(0).get(JdbcSourceTaskConfig.QUERY_CONFIG)); + assertThat(configs.get(0)) + .containsEntry(JdbcSourceTaskConfig.TABLES_CONFIG, "") + .containsEntry(JdbcSourceTaskConfig.QUERY_CONFIG, sampleQuery); connector.stop(); } @@ -218,23 +220,22 @@ public void testConflictingQueryTableSettings() { final String sampleQuery = "SELECT foo, bar FROM sample_table"; connProps.put(JdbcSourceConnectorConfig.QUERY_CONFIG, sampleQuery); connProps.put(JdbcSourceConnectorConfig.TABLE_WHITELIST_CONFIG, "foo,bar"); - assertThrows(ConnectException.class, () -> connector.start(connProps)); + assertThatThrownBy(() -> connector.start(connProps)).isInstanceOf(ConnectException.class); connector = new JdbcSourceConnector(); connProps.remove(JdbcSourceConnectorConfig.QUERY_CONFIG); connProps.put(JdbcSourceConnectorConfig.TABLE_NAMES_QUALIFY_CONFIG, "false"); connProps.put(JdbcSourceConnectorConfig.MODE_CONFIG, JdbcSourceConnectorConfig.MODE_INCREMENTING); - assertThrows(ConnectException.class, () -> connector.start(connProps)); + assertThatThrownBy(() -> connector.start(connProps)).isInstanceOf(ConnectException.class); connector = new JdbcSourceConnector(); connProps.put(JdbcSourceConnectorConfig.MODE_CONFIG, JdbcSourceConnectorConfig.MODE_TIMESTAMP_INCREMENTING); - assertThrows(ConnectException.class, () -> connector.start(connProps)); + assertThatThrownBy(() -> connector.start(connProps)).isInstanceOf(ConnectException.class); } private void assertTaskConfigsHaveParentConfigs(final List> configs) { for (final Map config : configs) { - assertEquals(this.db.getUrl(), - config.get(JdbcConfig.CONNECTION_URL_CONFIG)); + assertThat(config).containsEntry(JdbcConfig.CONNECTION_URL_CONFIG, this.db.getUrl()); } } diff --git a/src/test/java/io/aiven/connect/jdbc/dialect/BaseDialectTest.java b/src/test/java/io/aiven/connect/jdbc/dialect/BaseDialectTest.java index e3996cd1..0c6f53a9 100644 --- a/src/test/java/io/aiven/connect/jdbc/dialect/BaseDialectTest.java +++ b/src/test/java/io/aiven/connect/jdbc/dialect/BaseDialectTest.java @@ -63,8 +63,7 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -254,7 +253,7 @@ protected void assertMapping( } final SinkRecordField field = new SinkRecordField(schemaBuilder.build(), schemaName, false); final String sqlType = dialect.getSqlType(field); - assertEquals(expectedSqlType, sqlType); + assertThat(sqlType).isEqualTo(expectedSqlType); } protected void assertMapping( @@ -270,8 +269,9 @@ protected void assertMapping( protected Map propertiesFromPairs(final String... pairs) { final Map props = new HashMap<>(); - assertEquals("Expecting even number of properties but found " + pairs.length, 0, - pairs.length % 2); + assertThat(pairs.length % 2) + .as("Expecting even number of properties but found " + pairs.length) + .isZero(); for (int i = 0; i != pairs.length; ++i) { final String key = pairs[i]; final String value = pairs[++i]; @@ -282,7 +282,7 @@ protected Map propertiesFromPairs(final String... pairs) { protected void assertStatements(final String[] expected, final List actual) { // TODO: Remove - assertEquals(expected.length, actual.size()); + assertThat(actual).hasSameSizeAs(expected); for (int i = 0; i != expected.length; ++i) { assertQueryEquals(expected[i], actual.get(i)); } @@ -302,17 +302,17 @@ protected Collection columns(final TableId id, final String... names) protected void verifyDataTypeMapping(final String expected, final Schema schema) { final SinkRecordField field = new SinkRecordField(schema, schema.name(), schema.isOptional()); - assertEquals(expected, dialect.getSqlType(field)); + assertThat(dialect.getSqlType(field)).isEqualTo(expected); } protected void verifyCreateOneColNoPk(final String expected) { - assertQueryEquals(expected, dialect.buildCreateTableStatement(tableId, Arrays.asList( + assertQueryEquals(expected, dialect.buildCreateTableStatement(tableId, List.of( new SinkRecordField(Schema.INT32_SCHEMA, "col1", false) ))); } protected void verifyCreateOneColOnePk(final String expected) { - assertQueryEquals(expected, dialect.buildCreateTableStatement(tableId, Arrays.asList( + assertQueryEquals(expected, dialect.buildCreateTableStatement(tableId, List.of( new SinkRecordField(Schema.INT32_SCHEMA, "pk1", true) ))); } @@ -326,16 +326,16 @@ protected void verifyCreateThreeColTwoPk(final String expected) { } protected void verifyAlterAddOneCol(final String... expected) { - assertArrayEquals(expected, dialect.buildAlterTable(tableId, Arrays.asList( + assertThat(dialect.buildAlterTable(tableId, List.of( new SinkRecordField(Schema.OPTIONAL_INT32_SCHEMA, "newcol1", false) - )).toArray()); + ))).containsExactly(expected); } protected void verifyAlterAddTwoCols(final String... expected) { - assertArrayEquals(expected, dialect.buildAlterTable(tableId, Arrays.asList( + assertThat(dialect.buildAlterTable(tableId, Arrays.asList( new SinkRecordField(Schema.OPTIONAL_INT32_SCHEMA, "newcol1", false), new SinkRecordField(SchemaBuilder.int32().defaultValue(42).build(), "newcol2", false) - )).toArray()); + ))).containsExactly(expected); } @Test @@ -419,11 +419,11 @@ public void bindFieldMapUnsupported() throws SQLException { } protected void assertSanitizedUrl(final String url, final String expectedSanitizedUrl) { - assertEquals(expectedSanitizedUrl, dialect.sanitizedUrl(url)); + assertThat(dialect.sanitizedUrl(url)).isEqualTo(expectedSanitizedUrl); } protected void assertQueryEquals(final String expected, final String actual) { - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } protected PreparedStatement verifyBindField(final int index, final Schema schema, final Object value) diff --git a/src/test/java/io/aiven/connect/jdbc/dialect/BaseDialectTypeTest.java b/src/test/java/io/aiven/connect/jdbc/dialect/BaseDialectTypeTest.java index 1dce70b1..3fd83cd6 100644 --- a/src/test/java/io/aiven/connect/jdbc/dialect/BaseDialectTypeTest.java +++ b/src/test/java/io/aiven/connect/jdbc/dialect/BaseDialectTypeTest.java @@ -39,7 +39,8 @@ import org.junit.runners.Parameterized; import org.mockito.Mock; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -113,9 +114,9 @@ public void testValueConversionOnNumeric() throws Exception { dialect.addFieldToSchema(columnDefn, schemaBuilder); final Schema schema = schemaBuilder.build(); final List fields = schema.fields(); - assertEquals(1, fields.size()); + assertThat(fields).hasSize(1); final Field field = fields.get(0); - assertEquals(expectedType, field.schema().type()); + assertThat(field.schema().type()).isEqualTo(expectedType); // Set up the ResultSet when(resultSet.getBigDecimal(1, scale)).thenReturn(BIG_DECIMAL); @@ -137,9 +138,10 @@ public void testValueConversionOnNumeric() throws Exception { ); final Object value = converter.convert(resultSet); if (value instanceof Number && expectedValue instanceof Number) { - assertEquals(((Number) expectedValue).floatValue(), ((Number) value).floatValue(), 0.01d); + assertThat(((Number) value).floatValue()) + .isCloseTo(((Number) expectedValue).floatValue(), offset(0.01f)); } else { - assertEquals(expectedValue, value); + assertThat(value).isEqualTo(expectedValue); } } @@ -172,8 +174,8 @@ protected JdbcSourceConnectorConfig sourceConfigWithUrl( protected Map propertiesFromPairs(final String... pairs) { final Map props = new HashMap<>(); - assertEquals("Expecting even number of properties but found " + pairs.length, 0, - pairs.length % 2); + assertThat(pairs.length % 2).as("Expecting even number of properties but found " + pairs.length) + .isZero(); for (int i = 0; i != pairs.length; ++i) { final String key = pairs[i]; final String value = pairs[++i]; diff --git a/src/test/java/io/aiven/connect/jdbc/dialect/DatabaseDialectsTest.java b/src/test/java/io/aiven/connect/jdbc/dialect/DatabaseDialectsTest.java index b9e424b6..9a60bc16 100644 --- a/src/test/java/io/aiven/connect/jdbc/dialect/DatabaseDialectsTest.java +++ b/src/test/java/io/aiven/connect/jdbc/dialect/DatabaseDialectsTest.java @@ -29,7 +29,7 @@ import org.junit.Test; import static junit.framework.TestCase.assertSame; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; public class DatabaseDialectsTest { @@ -37,16 +37,17 @@ public class DatabaseDialectsTest { public void shouldLoadAllBuiltInDialects() { final Collection providers = DatabaseDialects .registeredDialectProviders(); - assertContainsInstanceOf(providers, GenericDatabaseDialect.Provider.class); - assertContainsInstanceOf(providers, DerbyDatabaseDialect.Provider.class); - assertContainsInstanceOf(providers, OracleDatabaseDialect.Provider.class); - assertContainsInstanceOf(providers, SqliteDatabaseDialect.Provider.class); - assertContainsInstanceOf(providers, PostgreSqlDatabaseDialect.Provider.class); - assertContainsInstanceOf(providers, MySqlDatabaseDialect.Provider.class); - assertContainsInstanceOf(providers, SqlServerDatabaseDialect.Provider.class); - assertContainsInstanceOf(providers, SapHanaDatabaseDialect.Provider.class); - assertContainsInstanceOf(providers, VerticaDatabaseDialect.Provider.class); - assertContainsInstanceOf(providers, MockDatabaseDialect.Provider.class); + assertThat(providers) + .hasAtLeastOneElementOfType(GenericDatabaseDialect.Provider.class) + .hasAtLeastOneElementOfType(DerbyDatabaseDialect.Provider.class) + .hasAtLeastOneElementOfType(OracleDatabaseDialect.Provider.class) + .hasAtLeastOneElementOfType(SqliteDatabaseDialect.Provider.class) + .hasAtLeastOneElementOfType(PostgreSqlDatabaseDialect.Provider.class) + .hasAtLeastOneElementOfType(MySqlDatabaseDialect.Provider.class) + .hasAtLeastOneElementOfType(SqlServerDatabaseDialect.Provider.class) + .hasAtLeastOneElementOfType(SapHanaDatabaseDialect.Provider.class) + .hasAtLeastOneElementOfType(VerticaDatabaseDialect.Provider.class) + .hasAtLeastOneElementOfType(MockDatabaseDialect.Provider.class); } @Test @@ -89,9 +90,6 @@ public void shouldFindSqlServerDialect() { @Test public void shouldFindSapDialect() { - try { - } finally { - } assertDialect(SapHanaDatabaseDialect.class, "jdbc:sap://myServer:30015/?autocommit=false"); } @@ -128,17 +126,4 @@ private void assertDialect( final DatabaseDialect dialect = DatabaseDialects.findBestFor(url, config); assertSame(dialect.getClass(), clazz); } - - private void assertContainsInstanceOf( - final Collection providers, - final Class clazz - ) { - for (final DatabaseDialectProvider provider : providers) { - if (provider.getClass().equals(clazz)) { - return; - } - } - fail("Missing " + clazz.getName()); - } - } diff --git a/src/test/java/io/aiven/connect/jdbc/dialect/GenericDatabaseDialectTest.java b/src/test/java/io/aiven/connect/jdbc/dialect/GenericDatabaseDialectTest.java index ee694883..10ef937e 100644 --- a/src/test/java/io/aiven/connect/jdbc/dialect/GenericDatabaseDialectTest.java +++ b/src/test/java/io/aiven/connect/jdbc/dialect/GenericDatabaseDialectTest.java @@ -21,11 +21,9 @@ import java.sql.Connection; import java.sql.SQLException; import java.sql.Types; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -55,10 +53,7 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class GenericDatabaseDialectTest extends BaseDialectTest { @@ -123,7 +118,7 @@ protected GenericDatabaseDialect newDialectFor( @Test public void testGetTablesEmpty() throws Exception { newDialectFor(TABLE_TYPES, null); - assertEquals(Collections.emptyList(), dialect.tableIds(conn)); + assertThat(dialect.tableIds(conn)).isEmpty(); } @Test @@ -131,7 +126,7 @@ public void testGetTablesSingle() throws Exception { newDialectFor(TABLE_TYPES, null); db.createTable("test", "id", "INT"); final TableId test = new TableId(null, "APP", "test"); - assertEquals(Arrays.asList(test), dialect.tableIds(conn)); + assertThat(dialect.tableIds(conn)).containsExactly(test); } @Test @@ -140,14 +135,14 @@ public void testFindTablesWithKnownTableType() throws Exception { newDialectFor(types, null); db.createTable("test", "id", "INT"); final TableId test = new TableId(null, "APP", "test"); - assertEquals(Arrays.asList(test), dialect.tableIds(conn)); + assertThat(dialect.tableIds(conn)).containsExactly(test); } @Test public void testNotFindTablesWithUnknownTableType() throws Exception { newDialectFor(Collections.singleton("view"), null); db.createTable("test", "id", "INT"); - assertEquals(Arrays.asList(), dialect.tableIds(conn)); + assertThat(dialect.tableIds(conn)).isEmpty(); } @Test @@ -159,8 +154,7 @@ public void testGetTablesMany() throws Exception { final TableId test = new TableId(null, "APP", "test"); final TableId foo = new TableId(null, "APP", "foo"); final TableId zab = new TableId(null, "APP", "zab"); - assertEquals(new HashSet<>(Arrays.asList(test, foo, zab)), - new HashSet<>(dialect.tableIds(conn))); + assertThat(dialect.tableIds(conn)).containsExactlyInAnyOrder(test, foo, zab); } @Test @@ -190,20 +184,20 @@ public void testGetTablesNarrowedToSchemas() throws Exception { assertTableNames(types, null, someTable, publicTable, privateTable, anotherPrivateTable); TableDefinition defn = dialect.describeTable(db.getConnection(), someTable); - assertEquals(someTable, defn.id()); - assertEquals("INTEGER", defn.definitionForColumn("id").typeName()); + assertThat(defn.id()).isEqualTo(someTable); + assertThat(defn.definitionForColumn("id").typeName()).isEqualTo("INTEGER"); defn = dialect.describeTable(db.getConnection(), publicTable); - assertEquals(publicTable, defn.id()); - assertEquals("INTEGER", defn.definitionForColumn("id").typeName()); + assertThat(defn.id()).isEqualTo(publicTable); + assertThat(defn.definitionForColumn("id").typeName()).isEqualTo("INTEGER"); defn = dialect.describeTable(db.getConnection(), privateTable); - assertEquals(privateTable, defn.id()); - assertEquals("INTEGER", defn.definitionForColumn("id").typeName()); + assertThat(defn.id()).isEqualTo(privateTable); + assertThat(defn.definitionForColumn("id").typeName()).isEqualTo("INTEGER"); defn = dialect.describeTable(db.getConnection(), anotherPrivateTable); - assertEquals(anotherPrivateTable, defn.id()); - assertEquals("INTEGER", defn.definitionForColumn("id").typeName()); + assertThat(defn.id()).isEqualTo(anotherPrivateTable); + assertThat(defn.definitionForColumn("id").typeName()).isEqualTo("INTEGER"); } protected void assertTableNames( @@ -214,16 +208,16 @@ protected void assertTableNames( newDialectFor(tableTypes, schemaPattern); final Collection ids = dialect.tableIds(db.getConnection()); for (final TableId expectedTableId : expectedTableIds) { - assertTrue(ids.contains(expectedTableId)); + assertThat(ids).contains(expectedTableId); } - assertEquals(expectedTableIds.length, ids.size()); + assertThat(ids).hasSameSizeAs(expectedTableIds); } @Test public void testDescribeTableOnEmptyDb() throws SQLException { final TableId someTable = new TableId(null, "APP", "some_table"); final TableDefinition defn = dialect.describeTable(db.getConnection(), someTable); - assertNull(defn); + assertThat(defn).isNull(); } @Test @@ -234,24 +228,24 @@ public void testDescribeTable() throws SQLException { "name", "VARCHAR(255) not null", "optional_age", "INTEGER"); final TableDefinition defn = dialect.describeTable(db.getConnection(), tableId); - assertEquals(tableId, defn.id()); + assertThat(defn.id()).isEqualTo(tableId); ColumnDefinition columnDefn = defn.definitionForColumn("id"); - assertEquals("INTEGER", columnDefn.typeName()); - assertEquals(Types.INTEGER, columnDefn.type()); - assertEquals(true, columnDefn.isPrimaryKey()); - assertEquals(false, columnDefn.isOptional()); + assertThat(columnDefn.typeName()).isEqualTo("INTEGER"); + assertThat(columnDefn.type()).isEqualTo(Types.INTEGER); + assertThat(columnDefn.isPrimaryKey()).isTrue(); + assertThat(columnDefn.isOptional()).isFalse(); columnDefn = defn.definitionForColumn("name"); - assertEquals("VARCHAR", columnDefn.typeName()); - assertEquals(Types.VARCHAR, columnDefn.type()); - assertEquals(false, columnDefn.isPrimaryKey()); - assertEquals(false, columnDefn.isOptional()); + assertThat(columnDefn.typeName()).isEqualTo("VARCHAR"); + assertThat(columnDefn.type()).isEqualTo(Types.VARCHAR); + assertThat(columnDefn.isPrimaryKey()).isFalse(); + assertThat(columnDefn.isOptional()).isFalse(); columnDefn = defn.definitionForColumn("optional_age"); - assertEquals("INTEGER", columnDefn.typeName()); - assertEquals(Types.INTEGER, columnDefn.type()); - assertEquals(false, columnDefn.isPrimaryKey()); - assertEquals(true, columnDefn.isOptional()); + assertThat(columnDefn.typeName()).isEqualTo("INTEGER"); + assertThat(columnDefn.type()).isEqualTo(Types.INTEGER); + assertThat(columnDefn.isPrimaryKey()).isFalse(); + assertThat(columnDefn.isOptional()).isTrue(); } @Test @@ -263,10 +257,10 @@ public void testDescribeColumns() throws Exception { ColumnId bar = new ColumnId(test, "bar"); Map defns = dialect .describeColumns(db.getConnection(), "test", null); - assertTrue(defns.get(id).isAutoIncrement()); - assertFalse(defns.get(bar).isAutoIncrement()); - assertFalse(defns.get(id).isOptional()); - assertTrue(defns.get(bar).isOptional()); + assertThat(defns.get(id).isAutoIncrement()).isTrue(); + assertThat(defns.get(bar).isAutoIncrement()).isFalse(); + assertThat(defns.get(id).isOptional()).isFalse(); + assertThat(defns.get(bar).isOptional()).isTrue(); // No auto increment db.createTable("none", "id", "INTEGER", "bar", "INTEGER"); @@ -274,10 +268,10 @@ public void testDescribeColumns() throws Exception { id = new ColumnId(none, "id"); bar = new ColumnId(none, "bar"); defns = dialect.describeColumns(db.getConnection(), "none", null); - assertFalse(defns.get(id).isAutoIncrement()); - assertFalse(defns.get(bar).isAutoIncrement()); - assertTrue(defns.get(id).isOptional()); - assertTrue(defns.get(bar).isOptional()); + assertThat(defns.get(id).isAutoIncrement()).isFalse(); + assertThat(defns.get(bar).isAutoIncrement()).isFalse(); + assertThat(defns.get(id).isOptional()).isTrue(); + assertThat(defns.get(bar).isOptional()).isTrue(); // We can't check multiple columns because Derby ties auto increment to identity and // disallows multiple auto increment columns. This is probably ok, multiple auto increment @@ -291,9 +285,9 @@ public void testDescribeColumns() throws Exception { id = new ColumnId(mixed, "id"); bar = new ColumnId(mixed, "bar"); defns = dialect.describeColumns(db.getConnection(), "mixed", null); - assertFalse(defns.get(foo).isAutoIncrement()); - assertTrue(defns.get(id).isAutoIncrement()); - assertFalse(defns.get(bar).isAutoIncrement()); + assertThat(defns.get(foo).isAutoIncrement()).isFalse(); + assertThat(defns.get(id).isAutoIncrement()).isTrue(); + assertThat(defns.get(bar).isAutoIncrement()).isFalse(); // Derby does not seem to allow null db.createTable("tstest", "ts", "TIMESTAMP NOT NULL", "tsdefault", "TIMESTAMP", "tsnull", @@ -304,10 +298,10 @@ public void testDescribeColumns() throws Exception { final ColumnId tsnull = new ColumnId(tstest, "tsnull"); defns = dialect.describeColumns(db.getConnection(), "tstest", null); - assertFalse(defns.get(ts).isOptional()); + assertThat(defns.get(ts).isOptional()).isFalse(); // The default for TIMESTAMP columns can vary between databases, but for Derby it is nullable - assertTrue(defns.get(tsdefault).isOptional()); - assertTrue(defns.get(tsnull).isOptional()); + assertThat(defns.get(tsdefault).isOptional()).isTrue(); + assertThat(defns.get(tsnull).isOptional()).isTrue(); } @Test(expected = ConnectException.class) @@ -351,14 +345,14 @@ private void verifyFormatColumnValue(final String expected, final Schema schema, final GenericDatabaseDialect dialect = dummyDialect(); final ExpressionBuilder builder = dialect.expressionBuilder(); dialect.formatColumnValue(builder, schema.name(), schema.parameters(), schema.type(), value); - assertEquals(expected, builder.toString()); + assertThat(builder).hasToString(expected); } private void verifyWriteColumnSpec(final String expected, final SinkRecordField field) { final GenericDatabaseDialect dialect = dummyDialect(); final ExpressionBuilder builder = dialect.expressionBuilder(); dialect.writeColumnSpec(builder, field); - assertEquals(expected, builder.toString()); + assertThat(builder).hasToString(expected); } private GenericDatabaseDialect dummyDialect() { diff --git a/src/test/java/io/aiven/connect/jdbc/dialect/PostgreSqlDatabaseDialectTest.java b/src/test/java/io/aiven/connect/jdbc/dialect/PostgreSqlDatabaseDialectTest.java index 2bb3210f..5db9ff35 100644 --- a/src/test/java/io/aiven/connect/jdbc/dialect/PostgreSqlDatabaseDialectTest.java +++ b/src/test/java/io/aiven/connect/jdbc/dialect/PostgreSqlDatabaseDialectTest.java @@ -45,8 +45,8 @@ import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; public class PostgreSqlDatabaseDialectTest extends BaseDialectTest { @@ -129,22 +129,20 @@ protected void assertColumnConverter(final int jdbcType, final String typeName, final Schema schemaType, final Class clazz) { - assertNotNull( - dialect.createColumnConverter( - new ColumnMapping( - createColumnDefinition( - new ColumnId( - new TableId( - "test_catalog", - "test", - "test_table" - ), - "column" - ), jdbcType, typeName, clazz), 1, - new Field("a", 1, schemaType) - ) - ) - ); + assertThat(dialect.createColumnConverter( + new ColumnMapping( + createColumnDefinition( + new ColumnId( + new TableId( + "test_catalog", + "test", + "test_table" + ), + "column" + ), jdbcType, typeName, clazz), 1, + new Field("a", 1, schemaType) + ) + )).isNotNull(); } @Test diff --git a/src/test/java/io/aiven/connect/jdbc/dialect/SqliteDatabaseDialectTest.java b/src/test/java/io/aiven/connect/jdbc/dialect/SqliteDatabaseDialectTest.java index 1dc7e61d..f207c3e2 100644 --- a/src/test/java/io/aiven/connect/jdbc/dialect/SqliteDatabaseDialectTest.java +++ b/src/test/java/io/aiven/connect/jdbc/dialect/SqliteDatabaseDialectTest.java @@ -46,8 +46,7 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class SqliteDatabaseDialectTest extends BaseDialectTest { @@ -205,24 +204,24 @@ public void testDescribeTable() throws SQLException { sqliteHelper.createTable( "create table x (id int primary key, name text not null, optional_age int null)"); final TableDefinition defn = dialect.describeTable(sqliteHelper.connection, tableId); - assertEquals(tableId, defn.id()); + assertThat(defn.id()).isEqualTo(tableId); ColumnDefinition columnDefn = defn.definitionForColumn("id"); - assertEquals("INT", columnDefn.typeName()); - assertEquals(Types.INTEGER, columnDefn.type()); - assertEquals(true, columnDefn.isPrimaryKey()); - assertEquals(false, columnDefn.isOptional()); + assertThat(columnDefn.typeName()).isEqualTo("INT"); + assertThat(columnDefn.type()).isEqualTo(Types.INTEGER); + assertThat(columnDefn.isPrimaryKey()).isTrue(); + assertThat(columnDefn.isOptional()).isFalse(); columnDefn = defn.definitionForColumn("name"); - assertEquals("TEXT", columnDefn.typeName()); - assertEquals(Types.VARCHAR, columnDefn.type()); - assertEquals(false, columnDefn.isPrimaryKey()); - assertEquals(false, columnDefn.isOptional()); + assertThat(columnDefn.typeName()).isEqualTo("TEXT"); + assertThat(columnDefn.type()).isEqualTo(Types.VARCHAR); + assertThat(columnDefn.isPrimaryKey()).isFalse(); + assertThat(columnDefn.isOptional()).isFalse(); columnDefn = defn.definitionForColumn("optional_age"); - assertEquals("INT", columnDefn.typeName()); - assertEquals(Types.INTEGER, columnDefn.type()); - assertEquals(false, columnDefn.isPrimaryKey()); - assertEquals(true, columnDefn.isOptional()); + assertThat(columnDefn.typeName()).isEqualTo("INT"); + assertThat(columnDefn.type()).isEqualTo(Types.INTEGER); + assertThat(columnDefn.isPrimaryKey()).isFalse(); + assertThat(columnDefn.isOptional()).isTrue(); } @Test @@ -231,6 +230,6 @@ public void testGettingCurrentTimeOnDB() throws SQLException { final Instant dbInstant = dialect.currentTimeOnDB(sqliteHelper.connection, cal).toInstant(); // Check that the UTC timezone is correct. final long diffSec = Math.abs(Duration.between(dbInstant, Instant.now()).getSeconds()); - assertTrue(diffSec <= 3); + assertThat(diffSec).isLessThanOrEqualTo(3); } } diff --git a/src/test/java/io/aiven/connect/jdbc/sink/BufferedRecordsTest.java b/src/test/java/io/aiven/connect/jdbc/sink/BufferedRecordsTest.java index faf3d119..01da6637 100644 --- a/src/test/java/io/aiven/connect/jdbc/sink/BufferedRecordsTest.java +++ b/src/test/java/io/aiven/connect/jdbc/sink/BufferedRecordsTest.java @@ -42,7 +42,7 @@ import org.mockito.ArgumentCaptor; import static java.sql.Statement.SUCCESS_NO_INFO; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.eq; @@ -80,36 +80,34 @@ public void correctBatching() throws SQLException { final TableId tableId = new TableId(null, null, "dummy"); final BufferedRecords buffer = new BufferedRecords( - config, tableId, dbDialect, dbStructure, sqliteHelper.connection); + config, tableId, dbDialect, dbStructure, sqliteHelper.connection); final Schema schemaA = SchemaBuilder.struct() - .field("name", Schema.STRING_SCHEMA) - .build(); + .field("name", Schema.STRING_SCHEMA) + .build(); final Struct valueA = new Struct(schemaA) - .put("name", "cuba"); + .put("name", "cuba"); final SinkRecord recordA = wrapInSinkRecord(valueA); final Schema schemaB = SchemaBuilder.struct() - .field("name", Schema.STRING_SCHEMA) - .field("age", Schema.OPTIONAL_INT32_SCHEMA) - .build(); + .field("name", Schema.STRING_SCHEMA) + .field("age", Schema.OPTIONAL_INT32_SCHEMA) + .build(); final Struct valueB = new Struct(schemaB) - .put("name", "cuba") - .put("age", 4); + .put("name", "cuba") + .put("age", 4); final SinkRecord recordB = new SinkRecord("dummy", 1, null, null, schemaB, valueB, 1); // test records are batched correctly based on schema equality as records are added // (schemaA,schemaA,schemaA,schemaB,schemaA) -> ([schemaA,schemaA,schemaA],[schemaB],[schemaA]) - assertEquals(Collections.emptyList(), buffer.add(recordA)); - assertEquals(Collections.emptyList(), buffer.add(recordA)); - assertEquals(Collections.emptyList(), buffer.add(recordA)); - - assertEquals(Arrays.asList(recordA, recordA, recordA), buffer.add(recordB)); + assertThat(buffer.add(recordA)).isEmpty(); + assertThat(buffer.add(recordA)).isEmpty(); + assertThat(buffer.add(recordA)).isEmpty(); - assertEquals(Collections.singletonList(recordB), buffer.add(recordA)); - - assertEquals(Collections.singletonList(recordA), buffer.flush()); + assertThat(buffer.add(recordB)).isEqualTo(Arrays.asList(recordA, recordA, recordA)); + assertThat(buffer.add(recordA)).isEqualTo(Collections.singletonList(recordB)); + assertThat(buffer.flush()).isEqualTo(Collections.singletonList(recordA)); } @Test @@ -222,14 +220,10 @@ public void testInsertModeMultiAutomaticFlush() throws SQLException { // Given the 5 records, and batch size of 2, we expect 2 inserts. // One record is still waiting in the buffer, and that is expected. verify(connection, times(2)).prepareStatement(sqlCaptor.capture()); - assertEquals( - sqlCaptor.getAllValues().get(0), - "INSERT INTO \"planets\"(\"name\",\"planetid\") VALUES (?,?),(?,?)" - ); - assertEquals( - sqlCaptor.getAllValues().get(1), - "INSERT INTO \"planets\"(\"name\",\"planetid\") VALUES (?,?),(?,?)" - ); + assertThat(sqlCaptor.getAllValues().get(0)).isEqualTo( + "INSERT INTO \"planets\"(\"name\",\"planetid\") VALUES (?,?),(?,?)"); + assertThat(sqlCaptor.getAllValues().get(1)).isEqualTo( + "INSERT INTO \"planets\"(\"name\",\"planetid\") VALUES (?,?),(?,?)"); } @Test diff --git a/src/test/java/io/aiven/connect/jdbc/sink/DbStructureTest.java b/src/test/java/io/aiven/connect/jdbc/sink/DbStructureTest.java index 281a018a..0aa6390e 100644 --- a/src/test/java/io/aiven/connect/jdbc/sink/DbStructureTest.java +++ b/src/test/java/io/aiven/connect/jdbc/sink/DbStructureTest.java @@ -30,8 +30,7 @@ import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class DbStructureTest { @@ -39,24 +38,24 @@ public class DbStructureTest { @Test public void testNoMissingFields() { - assertTrue(missingFields(sinkRecords("aaa"), columns("aaa", "bbb")).isEmpty()); + assertThat(missingFields(sinkRecords("aaa"), columns("aaa", "bbb"))).isEmpty(); } @Test public void testMissingFieldsWithSameCase() { - assertEquals(1, missingFields(sinkRecords("aaa", "bbb"), columns("aaa")).size()); + assertThat(missingFields(sinkRecords("aaa", "bbb"), columns("aaa"))).hasSize(1); } @Test public void testSameNamesDifferentCases() { - assertTrue(missingFields(sinkRecords("aaa"), columns("aAa", "AaA")).isEmpty()); + assertThat(missingFields(sinkRecords("aaa"), columns("aAa", "AaA"))).isEmpty(); } @Test public void testMissingFieldsWithDifferentCase() { - assertTrue(missingFields(sinkRecords("aaa", "bbb"), columns("AaA", "BbB")).isEmpty()); - assertTrue(missingFields(sinkRecords("AaA", "bBb"), columns("aaa", "bbb")).isEmpty()); - assertTrue(missingFields(sinkRecords("AaA", "bBb"), columns("aAa", "BbB")).isEmpty()); + assertThat(missingFields(sinkRecords("aaa", "bbb"), columns("AaA", "BbB"))).isEmpty(); + assertThat(missingFields(sinkRecords("AaA", "bBb"), columns("aaa", "bbb"))).isEmpty(); + assertThat(missingFields(sinkRecords("AaA", "bBb"), columns("aAa", "BbB"))).isEmpty(); } private Set missingFields( diff --git a/src/test/java/io/aiven/connect/jdbc/sink/JdbcDbWriterTest.java b/src/test/java/io/aiven/connect/jdbc/sink/JdbcDbWriterTest.java index 722c13ea..a48417b8 100644 --- a/src/test/java/io/aiven/connect/jdbc/sink/JdbcDbWriterTest.java +++ b/src/test/java/io/aiven/connect/jdbc/sink/JdbcDbWriterTest.java @@ -19,7 +19,6 @@ import java.io.IOException; import java.math.BigDecimal; -import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.HashMap; @@ -46,10 +45,8 @@ import org.junit.Before; import org.junit.Test; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; public class JdbcDbWriterTest { @@ -90,30 +87,26 @@ public void shouldGenerateNormalizedTableNameForTopic() { final DbStructure dbStructure = new DbStructure(dialect); final JdbcDbWriter jdbcDbWriter = new JdbcDbWriter(jdbcSinkConfig, dialect, dbStructure); - assertEquals("kafka_topic___some_topic", - jdbcDbWriter.generateTableNameFor("--some_topic")); + assertThat(jdbcDbWriter.generateTableNameFor("--some_topic")).isEqualTo("kafka_topic___some_topic"); - assertEquals("kafka_topic_some_topic", - jdbcDbWriter.generateTableNameFor("some_topic")); + assertThat(jdbcDbWriter.generateTableNameFor("some_topic")).isEqualTo("kafka_topic_some_topic"); - assertEquals("kafka_topic_some_topic", - jdbcDbWriter.generateTableNameFor("some-topic")); + assertThat(jdbcDbWriter.generateTableNameFor("some-topic")).isEqualTo("kafka_topic_some_topic"); - assertEquals("kafka_topic_this_is_topic_with_dots", - jdbcDbWriter.generateTableNameFor("this.is.topic.with.dots")); + assertThat(jdbcDbWriter.generateTableNameFor("this.is.topic.with.dots")) + .isEqualTo("kafka_topic_this_is_topic_with_dots"); - assertEquals("kafka_topic_this_is_topic_with_dots_and_weired_characters___", - jdbcDbWriter.generateTableNameFor("this.is.topic.with.dots.and.weired.characters#$%")); + assertThat(jdbcDbWriter.generateTableNameFor("this.is.topic.with.dots.and.weired.characters#$%")) + .isEqualTo("kafka_topic_this_is_topic_with_dots_and_weired_characters___"); - assertEquals("kafka_topic_orders_topic__3", - jdbcDbWriter.generateTableNameFor("orders_topic_#3")); + assertThat(jdbcDbWriter.generateTableNameFor("orders_topic_#3")).isEqualTo("kafka_topic_orders_topic__3"); } @Test public void shouldSelectTableFromMapping() { final Map props = new HashMap<>(); - props.put(JdbcSinkConfig.CONNECTION_URL_CONFIG, "jdbc://localhnost"); + props.put(JdbcSinkConfig.CONNECTION_URL_CONFIG, "jdbc://localhost"); props.put(JdbcSinkConfig.TABLE_NAME_FORMAT, "${topic}"); props.put(JdbcSinkConfig.TOPICS_TO_TABLES_MAPPING, "some_topic:same_table"); @@ -123,13 +116,13 @@ public void shouldSelectTableFromMapping() { final JdbcDbWriter writer = new JdbcDbWriter(jdbcSinkConfig, dialect, dbStructure); final TableId tableId = writer.destinationTable("some_topic"); - assertEquals("same_table", tableId.tableName()); + assertThat(tableId.tableName()).isEqualTo("same_table"); } @Test(expected = ConnectException.class) public void shouldThrowConnectExceptionForUnknownTopicToTableMapping() { final Map props = new HashMap<>(); - props.put(JdbcSinkConfig.CONNECTION_URL_CONFIG, "jdbc://localhnost"); + props.put(JdbcSinkConfig.CONNECTION_URL_CONFIG, "jdbc://localhost"); props.put(JdbcSinkConfig.TABLE_NAME_FORMAT, ""); props.put(JdbcSinkConfig.TOPICS_TO_TABLES_MAPPING, "some_topic:same_table,some_topic2:same_table2"); @@ -170,9 +163,9 @@ public void autoCreateWithAutoEvolve() throws SQLException { final TableDefinition metadata = dialect.describeTable(writer.cachedConnectionProvider.getConnection(), tableId); - assertTrue(metadata.definitionForColumn("id").isPrimaryKey()); + assertThat(metadata.definitionForColumn("id").isPrimaryKey()).isTrue(); for (final Field field : valueSchema1.fields()) { - assertNotNull(metadata.definitionForColumn(field.name())); + assertThat(metadata.definitionForColumn(field.name())).isNotNull(); } final Schema valueSchema2 = SchemaBuilder.struct() @@ -189,9 +182,9 @@ public void autoCreateWithAutoEvolve() throws SQLException { writer.write(Collections.singleton(new SinkRecord(topic, 0, keySchema, 2L, valueSchema2, valueStruct2, 0))); final TableDefinition refreshedMetadata = dialect.describeTable(sqliteHelper.connection, tableId); - assertTrue(refreshedMetadata.definitionForColumn("id").isPrimaryKey()); + assertThat(refreshedMetadata.definitionForColumn("id").isPrimaryKey()).isTrue(); for (final Field field : valueSchema2.fields()) { - assertNotNull(refreshedMetadata.definitionForColumn(field.name())); + assertThat(refreshedMetadata.definitionForColumn(field.name())).isNotNull(); } } @@ -268,15 +261,9 @@ private void writeSameRecordTwiceExpectingSingleUpdate( writer.write(Collections.nCopies(2, record)); - assertEquals( - 1, - sqliteHelper.select("select count(*) from books", new SqliteHelper.ResultSetReadCallback() { - @Override - public void read(final ResultSet rs) throws SQLException { - assertEquals(1, rs.getInt(1)); - } - }) - ); + assertThat(sqliteHelper.select("select count(*) from books", + rs -> assertThat(rs.getInt(1)).isOne())) + .isOne(); } @Test @@ -347,36 +334,27 @@ public void sameRecordNTimes() throws SQLException { new SinkRecord("topic", 0, null, null, schema, struct, 0) )); - assertEquals( - numRecords, - sqliteHelper.select( - "SELECT * FROM " + testId, - new SqliteHelper.ResultSetReadCallback() { - @Override - public void read(final ResultSet rs) throws SQLException { - assertEquals(struct.getInt8("the_byte").byteValue(), rs.getByte("the_byte")); - assertEquals(struct.getInt16("the_short").shortValue(), rs.getShort("the_short")); - assertEquals(struct.getInt32("the_int").intValue(), rs.getInt("the_int")); - assertEquals(struct.getInt64("the_long").longValue(), rs.getLong("the_long")); - assertEquals(struct.getFloat32("the_float"), rs.getFloat("the_float"), 0.01); - assertEquals(struct.getFloat64("the_double"), rs.getDouble("the_double"), 0.01); - assertEquals(struct.getBoolean("the_bool"), rs.getBoolean("the_bool")); - assertEquals(struct.getString("the_string"), rs.getString("the_string")); - assertArrayEquals(struct.getBytes("the_bytes"), rs.getBytes("the_bytes")); - assertEquals(struct.get("the_decimal"), rs.getBigDecimal("the_decimal")); - assertEquals( - new java.sql.Date(((java.util.Date) struct.get("the_date")).getTime()), - rs.getDate("the_date")); - assertEquals( - new java.sql.Time(((java.util.Date) struct.get("the_time")).getTime()), - rs.getTime("the_time")); - assertEquals( - new java.sql.Timestamp(((java.util.Date) struct.get("the_time")).getTime()), - rs.getTimestamp("the_timestamp")); - } - } - ) - ); + assertThat(sqliteHelper.select( + "SELECT * FROM " + testId, + rs -> { + assertThat(rs.getByte("the_byte")).isEqualTo(struct.getInt8("the_byte").byteValue()); + assertThat(rs.getShort("the_short")).isEqualTo(struct.getInt16("the_short").shortValue()); + assertThat(rs.getInt("the_int")).isEqualTo(struct.getInt32("the_int").intValue()); + assertThat(rs.getLong("the_long")).isEqualTo(struct.getInt64("the_long").longValue()); + assertThat(rs.getFloat("the_float")).isCloseTo(struct.getFloat32("the_float"), offset(0.01f)); + assertThat(rs.getDouble("the_double")).isCloseTo(struct.getFloat64("the_double"), offset(0.01d)); + assertThat(rs.getBoolean("the_bool")).isEqualTo(struct.getBoolean("the_bool")); + assertThat(rs.getString("the_string")).isEqualTo(struct.getString("the_string")); + assertThat(rs.getBytes("the_bytes")).containsExactly(struct.getBytes("the_bytes")); + assertThat(rs.getBigDecimal("the_decimal")).isEqualTo(struct.get("the_decimal")); + assertThat(rs.getDate("the_date")).isEqualTo( + new java.sql.Date(((java.util.Date) struct.get("the_date")).getTime())); + assertThat(rs.getTime("the_time")).isEqualTo( + new java.sql.Time(((java.util.Date) struct.get("the_time")).getTime())); + assertThat(rs.getTimestamp("the_timestamp")).isEqualTo( + new java.sql.Timestamp(((java.util.Date) struct.get("the_time")).getTime())); + } + )).isEqualTo(numRecords); } } diff --git a/src/test/java/io/aiven/connect/jdbc/sink/JdbcSinkConfigTest.java b/src/test/java/io/aiven/connect/jdbc/sink/JdbcSinkConfigTest.java index e2034244..af8ba7f2 100644 --- a/src/test/java/io/aiven/connect/jdbc/sink/JdbcSinkConfigTest.java +++ b/src/test/java/io/aiven/connect/jdbc/sink/JdbcSinkConfigTest.java @@ -24,8 +24,8 @@ import org.junit.Test; -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; public class JdbcSinkConfigTest { @@ -33,7 +33,7 @@ public class JdbcSinkConfigTest { public void shouldReturnEmptyMapForUndefinedMapping() { final Map props = new HashMap<>(); props.put(JdbcSinkConfig.CONNECTION_URL_CONFIG, "jdbc://localhost"); - assertTrue(new JdbcSinkConfig(props).topicsToTablesMapping.isEmpty()); + assertThat(new JdbcSinkConfig(props).topicsToTablesMapping).isEmpty(); } @Test @@ -44,15 +44,15 @@ public void shouldParseTopicToTableMappings() { JdbcSinkConfig config = new JdbcSinkConfig(props); - assertEquals(config.topicsToTablesMapping.size(), 2); - assertEquals(config.topicsToTablesMapping.get("t0"), "tbl0"); - assertEquals(config.topicsToTablesMapping.get("t1"), "tbl1"); + assertThat(config.topicsToTablesMapping) + .containsExactly( + entry("t0", "tbl0"), + entry("t1", "tbl1")); props.put(JdbcSinkConfig.TOPICS_TO_TABLES_MAPPING, "t3:tbl3"); config = new JdbcSinkConfig(props); - assertEquals(config.topicsToTablesMapping.size(), 1); - assertEquals(config.topicsToTablesMapping.get("t3"), "tbl3"); + assertThat(config.topicsToTablesMapping).containsExactly(entry("t3", "tbl3")); } @Test(expected = ConfigException.class) diff --git a/src/test/java/io/aiven/connect/jdbc/sink/JdbcSinkTaskTest.java b/src/test/java/io/aiven/connect/jdbc/sink/JdbcSinkTaskTest.java index c4b72953..0ea56303 100644 --- a/src/test/java/io/aiven/connect/jdbc/sink/JdbcSinkTaskTest.java +++ b/src/test/java/io/aiven/connect/jdbc/sink/JdbcSinkTaskTest.java @@ -18,7 +18,6 @@ package io.aiven.connect.jdbc.sink; import java.io.IOException; -import java.sql.ResultSet; import java.sql.SQLException; import java.time.ZoneOffset; import java.util.Collections; @@ -45,10 +44,10 @@ import org.junit.Before; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.data.Offset.offset; import static org.easymock.EasyMock.expectLastCall; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; public class JdbcSinkTaskTest extends EasyMockSupport { private final SqliteHelper sqliteHelper = new SqliteHelper(getClass().getSimpleName()); @@ -110,34 +109,28 @@ public void putPropagatesToDbWithAutoCreateAndPkModeKafka() throws Exception { new SinkRecord(topic, 1, null, null, SCHEMA, struct, 42) )); - assertEquals( - 1, - sqliteHelper.select( - "SELECT * FROM " + topic, - new SqliteHelper.ResultSetReadCallback() { - @Override - public void read(final ResultSet rs) throws SQLException { - assertEquals(topic, rs.getString("kafka_topic")); - assertEquals(1, rs.getInt("kafka_partition")); - assertEquals(42, rs.getLong("kafka_offset")); - assertEquals(struct.getString("firstName"), rs.getString("firstName")); - assertEquals(struct.getString("lastName"), rs.getString("lastName")); - assertEquals(struct.getBoolean("bool"), rs.getBoolean("bool")); - assertEquals(struct.getInt8("byte").byteValue(), rs.getByte("byte")); - assertEquals(struct.getInt16("short").shortValue(), rs.getShort("short")); - assertEquals(struct.getInt32("age").intValue(), rs.getInt("age")); - assertEquals(struct.getInt64("long").longValue(), rs.getLong("long")); - assertEquals(struct.getFloat32("float"), rs.getFloat("float"), 0.01); - assertEquals(struct.getFloat64("double"), rs.getDouble("double"), 0.01); - final java.sql.Timestamp dbTimestamp = rs.getTimestamp( - "modified", - DateTimeUtils.getTimeZoneCalendar(timeZone) - ); - assertEquals(((java.util.Date) struct.get("modified")).getTime(), dbTimestamp.getTime()); - } - } - ) - ); + assertThat(sqliteHelper.select( + "SELECT * FROM " + topic, + rs -> { + assertThat(rs.getString("kafka_topic")).isEqualTo(topic); + assertThat(rs.getInt("kafka_partition")).isOne(); + assertThat(rs.getLong("kafka_offset")).isEqualTo(42); + assertThat(rs.getString("firstName")).isEqualTo(struct.getString("firstName")); + assertThat(rs.getString("lastName")).isEqualTo(struct.getString("lastName")); + assertThat(rs.getBoolean("bool")).isEqualTo(struct.getBoolean("bool")); + assertThat(rs.getByte("byte")).isEqualTo(struct.getInt8("byte").byteValue()); + assertThat(rs.getShort("short")).isEqualTo(struct.getInt16("short").shortValue()); + assertThat(rs.getInt("age")).isEqualTo(struct.getInt32("age").intValue()); + assertThat(rs.getLong("long")).isEqualTo(struct.getInt64("long").longValue()); + assertThat(rs.getFloat("float")).isCloseTo(struct.getFloat32("float"), offset(0.01f)); + assertThat(rs.getDouble("double")).isCloseTo(struct.getFloat64("double"), offset(0.01)); + final java.sql.Timestamp dbTimestamp = rs.getTimestamp( + "modified", + DateTimeUtils.getTimeZoneCalendar(timeZone) + ); + assertThat(dbTimestamp.getTime()).isEqualTo(((Date) struct.get("modified")).getTime()); + } + )).isOne(); } @Test @@ -189,31 +182,25 @@ public void putPropagatesToDbWithPkModeRecordValue() throws Exception { + "' and lastName='" + struct.getString("lastName") + "'"; - assertEquals( - 1, - sqliteHelper.select( - query, - new SqliteHelper.ResultSetReadCallback() { - @Override - public void read(final ResultSet rs) throws SQLException { - assertEquals(struct.getBoolean("bool"), rs.getBoolean("bool")); - rs.getShort("short"); - assertTrue(rs.wasNull()); - assertEquals(struct.getInt8("byte").byteValue(), rs.getByte("byte")); - assertEquals(struct.getInt32("age").intValue(), rs.getInt("age")); - assertEquals(struct.getInt64("long").longValue(), rs.getLong("long")); - rs.getShort("float"); - assertTrue(rs.wasNull()); - assertEquals(struct.getFloat64("double"), rs.getDouble("double"), 0.01); - final java.sql.Timestamp dbTimestamp = rs.getTimestamp( - "modified", - DateTimeUtils.getTimeZoneCalendar(TimeZone.getTimeZone(ZoneOffset.UTC)) - ); - assertEquals(((java.util.Date) struct.get("modified")).getTime(), dbTimestamp.getTime()); - } - } - ) - ); + assertThat(sqliteHelper.select( + query, + rs -> { + assertThat(rs.getBoolean("bool")).isEqualTo(struct.getBoolean("bool")); + rs.getShort("short"); + assertThat(rs.wasNull()).isTrue(); + assertThat(rs.getByte("byte")).isEqualTo(struct.getInt8("byte").byteValue()); + assertThat(rs.getInt("age")).isEqualTo(struct.getInt32("age").intValue()); + assertThat(rs.getLong("long")).isEqualTo(struct.getInt64("long").longValue()); + rs.getShort("float"); + assertThat(rs.wasNull()).isTrue(); + assertThat(rs.getDouble("double")).isCloseTo(struct.getFloat64("double"), offset(0.01)); + final java.sql.Timestamp dbTimestamp = rs.getTimestamp( + "modified", + DateTimeUtils.getTimeZoneCalendar(TimeZone.getTimeZone(ZoneOffset.UTC)) + ); + assertThat(dbTimestamp.getTime()).isEqualTo(((Date) struct.get("modified")).getTime()); + } + )).isOne(); } @Test @@ -250,28 +237,13 @@ void initWriter() { replayAll(); - try { - task.put(records); - fail(); - } catch (final RetriableException expected) { - } - - try { - task.put(records); - fail(); - } catch (final RetriableException expected) { - } - - try { - task.put(records); - fail(); - } catch (final RetriableException e) { - fail("Non-retriable exception expected"); - } catch (final ConnectException expected) { - assertEquals(SQLException.class, expected.getCause().getClass()); - } + assertThatThrownBy(() -> task.put(records)).isInstanceOf(RetriableException.class); + assertThatThrownBy(() -> task.put(records)).isInstanceOf(RetriableException.class); + assertThatThrownBy(() -> task.put(records)) + .isNotInstanceOf(RetriableException.class) + .isInstanceOf(ConnectException.class) + .hasCauseInstanceOf(SQLException.class); verifyAll(); } - } diff --git a/src/test/java/io/aiven/connect/jdbc/sink/SqliteHelperTest.java b/src/test/java/io/aiven/connect/jdbc/sink/SqliteHelperTest.java index b8b30bbd..1166d994 100644 --- a/src/test/java/io/aiven/connect/jdbc/sink/SqliteHelperTest.java +++ b/src/test/java/io/aiven/connect/jdbc/sink/SqliteHelperTest.java @@ -34,10 +34,7 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class SqliteHelperTest { @@ -84,60 +81,57 @@ public void returnTheDatabaseTableInformation() throws SQLException { tables.put(tableId.tableName(), dialect.describeTable(sqliteHelper.connection, tableId)); } - assertEquals(tables.size(), 3); - assertTrue(tables.containsKey("employees")); - assertTrue(tables.containsKey("products")); - assertTrue(tables.containsKey("nonPk")); + assertThat(tables).containsOnlyKeys("employees", "products", "nonPk"); final TableDefinition nonPk = tables.get("nonPk"); - assertEquals(2, nonPk.columnCount()); + assertThat(nonPk.columnCount()).isEqualTo(2); ColumnDefinition colDefn = nonPk.definitionForColumn("id"); - assertTrue(colDefn.isOptional()); - assertFalse(colDefn.isPrimaryKey()); - assertEquals(Types.FLOAT, colDefn.type()); + assertThat(colDefn.isOptional()).isTrue(); + assertThat(colDefn.isPrimaryKey()).isFalse(); + assertThat(colDefn.type()).isEqualTo(Types.FLOAT); colDefn = nonPk.definitionForColumn("response"); - assertTrue(colDefn.isOptional()); - assertFalse(colDefn.isPrimaryKey()); - assertEquals(Types.VARCHAR, colDefn.type()); + assertThat(colDefn.isOptional()).isTrue(); + assertThat(colDefn.isPrimaryKey()).isFalse(); + assertThat(colDefn.type()).isEqualTo(Types.VARCHAR); final TableDefinition employees = tables.get("employees"); - assertEquals(4, employees.columnCount()); - - assertNotNull(employees.definitionForColumn("employee_id")); - assertFalse(employees.definitionForColumn("employee_id").isOptional()); - assertTrue(employees.definitionForColumn("employee_id").isPrimaryKey()); - assertEquals(Types.INTEGER, employees.definitionForColumn("employee_id").type()); - assertNotNull(employees.definitionForColumn("last_name")); - assertFalse(employees.definitionForColumn("last_name").isOptional()); - assertFalse(employees.definitionForColumn("last_name").isPrimaryKey()); - assertEquals(Types.VARCHAR, employees.definitionForColumn("last_name").type()); - assertNotNull(employees.definitionForColumn("first_name")); - assertTrue(employees.definitionForColumn("first_name").isOptional()); - assertFalse(employees.definitionForColumn("first_name").isPrimaryKey()); - assertEquals(Types.VARCHAR, employees.definitionForColumn("first_name").type()); - assertNotNull(employees.definitionForColumn("hire_date")); - assertTrue(employees.definitionForColumn("hire_date").isOptional()); - assertFalse(employees.definitionForColumn("hire_date").isPrimaryKey()); + assertThat(employees.columnCount()).isEqualTo(4); + + assertThat(employees.definitionForColumn("employee_id")).isNotNull(); + assertThat(employees.definitionForColumn("employee_id").isOptional()).isFalse(); + assertThat(employees.definitionForColumn("employee_id").isPrimaryKey()).isTrue(); + assertThat(employees.definitionForColumn("employee_id").type()).isEqualTo(Types.INTEGER); + assertThat(employees.definitionForColumn("last_name")).isNotNull(); + assertThat(employees.definitionForColumn("last_name").isOptional()).isFalse(); + assertThat(employees.definitionForColumn("last_name").isPrimaryKey()).isFalse(); + assertThat(employees.definitionForColumn("last_name").type()).isEqualTo(Types.VARCHAR); + assertThat(employees.definitionForColumn("first_name")).isNotNull(); + assertThat(employees.definitionForColumn("first_name").isOptional()).isTrue(); + assertThat(employees.definitionForColumn("first_name").isPrimaryKey()).isFalse(); + assertThat(employees.definitionForColumn("first_name").type()).isEqualTo(Types.VARCHAR); + assertThat(employees.definitionForColumn("hire_date")).isNotNull(); + assertThat(employees.definitionForColumn("hire_date").isOptional()).isTrue(); + assertThat(employees.definitionForColumn("hire_date").isPrimaryKey()).isFalse(); // sqlite returns VARCHAR for DATE. why?! - assertEquals(Types.VARCHAR, employees.definitionForColumn("hire_date").type()); + assertThat(employees.definitionForColumn("hire_date").type()).isEqualTo(Types.VARCHAR); // assertEquals(columns.get("hire_date").getSqlType(), Types.DATE); final TableDefinition products = tables.get("products"); - assertEquals(4, employees.columnCount()); - - assertNotNull(products.definitionForColumn("product_id")); - assertFalse(products.definitionForColumn("product_id").isOptional()); - assertTrue(products.definitionForColumn("product_id").isPrimaryKey()); - assertEquals(Types.INTEGER, products.definitionForColumn("product_id").type()); - assertNotNull(products.definitionForColumn("product_name")); - assertFalse(products.definitionForColumn("product_name").isOptional()); - assertFalse(products.definitionForColumn("product_name").isPrimaryKey()); - assertEquals(Types.VARCHAR, products.definitionForColumn("product_name").type()); - assertNotNull(products.definitionForColumn("quantity")); - assertFalse(products.definitionForColumn("quantity").isOptional()); - assertFalse(products.definitionForColumn("quantity").isPrimaryKey()); - assertEquals(Types.INTEGER, products.definitionForColumn("quantity").type()); + assertThat(employees.columnCount()).isEqualTo(4); + + assertThat(products.definitionForColumn("product_id")).isNotNull(); + assertThat(products.definitionForColumn("product_id").isOptional()).isFalse(); + assertThat(products.definitionForColumn("product_id").isPrimaryKey()).isTrue(); + assertThat(products.definitionForColumn("product_id").type()).isEqualTo(Types.INTEGER); + assertThat(products.definitionForColumn("product_name")).isNotNull(); + assertThat(products.definitionForColumn("product_name").isOptional()).isFalse(); + assertThat(products.definitionForColumn("product_name").isPrimaryKey()).isFalse(); + assertThat(products.definitionForColumn("product_name").type()).isEqualTo(Types.VARCHAR); + assertThat(products.definitionForColumn("quantity")).isNotNull(); + assertThat(products.definitionForColumn("quantity").isOptional()).isFalse(); + assertThat(products.definitionForColumn("quantity").isPrimaryKey()).isFalse(); + assertThat(products.definitionForColumn("quantity").type()).isEqualTo(Types.INTEGER); } } diff --git a/src/test/java/io/aiven/connect/jdbc/sink/metadata/FieldsMetadataTest.java b/src/test/java/io/aiven/connect/jdbc/sink/metadata/FieldsMetadataTest.java index 3d30fe86..7b48d4d2 100644 --- a/src/test/java/io/aiven/connect/jdbc/sink/metadata/FieldsMetadataTest.java +++ b/src/test/java/io/aiven/connect/jdbc/sink/metadata/FieldsMetadataTest.java @@ -30,9 +30,7 @@ import com.google.common.collect.Lists; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class FieldsMetadataTest { @@ -63,27 +61,21 @@ public void valueSchemaMustBeStructIfPresent() { @Test public void missingValueSchemaCanBeOk() { - assertEquals( - Set.of("name"), - extract( - JdbcSinkConfig.PrimaryKeyMode.RECORD_KEY, - Collections.emptyList(), - SIMPLE_STRUCT_SCHEMA, - null - ).allFields.keySet() - ); + assertThat(extract( + JdbcSinkConfig.PrimaryKeyMode.RECORD_KEY, + Collections.emptyList(), + SIMPLE_STRUCT_SCHEMA, + null + ).allFields.keySet()).isEqualTo(Set.of("name")); // this one is a bit weird, only columns being inserted would be kafka coords... // but not sure should explicitly disallow! - assertEquals( - List.of("__connect_topic", "__connect_partition", "__connect_offset"), - Lists.newArrayList(extract( - JdbcSinkConfig.PrimaryKeyMode.KAFKA, - Collections.emptyList(), - null, - null - ).allFields.keySet()) - ); + assertThat(Lists.newArrayList(extract( + JdbcSinkConfig.PrimaryKeyMode.KAFKA, + Collections.emptyList(), + null, + null + ).allFields.keySet())).isEqualTo(List.of("__connect_topic", "__connect_partition", "__connect_offset")); } @Test(expected = ConnectException.class) @@ -104,26 +96,24 @@ public void kafkaPkMode() { null, SIMPLE_STRUCT_SCHEMA ); - assertEquals( - List.of("__connect_topic", "__connect_partition", "__connect_offset"), - Lists.newArrayList(metadata.keyFieldNames) - ); - assertEquals(Set.of("name"), metadata.nonKeyFieldNames); + assertThat(Lists.newArrayList(metadata.keyFieldNames)).isEqualTo( + List.of("__connect_topic", "__connect_partition", "__connect_offset")); + assertThat(metadata.nonKeyFieldNames).isEqualTo(Set.of("name")); final SinkRecordField topicField = metadata.allFields.get("__connect_topic"); - assertEquals(Schema.Type.STRING, topicField.schemaType()); - assertTrue(topicField.isPrimaryKey()); - assertFalse(topicField.isOptional()); + assertThat(topicField.schemaType()).isEqualTo(Schema.Type.STRING); + assertThat(topicField.isPrimaryKey()).isTrue(); + assertThat(topicField.isOptional()).isFalse(); final SinkRecordField partitionField = metadata.allFields.get("__connect_partition"); - assertEquals(Schema.Type.INT32, partitionField.schemaType()); - assertTrue(partitionField.isPrimaryKey()); - assertFalse(partitionField.isOptional()); + assertThat(partitionField.schemaType()).isEqualTo(Schema.Type.INT32); + assertThat(partitionField.isPrimaryKey()).isTrue(); + assertThat(partitionField.isOptional()).isFalse(); final SinkRecordField offsetField = metadata.allFields.get("__connect_offset"); - assertEquals(Schema.Type.INT64, offsetField.schemaType()); - assertTrue(offsetField.isPrimaryKey()); - assertFalse(offsetField.isOptional()); + assertThat(offsetField.schemaType()).isEqualTo(Schema.Type.INT64); + assertThat(offsetField.isPrimaryKey()).isTrue(); + assertThat(offsetField.isOptional()).isFalse(); } @Test @@ -135,8 +125,8 @@ public void kafkaPkModeCustomNames() { null, SIMPLE_STRUCT_SCHEMA ); - assertEquals(customKeyNames, Lists.newArrayList(metadata.keyFieldNames)); - assertEquals(Collections.singleton("name"), metadata.nonKeyFieldNames); + assertThat(Lists.newArrayList(metadata.keyFieldNames)).isEqualTo(customKeyNames); + assertThat(metadata.nonKeyFieldNames).isEqualTo(Collections.singleton("name")); } @Test(expected = ConnectException.class) @@ -163,17 +153,17 @@ public void recordKeyPkModePrimitiveKey() { SIMPLE_STRUCT_SCHEMA ); - assertEquals(Collections.singleton("the_pk"), metadata.keyFieldNames); + assertThat(metadata.keyFieldNames).isEqualTo(Collections.singleton("the_pk")); - assertEquals(Collections.singleton("name"), metadata.nonKeyFieldNames); + assertThat(metadata.nonKeyFieldNames).isEqualTo(Collections.singleton("name")); - assertEquals(SIMPLE_PRIMITIVE_SCHEMA.type(), metadata.allFields.get("the_pk").schemaType()); - assertTrue(metadata.allFields.get("the_pk").isPrimaryKey()); - assertFalse(metadata.allFields.get("the_pk").isOptional()); + assertThat(metadata.allFields.get("the_pk").schemaType()).isEqualTo(SIMPLE_PRIMITIVE_SCHEMA.type()); + assertThat(metadata.allFields.get("the_pk").isPrimaryKey()).isTrue(); + assertThat(metadata.allFields.get("the_pk").isOptional()).isFalse(); - assertEquals(Schema.Type.STRING, metadata.allFields.get("name").schemaType()); - assertFalse(metadata.allFields.get("name").isPrimaryKey()); - assertFalse(metadata.allFields.get("name").isOptional()); + assertThat(metadata.allFields.get("name").schemaType()).isEqualTo(Schema.Type.STRING); + assertThat(metadata.allFields.get("name").isPrimaryKey()).isFalse(); + assertThat(metadata.allFields.get("name").isOptional()).isFalse(); } @Test(expected = ConnectException.class) @@ -235,12 +225,12 @@ public void recordValuePkModeWithValidPkFields() { SIMPLE_STRUCT_SCHEMA ); - assertEquals(Set.of("name"), metadata.keyFieldNames); - assertEquals(Collections.emptySet(), metadata.nonKeyFieldNames); + assertThat(metadata.keyFieldNames).isEqualTo(Set.of("name")); + assertThat(metadata.nonKeyFieldNames).isEqualTo(Collections.emptySet()); - assertEquals(Schema.Type.STRING, metadata.allFields.get("name").schemaType()); - assertTrue(metadata.allFields.get("name").isPrimaryKey()); - assertFalse(metadata.allFields.get("name").isOptional()); + assertThat(metadata.allFields.get("name").schemaType()).isEqualTo(Schema.Type.STRING); + assertThat(metadata.allFields.get("name").isPrimaryKey()).isTrue(); + assertThat(metadata.allFields.get("name").isOptional()).isFalse(); } @Test @@ -261,8 +251,8 @@ public void recordValuePkModeWithPkFieldsAndWhitelistFiltering() { valueSchema ); - assertEquals(List.of("field1"), Lists.newArrayList(metadata.keyFieldNames)); - assertEquals(List.of("field2", "field4"), Lists.newArrayList(metadata.nonKeyFieldNames)); + assertThat(Lists.newArrayList(metadata.keyFieldNames)).isEqualTo(List.of("field1")); + assertThat(Lists.newArrayList(metadata.nonKeyFieldNames)).isEqualTo(List.of("field2", "field4")); } @Test @@ -283,10 +273,8 @@ public void recordValuePkModeWithFieldsInOriginalOrdering() { valueSchema ); - assertEquals( - List.of("field4", "field2", "field1", "field3"), - Lists.newArrayList(metadata.allFields.keySet()) - ); + assertThat(Lists.newArrayList(metadata.allFields.keySet())).isEqualTo( + List.of("field4", "field2", "field1", "field3")); metadata = extract( JdbcSinkConfig.PrimaryKeyMode.RECORD_VALUE, @@ -296,7 +284,7 @@ public void recordValuePkModeWithFieldsInOriginalOrdering() { valueSchema ); - assertEquals(List.of("field4", "field1", "field3"), Lists.newArrayList(metadata.allFields.keySet())); + assertThat(Lists.newArrayList(metadata.allFields.keySet())).isEqualTo(List.of("field4", "field1", "field3")); final var keySchema = SchemaBuilder.struct() @@ -313,14 +301,14 @@ public void recordValuePkModeWithFieldsInOriginalOrdering() { null ); - assertEquals(List.of("field1", "field2", "field3"), Lists.newArrayList(metadata.allFields.keySet())); + assertThat(Lists.newArrayList(metadata.allFields.keySet())).isEqualTo(List.of("field1", "field2", "field3")); } private static FieldsMetadata extract(final JdbcSinkConfig.PrimaryKeyMode pkMode, final List pkFields, final Schema keySchema, final Schema valueSchema) { - return extract(pkMode, pkFields, Collections.emptySet(), keySchema, valueSchema); + return extract(pkMode, pkFields, Collections.emptySet(), keySchema, valueSchema); } private static FieldsMetadata extract(final JdbcSinkConfig.PrimaryKeyMode pkMode, diff --git a/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceConnectorConfigTest.java b/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceConnectorConfigTest.java index 361303a6..abf8508b 100644 --- a/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceConnectorConfigTest.java +++ b/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceConnectorConfigTest.java @@ -17,7 +17,6 @@ package io.aiven.connect.jdbc.source; -import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -42,10 +41,8 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.util.Lists.list; @RunWith(PowerMockRunner.class) @PrepareForTest({Recommender.class}) @@ -58,7 +55,7 @@ public class JdbcSourceConnectorConfigTest { private List results; @Mock private Recommender mockRecommender; - private MockTime time = new MockTime(); + private final MockTime time = new MockTime(); @Before public void setup() throws Exception { @@ -86,42 +83,42 @@ public void cleanup() throws Exception { } @Test - public void testConfigTableNameRecommenderWithoutSchemaOrTableTypes() throws Exception { + public void testConfigTableNameRecommenderWithoutSchemaOrTableTypes() { props.put(JdbcSourceConnectorConfig.MODE_CONFIG, JdbcSourceConnectorConfig.MODE_BULK); props.put(JdbcConfig.CONNECTION_URL_CONFIG, db.getUrl()); configDef = JdbcSourceConnectorConfig.baseConfigDef(); results = configDef.validate(props); - assertWhitelistRecommendations("some_table", "public_table", "private_table", "another_private_table"); - assertBlacklistRecommendations("some_table", "public_table", "private_table", "another_private_table"); + assertWhitelistRecommendations(list("some_table", "public_table", "private_table", "another_private_table")); + assertBlacklistRecommendations(list("some_table", "public_table", "private_table", "another_private_table")); } @Test - public void testConfigTableNameRecommenderWitSchemaAndWithoutTableTypes() throws Exception { + public void testConfigTableNameRecommenderWitSchemaAndWithoutTableTypes() { props.put(JdbcSourceConnectorConfig.MODE_CONFIG, JdbcSourceConnectorConfig.MODE_BULK); props.put(JdbcConfig.CONNECTION_URL_CONFIG, db.getUrl()); props.put(JdbcSourceConnectorConfig.SCHEMA_PATTERN_CONFIG, "PRIVATE_SCHEMA"); configDef = JdbcSourceConnectorConfig.baseConfigDef(); results = configDef.validate(props); - assertWhitelistRecommendations("private_table", "another_private_table"); - assertBlacklistRecommendations("private_table", "another_private_table"); + assertWhitelistRecommendations(list("private_table", "another_private_table")); + assertBlacklistRecommendations(list("private_table", "another_private_table")); } @Test - public void testConfigTableNameRecommenderWithSchemaAndTableTypes() throws Exception { + public void testConfigTableNameRecommenderWithSchemaAndTableTypes() { props.put(JdbcConfig.CONNECTION_URL_CONFIG, db.getUrl()); props.put(JdbcSourceConnectorConfig.SCHEMA_PATTERN_CONFIG, "PRIVATE_SCHEMA"); props.put(JdbcSourceConnectorConfig.TABLE_TYPE_CONFIG, "VIEW"); configDef = JdbcSourceConnectorConfig.baseConfigDef(); results = configDef.validate(props); - assertWhitelistRecommendations(); - assertBlacklistRecommendations(); + assertThat(namedValue(results, JdbcSourceConnectorConfig.TABLE_WHITELIST_CONFIG).recommendedValues()).isEmpty(); + assertThat(namedValue(results, JdbcSourceConnectorConfig.TABLE_BLACKLIST_CONFIG).recommendedValues()).isEmpty(); } @SuppressWarnings("unchecked") @Test public void testCachingRecommender() { - final List results1 = Collections.singletonList((Object) "xyz"); - final List results2 = Collections.singletonList((Object) "123"); + final List results1 = Collections.singletonList("xyz"); + final List results2 = Collections.singletonList("123"); // Set up the mock recommender to be called twice, returning different results each time EasyMock.expect(mockRecommender.validValues(EasyMock.anyObject(String.class), EasyMock.anyObject(Map.class))) .andReturn(results1); @@ -132,65 +129,57 @@ public void testCachingRecommender() { final CachingRecommender recommender = new CachingRecommender(mockRecommender, time, 1000L); - final Map config1 = Collections.singletonMap("k", (Object) "v"); + final Map config1 = Collections.singletonMap("k", "v"); // Populate the cache - assertSame(results1, recommender.validValues("x", config1)); + assertThat(recommender.validValues("x", config1)).isSameAs(results1); // Try the cache before expiration time.sleep(100L); - assertSame(results1, recommender.validValues("x", config1)); + assertThat(recommender.validValues("x", config1)).isSameAs(results1); // Wait for the cache to expire time.sleep(2000L); - assertSame(results2, recommender.validValues("x", config1)); + assertThat(recommender.validValues("x", config1)).isSameAs(results2); PowerMock.verifyAll(); } @Test public void testDefaultConstructedCachedTableValuesReturnsNull() { - final Map config = Collections.singletonMap("k", (Object) "v"); + final Map config = Collections.singletonMap("k", "v"); final CachedRecommenderValues cached = new CachedRecommenderValues(); - assertNull(cached.cachedValue(config, 20L)); + assertThat(cached.cachedValue(config, 20L)).isNull(); } @Test public void testCachedTableValuesReturnsCachedResultWithinExpiryTime() { - final Map config1 = Collections.singletonMap("k", (Object) "v"); - final Map config2 = Collections.singletonMap("k", (Object) "v"); - final List results = Collections.singletonList((Object) "xyz"); + final Map config1 = Collections.singletonMap("k", "v"); + final Map config2 = Collections.singletonMap("k", "v"); + final List results = Collections.singletonList("xyz"); final long expiry = 20L; final CachedRecommenderValues cached = new CachedRecommenderValues(config1, results, expiry); - assertSame(results, cached.cachedValue(config2, expiry - 1L)); + assertThat(cached.cachedValue(config2, expiry - 1L)).isSameAs(results); } @Test public void testCachedTableValuesReturnsNullResultAtOrAfterExpiryTime() { - final Map config1 = Collections.singletonMap("k", (Object) "v"); - final Map config2 = Collections.singletonMap("k", (Object) "v"); - final List results = Collections.singletonList((Object) "xyz"); + final Map config1 = Collections.singletonMap("k", "v"); + final Map config2 = Collections.singletonMap("k", "v"); + final List results = Collections.singletonList("xyz"); final long expiry = 20L; final CachedRecommenderValues cached = new CachedRecommenderValues(config1, results, expiry); - assertNull(cached.cachedValue(config2, expiry)); - assertNull(cached.cachedValue(config2, expiry + 1L)); + assertThat(cached.cachedValue(config2, expiry)).isNull(); + assertThat(cached.cachedValue(config2, expiry + 1L)).isNull(); } @Test public void testCachedTableValuesReturnsNullResultIfConfigurationChanges() { - final Map config1 = Collections.singletonMap("k", (Object) "v"); - final Map config2 = Collections.singletonMap("k", (Object) "zed"); - final List results = Collections.singletonList((Object) "xyz"); + final Map config1 = Collections.singletonMap("k", "v"); + final Map config2 = Collections.singletonMap("k", "zed"); + final List results = Collections.singletonList("xyz"); final long expiry = 20L; final CachedRecommenderValues cached = new CachedRecommenderValues(config1, results, expiry); - assertNull(cached.cachedValue(config2, expiry - 1L)); - assertNull(cached.cachedValue(config2, expiry)); - assertNull(cached.cachedValue(config2, expiry + 1L)); - } - - @SuppressWarnings("unchecked") - protected void assertContains(final Collection actual, final T... expected) { - for (final T e : expected) { - assertTrue(actual.contains(e)); - } - assertEquals(expected.length, actual.size()); + assertThat(cached.cachedValue(config2, expiry - 1L)).isNull(); + assertThat(cached.cachedValue(config2, expiry)).isNull(); + assertThat(cached.cachedValue(config2, expiry + 1L)).isNull(); } protected ConfigValue namedValue(final List values, final String name) { @@ -202,22 +191,13 @@ protected ConfigValue namedValue(final List values, final String na return null; } - @SuppressWarnings("unchecked") - protected void assertRecommendedValues(final ConfigValue value, final T... recommendedValues) { - assertContains(value.recommendedValues(), recommendedValues); + protected void assertWhitelistRecommendations(final List recommendedValues) { + assertThat(namedValue(results, JdbcSourceConnectorConfig.TABLE_WHITELIST_CONFIG).recommendedValues()) + .containsExactlyInAnyOrderElementsOf(recommendedValues); } - @SuppressWarnings("unchecked") - protected void assertWhitelistRecommendations(final T... recommendedValues) { - assertContains( - namedValue(results, JdbcSourceConnectorConfig.TABLE_WHITELIST_CONFIG).recommendedValues(), - recommendedValues); - } - - @SuppressWarnings("unchecked") - protected void assertBlacklistRecommendations(final T... recommendedValues) { - assertContains( - namedValue(results, JdbcSourceConnectorConfig.TABLE_BLACKLIST_CONFIG).recommendedValues(), - recommendedValues); + protected void assertBlacklistRecommendations(final List recommendedValues) { + assertThat(namedValue(results, JdbcSourceConnectorConfig.TABLE_BLACKLIST_CONFIG).recommendedValues()) + .containsExactlyInAnyOrderElementsOf(recommendedValues); } } diff --git a/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceTaskConversionTest.java b/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceTaskConversionTest.java index e34bfd5c..670c1d48 100644 --- a/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceTaskConversionTest.java +++ b/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceTaskConversionTest.java @@ -43,8 +43,7 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; // Tests conversion of data types and schemas. These use the types supported by Derby, which // might not cover everything in the SQL standards and definitely doesn't cover any non-standard @@ -209,16 +208,16 @@ public void testNullableBinary() throws Exception { public void testNumeric() throws Exception { typeConversion("NUMERIC(1)", false, new EmbeddedDerby.Literal("CAST (1 AS NUMERIC)"), - Schema.INT8_SCHEMA, new Byte("1")); + Schema.INT8_SCHEMA, Byte.valueOf("1")); typeConversion("NUMERIC(3)", false, new EmbeddedDerby.Literal("CAST (123 AS NUMERIC)"), - Schema.INT16_SCHEMA, new Short("123")); + Schema.INT16_SCHEMA, Short.valueOf("123")); typeConversion("NUMERIC(5)", false, new EmbeddedDerby.Literal("CAST (12345 AS NUMERIC)"), - Schema.INT32_SCHEMA, new Integer("12345")); + Schema.INT32_SCHEMA, Integer.valueOf("12345")); typeConversion("NUMERIC(10)", false, new EmbeddedDerby.Literal("CAST (1234567890 AS NUMERIC(10))"), - Schema.INT64_SCHEMA, new Long("1234567890")); + Schema.INT64_SCHEMA, Long.valueOf("1234567890")); } @Test @@ -286,7 +285,7 @@ public void testTimestamp() throws Exception { expected.setTimeZone(TimeZone.getTimeZone("UTC")); typeConversion("TIMESTAMP", false, "1977-02-13 23:03:20", Timestamp.builder().build(), - expected.getTime()); + java.sql.Timestamp.from(expected.getTime().toInstant())); } @Test @@ -295,7 +294,7 @@ public void testNullableTimestamp() throws Exception { expected.setTimeZone(TimeZone.getTimeZone("UTC")); typeConversion("TIMESTAMP", true, "1977-02-13 23:03:20", Timestamp.builder().optional().build(), - expected.getTime()); + java.sql.Timestamp.from(expected.getTime().toInstant())); typeConversion("TIMESTAMP", true, null, Timestamp.builder().optional().build(), null); @@ -325,26 +324,26 @@ private void typeConversion(final String sqlType, final boolean nullable, private void validateRecords(final List records, final Schema expectedFieldSchema, final Object expectedValue) { // Validate # of records and object type - assertEquals(1, records.size()); + assertThat(records).hasSize(1); final Object objValue = records.get(0).value(); - assertTrue(objValue instanceof Struct); + assertThat(objValue).isInstanceOf(Struct.class); final Struct value = (Struct) objValue; // Validate schema final Schema schema = value.schema(); - assertEquals(Type.STRUCT, schema.type()); + assertThat(schema.type()).isEqualTo(Type.STRUCT); final List fields = schema.fields(); - assertEquals(1, fields.size()); + assertThat(fields).hasSize(1); final Schema fieldSchema = fields.get(0).schema(); - assertEquals(expectedFieldSchema, fieldSchema); + assertThat(fieldSchema).isEqualTo(expectedFieldSchema); if (expectedValue instanceof byte[]) { - assertTrue(value.get(fields.get(0)) instanceof byte[]); - assertEquals(ByteBuffer.wrap((byte[]) expectedValue), - ByteBuffer.wrap((byte[]) value.get(fields.get(0)))); + assertThat(value.get(fields.get(0))).isInstanceOf(byte[].class); + assertThat(ByteBuffer.wrap((byte[]) value.get(fields.get(0)))) + .isEqualTo(ByteBuffer.wrap((byte[]) expectedValue)); } else { - assertEquals(expectedValue, value.get(fields.get(0))); + assertThat(value.get(fields.get(0))).isEqualTo(expectedValue); } } } diff --git a/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceTaskLifecycleTest.java b/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceTaskLifecycleTest.java index 8649df3b..0ad27ac6 100644 --- a/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceTaskLifecycleTest.java +++ b/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceTaskLifecycleTest.java @@ -36,7 +36,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(PowerMockRunner.class) @PrepareForTest({JdbcSourceTask.class}) @@ -99,15 +99,13 @@ public void testPollInterval() throws Exception { // First poll should happen immediately task.poll(); - assertEquals(startTime, time.milliseconds()); + assertThat(time.milliseconds()).isEqualTo(startTime); // Subsequent polls have to wait for timeout task.poll(); - assertEquals(startTime + JdbcSourceConnectorConfig.POLL_INTERVAL_MS_DEFAULT, - time.milliseconds()); + assertThat(time.milliseconds()).isEqualTo(startTime + JdbcSourceConnectorConfig.POLL_INTERVAL_MS_DEFAULT); task.poll(); - assertEquals(startTime + 2 * JdbcSourceConnectorConfig.POLL_INTERVAL_MS_DEFAULT, - time.milliseconds()); + assertThat(time.milliseconds()).isEqualTo(startTime + 2 * JdbcSourceConnectorConfig.POLL_INTERVAL_MS_DEFAULT); task.stop(); } @@ -129,16 +127,15 @@ public void testSingleUpdateMultiplePoll() throws Exception { db.insert(SINGLE_TABLE_NAME, "id", 2); List records = task.poll(); - assertEquals(startTime, time.milliseconds()); - assertEquals(1, records.size()); + assertThat(time.milliseconds()).isEqualTo(startTime); + assertThat(records).hasSize(1); records = task.poll(); - assertEquals(startTime, time.milliseconds()); - assertEquals(1, records.size()); + assertThat(time.milliseconds()).isEqualTo(startTime); + assertThat(records).hasSize(1); // Subsequent poll should wait for next timeout task.poll(); - assertEquals(startTime + JdbcSourceConnectorConfig.POLL_INTERVAL_MS_DEFAULT, - time.milliseconds()); + assertThat(time.milliseconds()).isEqualTo(startTime + JdbcSourceConnectorConfig.POLL_INTERVAL_MS_DEFAULT); } @@ -155,22 +152,20 @@ public void testMultipleTables() throws Exception { // Both tables should be polled immediately, in order List records = task.poll(); - assertEquals(startTime, time.milliseconds()); - assertEquals(1, records.size()); - assertEquals(SINGLE_TABLE_PARTITION, records.get(0).sourcePartition()); + assertThat(time.milliseconds()).isEqualTo(startTime); + assertThat(records).hasSize(1); + assertThat(records.get(0).sourcePartition()).isEqualTo(SINGLE_TABLE_PARTITION); records = task.poll(); - assertEquals(startTime, time.milliseconds()); - assertEquals(1, records.size()); - assertEquals(SECOND_TABLE_PARTITION, records.get(0).sourcePartition()); + assertThat(time.milliseconds()).isEqualTo(startTime); + assertThat(records).hasSize(1); + assertThat(records.get(0).sourcePartition()).isEqualTo(SECOND_TABLE_PARTITION); // Subsequent poll should wait for next timeout records = task.poll(); - assertEquals(startTime + JdbcSourceConnectorConfig.POLL_INTERVAL_MS_DEFAULT, - time.milliseconds()); + assertThat(time.milliseconds()).isEqualTo(startTime + JdbcSourceConnectorConfig.POLL_INTERVAL_MS_DEFAULT); validatePollResultTable(records, 1, SINGLE_TABLE_NAME); records = task.poll(); - assertEquals(startTime + JdbcSourceConnectorConfig.POLL_INTERVAL_MS_DEFAULT, - time.milliseconds()); + assertThat(time.milliseconds()).isEqualTo(startTime + JdbcSourceConnectorConfig.POLL_INTERVAL_MS_DEFAULT); validatePollResultTable(records, 1, SECOND_TABLE_NAME); } @@ -196,35 +191,33 @@ public void testMultipleTablesMultiplePolls() throws Exception { // Both tables should be polled immediately, in order for (int i = 0; i < 2; i++) { final List records = task.poll(); - assertEquals(startTime, time.milliseconds()); + assertThat(time.milliseconds()).isEqualTo(startTime); validatePollResultTable(records, 1, SINGLE_TABLE_NAME); } for (int i = 0; i < 2; i++) { final List records = task.poll(); - assertEquals(startTime, time.milliseconds()); + assertThat(time.milliseconds()).isEqualTo(startTime); validatePollResultTable(records, 1, SECOND_TABLE_NAME); } // Subsequent poll should wait for next timeout for (int i = 0; i < 2; i++) { final List records = task.poll(); - assertEquals(startTime + JdbcSourceConnectorConfig.POLL_INTERVAL_MS_DEFAULT, - time.milliseconds()); + assertThat(time.milliseconds()).isEqualTo(startTime + JdbcSourceConnectorConfig.POLL_INTERVAL_MS_DEFAULT); validatePollResultTable(records, 1, SINGLE_TABLE_NAME); } for (int i = 0; i < 2; i++) { final List records = task.poll(); - assertEquals(startTime + JdbcSourceConnectorConfig.POLL_INTERVAL_MS_DEFAULT, - time.milliseconds()); + assertThat(time.milliseconds()).isEqualTo(startTime + JdbcSourceConnectorConfig.POLL_INTERVAL_MS_DEFAULT); validatePollResultTable(records, 1, SECOND_TABLE_NAME); } } private static void validatePollResultTable(final List records, final int expected, final String table) { - assertEquals(expected, records.size()); + assertThat(records).hasSize(expected); for (final SourceRecord record : records) { - assertEquals(table, record.sourcePartition().get(JdbcSourceConnectorConstants.TABLE_NAME_KEY)); + assertThat(record.sourcePartition().get(JdbcSourceConnectorConstants.TABLE_NAME_KEY)).isEqualTo(table); } } } diff --git a/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceTaskUpdateTest.java b/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceTaskUpdateTest.java index a8be7d70..00fdfa18 100644 --- a/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceTaskUpdateTest.java +++ b/src/test/java/io/aiven/connect/jdbc/source/JdbcSourceTaskUpdateTest.java @@ -43,11 +43,9 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.entry; // Tests of polling that return data updates, i.e. verifies the different behaviors for getting // incremental data updates from the database @@ -77,11 +75,11 @@ public void testBulkPeriodicLoad() throws Exception { task.start(singleTableConfig()); List records = task.poll(); - assertEquals(Collections.singletonMap(1, 1), countIntValues(records, "id")); + assertThat(countIntValues(records, "id")).containsExactly(entry(1, 1)); assertRecordsTopic(records, TOPIC_PREFIX + SINGLE_TABLE_NAME); records = task.poll(); - assertEquals(Collections.singletonMap(1, 1), countIntValues(records, "id")); + assertThat(countIntValues(records, "id")).containsExactly(entry(1, 1)); assertRecordsTopic(records, TOPIC_PREFIX + SINGLE_TABLE_NAME); db.insert(SINGLE_TABLE_NAME, "id", 2); @@ -89,12 +87,12 @@ public void testBulkPeriodicLoad() throws Exception { final Map twoRecords = new HashMap<>(); twoRecords.put(1, 1); twoRecords.put(2, 1); - assertEquals(twoRecords, countIntValues(records, "id")); + assertThat(countIntValues(records, "id")).isEqualTo(twoRecords); assertRecordsTopic(records, TOPIC_PREFIX + SINGLE_TABLE_NAME); db.delete(SINGLE_TABLE_NAME, new EmbeddedDerby.EqualsCondition(column, 1)); records = task.poll(); - assertEquals(Collections.singletonMap(2, 1), countIntValues(records, "id")); + assertThat(countIntValues(records, "id")).containsExactly(entry(2, 1)); assertRecordsTopic(records, TOPIC_PREFIX + SINGLE_TABLE_NAME); } @@ -135,12 +133,12 @@ public void testTimestampInvalidColumn() throws Exception { @Test public void testManualIncrementing() throws Exception { - manualIncrementingInternal(null, Arrays.asList(0)); + manualIncrementingInternal(null, List.of(0)); } @Test public void testManualIncrementingManualId() throws Exception { - manualIncrementingInternal(-1L, Arrays.asList(0)); + manualIncrementingInternal(-1L, List.of(0)); } @Test @@ -205,12 +203,12 @@ public void testAutoincrement() throws Exception { @Test public void testTimestamp() throws Exception { - timestampInternal(null, Arrays.asList(1)); + timestampInternal(null, List.of(1)); } @Test public void testTimestampManualOffset() throws Exception { - timestampInternal(0L, Arrays.asList(1)); + timestampInternal(0L, List.of(1)); } @Test @@ -403,16 +401,12 @@ public void testTimestampInInvalidTimezone() throws Exception { "modified", "TIMESTAMP NOT NULL", "id", "INT NOT NULL"); - try { - startTask("modified", "id", null, 0L, invalidTimeZoneID, null, null); - fail("A ConfigException should have been thrown"); - } catch (final ConnectException e) { - assertTrue(e.getCause() instanceof ConfigException); - final ConfigException configException = (ConfigException) e.getCause(); - assertThat(configException.getMessage(), - equalTo( - "Invalid value Europe/Invalid for configuration db.timezone: Invalid time zone identifier")); - } + assertThatThrownBy(() -> + startTask("modified", "id", null, 0L, invalidTimeZoneID, null, null)) + .isInstanceOf(ConnectException.class) + .hasCauseInstanceOf(ConfigException.class) + .hasRootCauseMessage( + "Invalid value Europe/Invalid for configuration db.timezone: Invalid time zone identifier"); } @Test @@ -694,10 +688,10 @@ public void testCustomQueryBulk() throws Exception { + "ON (\"test\".\"user_id\" = \"users\".\"user_id\")"); List records = task.poll(); - assertEquals(1, records.size()); + assertThat(records).hasSize(1); Map recordUserIdCounts = new HashMap<>(); recordUserIdCounts.put(1, 1); - assertEquals(recordUserIdCounts, countIntValues(records, "id")); + assertThat(countIntValues(records, "id")).isEqualTo(recordUserIdCounts); assertRecordsTopic(records, TOPIC_PREFIX); assertRecordsSourcePartition(records, QUERY_SOURCE_PARTITION); @@ -706,18 +700,18 @@ public void testCustomQueryBulk() throws Exception { db.insert(SINGLE_TABLE_NAME, "id", 4, "user_id", 2); records = task.poll(); - assertEquals(4, records.size()); + assertThat(records).hasSize(4); recordUserIdCounts = new HashMap<>(); recordUserIdCounts.put(1, 2); recordUserIdCounts.put(2, 2); - assertEquals(recordUserIdCounts, countIntValues(records, "user_id")); + assertThat(countIntValues(records, "user_id")).isEqualTo(recordUserIdCounts); assertRecordsTopic(records, TOPIC_PREFIX); assertRecordsSourcePartition(records, QUERY_SOURCE_PARTITION); } @Test public void testCustomQueryWithTimestamp() throws Exception { - expectInitializeNoOffsets(Arrays.asList(JOIN_QUERY_PARTITION)); + expectInitializeNoOffsets(List.of(JOIN_QUERY_PARTITION)); PowerMock.replayAll(); @@ -776,7 +770,7 @@ private void startTask(final String timestampColumn, final String incrementingCo } private String mode(final String timestampColumn, final String incrementingColumn) { - String mode = null; + final String mode; if (timestampColumn != null && incrementingColumn != null) { mode = JdbcSourceConnectorConfig.MODE_TIMESTAMP_INCREMENTING; } else if (timestampColumn != null) { @@ -822,17 +816,17 @@ private Map taskConfig(final String timestampColumn, final Strin private void verifyIncrementingFirstPoll(final String topic) throws Exception { final List records = task.poll(); - assertEquals(Collections.singletonMap(1, 1), countIntValues(records, "id")); - assertEquals(Collections.singletonMap(1L, 1), countIntIncrementingOffsets(records, "id")); + assertThat(countIntValues(records, "id")).isEqualTo(Collections.singletonMap(1, 1)); + assertThat(countIntIncrementingOffsets(records, "id")).isEqualTo(Collections.singletonMap(1L, 1)); assertIncrementingOffsets(records); assertRecordsTopic(records, topic); } private List verifyMultiTimestampFirstPoll(final String topic) throws Exception { final List records = task.poll(); - assertEquals(1, records.size()); - assertEquals(Collections.singletonMap(1, 1), countIntValues(records, "id")); - assertEquals(Collections.singletonMap(10L, 1), countTimestampValues(records, "created")); + assertThat(records).hasSize(1); + assertThat(countIntValues(records, "id")).containsExactly(entry(1, 1)); + assertThat(countTimestampValues(records, "created")).containsExactly(entry(10L, 1)); assertMultiTimestampOffsets(records); assertRecordsTopic(records, topic); return records; @@ -840,9 +834,9 @@ private List verifyMultiTimestampFirstPoll(final String topic) thr private List verifyTimestampFirstPoll(final String topic) throws Exception { final List records = task.poll(); - assertEquals(1, records.size()); - assertEquals(Collections.singletonMap(1, 1), countIntValues(records, "id")); - assertEquals(Collections.singletonMap(10L, 1), countTimestampValues(records, "modified")); + assertThat(records).hasSize(1); + assertThat(countIntValues(records, "id")).containsExactly(entry(1, 1)); + assertThat(countTimestampValues(records, "modified")).containsExactly(entry(10L, 1)); assertTimestampOffsets(records); assertRecordsTopic(records, topic); return records; @@ -867,13 +861,13 @@ private void verifyPoll(final int numRecords, final String topic) throws Exception { final List records = task.poll(); - assertEquals(numRecords, records.size()); + assertThat(records).hasSize(numRecords); final HashMap valueCounts = new HashMap<>(); for (final T value : values) { valueCounts.put(value, 1); } - assertEquals(valueCounts, countIntValues(records, valueField)); + assertThat(countIntValues(records, valueField)).isEqualTo(valueCounts); if (timestampOffsets) { assertTimestampOffsets(records); @@ -916,7 +910,7 @@ private Map countInts(final List records, final Fi case INCREMENTING_OFFSET: { final TimestampIncrementingOffset offset = TimestampIncrementingOffset.fromMap(record.sourceOffset()); - extracted = (T) (Long) offset.getIncrementingOffset(); + extracted = (T) offset.getIncrementingOffset(); break; } case TIMESTAMP_OFFSET: { @@ -956,7 +950,7 @@ private void assertIncrementingOffsets(final List records) { final long incrementingValue = incrementing instanceof Integer ? (long) (Integer) incrementing : (Long) incrementing; final long offsetValue = TimestampIncrementingOffset.fromMap(record.sourceOffset()).getIncrementingOffset(); - assertEquals(incrementingValue, offsetValue); + assertThat(offsetValue).isEqualTo(incrementingValue); } } @@ -966,7 +960,7 @@ private void assertTimestampOffsets(final List records) { final Timestamp timestampValue = (Timestamp) ((Struct) record.value()).get("modified"); final Timestamp offsetValue = TimestampIncrementingOffset.fromMap(record.sourceOffset()).getTimestampOffset(); - assertEquals(timestampValue, offsetValue); + assertThat(offsetValue).isEqualTo(timestampValue); } } @@ -978,20 +972,20 @@ private void assertMultiTimestampOffsets(final List records) { } final Timestamp offsetValue = TimestampIncrementingOffset.fromMap(record.sourceOffset()).getTimestampOffset(); - assertEquals(timestampValue, offsetValue); + assertThat(offsetValue).isEqualTo(timestampValue); } } private void assertRecordsTopic(final List records, final String topic) { for (final SourceRecord record : records) { - assertEquals(topic, record.topic()); + assertThat(record.topic()).isEqualTo(topic); } } private void assertRecordsSourcePartition(final List records, final Map partition) { for (final SourceRecord record : records) { - assertEquals(partition, record.sourcePartition()); + assertThat(record.sourcePartition()).isEqualTo(partition); } } } diff --git a/src/test/java/io/aiven/connect/jdbc/source/NumericMappingConfigTest.java b/src/test/java/io/aiven/connect/jdbc/source/NumericMappingConfigTest.java index fb0b3e6f..ebdb3101 100644 --- a/src/test/java/io/aiven/connect/jdbc/source/NumericMappingConfigTest.java +++ b/src/test/java/io/aiven/connect/jdbc/source/NumericMappingConfigTest.java @@ -27,7 +27,7 @@ import org.junit.runners.Parameterized; import static io.aiven.connect.jdbc.source.JdbcSourceConnectorConfig.NumericMapping; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(Parameterized.class) public class NumericMappingConfigTest { @@ -70,7 +70,7 @@ public void setup() throws Exception { } @Test - public void testNumericMapping() throws Exception { + public void testNumericMapping() { props.put(JdbcSourceConnectorConfig.CONNECTION_URL_CONFIG, "jdbc:foo:bar"); props.put(JdbcSourceConnectorConfig.MODE_CONFIG, JdbcSourceConnectorConfig.MODE_BULK); props.put(JdbcSourceConnectorConfig.TOPIC_PREFIX_CONFIG, "test-"); @@ -82,6 +82,6 @@ public void testNumericMapping() throws Exception { props.put(JdbcSourceConnectorConfig.NUMERIC_MAPPING_CONFIG, extendedMapping); } final JdbcSourceConnectorConfig config = new JdbcSourceConnectorConfig(props); - assertEquals(expected, NumericMapping.get(config)); + assertThat(NumericMapping.get(config)).isEqualTo(expected); } } diff --git a/src/test/java/io/aiven/connect/jdbc/source/TableMonitorThreadTest.java b/src/test/java/io/aiven/connect/jdbc/source/TableMonitorThreadTest.java index 20c3c18e..d2d54879 100644 --- a/src/test/java/io/aiven/connect/jdbc/source/TableMonitorThreadTest.java +++ b/src/test/java/io/aiven/connect/jdbc/source/TableMonitorThreadTest.java @@ -45,8 +45,8 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Parameterized.class) @@ -211,7 +211,7 @@ public void testDuplicates() throws Exception { tableMonitorThread.join(); if (qualifiedTableNames) { - assertThrows(ConnectException.class, tableMonitorThread::tables); + assertThatThrownBy(tableMonitorThread::tables).isInstanceOf(ConnectException.class); } else { checkTableNames("foo", "bar", "baz", "dup"); } @@ -231,7 +231,7 @@ public void testDuplicateWithUnqualifiedWhitelist() throws Exception { tableMonitorThread.join(); if (qualifiedTableNames) { - assertThrows(ConnectException.class, tableMonitorThread::tables); + assertThatThrownBy(tableMonitorThread::tables).isInstanceOf(ConnectException.class); } else { checkTableNames("dup"); } @@ -251,7 +251,7 @@ public void testDuplicateWithUnqualifiedBlacklist() throws Exception { tableMonitorThread.join(); if (qualifiedTableNames) { - assertThrows(ConnectException.class, tableMonitorThread::tables); + assertThatThrownBy(tableMonitorThread::tables).isInstanceOf(ConnectException.class); } else { checkTableNames("bar", "baz", "dup"); } @@ -332,13 +332,13 @@ public void execute() { final TableId id = new TableId(null, null, expectedTableName); expectedTableIds.add(id); } - assertEquals(expectedTableIds, tableMonitorThread.tables()); + assertThat(tableMonitorThread.tables()).isEqualTo(expectedTableIds); } }; } protected void checkTableIds(final TableId... expectedTables) { - assertEquals(Arrays.asList(expectedTables), tableMonitorThread.tables()); + assertThat(tableMonitorThread.tables()).containsExactly(expectedTables); } protected void expectTableNames(final List expectedTableIds, final Op... operations) diff --git a/src/test/java/io/aiven/connect/jdbc/source/TimestampIncrementingCriteriaTest.java b/src/test/java/io/aiven/connect/jdbc/source/TimestampIncrementingCriteriaTest.java index c50f59b7..ad66e6df 100644 --- a/src/test/java/io/aiven/connect/jdbc/source/TimestampIncrementingCriteriaTest.java +++ b/src/test/java/io/aiven/connect/jdbc/source/TimestampIncrementingCriteriaTest.java @@ -18,7 +18,6 @@ package io.aiven.connect.jdbc.source; import java.math.BigDecimal; -import java.sql.SQLException; import java.time.ZoneOffset; import java.util.Arrays; import java.util.List; @@ -37,7 +36,7 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TimestampIncrementingCriteriaTest { @@ -77,25 +76,25 @@ protected void assertExtractedOffset(final long expected, final Schema schema, f criteria = this.criteria; } final TimestampIncrementingOffset offset = criteria.extractValues(schema, record, null); - assertEquals(expected, offset.getIncrementingOffset().longValue()); + assertThat(offset.getIncrementingOffset()).isEqualTo(expected); } @Test - public void extractIntOffset() throws SQLException { + public void extractIntOffset() { schema = SchemaBuilder.struct().field("id", SchemaBuilder.INT32_SCHEMA).build(); record = new Struct(schema).put("id", 42); assertExtractedOffset(42L, schema, record); } @Test - public void extractLongOffset() throws SQLException { + public void extractLongOffset() { schema = SchemaBuilder.struct().field("id", SchemaBuilder.INT64_SCHEMA).build(); record = new Struct(schema).put("id", 42L); assertExtractedOffset(42L, schema, record); } @Test - public void extractDecimalOffset() throws SQLException { + public void extractDecimalOffset() { final Schema decimalSchema = Decimal.schema(0); schema = SchemaBuilder.struct().field("id", decimalSchema).build(); record = new Struct(schema).put("id", new BigDecimal(42)); @@ -103,7 +102,7 @@ record = new Struct(schema).put("id", new BigDecimal(42)); } @Test(expected = ConnectException.class) - public void extractTooLargeDecimalOffset() throws SQLException { + public void extractTooLargeDecimalOffset() { final Schema decimalSchema = Decimal.schema(0); schema = SchemaBuilder.struct().field("id", decimalSchema).build(); record = new Struct(schema).put( @@ -113,7 +112,7 @@ record = new Struct(schema).put( } @Test(expected = ConnectException.class) - public void extractFractionalDecimalOffset() throws SQLException { + public void extractFractionalDecimalOffset() { final Schema decimalSchema = Decimal.schema(2); schema = SchemaBuilder.struct().field("id", decimalSchema).build(); record = new Struct(schema).put("id", new BigDecimal("42.42")); @@ -121,7 +120,7 @@ record = new Struct(schema).put("id", new BigDecimal("42.42")); } @Test - public void extractWithIncColumn() throws SQLException { + public void extractWithIncColumn() { schema = SchemaBuilder.struct() .field("id", SchemaBuilder.INT32_SCHEMA) .field(TS1_COLUMN.name(), Timestamp.SCHEMA) diff --git a/src/test/java/io/aiven/connect/jdbc/source/TimestampIncrementingOffsetTest.java b/src/test/java/io/aiven/connect/jdbc/source/TimestampIncrementingOffsetTest.java index 22c81978..d2199c00 100644 --- a/src/test/java/io/aiven/connect/jdbc/source/TimestampIncrementingOffsetTest.java +++ b/src/test/java/io/aiven/connect/jdbc/source/TimestampIncrementingOffsetTest.java @@ -22,8 +22,7 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; public class TimestampIncrementingOffsetTest { private final Timestamp ts = new Timestamp(100L); @@ -40,74 +39,71 @@ public void setUp() { final long millis = System.currentTimeMillis(); nanos = new Timestamp(millis); nanos.setNanos((int) (millis % 1000) * 1000000 + 123456); - assertEquals(millis, nanos.getTime()); + assertThat(nanos.getTime()).isEqualTo(millis); nanosOffset = new TimestampIncrementingOffset(nanos, null); } @Test public void testDefaults() { - assertNull(unset.getIncrementingOffset()); - assertNull(unset.getTimestampOffset()); + assertThat(unset.getIncrementingOffset()).isNull(); + assertThat(unset.getTimestampOffset()).isNull(); } @Test public void testToMap() { - assertEquals(0, unset.toMap().size()); - assertEquals(2, tsOnly.toMap().size()); - assertEquals(1, incOnly.toMap().size()); - assertEquals(3, tsInc.toMap().size()); - assertEquals(2, nanosOffset.toMap().size()); + assertThat(unset.toMap()).isEmpty(); + assertThat(tsOnly.toMap()).hasSize(2); + assertThat(incOnly.toMap()).hasSize(1); + assertThat(tsInc.toMap()).hasSize(3); + assertThat(nanosOffset.toMap()).hasSize(2); } @Test public void testGetIncrementingOffset() { - assertNull(unset.getIncrementingOffset()); - assertNull(tsOnly.getIncrementingOffset()); - assertEquals(id, incOnly.getIncrementingOffset().longValue()); - assertEquals(id, tsInc.getIncrementingOffset().longValue()); - assertNull(nanosOffset.getIncrementingOffset()); + assertThat(unset.getIncrementingOffset()).isNull(); + assertThat(tsOnly.getIncrementingOffset()).isNull(); + assertThat(incOnly.getIncrementingOffset().longValue()).isEqualTo(id); + assertThat(tsInc.getIncrementingOffset()).isEqualTo(id); + assertThat(nanosOffset.getIncrementingOffset()).isNull(); } @Test public void testGetTimestampOffset() { - assertNull(unset.getTimestampOffset()); + assertThat(unset.getTimestampOffset()).isNull(); final Timestamp zero = new Timestamp(0); - assertEquals(ts, tsOnly.getTimestampOffset()); - assertEquals(ts, tsOnly.getTimestampOffset()); - assertNull(incOnly.getTimestampOffset()); - assertEquals(ts, tsInc.getTimestampOffset()); - assertEquals(nanos, nanosOffset.getTimestampOffset()); + assertThat(tsOnly.getTimestampOffset()).isEqualTo(ts); + assertThat(tsOnly.getTimestampOffset()).isEqualTo(ts); + assertThat(incOnly.getTimestampOffset()).isNull(); + assertThat(tsInc.getTimestampOffset()).isEqualTo(ts); + assertThat(nanosOffset.getTimestampOffset()).isEqualTo(nanos); } @Test public void testFromMap() { - assertEquals(unset, TimestampIncrementingOffset.fromMap(unset.toMap())); - assertEquals(tsOnly, TimestampIncrementingOffset.fromMap(tsOnly.toMap())); - assertEquals(incOnly, TimestampIncrementingOffset.fromMap(incOnly.toMap())); - assertEquals(tsInc, TimestampIncrementingOffset.fromMap(tsInc.toMap())); - assertEquals(nanosOffset, TimestampIncrementingOffset.fromMap(nanosOffset.toMap())); + assertThat(TimestampIncrementingOffset.fromMap(unset.toMap())).isEqualTo(unset); + assertThat(TimestampIncrementingOffset.fromMap(tsOnly.toMap())).isEqualTo(tsOnly); + assertThat(TimestampIncrementingOffset.fromMap(incOnly.toMap())).isEqualTo(incOnly); + assertThat(TimestampIncrementingOffset.fromMap(tsInc.toMap())).isEqualTo(tsInc); + assertThat(TimestampIncrementingOffset.fromMap(nanosOffset.toMap())).isEqualTo(nanosOffset); } @Test public void testEquals() { - assertEquals(nanosOffset, nanosOffset); - assertEquals( - new TimestampIncrementingOffset(null, null), - new TimestampIncrementingOffset(null, null) - ); - assertEquals(unset, new TimestampIncrementingOffset(null, null)); + assertThat(nanosOffset).isEqualTo(nanosOffset); + assertThat(new TimestampIncrementingOffset(null, null)).isEqualTo(new TimestampIncrementingOffset(null, null)); + assertThat(new TimestampIncrementingOffset(null, null)).isEqualTo(unset); TimestampIncrementingOffset x = new TimestampIncrementingOffset(null, id); - assertEquals(x, incOnly); + assertThat(incOnly).isEqualTo(x); x = new TimestampIncrementingOffset(ts, null); - assertEquals(x, tsOnly); + assertThat(tsOnly).isEqualTo(x); x = new TimestampIncrementingOffset(ts, id); - assertEquals(x, tsInc); + assertThat(tsInc).isEqualTo(x); x = new TimestampIncrementingOffset(nanos, null); - assertEquals(x, nanosOffset); + assertThat(nanosOffset).isEqualTo(x); } } diff --git a/src/test/java/io/aiven/connect/jdbc/util/CachedConnectionProviderTest.java b/src/test/java/io/aiven/connect/jdbc/util/CachedConnectionProviderTest.java index e9ee2eac..da1e40ed 100644 --- a/src/test/java/io/aiven/connect/jdbc/util/CachedConnectionProviderTest.java +++ b/src/test/java/io/aiven/connect/jdbc/util/CachedConnectionProviderTest.java @@ -31,7 +31,8 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; @RunWith(PowerMockRunner.class) @PrepareForTest({CachedConnectionProviderTest.class}) @@ -48,11 +49,8 @@ public void retryTillFailure() throws SQLException { EasyMock.expect(provider.getConnection()).andThrow(new SQLException("test")).times(retries); PowerMock.replayAll(); - try { - connectionProvider.getConnection(); - } catch (final ConnectException ex) { - assertNotNull(ex); - } + assertThatThrownBy(connectionProvider::getConnection) + .isInstanceOf(ConnectException.class); PowerMock.verifyAll(); } @@ -70,7 +68,7 @@ public void retryTillConnect() throws SQLException { .andReturn(connection); PowerMock.replayAll(); - assertNotNull(connectionProvider.getConnection()); + assertThat(connectionProvider.getConnection()).isNotNull(); PowerMock.verifyAll(); } diff --git a/src/test/java/io/aiven/connect/jdbc/util/DatabaseHelper.java b/src/test/java/io/aiven/connect/jdbc/util/DatabaseHelper.java index 1ab96cc0..7ec9efa5 100644 --- a/src/test/java/io/aiven/connect/jdbc/util/DatabaseHelper.java +++ b/src/test/java/io/aiven/connect/jdbc/util/DatabaseHelper.java @@ -39,7 +39,7 @@ public DatabaseHelper(final DatabaseDialect dialect) { this.dialect = dialect; } - public void setUp() throws SQLException, IOException { + public void setUp() throws SQLException { connection = dialect.getConnection(); } diff --git a/src/test/java/io/aiven/connect/jdbc/util/IdentifierRulesTest.java b/src/test/java/io/aiven/connect/jdbc/util/IdentifierRulesTest.java index 3a155f25..78f03c8f 100644 --- a/src/test/java/io/aiven/connect/jdbc/util/IdentifierRulesTest.java +++ b/src/test/java/io/aiven/connect/jdbc/util/IdentifierRulesTest.java @@ -22,8 +22,8 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class IdentifierRulesTest { @@ -38,12 +38,12 @@ public void beforeEach() { @Test public void testParsingWithMultiCharacterQuotes() { rules = new IdentifierRules(".", "'''", "'''"); - assertParts("'''p1'''.'''p2'''.'''p3'''", "p1", "p2", "p3"); - assertParts("'''p1'''.'''p3'''", "p1", "p3"); - assertParts("'''p1'''", "p1"); - assertParts("'''p1.1.2.3'''", "p1.1.2.3"); - assertParts("'''p1.1.2.3.'''", "p1.1.2.3."); - assertParts("", ""); + assertThat(rules.parseQualifiedIdentifier("'''p1'''.'''p2'''.'''p3'''")).containsExactly("p1", "p2", "p3"); + assertThat(rules.parseQualifiedIdentifier("'''p1'''.'''p3'''")).containsExactly("p1", "p3"); + assertThat(rules.parseQualifiedIdentifier("'''p1'''")).containsExactly("p1"); + assertThat(rules.parseQualifiedIdentifier("'''p1.1.2.3'''")).containsExactly("p1.1.2.3"); + assertThat(rules.parseQualifiedIdentifier("'''p1.1.2.3.'''")).containsExactly("p1.1.2.3."); + assertThat(rules.parseQualifiedIdentifier("")).containsExactly(""); assertParsingFailure("'''p1.p2"); // unmatched quote assertParsingFailure("'''p1'''.'''p3'''."); // ends with delim } @@ -51,33 +51,33 @@ public void testParsingWithMultiCharacterQuotes() { @Test public void testParsingWithDifferentLeadingAndTrailingQuotes() { rules = new IdentifierRules(".", "[", "]"); - assertParts("[p1].[p2].[p3]", "p1", "p2", "p3"); - assertParts("[p1].[p3]", "p1", "p3"); - assertParts("[p1]", "p1"); - assertParts("[p1.1.2.3]", "p1.1.2.3"); - assertParts("[p1[.[1.[2.3]", "p1[.[1.[2.3"); - assertParts("", ""); + assertThat(rules.parseQualifiedIdentifier("[p1].[p2].[p3]")).containsExactly("p1", "p2", "p3"); + assertThat(rules.parseQualifiedIdentifier("[p1].[p3]")).containsExactly("p1", "p3"); + assertThat(rules.parseQualifiedIdentifier("[p1]")).containsExactly("p1"); + assertThat(rules.parseQualifiedIdentifier("[p1.1.2.3]")).containsExactly("p1.1.2.3"); + assertThat(rules.parseQualifiedIdentifier("[p1[.[1.[2.3]")).containsExactly("p1[.[1.[2.3"); + assertThat(rules.parseQualifiedIdentifier("")).containsExactly(""); assertParsingFailure("[p1].[p3]."); // ends with delim } @Test public void testParsingWithSingleCharacterQuotes() { rules = new IdentifierRules(".", "'", "'"); - assertParts("'p1'.'p2'.'p3'", "p1", "p2", "p3"); - assertParts("'p1'.'p3'", "p1", "p3"); - assertParts("'p1'", "p1"); - assertParts("'p1.1.2.3'", "p1.1.2.3"); - assertParts("", ""); + assertThat(rules.parseQualifiedIdentifier("'p1'.'p2'.'p3'")).containsExactly("p1", "p2", "p3"); + assertThat(rules.parseQualifiedIdentifier("'p1'.'p3'")).containsExactly("p1", "p3"); + assertThat(rules.parseQualifiedIdentifier("'p1'")).containsExactly("p1"); + assertThat(rules.parseQualifiedIdentifier("'p1.1.2.3'")).containsExactly("p1.1.2.3"); + assertThat(rules.parseQualifiedIdentifier("")).containsExactly(""); assertParsingFailure("'p1'.'p3'."); // ends with delim } @Test public void testParsingWithoutQuotes() { rules = new IdentifierRules(".", "'", "'"); - assertParts("p1.p2.p3", "p1", "p2", "p3"); - assertParts("p1.p3", "p1", "p3"); - assertParts("p1", "p1"); - assertParts("", ""); + assertThat(rules.parseQualifiedIdentifier("p1.p2.p3")).containsExactly("p1", "p2", "p3"); + assertThat(rules.parseQualifiedIdentifier("p1.p3")).containsExactly("p1", "p3"); + assertThat(rules.parseQualifiedIdentifier("p1")).containsExactly("p1"); + assertThat(rules.parseQualifiedIdentifier("")).containsExactly(""); assertParsingFailure("'p1'.'p3'."); // ends with delim assertParsingFailure("p1.p3."); // ends with delim } @@ -85,28 +85,15 @@ public void testParsingWithoutQuotes() { @Test public void testParsingWithUnsupportedQuotes() { rules = new IdentifierRules(".", " ", " "); - assertParts("p1.p2.p3", "p1", "p2", "p3"); - assertParts("p1.p3", "p1", "p3"); - assertParts("p1", "p1"); - assertParts("", ""); - } - - protected void assertParts(final String fqn, final String... expectedParts) { - parts = rules.parseQualifiedIdentifier(fqn); - assertEquals(expectedParts.length, parts.size()); - int index = 0; - for (final String expectedPart : expectedParts) { - assertEquals(expectedPart, parts.get(index++)); - } + assertThat(rules.parseQualifiedIdentifier("p1.p2.p3")).containsExactly("p1", "p2", "p3"); + assertThat(rules.parseQualifiedIdentifier("p1.p3")).containsExactly("p1", "p3"); + assertThat(rules.parseQualifiedIdentifier("p1")).containsExactly("p1"); + assertThat(rules.parseQualifiedIdentifier("")).containsExactly(""); } protected void assertParsingFailure(final String fqn) { - try { - parts = rules.parseQualifiedIdentifier(fqn); - fail("expected parsing error"); - } catch (final IllegalArgumentException e) { - // success - } + assertThatThrownBy(() -> rules.parseQualifiedIdentifier(fqn)) + .as("expected parsing error") + .isInstanceOf(IllegalArgumentException.class); } - } diff --git a/src/test/java/io/aiven/connect/jdbc/util/TimeZoneValidatorTest.java b/src/test/java/io/aiven/connect/jdbc/util/TimeZoneValidatorTest.java index 33b2261c..b2d4fee3 100644 --- a/src/test/java/io/aiven/connect/jdbc/util/TimeZoneValidatorTest.java +++ b/src/test/java/io/aiven/connect/jdbc/util/TimeZoneValidatorTest.java @@ -23,6 +23,8 @@ import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + public class TimeZoneValidatorTest { @Test @@ -45,13 +47,15 @@ public void testTimeZoneNotSpecified() { TimeZoneValidator.INSTANCE.ensureValid("db.timezone", null); } - @Test(expected = ConfigException.class) + @Test public void testInvalidTimeZone() { - TimeZoneValidator.INSTANCE.ensureValid("db.timezone", "invalid"); + assertThatThrownBy(() -> TimeZoneValidator.INSTANCE.ensureValid("db.timezone", "invalid")) + .isInstanceOf(ConfigException.class); } - @Test(expected = ConfigException.class) + @Test public void testEmptyTimeZone() { - TimeZoneValidator.INSTANCE.ensureValid("db.timezone", ""); + assertThatThrownBy(() -> TimeZoneValidator.INSTANCE.ensureValid("db.timezone", "")) + .isInstanceOf(ConfigException.class); } }