src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
SeedExtractor { public Seeds extract() { Select stmt = null; try { stmt = (Select) CCJSqlParserUtil.parse(sql); } catch (JSQLParserException e) { throw new RuntimeException(e); } Seeds seeds = new Seeds(); stmt.getSelectBody().accept(new SeedVisitor(seeds)); return seeds; } SeedExtractor(String sql); Seeds extract(); } | @Test public void extractNothing() { Seeds seeds = new SeedExtractor("select * from table where age = age2").extract(); Assert.assertTrue(seeds.getLongs().isEmpty()); Assert.assertTrue(seeds.getStrings().isEmpty()); Assert.assertTrue(seeds.getDoubles().isEmpty()); seeds = new SeedExtractor("select * from table").extract(); Assert.assertTrue(seeds.getLongs().isEmpty()); Assert.assertTrue(seeds.getStrings().isEmpty()); Assert.assertTrue(seeds.getDoubles().isEmpty()); }
@Test public void extractBetween() { Seeds seeds = new SeedExtractor("select * from table where age between 15 and 25").extract(); Assert.assertTrue(seeds.getLongs().contains("15")); Assert.assertTrue(seeds.getLongs().contains("25")); }
@Test public void extractFromSubquery() { Seeds seeds = new SeedExtractor("SELECT (SELECT MAX(Type) FROM Product_Detail WHERE Name = 'A') Subinfo, Product FROM Products").extract(); Assert.assertTrue(seeds.getStrings().contains("A")); }
@Test public void extractInt() { Seeds seeds = new SeedExtractor("select * from table where age = 15").extract(); Assert.assertTrue(seeds.getLongs().contains("15")); }
@Test public void extractComparisons() { Seeds seeds = new SeedExtractor("select * from table where age = 15 and age < 10 and age > 25 and age <= 30 and age >= 40 and age <> 50").extract(); Assert.assertTrue(seeds.getLongs().contains("10")); Assert.assertTrue(seeds.getLongs().contains("15")); Assert.assertTrue(seeds.getLongs().contains("25")); Assert.assertTrue(seeds.getLongs().contains("30")); Assert.assertTrue(seeds.getLongs().contains("40")); Assert.assertTrue(seeds.getLongs().contains("50")); }
@Test public void extractDouble() { Seeds seeds = new SeedExtractor("select * from table where age > 15.0").extract(); Assert.assertTrue(seeds.getDoubles().contains("15.0")); }
@Test public void extractStrings() { Seeds seeds = new SeedExtractor("select * from table where name = 'mauricio'").extract(); Assert.assertTrue(seeds.getStrings().contains("mauricio")); }
@Test public void extractStringsAndInts() { Seeds seeds = new SeedExtractor("select * from table where name = 'mauricio' and age = 20").extract(); Assert.assertTrue(seeds.getStrings().contains("mauricio")); Assert.assertTrue(seeds.getLongs().contains("20")); }
@Test public void extractSubQueries() { Seeds seeds = new SeedExtractor("select * from table where name = (select name from t2 where name = 'mauricio') and age = 10").extract(); Assert.assertTrue(seeds.getStrings().contains("mauricio")); Assert.assertTrue(seeds.getLongs().contains("10")); }
@Test public void extractLike() { Seeds seeds = new SeedExtractor("select * from table where name like '%mauricio%aniche'").extract(); Assert.assertTrue(seeds.getStrings().contains("%mauricio%aniche")); }
@Test public void extractIn() { Seeds seeds = new SeedExtractor("select * from table where age in (10, 15)").extract(); Assert.assertTrue(seeds.getLongs().contains("10")); Assert.assertTrue(seeds.getLongs().contains("15")); }
@Test public void extractArithmetic() { Seeds seeds = new SeedExtractor("select * from table where age = age + 10 + 15 - 5 / 2").extract(); Assert.assertTrue(seeds.getLongs().contains("10")); Assert.assertTrue(seeds.getLongs().contains("15")); Assert.assertTrue(seeds.getLongs().contains("5")); Assert.assertTrue(seeds.getLongs().contains("2")); } |
SqlSecurer { public String getSecureSql() { sql = sql.replaceAll("(?i)(?!`)([\\s\\.]?)primary([\\s\\.?])(?!`)", "$1`primary`$2"); sql = sql.replaceAll("(?i)AS '(.*?)'", "AS \"$1\""); sql = sql.replaceAll("(?i)([\\s(])DATE\\((.*?)\\)", "$1TIMESTAMP($2)"); sql = sql.replaceAll("(?i)\\sFOR UPDATE", ""); sql = sql.replaceAll("(?i)\\s=\\sNULL", " IS NULL"); sql = sql.replaceAll("(?i)\\s!=\\sNULL", " IS NOT NULL"); sql = sql.replaceAll("(?i)\\s<>\\sNULL", " IS NOT NULL"); Select stmt = null; try { stmt = (Select) CCJSqlParserUtil.parse(sql); } catch (JSQLParserException e) { throw new RuntimeException(e); } stmt.getSelectBody().accept(new SqlSecurerVisitor()); return stmt.toString(); } SqlSecurer(String sql); String getSecureSql(); } | @Test public void secureSelectAllQuery() { String sql = new SqlSecurer("SELECT * FROM Table").getSecureSql(); Assert.assertEquals(sql, "SELECT * FROM \"Table\""); }
@Test public void secureSelectColumnsQuery() { String sql = new SqlSecurer("SELECT Column1, Column2, Column3 FROM Table").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Column1\", \"Column2\", \"Column3\" FROM \"Table\""); }
@Test public void secureColumnAliasQuery() { String sql = new SqlSecurer("SELECT Column1 AS col1, Column2 AS col2, Column3 FROM Table").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Column1\" AS \"col1\", \"Column2\" AS \"col2\", \"Column3\" FROM \"Table\""); }
@Test public void secureSelectTableColumnsQuery() { String sql = new SqlSecurer("SELECT Table.Column1, Table.Column2, Table.Column3 FROM Table").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Table\".\"Column1\", \"Table\".\"Column2\", \"Table\".\"Column3\" FROM \"Table\""); }
@Test public void secureSelectTableAllColumnsQuery() { String sql = new SqlSecurer("SELECT Table.* FROM Table").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Table\".* FROM \"Table\""); }
@Test public void secureSelectTableAliasColumnsQuery() { String sql = new SqlSecurer("SELECT t1.Column1, t1.Column2, t1.Column3 FROM Table AS t1").getSecureSql(); Assert.assertEquals(sql, "SELECT \"t1\".\"Column1\", \"t1\".\"Column2\", \"t1\".\"Column3\" FROM \"Table\" AS \"t1\""); }
@Test public void secureSecureQuery() { String sql = new SqlSecurer("SELECT \"COLUMN1\", \"COLUMN2\", \"COLUMN3\" FROM \"Table\"").getSecureSql(); Assert.assertEquals(sql, "SELECT \"COLUMN1\", \"COLUMN2\", \"COLUMN3\" FROM \"Table\""); }
@Test public void secureWhereColumnsQuery() { String sql = new SqlSecurer("SELECT Column1 FROM Table WHERE Column2 = 10 AND 'Column3' = column3").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Column1\" FROM \"Table\" WHERE \"Column2\" = 10 AND 'Column3' = \"column3\""); }
@Test public void secureAggregateColumnsQuery() { String sql = new SqlSecurer("SELECT SUM(column1) FROM Table").getSecureSql(); Assert.assertEquals(sql, "SELECT SUM(\"column1\") FROM \"Table\""); }
@Test public void secureAggregateHavingColumnsQuery() { String sql = new SqlSecurer("SELECT SUM(column1) FROM Table HAVING AVG(column2) > 50").getSecureSql(); Assert.assertEquals(sql, "SELECT SUM(\"column1\") FROM \"Table\" HAVING AVG(\"column2\") > 50"); }
@Test public void secureSubqueryColumnsQuery() { String sql = new SqlSecurer("SELECT * FROM (SELECT column1, Column2 FROM Table) t1").getSecureSql(); Assert.assertEquals(sql, "SELECT * FROM (SELECT \"column1\", \"Column2\" FROM \"Table\") \"t1\""); }
@Test public void secureBackticksKeywordQuery() { String sql = new SqlSecurer("SELECT `Column1`, `primary` FROM Table").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Column1\", \"primary\" FROM \"Table\""); }
@Test public void securePrimaryNoBackticksQuery() { String sql = new SqlSecurer("SELECT table.primary FROM table").getSecureSql(); Assert.assertEquals(sql, "SELECT \"table\".\"primary\" FROM \"table\""); }
@Test public void securePrimaryPartOfWordQuery() { String sql = new SqlSecurer("SELECT primary_word FROM table").getSecureSql(); Assert.assertEquals(sql, "SELECT \"primary_word\" FROM \"table\""); }
@Test public void securePrimaryPartOfWord2Query() { String sql = new SqlSecurer("SELECT the_primary_word FROM table").getSecureSql(); Assert.assertEquals(sql, "SELECT \"the_primary_word\" FROM \"table\""); }
@Test public void secureRemoveOrderBy() { String sql = new SqlSecurer("SELECT Column1 FROM Table ORDER BY column1").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Column1\" FROM \"Table\""); }
@Test public void leaveInnerOrderBy() { String sql = new SqlSecurer("SELECT Column1 FROM Table WHERE column2 = (SELECT c FROM t ORDER BY c) ORDER BY Column1").getSecureSql(); Assert.assertEquals("SELECT \"Column1\" FROM \"Table\" WHERE \"column2\" = (SELECT \"c\" FROM \"t\" ORDER BY \"c\")", sql); }
@Test public void secureAliasSingleQuotes() { String sql = new SqlSecurer("SELECT Column1 AS 'Column' FROM Table").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Column1\" AS \"Column\" FROM \"Table\""); }
@Test public void secureAliasSingleQuotesTwice() { String sql = new SqlSecurer("SELECT Column1 AS 'Column', Column2 AS 'ColumnTwo' FROM Table").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Column1\" AS \"Column\", \"Column2\" AS \"ColumnTwo\" FROM \"Table\""); }
@Test public void secureExists() { String sql = new SqlSecurer("SELECT Column1 AS 'Column', Column2 AS 'ColumnTwo' FROM Table WHERE EXISTS (SELECT col FROM tab)").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Column1\" AS \"Column\", \"Column2\" AS \"ColumnTwo\" FROM \"Table\" WHERE EXISTS (SELECT \"col\" FROM \"tab\")"); }
@Test public void secureColumnCondition() { String sql = new SqlSecurer("SELECT Column1 AS 'Column', Column2 AS 'ColumnTwo' FROM Table WHERE Column1").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Column1\" AS \"Column\", \"Column2\" AS \"ColumnTwo\" FROM \"Table\" WHERE \"Column1\" = 1"); }
@Test public void secureColumnCondition2() { String sql = new SqlSecurer("SELECT Column1 AS 'Column', Column2 AS 'ColumnTwo' FROM Table WHERE Column1 = 2 AND Column1 OR Column3").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Column1\" AS \"Column\", \"Column2\" AS \"ColumnTwo\" FROM \"Table\" WHERE \"Column1\" = 2 AND \"Column1\" = 1 OR \"Column3\" = 1"); }
@Test public void secureGroupBy() { String sql = new SqlSecurer("SELECT Column1 AS 'Column', Column2 AS 'ColumnTwo' FROM Table GROUP BY Column1, Column2").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Column1\" AS \"Column\", \"Column2\" AS \"ColumnTwo\" FROM \"Table\" GROUP BY \"Column1\", \"Column2\""); }
@Test public void secureDatefunction() { String sql = new SqlSecurer("SELECT Column1 AS 'Column', Column2 AS 'ColumnTwo' FROM Table WHERE date(column1) <= date('2015-02-01')").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Column1\" AS \"Column\", \"Column2\" AS \"ColumnTwo\" FROM \"Table\" WHERE TIMESTAMP(\"column1\") <= TIMESTAMP('2015-02-01')"); }
@Test public void secureDatefunction2() { String sql = new SqlSecurer("SELECT Column1 AS 'Column', Column2 AS 'ColumnTwo' FROM Table WHERE (date(column1) <= date('2015-02-01'))").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Column1\" AS \"Column\", \"Column2\" AS \"ColumnTwo\" FROM \"Table\" WHERE (TIMESTAMP(\"column1\") <= TIMESTAMP('2015-02-01'))"); }
@Test public void secureCurdatefunction() { String sql = new SqlSecurer("SELECT Column1 AS 'Column', Column2 AS 'ColumnTwo' FROM Table WHERE date(column1) <= CURDATE()").getSecureSql(); Assert.assertEquals(sql, "SELECT \"Column1\" AS \"Column\", \"Column2\" AS \"ColumnTwo\" FROM \"Table\" WHERE TIMESTAMP(\"column1\") <= CURDATE()"); }
@Test public void secureForUpdate() { String sql = new SqlSecurer("SELECT column1 FROM table FOR UPDATE").getSecureSql(); Assert.assertEquals(sql, "SELECT \"column1\" FROM \"table\""); }
@Test public void secureEqualsNull() { String sql = new SqlSecurer("SELECT column1 FROM table WHERE column2 = NULL").getSecureSql(); Assert.assertEquals(sql, "SELECT \"column1\" FROM \"table\" WHERE \"column2\" IS NULL"); }
@Test public void secureNotEqualsNull() { String sql = new SqlSecurer("SELECT column1 FROM table WHERE column2 != NULL").getSecureSql(); Assert.assertEquals(sql, "SELECT \"column1\" FROM \"table\" WHERE \"column2\" IS NOT NULL"); }
@Test public void secureNotEqualsNull2() { String sql = new SqlSecurer("SELECT column1 FROM table WHERE column2 <> NULL").getSecureSql(); Assert.assertEquals(sql, "SELECT \"column1\" FROM \"table\" WHERE \"column2\" IS NOT NULL"); }
@Test public void leaveBinaryOpNull() { String sql = new SqlSecurer("SELECT column1 FROM table WHERE column2 >= NULL").getSecureSql(); Assert.assertEquals(sql, "SELECT \"column1\" FROM \"table\" WHERE \"column2\" >= NULL"); } |
DBTypeSelector { public DBType create(int dataType, int length) { switch (dataType) { case Types.DOUBLE: return new DBDouble(); case Types.REAL: return new DBDouble("REAL"); case Types.DECIMAL: return new DBDouble("DECIMAL"); case Types.INTEGER: return new DBInteger(); case Types.SMALLINT: return new DBInteger("SMALLINT"); case Types.TINYINT: return new DBInteger("TINYINT"); case Types.BIGINT: return new DBInteger(); case Types.VARCHAR: return new DBString(length); case Types.NVARCHAR: return new DBString(length, "NVARCHAR"); case Types.LONGVARCHAR: return new DBString(EvoSQLConfiguration.MAX_STRING_LENGTH, "LONGVARCHAR"); case Types.LONGNVARCHAR: return new DBString(EvoSQLConfiguration.MAX_STRING_LENGTH, "LONGNVARCHAR"); case Types.CHAR: return new DBString(length, "CHAR(" + length + ")"); case Types.NCHAR: return new DBString(length, "NCHAR"); case Types.BIT: return new DBBoolean("BIT"); case Types.BOOLEAN: return new DBBoolean("BOOLEAN"); case Types.DATE: return new DBDate(); case Types.TIME: return new DBTime(); case Types.TIMESTAMP: return new DBDateTime("TIMESTAMP"); case Types.NUMERIC: return new DBDouble("NUMERIC(18, 6)"); case Types.ARRAY: throw new UnsupportedOperationException("The ARRAY data type is currently not supported by EvoSQL."); default: throw new UnsupportedOperationException("This database type is not currently supported: " + dataType); } } DBType create(int dataType, int length); } | @Test void dbBooleanTest() { assertThat(dbTypeSelector.create(Types.BIT, 0)).isInstanceOf(DBBoolean.class); assertThat(dbTypeSelector.create(Types.BOOLEAN, 0)).isInstanceOf(DBBoolean.class); }
@Test void dbDateTest() { assertThat(dbTypeSelector.create(Types.DATE, 0)).isInstanceOf(DBDate.class); }
@Test void dbDateTimeTest() { assertThat(dbTypeSelector.create(Types.TIMESTAMP, 0)).isInstanceOf(DBDateTime.class); }
@Test void dbDoubleTest() { assertThat(dbTypeSelector.create(Types.DOUBLE, 0)).isInstanceOf(DBDouble.class); assertThat(dbTypeSelector.create(Types.REAL, 0)).isInstanceOf(DBDouble.class); assertThat(dbTypeSelector.create(Types.DECIMAL, 0)).isInstanceOf(DBDouble.class); }
@Test void dbIntegerTest() { assertThat(dbTypeSelector.create(Types.INTEGER, 0)).isInstanceOf(DBInteger.class); assertThat(dbTypeSelector.create(Types.SMALLINT, 0)).isInstanceOf(DBInteger.class); assertThat(dbTypeSelector.create(Types.TINYINT, 0)).isInstanceOf(DBInteger.class); assertThat(dbTypeSelector.create(Types.BIGINT, 0)).isInstanceOf(DBInteger.class); }
@Test void dbStringTest() { assertThat(dbTypeSelector.create(Types.VARCHAR, 16)).isInstanceOf(DBString.class); assertThat(dbTypeSelector.create(Types.NVARCHAR, 16)).isInstanceOf(DBString.class); assertThat(dbTypeSelector.create(Types.LONGVARCHAR, 16)).isInstanceOf(DBString.class); assertThat(dbTypeSelector.create(Types.LONGNVARCHAR, 16)).isInstanceOf(DBString.class); assertThat(dbTypeSelector.create(Types.CHAR, 16)).isInstanceOf(DBString.class); assertThat(dbTypeSelector.create(Types.NCHAR, 16)).isInstanceOf(DBString.class); }
@Test void dbTimeTest() { assertThat(dbTypeSelector.create(Types.TIME, 0)).isInstanceOf(DBTime.class); }
@Test void dbArrayTest() { assertThatThrownBy(() -> dbTypeSelector.create(Types.ARRAY, 0)) .isInstanceOf(UnsupportedOperationException.class) .hasMessageContaining("ARRAY"); }
@Test void dbOtherTest() { assertThatThrownBy(() -> dbTypeSelector.create(Types.OTHER, 0)) .isInstanceOf(UnsupportedOperationException.class) .hasMessageContaining("This database type"); assertThatThrownBy(() -> dbTypeSelector.create(Types.JAVA_OBJECT, 0)) .isInstanceOf(UnsupportedOperationException.class) .hasMessageContaining("This database type"); } |
DBDouble implements DBType { static String truncateDecimals(double value, int decimals) { StringBuilder builder = new StringBuilder("0"); if (decimals > 0) builder.append('.'); for (int i = 0; i < decimals; i++) builder.append('#'); DecimalFormat df = new DecimalFormat(builder.toString(), defaultDecimalFormatSymbols); df.setRoundingMode(RoundingMode.FLOOR); return df.format(value); } DBDouble(); DBDouble(String typeString); @Override String generateRandom(boolean nullable); @Override String mutate(String currentValue, boolean nullable); @Override boolean hasSeed(Seeds seeds); @Override String generateFromSeed(Seeds seeds); @Override String getTypeString(); @Override String getNormalizedTypeString(); } | @Test void truncateDecimals() { assertThat(DBDouble.truncateDecimals(3, 4)).isEqualTo("3"); assertThat(DBDouble.truncateDecimals(4.52, 1)).isEqualTo("4.5"); assertThat(DBDouble.truncateDecimals(4.58, 1)).isEqualTo("4.5"); assertThat(DBDouble.truncateDecimals(5.1, 3)).isEqualTo("5.1"); }
@Test void truncateDecimals_locale() { Locale currentLocale = Locale.getDefault(); Locale.setDefault(Locale.GERMAN); DecimalFormat decimalFormat = new DecimalFormat(); assertThat(decimalFormat.format(50.4)).isEqualTo("50,4"); assertThat(DBDouble.truncateDecimals(50.4, 4)).isEqualTo("50.4"); Locale.setDefault(currentLocale); } |
Fixture implements Cloneable { public String prettyPrint() { StringBuilder prettyFixture = new StringBuilder(); for (FixtureTable table : tables) { prettyFixture.append("-- Table: " + table.getName() + "\n"); Iterator<FixtureRow> it = table.getRows().iterator(); int rowCount = 1; while (it.hasNext()) { FixtureRow row = it.next(); prettyFixture.append(" Row #" + rowCount + ": "); for (Map.Entry<String, String> kv : row.getValues().entrySet()) { prettyFixture.append(kv.getKey() + "='" + kv.getValue() + "',"); } prettyFixture.append("\n"); rowCount++; } prettyFixture.append("\n"); } return prettyFixture.toString().trim(); } Fixture(List<FixtureTable> tables); List<FixtureTable> getTables(); FixtureTable getTable(TableSchema ts); void removeTable(int idx); void addTable(FixtureTable table); @Override String toString(); List<String> getInsertStatements(); List<String> getInsertStatements(String excludeTableName, int excludeIndex); FixtureFitness getFitness(); void setFitness(FixtureFitness fitness); void unsetFitness(); void remove(String tableName, int index); Fixture copy(); String prettyPrint(); int qtyOfTables(); FixtureTable getTable(int index); FixtureTable getTable(String tableName); @Override boolean equals(Object o); @Override int hashCode(); boolean isChanged(); void setChanged(boolean changed); int getNumberOfTables(); } | @Test public void prettyPrint() { TableSchema t1Schema = Mockito.mock(TableSchema.class); Mockito.when(t1Schema.getName()).thenReturn("t1"); FixtureRow r1 = new FixtureRow("t1", t1Schema); r1.set("c1", "1"); r1.set("c2", "Mauricio"); FixtureRow r2 = new FixtureRow("t1", t1Schema); r2.set("c1", "2"); r2.set("c2", "Jeroen"); TableSchema t2Schema = Mockito.mock(TableSchema.class); Mockito.when(t2Schema.getName()).thenReturn("t2"); FixtureRow r3 = new FixtureRow("t2", t2Schema); r3.set("c3", "10.0"); r3.set("c4", "Mozhan"); FixtureRow r4 = new FixtureRow("t2", t2Schema); r4.set("c3", "25.5"); r4.set("c4", "Annibale"); List<FixtureTable> tables = Arrays.asList( new FixtureTable(t1Schema, Arrays.asList(r1, r2)), new FixtureTable(t2Schema, Arrays.asList(r3, r4))); Fixture fixture = new Fixture(tables); Assert.assertEquals( "-- Table: t1\n" + " Row #1: c1='1',c2='Mauricio',\n" + " Row #2: c1='2',c2='Jeroen',\n" + "\n" + "-- Table: t2\n" + " Row #1: c3='10.0',c4='Mozhan',\n" + " Row #2: c3='25.5',c4='Annibale',", fixture.prettyPrint()); } |
Pipeline { public void execute() { Result queryRunnerResult = queryRunner.runQuery(sqlQuery, connectionData); Map<Generator, List<Output>> outputCache = new HashMap<>(); for (ResultProcessor rp : resultProcessors) { List<Output> generatedOutputs; if (outputCache.containsKey(rp.getGenerator())) { generatedOutputs = outputCache.get(rp.getGenerator()); } else { generatedOutputs = rp.getGenerator() .generate(queryRunnerResult, rp.getVendorOptions()); outputCache.put(rp.getGenerator(), generatedOutputs); } rp.getOutputConsumer().consumeOutput(generatedOutputs); } } void execute(); } | @Test @DisplayName("Methods should not be called more than once") void pipelineTest() { final QueryRunner queryRunner = mock(QueryRunner.class); final String sql = "Select * From any;"; final ConnectionData connectionData = new ConnectionData("", "", "", ""); final Result result = mock(Result.class); when(queryRunner.runQuery(sql, connectionData)).thenReturn(result); final Generator generator = mock(Generator.class); final VendorOptions vendorOptions = new PostgreSQLOptions(); final List<Output> outputs = Arrays.asList(new Output("1", "one"), new Output("2", "two")); when(generator.generate(result, vendorOptions)).thenReturn(outputs); final OutputConsumer outputConsumer = mock(OutputConsumer.class); Pipeline p = Pipeline.builder() .queryRunner(queryRunner) .connectionData(connectionData) .sqlQuery(sql) .resultProcessor(new Pipeline.ResultProcessor(generator, vendorOptions, outputConsumer)) .build(); p.execute(); verify(queryRunner, times(1)).runQuery(sql, connectionData); verify(generator, times(1)).generate(result, vendorOptions); verify(outputConsumer, times(1)).consumeOutput(outputs); }
@Test @DisplayName("The same generator should be called once") void generatorCacheTest() { final QueryRunner queryRunner = mock(QueryRunner.class); final String sql = "Select * From any;"; final ConnectionData connectionData = new ConnectionData("", "", "", ""); final Result result = mock(Result.class); when(queryRunner.runQuery(sql, connectionData)).thenReturn(result); final Generator generator = mock(Generator.class); final VendorOptions vendorOptions = new PostgreSQLOptions(); final List<Output> outputs = Arrays.asList(new Output("1", "one"), new Output("2", "two")); when(generator.generate(result, vendorOptions)).thenReturn(outputs); final OutputConsumer outputConsumer1 = mock(OutputConsumer.class); final OutputConsumer outputConsumer2 = mock(OutputConsumer.class); Pipeline p = Pipeline.builder() .queryRunner(queryRunner) .connectionData(connectionData) .sqlQuery(sql) .resultProcessor(new Pipeline.ResultProcessor(generator, vendorOptions, outputConsumer1)) .resultProcessor(new Pipeline.ResultProcessor(generator, vendorOptions, outputConsumer2)) .build(); p.execute(); verify(queryRunner, times(1)).runQuery(sql, connectionData); verify(generator, times(1)).generate(result, vendorOptions); verify(outputConsumer1, times(1)).consumeOutput(outputs); verify(outputConsumer2, times(1)).consumeOutput(outputs); } |
JUnitGeneratorHelper { public MethodSpec buildRunSqlImplementation() { MethodSpec.Builder runSql = MethodSpec.methodBuilder(METHOD_RUN_SQL) .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(RETURN_TYPE_RUN_SQL) .addParameter(String.class, "query") .addParameter(TypeName.BOOLEAN, "isUpdate") .addException(SQLException.class) .addJavadoc("Executes an SQL query on the database.\n\n" + "@param query The query to execute.\n" + "@param isUpdate Whether the query is a data modification statement.\n\n" + "@returns The resulting table, or null if the query is an update.\n"); runSql.addStatement( "$T connection = $T.getConnection($L, $L, $L)", Connection.class, DriverManager.class, FIELD_DB_JDBC_URL, FIELD_DB_USER, FIELD_DB_PASSWORD) .addStatement("$T statement = connection.createStatement()", Statement.class) .beginControlFlow("if (isUpdate == true)") .addStatement("statement.executeUpdate(query)") .addStatement("return null") .nextControlFlow("else") .addStatement("$T tableStructure = new $T()", RETURN_TYPE_RUN_SQL, RETURN_TYPE_RUN_SQL) .addStatement("$T resultSet = statement.executeQuery(query)", ResultSet.class) .addStatement("$T columns = $L(resultSet)", ParameterizedTypeName.get(List.class, String.class), METHOD_GET_RESULT_COLUMNS) .beginControlFlow("while (resultSet.next())") .addStatement("$T values = new $T<>()", ParameterizedTypeName.get(HashMap.class, String.class, String.class), HashMap.class) .beginControlFlow("for (String column : columns)") .addStatement("Object value = resultSet.getObject(column)") .addStatement("values.put(column, value != null ? value.toString() : \"NULL\")") .endControlFlow() .addStatement("tableStructure.add(values)") .endControlFlow() .addStatement("return tableStructure") .endControlFlow(); return runSql.build(); } MethodSpec buildRunSqlImplementation(); MethodSpec buildRunSqlEmpty(); MethodSpec buildMapMaker(); MethodSpec buildGetResultColumns(); static final String METHOD_RUN_SQL; static final ParameterizedTypeName RETURN_TYPE_RUN_SQL; static final String METHOD_MAP_MAKER; static final String METHOD_GET_RESULT_COLUMNS; } | @Test void runSqlImplementationTest() { JUnitGeneratorHelper helper = new JUnitGeneratorHelper(); String expected = "\n" + "private static java.util.ArrayList<java.util.HashMap<java.lang.String, java.lang.String>> runSql(\n" + " java.lang.String query, boolean isUpdate) throws java.sql.SQLException {\n" + " java.sql.Connection connection = java.sql.DriverManager.getConnection(DB_JDBC_URL, DB_USER, DB_PASSWORD);\n" + " java.sql.Statement statement = connection.createStatement();\n" + " if (isUpdate == true) {\n" + " statement.executeUpdate(query);\n" + " return null;\n" + " } else {\n" + " java.util.ArrayList<java.util.HashMap<java.lang.String, java.lang.String>> tableStructure = new java.util.ArrayList<java.util.HashMap<java.lang.String, java.lang.String>>();\n" + " java.sql.ResultSet resultSet = statement.executeQuery(query);\n" + " java.util.List<java.lang.String> columns = getResultColumns(resultSet);\n" + " while (resultSet.next()) {\n" + " java.util.HashMap<java.lang.String, java.lang.String> values = new java.util.HashMap<>();\n" + " for (String column : columns) {\n" + " Object value = resultSet.getObject(column);\n" + " values.put(column, value != null ? value.toString() : \"NULL\");\n" + " }\n" + " tableStructure.add(values);\n" + " }\n" + " return tableStructure;\n" + " }\n" + "}\n"; assertThat(helper.buildRunSqlImplementation().toString()).isEqualTo(expected); } |
JUnitGeneratorHelper { public MethodSpec buildRunSqlEmpty() { MethodSpec.Builder runSql = MethodSpec.methodBuilder(METHOD_RUN_SQL) .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(RETURN_TYPE_RUN_SQL) .addParameter(String.class, "query") .addParameter(TypeName.BOOLEAN, "isUpdate") .addException(SQLException.class) .addJavadoc("This method should connect to your database and execute the given query.\n" + "In order for the assertions to work correctly this method must return a list of maps\n" + "in the case that the query succeeds, or null if the query fails. The tests will assert the results.\n\n" + "@param query The query to execute.\n" + "@param isUpdate Whether the query is a data modification statement.\n\n" + "@returns The resulting table, or null if the query is an update.\n"); runSql.addComment("TODO: implement method stub.") .addStatement("return null"); return runSql.build(); } MethodSpec buildRunSqlImplementation(); MethodSpec buildRunSqlEmpty(); MethodSpec buildMapMaker(); MethodSpec buildGetResultColumns(); static final String METHOD_RUN_SQL; static final ParameterizedTypeName RETURN_TYPE_RUN_SQL; static final String METHOD_MAP_MAKER; static final String METHOD_GET_RESULT_COLUMNS; } | @Test void runSqlEmptyTest() { JUnitGeneratorHelper helper = new JUnitGeneratorHelper(); String expected = "\n" + "private static java.util.ArrayList<java.util.HashMap<java.lang.String, java.lang.String>> runSql(\n" + " java.lang.String query, boolean isUpdate) throws java.sql.SQLException {\n" + " " return null;\n" + "}\n"; assertThat(helper.buildRunSqlEmpty().toString()).isEqualTo(expected); } |
JUnitGeneratorHelper { public MethodSpec buildMapMaker() { MethodSpec.Builder mapMaker = MethodSpec.methodBuilder(METHOD_MAP_MAKER) .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(ParameterizedTypeName.get(HashMap.class, String.class, String.class)) .addParameter(String[].class, "strings") .varargs() .addJavadoc("Generates a string map from a list of strings.\n"); mapMaker.addStatement("$T<$T, $T> result = new $T<>()", HashMap.class, String.class, String.class, HashMap.class) .beginControlFlow("for(int i = 0; i < strings.length; i += 2)") .addStatement("result.put(strings[i], strings[i + 1])") .endControlFlow() .addStatement("return result"); return mapMaker.build(); } MethodSpec buildRunSqlImplementation(); MethodSpec buildRunSqlEmpty(); MethodSpec buildMapMaker(); MethodSpec buildGetResultColumns(); static final String METHOD_RUN_SQL; static final ParameterizedTypeName RETURN_TYPE_RUN_SQL; static final String METHOD_MAP_MAKER; static final String METHOD_GET_RESULT_COLUMNS; } | @Test void mapMakerTest() { JUnitGeneratorHelper helper = new JUnitGeneratorHelper(); String expected = "\n" + "private static java.util.HashMap<java.lang.String, java.lang.String> makeMap(\n" + " java.lang.String... strings) {\n" + " java.util.HashMap<java.lang.String, java.lang.String> result = new java.util.HashMap<>();\n" + " for(int i = 0; i < strings.length; i += 2) {\n" + " result.put(strings[i], strings[i + 1]);\n" + " }\n" + " return result;\n" + "}\n"; assertThat(helper.buildMapMaker().toString()).isEqualTo(expected); } |
JUnitGeneratorHelper { public MethodSpec buildGetResultColumns() { MethodSpec.Builder getResultColumns = MethodSpec.methodBuilder(METHOD_GET_RESULT_COLUMNS) .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .returns(ParameterizedTypeName.get(List.class, String.class)) .addParameter(ResultSet.class, "result") .addException(SQLException.class) .addJavadoc("Gets the columns of a statement result set.\n"); getResultColumns.addStatement("$T meta = result.getMetaData()", ResultSetMetaData.class) .addStatement("$T<$T> columns = new $T<>()", List.class, String.class, ArrayList.class) .addComment("Start at one; this is 1-indexed") .beginControlFlow("for (int i = 1; i <= meta.getColumnCount(); ++i)") .addStatement("columns.add(meta.getColumnLabel(i))") .endControlFlow() .addStatement("return columns"); return getResultColumns.build(); } MethodSpec buildRunSqlImplementation(); MethodSpec buildRunSqlEmpty(); MethodSpec buildMapMaker(); MethodSpec buildGetResultColumns(); static final String METHOD_RUN_SQL; static final ParameterizedTypeName RETURN_TYPE_RUN_SQL; static final String METHOD_MAP_MAKER; static final String METHOD_GET_RESULT_COLUMNS; } | @Test void getResultColumnsTest() { JUnitGeneratorHelper helper = new JUnitGeneratorHelper(); String expected = "\n" + "private static java.util.List<java.lang.String> getResultColumns(java.sql.ResultSet result) throws\n" + " java.sql.SQLException {\n" + " java.sql.ResultSetMetaData meta = result.getMetaData();\n" + " java.util.List<java.lang.String> columns = new java.util.ArrayList<>();\n" + " " for (int i = 1; i <= meta.getColumnCount(); ++i) {\n" + " columns.add(meta.getColumnLabel(i));\n" + " }\n" + " return columns;\n" + "}\n"; assertThat(helper.buildGetResultColumns().toString()).isEqualTo(expected); } |
JUnitGeneratorSettings { public static JUnitGeneratorSettings getDefault( ConnectionData connectionData, String filePackage, String className) { return new JUnitGeneratorSettings( connectionData, filePackage, className, true, true, true, false, true ); } static JUnitGeneratorSettings getDefault(
ConnectionData connectionData, String filePackage, String className); } | @Test void staticDefaultMethod() { ConnectionData connectionData = new ConnectionData("", "", "", ""); JUnitGeneratorSettings settings = JUnitGeneratorSettings.getDefault( connectionData, "pack", "className"); assertThat(settings.getConnectionData()).isSameAs(connectionData); assertThat(settings.getFilePackage()).isEqualTo("pack"); assertThat(settings.getClassName()).isEqualTo("className"); } |
EvoSQLRunner implements QueryRunner { @Override public Result runQuery(@NonNull String sqlQuery, @NonNull ConnectionData connectionData) { EvoSQL evoSQL = evoSQLFactory.createEvoSQL(connectionData); nl.tudelft.serg.evosql.Result evoSQLResult = evoSQL.execute(sqlQuery); return convertResult(evoSQLResult); } @Override Result runQuery(@NonNull String sqlQuery, @NonNull ConnectionData connectionData); } | @Test void testRunQueryFail() { assertThatNullPointerException().isThrownBy(() -> { new EvoSQLRunner().runQuery(null, Mockito.mock(ConnectionData.class)); }); assertThatNullPointerException().isThrownBy(() -> { new EvoSQLRunner().runQuery("Select * From all", null); }); }
@Test void runQueryTest() { EvoSQL evoSQL = Mockito.mock(EvoSQL.class); EvoSQLFactory evoSQLFactory = Mockito.mock(EvoSQLFactory.class); Mockito.when(evoSQLFactory.createEvoSQL(Mockito.any())).thenReturn(evoSQL); Result result = new Result("Select * From all;", 0); Mockito.when(evoSQL.execute(Mockito.anyString())).thenReturn(result); ConnectionData connectionData = new ConnectionData("cs", "db", "user", "pass"); EvoSQLRunner evoSQLRunner = new EvoSQLRunner(); evoSQLRunner.setEvoSQLFactory(evoSQLFactory); evoSQLRunner.runQuery("Select * From all;", connectionData); Mockito.verify(evoSQLFactory, Mockito.times(1)).createEvoSQL(connectionData); Mockito.verify(evoSQL, Mockito.times(1)).execute("Select * From all;"); } |
EvoSQLRunner implements QueryRunner { Result convertResult(nl.tudelft.serg.evosql.Result evoSqlResult) { return new Result( evoSqlResult.getInputQuery(), evoSqlResult.getPathResults().stream() .filter(pr -> pr.getFixture() != null) .filter(pr -> pr.isSuccess()) .map(this::convertPathResult) .collect(Collectors.toList()) ); } @Override Result runQuery(@NonNull String sqlQuery, @NonNull ConnectionData connectionData); } | @Test void conversionTest() { Result result = new Result("Select * From table", 0); result.getPathResults().add(buildPathResult(1)); result.getPathResults().add(buildPathResult(2)); EvoSQLRunner evoSQLRunner = new EvoSQLRunner(); nl.tudelft.serg.evosql.brew.data.Result brewResult = evoSQLRunner.convertResult(result); assertThat(brewResult.getInputQuery()).isEqualTo("Select * From table"); assertThat(brewResult.getPaths().size()).isEqualTo(2); assertThat(brewResult.getPaths().get(0).getFixture().getTables().size()).isEqualTo(3); assertThat(brewResult.getPaths().get(0).getPathSql()).isEqualTo("Select * From table1"); assertThat(brewResult.getPaths().get(1).getFixture().getTables().get(1).getSchema().getName()) .isEqualTo("testTable2"); assertThat(brewResult.getPaths().get(0).getFixture().getTables().get(0).getRows().get(0).getValues().get("testColumn1_1")) .isEqualTo("'string1'"); assertThat(brewResult.getPaths().get(0).getFixture().getTables().get(2).getRows().get(1).getValues().get("testColumn3_2")) .isEqualTo("20"); } |
EvoSQLFactory { public EvoSQL createEvoSQL(ConnectionData connectionData) { return new EvoSQL( connectionData.getConnectionString(), connectionData.getDatabase(), connectionData.getUsername(), connectionData.getPassword(), false); } EvoSQL createEvoSQL(ConnectionData connectionData); } | @Test void createEvoSQLTest() { ConnectionData connectionData = new ConnectionData("cs", "db", "user", "pass"); EvoSQLFactory evoSQLFactory = new EvoSQLFactory(); assertThat(evoSQLFactory.createEvoSQL(connectionData)).isInstanceOf(EvoSQL.class); } |
ExistingDataRunner implements QueryRunner { @Override public Result runQuery(String sqlQuery, ConnectionData connectionData) { return result; } @Override Result runQuery(String sqlQuery, ConnectionData connectionData); } | @Test void testRunQuerySame() { final Result expected = Mockito.mock(Result.class); Result actual = new ExistingDataRunner(expected).runQuery(null, null); assertThat(actual).isSameAs(expected); }
@Test void testRunQueryNull() { final Result expected = null; Result actual = new ExistingDataRunner(expected).runQuery(null, null); assertThat(actual).isSameAs(expected); } |
FileConsumer implements OutputConsumer { @Override public void consumeOutput(List<Output> outputs) { try { Files.createDirectories(directory); for (Output output : outputs) { File outfile = Paths.get(directory.toString(), output.getName()).toFile(); FileOutputStream outStream = fileOutputStreamProvider.createStream(outfile); OutputStreamWriter writer = new OutputStreamWriter(outStream, StandardCharsets.UTF_8); writer.write(output.getData()); writer.close(); } } catch (IOException e) { throw new RuntimeException(e); } } FileConsumer(Path directory); FileConsumer(@NonNull Path directory, FileOutputStreamProvider fileOutputStreamProvider); @Override void consumeOutput(List<Output> outputs); } | @Test void ioExceptionTest() throws FileNotFoundException { final IOException ioException = new IOException(); FileConsumer.FileOutputStreamProvider fileOutputStreamProvider = Mockito.mock(FileConsumer.FileOutputStreamProvider.class); Mockito.when(fileOutputStreamProvider.createStream(Mockito.any())).then(invocation -> { throw ioException; }); Output output = new Output("exception test", ""); FileConsumer fileConsumer = new FileConsumer(tempDir, fileOutputStreamProvider); assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> { fileConsumer.consumeOutput(Collections.singletonList(output)); }).withCause(ioException); }
@Test void simpleCreateTest() throws IOException { Output output = new Output("simple", "This is a simple test."); FileConsumer fileConsumer = new FileConsumer(tempDir); fileConsumer.consumeOutput(Collections.singletonList(output)); Path expectedFilePath = Paths.get(tempDir.toString(), output.getName()); assertThat(expectedFilePath.toFile().exists()).isTrue(); assertThat(Files.readAllLines(expectedFilePath)) .isEqualTo(Collections.singletonList(output.getData())); }
@Test void multipleTest() throws IOException { Output output1 = new Output("multiple1.md", "# First multiple test\n\nIf you can read this, the test was probably successful.\n"); Output output2 = new Output("multiple2", "You may delete these files (but not before the test finishes ;) )"); FileConsumer fileConsumer = new FileConsumer(tempDir); fileConsumer.consumeOutput(Arrays.asList(output1, output2)); Path expectedFilePath1 = Paths.get(tempDir.toString(), output1.getName()); assertThat(expectedFilePath1.toFile().exists()).isTrue(); String file1Content = new String(Files.readAllBytes(expectedFilePath1), StandardCharsets.UTF_8); assertThat(file1Content).isEqualTo(output1.getData()); Path expectedFilePath2 = Paths.get(tempDir.toString(), output2.getName()); assertThat(expectedFilePath2.toFile().exists()).isTrue(); String file2Content = new String(Files.readAllBytes(expectedFilePath2), StandardCharsets.UTF_8); assertThat(file2Content).isEqualTo(output2.getData()); } |
TableCreationBuilder extends QueryBuilder { @Override public List<String> buildQueries(Path path) { return path.getFixture().getTables().stream().map(table -> { StringBuilder createBuilder = new StringBuilder(); createBuilder.append("CREATE TABLE "); createBuilder.append(getVendorOptions().escapeIdentifier(table.getSchema().getName())); createBuilder.append(" ("); List<String> columnsWithTypes = table.getSchema().getColumns().stream() .map(c -> getVendorOptions().escapeIdentifier(c.getName()) + " " + c.getType()) .collect(Collectors.toList()); createBuilder.append(String.join(", ", columnsWithTypes)); createBuilder.append(");"); return createBuilder.toString(); }).collect(Collectors.toList()); } TableCreationBuilder(VendorOptions vendorOptions); @Override List<String> buildQueries(Path path); } | @Test void createTableMySQLStringTestSmall() { String expected = "CREATE TABLE `table1` (`column1_1` INTEGER, `column1_2` DOUBLE, `column1_3` VARCHAR(100));"; TableCreationBuilder tableCreationBuilder = new TableCreationBuilder(new MySQLOptions()); assertThat(tableCreationBuilder.buildQueries(pathsSmall.get(0)).get(0)).isEqualTo(expected); }
@Test void createTablePostgreSQLTestSmall() { String expected = "CREATE TABLE \"table1\" (\"column1_1\" INTEGER, \"column1_2\" DOUBLE, \"column1_3\" VARCHAR(100));"; TableCreationBuilder tableCreationBuilder = new TableCreationBuilder(new PostgreSQLOptions()); assertThat(tableCreationBuilder.buildQueries(pathsSmall.get(0)).get(0)).isEqualTo(expected); }
@Test void createTableMySQLStringTestMedium() { List<String> expected = Arrays.asList( "CREATE TABLE `table1` (`column1_1` INTEGER, `column1_2` VARCHAR(100));", "CREATE TABLE `products` (`product_name` VARCHAR(100), `expired` BIT, `expiry_date` DATETIME);"); TableCreationBuilder tableCreationBuilder = new TableCreationBuilder(new MySQLOptions()); assertThat(tableCreationBuilder.buildQueries(pathsMedium.get(3))).isEqualTo(expected); } |
QueryBuilder { protected String getEscapedValue(FixtureColumn fixtureColumn, FixtureRow fixtureRow) { String value = fixtureRow.getValues().get(fixtureColumn.getName()); if (value == null || "NULL".equals(value)) { return "NULL"; } if (!numericSqlTypes.contains(fixtureColumn.getType())) { return "'" + value.replaceAll("'", "''") + "'"; } return value; } abstract List<String> buildQueries(Path path); } | @Test void testGetEscapedValueNull() { QueryBuilder queryBuilder = getQueryBuilder(); assertThat(queryBuilder.getEscapedValue(new FixtureColumn("nulltest", "STRING"), fixtureRow)) .isEqualTo("NULL"); }
@Test void testInteger() { QueryBuilder queryBuilder = getQueryBuilder(); assertThat(queryBuilder.getEscapedValue(fixtureColumns.get(0), fixtureRow)).isEqualTo("42"); }
@Test void testDouble() { QueryBuilder queryBuilder = getQueryBuilder(); assertThat(queryBuilder.getEscapedValue(fixtureColumns.get(1), fixtureRow)).isEqualTo("2.5"); }
@Test void testBoolean() { QueryBuilder queryBuilder = getQueryBuilder(); assertThat(queryBuilder.getEscapedValue(fixtureColumns.get(2), fixtureRow)).isEqualTo("1"); }
@Test void testString() { QueryBuilder queryBuilder = getQueryBuilder(); assertThat(queryBuilder.getEscapedValue(fixtureColumns.get(3), fixtureRow)).isEqualTo("'This is a ''string''.'"); }
@Test void testGetEscapedValueNullString() { QueryBuilder queryBuilder = getQueryBuilder(); assertThat(queryBuilder.getEscapedValue(fixtureColumns.get(4), fixtureRow)).isEqualTo("NULL"); }
@Test void testDate() { QueryBuilder queryBuilder = getQueryBuilder(); assertThat(queryBuilder.getEscapedValue(fixtureColumns.get(5), fixtureRow)).isEqualTo("'2018-03-27'"); } |
SelectionBuilder extends QueryBuilder { @Override public List<String> buildQueries(Path path) { return Collections.singletonList(path.getPathSql()); } SelectionBuilder(VendorOptions vendorOptions); @Override List<String> buildQueries(Path path); } | @Test void selectionBuilderTestSmall() { SelectionBuilder selectionBuilder = new SelectionBuilder(new MySQLOptions()); Result result1 = DataGenerator.makeResult1(); assertThat(selectionBuilder.buildQueries(result1.getPaths().get(0))) .isEqualTo(Collections.singletonList(result1.getPaths().get(0).getPathSql())); }
@Test void selectionBuilderTestMedium() { SelectionBuilder selectionBuilder = new SelectionBuilder(new MySQLOptions()); Result result2 = DataGenerator.makeResult2(); assertThat(selectionBuilder.buildQueries(result2.getPaths().get(2))) .isEqualTo(Collections.singletonList(result2.getPaths().get(2).getPathSql())); } |
CleaningBuilder extends QueryBuilder { @Override public List<String> buildQueries(Path path) { return path.getFixture().getTables().stream().map(table -> { StringBuilder truncateBuilder = new StringBuilder(); truncateBuilder.append("TRUNCATE TABLE "); truncateBuilder.append(getVendorOptions().escapeIdentifier(table.getSchema().getName())); truncateBuilder.append(";"); return truncateBuilder.toString(); }).collect(Collectors.toList()); } CleaningBuilder(VendorOptions vendorOptions); @Override List<String> buildQueries(Path path); } | @Test void truncateTableMySQLStringTest() { String expected = "TRUNCATE TABLE `table1`;"; CleaningBuilder cleaningBuilder = new CleaningBuilder(new MySQLOptions()); assertThat(cleaningBuilder.buildQueries(pathsSmall.get(0)).get(0)).isEqualTo(expected); }
@Test void truncateTablePostgreSQLTest() { String expected = "TRUNCATE TABLE \"table1\";"; CleaningBuilder cleaningBuilder = new CleaningBuilder(new PostgreSQLOptions()); assertThat(cleaningBuilder.buildQueries(pathsSmall.get(0)).get(0)).isEqualTo(expected); }
@Test void dropTableMySQLStringTestMedium() { List<String> expected = Arrays.asList("TRUNCATE TABLE `table1`;", "TRUNCATE TABLE `products`;"); CleaningBuilder cleaningBuilder = new CleaningBuilder(new MySQLOptions()); assertThat(cleaningBuilder.buildQueries(pathsMedium.get(2))).isEqualTo(expected); } |
InsertionBuilder extends QueryBuilder { @Override public List<String> buildQueries(Path path) { return path.getFixture().getTables().stream().map(table -> { StringBuilder insertBuilder = new StringBuilder(); insertBuilder.append("INSERT INTO "); insertBuilder.append(getVendorOptions().escapeIdentifier(table.getSchema().getName())); insertBuilder.append(" ("); List<String> escapedColumnNames = table.getSchema().getColumns().stream() .map(c -> getVendorOptions().escapeIdentifier(c.getName())) .collect(Collectors.toList()); insertBuilder.append(String.join(", ", escapedColumnNames)); insertBuilder.append(") VALUES "); List<String> valueStrings = table.getRows().stream().map(row -> { StringBuilder valueBuilder = new StringBuilder(); valueBuilder.append("("); List<String> values = row.getTableSchema().getColumns().stream() .map(c -> getEscapedValue(c, row)) .collect(Collectors.toList()); valueBuilder.append(String.join(", ", values)); valueBuilder.append(")"); return valueBuilder.toString(); }).collect(Collectors.toList()); insertBuilder.append(String.join(", ", valueStrings)); insertBuilder.append(";"); return insertBuilder.toString(); }).collect(Collectors.toList()); } InsertionBuilder(VendorOptions vendorOptions); @Override List<String> buildQueries(Path path); } | @Test void result1Test() { Result result1 = DataGenerator.makeResult1(); InsertionBuilder insertionBuilder = new InsertionBuilder(new MySQLOptions()); List<String> insertionQueries = insertionBuilder.buildQueries(result1.getPaths().get(0)); List<String> expectedQueries = Arrays.asList( "INSERT INTO `table1` (`column1_1`, `column1_2`, `column1_3`) VALUES (1, 0.5, 'The first row of table 1.'), (2, 1.5, 'The second row.');" ); assertThat(insertionQueries).isEqualTo(expectedQueries); } |
PostgreSQLOptions implements VendorOptions { @Override public String escapeIdentifier(String id) { return "\"" + id + "\""; } @Override String escapeIdentifier(String id); } | @Test void testStandard() { VendorOptions postgreSQLOptions = new PostgreSQLOptions(); assertThat(postgreSQLOptions.escapeIdentifier("table")).isEqualTo("\"table\""); }
@Test void testSpace() { VendorOptions postgreSQLOptions = new PostgreSQLOptions(); assertThat(postgreSQLOptions.escapeIdentifier("table space")).isEqualTo("\"table space\""); }
@Test void testNumber() { VendorOptions postgreSQLOptions = new PostgreSQLOptions(); assertThat(postgreSQLOptions.escapeIdentifier("table2table")).isEqualTo("\"table2table\""); } |
MySQLOptions implements VendorOptions { @Override public String escapeIdentifier(String id) { return "`" + id + "`"; } @Override String escapeIdentifier(String id); } | @Test void testNormal() { VendorOptions mySQLOptions = new MySQLOptions(); assertThat(mySQLOptions.escapeIdentifier("table")).isEqualTo("`table`"); }
@Test void testSpace() { VendorOptions mySQLOptions = new MySQLOptions(); assertThat(mySQLOptions.escapeIdentifier("table space")).isEqualTo("`table space`"); }
@Test void testNumber() { VendorOptions mySQLOptions = new MySQLOptions(); assertThat(mySQLOptions.escapeIdentifier("table2table")).isEqualTo("`table2table`"); } |
DestructionBuilder extends QueryBuilder { @Override public List<String> buildQueries(Path path) { return path.getFixture().getTables().stream().map(table -> { StringBuilder destructionBuilder = new StringBuilder(); destructionBuilder.append("DROP TABLE "); destructionBuilder.append(getVendorOptions().escapeIdentifier(table.getSchema().getName())); destructionBuilder.append(";"); return destructionBuilder.toString(); }).collect(Collectors.toList()); } DestructionBuilder(VendorOptions vendorOptions); @Override List<String> buildQueries(Path path); } | @Test void dropTableMySQLStringTestSmall() { String expected = "DROP TABLE `table1`;"; DestructionBuilder destructionBuilder = new DestructionBuilder(new MySQLOptions()); assertThat(destructionBuilder.buildQueries(pathsSmall.get(0)).get(0)).isEqualTo(expected); }
@Test void dropTablePostgreSQLTestSmall() { String expected = "DROP TABLE \"table1\";"; DestructionBuilder destructionBuilder = new DestructionBuilder(new PostgreSQLOptions()); assertThat(destructionBuilder.buildQueries(pathsSmall.get(0)).get(0)).isEqualTo(expected); }
@Test void dropTableMySQLStringTestMedium() { List<String> expected = Arrays.asList("DROP TABLE `table1`;", "DROP TABLE `products`;"); DestructionBuilder destructionBuilder = new DestructionBuilder(new MySQLOptions()); assertThat(destructionBuilder.buildQueries(pathsMedium.get(2))).isEqualTo(expected); } |
Vector3D { public static float[] vectorMultiply(float[] lhs, float[] rhs) { float[] result = new float[3]; result[x] = lhs[y]*rhs[z] - lhs[z]*rhs[y]; result[y] = lhs[z]*rhs[x] - lhs[x]*rhs[z]; result[z] = lhs[x]*rhs[y] - lhs[y]*rhs[x]; return result; } static float[] vectorMultiply(float[] lhs, float[] rhs); static float scalarMultiply(float[] lhs, float[] rhs); static float distanceVertices(float[] left, float[] right); static float vectorLength(float[] vector); static float[] createVector(float[] start, float[] end); static float distanceDotLine(float[] dot, float[] lineA, float[] lineB); static float distancevertexSegment(float[] dot, float[] segmentStart, float[] segmentEnd); static final float Epsilon; } | @Test public void vectorMultiply() throws Exception { float vec1[] = {1, 0, 0}; float vec2[] = {0, 1, 0}; float res[] = Vector3D.vectorMultiply(vec1, vec2); assertTrue(vectorEqual(res, new float[] {0, 0, 1})); res = Vector3D.vectorMultiply(vec2, vec1); assertTrue(vectorEqual(res, new float[] {0, 0, -1})); float[] vec3 = {1, 2, 3}; float[] vec4 = {4, 5, 6}; res = Vector3D.vectorMultiply(vec3, vec4); assertTrue(vectorEqual(res, new float[] {-3, 6, -3})); res = Vector3D.vectorMultiply(vec4, vec3); assertTrue(vectorEqual(res, new float[] {3, -6, 3})); res = Vector3D.vectorMultiply(vec4, vec4); assertTrue(vectorEqual(res, new float[] {0, 0, 0})); } |
Vector3D { public static float scalarMultiply(float[] lhs, float[] rhs) { return lhs[x]*rhs[x] + lhs[y]*rhs[y] + lhs[z]*rhs[z]; } static float[] vectorMultiply(float[] lhs, float[] rhs); static float scalarMultiply(float[] lhs, float[] rhs); static float distanceVertices(float[] left, float[] right); static float vectorLength(float[] vector); static float[] createVector(float[] start, float[] end); static float distanceDotLine(float[] dot, float[] lineA, float[] lineB); static float distancevertexSegment(float[] dot, float[] segmentStart, float[] segmentEnd); static final float Epsilon; } | @Test public void scalarMultiply() throws Exception { float vec1[] = {1, 0, 0}; float vec2[] = {0, 1, 0}; float res = Vector3D.scalarMultiply(vec1, vec2); assertTrue(equal(res, 0)); float v3[] = {5, 0, 0}; float v4[] = {3, -1, 0}; res = Vector3D.scalarMultiply(v3, v4); assertTrue(equal(res, 15)); } |
Vector3D { public static float distanceVertices(float[] left, float[] right) { float sum = 0; for (int i = 0; i < 3; i++) { sum += (left[i] - right[i])*(left[i] - right[i]); } return (float) Math.sqrt(sum); } static float[] vectorMultiply(float[] lhs, float[] rhs); static float scalarMultiply(float[] lhs, float[] rhs); static float distanceVertices(float[] left, float[] right); static float vectorLength(float[] vector); static float[] createVector(float[] start, float[] end); static float distanceDotLine(float[] dot, float[] lineA, float[] lineB); static float distancevertexSegment(float[] dot, float[] segmentStart, float[] segmentEnd); static final float Epsilon; } | @Test public void distanceVertices() throws Exception { float[] start = {0, 1, 0, 1}; float[] end = {5, 1, 0, 1}; float[] vertex = {3, 0, 0, 1}; float res = Vector3D.distanceVertices(start, end); assertTrue(equal(res, 5)); res = Vector3D.distanceVertices(start, vertex); assertTrue(equal(res, 3.1623f)); } |
Vector3D { public static float vectorLength(float[] vector) { return (float) Math.sqrt(vector[x]*vector[x] + vector[y]*vector[y] + vector[z]*vector[z]); } static float[] vectorMultiply(float[] lhs, float[] rhs); static float scalarMultiply(float[] lhs, float[] rhs); static float distanceVertices(float[] left, float[] right); static float vectorLength(float[] vector); static float[] createVector(float[] start, float[] end); static float distanceDotLine(float[] dot, float[] lineA, float[] lineB); static float distancevertexSegment(float[] dot, float[] segmentStart, float[] segmentEnd); static final float Epsilon; } | @Test public void vectorLength() throws Exception { } |
Vector3D { public static float[] createVector(float[] start, float[] end) { float[] res = new float[4]; for (int i = 0; i < 3; i++) { res[i] = end[i] - start[i]; } res[w] = 0; return res; } static float[] vectorMultiply(float[] lhs, float[] rhs); static float scalarMultiply(float[] lhs, float[] rhs); static float distanceVertices(float[] left, float[] right); static float vectorLength(float[] vector); static float[] createVector(float[] start, float[] end); static float distanceDotLine(float[] dot, float[] lineA, float[] lineB); static float distancevertexSegment(float[] dot, float[] segmentStart, float[] segmentEnd); static final float Epsilon; } | @Test public void createVector() throws Exception { } |
Vector3D { public static float distanceDotLine(float[] dot, float[] lineA, float[] lineB) { float[] v_l = createVector(lineA, lineB); float[] w = createVector(lineA, dot); float[] mul = vectorMultiply(v_l, w); return vectorLength(mul)/vectorLength(v_l); } static float[] vectorMultiply(float[] lhs, float[] rhs); static float scalarMultiply(float[] lhs, float[] rhs); static float distanceVertices(float[] left, float[] right); static float vectorLength(float[] vector); static float[] createVector(float[] start, float[] end); static float distanceDotLine(float[] dot, float[] lineA, float[] lineB); static float distancevertexSegment(float[] dot, float[] segmentStart, float[] segmentEnd); static final float Epsilon; } | @Test public void distanceDotLine() throws Exception { } |
Vector3D { public static float distancevertexSegment(float[] dot, float[] segmentStart, float[] segmentEnd) { float[] vecSegment = createVector(segmentStart, segmentEnd); float[] vecDot = createVector(segmentStart, dot); float scalarMul = scalarMultiply(vecSegment, vecDot); if ((Math.abs(scalarMul) < Epsilon) || (scalarMul < 0)) { return distanceVertices(dot, segmentStart); } vecSegment = createVector(segmentEnd, segmentStart); vecDot = createVector(segmentEnd, dot); scalarMul = scalarMultiply(vecSegment, vecDot); if ((Math.abs(scalarMul) < Epsilon) || (scalarMul < 0)) { return distanceVertices(dot, segmentEnd); } return distanceDotLine(dot, segmentStart, segmentEnd); } static float[] vectorMultiply(float[] lhs, float[] rhs); static float scalarMultiply(float[] lhs, float[] rhs); static float distanceVertices(float[] left, float[] right); static float vectorLength(float[] vector); static float[] createVector(float[] start, float[] end); static float distanceDotLine(float[] dot, float[] lineA, float[] lineB); static float distancevertexSegment(float[] dot, float[] segmentStart, float[] segmentEnd); static final float Epsilon; } | @Test public void distanceVertexSegment() throws Exception { float[] start = {0, 1, 0, 1}; float[] end = {5, 1, 0, 1}; float[] vertex = {3, 0, 0, 1}; float res = Vector3D.distancevertexSegment(vertex, start, end); assertTrue(equal(res, 1)); float[] vertex2 = {0, 0, 0}; res = Vector3D.distancevertexSegment(vertex2, start, end); assertTrue(equal(res, 1)); float[] vertex3 = {-1, 0, 0}; res = Vector3D.distancevertexSegment(vertex3, start, end); assertTrue(equal(res, 1.4142f)); float[] start2 = {-3f, 2, -5f}; float[] end2 = {3, 2, 5}; res = Vector3D.distancevertexSegment(vertex2, start2, end2); assertTrue(equal(res, 2)); } |
ProductEventConsumer extends AbstractKafkaConsumer { @KafkaListener(topics = "${eventing.topic_name}") public void listen(final ConsumerRecord<String, String> consumerRecord, final Acknowledgment ack) { super.handleConsumerRecord(consumerRecord, ack); } @Inject protected ProductEventConsumer(ProductEventProcessor messageProcessor, UnprocessableEventService unprocessableEventService); @KafkaListener(topics = "${eventing.topic_name}") void listen(final ConsumerRecord<String, String> consumerRecord, final Acknowledgment ack); } | @Test public void eventWithSyntaxErrorShouldNeitherBeProcessedNorStoredAsUnprocessable() { productEventConsumer = new ProductEventConsumer(mockedProcessor(SUCCESS), unprocessableEventService); productEventConsumer.listen(CONSUMER_RECORD,ack); verify(ack).acknowledge(); verify(unprocessableEventService, never()).save(any()); }
@Test public void eventLeadingToUnexpectedErrorShouldBeStoredAsUnprocessable() { final ProductEventProcessor processor = mockedProcessor(UNEXPECTED_ERROR); productEventConsumer = new ProductEventConsumer(processor, unprocessableEventService); productEventConsumer.listen(CONSUMER_RECORD,ack); verify(ack).acknowledge(); verify(processor).processConsumerRecord(any()); verify(unprocessableEventService).save(any()); }
@Test(expected = TemporaryKafkaProcessingError.class) public void temporaryErrorShouldStoreEventAsUnprocessable() { final ProductEventProcessor processor = mockedProcessor(TEMPORARY_ERROR); productEventConsumer = new ProductEventConsumer(processor, unprocessableEventService); productEventConsumer.listen(CONSUMER_RECORD,ack); verify(ack, never()).acknowledge(); verify(processor).processEvent(any()); verify(unprocessableEventService).save(any()); } |
ApiVerticle extends AbstractVerticle { private void getProducts(RoutingContext rc) { catalogService.getProducts(ar -> { if (ar.succeeded()) { List<Product> products = ar.result(); JsonArray json = new JsonArray(); products.stream() .map(Product::toJson) .forEach(json::add); rc.response() .putHeader("Content-type", "application/json") .end(json.encodePrettily()); } else { rc.fail(ar.cause()); } }); } ApiVerticle(CatalogService catalogService); @Override void start(Future<Void> startFuture); } | @Test public void testGetProducts(TestContext context) throws Exception { String itemId1 = "111111"; JsonObject json1 = new JsonObject() .put("itemId", itemId1) .put("name", "productName1") .put("desc", "productDescription1") .put("price", new Double(100.0)); String itemId2 = "222222"; JsonObject json2 = new JsonObject() .put("itemId", itemId2) .put("name", "productName2") .put("desc", "productDescription2") .put("price", new Double(100.0)); List<Product> products = new ArrayList<>(); products.add(new Product(json1)); products.add(new Product(json2)); doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation){ Handler<AsyncResult<List<Product>>> handler = invocation.getArgument(0); handler.handle(Future.succeededFuture(products)); return null; } }).when(catalogService).getProducts(any()); Async async = context.async(); vertx.createHttpClient().get(port, "localhost", "/products", response -> { assertThat(response.statusCode(), equalTo(200)); assertThat(response.headers().get("Content-type"), equalTo("application/json")); response.bodyHandler(body -> { JsonArray json = body.toJsonArray(); Set<String> itemIds = json.stream() .map(j -> new Product((JsonObject)j)) .map(p -> p.getItemId()) .collect(Collectors.toSet()); assertThat(itemIds.size(), equalTo(2)); assertThat(itemIds, allOf(hasItem(itemId1),hasItem(itemId2))); verify(catalogService).getProducts(any()); async.complete(); }) .exceptionHandler(context.exceptionHandler()); }) .exceptionHandler(context.exceptionHandler()) .end(); }
@Test public void testGetProductsWhenCatalogServiceThrowsError(TestContext context) { doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation){ Handler<AsyncResult<List<Product>>> handler = invocation.getArgument(0); handler.handle(Future.failedFuture("error")); return null; } }).when(catalogService).getProducts(any()); Async async = context.async(); vertx.createHttpClient().get(port, "localhost", "/products", response -> { assertThat(response.statusCode(), equalTo(503)); response.bodyHandler(body -> { assertThat(body.toString(), equalTo("Service Unavailable")); verify(catalogService).getProducts(any()); async.complete(); }) .exceptionHandler(context.exceptionHandler()); }) .exceptionHandler(context.exceptionHandler()) .end(); }
@Test public void testGetProductsWithTimeOut(TestContext context) { doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation) { vertx.setTimer(1500, l -> { Handler<AsyncResult<List<Product>>> handler = invocation.getArgument(0); handler.handle(Future.succeededFuture(new ArrayList<>())); }); return null; } }).when(catalogService).getProducts(any()); Async async = context.async(); vertx.createHttpClient().get(port, "localhost", "/products", response -> { assertThat(response.statusCode(), equalTo(503)); response.bodyHandler(body -> { assertThat(body.toString(), equalTo("Service Unavailable")); verify(catalogService).getProducts(any()); async.complete(); }) .exceptionHandler(context.exceptionHandler()); }) .exceptionHandler(context.exceptionHandler()) .end(); }
@Test public void testGetProductsWithCircuitOpen(TestContext context) { doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation){ Handler<AsyncResult<List<Product>>> handler = invocation.getArgument(0); handler.handle(Future.failedFuture("Error")); return null; } }).when(catalogService).getProducts(any()); Async async = context.async(); Async calls = context.async(3); for (int i = 0; i < 3; i++) { vertx.createHttpClient().get(port, "localhost", "/products", response -> {calls.countDown();}) .exceptionHandler(context.exceptionHandler()) .end(); } calls.await(); vertx.createHttpClient().get(port, "localhost", "/products", response -> { assertThat(response.statusCode(), equalTo(503)); response.bodyHandler(body -> { assertThat(body.toString(), equalTo("Service Unavailable")); verify(catalogService, times(3)).getProducts(any()); async.complete(); }) .exceptionHandler(context.exceptionHandler()); }) .exceptionHandler(context.exceptionHandler()) .end(); }
@Test public void testGetProductsWhenCircuitResetAfterOpen(TestContext context) { doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation){ Handler<AsyncResult<List<Product>>> handler = invocation.getArgument(0); handler.handle(Future.failedFuture("Error")); return null; } }).when(catalogService).getProducts(any()); Async async = context.async(); Async calls = context.async(3); for (int i = 0; i < 10; i++) { vertx.createHttpClient().get(port, "localhost", "/products", response -> {calls.countDown();}) .exceptionHandler(context.exceptionHandler()) .end(); } calls.await(); reset(catalogService); vertx.setTimer(5000, l -> { vertx.createHttpClient().get(port, "localhost", "/products", response -> { assertThat(response.statusCode(), equalTo(503)); response.bodyHandler(body -> { assertThat(body.toString(), equalTo("Service Unavailable")); verify(catalogService, times(1)).getProducts(any()); async.complete(); }) .exceptionHandler(context.exceptionHandler()); }) .exceptionHandler(context.exceptionHandler()) .end(); }); } |
ApiVerticle extends AbstractVerticle { private void getProduct(RoutingContext rc) { String itemId = rc.request().getParam("itemid"); catalogService.getProduct(itemId, ar -> { if (ar.succeeded()) { Product product = ar.result(); if (product != null) { rc.response() .putHeader("Content-type", "application/json") .end(product.toJson().encodePrettily()); } } else { rc.fail(ar.cause()); } }); } ApiVerticle(CatalogService catalogService); @Override void start(Future<Void> startFuture); } | @Test public void testGetProduct(TestContext context) throws Exception { String itemId = "111111"; JsonObject json = new JsonObject() .put("itemId", itemId) .put("name", "productName1") .put("desc", "productDescription1") .put("price", new Double(100.0)); Product product = new Product(json); doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation){ Handler<AsyncResult<Product>> handler = invocation.getArgument(1); handler.handle(Future.succeededFuture(product)); return null; } }).when(catalogService).getProduct(eq("111111"),any()); Async async = context.async(); vertx.createHttpClient().get(port, "localhost", "/product/111111", response -> { assertThat(response.statusCode(), equalTo(200)); assertThat(response.headers().get("Content-type"), equalTo("application/json")); response.bodyHandler(body -> { JsonObject result = body.toJsonObject(); assertThat(result, notNullValue()); assertThat(result.containsKey("itemId"), is(true)); assertThat(result.getString("itemId"), equalTo("111111")); verify(catalogService).getProduct(eq("111111"),any()); async.complete(); }) .exceptionHandler(context.exceptionHandler()); }) .exceptionHandler(context.exceptionHandler()) .end(); }
@Test public void testGetNonExistingProduct(TestContext context) throws Exception { doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation){ Handler<AsyncResult<Product>> handler = invocation.getArgument(1); handler.handle(Future.succeededFuture(null)); return null; } }).when(catalogService).getProduct(eq("111111"),any()); Async async = context.async(); vertx.createHttpClient().get(port, "localhost", "/product/111111", response -> { assertThat(response.statusCode(), equalTo(404)); async.complete(); }) .exceptionHandler(context.exceptionHandler()) .end(); }
@Test public void testGetProductWhenCatalogServiceThrowsError(TestContext context) { doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation){ Handler<AsyncResult<List<Product>>> handler = invocation.getArgument(1); handler.handle(Future.failedFuture("error")); return null; } }).when(catalogService).getProduct(any(),any()); Async async = context.async(); vertx.createHttpClient().get(port, "localhost", "/product/111111", response -> { assertThat(response.statusCode(), equalTo(503)); response.bodyHandler(body -> { assertThat(body.toString(), equalTo("Service Unavailable")); verify(catalogService).getProduct(eq("111111"),any()); async.complete(); }) .exceptionHandler(context.exceptionHandler()); }) .exceptionHandler(context.exceptionHandler()) .end(); } |
ApiVerticle extends AbstractVerticle { private void addProduct(RoutingContext rc) { JsonObject json = rc.getBodyAsJson(); catalogService.addProduct(new Product(json), ar -> { if (ar.succeeded()) { rc.response().setStatusCode(201).end(); } else { rc.fail(ar.cause()); } }); } ApiVerticle(CatalogService catalogService); @Override void start(Future<Void> startFuture); } | @Test public void testAddProduct(TestContext context) throws Exception { doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation){ Handler<AsyncResult<String>> handler = invocation.getArgument(1); handler.handle(Future.succeededFuture(null)); return null; } }).when(catalogService).addProduct(any(),any()); Async async = context.async(); String itemId = "111111"; JsonObject json = new JsonObject() .put("itemId", itemId) .put("name", "productName") .put("desc", "productDescription") .put("price", new Double(100.0)); String body = json.encodePrettily(); String length = Integer.toString(body.length()); vertx.createHttpClient().post(port, "localhost", "/product") .exceptionHandler(context.exceptionHandler()) .putHeader("Content-type", "application/json") .putHeader("Content-length", length) .handler(response -> { assertThat(response.statusCode(), equalTo(201)); ArgumentCaptor<Product> argument = ArgumentCaptor.forClass(Product.class); verify(catalogService).addProduct(argument.capture(), any()); assertThat(argument.getValue().getItemId(), equalTo(itemId)); async.complete(); }) .write(body) .end(); } |
FileEventStorage implements InteractionContextSink, Closeable { String serialize(InteractionContext interactionContext) throws JsonProcessingException { return mapper.writeValueAsString(interactionContext); } FileEventStorage(ObjectMapper mapper); @Override void apply(InteractionContext interactionContext); void load(File file, EventStore eventStore); void save(File file, EventSource eventSource); @Override void close(); } | @Test public void givenInteractionContextWithEventWhenSerializeThenIsSerialized() throws JsonProcessingException { List<Event> events = new ArrayList<>(); events.add(new ChangedDescriptionEvent() {{ description = "Hello World"; }}); events.add(new ChangedDescriptionEvent() {{ description = "Hello World2"; }}); Map<String, String> attributes = new HashMap<>(); attributes.put("user", "rickard"); InteractionContext interaction = new InteractionContext("task", 1, new Date(12345), attributes, new Interaction(new Identifier(1), events)); String json = eventStorage.serialize(interaction); System.out.println(json); } |
FileEventStorage implements InteractionContextSink, Closeable { InteractionContext deserialize(String line) throws IOException { return mapper.readValue(line, InteractionContext.class); } FileEventStorage(ObjectMapper mapper); @Override void apply(InteractionContext interactionContext); void load(File file, EventStore eventStore); void save(File file, EventSource eventSource); @Override void close(); } | @Test public void givenEventStringWhenDeserializeThenInteractionContextDeserialized() throws IOException { String json = "{\"type\":\"task\",\"version\":1,\"timestamp\":12345,\"id\":1," + "\"attributes\":{\"user\":\"rickard\"},\"events\":[{\"type\":\"com.github.rickardoberg.stuff.event" + ".ChangedDescriptionEvent\",\"description\":\"Hello World\"},{\"type\":\"com.github.rickardoberg" + ".stuff.event.ChangedDescriptionEvent\",\"description\":\"Hello World2\"}]}\n"; InteractionContext context = eventStorage.deserialize(json); Assert.assertThat(context, CoreMatchers.notNullValue()); } |
InboxModel implements InteractionContextSink { public abstract Map<Identifier, InboxTask> getTasks(); abstract Map<Identifier, InboxTask> getTasks(); } | @Test public void givenEmptyModelWhenCreatedTaskThenModelHasTask() { InboxModel model = new InMemoryInboxModel(); List<Event> events = new ArrayList<>(); Identifier id = new Identifier(0); events.add(new CreatedEvent()); InteractionContext context = new InteractionContext("task", -1, new Date(), Collections.<String, String>emptyMap(), new Interaction(id, events)); model.apply(context); assertThat(model.getTasks().entrySet().size(), CoreMatchers.equalTo(1)); } |
Inbox { public static Function<Inbox, Function<NewTask, Task>> newTask() { return inbox -> newTask -> { Task task = new Task(newTask.id); inbox.select(task); changeDescription().apply(inbox).apply(newTask.changeDescription); return task; }; } void select(Task task); static Function<Inbox, Function<NewTask, Task>> newTask(); static Function<Inbox, Function<ChangeDescription, InteractionSource>> changeDescription(); static Function<Inbox, Function<TaskDone, InteractionSource>> done(); } | @Test public void givenInboxWhenCreateNewTaskThenNewTaskCreated() { Inbox inbox = new Inbox(); Inbox.ChangeDescription changeDescription = new Inbox.ChangeDescription(); changeDescription.description = "Description"; Inbox.NewTask newTask = new Inbox.NewTask(); newTask.changeDescription = changeDescription; Interaction interaction = Inbox.newTask().apply(inbox).apply(newTask).getInteraction(); Iterator<Event> events = interaction.getEvents().iterator(); CreatedEvent createdTask = (CreatedEvent) events.next(); } |
Version { public String toString() { return mMajor + "." + mMinor + "." + mBuild; } Version(String versionString); boolean isEqualTo(Version compareVersion); boolean isLowerThan(Version compareVersion); boolean ishIGHERThan(Version compareVersion); int getMajor(); int getMinor(); int getBuild(); String toString(); } | @Test public void toStringTest() { String testVersion = "7.0.0"; Version version = new Version(testVersion); assertEquals(version.toString(), testVersion); } |
JsonBindingExample extends JsonData { public Book deserializeBook() { return JsonbBuilder.create().fromJson(bookJson, Book.class); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String customizedMapping(); String annotationPropertiesMapping(); String annotationMethodMapping(); String annotationPropertyAndMethodMapping(); String bookAdapterToJson(); Book bookAdapterToBook(); void usingAProvider(); String allCustomizedMapping(); } | @Test public void givenJSON_shouldDeserializeBook() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); Book book = jsonBindingExample.deserializeBook(); assertThat(book).isEqualTo(book1); } |
JsonBindingExample extends JsonData { public String bookAdapterToJson() { JsonbConfig jsonbConfig = new JsonbConfig().withAdapters(new BookletAdapter()); Jsonb jsonb = JsonbBuilder.create(jsonbConfig); return jsonb.toJson(book1); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String customizedMapping(); String annotationPropertiesMapping(); String annotationMethodMapping(); String annotationPropertyAndMethodMapping(); String bookAdapterToJson(); Book bookAdapterToBook(); void usingAProvider(); String allCustomizedMapping(); } | @Test @Ignore("adapter missing") public void givenAdapter_shouldSerialiseJSON() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String result = jsonBindingExample.bookAdapterToJson(); String json = "{\"isbn\":\"1234567890\",\"bookTitle\":\"Professional Java EE Design Patterns\",\"firstName\":\"Alex\",\"lastName\":\"Theedom\"}"; assertThat(result).isEqualToIgnoringCase(json); } |
JsonBindingExample extends JsonData { public Book bookAdapterToBook() { JsonbConfig jsonbConfig = new JsonbConfig().withAdapters(new BookletAdapter()); Jsonb jsonb = JsonbBuilder.create(jsonbConfig); String json = "{\"isbn\":\"1234567890\",\"bookTitle\":\"Professional Java EE Design Patterns\",\"firstName\":\"Alex\",\"lastName\":\"Theedom\"}"; return jsonb.fromJson(json, Book.class); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String customizedMapping(); String annotationPropertiesMapping(); String annotationMethodMapping(); String annotationPropertyAndMethodMapping(); String bookAdapterToJson(); Book bookAdapterToBook(); void usingAProvider(); String allCustomizedMapping(); } | @Test @Ignore("Book adapter missing") public void givenAdapter_shouldDeserialiseJson() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); Book book = jsonBindingExample.bookAdapterToBook(); assertThat(book).isEqualTo(bookAdapted); } |
EnumExample { public String enumSerialisationInObject() { return JsonbBuilder.create().toJson(new container()); } String enumSerialisation(); String enumSerialisationInObject(); } | @Test public void enumSerialisationInObject() { String expectedJson = "{\"binding\":\"Hard Back\"}"; EnumExample enumExample = new EnumExample(); String actualJson = enumExample.enumSerialisationInObject(); assertThat(actualJson).isEqualTo(expectedJson); } |
EnumExample { public String enumSerialisation() { return JsonbBuilder.create().toJson(Binding.HARD_BACK.name()); } String enumSerialisation(); String enumSerialisationInObject(); } | @Test @Ignore public void givenEnum_shouldThrownExceptionWhenSerialised() { new EnumExample().enumSerialisation(); } |
ComprehensiveExample { public String serialiseMagazine() throws MalformedURLException { Magazine magazine = new Magazine(); magazine.setId("ABCD-1234"); magazine.setTitle("Fun with Java"); magazine.setAuthor(new Author("Alex", "Theedom")); magazine.setPrice(45.00f); magazine.setPages(300); magazine.setInPrint(true); magazine.setBinding(Binding.SOFT_BACK); magazine.setLanguages(Arrays.asList("French", "English", "Spanish", null)); magazine.setWebsite(new URL("https: magazine.setInternalAuditCode("IN-675X-NF09"); magazine.setPublished(LocalDate.parse("01/01/2018", DateTimeFormatter.ofPattern("MM/dd/yyyy"))); magazine.setAlternativeTitle(null); return JsonbBuilder.create().toJson(magazine); } String serialiseMagazine(); Magazine deserialiseMagazine(); } | @Test @Ignore("failing test fix!") public void givenMagazine_shouldSerialiseToJson() throws MalformedURLException { String expectedJson = "{\"author\":{\"firstName\":\"Alex\",\"lastName\":\"Theedom\"},\"binding\":\"SOFT_BACK\",\"id\":\"ABCD-1234\",\"inPrint\":true,\"languages\":[\"French\",\"English\",\"Spanish\",null],\"pages\":300,\"price\":45.0,\"published\":\"2018-01-01\",\"title\":\"Fun with Java\",\"website\":\"https: ComprehensiveExample comprehensiveExample = new ComprehensiveExample(); String actualJson = comprehensiveExample.serialiseMagazine(); assertThat(actualJson).isEqualTo(expectedJson); } |
ComprehensiveExample { public Magazine deserialiseMagazine() { String json = "{\"author\":{\"firstName\":\"Alex\",\"lastName\":\"Theedom\"},\"binding\":\"SOFT_BACK\",\"id\":\"ABCD-1234\",\"inPrint\":true,\"languages\":[\"French\",\"English\",\"Spanish\",null],\"pages\":300,\"price\":45.0,\"published\":\"2018-01-01\",\"title\":\"Fun with Java\",\"website\":\"https: return JsonbBuilder.create().fromJson(json, Magazine.class); } String serialiseMagazine(); Magazine deserialiseMagazine(); } | @Test public void givenJson_shouldDeserialiseToMagazine() throws MalformedURLException { Magazine expectedMagazine = new Magazine(); expectedMagazine.setId("ABCD-1234"); expectedMagazine.setTitle("Fun with Java"); expectedMagazine.setAuthor(new Author("Alex", "Theedom")); expectedMagazine.setPrice(45.00f); expectedMagazine.setPages(300); expectedMagazine.setInPrint(true); expectedMagazine.setBinding(Binding.SOFT_BACK); expectedMagazine.setLanguages(Arrays.asList("French", "English", "Spanish", null)); expectedMagazine.setWebsite(new URL("https: expectedMagazine.setInternalAuditCode(null); expectedMagazine.setPublished(LocalDate.parse("01/01/2018", DateTimeFormatter.ofPattern("MM/dd/yyyy"))); expectedMagazine.setAlternativeTitle(null); ComprehensiveExample comprehensiveExample = new ComprehensiveExample(); Magazine actualMagazine = comprehensiveExample.deserialiseMagazine(); assertThat(actualMagazine).isEqualTo(expectedMagazine); } |
NestedClassExample { public String serializeNestedClasses() { OuterClass.InnerClass innerClass = new OuterClass().new InnerClass(); Jsonb jsonb = JsonbBuilder.create(); String json = jsonb.toJson(innerClass); return json; } String serializeNestedClasses(); OuterClass.InnerClass deserialiseNestedClasses(); } | @Test public void givenNestedInnerClass_shouldSerializeNestedClasses() { String expectedJson = "{\"name\":\"Inner Class\"}"; NestedClassExample nestedClassExample = new NestedClassExample(); String actualJson = nestedClassExample.serializeNestedClasses(); assertThat(actualJson).isEqualTo(expectedJson); } |
NestedClassExample { public OuterClass.InnerClass deserialiseNestedClasses() { String json = "{\"name\":\"Inner Class\"}"; OuterClass.InnerClass innerClass = JsonbBuilder.create().fromJson(json, OuterClass.InnerClass.class); return innerClass; } String serializeNestedClasses(); OuterClass.InnerClass deserialiseNestedClasses(); } | @Test @Ignore public void givenJson_shouldDeserialiseToNestedClass() { OuterClass.InnerClass expectedInner = new OuterClass().new InnerClass(); NestedClassExample nestedClassExample = new NestedClassExample(); OuterClass.InnerClass actualInnerClass = nestedClassExample.deserialiseNestedClasses(); assertThat(actualInnerClass).isEqualTo(expectedInner); } |
MinimalExample { public String serializeBook() { Book book = new Book("SHDUJ-4532", "Fun with Java", "Alex Theedom"); Jsonb jsonb = JsonbBuilder.create(); String json = jsonb.toJson(book); return json; } String serializeBook(); Book deserializeBook(); } | @Test public void givenBookInstance_shouldSerialiseToJSONString() { String expectedJson = "{\"author\":\"Alex Theedom\",\"id\":\"SHDUJ-4532\",\"title\":\"Fun with Java\"}"; MinimalExample minimalExample = new MinimalExample(); String actualJson = minimalExample.serializeBook(); assertThat(actualJson).isEqualTo(expectedJson); } |
MinimalExample { public Book deserializeBook() { Book book = new Book("SHDUJ-4532", "Fun with Java", "Alex Theedom"); Jsonb jsonb = JsonbBuilder.create(); String json = jsonb.toJson(book); book = jsonb.fromJson(json, Book.class); return book; } String serializeBook(); Book deserializeBook(); } | @Test public void givenJSONString_shouldDeserializeToBookObject() { Book expectedBook = new Book("SHDUJ-4532", "Fun with Java", "Alex Theedom"); MinimalExample minimalExample = new MinimalExample(); Book actualBook = minimalExample.deserializeBook(); assertThat(actualBook).isEqualTo(expectedBook); } |
JsonBindingExample extends JsonData { public String serializeBook() { return JsonbBuilder.create().toJson(book1); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String customizedMapping(); String annotationPropertiesMapping(); String annotationMethodMapping(); String annotationPropertyAndMethodMapping(); String bookAdapterToJson(); Book bookAdapterToBook(); void usingAProvider(); String allCustomizedMapping(); } | @Test public void givenBookObject_shouldSerializeToJSONString() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String json = jsonBindingExample.serializeBook(); assertThat(json).isEqualToIgnoringCase(bookJson); } |
JsonPointerExample { public String find() { JsonPointer pointer = Json.createPointer("/topics/1"); JsonString jsonValue = (JsonString) pointer.getValue(jsonObject); return jsonValue.getString(); } String find(); String replace(); String add(); } | @Test public void givenPointerToTopic_shouldReturnTopic() { JsonPointerExample jsonPointerExample = new JsonPointerExample(); String topic = jsonPointerExample.find(); assertThat(topic).isEqualToIgnoringCase("Cloud"); } |
JsonPointerExample { public String replace() { JsonPointer pointer = Json.createPointer("/topics/1"); JsonObject newJsonObject = pointer.replace(jsonObject, Json.createValue("Big Data")); JsonString jsonValue = (JsonString) pointer.getValue(newJsonObject); return jsonValue.getString(); } String find(); String replace(); String add(); } | @Test public void givenPointerToTopic_shouldReplaceTopic() { JsonPointerExample jsonPointerExample = new JsonPointerExample(); String topic = jsonPointerExample.replace(); assertThat(topic).isEqualToIgnoringCase("Big Data"); } |
JsonPointerExample { public String add(){ JsonPointer pointer = Json.createPointer("/topics/0"); JsonObject newJsonObject = pointer.add(jsonObject,Json.createValue("Java EE")); JsonString jsonValue = (JsonString) pointer.getValue(newJsonObject); return jsonValue.getString(); } String find(); String replace(); String add(); } | @Test public void givenPointerToArrayElement_shouldInsertTopicInToList() { JsonPointerExample jsonPointerExample = new JsonPointerExample(); String topic = jsonPointerExample.add(); assertThat(topic).isEqualToIgnoringCase("Java EE"); } |
JsonMergePatchExample extends JsonExample { public JsonValue changeValue() { JsonValue source = Json.createValue("{\"colour\":\"blue\"}"); JsonValue patch = Json.createValue("{\"colour\":\"red\"}"); JsonMergePatch jsonMergePatch = Json.createMergePatch(patch); return jsonMergePatch.apply(source); } JsonValue changeValue(); JsonValue addValue(); JsonValue deleteValue(); } | @Test public void givenPatch_sourceValueChanges() throws Exception { JsonMergePatchExample jsonMergePatchExample = new JsonMergePatchExample(); JsonValue result = jsonMergePatchExample.changeValue(); assertThat(((JsonString) result).getString()).isEqualToIgnoringCase("{\"colour\":\"red\"}"); } |
JsonMergePatchExample extends JsonExample { public JsonValue addValue() { JsonValue source = Json.createValue("{\"colour\":\"blue\"}"); JsonValue patch = Json.createValue("{\"blue\":\"light\"}"); JsonMergePatch jsonMergePatch = Json.createMergePatch(patch); return jsonMergePatch.apply(source); } JsonValue changeValue(); JsonValue addValue(); JsonValue deleteValue(); } | @Test @Ignore public void givenPatch_addNewJsonToSource() throws Exception { JsonMergePatchExample jsonMergePatchExample = new JsonMergePatchExample(); JsonValue result = jsonMergePatchExample.addValue(); assertThat(((JsonString) result).getString()).isEqualToIgnoringCase("{\"colour\":\"blue\",\"blue\":\"light\"}"); } |
JsonMergePatchExample extends JsonExample { public JsonValue deleteValue() { JsonValue source = Json.createValue("{\"colour\":\"blue\"}"); JsonValue patch = Json.createValue("{\"colour\":null}"); JsonMergePatch jsonMergePatch = Json.createMergePatch(patch); return jsonMergePatch.apply(source); } JsonValue changeValue(); JsonValue addValue(); JsonValue deleteValue(); } | @Test @Ignore public void givenPatch_deleteValue() throws Exception { JsonMergePatchExample jsonMergePatchExample = new JsonMergePatchExample(); JsonValue result = jsonMergePatchExample.deleteValue(); assertThat(((JsonString) result).getString()).isEqualToIgnoringCase("{}"); } |
JsonPatchExample extends JsonExample { public JsonObject toJsonArray() { JsonPatchBuilder builder = Json.createPatchBuilder(); JsonArray jsonArray = builder.copy("/series/0", "/topics/0").build().toJsonArray(); return Json.createPatchBuilder(jsonArray).build().apply(jsonObject); } String replace(); JsonObject addAndRemove(); JsonObject move(); JsonObject copy(); JsonObject test(); JsonObject toJsonArray(); } | @Test public void ifValueIsMoved_shouldNotAmendOriginalJSON() { JsonPatchExample jsonPatchExample = new JsonPatchExample(); JsonObject jsonObject = jsonPatchExample.toJsonArray(); JsonPointer pointer = Json.createPointer("/series/0"); JsonString jsonString = (JsonString) pointer.getValue(jsonObject); assertThat(jsonString.getString()).isEqualToIgnoringCase("Cognitive"); } |
JsonPatchExample extends JsonExample { public JsonObject test() { JsonPatchBuilder builder = Json.createPatchBuilder(); JsonPatch jsonPatch = builder .test("/topics/2", "Data") .move("/series/2", "/topics/2") .build(); return jsonPatch.apply(jsonObject); } String replace(); JsonObject addAndRemove(); JsonObject move(); JsonObject copy(); JsonObject test(); JsonObject toJsonArray(); } | @Test public void ifValueExists_moveItToDestination() { JsonPatchExample jsonPatchExample = new JsonPatchExample(); JsonObject jsonObject = jsonPatchExample.test(); JsonPointer pointer = Json.createPointer("/series/2"); JsonString jsonString = (JsonString) pointer.getValue(jsonObject); assertThat(jsonString.getString()).isEqualToIgnoringCase("Data"); } |
JsonPatchExample extends JsonExample { public JsonObject copy() { JsonPatchBuilder builder = Json.createPatchBuilder(); JsonPatch jsonPatch = builder.copy("/series/0", "/topics/0").build(); return jsonPatch.apply(jsonObject); } String replace(); JsonObject addAndRemove(); JsonObject move(); JsonObject copy(); JsonObject test(); JsonObject toJsonArray(); } | @Test public void givenPath_copyToTargetPath() throws Exception { JsonPatchExample jsonPatchExample = new JsonPatchExample(); JsonObject jsonObject = jsonPatchExample.copy(); JsonPointer pointer = Json.createPointer("/series/0"); JsonString jsonString = (JsonString) pointer.getValue(jsonObject); assertThat(jsonString.getString()).isEqualToIgnoringCase("Cognitive"); } |
JsonPatchExample extends JsonExample { public JsonObject move() { JsonPatchBuilder builder = Json.createPatchBuilder(); JsonPatch jsonPatch = builder.move("/series/0", "/topics/0").build(); return jsonPatch.apply(jsonObject); } String replace(); JsonObject addAndRemove(); JsonObject move(); JsonObject copy(); JsonObject test(); JsonObject toJsonArray(); } | @Test public void givenPath_moveToTargetPath() throws Exception { JsonPatchExample jsonPatchExample = new JsonPatchExample(); JsonObject jsonObject = jsonPatchExample.move(); JsonPointer pointer = Json.createPointer("/series/0"); JsonString jsonString = (JsonString) pointer.getValue(jsonObject); assertThat(jsonString.getString()).isEqualToIgnoringCase("Cognitive"); } |
JsonBindingExample extends JsonData { public String serializeListOfBooks() { return JsonbBuilder.create().toJson(books); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String customizedMapping(); String annotationPropertiesMapping(); String annotationMethodMapping(); String annotationPropertyAndMethodMapping(); String bookAdapterToJson(); Book bookAdapterToBook(); void usingAProvider(); String allCustomizedMapping(); } | @Test public void givenListOfBooks_shouldSerialiseToJson() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String json = jsonBindingExample.serializeListOfBooks(); assertThat(json).isEqualToIgnoringCase(bookListJson); } |
JsonPatchExample extends JsonExample { public JsonObject addAndRemove() { JsonPatchBuilder builder = Json.createPatchBuilder(); JsonPatch jsonPatch = builder .add("/comments", Json.createArrayBuilder().add("Very Good!").add("Excellent").build()) .remove("/notes") .build(); return jsonPatch.apply(jsonObject); } String replace(); JsonObject addAndRemove(); JsonObject move(); JsonObject copy(); JsonObject test(); JsonObject toJsonArray(); } | @Test public void givenPatchPath_shouldRemoveAndAdd() { JsonPatchExample jsonPatchExample = new JsonPatchExample(); JsonObject jsonObject = jsonPatchExample.addAndRemove(); JsonPointer pointer = Json.createPointer("/comments"); JsonValue jsonValue = pointer.getValue(jsonObject); assertThat(jsonValue.getValueType()).isEqualTo(JsonValue.ValueType.ARRAY); assertThat(jsonValue.asJsonArray().contains(Json.createValue("Very Good!"))).isTrue(); assertThat(jsonValue.asJsonArray().contains(Json.createValue("Excellent"))).isTrue(); pointer = Json.createPointer("/notes"); boolean contains = pointer.containsValue(jsonObject); assertThat(contains).isFalse(); } |
JsonPatchExample extends JsonExample { public String replace() { JsonPatchBuilder builder = Json.createPatchBuilder(); JsonPatch jsonPatch = builder.replace("/series/0", "Spring 5").build(); JsonObject newJsonObject = jsonPatch.apply(jsonObject); JsonPointer pointer = Json.createPointer("/series/0"); JsonString jsonValue = (JsonString) pointer.getValue(newJsonObject); return jsonValue.getString(); } String replace(); JsonObject addAndRemove(); JsonObject move(); JsonObject copy(); JsonObject test(); JsonObject toJsonArray(); } | @Test public void givenPatchPath_shouldReplaceElement() { JsonPatchExample jsonPatchExample = new JsonPatchExample(); String series = jsonPatchExample.replace(); assertThat(series).isEqualToIgnoringCase("Spring 5"); } |
JsonMergeDiffExample extends JsonExample { public JsonMergePatch createMergePatch(){ JsonValue source = Json.createValue("{\"colour\":\"blue\"}"); JsonValue target = Json.createValue("{\"colour\":\"red\"}"); JsonMergePatch jsonMergePatch = Json.createMergeDiff(source, target); return jsonMergePatch; } JsonMergePatch createMergePatch(); } | @Test public void givenSourceAndTarget_shouldCreateMergePatch() { JsonMergeDiffExample jsonMergeDiffExample = new JsonMergeDiffExample(); JsonMergePatch mergePatch = jsonMergeDiffExample.createMergePatch(); JsonString jsonString = (JsonString) mergePatch.toJsonValue(); assertThat(jsonString.getString()).isEqualToIgnoringCase("{\"colour\":\"red\"}"); } |
Java8Integration extends JsonExample { public List<String> filterJsonArrayToList() { List<String> topics = jsonObject.getJsonArray("topics").stream() .filter(jsonValue -> ((JsonString) jsonValue).getString().startsWith("C")) .map(jsonValue -> ((JsonString) jsonValue).getString()) .collect(Collectors.toList()); return topics; } List<String> filterJsonArrayToList(); JsonArray filterJsonArrayToJsonArray(); } | @Test public void givenJsonArray_shouldFilterAllTopicsStartingCToList() throws Exception { Java8Integration java8Integration = new Java8Integration(); List<String> topics = java8Integration.filterJsonArrayToList(); assertThat(topics).contains("Cloud"); assertThat(topics).contains("Cognitive"); } |
Java8Integration extends JsonExample { public JsonArray filterJsonArrayToJsonArray() { JsonArray topics = jsonObject.getJsonArray("topics").stream() .filter(jsonValue -> ((JsonString) jsonValue).getString().startsWith("C")) .collect(JsonCollectors.toJsonArray()); return topics; } List<String> filterJsonArrayToList(); JsonArray filterJsonArrayToJsonArray(); } | @Test public void givenJsonArray_shouldFilterAllTopicsStartingCToJsonArray() throws Exception { Java8Integration java8Integration = new Java8Integration(); JsonArray topics = java8Integration.filterJsonArrayToJsonArray(); assertThat(topics.contains(Json.createValue("Cloud"))).isTrue(); assertThat(topics.contains(Json.createValue("Cognitive"))).isTrue(); } |
Book { public void addChapterTitle(String chapterTitle) { chapterTitles.add(chapterTitle); } List<String> getChapterTitles(); void addChapterTitle(String chapterTitle); Map<String, String> getAuthorChapter(); void addAuthorChapter(String author, String chapter); } | @Test public void givenListWithConstraints_shouldValidate() { Book book = new Book(); book.addChapterTitle("Chapter 1"); Set<ConstraintViolation<Book>> constraintViolations = validator.validate(book); assertThat(constraintViolations.size()).isEqualTo(0); }
@Test public void givenListWithConstraints_shouldNotValidate() { Book book = new Book(); book.addChapterTitle(" "); Set<ConstraintViolation<Book>> constraintViolations = validator.validate(book); assertThat(constraintViolations.size()).isEqualTo(1); } |
Book { public void addAuthorChapter(String author, String chapter) { authorChapter.put(author,chapter); } List<String> getChapterTitles(); void addChapterTitle(String chapterTitle); Map<String, String> getAuthorChapter(); void addAuthorChapter(String author, String chapter); } | @Test public void givenMapWithConstraints_shouldValidate() { Book book = new Book(); book.addAuthorChapter("Alex","Chapter 1"); book.addAuthorChapter("John","Chapter 2"); book.addAuthorChapter("May","Chapter 3"); Set<ConstraintViolation<Book>> constraintViolations = validator.validate(book); assertThat(constraintViolations.size()).isEqualTo(0); }
@Test public void givenMapWithConstraints_shouldNotValidate() { Book book = new Book(); book.addAuthorChapter(" "," "); Set<ConstraintViolation<Book>> constraintViolations = validator.validate(book); assertThat(constraintViolations.size()).isEqualTo(2); } |
ClientChoice { public void addChoices(Choice choice) { choices.add(choice); } void addChoices(Choice choice); void addClientChoices(String name, List<Choice> choices); List<Choice> getChoices(); Map<String, List<Choice>> getClientChoices(); } | @Test public void givenListWithConstraints_shouldValidate() { ClientChoice clientChoice = new ClientChoice(); clientChoice.addChoices(new Choice(1, "Pineapple")); clientChoice.addChoices(new Choice(2, "Banana")); clientChoice.addChoices(new Choice(3, "Apple")); Set<ConstraintViolation<ClientChoice>> constraintViolations = validator.validate(clientChoice); assertThat(constraintViolations.size()).isEqualTo(0); }
@Test public void givenListWithConstraints_shouldNotValidate() { ClientChoice clientChoice = new ClientChoice(); clientChoice.addChoices(new Choice(1, "Fish")); clientChoice.addChoices(new Choice(2, "Egg")); clientChoice.addChoices(new Choice(3, "Apple")); Set<ConstraintViolation<ClientChoice>> constraintViolations = validator.validate(clientChoice); assertThat(constraintViolations.size()).isEqualTo(2); } |
JsonBindingExample extends JsonData { public List<Book> deserializeListOfBooks() { return JsonbBuilder.create().fromJson(bookListJson, new ArrayList<Book>().getClass().getGenericSuperclass()); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String customizedMapping(); String annotationPropertiesMapping(); String annotationMethodMapping(); String annotationPropertyAndMethodMapping(); String bookAdapterToJson(); Book bookAdapterToBook(); void usingAProvider(); String allCustomizedMapping(); } | @Test @Ignore public void givenJSON_deserializeToListOfBooks() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); List<Book> actualBooks = jsonBindingExample.deserializeListOfBooks(); assertThat(actualBooks).isEqualTo(books); } |
ClientChoice { public void addClientChoices(String name, List<Choice> choices) { clientChoices.put(name, choices); } void addChoices(Choice choice); void addClientChoices(String name, List<Choice> choices); List<Choice> getChoices(); Map<String, List<Choice>> getClientChoices(); } | @Test public void givenMapWithConstraints_shouldValidate() { ClientChoice clientChoice = new ClientChoice(); clientChoice.addClientChoices("John", new ArrayList<Choice>() {{ add(new Choice(1, "Roast Lamb")); add(new Choice(1, "Ice Cream")); add(new Choice(1, "Apple")); }}); clientChoice.addClientChoices("May", new ArrayList<Choice>() {{ add(new Choice(1, "Grapes")); add(new Choice(1, "Beef Stake")); add(new Choice(1, "Pizza")); }}); Set<ConstraintViolation<ClientChoice>> constraintViolations = validator.validate(clientChoice); assertThat(constraintViolations.size()).isEqualTo(0); }
@Test public void givenMapWithConstraints_shouldNotValidate() { ClientChoice clientChoice = new ClientChoice(); clientChoice.addClientChoices("John", new ArrayList<Choice>() {{ add(new Choice(1, "Fish")); add(new Choice(1, "Egg")); add(new Choice(1, "Apple")); }}); clientChoice.addClientChoices("May", new ArrayList<Choice>() {{ add(new Choice(1, "Grapes")); add(new Choice(1, "Beef Stake")); add(new Choice(1, "Pizza")); }}); Set<ConstraintViolation<ClientChoice>> constraintViolations = validator.validate(clientChoice); assertThat(constraintViolations.size()).isEqualTo(2); } |
Customer { public void setEmail(String email) { this.email = email; } String getFirstName(); void setFirstName(String firstName); String getSecondName(); void setSecondName(String secondName); String getEmail(); void setEmail(String email); } | @Test public void givenBeanWithValidEmailConstraints_shouldValidate() { Customer customer = new Customer(); customer.setEmail("[email protected]"); Set<ConstraintViolation<Customer>> constraintViolations = validator.validate(customer); assertThat(constraintViolations.size()).isEqualTo(0); }
@Test public void givenBeanWithInvalidEmailConstraints_shouldNotValidate() { Customer customer = new Customer(); customer.setEmail("[email protected]"); Set<ConstraintViolation<Customer>> constraintViolations = validator.validate(customer); assertThat(constraintViolations.size()).isEqualTo(1); } |
Person { public void setEmail(String email) { this.email = email; } String getFirstName(); void setFirstName(String firstName); String getSecondName(); void setSecondName(String secondName); String getEmail(); void setEmail(String email); } | @Test public void givenBeanWithValidEmailConstraints_shouldValidate() { Person person = new Person(); person.setEmail("[email protected]"); Set<ConstraintViolation<Person>> constraintViolations = validator.validate(person); assertThat(constraintViolations.size()).isEqualTo(0); }
@Test public void givenBeanWithInvalidEmailConstraints_shouldNotValidate() { Person person = new Person(); person.setEmail("alex.theedom@example"); Set<ConstraintViolation<Person>> constraintViolations = validator.validate(person); assertThat(constraintViolations.size()).isEqualTo(0); } |
Person { public void setCars(List<String> cars) { this.cars = cars; } String getFirstName(); void setFirstName(String firstName); String getSecondName(); void setSecondName(String secondName); String getEmail(); void setEmail(String email); List<String> getCars(); void setCars(List<String> cars); } | @Test public void givenBeanWithEmptyElementInCollection_shouldValidate() { Person person = new Person(); person.setCars(new ArrayList<String>() { { add(null); } }); Set<ConstraintViolation<Person>> constraintViolations = validator.validateProperty(person, "cars"); assertThat(constraintViolations.size()).isEqualTo(1); }
@Test public void givenBeanWithEmptyElementInCollection_shouldNotValidate() { Person person = new Person(); person.setCars(new ArrayList<String>() { { add(null); } }); Set<ConstraintViolation<Person>> constraintViolations = validator.validateProperty(person, "cars"); assertThat(constraintViolations.size()).isEqualTo(1); } |
RepeatedConstraint { public void setText(String text) { this.text = text; } String getText(); void setText(String text); } | @Test public void givenBeanWithValidDomain_shouldValidate() { RepeatedConstraint repeatedConstraint = new RepeatedConstraint(); repeatedConstraint.setText("www.readlearncode.com"); Set<ConstraintViolation<RepeatedConstraint>> constraintViolations = validator.validate(repeatedConstraint); assertThat(constraintViolations.size()).isEqualTo(0); }
@Test public void givenBeanWithInValidDomain_shouldNotValidate() { RepeatedConstraint repeatedConstraint = new RepeatedConstraint(); repeatedConstraint.setText("www.readlearncode.net"); Set<ConstraintViolation<RepeatedConstraint>> constraintViolations = validator.validate(repeatedConstraint); assertThat(constraintViolations.size()).isEqualTo(1); } |
JsonBindingExample extends JsonData { public String serializeArrayOfBooks() { return JsonbBuilder.create().toJson(arrayBooks); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String customizedMapping(); String annotationPropertiesMapping(); String annotationMethodMapping(); String annotationPropertyAndMethodMapping(); String bookAdapterToJson(); Book bookAdapterToBook(); void usingAProvider(); String allCustomizedMapping(); } | @Test public void givenArrayOfBooks_shouldSerialiseToJson() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String json = jsonBindingExample.serializeArrayOfBooks(); assertThat(json).isEqualToIgnoringCase(bookListJson); } |
OptionalExample { public void setText(String text) { this.text = Optional.of(text); } Optional<String> getName(); void setName(String name); Optional<String> getText(); void setText(String text); } | @Test public void givenBeanWithOptionalStringExample_shouldNotValidate() { OptionalExample optionalExample = new OptionalExample(); optionalExample.setText(" "); Set<ConstraintViolation<OptionalExample>> constraintViolations = validator.validate(optionalExample); assertThat(constraintViolations.size()).isEqualTo(2); } |
JsonBindingExample extends JsonData { public String serializeArrayOfStrings() { return JsonbBuilder.create().toJson(new String[]{"Java EE", "Java SE"}); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String customizedMapping(); String annotationPropertiesMapping(); String annotationMethodMapping(); String annotationPropertyAndMethodMapping(); String bookAdapterToJson(); Book bookAdapterToBook(); void usingAProvider(); String allCustomizedMapping(); } | @Test public void givenArrayOfStrings_shouldSerialiseToJson() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String json = jsonBindingExample.serializeArrayOfStrings(); assertThat(json).isEqualToIgnoringCase("[\"Java EE\",\"Java SE\"]"); } |
JsonBindingExample extends JsonData { public String customizedMapping() { JsonbConfig jsonbConfig = new JsonbConfig() .withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_DASHES) .withPropertyOrderStrategy(PropertyOrderStrategy.LEXICOGRAPHICAL) .withStrictIJSON(true) .withFormatting(true) .withNullValues(true); Jsonb jsonb = JsonbBuilder.create(jsonbConfig); return jsonb.toJson(book1); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String customizedMapping(); String annotationPropertiesMapping(); String annotationMethodMapping(); String annotationPropertyAndMethodMapping(); String bookAdapterToJson(); Book bookAdapterToBook(); void usingAProvider(); String allCustomizedMapping(); } | @Test public void givenCustomisationOnProperties_shouldProduceJSON() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String result = jsonBindingExample.customizedMapping(); assertThat(result).isEqualToIgnoringCase(customisedJson); } |
JsonBindingExample extends JsonData { public String annotationMethodMapping() { return JsonbBuilder.create().toJson(newspaper); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String customizedMapping(); String annotationPropertiesMapping(); String annotationMethodMapping(); String annotationPropertyAndMethodMapping(); String bookAdapterToJson(); Book bookAdapterToBook(); void usingAProvider(); String allCustomizedMapping(); } | @Test public void givenCustomisationOnMethods_shouldProduceJSON() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String result = jsonBindingExample.annotationMethodMapping(); assertThat(result).isEqualToIgnoringCase(customisedJsonNewspaper); } |
JsonBindingExample extends JsonData { public String annotationPropertyAndMethodMapping() { return JsonbBuilder.create().toJson(booklet); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String customizedMapping(); String annotationPropertiesMapping(); String annotationMethodMapping(); String annotationPropertyAndMethodMapping(); String bookAdapterToJson(); Book bookAdapterToBook(); void usingAProvider(); String allCustomizedMapping(); } | @Test public void givenCustomisationOnPropertiesAndMethods_shouldProduceJSON() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String result = jsonBindingExample.annotationPropertyAndMethodMapping(); assertThat(result).isEqualToIgnoringCase("{\"cost\":\"10.00\",\"author\":{\"firstName\":\"Alex\",\"lastName\":\"Theedom\"}}"); } |
JsonBindingExample extends JsonData { public String annotationPropertiesMapping() { return JsonbBuilder.create().toJson(magazine); } String serializeBook(); Book deserializeBook(); String serializeListOfBooks(); List<Book> deserializeListOfBooks(); String serializeArrayOfBooks(); String serializeArrayOfStrings(); String customizedMapping(); String annotationPropertiesMapping(); String annotationMethodMapping(); String annotationPropertyAndMethodMapping(); String bookAdapterToJson(); Book bookAdapterToBook(); void usingAProvider(); String allCustomizedMapping(); } | @Test public void givenAnnotationPojo_shouldProduceJson() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String result = jsonBindingExample.annotationPropertiesMapping(); assertThat(result).isEqualToIgnoringCase(expectedMagazine); } |
AuthenticationUtil { public static void clearAuthentication() { SecurityContextHolder.getContext().setAuthentication(null); } private AuthenticationUtil(); static void clearAuthentication(); static void configureAuthentication(String role); } | @Test public void clearAuthentication_ShouldRemoveAuthenticationFromSecurityContext() { Authentication authentication = createAuthentication(); SecurityContextHolder.getContext().setAuthentication(authentication); AuthenticationUtil.clearAuthentication(); Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication(); assertThat(currentAuthentication).isNull(); } |
AuthenticationUtil { public static void configureAuthentication(String role) { Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(role); Authentication authentication = new UsernamePasswordAuthenticationToken( USERNAME, role, authorities ); SecurityContextHolder.getContext().setAuthentication(authentication); } private AuthenticationUtil(); static void clearAuthentication(); static void configureAuthentication(String role); } | @Test public void configurationAuthentication_ShouldSetAuthenticationToSecurityContext() { AuthenticationUtil.configureAuthentication(ROLE); Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication(); assertThat(currentAuthentication.getAuthorities()).hasSize(1); assertThat(currentAuthentication.getAuthorities().iterator().next().getAuthority()).isEqualTo(ROLE); User principal = (User) currentAuthentication.getPrincipal(); assertThat(principal.getAuthorities()).hasSize(1); assertThat(principal.getAuthorities().iterator().next().getAuthority()).isEqualTo(ROLE); } |
SerializerFactoryLoader { public static SerializerFactory getFactory(ProcessingEnvironment processingEnv) { return new SerializerFactoryImpl(loadExtensions(processingEnv), processingEnv); } private SerializerFactoryLoader(); static SerializerFactory getFactory(ProcessingEnvironment processingEnv); } | @Test public void getFactory_extensionsLoaded() throws Exception { SerializerFactory factory = SerializerFactoryLoader.getFactory(mockProcessingEnvironment); Serializer actualSerializer = factory.getSerializer(typeMirrorOf(String.class)); assertThat(actualSerializer.getClass().getName()) .contains("TestStringSerializerFactory$TestStringSerializer"); } |
AnnotationValues { public static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value) { return TYPE_MIRRORS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); } | @Test public void getTypeMirrors() { TypeMirror insideClassA = getTypeElement(InsideClassA.class).asType(); TypeMirror insideClassB = getTypeElement(InsideClassB.class).asType(); AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "classValues"); ImmutableList<DeclaredType> valueElements = AnnotationValues.getTypeMirrors(value); assertThat(valueElements) .comparingElementsUsing(Correspondence.from(types::isSameType, "has Same Type")) .containsExactly(insideClassA, insideClassB) .inOrder(); } |
AnnotationValues { public static AnnotationMirror getAnnotationMirror(AnnotationValue value) { return AnnotationMirrorVisitor.INSTANCE.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); } | @Test public void getAnnotationMirror() { TypeElement insideAnnotation = getTypeElement(InsideAnnotation.class); AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "insideAnnotationValue"); AnnotationMirror annotationMirror = AnnotationValues.getAnnotationMirror(value); assertThat(annotationMirror.getAnnotationType().asElement()).isEqualTo(insideAnnotation); assertThat(AnnotationMirrors.getAnnotationValue(annotationMirror, "value").getValue()) .isEqualTo(19); } |
AnnotationValues { public static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value) { return ANNOTATION_MIRRORS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); } | @Test public void getAnnotationMirrors() { TypeElement insideAnnotation = getTypeElement(InsideAnnotation.class); AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "insideAnnotationValues"); ImmutableList<AnnotationMirror> annotationMirrors = AnnotationValues.getAnnotationMirrors(value); ImmutableList<Element> valueElements = annotationMirrors.stream() .map(AnnotationMirror::getAnnotationType) .map(DeclaredType::asElement) .collect(toImmutableList()); assertThat(valueElements).containsExactly(insideAnnotation, insideAnnotation); ImmutableList<Object> valuesStoredInAnnotation = annotationMirrors.stream() .map( annotationMirror -> AnnotationMirrors.getAnnotationValue(annotationMirror, "value").getValue()) .collect(toImmutableList()); assertThat(valuesStoredInAnnotation).containsExactly(20, 21).inOrder(); } |
AnnotationValues { public static String getString(AnnotationValue value) { return valueOfType(value, String.class); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); } | @Test public void getString() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "stringValue"); assertThat(AnnotationValues.getString(value)).isEqualTo("hello"); } |
AnnotationValues { public static ImmutableList<String> getStrings(AnnotationValue value) { return STRINGS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); } | @Test public void getStrings() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "stringValues"); assertThat(AnnotationValues.getStrings(value)).containsExactly("it's", "me").inOrder(); } |
AnnotationValues { public static VariableElement getEnum(AnnotationValue value) { return EnumVisitor.INSTANCE.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); } | @Test public void getEnum() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "enumValue"); assertThat(AnnotationValues.getEnum(value)).isEqualTo(value.getValue()); } |
AnnotationValues { public static ImmutableList<VariableElement> getEnums(AnnotationValue value) { return ENUMS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); } | @Test public void getEnums() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "enumValues"); assertThat(getEnumNames(AnnotationValues.getEnums(value))) .containsExactly(Foo.BAZ.name(), Foo.BAH.name()) .inOrder(); } |
AnnotationValues { public static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value) { return ANNOTATION_VALUES_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); } | @Test public void getAnnotationValues() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "intValues"); ImmutableList<AnnotationValue> values = AnnotationValues.getAnnotationValues(value); assertThat(values) .comparingElementsUsing(Correspondence.transforming(AnnotationValue::getValue, "has value")) .containsExactly(1, 2) .inOrder(); } |
AnnotationValues { public static int getInt(AnnotationValue value) { return valueOfType(value, Integer.class); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); } | @Test public void getInt() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "intValue"); assertThat(AnnotationValues.getInt(value)).isEqualTo(5); } |
AnnotationValues { public static ImmutableList<Integer> getInts(AnnotationValue value) { return INTS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); } | @Test public void getInts() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "intValues"); assertThat(AnnotationValues.getInts(value)).containsExactly(1, 2).inOrder(); } |
OptionalSerializerExtension implements SerializerExtension { @Override public Optional<Serializer> getSerializer( TypeMirror typeMirror, SerializerFactory factory, ProcessingEnvironment processingEnv) { if (!isOptional(typeMirror)) { return Optional.empty(); } TypeMirror containedType = getContainedType(typeMirror); Serializer containedTypeSerializer = factory.getSerializer(containedType); return Optional.of(new OptionalSerializer(containedTypeSerializer)); } OptionalSerializerExtension(); @Override Optional<Serializer> getSerializer(
TypeMirror typeMirror, SerializerFactory factory, ProcessingEnvironment processingEnv); } | @Test public void toProxy() { TypeMirror typeMirror = declaredTypeOf(Optional.class, Integer.class); Serializer serializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment).get(); CodeBlock actualCodeBlock = serializer.toProxy(CodeBlock.of("x")); assertThat(actualCodeBlock.toString()).isEqualTo("x.isPresent() ? x.get() : null"); }
@Test public void fromProxy() { TypeMirror typeMirror = declaredTypeOf(Optional.class, Integer.class); Serializer serializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment).get(); CodeBlock actualCodeBlock = serializer.fromProxy(CodeBlock.of("x")); assertThat(actualCodeBlock.toString()) .isEqualTo("java.util.Optional.ofNullable(x == null ? null : x)"); }
@Test public void getSerializer_nonOptional_emptyReturned() { TypeMirror typeMirror = typeMirrorOf(String.class); Optional<Serializer> actualSerializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment); assertThat(actualSerializer).isEmpty(); }
@Test public void getSerializer_optional_serializerReturned() { TypeMirror typeMirror = typeMirrorOf(Optional.class); Serializer actualSerializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment).get(); assertThat(actualSerializer.getClass().getName()) .contains("OptionalSerializerExtension$OptionalSerializer"); }
@Test public void proxyFieldType() { TypeMirror typeMirror = declaredTypeOf(Optional.class, Integer.class); Serializer serializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment).get(); TypeMirror actualTypeMirror = serializer.proxyFieldType(); assertThat(actualTypeMirror).isEqualTo(typeMirrorOf(Integer.class)); } |
AnnotationValues { public static long getLong(AnnotationValue value) { return valueOfType(value, Long.class); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); } | @Test public void getLong() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "longValue"); assertThat(AnnotationValues.getLong(value)).isEqualTo(6L); } |
AnnotationValues { public static ImmutableList<Long> getLongs(AnnotationValue value) { return LONGS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); } | @Test public void getLongs() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "longValues"); assertThat(AnnotationValues.getLongs(value)).containsExactly(3L, 4L).inOrder(); } |
Subsets and Splits