method2testcases
stringlengths 118
6.63k
|
---|
### Question:
Proto { public void applyBindings() { initBindings(null).applyBindings(null); } Proto(Object obj, Type type, BrwsrCtx context); BrwsrCtx getContext(); void acquireLock(); void acquireLock(String propName); void accessProperty(String propName); void verifyUnlocked(); void releaseLock(); void valueHasMutated(final String propName); void valueHasMutated(
final String propName, final Object oldValue, final Object newValue
); void applyBindings(); void applyBindings(String id); void runInBrowser(Runnable run); void runInBrowser(final int index, final Object... args); void initTo(Collection<?> to, Object array); void extract(Object json, String[] props, Object[] values); T read(Class<T> modelClass, Object data); void loadJSON(final int index,
String urlBefore, String urlAfter, String method,
final Object data
); void loadJSON(final int index,
String urlBefore, String urlAfter, String method,
final Object data, final Object... params
); void loadJSONWithHeaders(final int index,
String headers,
String urlBefore, String urlAfter, String method,
final Object data, final Object... params
); Object wsOpen(final int index, String url, Object data); void wsSend(Object webSocket, String url, Object data); String toString(Object data, String propName); Number toNumber(Object data, String propName); T toModel(Class<T> type, Object data); List<T> createList(String propName, int onChange, String... dependingProps); void cloneList(Collection<T> to, BrwsrCtx ctx, Collection<T> from); }### Answer:
@Test public void registerFunctionsIncrementally() { BrwsrCtx ctx = Contexts.newBuilder().register(Technology.class, this, 100).build(); MyType type = new MyType(); MyObj obj = new MyObj(type, ctx); type.registerFunction("fifth", 5); obj.proto.applyBindings(); assertEquals(6, functions.length); assertNull(functions[0]); assertNull(functions[1]); assertNull(functions[2]); assertNull(functions[3]); assertNull(functions[4]); assertNotNull(functions[5]); } |
### Question:
Models { public static boolean isModel(Class<?> clazz) { return JSON.isModel(clazz); } private Models(); static boolean isModel(Class<?> clazz); static Model bind(Model model, BrwsrCtx context); static M parse(BrwsrCtx c, Class<M> model, InputStream is); static void parse(
BrwsrCtx c, Class<M> model,
InputStream is, Collection<? super M> collectTo
); static M fromRaw(BrwsrCtx ctx, Class<M> model, Object jsonObject); static Object toRaw(Object model); static void applyBindings(Object model); static void applyBindings(Object model, String targetId); static List<T> asList(T... values); }### Answer:
@Test public void peopleAreModel() { assertTrue(Models.isModel(People.class), "People are generated class"); }
@Test public void personIsModel() { assertTrue(Models.isModel(Person.class), "Person is generated class"); }
@Test public void implClassIsNotModel() { assertFalse(Models.isModel(PersonImpl.class), "Impl is not model"); }
@Test public void randomClassIsNotModel() { assertFalse(Models.isModel(StringBuilder.class), "JDK classes are not model"); } |
### Question:
CoordImpl extends Position.Coordinates { @Override public double getLatitude() { return provider.latitude(data); } CoordImpl(Coords data, GLProvider<Coords, ?> p); @Override double getLatitude(); @Override double getLongitude(); @Override double getAccuracy(); @Override Double getAltitude(); @Override Double getAltitudeAccuracy(); @Override Double getHeading(); @Override Double getSpeed(); }### Answer:
@Test public void testGetLatitude() { CoordImpl<Double> c = new CoordImpl<Double>(50.5, this); assertEquals(c.getLatitude(), 50.5, 0.1, "Latitude returned as provided"); } |
### Question:
Scripts { public static Scripts newPresenter() { return new Scripts(); } private Scripts(); @Deprecated static Presenter createPresenter(); @Deprecated static Presenter createPresenter(Executor exc); static Scripts newPresenter(); Scripts executor(Executor exc); Scripts engine(ScriptEngine engine); Scripts sanitize(boolean yesOrNo); Presenter build(); }### Answer:
@Test public void isSanitizationOnByDefault() throws Exception { assertSanitized(Scripts.newPresenter()); } |
### Question:
FXBrwsr extends Application { static String findCalleeClassName() { StackTraceElement[] frames = new Exception().getStackTrace(); for (StackTraceElement e : frames) { String cn = e.getClassName(); if (cn.startsWith("org.netbeans.html.")) { continue; } if (cn.startsWith("net.java.html.")) { continue; } if (cn.startsWith("java.")) { continue; } if (cn.startsWith("javafx.")) { continue; } if (cn.startsWith("com.sun.")) { continue; } return cn; } return "org.netbeans.html"; } static synchronized WebView findWebView(final URL url, final AbstractFXPresenter onLoad); @Override void start(Stage primaryStage); }### Answer:
@Test public void testFindCalleeClassName() throws InterruptedException { String callee = invokeMain(); assertEquals(callee, SampleApp.class.getName(), "Callee is found correctly"); } |
### Question:
FXBrowsers { public static void runInBrowser(WebView webView, Runnable code) { Object ud = webView.getUserData(); if (ud instanceof Fn.Ref<?>) { ud = ((Fn.Ref<?>)ud).presenter(); } if (!(ud instanceof InitializeWebView)) { throw new IllegalArgumentException(); } ((InitializeWebView)ud).runInContext(code); } private FXBrowsers(); static void load(
final WebView webView, final URL url,
Class<?> onPageLoad, String methodName,
String... args
); static void load(
WebView webView, final URL url, Runnable onPageLoad
); static void load(
WebView webView, final URL url, Runnable onPageLoad, ClassLoader loader
); static void load(
WebView webView, final URL url, Runnable onPageLoad, ClassLoader loader,
Object... context
); static void runInBrowser(WebView webView, Runnable code); }### Answer:
@Test public void brwsrCtxExecute() throws Throwable { assertFalse(inJS(), "We aren't in JS now"); final CountDownLatch init = new CountDownLatch(1); final BrwsrCtx[] ctx = { null }; FXBrowsers.runInBrowser(App.getV1(), new Runnable() { @Override public void run() { assertTrue(inJS(), "We are in JS context now"); ctx[0] = BrwsrCtx.findDefault(FXBrowsersTest.class); init.countDown(); } }); init.await(); final CountDownLatch cdl = new CountDownLatch(1); class R implements Runnable { @Override public void run() { if (Platform.isFxApplicationThread()) { assertTrue(inJS()); cdl.countDown(); } else { ctx[0].execute(this); } } } new Thread(new R(), "Background thread").start(); cdl.await(); } |
### Question:
JsCallback { final String parse(String body) { StringBuilder sb = new StringBuilder(); int pos = 0; for (;;) { int next = body.indexOf(".@", pos); if (next == -1) { sb.append(body.substring(pos)); body = sb.toString(); break; } int ident = next; while (ident > 0) { if (!Character.isJavaIdentifierPart(body.charAt(--ident))) { ident++; break; } } String refId = body.substring(ident, next); sb.append(body.substring(pos, ident)); int sigBeg = body.indexOf('(', next); int sigEnd = body.indexOf(')', sigBeg); int colon4 = body.indexOf("::", next); if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) { throw new IllegalStateException( "Wrong format of instance callback. " + "Should be: '[email protected]::method(Ljava/lang/Object;)(param)':\n" + body ); } String fqn = body.substring(next + 2, colon4); String method = body.substring(colon4 + 2, sigBeg); String params = body.substring(sigBeg, sigEnd + 1); int paramBeg = body.indexOf('(', sigEnd + 1); if (paramBeg == -1) { throw new IllegalStateException( "Wrong format of instance callback. " + "Should be: '[email protected]::method(Ljava/lang/Object;)(param)':\n" + body ); } sb.append(callMethod(refId, fqn, method, params)); if (body.charAt(paramBeg + 1) != (')')) { sb.append(","); } pos = paramBeg + 1; } pos = 0; sb = null; for (;;) { int next = body.indexOf("@", pos); if (next == -1) { if (sb == null) { return body; } sb.append(body.substring(pos)); return sb.toString(); } if (sb == null) { sb = new StringBuilder(); } sb.append(body.substring(pos, next)); int sigBeg = body.indexOf('(', next); int sigEnd = body.indexOf(')', sigBeg); int colon4 = body.indexOf("::", next); int paramBeg = body.indexOf('(', sigEnd + 1); if (sigBeg == -1 || sigEnd == -1 || colon4 == -1 || paramBeg == -1) { throw new IllegalStateException( "Wrong format of static callback. " + "Should be: '@pkg.Class::staticMethod(Ljava/lang/Object;)(param)':\n" + body ); } String fqn = body.substring(next + 1, colon4); String method = body.substring(colon4 + 2, sigBeg); String params = body.substring(sigBeg, sigEnd + 1); sb.append(callMethod(null, fqn, method, params)); pos = paramBeg + 1; } } }### Answer:
@Test public void missingTypeSpecification() { String body = "console[attr] = function(msg) {\n" + " @org.netbeans.html.charts.Main::log(msg);\n" + "};\n"; JsCallback instance = new JsCallbackImpl(); try { String result = instance.parse(body); fail("The parsing should fail!"); } catch (IllegalStateException ex) { } } |
### Question:
FallbackIdentity extends WeakReference<Fn.Presenter> implements Fn.Ref { @Override public int hashCode() { return hashCode; } FallbackIdentity(Fn.Presenter p); @Override Fn.Ref reference(); @Override Fn.Presenter presenter(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testIdAndWeak() { Fn.Presenter p = new Fn.Presenter() { @Override public Fn defineFn(String arg0, String... arg1) { return null; } @Override public void displayPage(URL arg0, Runnable arg1) { } @Override public void loadScript(Reader arg0) throws Exception { } }; Fn.Ref<?> id1 = Fn.ref(p); Fn.Ref<?> id2 = Fn.ref(p); assertNotSame(id1, id2); assertEquals(id1, id2); assertEquals(id1.hashCode(), id2.hashCode()); Reference<Fn.Presenter> ref = new WeakReference<>(p); p = null; NbTestCase.assertGC("Presenter is held weakly", ref); } |
### Question:
BrowserBuilder { static URL findLocalizedResourceURL(String resource, Locale l, IOException[] mal, Class<?> relativeTo) { URL url = null; if (l != null) { url = findResourceURL(resource, "_" + l.getLanguage() + "_" + l.getCountry(), mal, relativeTo); if (url != null) { return url; } url = findResourceURL(resource, "_" + l.getLanguage(), mal, relativeTo); } if (url != null) { return url; } return findResourceURL(resource, null, mal, relativeTo); } private BrowserBuilder(Object[] context); static BrowserBuilder newBrowser(Object... context); BrowserBuilder loadClass(Class<?> mainClass); BrowserBuilder loadFinished(Runnable r); BrowserBuilder loadPage(String page); BrowserBuilder locale(Locale locale); BrowserBuilder invoke(String methodName, String... args); BrowserBuilder classloader(ClassLoader l); void showAndWait(); }### Answer:
@Test public void findsZhCN() throws IOException { File zh = new File(dir, "index_zh.html"); zh.createNewFile(); File zhCN = new File(dir, "index_zh_CN.html"); zhCN.createNewFile(); IOException[] mal = { null }; URL url = BrowserBuilder.findLocalizedResourceURL("index.html", Locale.SIMPLIFIED_CHINESE, mal, BrowserBuilder.class); assertEquals(url, zhCN.toURI().toURL(), "Found both suffixes"); }
@Test public void findsZh() throws IOException { File zh = new File(dir, "index_zh.html"); zh.createNewFile(); IOException[] mal = { null }; URL url = BrowserBuilder.findLocalizedResourceURL("index.html", Locale.SIMPLIFIED_CHINESE, mal, BrowserBuilder.class); assertEquals(url, zh.toURI().toURL(), "Found one suffix"); }
@Test public void findsIndex() throws IOException { IOException[] mal = { null }; URL url = BrowserBuilder.findLocalizedResourceURL("index.html", Locale.SIMPLIFIED_CHINESE, mal, BrowserBuilder.class); assertEquals(url, index.toURI().toURL(), "Found root file"); } |
### Question:
JSONList extends SimpleList<T> { @Override public String toString() { Iterator<T> it = iterator(); if (!it.hasNext()) { return "[]"; } String sep = ""; StringBuilder sb = new StringBuilder(); sb.append('['); while (it.hasNext()) { T t = it.next(); sb.append(sep); sb.append(JSON.toJSON(t)); sep = ","; } sb.append(']'); return sb.toString(); } JSONList(Proto proto, String name, int changeIndex, String... deps); void init(Object values); static void init(Collection<T> to, Object values); @Override boolean add(T e); @Override boolean addAll(Collection<? extends T> c); @Override boolean addAll(int index, Collection<? extends T> c); void fastReplace(Collection<? extends T> c); @Override boolean remove(Object o); @Override void clear(); @Override boolean removeAll(Collection<?> c); void sort(Comparator<? super T> c); @Override boolean retainAll(Collection<?> c); @Override T set(int index, T element); @Override void add(int index, T element); @Override T remove(int index); @Override String toString(); @Override JSONList clone(); }### Answer:
@Test public void testConvertorOnAnArray() { BrwsrCtx c = Contexts.newBuilder().register(Technology.class, this, 1).build(); Person p = Models.bind(new Person(), c); p.setFirstName("1"); p.setLastName("2"); p.setSex(Sex.MALE); People people = Models.bind(new People(p), c).applyBindings(); assertEquals(people.getInfo().toString(), "[{\"firstName\":\"1\",\"lastName\":\"2\",\"sex\":\"MALE\"}]", "Converted to real JSON"); PropertyBinding pb = bindings.get("info"); assertNotNull(pb, "Binding for info found"); Object real = pb.getValue(); assertTrue(real instanceof Object[], "It is an array: " + real); Object[] arr = (Object[])real; assertEquals(arr.length, 1, "Size is one"); assertEquals(this, arr[0], "I am the right model"); }
@Test public void toStringOnArrayOfStrings() { JSNLst l = new JSNLst("Jarda", "Jirka", "Parda"); assertEquals(l.toString(), "{\"names\":[\"Jarda\",\"Jirka\",\"Parda\"]}", "Properly quoted"); } |
### Question:
JSONList extends SimpleList<T> { @Override public boolean add(T e) { prepareChange(); boolean ret = super.add(e); notifyChange(); return ret; } JSONList(Proto proto, String name, int changeIndex, String... deps); void init(Object values); static void init(Collection<T> to, Object values); @Override boolean add(T e); @Override boolean addAll(Collection<? extends T> c); @Override boolean addAll(int index, Collection<? extends T> c); void fastReplace(Collection<? extends T> c); @Override boolean remove(Object o); @Override void clear(); @Override boolean removeAll(Collection<?> c); void sort(Comparator<? super T> c); @Override boolean retainAll(Collection<?> c); @Override T set(int index, T element); @Override void add(int index, T element); @Override T remove(int index); @Override String toString(); @Override JSONList clone(); }### Answer:
@Test public void testNicknames() { BrwsrCtx c = Contexts.newBuilder().register(Technology.class, this, 1).build(); People people = Models.bind(new People(), c).applyBindings(); people.getNicknames().add("One"); people.getNicknames().add("Two"); PropertyBinding pb = bindings.get("nicknames"); assertNotNull(pb, "Binding for info found"); Object real = pb.getValue(); assertTrue(real instanceof Object[], "It is an array: " + real); Object[] arr = (Object[])real; assertEquals(arr.length, 2, "Length two"); assertEquals(arr[0], "One", "Text should be in the model"); assertEquals(arr[1], "Two", "2nd text in the model"); }
@Test public void testConvertorOnAnArrayWithWrapper() { this.replaceArray = true; BrwsrCtx c = Contexts.newBuilder().register(Technology.class, this, 1).build(); Person p = Models.bind(new Person(), c); p.setFirstName("1"); p.setLastName("2"); p.setSex(Sex.MALE); People people = Models.bind(new People(), c).applyBindings(); people.getInfo().add(p); Object real = JSON.find(people.getInfo()); assertEquals(real, this, "I am the model of the array"); }
@Test public void bindingsOnArray() { this.replaceArray = true; BrwsrCtx c = Contexts.newBuilder().register(Technology.class, this, 1).build(); People p = Models.bind(new People(), c).applyBindings(); p.getAge().add(30); PropertyBinding pb = bindings.get("age"); assertNotNull(pb, "There is a binding for age list"); assertEquals(pb.getValue(), this, "I am the model of the array"); } |
### Question:
JSON { public static String stringValue(Object val) { if (val instanceof Boolean) { return ((Boolean)val ? "true" : "false"); } if (isNumeric(val)) { return Long.toString(((Number)val).longValue()); } if (val instanceof Float) { return Float.toString((Float)val); } if (val instanceof Double) { return Double.toString((Double)val); } return (String)val; } private JSON(); static Transfer findTransfer(BrwsrCtx c); static WSTransfer<?> findWSTransfer(BrwsrCtx c); static void readBindings(BrwsrCtx c, M model, Object value); static void extract(BrwsrCtx c, Object value, String[] props, Object[] values); static String toJSON(Object value); static String toString(BrwsrCtx c, Object obj, String prop); static Number toNumber(BrwsrCtx c, Object obj, String prop); static M toModel(BrwsrCtx c, Class<M> aClass, Object data, Object object); static boolean isSame(int a, int b); static boolean isSame(double a, double b); static boolean isSame(Object a, Object b); static int hashPlus(Object o, int h); static T extractValue(Class<T> type, Object val); static String stringValue(Object val); static Number numberValue(Object val); static Character charValue(Object val); static Boolean boolValue(Object val); static Object find(Object object, Bindings model); static Object find(Object object); static void applyBindings(Object object, String id); static void register(Class c, Proto.Type<?> type); static boolean isModel(Class<?> clazz); static Model bindTo(Model model, BrwsrCtx c); static T readStream(BrwsrCtx c, Class<T> modelClazz, InputStream data, Collection<? super T> collectTo); static T read(BrwsrCtx c, Class<T> modelClazz, Object data); }### Answer:
@Test public void longToStringValue() { assertEquals(JSON.stringValue(Long.valueOf(1)), "1"); } |
### Question:
JSON { public static Number numberValue(Object val) { if (val instanceof String) { try { return Double.valueOf((String)val); } catch (NumberFormatException ex) { return Double.NaN; } } if (val instanceof Boolean) { return (Boolean)val ? 1 : 0; } return (Number)val; } private JSON(); static Transfer findTransfer(BrwsrCtx c); static WSTransfer<?> findWSTransfer(BrwsrCtx c); static void readBindings(BrwsrCtx c, M model, Object value); static void extract(BrwsrCtx c, Object value, String[] props, Object[] values); static String toJSON(Object value); static String toString(BrwsrCtx c, Object obj, String prop); static Number toNumber(BrwsrCtx c, Object obj, String prop); static M toModel(BrwsrCtx c, Class<M> aClass, Object data, Object object); static boolean isSame(int a, int b); static boolean isSame(double a, double b); static boolean isSame(Object a, Object b); static int hashPlus(Object o, int h); static T extractValue(Class<T> type, Object val); static String stringValue(Object val); static Number numberValue(Object val); static Character charValue(Object val); static Boolean boolValue(Object val); static Object find(Object object, Bindings model); static Object find(Object object); static void applyBindings(Object object, String id); static void register(Class c, Proto.Type<?> type); static boolean isModel(Class<?> clazz); static Model bindTo(Model model, BrwsrCtx c); static T readStream(BrwsrCtx c, Class<T> modelClazz, InputStream data, Collection<? super T> collectTo); static T read(BrwsrCtx c, Class<T> modelClazz, Object data); }### Answer:
@Test public void booleanIsSortOfNumber() { assertEquals(JSON.numberValue(Boolean.TRUE), Integer.valueOf(1)); assertEquals(JSON.numberValue(Boolean.FALSE), Integer.valueOf(0)); } |
### Question:
TableXMLFormatter { public String getSchemaXml() { String result= "<schema>"; Map<String, TableSchema> tableSchemas = schemaExtractor.getTablesFromQuery(query); for (TableSchema tableSchema : tableSchemas.values()) { result += getTableSchemaXml(tableSchema); } result += "</schema>"; return result; } TableXMLFormatter(ISchemaExtractor schemaExtractor, String query); String getSchemaXml(); }### Answer:
@Test public void queryTest() { tableXMLFormatter = new TableXMLFormatter(schemaExtractor, QUERY); String expected = "<schema>" + "<table name=\"users\">" + "<column name=\"username\" type=\"varchar\" notnull=\"true\"/>" + "<column name=\"email\" type=\"varchar\" notnull=\"true\"/>" + "</table>" + "</schema>"; String actual = tableXMLFormatter.getSchemaXml(); Assert.assertEquals(expected, actual); } |
### Question:
QueryStripper { public String getStrippedSql() { String secureQuery = new SqlSecurer(sql).getSecureSql(); Select stmt = null; try { stmt = (Select) CCJSqlParserUtil.parse(secureQuery); } catch (JSQLParserException e) { throw new RuntimeException(e); } stmt.getSelectBody().accept(new QueryStripperVisitor()); return stmt.toString(); } QueryStripper(String sql); String getStrippedSql(); }### Answer:
@Test public void stripDouble() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = 50.1234").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = 0"); }
@Test public void stripDate() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = '1999-03-04'").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = '2000-01-01'"); }
@Test public void stripDate2() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = '1999-3-4'").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = '2000-01-01'"); }
@Test public void stripTime() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = '1:13:56'").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = '12:00:00'"); }
@Test public void stripTime2() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = '14:13:56'").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = '12:00:00'"); }
@Test public void stripTimestamp() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = '1999-03-04 01:13:56'").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = '2000-01-01 12:00:00'"); }
@Test public void stripTimestamp2() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = '1999-3-4 13:13:56.100'").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = '2000-01-01 12:00:00'"); }
@Test public void stripSelectAllQuery() { String sql = new QueryStripper("SELECT * FROM Table").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\""); }
@Test public void stripInteger() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = 10").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = 0"); }
@Test public void stripString() { String sql = new QueryStripper("SELECT * FROM Table WHERE col = 'test'").getStrippedSql(); Assertions.assertEquals(sql, "SELECT * FROM \"TABLE\" WHERE \"COL\" = ''"); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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); }### Answer:
@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"); } |
### Question:
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); }### Answer:
@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;"); } |
### Question:
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); }### Answer:
@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"); } |
### Question:
EvoSQLFactory { public EvoSQL createEvoSQL(ConnectionData connectionData) { return new EvoSQL( connectionData.getConnectionString(), connectionData.getDatabase(), connectionData.getUsername(), connectionData.getPassword(), false); } EvoSQL createEvoSQL(ConnectionData connectionData); }### Answer:
@Test void createEvoSQLTest() { ConnectionData connectionData = new ConnectionData("cs", "db", "user", "pass"); EvoSQLFactory evoSQLFactory = new EvoSQLFactory(); assertThat(evoSQLFactory.createEvoSQL(connectionData)).isInstanceOf(EvoSQL.class); } |
### Question:
ExistingDataRunner implements QueryRunner { @Override public Result runQuery(String sqlQuery, ConnectionData connectionData) { return result; } @Override Result runQuery(String sqlQuery, ConnectionData connectionData); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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'"); } |
### Question:
SelectionBuilder extends QueryBuilder { @Override public List<String> buildQueries(Path path) { return Collections.singletonList(path.getPathSql()); } SelectionBuilder(VendorOptions vendorOptions); @Override List<String> buildQueries(Path path); }### Answer:
@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())); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
PostgreSQLOptions implements VendorOptions { @Override public String escapeIdentifier(String id) { return "\"" + id + "\""; } @Override String escapeIdentifier(String id); }### Answer:
@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\""); } |
### Question:
MySQLOptions implements VendorOptions { @Override public String escapeIdentifier(String id) { return "`" + id + "`"; } @Override String escapeIdentifier(String id); }### Answer:
@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`"); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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; }### Answer:
@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})); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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; }### Answer:
@Test public void vectorLength() throws Exception { } |
### Question:
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; }### Answer:
@Test public void createVector() throws Exception { } |
### Question:
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; }### Answer:
@Test public void distanceDotLine() throws Exception { } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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(); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
InboxModel implements InteractionContextSink { public abstract Map<Identifier, InboxTask> getTasks(); abstract Map<Identifier, InboxTask> getTasks(); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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(); }### Answer:
@Test public void toStringTest() { String testVersion = "7.0.0"; Version version = new Version(testVersion); assertEquals(version.toString(), testVersion); } |
### Question:
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(); }### Answer:
@Test public void givenJSON_shouldDeserializeBook() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); Book book = jsonBindingExample.deserializeBook(); assertThat(book).isEqualTo(book1); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test @Ignore("Book adapter missing") public void givenAdapter_shouldDeserialiseJson() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); Book book = jsonBindingExample.bookAdapterToBook(); assertThat(book).isEqualTo(bookAdapted); } |
### Question:
EnumExample { public String enumSerialisationInObject() { return JsonbBuilder.create().toJson(new container()); } String enumSerialisation(); String enumSerialisationInObject(); }### Answer:
@Test public void enumSerialisationInObject() { String expectedJson = "{\"binding\":\"Hard Back\"}"; EnumExample enumExample = new EnumExample(); String actualJson = enumExample.enumSerialisationInObject(); assertThat(actualJson).isEqualTo(expectedJson); } |
### Question:
EnumExample { public String enumSerialisation() { return JsonbBuilder.create().toJson(Binding.HARD_BACK.name()); } String enumSerialisation(); String enumSerialisationInObject(); }### Answer:
@Test @Ignore public void givenEnum_shouldThrownExceptionWhenSerialised() { new EnumExample().enumSerialisation(); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test public void givenNestedInnerClass_shouldSerializeNestedClasses() { String expectedJson = "{\"name\":\"Inner Class\"}"; NestedClassExample nestedClassExample = new NestedClassExample(); String actualJson = nestedClassExample.serializeNestedClasses(); assertThat(actualJson).isEqualTo(expectedJson); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test public void givenBookObject_shouldSerializeToJSONString() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String json = jsonBindingExample.serializeBook(); assertThat(json).isEqualToIgnoringCase(bookJson); } |
### Question:
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(); }### Answer:
@Test public void givenPointerToTopic_shouldReturnTopic() { JsonPointerExample jsonPointerExample = new JsonPointerExample(); String topic = jsonPointerExample.find(); assertThat(topic).isEqualToIgnoringCase("Cloud"); } |
### Question:
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(); }### Answer:
@Test public void givenPointerToTopic_shouldReplaceTopic() { JsonPointerExample jsonPointerExample = new JsonPointerExample(); String topic = jsonPointerExample.replace(); assertThat(topic).isEqualToIgnoringCase("Big Data"); } |
### Question:
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(); }### Answer:
@Test public void givenPointerToArrayElement_shouldInsertTopicInToList() { JsonPointerExample jsonPointerExample = new JsonPointerExample(); String topic = jsonPointerExample.add(); assertThat(topic).isEqualToIgnoringCase("Java EE"); } |
### Question:
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(); }### Answer:
@Test public void givenPatch_sourceValueChanges() throws Exception { JsonMergePatchExample jsonMergePatchExample = new JsonMergePatchExample(); JsonValue result = jsonMergePatchExample.changeValue(); assertThat(((JsonString) result).getString()).isEqualToIgnoringCase("{\"colour\":\"red\"}"); } |
### Question:
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(); }### Answer:
@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\"}"); } |
### Question:
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(); }### Answer:
@Test @Ignore public void givenPatch_deleteValue() throws Exception { JsonMergePatchExample jsonMergePatchExample = new JsonMergePatchExample(); JsonValue result = jsonMergePatchExample.deleteValue(); assertThat(((JsonString) result).getString()).isEqualToIgnoringCase("{}"); } |
### Question:
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(); }### Answer:
@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"); } |
### Question:
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(); }### Answer:
@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"); } |
### Question:
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(); }### Answer:
@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"); } |
### Question:
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(); }### Answer:
@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"); } |
### Question:
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(); }### Answer:
@Test public void givenListOfBooks_shouldSerialiseToJson() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String json = jsonBindingExample.serializeListOfBooks(); assertThat(json).isEqualToIgnoringCase(bookListJson); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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(); }### Answer:
@Test public void givenPatchPath_shouldReplaceElement() { JsonPatchExample jsonPatchExample = new JsonPatchExample(); String series = jsonPatchExample.replace(); assertThat(series).isEqualToIgnoringCase("Spring 5"); } |
### Question:
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(); }### Answer:
@Test public void givenSourceAndTarget_shouldCreateMergePatch() { JsonMergeDiffExample jsonMergeDiffExample = new JsonMergeDiffExample(); JsonMergePatch mergePatch = jsonMergeDiffExample.createMergePatch(); JsonString jsonString = (JsonString) mergePatch.toJsonValue(); assertThat(jsonString.getString()).isEqualToIgnoringCase("{\"colour\":\"red\"}"); } |
### Question:
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(); }### Answer:
@Test public void givenJsonArray_shouldFilterAllTopicsStartingCToList() throws Exception { Java8Integration java8Integration = new Java8Integration(); List<String> topics = java8Integration.filterJsonArrayToList(); assertThat(topics).contains("Cloud"); assertThat(topics).contains("Cognitive"); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test @Ignore public void givenJSON_deserializeToListOfBooks() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); List<Book> actualBooks = jsonBindingExample.deserializeListOfBooks(); assertThat(actualBooks).isEqualTo(books); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
RepeatedConstraint { public void setText(String text) { this.text = text; } String getText(); void setText(String text); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test public void givenArrayOfBooks_shouldSerialiseToJson() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String json = jsonBindingExample.serializeArrayOfBooks(); assertThat(json).isEqualToIgnoringCase(bookListJson); } |
### Question:
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); }### Answer:
@Test public void givenBeanWithOptionalStringExample_shouldNotValidate() { OptionalExample optionalExample = new OptionalExample(); optionalExample.setText(" "); Set<ConstraintViolation<OptionalExample>> constraintViolations = validator.validate(optionalExample); assertThat(constraintViolations.size()).isEqualTo(2); } |
### Question:
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(); }### Answer:
@Test public void givenArrayOfStrings_shouldSerialiseToJson() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String json = jsonBindingExample.serializeArrayOfStrings(); assertThat(json).isEqualToIgnoringCase("[\"Java EE\",\"Java SE\"]"); } |
### Question:
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(); }### Answer:
@Test public void givenCustomisationOnProperties_shouldProduceJSON() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String result = jsonBindingExample.customizedMapping(); assertThat(result).isEqualToIgnoringCase(customisedJson); } |
### Question:
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(); }### Answer:
@Test public void givenCustomisationOnMethods_shouldProduceJSON() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String result = jsonBindingExample.annotationMethodMapping(); assertThat(result).isEqualToIgnoringCase(customisedJsonNewspaper); } |
### Question:
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(); }### Answer:
@Test public void givenCustomisationOnPropertiesAndMethods_shouldProduceJSON() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String result = jsonBindingExample.annotationPropertyAndMethodMapping(); assertThat(result).isEqualToIgnoringCase("{\"cost\":\"10.00\",\"author\":{\"firstName\":\"Alex\",\"lastName\":\"Theedom\"}}"); } |
### Question:
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(); }### Answer:
@Test public void givenAnnotationPojo_shouldProduceJson() { JsonBindingExample jsonBindingExample = new JsonBindingExample(); String result = jsonBindingExample.annotationPropertiesMapping(); assertThat(result).isEqualToIgnoringCase(expectedMagazine); } |
### Question:
AuthenticationUtil { public static void clearAuthentication() { SecurityContextHolder.getContext().setAuthentication(null); } private AuthenticationUtil(); static void clearAuthentication(); static void configureAuthentication(String role); }### Answer:
@Test public void clearAuthentication_ShouldRemoveAuthenticationFromSecurityContext() { Authentication authentication = createAuthentication(); SecurityContextHolder.getContext().setAuthentication(authentication); AuthenticationUtil.clearAuthentication(); Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication(); assertThat(currentAuthentication).isNull(); } |
### Question:
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); }### Answer:
@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); } |
### Question:
SerializerFactoryLoader { public static SerializerFactory getFactory(ProcessingEnvironment processingEnv) { return new SerializerFactoryImpl(loadExtensions(processingEnv), processingEnv); } private SerializerFactoryLoader(); static SerializerFactory getFactory(ProcessingEnvironment processingEnv); }### Answer:
@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"); } |
### Question:
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); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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(); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.