method2testcases
stringlengths 118
3.08k
|
---|
### Question:
XSDParser extends AbstractXMLParser { public static SushiEventType generateEventTypeFromXSD(String filePath, String eventTypeName) throws XMLParsingException { Document doc = readXMLDocument(filePath); if (doc == null) { throw new XMLParsingException("could not read XSD: " + filePath); } return generateEventType(doc, eventTypeName); } static SushiEventType generateEventTypeFromXSD(String filePath, String eventTypeName); static SushiEventType generateEventType(Document doc, String schemaName); }### Answer:
@Test public void testXSDParsing() throws XPathExpressionException, ParserConfigurationException, SAXException, IOException{ SushiEventType eventType = null; try { eventType = XSDParser.generateEventTypeFromXSD(filePath, "EventTaxonomy"); } catch (XMLParsingException e) { fail(); } assertNotNull(eventType); } |
### Question:
BPM2XMLToSignavioXMLConverter extends AbstractXMLParser { public SignavioBPMNProcess parseBPM2XML() { Document doc = readXMLDocument(bpm2FilePath); process = new SignavioBPMNProcess(); Node definitionNode = getDefinitionsElementFromBPM(doc); if(definitionNode != null){ process.addPropertyValue("targetnamespace", definitionNode.getAttributes().getNamedItem("targetNamespace").getNodeValue()); process.addPropertyValue("expressionlanguage", definitionNode.getAttributes().getNamedItem("expressionLanguage").getNodeValue()); process.addPropertyValue("typelanguage", definitionNode.getAttributes().getNamedItem("typeLanguage").getNodeValue()); } NodeList processChilds = getProcessElementsFromBPM(doc); for(int i = 0; i < processChilds.getLength(); i++){ process.addChildShape(getProcessChildFromXML(processChilds.item(i), doc)); } return process; } BPM2XMLToSignavioXMLConverter(String bpm2FilePath); String generateSignavioXMLFromBPM2XML(); SignavioBPMNProcess parseBPM2XML(); }### Answer:
@Test public void testParsing(){ BPM2XMLToSignavioXMLConverter converter = new BPM2XMLToSignavioXMLConverter(emptyBpmn2FilePath); converter.parseBPM2XML(); } |
### Question:
AbstractClient { protected static void init() { keywordSet.add("-" + HOST_ARGS); keywordSet.add("-" + HELP_ARGS); keywordSet.add("-" + PORT_ARGS); keywordSet.add("-" + PASSWORD_ARGS); keywordSet.add("-" + USERNAME_ARGS); keywordSet.add("-" + ISO8601_ARGS); keywordSet.add("-" + MAX_PRINT_ROW_COUNT_ARGS); } static void output(ResultSet res, boolean printToConsole, String statement, ZoneId zoneId); }### Answer:
@Test public void testInit() { AbstractClient.init(); String[] keywords = {AbstractClient.HOST_ARGS, AbstractClient.HELP_ARGS, AbstractClient.PORT_ARGS, AbstractClient.PASSWORD_ARGS, AbstractClient.USERNAME_ARGS, AbstractClient.ISO8601_ARGS, AbstractClient.MAX_PRINT_ROW_COUNT_ARGS,}; for (String keyword : keywords) { if (!AbstractClient.keywordSet.contains("-" + keyword)) { System.out.println(keyword); fail(); } } } |
### Question:
Pair { @Override public String toString() { return "<" + left + "," + right + ">"; } Pair(L l, R r); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); public L left; public R right; }### Answer:
@Test public void testToString() { Pair<String, Integer> p1 = new Pair<String, Integer>("a", 123123); assertEquals("<a,123123>", p1.toString()); Pair<Float, Double> p2 = new Pair<Float, Double>(32.5f, 123.123d); assertEquals("<32.5,123.123>", p2.toString()); } |
### Question:
MetadataQuerierByFileImpl implements MetadataQuerier { @Override public List<ChunkMetaData> getChunkMetaDataList(Path path) throws IOException { return chunkMetaDataCache.get(path); } MetadataQuerierByFileImpl(TsFileSequenceReader tsFileReader); @Override List<ChunkMetaData> getChunkMetaDataList(Path path); @Override TsFileMetaData getWholeFileMetadata(); @Override void loadChunkMetaDatas(List<Path> paths); }### Answer:
@Test public void test() throws IOException { fileReader = new TsFileSequenceReader(FILE_PATH); MetadataQuerierByFileImpl metadataQuerierByFile = new MetadataQuerierByFileImpl(fileReader); List<ChunkMetaData> chunkMetaDataList = metadataQuerierByFile .getChunkMetaDataList(new Path("d2.s1")); for (ChunkMetaData chunkMetaData : chunkMetaDataList) { Assert.assertEquals(chunkMetaData.getMeasurementUid(), "s1"); } } |
### Question:
Path { public boolean startWith(String prefix) { return prefix != null && fullPath.startsWith(prefix); } Path(StringContainer pathSc); Path(String pathSc); Path(String[] pathSc); Path(String device, String measurement); static Path mergePath(Path prefix, Path suffix); static Path addPrefixPath(Path src, String prefix); static Path addPrefixPath(Path src, Path prefix); static Path replace(String srcPrefix, Path descPrefix); static Path replace(Path srcPrefix, Path descPrefix); String getFullPath(); String getDevice(); String getMeasurement(); @Override int hashCode(); @Override boolean equals(Object obj); boolean equals(String obj); @Override String toString(); @Override Path clone(); boolean startWith(String prefix); boolean startWith(Path prefix); }### Answer:
@Test public void startWith() throws Exception { Path path = new Path("a.b.c"); assertTrue(path.startWith(new Path(""))); assertTrue(path.startWith(new Path("a"))); assertTrue(path.startWith(new Path("a.b.c"))); } |
### Question:
Path { public static Path mergePath(Path prefix, Path suffix) { StringContainer sc = new StringContainer(SystemConstant.PATH_SEPARATOR); sc.addTail(prefix); sc.addTail(suffix); return new Path(sc); } Path(StringContainer pathSc); Path(String pathSc); Path(String[] pathSc); Path(String device, String measurement); static Path mergePath(Path prefix, Path suffix); static Path addPrefixPath(Path src, String prefix); static Path addPrefixPath(Path src, Path prefix); static Path replace(String srcPrefix, Path descPrefix); static Path replace(Path srcPrefix, Path descPrefix); String getFullPath(); String getDevice(); String getMeasurement(); @Override int hashCode(); @Override boolean equals(Object obj); boolean equals(String obj); @Override String toString(); @Override Path clone(); boolean startWith(String prefix); boolean startWith(Path prefix); }### Answer:
@Test public void mergePath() throws Exception { Path prefix = new Path("a.b.c"); Path suffix = new Path("d.e"); Path suffix1 = new Path(""); testPath(Path.mergePath(prefix, suffix), "a.b.c.d", "e", "a.b.c.d.e"); testPath(Path.mergePath(prefix, suffix1), "a.b", "c", "a.b.c"); } |
### Question:
IoTDBMetadataResultMetadata implements ResultSetMetaData { @Override public int getColumnCount() throws SQLException { if (showLabels == null || showLabels.length == 0) { throw new SQLException("No column exists"); } return showLabels.length; } IoTDBMetadataResultMetadata(String[] showLabels); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override String getCatalogName(int arg0); @Override String getColumnClassName(int arg0); @Override int getColumnCount(); @Override int getColumnDisplaySize(int arg0); @Override String getColumnLabel(int column); @Override String getColumnName(int column); @Override int getColumnType(int column); @Override String getColumnTypeName(int arg0); @Override int getPrecision(int arg0); @Override int getScale(int arg0); @Override String getSchemaName(int arg0); @Override String getTableName(int arg0); @Override boolean isAutoIncrement(int arg0); @Override boolean isCaseSensitive(int arg0); @Override boolean isCurrency(int arg0); @Override boolean isDefinitelyWritable(int arg0); @Override int isNullable(int arg0); @Override boolean isReadOnly(int arg0); @Override boolean isSearchable(int arg0); @Override boolean isSigned(int arg0); @Override boolean isWritable(int arg0); }### Answer:
@Test public void testGetColumnCount() throws SQLException { boolean flag = false; try { metadata = new IoTDBMetadataResultMetadata(null); assertEquals((long) metadata.getColumnCount(), 0); } catch (Exception e) { flag = true; } assertEquals(flag, true); flag = false; try { String[] nullArray = {}; metadata = new IoTDBMetadataResultMetadata(nullArray); assertEquals((long) metadata.getColumnCount(), 0); } catch (Exception e) { flag = true; } assertEquals(flag, true); metadata = new IoTDBMetadataResultMetadata(cols); assertEquals((long) metadata.getColumnCount(), cols.length); } |
### Question:
IoTDBResultMetadata implements ResultSetMetaData { @Override public int getColumnCount() throws SQLException { if (columnInfoList == null || columnInfoList.size() == 0) { throw new SQLException("No column exists"); } return columnInfoList.size(); } IoTDBResultMetadata(List<String> columnInfoList, String operationType,
List<String> columnTypeList); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override String getCatalogName(int arg0); @Override String getColumnClassName(int arg0); @Override int getColumnCount(); @Override int getColumnDisplaySize(int arg0); @Override String getColumnLabel(int column); @Override String getColumnName(int column); @Override int getColumnType(int column); @Override String getColumnTypeName(int arg0); @Override int getPrecision(int arg0); @Override int getScale(int arg0); @Override String getSchemaName(int arg0); @Override String getTableName(int arg0); @Override boolean isAutoIncrement(int arg0); @Override boolean isCaseSensitive(int arg0); @Override boolean isCurrency(int arg0); @Override boolean isDefinitelyWritable(int arg0); @Override int isNullable(int arg0); @Override boolean isReadOnly(int arg0); @Override boolean isSearchable(int arg0); @Override boolean isSigned(int arg0); @Override boolean isWritable(int arg0); }### Answer:
@Test public void testGetColumnCount() throws SQLException { metadata = new IoTDBResultMetadata(null, null, null); boolean flag = false; try { metadata.getColumnCount(); } catch (Exception e) { flag = true; } assertEquals(flag, true); List<String> columnInfoList = new ArrayList<>(); flag = false; try { metadata = new IoTDBResultMetadata(columnInfoList, null, null); metadata.getColumnCount(); } catch (Exception e) { flag = true; } assertEquals(flag, true); columnInfoList.add("root.a.b.c"); assertEquals(metadata.getColumnCount(), 1); } |
### Question:
IoTDBResultMetadata implements ResultSetMetaData { @Override public String getColumnTypeName(int arg0) throws SQLException { return operationType; } IoTDBResultMetadata(List<String> columnInfoList, String operationType,
List<String> columnTypeList); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override String getCatalogName(int arg0); @Override String getColumnClassName(int arg0); @Override int getColumnCount(); @Override int getColumnDisplaySize(int arg0); @Override String getColumnLabel(int column); @Override String getColumnName(int column); @Override int getColumnType(int column); @Override String getColumnTypeName(int arg0); @Override int getPrecision(int arg0); @Override int getScale(int arg0); @Override String getSchemaName(int arg0); @Override String getTableName(int arg0); @Override boolean isAutoIncrement(int arg0); @Override boolean isCaseSensitive(int arg0); @Override boolean isCurrency(int arg0); @Override boolean isDefinitelyWritable(int arg0); @Override int isNullable(int arg0); @Override boolean isReadOnly(int arg0); @Override boolean isSearchable(int arg0); @Override boolean isSigned(int arg0); @Override boolean isWritable(int arg0); }### Answer:
@Test public void testGetColumnTypeName() throws SQLException { String operationType = "sum"; metadata = new IoTDBResultMetadata(null, operationType, null); assertEquals(metadata.getColumnTypeName(1), operationType); } |
### Question:
FloatDecoder extends Decoder { @Override public float readFloat(ByteBuffer buffer) { readMaxPointValue(buffer); int value = decoder.readInt(buffer); double result = value / maxPointValue; return (float) result; } FloatDecoder(TSEncoding encodingType, TSDataType dataType); @Override float readFloat(ByteBuffer buffer); @Override double readDouble(ByteBuffer buffer); @Override boolean hasNext(ByteBuffer buffer); @Override Binary readBinary(ByteBuffer buffer); @Override boolean readBoolean(ByteBuffer buffer); @Override short readShort(ByteBuffer buffer); @Override int readInt(ByteBuffer buffer); @Override long readLong(ByteBuffer buffer); @Override void reset(); }### Answer:
@Test public void test() throws Exception { float value = 7.101f; Encoder encoder = new FloatEncoder(TSEncoding.RLE, TSDataType.FLOAT, 3); ByteArrayOutputStream baos = new ByteArrayOutputStream(); encoder.encode(value, baos); encoder.flush(baos); encoder.encode(value + 2, baos); encoder.flush(baos); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); Decoder decoder1 = new FloatDecoder(TSEncoding.RLE, TSDataType.FLOAT); Decoder decoder2 = new FloatDecoder(TSEncoding.RLE, TSDataType.FLOAT); float value1_ = decoder1.readFloat(buffer); float value2_ = decoder2.readFloat(buffer); assertEquals(value, value1_, delta); assertEquals(value + 2, value2_, delta); LOGGER.debug("{} LOGGER.debug("{} } |
### Question:
Utils { public static IoTDBConnectionParams parseUrl(String url, Properties info) throws IoTDBURLException { IoTDBConnectionParams params = new IoTDBConnectionParams(url); if (url.trim().equalsIgnoreCase(Config.IOTDB_URL_PREFIX)) { return params; } Pattern pattern = Pattern.compile("([^;]*):([^;]*)/"); Matcher matcher = pattern.matcher(url.substring(Config.IOTDB_URL_PREFIX.length())); boolean isUrlLegal = false; while (matcher.find()) { params.setHost(matcher.group(1)); params.setPort(Integer.parseInt((matcher.group(2)))); isUrlLegal = true; } if (!isUrlLegal) { throw new IoTDBURLException("Error url format, url should be jdbc:iotdb: } if (info.containsKey(Config.AUTH_USER)) { params.setUsername(info.getProperty(Config.AUTH_USER)); } if (info.containsKey(Config.AUTH_PASSWORD)) { params.setPassword(info.getProperty(Config.AUTH_PASSWORD)); } return params; } static IoTDBConnectionParams parseUrl(String url, Properties info); static void verifySuccess(TS_Status status); static List<RowRecord> convertRowRecords(TSQueryDataSet tsQueryDataSet); }### Answer:
@Test public void testParseURL() throws IoTDBURLException { String userName = "test"; String userPwd = "test"; String host = "localhost"; int port = 6667; Properties properties = new Properties(); properties.setProperty(Config.AUTH_USER, userName); properties.setProperty(Config.AUTH_PASSWORD, userPwd); IoTDBConnectionParams params = Utils .parseUrl(String.format(Config.IOTDB_URL_PREFIX + "%s:%s/", host, port), properties); assertEquals(params.getHost(), host); assertEquals(params.getPort(), port); assertEquals(params.getUsername(), userName); assertEquals(params.getPassword(), userPwd); } |
### Question:
Utils { public static void verifySuccess(TS_Status status) throws IoTDBSQLException { if (status.getStatusCode() != TS_StatusCode.SUCCESS_STATUS) { throw new IoTDBSQLException(status.errorMessage); } } static IoTDBConnectionParams parseUrl(String url, Properties info); static void verifySuccess(TS_Status status); static List<RowRecord> convertRowRecords(TSQueryDataSet tsQueryDataSet); }### Answer:
@Test public void testVerifySuccess() { try { Utils.verifySuccess(new TS_Status(TS_StatusCode.SUCCESS_STATUS)); } catch (Exception e) { fail(); } try { Utils.verifySuccess(new TS_Status(TS_StatusCode.ERROR_STATUS)); } catch (Exception e) { return; } fail(); } |
### Question:
Processor { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Processor other = (Processor) obj; if (processorName == null) { if (other.processorName != null) { return false; } } else if (!processorName.equals(other.processorName)) { return false; } return true; } Processor(String processorName); void readUnlock(); void readLock(); void writeLock(); void writeUnlock(); void lock(boolean isWriteLock); boolean tryLock(boolean isWriteLock); void unlock(boolean isWriteUnlock); String getProcessorName(); boolean tryWriteLock(); boolean tryReadLock(); @Override int hashCode(); @Override boolean equals(Object obj); abstract boolean canBeClosed(); abstract boolean flush(); abstract void close(); abstract long memoryUsage(); }### Answer:
@Test public void testEquals() { assertEquals(processor1, processor3); assertFalse(processor1.equals(processor2)); } |
### Question:
OFFileMetadata { public OFFileMetadata() { } OFFileMetadata(); OFFileMetadata(long lastFooterOffset, List<OFRowGroupListMetadata> rowGroupLists); static OFFileMetadata deserializeFrom(InputStream inputStream); static OFFileMetadata deserializeFrom(ByteBuffer buffer); void addRowGroupListMetaData(OFRowGroupListMetadata rowGroupListMetadata); List<OFRowGroupListMetadata> getRowGroupLists(); long getLastFooterOffset(); void setLastFooterOffset(long lastFooterOffset); @Override String toString(); int serializeTo(OutputStream outputStream); int serializeTo(ByteBuffer buffer); }### Answer:
@Test public void testOFFileMetadata() throws Exception { OFFileMetadata ofFileMetadata = OverflowTestHelper.createOFFileMetadata(); serialize(ofFileMetadata); OFFileMetadata deOFFileMetadata = deSerialize(); OverflowUtils.isOFFileMetadataEqual(ofFileMetadata, deOFFileMetadata); } |
### Question:
OFRowGroupListMetadata { private OFRowGroupListMetadata() { } private OFRowGroupListMetadata(); OFRowGroupListMetadata(String deviceId); static OFRowGroupListMetadata deserializeFrom(InputStream inputStream); static OFRowGroupListMetadata deserializeFrom(ByteBuffer buffer); void addSeriesListMetaData(OFSeriesListMetadata timeSeries); List<OFSeriesListMetadata> getSeriesList(); @Override String toString(); String getdeviceId(); int serializeTo(OutputStream outputStream); int serializeTo(ByteBuffer buffer); }### Answer:
@Test public void testOFRowGroupListMetadata() throws Exception { OFRowGroupListMetadata ofRowGroupListMetadata = OverflowTestHelper .createOFRowGroupListMetadata(); serialize(ofRowGroupListMetadata); OFRowGroupListMetadata deOfRowGroupListMetadata = deSerialized(); OverflowUtils.isOFRowGroupListMetadataEqual(ofRowGroupListMetadata, deOfRowGroupListMetadata); } |
### Question:
OverflowIO extends TsFileIOWriter { public void close() throws IOException { overflowReadWriter.close(); } OverflowIO(OverflowReadWriter overflowReadWriter); @Deprecated static InputStream readOneTimeSeriesChunk(ChunkMetaData chunkMetaData,
TsFileInput fileReader); @Deprecated ChunkMetaData flush(OverflowSeriesImpl index); void clearRowGroupMetadatas(); @Deprecated List<OFRowGroupListMetadata> flush(
Map<String, Map<String, OverflowSeriesImpl>> overflowTrees); void toTail(); long getPos(); void close(); void flush(); OverflowReadWriter getReader(); OverflowReadWriter getWriter(); }### Answer:
@Test public void testFileCutoff() throws IOException { File file = new File("testoverflowfile"); FileOutputStream fileOutputStream = new FileOutputStream(file); byte[] bytes = new byte[20]; fileOutputStream.write(bytes); fileOutputStream.close(); assertEquals(20, file.length()); OverflowIO overflowIO = new OverflowIO(new OverflowIO.OverflowReadWriter(file.getPath())); assertEquals(20, file.length()); overflowIO.close(); file.delete(); } |
### Question:
OverflowSupport { public void insert(TSRecord tsRecord) { for (DataPoint dataPoint : tsRecord.dataPointList) { memTable.write(tsRecord.deviceId, dataPoint.getMeasurementId(), dataPoint.getType(), tsRecord.time, dataPoint.getValue().toString()); } } OverflowSupport(); void insert(TSRecord tsRecord); @Deprecated void update(String deviceId, String measurementId, long startTime, long endTime,
TSDataType dataType,
byte[] value); @Deprecated void delete(String deviceId, String measurementId, long timestamp, TSDataType dataType); TimeValuePairSorter queryOverflowInsertInMemory(String deviceId, String measurementId,
TSDataType dataType); BatchData queryOverflowUpdateInMemory(String deviceId, String measurementId,
TSDataType dataType,
BatchData data); boolean isEmptyOfOverflowSeriesMap(); Map<String, Map<String, OverflowSeriesImpl>> getOverflowSeriesMap(); boolean isEmptyOfMemTable(); IMemTable getMemTabale(); long getSize(); void clear(); }### Answer:
@Test public void testInsert() { support.clear(); assertEquals(true, support.isEmptyOfMemTable()); OverflowTestUtils.produceInsertData(support); assertEquals(false, support.isEmptyOfMemTable()); int num = 1; for (TimeValuePair pair : support .queryOverflowInsertInMemory(deviceId1, measurementId1, dataType1) .getSortedTimeValuePairList()) { assertEquals(num, pair.getTimestamp()); assertEquals(num, pair.getValue().getInt()); num++; } num = 1; for (TimeValuePair pair : support .queryOverflowInsertInMemory(deviceId2, measurementId2, dataType2) .getSortedTimeValuePairList()) { assertEquals(num, pair.getTimestamp()); if (num == 2) { assertEquals(10.5, pair.getValue().getFloat(), error); } else { assertEquals(5.5, pair.getValue().getFloat(), error); } num++; } } |
### Question:
IoTDBThreadPoolFactory { public static ExecutorService newFixedThreadPool(int nthreads, String poolName) { return Executors.newFixedThreadPool(nthreads, new IoTThreadFactory(poolName)); } static ExecutorService newFixedThreadPool(int nthreads, String poolName); static ExecutorService newFixedThreadPool(int nthreads, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newSingleThreadExecutor(String poolName); static ExecutorService newSingleThreadExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newCachedThreadPool(String poolName); static ExecutorService newCachedThreadPool(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService createJDBCClientThreadPool(Args args, String poolName); static ExecutorService createJDBCClientThreadPool(Args args, String poolName,
Thread.UncaughtExceptionHandler handler); }### Answer:
@Test public void testNewFixedThreadPool() throws InterruptedException, ExecutionException { String reason = "NewFixedThreadPool"; Thread.UncaughtExceptionHandler handler = new TestExceptionHandler(reason); int threadCount = 5; latch = new CountDownLatch(threadCount); ExecutorService exec = IoTDBThreadPoolFactory .newFixedThreadPool(threadCount, POOL_NAME, handler); for (int i = 0; i < threadCount; i++) { Runnable task = new TestThread(reason); exec.execute(task); } try { latch.await(); assertEquals(count.get(), threadCount); } catch (InterruptedException E) { fail(); } } |
### Question:
IoTDBThreadPoolFactory { public static ExecutorService newSingleThreadExecutor(String poolName) { return Executors.newSingleThreadExecutor(new IoTThreadFactory(poolName)); } static ExecutorService newFixedThreadPool(int nthreads, String poolName); static ExecutorService newFixedThreadPool(int nthreads, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newSingleThreadExecutor(String poolName); static ExecutorService newSingleThreadExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newCachedThreadPool(String poolName); static ExecutorService newCachedThreadPool(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService createJDBCClientThreadPool(Args args, String poolName); static ExecutorService createJDBCClientThreadPool(Args args, String poolName,
Thread.UncaughtExceptionHandler handler); }### Answer:
@Test public void testNewSingleThreadExecutor() throws InterruptedException { String reason = "NewSingleThreadExecutor"; Thread.UncaughtExceptionHandler handler = new TestExceptionHandler(reason); int threadCount = 1; latch = new CountDownLatch(threadCount); ExecutorService exec = IoTDBThreadPoolFactory.newSingleThreadExecutor(POOL_NAME, handler); for (int i = 0; i < threadCount; i++) { Runnable task = new TestThread(reason); exec.execute(task); } try { latch.await(); assertEquals(count.get(), threadCount); } catch (InterruptedException E) { fail(); } } |
### Question:
IoTDBThreadPoolFactory { public static ExecutorService newCachedThreadPool(String poolName) { return Executors.newCachedThreadPool(new IoTThreadFactory(poolName)); } static ExecutorService newFixedThreadPool(int nthreads, String poolName); static ExecutorService newFixedThreadPool(int nthreads, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newSingleThreadExecutor(String poolName); static ExecutorService newSingleThreadExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService newCachedThreadPool(String poolName); static ExecutorService newCachedThreadPool(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName); static ScheduledExecutorService newSingleThreadScheduledExecutor(String poolName,
Thread.UncaughtExceptionHandler handler); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName); static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String poolName,
Thread.UncaughtExceptionHandler handler); static ExecutorService createJDBCClientThreadPool(Args args, String poolName); static ExecutorService createJDBCClientThreadPool(Args args, String poolName,
Thread.UncaughtExceptionHandler handler); }### Answer:
@Test public void testNewCachedThreadPool() throws InterruptedException { String reason = "NewCachedThreadPool"; Thread.UncaughtExceptionHandler handler = new TestExceptionHandler(reason); int threadCount = 10; latch = new CountDownLatch(threadCount); ExecutorService exec = IoTDBThreadPoolFactory.newCachedThreadPool(POOL_NAME, handler); for (int i = 0; i < threadCount; i++) { Runnable task = new TestThread(reason); exec.execute(task); } try { latch.await(); assertEquals(count.get(), threadCount); } catch (InterruptedException E) { fail(); } } |
### Question:
BitStream { public void write(int n, long v) { if (n < 1 || n > 64) { throw new IllegalArgumentException( String.format("Unable to write %s bits to value %d", n, v)); } reserve(n); long v1 = v << 64 - n >>> shift; data[index] = data[index] | v1; shift += n; if (shift >= 64) { shift -= 64; index++; if (shift != 0) { long v2 = v << 64 - shift; data[index] = data[index] | v2; } } } BitStream(); BitStream(int initialCapacity); BitStream(long[] data, int len, int index, byte shift); void write(int n, long v); Map<String, Double> getStats(); BitStreamIterator read(); static BitStream deserialize(ByteBuffer buffer); void serialize(ByteBuffer buffer); int getSerializedByteSize(); }### Answer:
@Test public void testNegativeBitEncoding() { thrown.expect(IllegalArgumentException.class); new BitStream( 2).write(-1, 10); }
@Test public void testZeroBitEncoding() { thrown.expect(IllegalArgumentException.class); new BitStream( 2).write(0, 10); }
@Test public void test9ByteEncoding() { thrown.expect(IllegalArgumentException.class); new BitStream( 2).write(65, 10); } |
### Question:
ChunkManager { public List<TimeSeries> query(Query query, long startTsSecs, long endTsSecs, QueryAggregation queryAggregation) { return queryAroundChunkBoundaries(query, startTsSecs, endTsSecs, queryAggregation); } ChunkManager(String chunkDataPrefix, int expectedTagStoreSize); ChunkManager(String chunkDataPrefix, int expectedTagStoreSize, String dataDirectory); Chunk getChunk(long timestamp); void addMetric(final String metricString); List<TimeSeries> queryAroundChunkBoundaries(Query query, long startTsSecs,
long endTsSecs,
QueryAggregation queryAggregation); List<TimeSeries> query(Query query, long startTsSecs, long endTsSecs,
QueryAggregation queryAggregation); void toReadOnlyChunks(List<Map.Entry<Long, Chunk>> expiredChunks); void removeStaleChunks(List<Map.Entry<Long, Chunk>> staleChunks); static Duration DEFAULT_CHUNK_DURATION; }### Answer:
@Test public void testChunkWithRawMetricData() { long currentTs = Instant.now().getEpochSecond(); long previousHourTs = Instant.now().minusSeconds(3600).getEpochSecond(); final Query emptyQuery = new Query("test", Collections.emptyList()); assertTrue( chunkManager.query(emptyQuery, currentTs, previousHourTs, QueryAggregation.NONE).isEmpty()); } |
### Question:
InvertedIndexTagStore implements TagStore { @Override public int getOrCreate(final Metric m) { Optional<Integer> optionalMetric = get(m); return optionalMetric.isPresent() ? optionalMetric.get() : create(m); } InvertedIndexTagStore(); InvertedIndexTagStore(int metricIdMapCapacity, int initialIndexSize); InvertedIndexTagStore(int metricIdMapCapacity, int initialIndexSize,
String dataDirectory); InvertedIndexTagStore(int metricIdMapCapacity, int initialIndexSize,
String dataDirectory, boolean useOffHeapIdStore,
boolean useOffHeapIndexStore); @Override Optional<Integer> get(Metric m); @Override List<Integer> lookup(Query q); RoaringBitmap lookupMetricIndex(String key); @VisibleForTesting Map<Integer, String> getValuesForMetricKey(String metricName, String key); @Override int getOrCreate(final Metric m); @Override String getMetricName(final int metricId); @Override Map<String, Object> getStats(); @Override void close(); @Override boolean isReadOnly(); String getMetricNameFromId(final int id); }### Answer:
@Test(expected = PatternSyntaxException.class) public void testFailedRegExQuery() { ids.add(store.getOrCreate( new Metric(METRIC1, Collections.singletonList("host=ogg-01.ops.ankh.morpork.com")))); query(makeRegExQuery(METRIC1, HOST_TAG, "ogg-\\d(3.ops.ankh.morpork.com")); } |
### Question:
TagMatcher { public static TagMatcher wildcardMatch(String key, String wildcardString) { return createWildCardTagMatcher(key, wildcardString, MatchType.WILDCARD); } TagMatcher(MatchType type, Tag tag); @Override boolean equals(Object o); @Override int hashCode(); static TagMatcher exactMatch(Tag tag); static TagMatcher wildcardMatch(String key, String wildcardString); static TagMatcher iwildcardMatch(String key, String wildcardString); static TagMatcher literalOrMatch(String key, String orLiteralString,
boolean caseInsensitive); static TagMatcher notLiteralOrMatch(String key, String orLiteralString,
boolean caseInsensitive); static TagMatcher regExMatch(String key, String regExString); @Override String toString(); static final String WILDCARD; final MatchType type; final Tag tag; }### Answer:
@Test public void testTagMatcherCreation() { TagMatcher m2 = new TagMatcher(MatchType.WILDCARD, testTag); assertEquals(testTag, m2.tag); assertEquals(MatchType.WILDCARD, m2.type); TagMatcher m4 = TagMatcher.wildcardMatch(testKey, "*"); assertEquals(new Tag(testKey, "*"), m4.tag); assertEquals(MatchType.WILDCARD, m4.type); } |
### Question:
Tag implements Comparable<Tag> { public static Tag parseTag(String rawTag) { int index = getDelimiterIndex(rawTag); String key = rawTag.substring(0, index); String value = rawTag.substring(index + 1); if (key.isEmpty() || value.isEmpty()) { throw new IllegalArgumentException("Invalid rawTag" + rawTag); } return new Tag(key, value, rawTag); } Tag(String key, String value, String rawTag); Tag(String key, String value); @Override int compareTo(Tag o); @Override boolean equals(Object o); @Override int hashCode(); static Tag parseTag(String rawTag); final String rawTag; final String key; final String value; }### Answer:
@Test public void testTagParse() { testInvalidTagParse("a"); testInvalidTagParse("a="); testInvalidTagParse("=a"); testInvalidTagParse("="); Tag t = Tag.parseTag("k=v"); assertEquals("k", t.key); assertEquals("v", t.value); assertEquals("k=v", t.rawTag); Tag t1 = Tag.parseTag("k=v=1"); assertEquals("k", t1.key); assertEquals("v=1", t1.value); assertEquals("k=v=1", t1.rawTag); } |
### Question:
Query { public static Query parse(String s) { List<String> splits = Arrays.asList(s.split(" ")); String metricName = splits.get(0); List<TagMatcher> matchers = new ArrayList<>(); for (String s2 : splits.subList(1, splits.size())) { Tag tag = Tag.parseTag(s2); if (tag.value.equals("*")) { matchers.add(TagMatcher.wildcardMatch(tag.key, "*")); } else { matchers.add(TagMatcher.exactMatch(tag)); } } return new Query(metricName, matchers); } Query(final String metricName, final List<TagMatcher> tagMatchers); static Query parse(String s); @Override String toString(); final String metricName; final List<TagMatcher> tagMatchers; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testDuplicateTagKeysUsingParse() { Query.parse("metric k1=v1 k1=v2"); } |
### Question:
OffHeapVarBitMetricStore implements MetricStore { @Override public List<Point> getSeries(long uuid) { final LongValue key = Values.newHeapInstance(LongValue.class); key.setValue(uuid); if (timeSeries.containsKey(key)) { ByteBuffer serializedValues = timeSeries.get(key); TimeSeriesIterator iterator = VarBitTimeSeries.deserialize(serializedValues); return iterator.getPoints(); } else { return Collections.emptyList(); } } OffHeapVarBitMetricStore(long size, String chunkInfo); OffHeapVarBitMetricStore(long size, int valueSize, String chunkInfo); OffHeapVarBitMetricStore(long size, int valueSize, String chunkInfo, String dir); @Override List<Point> getSeries(long uuid); static OffHeapVarBitMetricStore toOffHeapStore(Map<Long, VarBitTimeSeries> timeSeriesMap,
String chunkInfo, String dataDirectory); void addPoint(long uuid, ByteBuffer series); @Override void addPoint(long uuid, long ts, double val); @Override Map<String, Object> getStats(); @Override Map getSeriesMap(); @Override void close(); @Override boolean isReadOnly(); @Override void setReadOnly(boolean readOnly); }### Answer:
@Test public void testEmpty() { MetricStore store = new OffHeapVarBitMetricStore(1, testFileName); assertTrue(store.getSeries(1).isEmpty()); assertTrue(store.getSeries(2).isEmpty()); } |
### Question:
OffHeapVarBitMetricStore implements MetricStore { public void addPoint(long uuid, ByteBuffer series) { LongValue key = Values.newHeapInstance(LongValue.class); key.setValue(uuid); timeSeries.put(key, series); } OffHeapVarBitMetricStore(long size, String chunkInfo); OffHeapVarBitMetricStore(long size, int valueSize, String chunkInfo); OffHeapVarBitMetricStore(long size, int valueSize, String chunkInfo, String dir); @Override List<Point> getSeries(long uuid); static OffHeapVarBitMetricStore toOffHeapStore(Map<Long, VarBitTimeSeries> timeSeriesMap,
String chunkInfo, String dataDirectory); void addPoint(long uuid, ByteBuffer series); @Override void addPoint(long uuid, long ts, double val); @Override Map<String, Object> getStats(); @Override Map getSeriesMap(); @Override void close(); @Override boolean isReadOnly(); @Override void setReadOnly(boolean readOnly); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testReadOnlyStore() { MetricStore store = new OffHeapVarBitMetricStore(1, testFileName); store.addPoint(1, 1, 1); } |
### Question:
VarBitTimeSeries { public synchronized void append(long timestamp, double value) { if (timestamp < 0 || timestamp > MAX_UNIX_TIMESTAMP) { throw new IllegalArgumentException("Timestamp is not a valid unix timestamp: " + timestamp); } if (size == 0) { appendFirstPoint(timestamp, value); } else { appendNextPoint(timestamp, value); } size++; } VarBitTimeSeries(); synchronized void append(long timestamp, double value); synchronized TimeSeriesIterator read(); Map<String, Double> getStats(); int getSerializedByteSize(); void serialize(ByteBuffer buffer); static TimeSeriesIterator deserialize(final ByteBuffer buffer); static final long MAX_UNIX_TIMESTAMP; static final int BLOCK_HEADER_OFFSET_SECS; static final short DEFAULT_TIMESTAMP_BITSTREAM_SIZE; static final short DEFAULT_VALUE_BITSTREAM_SIZE; }### Answer:
@Test public void testMinTimestamp() { VarBitTimeSeries series = new VarBitTimeSeries(); thrown.expect(IllegalArgumentException.class); series.append(-1, 1); }
@Test public void testMaxTimestamp() { VarBitTimeSeries series = new VarBitTimeSeries(); thrown.expect(IllegalArgumentException.class); series.append(-1, 1); }
@Test(expected = IllegalArgumentException.class) public void testTimestampEncodingOverflow() { VarBitTimeSeries series = new VarBitTimeSeries(); int i = 10; long ts1 = 1477678600L; long ts2 = 14776780L; long ts3 = 1477678580L; series.append(ts1, i); series.append(ts2, i); series.append(ts3, i); } |
### Question:
VarBitTimeSeries { public synchronized TimeSeriesIterator read() { return new CachingVarBitTimeSeriesIterator(size, timestamps.read(), values.read()); } VarBitTimeSeries(); synchronized void append(long timestamp, double value); synchronized TimeSeriesIterator read(); Map<String, Double> getStats(); int getSerializedByteSize(); void serialize(ByteBuffer buffer); static TimeSeriesIterator deserialize(final ByteBuffer buffer); static final long MAX_UNIX_TIMESTAMP; static final int BLOCK_HEADER_OFFSET_SECS; static final short DEFAULT_TIMESTAMP_BITSTREAM_SIZE; static final short DEFAULT_VALUE_BITSTREAM_SIZE; }### Answer:
@Test public void testEmptyPoints() { VarBitTimeSeries series = new VarBitTimeSeries(); TimeSeriesIterator dr = series.read(); List<Point> points = dr.getPoints(); assertTrue(points.isEmpty()); } |
### Question:
VarBitMetricStore implements MetricStore { @Override public List<Point> getSeries(long uuid) { mu.readLock().lock(); try { VarBitTimeSeries s = series.get(uuid); if (s == null) { return Collections.emptyList(); } return s.read().getPoints(); } finally { mu.readLock().unlock(); } } VarBitMetricStore(); VarBitMetricStore(int initialSize); @Override List<Point> getSeries(long uuid); @Override void addPoint(long uuid, long ts, double val); @Override Map<String, Object> getStats(); @Override Map getSeriesMap(); @Override void close(); void setReadOnly(boolean readOnly); @Override boolean isReadOnly(); }### Answer:
@Test public void testEmpty() { MetricStore store = new VarBitMetricStore(); assertTrue(store.getSeries(1).isEmpty()); assertTrue(store.getSeries(2).isEmpty()); } |
### Question:
ChunkImpl implements Chunk { @Override public boolean containsDataInTimeRange(long startTs, long endTs) { return (chunkInfo.startTimeSecs <= startTs && chunkInfo.endTimeSecs >= startTs) || (chunkInfo.startTimeSecs <= endTs && chunkInfo.endTimeSecs >= endTs) || (chunkInfo.startTimeSecs >= startTs && chunkInfo.endTimeSecs <= endTs); } ChunkImpl(MetricAndTagStore store, ChunkInfo chunkInfo); @Override List<TimeSeries> query(Query query); @Override void addPoint(Metric metric, long ts, double value); @Override ChunkInfo info(); @Override boolean isReadOnly(); @Override boolean containsDataInTimeRange(long startTs, long endTs); @Override Map<String, Object> getStats(); @Override void close(); @Override void setReadOnly(boolean readOnly); MetricAndTagStore getStore(); @Override String toString(); }### Answer:
@Test public void testChunkContainsData() { assertTrue(chunk.containsDataInTimeRange(startTime - 1, endTime + 1)); assertTrue(chunk.containsDataInTimeRange(startTime + 1, endTime + 1)); assertTrue(chunk.containsDataInTimeRange(startTime + 1, endTime - 1)); assertTrue(chunk.containsDataInTimeRange(startTime - 1, endTime - 1)); assertTrue(chunk.containsDataInTimeRange(startTime, endTime)); assertTrue(chunk.containsDataInTimeRange(startTime, endTime - 1)); assertTrue(chunk.containsDataInTimeRange(startTime, endTime + 1)); assertTrue(chunk.containsDataInTimeRange(startTime + 1, endTime)); assertTrue(chunk.containsDataInTimeRange(startTime - 1, endTime)); assertFalse(chunk.containsDataInTimeRange(startTime - 10000, endTime - 10000)); assertFalse(chunk.containsDataInTimeRange(startTime + 10000, endTime + 10000)); } |
### Question:
EtcdHeartbeatLease implements AutoCloseable { public Long getLeaseId() { initLease(); return leaseId; } EtcdHeartbeatLease(Client etcdClient, HeartbeatProperties properties); void initLease(); Long getLeaseId(); void revoke(); @Override void close(); }### Answer:
@Test public void testEtcdLeaseIsAvailable() throws ExecutionException, InterruptedException { Client client = Client.builder() .endpoints(container.clientEndpoint()) .build(); HeartbeatProperties heartbeatProperties = new HeartbeatProperties(); heartbeatProperties.setInterval(5); EtcdHeartbeatLease heartbeatLease = new EtcdHeartbeatLease(client, heartbeatProperties); Long leaseId = heartbeatLease.getLeaseId(); assertNotNull(leaseId); LeaseTimeToLiveResponse leaseTimeToLiveResponse = client.getLeaseClient().timeToLive(leaseId, LeaseOption.DEFAULT).get(); Thread.sleep(10); assertEquals(leaseTimeToLiveResponse.getGrantedTTL(), heartbeatProperties.getInterval()); assertTrue(leaseTimeToLiveResponse.getTTl() > 0); assertTrue(leaseTimeToLiveResponse.getTTl() < heartbeatProperties.getInterval()); } |
### Question:
Counter extends Applet { private void credit(APDU apdu, byte[] buffer) { short credit; if (apdu.setIncomingAndReceive() != 2) ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); credit = Util.getShort(buffer, ISO7816.OFFSET_CDATA); if (((short) (credit + balance) > MAX_BALANCE) || (credit <= 0) || (credit > MAX_CREDIT)) ISOException.throwIt(ISO7816.SW_WRONG_DATA); balance += credit; getBalance(apdu, buffer); } private Counter(); static void install(byte[] buffer, short offset, byte length); void process(APDU apdu); static final byte INS_GET_BALANCE; static final byte INS_CREDIT; static final byte INS_DEBIT; static final short MAX_BALANCE; static final short MAX_CREDIT; static final short MAX_DEBIT; }### Answer:
@Test public void creditTest() throws CardException { sendCredit(new byte[]{0x00, 0x05}, 0x9000, new byte[]{0x00, 0x05}); assertArrayEquals(new byte[]{0x00, 0x05}, getBalance().getData()); } |
### Question:
Counter extends Applet { private void debit(APDU apdu, byte[] buffer) { short debit; if (apdu.setIncomingAndReceive() != 2) ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); debit = Util.getShort(buffer, ISO7816.OFFSET_CDATA); if ((debit > balance) || (debit <= 0) || (debit > MAX_DEBIT)) ISOException.throwIt(ISO7816.SW_WRONG_DATA); balance -= debit; getBalance(apdu, buffer); } private Counter(); static void install(byte[] buffer, short offset, byte length); void process(APDU apdu); static final byte INS_GET_BALANCE; static final byte INS_CREDIT; static final byte INS_DEBIT; static final short MAX_BALANCE; static final short MAX_CREDIT; static final short MAX_DEBIT; }### Answer:
@Test public void debitTest() throws CardException { sendCredit(new byte[]{0x00, 0x05}, 0x9000, new byte[]{0x00, 0x05}); assertArrayEquals(new byte[]{0x00, 0x05}, getBalance().getData()); sendDebit(new byte[]{0x00, 0x05}, 0x9000, new byte[]{0x00, 0x00}); assertArrayEquals(new byte[]{0x00, 0x00}, getBalance().getData()); } |
### Question:
PasswordEntry { static void delete(byte[] buf, short ofs, byte len) { PasswordEntry pe = search(buf, ofs, len); if (pe != null) { JCSystem.beginTransaction(); pe.remove(); pe.recycle(); JCSystem.commitTransaction(); } } private PasswordEntry(); static PasswordEntry getFirst(); byte getIdLength(); PasswordEntry getNext(); void setId(byte[] buf, short ofs, byte len); void setUserName(byte[] buf, short ofs, byte len); void setPassword(byte[] buf, short ofs, byte len); static short SIZE_ID; static short SIZE_USERNAME; static short SIZE_PASSWORD; }### Answer:
@Test public void deleteTest() throws NoSuchFieldException, IllegalAccessException { assertEquals("init length", 0, getLength()); addItem(ID_BASIC, USERNAME_BASIC, PASSWORD_BASIC); assertEquals("length after addition", 1, getLength()); deleteItem(ID_BASIC); assertEquals("length after deletion", 0, getLength()); } |
### Question:
MapValueReader implements ValueReader<Map<String, Object>> { @Override public Object get(Map<String, Object> source, String memberName) { return source.get(memberName); } @Override Object get(Map<String, Object> source, String memberName); @SuppressWarnings("unchecked") @Override Member<Map<String, Object>> getMember(Map<String, Object> source, String memberName); @Override Collection<String> memberNames(Map<String, Object> source); }### Answer:
@Test(enabled = false) public void shouldMapBeanToMap() { Order order = new Order(); order.customer = new Customer(); order.customer.address = new Address(); order.customer.address.city = "Seattle"; order.customer.address.street = "1234 Main Street"; @SuppressWarnings("unchecked") Map<String, Map<String, Map<String, String>>> map = modelMapper.map(order, LinkedHashMap.class); modelMapper.validate(); assertEquals(map.get("customer").get("address").get("city"), order.customer.address.city); assertEquals(map.get("customer").get("address").get("street"), order.customer.address.street); } |
### Question:
ProxyFactory { static <T> T proxyFor(Class<T> type, InvocationHandler interceptor, Errors errors) throws ErrorsException { return proxyFor(type, interceptor, errors, Boolean.FALSE); } }### Answer:
@Test public void shouldProxyTypesWithNonDefaultConstructor() { InvocationHandler interceptor = mock(InvocationHandler.class); A1 a1 = ProxyFactory.proxyFor(A1.class, interceptor, null); assertNotNull(a1); A2 a2 = ProxyFactory.proxyFor(A2.class, interceptor, null); assertNotNull(a2); } |
### Question:
BooleanConverter implements ConditionalConverter<Object, Boolean> { public Boolean convert(MappingContext<Object, Boolean> context) { Object source = context.getSource(); if (source == null) return null; String stringValue = source.toString().toLowerCase(); if (stringValue.length() == 0) return null; for (int i = 0; i < TRUE_STRINGS.length; i++) if (TRUE_STRINGS[i].equals(stringValue)) return Boolean.TRUE; for (int i = 0; i < FALSE_STRINGSS.length; i++) if (FALSE_STRINGSS[i].equals(stringValue)) return Boolean.FALSE; throw new Errors().errorMapping(context.getSource(), context.getDestinationType()) .toMappingException(); } Boolean convert(MappingContext<Object, Boolean> context); MatchResult match(Class<?> sourceType, Class<?> destinationType); }### Answer:
@Test(expectedExceptions = MappingException.class) public void shouldThrowOnInvalidString() { convert("abc"); } |
### Question:
MapObjs { synchronized static Object[] toArray(Object now) { if (now instanceof MapObjs) { return ((MapObjs) now).all.toArray(); } final Fn.Presenter p = getOnlyPresenter(); if (p == null) { return new Object[0]; } return new Object[] { p, now }; } private MapObjs(Fn.Ref id1, Object js); private MapObjs(Fn.Ref id1, Object js1, Fn.Ref id2, Object js2); }### Answer:
@Test public void testToArrayNoPresenterYet() { Object[] arr = MapObjs.toArray(null); assertEquals(arr.length, 0, "Empty array: " + Arrays.toString(arr)); } |
### Question:
JSON { public static Boolean boolValue(Object val) { if (val instanceof String) { return Boolean.parseBoolean((String)val); } if (val instanceof Number) { return numberValue(val).doubleValue() != 0.0; } return Boolean.TRUE.equals(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 stringToBoolean() { assertEquals(JSON.boolValue("false"), Boolean.FALSE); assertEquals(JSON.boolValue("True"), Boolean.TRUE); }
@Test public void numberToBoolean() { assertEquals(JSON.boolValue(0), Boolean.FALSE); assertEquals(JSON.boolValue(1), Boolean.TRUE); } |
### Question:
SimpleList implements List<E> { @Override public ListIterator<E> listIterator() { return new LI(0, size); } SimpleList(); private SimpleList(Object[] data); static List<T> asList(T... arr); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<E> iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(E e); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends E> c); @Override boolean addAll(int index, Collection<? extends E> c); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); void sort(Comparator<? super E> c); @Override void clear(); @Override E get(int index); @Override E set(int index, E element); @Override void add(int index, E element); @Override E remove(int index); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); int lastIndexOfImpl(Object o, int from, int to); @Override ListIterator<E> listIterator(); @Override ListIterator<E> listIterator(int index); @Override List<E> subList(int fromIndex, int toIndex); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static void ensureSize(List<?> list, int size); }### Answer:
@Test(dataProvider = "lists") public void testListIterator(List<String> list) { list.add("Hi"); list.add("Ahoj"); list.add("Ciao"); Collections.sort(list); ListIterator<String> it = list.listIterator(3); assertEquals(it.previous(), "Hi"); assertEquals(it.previous(), "Ciao"); it.remove(); assertEquals(it.next(), "Hi"); assertEquals(it.previous(), "Hi"); assertEquals(it.previous(), "Ahoj"); assertEquals(list.size(), 2); } |
### Question:
SimpleList implements List<E> { @Override public boolean retainAll(Collection<?> c) { return retainImpl(this, c); } SimpleList(); private SimpleList(Object[] data); static List<T> asList(T... arr); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<E> iterator(); @Override Object[] toArray(); @Override T[] toArray(T[] a); @Override boolean add(E e); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends E> c); @Override boolean addAll(int index, Collection<? extends E> c); @Override boolean removeAll(Collection<?> c); @Override boolean retainAll(Collection<?> c); void sort(Comparator<? super E> c); @Override void clear(); @Override E get(int index); @Override E set(int index, E element); @Override void add(int index, E element); @Override E remove(int index); @Override int indexOf(Object o); @Override int lastIndexOf(Object o); int lastIndexOfImpl(Object o, int from, int to); @Override ListIterator<E> listIterator(); @Override ListIterator<E> listIterator(int index); @Override List<E> subList(int fromIndex, int toIndex); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static void ensureSize(List<?> list, int size); }### Answer:
@Test(dataProvider = "lists") public void retainAll(List<Number> list) { list.add(3); list.add(3.3f); list.add(4L); list.add(4.4); list.retainAll(Collections.singleton(4L)); assertEquals(list.size(), 1); assertEquals(list.get(0), 4L); } |
### 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:
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:
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:
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:
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:
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:
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:
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 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"); } |
Subsets and Splits