method2testcases
stringlengths
118
3.08k
### Question: BaseSourceImpl implements BaseSource, MetricsSource { public void setGauge(String gaugeName, long value) { MutableGaugeLong gaugeInt = metricsRegistry.getLongGauge(gaugeName, value); gaugeInt.set(value); } BaseSourceImpl( String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext); void init(); void setGauge(String gaugeName, long value); void incGauge(String gaugeName, long delta); void decGauge(String gaugeName, long delta); void incCounters(String key, long delta); @Override void updateHistogram(String name, long value); @Override void updateQuantile(String name, long value); void removeMetric(String key); @Override void getMetrics(MetricsCollector metricsCollector, boolean all); DynamicMetricsRegistry getMetricsRegistry(); String getMetricsContext(); String getMetricsDescription(); String getMetricsJmxContext(); String getMetricsName(); }### Answer: @Test public void testSetGauge() throws Exception { bmsi.setGauge("testset", 100); assertEquals(100, ((MutableGaugeLong) bmsi.metricsRegistry.get("testset")).value()); bmsi.setGauge("testset", 300); assertEquals(300, ((MutableGaugeLong) bmsi.metricsRegistry.get("testset")).value()); }
### Question: BaseSourceImpl implements BaseSource, MetricsSource { public void incGauge(String gaugeName, long delta) { MutableGaugeLong gaugeInt = metricsRegistry.getLongGauge(gaugeName, 0l); gaugeInt.incr(delta); } BaseSourceImpl( String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext); void init(); void setGauge(String gaugeName, long value); void incGauge(String gaugeName, long delta); void decGauge(String gaugeName, long delta); void incCounters(String key, long delta); @Override void updateHistogram(String name, long value); @Override void updateQuantile(String name, long value); void removeMetric(String key); @Override void getMetrics(MetricsCollector metricsCollector, boolean all); DynamicMetricsRegistry getMetricsRegistry(); String getMetricsContext(); String getMetricsDescription(); String getMetricsJmxContext(); String getMetricsName(); }### Answer: @Test public void testIncGauge() throws Exception { bmsi.incGauge("testincgauge", 100); assertEquals(100, ((MutableGaugeLong) bmsi.metricsRegistry.get("testincgauge")).value()); bmsi.incGauge("testincgauge", 100); assertEquals(200, ((MutableGaugeLong) bmsi.metricsRegistry.get("testincgauge")).value()); }
### Question: BaseSourceImpl implements BaseSource, MetricsSource { public void decGauge(String gaugeName, long delta) { MutableGaugeLong gaugeInt = metricsRegistry.getLongGauge(gaugeName, 0l); gaugeInt.decr(delta); } BaseSourceImpl( String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext); void init(); void setGauge(String gaugeName, long value); void incGauge(String gaugeName, long delta); void decGauge(String gaugeName, long delta); void incCounters(String key, long delta); @Override void updateHistogram(String name, long value); @Override void updateQuantile(String name, long value); void removeMetric(String key); @Override void getMetrics(MetricsCollector metricsCollector, boolean all); DynamicMetricsRegistry getMetricsRegistry(); String getMetricsContext(); String getMetricsDescription(); String getMetricsJmxContext(); String getMetricsName(); }### Answer: @Test public void testDecGauge() throws Exception { bmsi.decGauge("testdec", 100); assertEquals(-100, ((MutableGaugeLong) bmsi.metricsRegistry.get("testdec")).value()); bmsi.decGauge("testdec", 100); assertEquals(-200, ((MutableGaugeLong) bmsi.metricsRegistry.get("testdec")).value()); }
### Question: BaseSourceImpl implements BaseSource, MetricsSource { public void incCounters(String key, long delta) { MutableCounterLong counter = metricsRegistry.getLongCounter(key, 0l); counter.incr(delta); } BaseSourceImpl( String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext); void init(); void setGauge(String gaugeName, long value); void incGauge(String gaugeName, long delta); void decGauge(String gaugeName, long delta); void incCounters(String key, long delta); @Override void updateHistogram(String name, long value); @Override void updateQuantile(String name, long value); void removeMetric(String key); @Override void getMetrics(MetricsCollector metricsCollector, boolean all); DynamicMetricsRegistry getMetricsRegistry(); String getMetricsContext(); String getMetricsDescription(); String getMetricsJmxContext(); String getMetricsName(); }### Answer: @Test public void testIncCounters() throws Exception { bmsi.incCounters("testinccounter", 100); assertEquals(100, ((MutableCounterLong) bmsi.metricsRegistry.get("testinccounter")).value()); bmsi.incCounters("testinccounter", 100); assertEquals(200, ((MutableCounterLong) bmsi.metricsRegistry.get("testinccounter")).value()); }
### Question: BaseSourceImpl implements BaseSource, MetricsSource { public void removeMetric(String key) { metricsRegistry.removeMetric(key); JmxCacheBuster.clearJmxCache(); } BaseSourceImpl( String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext); void init(); void setGauge(String gaugeName, long value); void incGauge(String gaugeName, long delta); void decGauge(String gaugeName, long delta); void incCounters(String key, long delta); @Override void updateHistogram(String name, long value); @Override void updateQuantile(String name, long value); void removeMetric(String key); @Override void getMetrics(MetricsCollector metricsCollector, boolean all); DynamicMetricsRegistry getMetricsRegistry(); String getMetricsContext(); String getMetricsDescription(); String getMetricsJmxContext(); String getMetricsName(); }### Answer: @Test public void testRemoveMetric() throws Exception { bmsi.setGauge("testrmgauge", 100); bmsi.removeMetric("testrmgauge"); assertNull(bmsi.metricsRegistry.get("testrmgauge")); }
### Question: MetricsThriftServerSourceFactoryImpl implements MetricsThriftServerSourceFactory { @Override public MetricsThriftServerSource createThriftOneSource() { return FactoryStorage.INSTANCE.thriftOne; } @Override MetricsThriftServerSource createThriftOneSource(); @Override MetricsThriftServerSource createThriftTwoSource(); }### Answer: @Test public void testCreateThriftOneSource() throws Exception { assertSame(new MetricsThriftServerSourceFactoryImpl().createThriftOneSource(), new MetricsThriftServerSourceFactoryImpl().createThriftOneSource()); }
### Question: MetricsThriftServerSourceFactoryImpl implements MetricsThriftServerSourceFactory { @Override public MetricsThriftServerSource createThriftTwoSource() { return FactoryStorage.INSTANCE.thriftTwo; } @Override MetricsThriftServerSource createThriftOneSource(); @Override MetricsThriftServerSource createThriftTwoSource(); }### Answer: @Test public void testCreateThriftTwoSource() throws Exception { assertSame(new MetricsThriftServerSourceFactoryImpl().createThriftTwoSource(), new MetricsThriftServerSourceFactoryImpl().createThriftTwoSource()); }
### Question: MetricsRegionSourceImpl implements MetricsRegionSource { @Override public int compareTo(MetricsRegionSource source) { if (!(source instanceof MetricsRegionSourceImpl)) return -1; MetricsRegionSourceImpl impl = (MetricsRegionSourceImpl) source; return this.regionWrapper.getRegionName() .compareTo(impl.regionWrapper.getRegionName()); } MetricsRegionSourceImpl(MetricsRegionWrapper regionWrapper, MetricsRegionAggregateSourceImpl aggregate); @Override void close(); @Override void updatePut(); @Override void updateDelete(); @Override void updateGet(long getSize); @Override void updateScan(long scanSize); @Override void updateIncrement(); @Override void updateAppend(); @Override MetricsRegionAggregateSource getAggregateSource(); @Override int compareTo(MetricsRegionSource source); @Override boolean equals(Object obj); }### Answer: @Test public void testCompareTo() throws Exception { MetricsRegionServerSourceFactory fact = CompatibilitySingletonFactory.getInstance(MetricsRegionServerSourceFactory.class); MetricsRegionSource one = fact.createRegion(new RegionWrapperStub("TEST")); MetricsRegionSource oneClone = fact.createRegion(new RegionWrapperStub("TEST")); MetricsRegionSource two = fact.createRegion(new RegionWrapperStub("TWO")); assertEquals(0, one.compareTo(oneClone)); assertTrue( one.compareTo(two) < 0); assertTrue( two.compareTo(one) > 0); }
### Question: HFileArchiveUtil { public static Path getTableArchivePath(final Path rootdir, final TableName tableName) { return FSUtils.getTableDir(getArchivePath(rootdir), tableName); } private HFileArchiveUtil(); static Path getStoreArchivePath(final Configuration conf, final TableName tableName, final String regionName, final String familyName); static Path getStoreArchivePath(Configuration conf, HRegionInfo region, Path tabledir, byte[] family); static Path getRegionArchiveDir(Path rootDir, TableName tableName, Path regiondir); static Path getRegionArchiveDir(Path rootDir, TableName tableName, String encodedRegionName); static Path getTableArchivePath(final Path rootdir, final TableName tableName); static Path getTableArchivePath(final Configuration conf, final TableName tableName); static Path getArchivePath(Configuration conf); }### Answer: @Test public void testGetTableArchivePath() { assertNotNull(HFileArchiveUtil.getTableArchivePath(rootDir, TableName.valueOf("table"))); }
### Question: HFileArchiveUtil { public static Path getArchivePath(Configuration conf) throws IOException { return getArchivePath(FSUtils.getRootDir(conf)); } private HFileArchiveUtil(); static Path getStoreArchivePath(final Configuration conf, final TableName tableName, final String regionName, final String familyName); static Path getStoreArchivePath(Configuration conf, HRegionInfo region, Path tabledir, byte[] family); static Path getRegionArchiveDir(Path rootDir, TableName tableName, Path regiondir); static Path getRegionArchiveDir(Path rootDir, TableName tableName, String encodedRegionName); static Path getTableArchivePath(final Path rootdir, final TableName tableName); static Path getTableArchivePath(final Configuration conf, final TableName tableName); static Path getArchivePath(Configuration conf); }### Answer: @Test public void testGetArchivePath() throws Exception { Configuration conf = new Configuration(); FSUtils.setRootDir(conf, new Path("root")); assertNotNull(HFileArchiveUtil.getArchivePath(conf)); }
### Question: HFileArchiveUtil { public static Path getRegionArchiveDir(Path rootDir, TableName tableName, Path regiondir) { Path archiveDir = getTableArchivePath(rootDir, tableName); String encodedRegionName = regiondir.getName(); return HRegion.getRegionDir(archiveDir, encodedRegionName); } private HFileArchiveUtil(); static Path getStoreArchivePath(final Configuration conf, final TableName tableName, final String regionName, final String familyName); static Path getStoreArchivePath(Configuration conf, HRegionInfo region, Path tabledir, byte[] family); static Path getRegionArchiveDir(Path rootDir, TableName tableName, Path regiondir); static Path getRegionArchiveDir(Path rootDir, TableName tableName, String encodedRegionName); static Path getTableArchivePath(final Path rootdir, final TableName tableName); static Path getTableArchivePath(final Configuration conf, final TableName tableName); static Path getArchivePath(Configuration conf); }### Answer: @Test public void testRegionArchiveDir() { Path regionDir = new Path("region"); assertNotNull(HFileArchiveUtil.getRegionArchiveDir(rootDir, TableName.valueOf("table"), regionDir)); }
### Question: HFileArchiveUtil { public static Path getStoreArchivePath(final Configuration conf, final TableName tableName, final String regionName, final String familyName) throws IOException { Path tableArchiveDir = getTableArchivePath(conf, tableName); return HStore.getStoreHomedir(tableArchiveDir, regionName, Bytes.toBytes(familyName)); } private HFileArchiveUtil(); static Path getStoreArchivePath(final Configuration conf, final TableName tableName, final String regionName, final String familyName); static Path getStoreArchivePath(Configuration conf, HRegionInfo region, Path tabledir, byte[] family); static Path getRegionArchiveDir(Path rootDir, TableName tableName, Path regiondir); static Path getRegionArchiveDir(Path rootDir, TableName tableName, String encodedRegionName); static Path getTableArchivePath(final Path rootdir, final TableName tableName); static Path getTableArchivePath(final Configuration conf, final TableName tableName); static Path getArchivePath(Configuration conf); }### Answer: @Test public void testGetStoreArchivePath() throws IOException { byte[] family = Bytes.toBytes("Family"); Path tabledir = FSUtils.getTableDir(rootDir, TableName.valueOf("table")); HRegionInfo region = new HRegionInfo(TableName.valueOf("table")); Configuration conf = new Configuration(); FSUtils.setRootDir(conf, new Path("root")); assertNotNull(HFileArchiveUtil.getStoreArchivePath(conf, region, tabledir, family)); }
### Question: RegionSizeCalculator { public long getRegionSize(byte[] regionId) { Long size = sizeMap.get(regionId); if (size == null) { LOG.debug("Unknown region:" + Arrays.toString(regionId)); return 0; } else { return size; } } RegionSizeCalculator(HTable table); RegionSizeCalculator(HTable table, HBaseAdmin admin); long getRegionSize(byte[] regionId); Map<byte[], Long> getRegionSizeMap(); }### Answer: @Test public void testLargeRegion() throws Exception { HTable table = mockTable("largeRegion"); HBaseAdmin admin = mockAdmin( mockServer( mockRegion("largeRegion", Integer.MAX_VALUE) ) ); RegionSizeCalculator calculator = new RegionSizeCalculator(table, admin); assertEquals(((long) Integer.MAX_VALUE) * megabyte, calculator.getRegionSize("largeRegion".getBytes())); }
### Question: BoundedPriorityBlockingQueue extends AbstractQueue<E> implements BlockingQueue<E> { public E poll() { E result = null; lock.lock(); try { if (queue.size() > 0) { result = queue.poll(); notFull.signal(); } } finally { lock.unlock(); } return result; } BoundedPriorityBlockingQueue(int capacity, Comparator<? super E> comparator); boolean offer(E e); void put(E e); boolean offer(E e, long timeout, TimeUnit unit); E take(); E poll(); E poll(long timeout, TimeUnit unit); E peek(); int size(); Iterator<E> iterator(); Comparator<? super E> comparator(); int remainingCapacity(); boolean remove(Object o); boolean contains(Object o); int drainTo(Collection<? super E> c); int drainTo(Collection<? super E> c, int maxElements); }### Answer: @Test public void testPoll() { assertNull(queue.poll()); PriorityQueue<TestObject> testList = new PriorityQueue<TestObject>(CAPACITY, new TestObjectComparator()); for (int i = 0; i < CAPACITY; ++i) { TestObject obj = new TestObject(i, i); testList.add(obj); queue.offer(obj); } for (int i = 0; i < CAPACITY; ++i) { assertEquals(testList.poll(), queue.poll()); } assertNull(null, queue.poll()); }
### Question: FSVisitor { public static void visitTableStoreFiles(final FileSystem fs, final Path tableDir, final StoreFileVisitor visitor) throws IOException { FileStatus[] regions = FSUtils.listStatus(fs, tableDir, new FSUtils.RegionDirFilter(fs)); if (regions == null) { LOG.info("No regions under directory:" + tableDir); return; } for (FileStatus region: regions) { visitRegionStoreFiles(fs, region.getPath(), visitor); } } private FSVisitor(); static void visitRegions(final FileSystem fs, final Path tableDir, final RegionVisitor visitor); static void visitTableStoreFiles(final FileSystem fs, final Path tableDir, final StoreFileVisitor visitor); static void visitRegionStoreFiles(final FileSystem fs, final Path regionDir, final StoreFileVisitor visitor); static void visitTableRecoveredEdits(final FileSystem fs, final Path tableDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitRegionRecoveredEdits(final FileSystem fs, final Path regionDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitLogFiles(final FileSystem fs, final Path rootDir, final LogFileVisitor visitor); }### Answer: @Test public void testVisitStoreFiles() throws IOException { final Set<String> regions = new HashSet<String>(); final Set<String> families = new HashSet<String>(); final Set<String> hfiles = new HashSet<String>(); FSVisitor.visitTableStoreFiles(fs, tableDir, new FSVisitor.StoreFileVisitor() { public void storeFile(final String region, final String family, final String hfileName) throws IOException { regions.add(region); families.add(family); hfiles.add(hfileName); } }); assertEquals(tableRegions, regions); assertEquals(tableFamilies, families); assertEquals(tableHFiles, hfiles); }
### Question: FSVisitor { public static void visitTableRecoveredEdits(final FileSystem fs, final Path tableDir, final FSVisitor.RecoveredEditsVisitor visitor) throws IOException { FileStatus[] regions = FSUtils.listStatus(fs, tableDir, new FSUtils.RegionDirFilter(fs)); if (regions == null) { LOG.info("No recoveredEdits regions under directory:" + tableDir); return; } for (FileStatus region: regions) { visitRegionRecoveredEdits(fs, region.getPath(), visitor); } } private FSVisitor(); static void visitRegions(final FileSystem fs, final Path tableDir, final RegionVisitor visitor); static void visitTableStoreFiles(final FileSystem fs, final Path tableDir, final StoreFileVisitor visitor); static void visitRegionStoreFiles(final FileSystem fs, final Path regionDir, final StoreFileVisitor visitor); static void visitTableRecoveredEdits(final FileSystem fs, final Path tableDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitRegionRecoveredEdits(final FileSystem fs, final Path regionDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitLogFiles(final FileSystem fs, final Path rootDir, final LogFileVisitor visitor); }### Answer: @Test public void testVisitRecoveredEdits() throws IOException { final Set<String> regions = new HashSet<String>(); final Set<String> edits = new HashSet<String>(); FSVisitor.visitTableRecoveredEdits(fs, tableDir, new FSVisitor.RecoveredEditsVisitor() { public void recoveredEdits (final String region, final String logfile) throws IOException { regions.add(region); edits.add(logfile); } }); assertEquals(tableRegions, regions); assertEquals(recoveredEdits, edits); }
### Question: FSVisitor { public static void visitLogFiles(final FileSystem fs, final Path rootDir, final LogFileVisitor visitor) throws IOException { Path logsDir = new Path(rootDir, HConstants.HREGION_LOGDIR_NAME); FileStatus[] logServerDirs = FSUtils.listStatus(fs, logsDir); if (logServerDirs == null) { LOG.info("No logs under directory:" + logsDir); return; } for (FileStatus serverLogs: logServerDirs) { String serverName = serverLogs.getPath().getName(); FileStatus[] hlogs = FSUtils.listStatus(fs, serverLogs.getPath()); if (hlogs == null) { LOG.debug("No hfiles found for server: " + serverName + ", skipping."); continue; } for (FileStatus hlogRef: hlogs) { visitor.logFile(serverName, hlogRef.getPath().getName()); } } } private FSVisitor(); static void visitRegions(final FileSystem fs, final Path tableDir, final RegionVisitor visitor); static void visitTableStoreFiles(final FileSystem fs, final Path tableDir, final StoreFileVisitor visitor); static void visitRegionStoreFiles(final FileSystem fs, final Path regionDir, final StoreFileVisitor visitor); static void visitTableRecoveredEdits(final FileSystem fs, final Path tableDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitRegionRecoveredEdits(final FileSystem fs, final Path regionDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitLogFiles(final FileSystem fs, final Path rootDir, final LogFileVisitor visitor); }### Answer: @Test public void testVisitLogFiles() throws IOException { final Set<String> servers = new HashSet<String>(); final Set<String> logs = new HashSet<String>(); FSVisitor.visitLogFiles(fs, rootDir, new FSVisitor.LogFileVisitor() { public void logFile (final String server, final String logfile) throws IOException { servers.add(server); logs.add(logfile); } }); assertEquals(regionServers, servers); assertEquals(serverLogs, logs); }
### Question: SlabCache implements SlabItemActionWatcher, BlockCache, HeapSize { Entry<Integer, SingleSizeCache> getHigherBlock(int size) { return slabs.higherEntry(size - 1); } SlabCache(long size, long avgBlockSize); Map<Integer, SingleSizeCache> getSizer(); void addSlabByConf(Configuration conf); void cacheBlock(BlockCacheKey cacheKey, Cacheable cachedItem); void cacheBlock(BlockCacheKey cacheKey, Cacheable buf, boolean inMemory); CacheStats getStats(); Cacheable getBlock(BlockCacheKey key, boolean caching, boolean repeat, boolean updateCacheMetrics); boolean evictBlock(BlockCacheKey cacheKey); @Override void onEviction(BlockCacheKey key, SingleSizeCache notifier); @Override void onInsertion(BlockCacheKey key, SingleSizeCache notifier); void shutdown(); long heapSize(); long size(); long getFreeSize(); @Override long getBlockCount(); long getCurrentSize(); long getEvictedCount(); int evictBlocksByHfileName(String hfileName); @Override Iterator<CachedBlock> iterator(); @Override BlockCache[] getBlockCaches(); }### Answer: @Test public void testElementPlacement() { assertEquals(cache.getHigherBlock(BLOCK_SIZE).getKey().intValue(), (BLOCK_SIZE * 11 / 10)); assertEquals(cache.getHigherBlock((BLOCK_SIZE * 2)).getKey() .intValue(), (BLOCK_SIZE * 21 / 10)); }
### Question: BucketCache implements BlockCache, HeapSize { void stopWriterThreads() throws InterruptedException { for (WriterThread writerThread : writerThreads) { writerThread.disableWriter(); writerThread.interrupt(); writerThread.join(); } } BucketCache(String ioEngineName, long capacity, int blockSize, int[] bucketSizes, int writerThreadNum, int writerQLen, String persistencePath); BucketCache(String ioEngineName, long capacity, int blockSize, int[] bucketSizes, int writerThreadNum, int writerQLen, String persistencePath, int ioErrorsTolerationDuration); String getIoEngine(); @Override void cacheBlock(BlockCacheKey cacheKey, Cacheable buf); @Override void cacheBlock(BlockCacheKey cacheKey, Cacheable cachedItem, boolean inMemory); void cacheBlockWithWait(BlockCacheKey cacheKey, Cacheable cachedItem, boolean inMemory, boolean wait); @Override Cacheable getBlock(BlockCacheKey key, boolean caching, boolean repeat, boolean updateCacheMetrics); @Override boolean evictBlock(BlockCacheKey cacheKey); void logStats(); long getFailedBlockAdditions(); long getRealCacheSize(); @Override void shutdown(); @Override CacheStats getStats(); BucketAllocator getAllocator(); @Override long heapSize(); @Override long size(); @Override long getFreeSize(); @Override long getBlockCount(); @Override long getCurrentSize(); @Override int evictBlocksByHfileName(String hfileName); @Override Iterator<CachedBlock> iterator(); @Override BlockCache[] getBlockCaches(); static final int DEFAULT_ERROR_TOLERATION_DURATION; }### Answer: @Test public void testHeapSizeChanges() throws Exception { cache.stopWriterThreads(); CacheTestUtils.testHeapSizeChanges(cache, BLOCK_SIZE); }
### Question: HFileBlock implements Cacheable { public int getUncompressedSizeWithoutHeader() { return uncompressedSizeWithoutHeader; } HFileBlock(BlockType blockType, int onDiskSizeWithoutHeader, int uncompressedSizeWithoutHeader, long prevBlockOffset, ByteBuffer buf, boolean fillHeader, long offset, int onDiskDataSizeWithHeader, HFileContext fileContext); HFileBlock(ByteBuffer b, boolean usesHBaseChecksum); BlockType getBlockType(); short getDataBlockEncodingId(); int getOnDiskSizeWithHeader(); int getOnDiskSizeWithoutHeader(); int getUncompressedSizeWithoutHeader(); long getPrevBlockOffset(); ByteBuffer getBufferWithoutHeader(); ByteBuffer getBufferReadOnly(); ByteBuffer getBufferReadOnlyWithHeader(); @Override String toString(); void assumeUncompressed(); void expectType(BlockType expectedType); long getOffset(); DataInputStream getByteStream(); @Override long heapSize(); static boolean readWithExtra(InputStream in, byte buf[], int bufOffset, int necessaryLen, int extraLen); int getNextBlockOnDiskSizeWithHeader(); @Override int getSerializedLength(); @Override void serialize(ByteBuffer destination); void serializeExtraInfo(ByteBuffer destination); @Override CacheableDeserializer<Cacheable> getDeserializer(); @Override boolean equals(Object comparison); DataBlockEncoding getDataBlockEncoding(); int headerSize(); static int headerSize(boolean usesHBaseChecksum); byte[] getDummyHeaderForVersion(); HFileContext getHFileContext(); static final boolean FILL_HEADER; static final boolean DONT_FILL_HEADER; static final int ENCODED_HEADER_SIZE; static final int BYTE_BUFFER_HEAP_SIZE; static final int EXTRA_SERIALIZATION_SPACE; }### Answer: @Test public void testNoCompression() throws IOException { assertEquals(4000, createTestV2Block(NONE, includesMemstoreTS, false). getBlockForCaching().getUncompressedSizeWithoutHeader()); }
### Question: Reference { public static Reference read(final FileSystem fs, final Path p) throws IOException { InputStream in = fs.open(p); try { in = in.markSupported()? in: new BufferedInputStream(in); int pblen = ProtobufUtil.lengthOfPBMagic(); in.mark(pblen); byte [] pbuf = new byte[pblen]; int read = in.read(pbuf); if (read != pblen) throw new IOException("read=" + read + ", wanted=" + pblen); if (ProtobufUtil.isPBMagicPrefix(pbuf)) return convert(FSProtos.Reference.parseFrom(in)); in.reset(); Reference r = new Reference(); DataInputStream dis = new DataInputStream(in); in = dis; r.readFields(dis); return r; } finally { in.close(); } } Reference(final byte [] splitRow, final Range fr); @Deprecated // Make this private when it comes time to let go of this constructor. Needed by pb serialization. Reference(); static Reference createTopReference(final byte [] splitRow); static Reference createBottomReference(final byte [] splitRow); Range getFileRegion(); byte [] getSplitKey(); @Override String toString(); static boolean isTopFileRegion(final Range r); @Deprecated void readFields(DataInput in); Path write(final FileSystem fs, final Path p); static Reference read(final FileSystem fs, final Path p); FSProtos.Reference convert(); static Reference convert(final FSProtos.Reference r); }### Answer: @Test public void testParsingWritableReference() throws IOException { final String datafile = System.getProperty("project.build.testSourceDirectory", "src/test") + File.separator + "data" + File.separator + "a6a6562b777440fd9c34885428f5cb61.21e75333ada3d5bafb34bb918f29576c"; FileSystem fs = FileSystem.get(HTU.getConfiguration()); Reference.read(fs, new Path(datafile)); }
### Question: HDFSBlocksDistribution { public void addHostsAndBlockWeight(String[] hosts, long weight) { if (hosts == null || hosts.length == 0) { return; } addUniqueWeight(weight); for (String hostname : hosts) { addHostAndBlockWeight(hostname, weight); } } HDFSBlocksDistribution(); @Override synchronized String toString(); void addHostsAndBlockWeight(String[] hosts, long weight); Map<String,HostAndWeight> getHostAndWeights(); long getWeight(String host); long getUniqueBlocksTotalWeight(); float getBlockLocalityIndex(String host); void add(HDFSBlocksDistribution otherBlocksDistribution); List<String> getTopHosts(); HostAndWeight[] getTopHostsWithWeights(); }### Answer: @Test public void testAddHostsAndBlockWeight() throws Exception { HDFSBlocksDistribution distribution = new HDFSBlocksDistribution(); distribution.addHostsAndBlockWeight(null, 100); assertEquals("Expecting no hosts weights", 0, distribution.getHostAndWeights().size()); distribution.addHostsAndBlockWeight(new String[0], 100); assertEquals("Expecting no hosts weights", 0, distribution.getHostAndWeights().size()); distribution.addHostsAndBlockWeight(new String[] {"test"}, 101); assertEquals("Should be one host", 1, distribution.getHostAndWeights().size()); distribution.addHostsAndBlockWeight(new String[] {"test"}, 202); assertEquals("Should be one host", 1, distribution.getHostAndWeights().size()); assertEquals("test host should have weight 303", 303, distribution.getHostAndWeights().get("test").getWeight()); distribution.addHostsAndBlockWeight(new String[] {"testTwo"}, 222); assertEquals("Should be two hosts", 2, distribution.getHostAndWeights().size()); assertEquals("Total weight should be 525", 525, distribution.getUniqueBlocksTotalWeight()); }
### Question: HDFSBlocksDistribution { public void add(HDFSBlocksDistribution otherBlocksDistribution) { Map<String,HostAndWeight> otherHostAndWeights = otherBlocksDistribution.getHostAndWeights(); for (Map.Entry<String, HostAndWeight> otherHostAndWeight: otherHostAndWeights.entrySet()) { addHostAndBlockWeight(otherHostAndWeight.getValue().host, otherHostAndWeight.getValue().weight); } addUniqueWeight(otherBlocksDistribution.getUniqueBlocksTotalWeight()); } HDFSBlocksDistribution(); @Override synchronized String toString(); void addHostsAndBlockWeight(String[] hosts, long weight); Map<String,HostAndWeight> getHostAndWeights(); long getWeight(String host); long getUniqueBlocksTotalWeight(); float getBlockLocalityIndex(String host); void add(HDFSBlocksDistribution otherBlocksDistribution); List<String> getTopHosts(); HostAndWeight[] getTopHostsWithWeights(); }### Answer: @Test public void testAdd() throws Exception { HDFSBlocksDistribution distribution = new HDFSBlocksDistribution(); distribution.add(new MockHDFSBlocksDistribution()); assertEquals("Expecting no hosts weights", 0, distribution.getHostAndWeights().size()); distribution.addHostsAndBlockWeight(new String[]{"test"}, 10); assertEquals("Should be one host", 1, distribution.getHostAndWeights().size()); distribution.add(new MockHDFSBlocksDistribution()); assertEquals("Should be one host", 1, distribution.getHostAndWeights().size()); assertEquals("Total weight should be 10", 10, distribution.getUniqueBlocksTotalWeight()); }
### Question: Activators { public static Object createInstance(String className) { log.trace("create instance... className=[{}]", className); try { return createInstance(Class.forName(className)); } catch (Exception e) { throw new RuntimeException(e); } } private Activators(); static Object createInstance(String className); static T createInstance(Class<T> clazz); @SuppressWarnings("unchecked") static T createInstance(Class<T> clazz, Object... initArgs); static Constructor<T> getConstructor(Class<T> clazz, Class<?>... parameterTypes); }### Answer: @BenchmarkOptions(benchmarkRounds = 100, warmupRounds = 1) @Test public void createInstanceWithDefaultConstructor() { JClass obj = Activators.createInstance(JClass.class); Assert.assertNotNull(obj); Assert.assertEquals(0, obj.getId()); } @BenchmarkOptions(benchmarkRounds = 100, warmupRounds = 1) @Test public void crateInstanceWithParameters() { JClass obj = Activators.createInstance(JClass.class, 100, "Dynamic", 200); Assert.assertNotNull(obj); Assert.assertEquals(100, obj.getId()); Assert.assertEquals("Dynamic", obj.getName()); }
### Question: Activators { public static <T> Constructor<T> getConstructor(Class<T> clazz, Class<?>... parameterTypes) { log.trace("[{}] μˆ˜ν˜•μ˜ μƒμ„±μžλ₯Ό κ΅¬ν•©λ‹ˆλ‹€. parameterTypes=[{}]", clazz.getName(), StringTool.listToString(parameterTypes)); try { return clazz.getDeclaredConstructor(parameterTypes); } catch (Exception e) { throw new RuntimeException(e); } } private Activators(); static Object createInstance(String className); static T createInstance(Class<T> clazz); @SuppressWarnings("unchecked") static T createInstance(Class<T> clazz, Object... initArgs); static Constructor<T> getConstructor(Class<T> clazz, Class<?>... parameterTypes); }### Answer: @BenchmarkOptions(benchmarkRounds = 100, warmupRounds = 1) @Test public void crateInstanceWithParameterTypes() throws Exception { JClass obj = (JClass) Activators .getConstructor(JClass.class, Integer.TYPE, String.class, Integer.class) .newInstance(100, "Dynamic", 200); Assert.assertNotNull(obj); Assert.assertEquals(100, obj.getId()); Assert.assertEquals("Dynamic", obj.getName()); } @BenchmarkOptions(benchmarkRounds = 100, warmupRounds = 1) @Test public void reflectionsWithDefaultConstructor() { try { JClass obj = (JClass) JClass.class .getConstructor(Integer.TYPE, String.class, Integer.class) .newInstance(100, "Dynamic", 200); Assert.assertNotNull(obj); Assert.assertEquals(100, obj.getId()); Assert.assertEquals("Dynamic", obj.getName()); } catch (Exception e) { throw new RuntimeException(e); } }
### Question: DynamicAccessorFactory { @SuppressWarnings("unchecked") public static <T> DynamicAccessor<T> create(Class<T> targetType) { try { return (DynamicAccessor<T>) cache.get(targetType); } catch (ExecutionException e) { log.error("DynamicAccessor λ₯Ό μƒμ„±ν•˜λŠ”λ° μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€. targetType=" + targetType.getName(), e); return null; } } @SuppressWarnings("unchecked") static DynamicAccessor<T> create(Class<T> targetType); static synchronized void clear(); }### Answer: @BenchmarkOptions(benchmarkRounds = 100, warmupRounds = 1) @Test public void createDynamicAccessor() { DynamicAccessor<User> userAccessor = DynamicAccessorFactory.create(User.class); Assert.assertNotNull(userAccessor); Object user = userAccessor.newInstance(); userAccessor.setProperty(user, "email", "[email protected]"); Assert.assertEquals("[email protected]", userAccessor.getProperty(user, "email")); }
### Question: CryptoTool { public static byte[] getRandomBytes(final int numBytes) { assert (numBytes >= 0); byte[] bytes = new byte[numBytes]; if (numBytes > 0) random.nextBytes(bytes); return bytes; } private CryptoTool(); static byte[] getRandomBytes(final int numBytes); }### Answer: @Test public void getRandomBytesTest() throws Exception { byte[] bytes = CryptoTool.getRandomBytes(100); byte[] bytes2 = CryptoTool.getRandomBytes(100); Assert.assertEquals(bytes.length, bytes2.length); Assert.assertFalse(Arrays.equals(bytes, bytes2)); }
### Question: FutureWebCacheRepository extends CacheRepositoryBase { @Override public Object get(final String key) throws ExecutionException { return cache.get(key); } FutureWebCacheRepository(); @Override Object get(final String key); @Override void set(final String key, final Object value, long validFor); @Override void remove(final String key); @Override void removeAll(final String... keys); @Override void removeAll(final Iterable<String> keys); @Override boolean exists(final String key); @Override void clear(); }### Answer: @Test public void webCacheRepositoryTest() throws Exception { FutureWebCacheRepository repository = new FutureWebCacheRepository(); Stopwatch stopwatch = new Stopwatch(); for (final String url : urls) { stopwatch.start(); repository.get(url); stopwatch.stop(); log.debug("First: " + stopwatch.toString()); stopwatch.start(); repository.get(url); stopwatch.stop(); log.debug("Second: " + stopwatch.toString()); } }
### Question: NumberRange implements Iterable<T> { public static IntRange range(int fromInclude, int toExclude, int step) { return new IntRange(fromInclude, toExclude, step); } private NumberRange(); static IntRange range(int fromInclude, int toExclude, int step); static IntRange range(int fromInclude, int toExclude); static IntRange range(int count); static LongRange range(long fromInclude, long toExclude, long step); static LongRange range(long fromInclude, long toExclude); static LongRange range(long count); static List<IntRange> partition(IntRange range, int partitionCount); static List<IntRange> partition(int fromInclude, int toExclude, int step, int partitionCount); static List<IntRange> partition(int fromInclude, int toExclude, int partitionCount); static List<IntRange> partition(int count, int partitionCount); static List<LongRange> partition(LongRange range, int partitionCount); static List<LongRange> partition(long fromInclude, long toExclude, int step, int partitionCount); static List<LongRange> partition(long fromInclude, long toExclude, int partitionCount); static List<LongRange> partition(long count, int partitionCount); }### Answer: @Test public void createIntRange() { NumberRange.IntRange intRange = NumberRange.range(10); assertEquals(0, intRange.getFromInclude()); assertEquals(10, intRange.getToExclude()); assertEquals(1, intRange.getStep()); assertEquals(10, intRange.size()); log.debug(StringTool.join(intRange, ",")); intRange.reset(); for (int x : intRange) System.out.print(x + ", "); }
### Question: MongoCache implements Cache { @Override public void clear() { mongoTemplate.dropCollection(name); } MongoCache(String name, MongoTemplate mongoTemplate); @Override String getName(); @Override Object getNativeCache(); @Override ValueWrapper get(Object key); @Override void put(Object key, Object value); @Override void evict(Object key); @Override void clear(); }### Answer: @Test public void clearTest() { Assert.assertNotNull(cacheManager); Cache cache = cacheManager.getCache("user"); Assert.assertNotNull(cache); }
### Question: MapperTool { public static <T> T map(final Object source, final Class<T> destinationClass) { shouldNotBeNull(source, "source"); shouldNotBeNull(destinationClass, "destinationClass"); return mapper.map(source, destinationClass); } private MapperTool(); static T map(final Object source, final Class<T> destinationClass); static void map(final Object source, Object destination); static List<T> mapList(final Iterable<S> sources, final Class<T> destinationClass); static Future<T> mapAsync(final Object source, final Class<T> destinationClass); static Future<List<T>> mapListAsync(final Iterable<S> sources, final Class<T> destinationClass); }### Answer: @BenchmarkOptions(benchmarkRounds = 100, warmupRounds = 1) @Test public void mapTest() { Parent parent = getParentSample(); ParentDTO parentDTO = MapperTool.map(parent, ParentDTO.class); Assert.assertNotNull(parentDTO); Assert.assertEquals(parent.getChildren().size(), parentDTO.getChildren().size()); Assert.assertEquals(parent.getName(), parentDTO.getName()); for (int i = 0; i < parent.getChildren().size(); i++) { Assert.assertEquals(parent.getChildren().get(i).getName(), parentDTO.getChildren().get(i).getName()); Assert.assertEquals(parent.getChildren().get(i).getDescription(), parentDTO.getChildren().get(i).getDescription()); } }
### Question: HashTool { public static int compute(final Object... objs) { if (objs == null || objs.length == 0) return NULL_VALUE; int hash = NULL_VALUE; for (Object x : objs) { hash = hash * FACTOR + computeInternal(x); } return hash; } static int compute(final Object... objs); static final int NULL_VALUE; static final int ONE_VALUE; static final int FACTOR; }### Answer: @BenchmarkOptions(benchmarkRounds = 100, warmupRounds = 1) @Test public void computeHashTest() { int a = HashTool.compute(1, 2); int b = HashTool.compute(2, 1); assertNotEquals(a, b); assertEquals(a, HashTool.compute(1, 2)); int withNull1 = HashTool.compute(new YearWeek(2013, 1), null); int withNull2 = HashTool.compute(null, new YearWeek(2013, 1)); int withNull3 = HashTool.compute(new YearWeek(2013, 1), null); assertNotEquals(withNull1, withNull2); assertNotEquals(withNull2, withNull3); assertEquals(withNull1, withNull3); }
### Question: HiveUtil extends BaseDao { public static boolean isTokDDL(String sql) { if (org.apache.commons.lang3.StringUtils.isEmpty(sql)) { return false; } String tmp = sql.toUpperCase(); if (tmp.startsWith("CREATE") || tmp.startsWith("DROP") || tmp.startsWith("ALTER")) { return true; } return false; } @Override void init(); static String getTmpTableName(int projectId, int execId); static String getORCTmpTableDDL(String dbName, String tableName, List<HqlColumn> hqlColumnList, String localtion); static String getTmpTableDDL(String dbName, String tableName, List<HqlColumn> hqlColumnList, String localtion, String fieldDelimiter, String fileCode); static boolean isTokQuery(String sql); static boolean isTokDDL(String sql); static boolean isLikeShowStm(String sql); HiveService2Client getHiveService2Client(); HiveMetaPoolClient getHiveMetaPoolClient(); HiveService2ConnectionInfo getHiveService2ConnectionInfo(String userName); static final int DEFAULT_QUERY_PROGRESS_THREAD_TIMEOUT; }### Answer: @Test public void testDDL() { assertFalse(HiveUtil.isTokDDL("")); assertTrue(HiveUtil.isTokDDL("create table abc")); assertTrue(HiveUtil.isTokDDL("alter table abc")); assertFalse(HiveUtil.isTokDDL("select * from abc")); assertFalse(HiveUtil.isTokDDL(null)); }
### Question: HdfsClient implements Closeable { public void mkdir(String dir) throws HdfsException { mkdir(dir, FsPermission.getDefault()); } private HdfsClient(Configuration conf); static void init(Configuration conf); static HdfsClient getInstance(); void addFile(String fileName, byte[] content, String destPath, boolean isOverwrite); void readFile(String hdfsFile, String localFile, boolean overwrite); byte[] readFile(String hdfsFile); boolean delete(String path, boolean recursive); boolean rename(String path, String destPath); void mkdir(String dir); void mkdir(String dir, FsPermission perm); void setOwner(Path path, String user, String group); void setPermission(Path path, FsPermission perm); void setPermissionThis(Path path, FsPermission perm); boolean copy(String srcPath, String dstPath, boolean deleteSource, boolean overwrite); boolean copyLocalToHdfs(String srcPath, String dstPath, boolean deleteSource, boolean overwrite); boolean copyHdfsToLocal(String srcPath, String dstPath, boolean deleteSource, boolean overwrite); long getFileLength(String filePath); boolean exists(String filePath); FileStatus getFileStatus(String filePath); FileStatus[] listFileStatus(String filePath); ContentSummary getContentSummary(String filePath); String getUrl(); @Override void close(); FsStatus getCapacity(); }### Answer: @Test public void testMkdir() { try { hdfsClient.mkdir("/tmp/test-001/2/3/"); assertEquals(hdfsClient.exists("/tmp/test-001/2/3/"), true); } catch (IOException e) { assertTrue(false); } hdfsClient.delete("/tmp/test-001", true); try { assertEquals(hdfsClient.exists("/tmp/test-001"), false); } catch (IOException e) { assertTrue(true); } }
### Question: HiveMetaExec { public List<String> getTables(String dbname) throws Exception { HiveMetaStoreClient hiveMetaStoreClient = hiveMetaPoolClient.borrowClient(); try { return hiveMetaStoreClient.getAllTables(dbname); } catch (Exception e) { doWithException(hiveMetaStoreClient, e); throw e; } finally { if (hiveMetaStoreClient != null) { hiveMetaPoolClient.returnClient(hiveMetaStoreClient); } } } HiveMetaExec(Logger logger); List<HqlColumn> getHiveDesc(String dbName, String tableName); List<HqlColumn> checkHiveColumn(List<HiveColumn> srcColumn, List<HqlColumn> destColumn); List<FieldSchema> getPartionField(String dbName, String table); List<FieldSchema> getGeneralField(String dbName, String table); List<String> getTables(String dbname); List<Table> getTableObjectsByName(String dbname); }### Answer: @Test public void testGetTables() { try { Logger logger = LoggerFactory.getLogger(HiveMetaExec.class); HiveMetaExec hiveMetaExec = new HiveMetaExec(logger); int times = 100; long start = System.currentTimeMillis(); for (int i = 0; i < times; ++i) { hiveMetaExec.getTables("dw"); } long end = System.currentTimeMillis(); System.out.println("get tables time(ms): " + (end - start) / times); start = System.currentTimeMillis(); for (int i = 0; i < times; ++i) { hiveMetaExec.getTableObjectsByName("dw"); } end = System.currentTimeMillis(); System.out.println("get tables objects time(ms): " + (end - start) / times); } catch (Exception e) { } }
### Question: OracleDatasource extends Datasource { @Override public void isConnectable() throws Exception { Connection con = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); String address = MessageFormat.format("jdbc:oracle:thin:@ con = DriverManager.getConnection(address, this.user, this.password); } finally { if (con != null) { try { con.close(); } catch (SQLException e) { logger.error("Orcale datasource try conn close conn error", e); throw e; } } } } static Logger getLogger(); static void setLogger(Logger logger); String getHost(); void setHost(String host); int getPort(); void setPort(int port); String getService(); void setService(String service); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); @Override void isConnectable(); }### Answer: @Test public void testIsConnectable() throws Exception { OracleDatasource oracleDatasource = new OracleDatasource(); oracleDatasource.setHost("172.18.1.112"); oracleDatasource.setPort(1521); oracleDatasource.setService("orcl"); oracleDatasource.setUser("test"); oracleDatasource.setPassword("test"); oracleDatasource.isConnectable(); }
### Question: FtpDatasource extends Datasource { @Override public void isConnectable() throws Exception { FTPClient ftpClient = new FTPClient(); ftpClient.connect(this.host, this.port); if (!ftpClient.login(this.user, this.password)){ throw new Exception("wrong user name or password"); } } String getHost(); void setHost(String host); int getPort(); void setPort(int port); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); @Override void isConnectable(); }### Answer: @Test public void testIsConnectable() throws Exception { }
### Question: PostgreDatasource extends Datasource { @Override public void isConnectable() throws Exception { Connection con = null; try { Class.forName("org.postgresql.Driver"); con = DriverManager.getConnection(getJdbcUrl(), this.user, this.password); } finally { if (con != null) { try { con.close(); } catch (SQLException e) { logger.error("Postgre datasource try conn close conn error", e); throw e; } } } } String getAddress(); void setAddress(String address); String getDatabase(); void setDatabase(String database); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); String getJdbcUrl(); @Override void isConnectable(); }### Answer: @Test public void testIsConnectable() throws Exception { PostgreDatasource postgreDatasource = new PostgreDatasource(); postgreDatasource.setAddress("jdbc:postgresql: postgreDatasource.setUser("postgres"); postgreDatasource.setDatabase("test01"); postgreDatasource.setPassword("postgres-2017"); postgreDatasource.isConnectable(); }
### Question: MailSendUtil { public static boolean sendMails(Collection<String> receivers, String title, String content) { if (receivers == null) { LOGGER.error("Mail receivers is null."); return false; } receivers.removeIf((from) -> (StringUtils.isEmpty(from))); if (receivers.isEmpty()) { LOGGER.error("Mail receivers is empty."); return false; } HtmlEmail email = new HtmlEmail(); try { email.setHostName(mailServerHost); email.setSmtpPort(mailServerPort); email.setCharset("UTF-8"); for (String receiver : receivers) { email.addTo(receiver); } email.setFrom(mailSender, mailSender); email.setAuthentication(mailSender, mailPasswd); email.setSubject(title); email.setMsg(content); email.send(); return true; } catch (Throwable e) { LOGGER.error("Send email to {} failed", StringUtils.join(",", receivers), e); } return false; } static boolean sendMails(Collection<String> receivers, String title, String content); }### Answer: @Test public void testSendMails() { String[] mails = new String[]{"[email protected]"}; String title = "test from swordfish"; String content = "test"; MailSendUtil.sendMails(Arrays.asList(mails), title, content); }
### Question: CrontabUtil { public static List<Date> getCycleFireDate(Date startTime, Date endTime, CronExpression cronExpression) { List<Date> dateList = new ArrayList<>(); while (true) { startTime = cronExpression.getNextValidTimeAfter(startTime); if (startTime.after(endTime)) { break; } dateList.add(startTime); } return dateList; } static Cron parseCron(String crontab); static CronExpression parseCronExp(String crontab); static ScheduleType getCycle(Cron cron); static ScheduleType getCycle(String crontab); static List<Date> getCycleFireDate(Date startTime, Date endTime, CronExpression cronExpression); static ZonedDateTime parseDateToZdt(Date date); static Date parseZdtToDate(ZonedDateTime zdt); static Map.Entry<Date, Date> getPreCycleDate(Date scheduledFireTime, ScheduleType scheduleType); }### Answer: @Test public void testGetCycleFireDate() throws ParseException { String hourCrontab = "0 0 2-22/2 * * ? *"; CronExpression cronExpression = CrontabUtil.parseCronExp(hourCrontab); Date startTime = new Date(1495555200000L); Date endTime = new Date(1495814400000L); List<Date> dateList = CrontabUtil.getCycleFireDate(startTime, endTime, cronExpression); for (Date date : dateList) { System.out.println(date); } }
### Question: FlowNode { public void setDep(String dep) throws IOException { this.dep = dep; this.depList = JsonUtil.parseObjectList(dep, String.class); } int getId(); void setId(int id); String getName(); void setName(String name); String getDesc(); void setDesc(String desc); String getType(); void setType(String type); int getFlowId(); void setFlowId(int flowId); String getParameter(); void setParameter(String parameter); String getDep(); void setDep(String dep); String getExtras(); void setExtras(String extras); List<String> getDepList(); void setDepList(List<String> depList); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testSetDep() throws IOException { }
### Question: FlowNode { public void setName(String name) { this.name = name; } int getId(); void setId(int id); String getName(); void setName(String name); String getDesc(); void setDesc(String desc); String getType(); void setType(String type); int getFlowId(); void setFlowId(int flowId); String getParameter(); void setParameter(String parameter); String getDep(); void setDep(String dep); String getExtras(); void setExtras(String extras); List<String> getDepList(); void setDepList(List<String> depList); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testDeserializer() { String nodeStr = "{\"name\":\"shelljob1\",\"desc\":\"shell\",\"type\":\"VIRTUAL\",\"parameter\":{\"script\":\"echo shelljob1\"},\"dep\":[],\"extras\":null}"; FlowNode flowNode = JsonUtil.parseObject(nodeStr, FlowNode.class); List<FlowNode> nodes = new ArrayList<>(); nodes.add(flowNode); flowNode.setName("shelljob2"); nodes.add(flowNode); String nodesStr = JsonUtil.toJsonString(nodes); }
### Question: ParamHelper { public static String resolvePlaceholders(String text, Map<String, String> paramMap) { if (StringUtils.isEmpty(text)) { return text; } String cycTimeStr = paramMap.get(SystemParamManager.CYC_TIME); Date cycTime = getCycTime(cycTimeStr); text = PlaceholderUtil.resolvePlaceholders(text, paramMap, true); if (cycTime != null) { text = TimePlaceholderUtil.resolvePlaceholders(text, cycTime, true); } return text; } static String resolvePlaceholders(String text, Map<String, String> paramMap); }### Answer: @Test public void testResolvePlaceholders() { Map<String, String> definedParamMap = SystemParamManager .buildSystemParam(ExecType.DIRECT, new Date(), 200, "job id 001"); String sqls = "${sf.system.bizdate}"; System.out.println(ParamHelper.resolvePlaceholders(sqls, definedParamMap)); sqls = "${sf.system.bizcurdate}"; System.out.println(ParamHelper.resolvePlaceholders(sqls, definedParamMap)); sqls = "${sf.system.cyctime}"; System.out.println(ParamHelper.resolvePlaceholders(sqls, definedParamMap)); sqls = "$[yyyyMMdd]"; System.out.println(ParamHelper.resolvePlaceholders(sqls, definedParamMap)); sqls = "${sf.system.execId}"; System.out.println(ParamHelper.resolvePlaceholders(sqls, definedParamMap)); sqls = "${sf.system.jobId}"; System.out.println(ParamHelper.resolvePlaceholders(sqls, definedParamMap)); }
### Question: AdHocDao extends BaseDao { public AdHoc getAdHoc(int id) { return adHocMapper.selectById(id); } boolean updateAdHoc(AdHoc adHoc); boolean updateAdHocStatus(AdHoc adHoc); AdHoc getAdHoc(int id); boolean updateAdHocResult(AdHocResult adHocResult); @Transactional(value = "TransactionManager") void initAdHocResult(int execId, List<String> execSqls); }### Answer: @Test public void testgetAdHoc() { }
### Question: FlowDao extends BaseDao { public ExecutionFlow queryExecutionFlow(int execId) { return executionFlowMapper.selectByExecId(execId); } ExecutionFlow queryExecutionFlow(int execId); int deleteExecutionNodes(int execId); List<ExecutionFlow> queryAllNoFinishFlow(); List<ExecutionFlow> queryNoFinishFlow(String worker); ExecutionFlow queryExecutionFlowByScheduleTime(int flowId, Date scheduleTime); boolean updateExecutionFlowStatus(int execId, FlowStatus status); boolean updateExecutionFlowStatus(int execId, FlowStatus status, String worker); boolean updateExecutionFlow(ExecutionFlow executionFlow); boolean updateExecutionFlowDataSub(ExecutionFlow executionFlow); ExecutionFlow scheduleFlowToExecution(Integer projectId, Integer workflowId, int submitUser, Date scheduleTime, ExecType runType, FailurePolicyType failurePolicyType, Integer maxTryTimes, String nodeName, NodeDepType nodeDep, NotifyType notifyType, List<String> mails, int timeout); @Transactional(value = "TransactionManager") void deleteWorkflow(int workflowId); void insertExecutionNode(ExecutionNode executionNode); void updateExecutionNode(ExecutionNode executionNode); ExecutionNode queryExecutionNode(long execId, String nodeName); Schedule querySchedule(int flowId); ProjectFlow projectFlowfindByName(int projectId, String name); ProjectFlow projectFlowFindById(int id); @Transactional(value = "TransactionManager", rollbackFor = Exception.class) void createProjectFlow(ProjectFlow projectFlow); @Transactional(value = "TransactionManager", rollbackFor = Exception.class) void modifyProjectFlow(ProjectFlow projectFlow); ProjectFlow projectFlowFindByPorjectNameAndName(String projectName, String name); List<ProjectFlow> projectFlowFindByProject(int projectId); ExecutionFlow executionFlowPreDate(int flowId, Date date); ExecutionFlow executionFlowPreDate2(int flowId, Date date); ExecutionFlow executionFlowByStartTimeAndScheduleTime(int flowId, Date startTIme, Date scheduleTime); }### Answer: @Test public void testQueryExecutionFlow() { }
### Question: FlowDao extends BaseDao { public Schedule querySchedule(int flowId) { return scheduleMapper.selectByFlowId(flowId); } ExecutionFlow queryExecutionFlow(int execId); int deleteExecutionNodes(int execId); List<ExecutionFlow> queryAllNoFinishFlow(); List<ExecutionFlow> queryNoFinishFlow(String worker); ExecutionFlow queryExecutionFlowByScheduleTime(int flowId, Date scheduleTime); boolean updateExecutionFlowStatus(int execId, FlowStatus status); boolean updateExecutionFlowStatus(int execId, FlowStatus status, String worker); boolean updateExecutionFlow(ExecutionFlow executionFlow); boolean updateExecutionFlowDataSub(ExecutionFlow executionFlow); ExecutionFlow scheduleFlowToExecution(Integer projectId, Integer workflowId, int submitUser, Date scheduleTime, ExecType runType, FailurePolicyType failurePolicyType, Integer maxTryTimes, String nodeName, NodeDepType nodeDep, NotifyType notifyType, List<String> mails, int timeout); @Transactional(value = "TransactionManager") void deleteWorkflow(int workflowId); void insertExecutionNode(ExecutionNode executionNode); void updateExecutionNode(ExecutionNode executionNode); ExecutionNode queryExecutionNode(long execId, String nodeName); Schedule querySchedule(int flowId); ProjectFlow projectFlowfindByName(int projectId, String name); ProjectFlow projectFlowFindById(int id); @Transactional(value = "TransactionManager", rollbackFor = Exception.class) void createProjectFlow(ProjectFlow projectFlow); @Transactional(value = "TransactionManager", rollbackFor = Exception.class) void modifyProjectFlow(ProjectFlow projectFlow); ProjectFlow projectFlowFindByPorjectNameAndName(String projectName, String name); List<ProjectFlow> projectFlowFindByProject(int projectId); ExecutionFlow executionFlowPreDate(int flowId, Date date); ExecutionFlow executionFlowPreDate2(int flowId, Date date); ExecutionFlow executionFlowByStartTimeAndScheduleTime(int flowId, Date startTIme, Date scheduleTime); }### Answer: @Test public void testQuerySchedule() { }
### Question: VerifyUtil { public static boolean matcheUserName(String str) { return regexMatches(str, Constants.REGEX_USER_NAME); } static boolean regexMatches(String str, Pattern pattern); static boolean matcheProjectName(String str); static boolean matcheUserName(String str); static boolean matchEmail(String str); static boolean matcheResName(String str); static boolean matcheDatasourceName(String str); static boolean matchWorkflowName(String str); static boolean matchProxyUser(String str); }### Answer: @Test public void testMatcheUserName() { { String test = "bfd_test"; assertTrue(VerifyUtil.matcheUserName(test)); } }
### Question: VerifyUtil { public static boolean matcheProjectName(String str) { return regexMatches(str, Constants.REGEX_PROJECT_NAME); } static boolean regexMatches(String str, Pattern pattern); static boolean matcheProjectName(String str); static boolean matcheUserName(String str); static boolean matchEmail(String str); static boolean matcheResName(String str); static boolean matcheDatasourceName(String str); static boolean matchWorkflowName(String str); static boolean matchProxyUser(String str); }### Answer: @Test public void testMatcheProjectName() { { String test = "bfd_test"; assertTrue(VerifyUtil.matcheProjectName(test)); } }
### Question: VerifyUtil { public static boolean matcheResName(String str) { return regexMatches(str, Constants.REGEX_RES_NAME); } static boolean regexMatches(String str, Pattern pattern); static boolean matcheProjectName(String str); static boolean matcheUserName(String str); static boolean matchEmail(String str); static boolean matcheResName(String str); static boolean matcheDatasourceName(String str); static boolean matchWorkflowName(String str); static boolean matchProxyUser(String str); }### Answer: @Test public void testMatcheResName() { { assertTrue(VerifyUtil.matcheResName("aa.jar")); assertTrue(VerifyUtil.matcheResName("spark-examples-1.0-SNAPSHOT-hadoop2.6.0.jar")); } }
### Question: DroneInstance extends Instance { public static String getTeamname(Discoverer discoverer, String id){ return discoverer.getNode(new DroneInstance(id)).getValues().getOrDefault("team", null); } DroneInstance(String id); DroneInstance(String id, Map<String, String> properties); static String getTeamname(Discoverer discoverer, String id); }### Answer: @Test public void getTeamname() throws Exception { String id = ""; Map<String, String> props = new HashMap<>(); DroneInstance instance = new DroneInstance(id); MockDiscoverer discoverer = spy(new MockDiscoverer()); MockDiscoveryStoredNode node = new MockDiscoveryStoredNode(id, props); doReturn(node).when(discoverer).getNode(any()); Assert.assertEquals(DroneInstance.getTeamname(discoverer, id), null); String teamname = "test_team"; props.put("team", teamname); Assert.assertEquals(DroneInstance.getTeamname(discoverer, id), teamname); }
### Question: Tactic extends ManagedThread implements Subscriber { @Override protected final void work() throws InterruptedException { if (ticker.timeIsExceeded()) { ticker.reset(); Thread t = new Thread(this::calculateTactics); t.start(); workTimoutTimer.reset(); while (t.isAlive()) { if (workTimoutTimer.timeIsExceeded()) { t.interrupt(); } } } } Radar getRadar(); GPS getGps(); Engine getEngine(); Gun getGun(); Radio getRadio(); final void startTactic(); final void stopTactic(); @Override @Deprecated final void destroy(); @Override void receive(Object msg, MultipartCallbacks multipartCallbacks); final String getIdentifier(); final Set<String> getAvailableComponents(); }### Answer: @Test public void testWork() throws Exception { TimeoutTimer ticker = getField(tactic, "ticker"); double timeout = getField(ticker, "timeout"); verify(tacticMock, times(0)).calculateTactics(); ticker.reset(); tactic.work(); verify(tacticMock, times(0)).calculateTactics(); TestUtils.setField(ticker, "lastTime", System.currentTimeMillis() - (long) timeout - 1L); tactic.work(); verify(tacticMock, times(1)).calculateTactics(); } @Test public void testWorkWithSlowTactic() throws Exception { double timeout = getField(getField(tactic, "ticker"), "timeout"); long durationLongCommand = (long) timeout * 5; boolean[] isInterrupted = new boolean[1]; Tactic tacticSlow = new DoNothingTactic() { @Override protected void calculateTactics() { try { Thread.sleep(durationLongCommand); } catch (InterruptedException e) { isInterrupted[0] = true; } } }; long executeStart = System.currentTimeMillis(); tacticSlow.work(); long executeEnd = System.currentTimeMillis(); Assert.assertTrue(isInterrupted[0]); Assert.assertTrue(executeEnd - executeStart < durationLongCommand); }
### Question: Tactic extends ManagedThread implements Subscriber { public final Set<String> getAvailableComponents() { Set<String> componentlist = new HashSet<>(); if (radar != null) { componentlist.add("radar"); } if (gps != null) { componentlist.add("gps"); } if (engine != null) { componentlist.add("engine"); } if (radio != null) { componentlist.add("radio"); } if (gun != null) { componentlist.add("gun"); } return componentlist; } Radar getRadar(); GPS getGps(); Engine getEngine(); Gun getGun(); Radio getRadio(); final void startTactic(); final void stopTactic(); @Override @Deprecated final void destroy(); @Override void receive(Object msg, MultipartCallbacks multipartCallbacks); final String getIdentifier(); final Set<String> getAvailableComponents(); }### Answer: @Test public void getAvailableComponents() throws Exception { Assert.assertEquals(new HashSet<>(Arrays.asList("engine", "radio", "radar", "gps", "gun")), tactic.getAvailableComponents()); setField(tactic, "gun", null); Assert.assertEquals(new HashSet<>(Arrays.asList("engine", "radio", "radar", "gps")), tactic.getAvailableComponents()); }
### Question: DroneInit { public void start() throws IOException { log.info("Starting the drone now!"); this.registerDroneService(); } DroneInit(String identifier, Discoverer discoverer, Instance registeredInstance); DroneInit(); String getIdentifier(); void setIdentifier(String identifier); static Logger getLog(); Discoverer getDiscoverer(); void setDiscoverer(Discoverer discoverer); Instance getRegisteredInstance(); void setRegisteredInstance(Instance registeredInstance); void start(); void stop(); String getTeamname(); void initIdentifier(); }### Answer: @Test public void testStart() throws Exception { environmentVariables.set("DRONENAME", instance.getName()); drone.initIdentifier(); drone.start(); Assert.assertTrue(mockDiscoverer.getRegisteredInstances().parallelStream().filter(ri -> ri.getName().equals(instance.getName())).count() == 1); drone.start(); Assert.assertThat(drone.getIdentifier(), startsWith(instance.getName() + "-")); Assert.assertThat(mockDiscoverer.getRegisteredInstances().size(), is(2)); }
### Question: DroneInit { public void stop() throws IOException { log.info("Stopping the drone now!"); this.unregisterDroneService(); } DroneInit(String identifier, Discoverer discoverer, Instance registeredInstance); DroneInit(); String getIdentifier(); void setIdentifier(String identifier); static Logger getLog(); Discoverer getDiscoverer(); void setDiscoverer(Discoverer discoverer); Instance getRegisteredInstance(); void setRegisteredInstance(Instance registeredInstance); void start(); void stop(); String getTeamname(); void initIdentifier(); }### Answer: @Test public void testStop() throws Exception { testStart(); drone.stop(); Assert.assertTrue(mockDiscoverer.getRegisteredInstances().parallelStream().filter(ri -> ri.getName().equals(instance.getName())).count() == 1); Assert.assertTrue(mockDiscoverer.getRegisteredInstances().get(0).getName().equals(instance.getName())); }
### Question: DroneInit { public String getTeamname() { String teamname = "unknown_team"; if (System.getenv("DRONE_TEAM") != null) { teamname = System.getenv("DRONE_TEAM"); } return teamname; } DroneInit(String identifier, Discoverer discoverer, Instance registeredInstance); DroneInit(); String getIdentifier(); void setIdentifier(String identifier); static Logger getLog(); Discoverer getDiscoverer(); void setDiscoverer(Discoverer discoverer); Instance getRegisteredInstance(); void setRegisteredInstance(Instance registeredInstance); void start(); void stop(); String getTeamname(); void initIdentifier(); }### Answer: @Test public void testGetTeamname() throws Exception { Assert.assertEquals("unknown_team", drone.getTeamname()); environmentVariables.set("DRONE_TEAM", "known_team"); Assert.assertEquals("known_team", drone.getTeamname()); }
### Question: DroneInit { public void initIdentifier() { Map<String, String> env = System.getenv(); if (env.containsKey("DRONENAME")) this.setIdentifier(env.get("DRONENAME")); else if (env.containsKey("COMPUTERNAME")) this.setIdentifier(env.get("COMPUTERNAME")); else if (env.containsKey("HOSTNAME")) this.setIdentifier(env.get("HOSTNAME")); else this.setIdentifier(UUID.randomUUID().toString()); } DroneInit(String identifier, Discoverer discoverer, Instance registeredInstance); DroneInit(); String getIdentifier(); void setIdentifier(String identifier); static Logger getLog(); Discoverer getDiscoverer(); void setDiscoverer(Discoverer discoverer); Instance getRegisteredInstance(); void setRegisteredInstance(Instance registeredInstance); void start(); void stop(); String getTeamname(); void initIdentifier(); }### Answer: @Test public void testInitIdentifier() throws Exception { DroneInit simpleDrone = new DroneInit(); Assert.assertThat(simpleDrone.getIdentifier(), isUUID()); environmentVariables.set("HOSTNAME", "HOSTNAME"); simpleDrone = new DroneInit(); Assert.assertThat(simpleDrone.getIdentifier(), is("HOSTNAME")); environmentVariables.set("COMPUTERNAME", "COMPUTERNAME"); simpleDrone = new DroneInit(); Assert.assertThat(simpleDrone.getIdentifier(), is("COMPUTERNAME")); environmentVariables.set("DRONENAME", "DRONENAME"); simpleDrone = new DroneInit(); Assert.assertThat(simpleDrone.getIdentifier(), is("DRONENAME")); }
### Question: Explosion extends UIUpdate { @Override public void execute(Pane pane) { ImageView explosionImage = new ImageView(new Image(getClass().getResourceAsStream("/explosion.png"))); explosionImage.setScaleX(scale); explosionImage.setScaleY(scale); explosionImage.setX(imageView.getLayoutX() - imageView.getFitWidth() / 2); explosionImage.setY(imageView.getLayoutY() - imageView.getFitHeight() / 2); SpriteAnimation explosionAnimation = new SpriteAnimation(explosionImage, Duration.millis(1000), 40, 8, 0, 0, 256, 256); explosionAnimation.setCycleCount(1); explosionAnimation.play(); pane.getChildren().addAll(explosionImage); explosionAnimation.setOnFinished( event -> { pane.getChildren().remove(explosionImage); log.warn("Removed"); } ); } Explosion(double scale, ImageView imageView); @Override void execute(Pane pane); }### Answer: @Test public void execute() throws Exception { Pane pane = mock(Pane.class); LinkedList<Node> paneChildren = new LinkedList<>(); when(pane.getChildren()).thenReturn(new ObservableListWrapper<>(paneChildren)); ImageView imageView = mock(ImageView.class); Explosion explosion = new Explosion(0.5, imageView); explosion.execute(pane); Assert.assertThat(paneChildren, hasSize(greaterThan(0))); }
### Question: BaseEntity { void updateUI() { setSpriteX(position.getX() - imageView.getFitWidth() / 2); setSpriteY(position.getY() - imageView.getFitHeight() / 2); imageView.relocate(getSpriteX(), getSpriteY()); imageView.setRotate(getRotation()); imageView.setScaleX(getScale()); imageView.setScaleY(getScale()); } BaseEntity(BlockingQueue<UIUpdate> uiUpdates, String image); void setPosition(D3Vector position); void setDirection(D3PolarCoordinate direction); double getSpriteX(); void setSpriteX(double spriteX); double getSpriteY(); void setSpriteY(double spriteY); String getId(); void setId(String id); void delete(); }### Answer: @Test public void testUpdateUI() throws Exception { D3Vector position = new D3Vector(150, 100, 500); baseEntity.setPosition(position); D3PolarCoordinate direction = new D3PolarCoordinate(0.25 * Math.PI, 0.5 * Math.PI, 100); baseEntity.setDirection(direction); baseEntity.updateUI(); Assert.assertEquals(150, baseEntity.getSpriteX(), 0.1); Assert.assertEquals(100, baseEntity.getSpriteY(), 0.1); Assert.assertEquals(150, baseEntity.imageView.getLayoutX(), 0.1); Assert.assertEquals(100, baseEntity.imageView.getLayoutY(), 0.1); Assert.assertEquals(45, baseEntity.imageView.getRotate(), 0.1); Assert.assertEquals(0.55, baseEntity.imageView.getScaleX(), 0.1); Assert.assertEquals(0.55, baseEntity.imageView.getScaleY(), 0.1); }
### Question: BaseEntity { public void delete() { uiUpdates.add(new RemoveBaseEntity(imageView)); } BaseEntity(BlockingQueue<UIUpdate> uiUpdates, String image); void setPosition(D3Vector position); void setDirection(D3PolarCoordinate direction); double getSpriteX(); void setSpriteX(double spriteX); double getSpriteY(); void setSpriteY(double spriteY); String getId(); void setId(String id); void delete(); }### Answer: @Test public void testDelete() throws Exception { int sizeBefore = uiUpdates.size(); baseEntity.delete(); int sizeAfter = uiUpdates.size(); Assert.assertEquals(sizeBefore + 1, sizeAfter); Assert.assertTrue(uiUpdates.contains(new RemoveBaseEntity(baseEntity.imageView))); }
### Question: ArchitectureButtonEventHandler implements EventHandler<MouseEvent> { @Override public void handle(MouseEvent event) { RequestArchitectureStateChangeMessage msg = new RequestArchitectureStateChangeMessage(action); publisher.send(msg); } ArchitectureButtonEventHandler(SimulationAction action, Publisher publisher); @Override void handle(MouseEvent event); }### Answer: @Test public void testHandle() { handler.handle(mock(MouseEvent.class)); Assert.assertTrue(publisher.isMessageReceived(MessageTopic.ARCHITECTURE, new RequestArchitectureStateChangeMessage(SimulationAction.INIT))); }
### Question: TimeoutTimer { public static boolean isTimeExceeded(long startTime, double timeout) { return (startTime + timeout) < System.currentTimeMillis(); } TimeoutTimer(double timeout); static boolean isTimeExceeded(long startTime, double timeout); static boolean isTimeExceeded(LocalDateTime startTime, long timeout); static boolean isTimeExceeded(LocalDateTime startTime, double timeout); synchronized void reset(); synchronized boolean timeIsExceeded(); }### Answer: @Test public void isTimeExceeded() throws Exception { long testDelta = 1000; long oldTime = System.currentTimeMillis() - testDelta; Assert.assertTrue(TimeoutTimer.isTimeExceeded(oldTime, testDelta * 0.5)); Assert.assertFalse(TimeoutTimer.isTimeExceeded(oldTime, testDelta * 2)); } @Test public void isTimeExceeded1() throws Exception { long testDelta = 1000; LocalDateTime oldTime = LocalDateTime.now().minusSeconds(testDelta); Assert.assertTrue(TimeoutTimer.isTimeExceeded(oldTime, (long) (testDelta * 0.5))); Assert.assertFalse(TimeoutTimer.isTimeExceeded(oldTime, testDelta * 2)); Assert.assertTrue(TimeoutTimer.isTimeExceeded(oldTime, (testDelta * 0.5))); Assert.assertFalse(TimeoutTimer.isTimeExceeded(oldTime, testDelta * 2.0)); double testDeltaDouble = 0.005; oldTime = LocalDateTime.now().minusNanos((long) (testDeltaDouble * 1e9)); Assert.assertTrue(TimeoutTimer.isTimeExceeded(oldTime, (testDeltaDouble * 0.5))); Assert.assertFalse(TimeoutTimer.isTimeExceeded(oldTime, testDeltaDouble * 2.0)); }
### Question: D2Vector { public D2Vector add(D2Vector other) { return new D2Vector(this.getX() + other.getX(), this.getY() + other.getY()); } D2Vector(double x, double y); D2Vector(); double getX(); double getY(); D2Vector add(D2Vector other); D2Vector sub(D2Vector other); double length(); D2Vector scale(double scalar); @Override boolean equals(Object o); @Override int hashCode(); static final D2Vector UNIT; }### Answer: @Test public void add() throws Exception { Assert.assertEquals(new D2Vector(5, 7), vector1.add(vector2)); }
### Question: D2Vector { public D2Vector sub(D2Vector other) { return new D2Vector(this.getX() - other.getX(), this.getY() - other.getY()); } D2Vector(double x, double y); D2Vector(); double getX(); double getY(); D2Vector add(D2Vector other); D2Vector sub(D2Vector other); double length(); D2Vector scale(double scalar); @Override boolean equals(Object o); @Override int hashCode(); static final D2Vector UNIT; }### Answer: @Test public void sub() throws Exception { Assert.assertEquals(new D2Vector(1, 1), vector3.sub(vector2)); }
### Question: D2Vector { public double length() { return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); } D2Vector(double x, double y); D2Vector(); double getX(); double getY(); D2Vector add(D2Vector other); D2Vector sub(D2Vector other); double length(); D2Vector scale(double scalar); @Override boolean equals(Object o); @Override int hashCode(); static final D2Vector UNIT; }### Answer: @Test public void length() throws Exception { Assert.assertEquals(5, vector2.length(), 0.1); }
### Question: D2Vector { public D2Vector scale(double scalar) { return new D2Vector(this.getX() * scalar, this.getY() * scalar); } D2Vector(double x, double y); D2Vector(); double getX(); double getY(); D2Vector add(D2Vector other); D2Vector sub(D2Vector other); double length(); D2Vector scale(double scalar); @Override boolean equals(Object o); @Override int hashCode(); static final D2Vector UNIT; }### Answer: @Test public void scale() throws Exception { Assert.assertEquals(new D2Vector(4, 6), vector1.scale(2)); }
### Question: Settings { public static double getTickTime(ChronoUnit temporalUnit) { switch (temporalUnit) { case NANOS: return getTickTime(ChronoUnit.MICROS) * 1000d; case MICROS: return getTickTime(ChronoUnit.MILLIS) * 1000d; case MILLIS: return TICK_TIME; case SECONDS: return getTickTime(ChronoUnit.MILLIS) / 1000d; case MINUTES: return getTickTime(ChronoUnit.SECONDS) / 60d; case HOURS: return getTickTime(ChronoUnit.MINUTES) / 60d; default: throw new IllegalArgumentException(temporalUnit.name() + " is not (yet) supported"); } } private Settings(); static double getTickTime(ChronoUnit temporalUnit); static final String ETCD_HOST; static final String ETCD_PORT; static final double ARENA_HEIGHT; static final double ARENA_DEPTH; static final double ARENA_WIDTH; static final D3Vector ARENA; static final GameMode GAME_MODE; static final long TICK_TIME; static final double MAX_DRONE_ACCELERATION; static final double MAX_DRONE_VELOCITY; }### Answer: @Test public void getTickTime() throws Exception { Assert.assertEquals(Settings.TICK_TIME, Settings.getTickTime(ChronoUnit.MILLIS), 0.1); Assert.assertEquals(Settings.TICK_TIME / 1000, Settings.getTickTime(ChronoUnit.SECONDS), 0.1); Assert.assertEquals(Settings.TICK_TIME * 1000, Settings.getTickTime(ChronoUnit.MICROS), 0.1); }
### Question: Radar implements Subscriber { public List<D3Vector> getRadar() { List<D3Vector> results; if (position != null) { results = allEntities.values() .parallelStream() .filter(otherDrone -> position.distance_between(otherDrone) <= RADAR_RANGE) .collect(Collectors.toList()); } else { results = Collections.emptyList(); } return new ArrayList<>(results); } Radar(); Radar(ArchitectureEventController architectureEventController, DroneInit drone, Discoverer discoverer, D3Vector position); Radar(Radar copy); D3Vector getPosition(); void setPosition(D3Vector position); void start(); List<D3Vector> getRadar(); Optional<D3Vector> getNearestTarget(); @Override void receive(Object msg, MultipartCallbacks multipartCallbacks); @Override boolean equals(Object o); @Override int hashCode(); static final int RADAR_RANGE; }### Answer: @Test public void testGetRadar() throws Exception { Map<String, D3Vector> allEntities = new ConcurrentHashMap<>(); setField(radar, "allEntities", allEntities); allEntities.put("in-range", new D3Vector(100, 100, 100)); Assert.assertThat(radar.getRadar(), hasItems(allEntities.values().toArray(new D3Vector[allEntities.size()]))); allEntities.put("Out-of-range", new D3Vector(800, 800, 800)); Assert.assertThat(radar.getRadar(), not(hasItem(new D3Vector(800, 800, 800)))); setField(radar, "position", null); Assert.assertEquals(Collections.emptyList(), radar.getRadar()); }
### Question: Radar implements Subscriber { public Optional<D3Vector> getNearestTarget() { return getRadar() .parallelStream().min(Comparator.comparingDouble(e -> e.distance_between(position))); } Radar(); Radar(ArchitectureEventController architectureEventController, DroneInit drone, Discoverer discoverer, D3Vector position); Radar(Radar copy); D3Vector getPosition(); void setPosition(D3Vector position); void start(); List<D3Vector> getRadar(); Optional<D3Vector> getNearestTarget(); @Override void receive(Object msg, MultipartCallbacks multipartCallbacks); @Override boolean equals(Object o); @Override int hashCode(); static final int RADAR_RANGE; }### Answer: @Test public void testGetNearestTarget() throws Exception { Map<String, D3Vector> allEntities = new ConcurrentHashMap<>(); setField(radar, "allEntities", allEntities); allEntities.put("far", new D3Vector(100, 100, 100)); allEntities.put("near", new D3Vector(10, 10, 10)); allEntities.put("Out-of-range", new D3Vector(800, 800, 800)); Optional<D3Vector> target = radar.getNearestTarget(); if (target.isPresent()) { Assert.assertThat(target.get(), is(new D3Vector(10, 10, 10))); } else { Assert.fail("No nearest target found"); } }
### Question: Engine { public static D3Vector maximize_acceleration(D3Vector input) { D3Vector output = input; if (input.length() < Settings.MAX_DRONE_ACCELERATION && input.length() != 0) { double correctionFactor = Settings.MAX_DRONE_ACCELERATION / input.length(); output = input.scale(correctionFactor); } return output; } Engine(); Engine(Publisher m_publisher, GPS m_gps, DroneInit m_drone, D3Vector lastAcceleration); D3Vector getLastAcceleration(); static D3Vector limit_acceleration(D3Vector input); static D3Vector maximize_acceleration(D3Vector input); D3Vector stagnate_acceleration(D3Vector input); void changeAcceleration(D3Vector input_acceleration); D3Vector changeVelocity(D3Vector input); final void registerCallback(EngineCallback callback); }### Answer: @Test public void maximize_acceleration() throws Exception { Assert.assertEquals(new D3Vector(0, 0, 0), Engine.maximize_acceleration(new D3Vector(0, 0, 0))); Assert.assertEquals(new D3Vector(5.77350269189625764509148780501957, 5.77350269189625764509148780501957, 5.77350269189625764509148780501957), Engine.maximize_acceleration(new D3Vector(5, 5, 5))); Assert.assertEquals(new D3Vector(15, 15, 15), Engine.maximize_acceleration(new D3Vector(15, 15, 15))); }
### Question: Engine { public D3Vector stagnate_acceleration(D3Vector input) { D3Vector output = input; if (m_gps.getVelocity().length() >= (Settings.MAX_DRONE_VELOCITY * 0.9)) { double maxAcceleration = Settings.MAX_DRONE_VELOCITY - m_gps.getVelocity().length(); if (output.length() > Math.abs(maxAcceleration)) { output = output.scale(maxAcceleration / output.length() == 0 ? 1 : output.length()); } } return output; } Engine(); Engine(Publisher m_publisher, GPS m_gps, DroneInit m_drone, D3Vector lastAcceleration); D3Vector getLastAcceleration(); static D3Vector limit_acceleration(D3Vector input); static D3Vector maximize_acceleration(D3Vector input); D3Vector stagnate_acceleration(D3Vector input); void changeAcceleration(D3Vector input_acceleration); D3Vector changeVelocity(D3Vector input); final void registerCallback(EngineCallback callback); }### Answer: @Test @Ignore public void stagnate_acceleration() throws Exception { Assert.assertEquals("We should keep the same acceleration if we do not accelerate", new D3Vector(0, 0, 0), engine.stagnate_acceleration(new D3Vector(0, 0, 0))); Assert.assertEquals("When we exceed the 90% mark of velocity, then we should limit the accelaration to 75% of the original acceleration.", current_acceleration.scale(0.25), engine.stagnate_acceleration(new D3Vector(1, 1, 1))); }
### Question: Radio implements Subscriber { public boolean send(Object msg) { publisher.send(new RadioMessage(teamName, msg)); return true; } Radio(); Radio(Publisher publisher, DroneInit drone, String teamName); void start(); boolean send(Object msg); final Queue<Object> getMessages(); @Override void receive(Object o, MultipartCallbacks multipartCallbacks); final M getMessage(Class<M> messageClass); }### Answer: @Test public void send() throws Exception { TextMessage msg = new TextMessage("This is a test message"); String another = "another test object"; Assert.assertTrue(radio.send(another)); Assert.assertTrue(radio.send(msg)); Assert.assertEquals(msg, radio.getMessage(TextMessage.class)); Assert.assertEquals(another, radio.getMessage(String.class)); Assert.assertTrue(publisher.getReceivedMessages().get(0) instanceof RadioMessage); }
### Question: SimpleLogger implements Log { public void info(Object message) { out.println(message); } void debug(Object message); void debug(Object message, Throwable th); void error(Object message); void error(Object message, Throwable th); void fatal(Object message); void fatal(Object message, Throwable th); void info(Object message); void info(Object message, Throwable th); boolean isDebugEnabled(); boolean isErrorEnabled(); boolean isFatalEnabled(); boolean isInfoEnabled(); boolean isTraceEnabled(); boolean isWarnEnabled(); void trace(Object message); void trace(Object message, Throwable th); void warn(Object message); void warn(Object message, Throwable th); }### Answer: @Test public void testInfoObjectThrowable() { testee.info(object, throwable); assertMessageSendViaSystemOut(); assertMessageNotSendViaSystemErr(); assertThrowablePrintedToSystemOut(); } @Test public void testTraceObjectThrowable() { testee.info(object, throwable); assertMessageSendViaSystemOut(); assertThrowablePrintedToSystemOut(); assertMessageNotSendViaSystemErr(); } @Test public void testInfoObject() { testee.info(object); assertMessageSendViaSystemOut(); assertMessageNotSendViaSystemErr(); }
### Question: SimpleLogger implements Log { public boolean isDebugEnabled() { return true; } void debug(Object message); void debug(Object message, Throwable th); void error(Object message); void error(Object message, Throwable th); void fatal(Object message); void fatal(Object message, Throwable th); void info(Object message); void info(Object message, Throwable th); boolean isDebugEnabled(); boolean isErrorEnabled(); boolean isFatalEnabled(); boolean isInfoEnabled(); boolean isTraceEnabled(); boolean isWarnEnabled(); void trace(Object message); void trace(Object message, Throwable th); void warn(Object message); void warn(Object message, Throwable th); }### Answer: @Test public void testIsDebugEnabled() { assertThat(testee.isDebugEnabled()).isTrue(); }
### Question: SimpleLogger implements Log { public boolean isErrorEnabled() { return true; } void debug(Object message); void debug(Object message, Throwable th); void error(Object message); void error(Object message, Throwable th); void fatal(Object message); void fatal(Object message, Throwable th); void info(Object message); void info(Object message, Throwable th); boolean isDebugEnabled(); boolean isErrorEnabled(); boolean isFatalEnabled(); boolean isInfoEnabled(); boolean isTraceEnabled(); boolean isWarnEnabled(); void trace(Object message); void trace(Object message, Throwable th); void warn(Object message); void warn(Object message, Throwable th); }### Answer: @Test public void testIsErrorEnabled() { assertThat(testee.isErrorEnabled()).isTrue(); }
### Question: SimpleLogger implements Log { public boolean isFatalEnabled() { return true; } void debug(Object message); void debug(Object message, Throwable th); void error(Object message); void error(Object message, Throwable th); void fatal(Object message); void fatal(Object message, Throwable th); void info(Object message); void info(Object message, Throwable th); boolean isDebugEnabled(); boolean isErrorEnabled(); boolean isFatalEnabled(); boolean isInfoEnabled(); boolean isTraceEnabled(); boolean isWarnEnabled(); void trace(Object message); void trace(Object message, Throwable th); void warn(Object message); void warn(Object message, Throwable th); }### Answer: @Test public void testIsFatalEnabled() { assertThat(testee.isFatalEnabled()).isTrue(); }
### Question: SimpleLogger implements Log { public boolean isInfoEnabled() { return true; } void debug(Object message); void debug(Object message, Throwable th); void error(Object message); void error(Object message, Throwable th); void fatal(Object message); void fatal(Object message, Throwable th); void info(Object message); void info(Object message, Throwable th); boolean isDebugEnabled(); boolean isErrorEnabled(); boolean isFatalEnabled(); boolean isInfoEnabled(); boolean isTraceEnabled(); boolean isWarnEnabled(); void trace(Object message); void trace(Object message, Throwable th); void warn(Object message); void warn(Object message, Throwable th); }### Answer: @Test public void testIsInfoEnabled() { assertThat(testee.isInfoEnabled()).isTrue(); }
### Question: SimpleLogger implements Log { public boolean isTraceEnabled() { return true; } void debug(Object message); void debug(Object message, Throwable th); void error(Object message); void error(Object message, Throwable th); void fatal(Object message); void fatal(Object message, Throwable th); void info(Object message); void info(Object message, Throwable th); boolean isDebugEnabled(); boolean isErrorEnabled(); boolean isFatalEnabled(); boolean isInfoEnabled(); boolean isTraceEnabled(); boolean isWarnEnabled(); void trace(Object message); void trace(Object message, Throwable th); void warn(Object message); void warn(Object message, Throwable th); }### Answer: @Test public void testIsTraceEnabled() { assertThat(testee.isTraceEnabled()).isTrue(); }
### Question: SimpleLogger implements Log { public boolean isWarnEnabled() { return true; } void debug(Object message); void debug(Object message, Throwable th); void error(Object message); void error(Object message, Throwable th); void fatal(Object message); void fatal(Object message, Throwable th); void info(Object message); void info(Object message, Throwable th); boolean isDebugEnabled(); boolean isErrorEnabled(); boolean isFatalEnabled(); boolean isInfoEnabled(); boolean isTraceEnabled(); boolean isWarnEnabled(); void trace(Object message); void trace(Object message, Throwable th); void warn(Object message); void warn(Object message, Throwable th); }### Answer: @Test public void testIsWarnEnabled() { assertThat(testee.isWarnEnabled()).isTrue(); }
### Question: SimpleLogger implements Log { public void trace(Object message) { out.println(message); } void debug(Object message); void debug(Object message, Throwable th); void error(Object message); void error(Object message, Throwable th); void fatal(Object message); void fatal(Object message, Throwable th); void info(Object message); void info(Object message, Throwable th); boolean isDebugEnabled(); boolean isErrorEnabled(); boolean isFatalEnabled(); boolean isInfoEnabled(); boolean isTraceEnabled(); boolean isWarnEnabled(); void trace(Object message); void trace(Object message, Throwable th); void warn(Object message); void warn(Object message, Throwable th); }### Answer: @Test public void testTraceObject() { testee.trace(object); assertMessageSendViaSystemOut(); assertMessageNotSendViaSystemErr(); }
### Question: SimpleLogger implements Log { public void warn(Object message) { out.println(message); } void debug(Object message); void debug(Object message, Throwable th); void error(Object message); void error(Object message, Throwable th); void fatal(Object message); void fatal(Object message, Throwable th); void info(Object message); void info(Object message, Throwable th); boolean isDebugEnabled(); boolean isErrorEnabled(); boolean isFatalEnabled(); boolean isInfoEnabled(); boolean isTraceEnabled(); boolean isWarnEnabled(); void trace(Object message); void trace(Object message, Throwable th); void warn(Object message); void warn(Object message, Throwable th); }### Answer: @Test public void testWarnObject() { testee.warn(object); assertMessageSendViaSystemOut(); assertMessageNotSendViaSystemErr(); } @Test public void testWarnObjectThrowable() { testee.warn(object, throwable); assertMessageSendViaSystemOut(); assertThrowablePrintedToSystemOut(); assertMessageNotSendViaSystemErr(); }
### Question: TypeFactory { static ReifiedType getType(TypeDescriptor targetType) { return new GenericsReifiedType(targetType); } }### Answer: @Test public void testRecursiveGenericType() throws Exception { assertNotNull(TypeFactory.getType(TypeDescriptor.valueOf(RecursiveGenericType.class))); } @Test public void testSingleAndRecursiveGenericType() throws Exception { assertNotNull(TypeFactory.getType(TypeDescriptor.valueOf(SingleAndRecursiveGenericType.class))); } @Test public void testMultipleRecursiveGenericType() throws Exception { assertNotNull(TypeFactory.getType(TypeDescriptor.valueOf(MultipleRecursiveGenericType.class))); } @Test public void testMutuallyRecursiveGenericType() throws Exception { assertNotNull(TypeFactory.getType(TypeDescriptor.valueOf(MutuallyRecursiveGenericType.class))); } @Test public void testComplexRecursiveGenericType() throws Exception { assertNotNull(TypeFactory.getType(TypeDescriptor.valueOf(ComplexRecursiveGenericType.class))); } @Test public void testMultiBoundedRecursiveGenericType() throws Exception { assertNotNull(TypeFactory.getType(TypeDescriptor.valueOf(MultiBoundedRecursiveGenericType.class))); } @Test public void testMultiBoundedGenericType() throws Exception { ReifiedType reifiedA = TypeFactory.getType(TypeDescriptor.valueOf(A.class)); assertNotNull(reifiedA); ReifiedType reifiedB = TypeFactory.getType(TypeDescriptor.valueOf(B.class)); assertNotNull(reifiedB); } @Test public void testMutuallyRecursiveThroughSecondBoundGenericType() throws Exception { assertNotNull(TypeFactory.getType(TypeDescriptor.valueOf(MutuallyRecursiveThroughSecondBoundGenericType.class))); }
### Question: SimpleLogger implements Log { public void debug(Object message) { out.println(message); } void debug(Object message); void debug(Object message, Throwable th); void error(Object message); void error(Object message, Throwable th); void fatal(Object message); void fatal(Object message, Throwable th); void info(Object message); void info(Object message, Throwable th); boolean isDebugEnabled(); boolean isErrorEnabled(); boolean isFatalEnabled(); boolean isInfoEnabled(); boolean isTraceEnabled(); boolean isWarnEnabled(); void trace(Object message); void trace(Object message, Throwable th); void warn(Object message); void warn(Object message, Throwable th); }### Answer: @Test public void testDebugObject() { testee.debug(object); assertMessageSendViaSystemOut(); assertMessageNotSendViaSystemErr(); } @Test public void testDebugObjectThrowable() { testee.debug(object, throwable); assertMessageSendViaSystemOut(); assertMessageNotSendViaSystemErr(); }
### Question: SimpleLogger implements Log { public void error(Object message) { err.println(message); } void debug(Object message); void debug(Object message, Throwable th); void error(Object message); void error(Object message, Throwable th); void fatal(Object message); void fatal(Object message, Throwable th); void info(Object message); void info(Object message, Throwable th); boolean isDebugEnabled(); boolean isErrorEnabled(); boolean isFatalEnabled(); boolean isInfoEnabled(); boolean isTraceEnabled(); boolean isWarnEnabled(); void trace(Object message); void trace(Object message, Throwable th); void warn(Object message); void warn(Object message, Throwable th); }### Answer: @Test public void testErrorObject() { testee.error(object); assertMessageNotSendViaSystemOut(); assertMessageSendViaSystemErr(); } @Test public void testErrorObjectThrowable() { testee.error(object, throwable); assertMessageSendViaSystemErr(); assertThrowablePrintedToSystemErr(); assertMessageNotSendViaSystemOut(); }
### Question: SimpleLogger implements Log { public void fatal(Object message) { err.println(message); } void debug(Object message); void debug(Object message, Throwable th); void error(Object message); void error(Object message, Throwable th); void fatal(Object message); void fatal(Object message, Throwable th); void info(Object message); void info(Object message, Throwable th); boolean isDebugEnabled(); boolean isErrorEnabled(); boolean isFatalEnabled(); boolean isInfoEnabled(); boolean isTraceEnabled(); boolean isWarnEnabled(); void trace(Object message); void trace(Object message, Throwable th); void warn(Object message); void warn(Object message, Throwable th); }### Answer: @Test public void testFatalObject() { testee.fatal(object); assertMessageSendViaSystemErr(); assertMessageNotSendViaSystemOut(); } @Test public void testFatalObjectThrowable() { testee.fatal(object, throwable); assertMessageSendViaSystemErr(); assertThrowablePrintedToSystemErr(); assertMessageNotSendViaSystemOut(); }
### Question: FileIngestorRouteBuilder extends RouteBuilder { protected String getEnqueueRecordsDestinationUri() { return "activemq:queue:" + recordsQueueName; } @Override void configure(); String getSourceDirPath(); void setSourceDirPath(String sourceDirPath); String getDoneDirPath(); void setDoneDirPath(String doneDirPath); String getFailDirPath(); void setFailDirPath(String failDirPath); String getRecordsQueueName(); void setRecordsQueueName(String recordsQueueName); }### Answer: @Test @DirtiesContext public void testJmsFailure() throws Exception { RouteDefinition routeDef = context.getRouteDefinition( FileIngestorRouteBuilder.ENQUEUE_RECORD_ROUTE_ID); routeDef.adviceWith(context, new RouteBuilder() { @Override public void configure() throws Exception { interceptSendToEndpoint(builder.getEnqueueRecordsDestinationUri()) .choice() .when().xpath("/example:record/example:id[text() = '1']", FileIngestorRouteBuilder.NAMESPACES) .throwException(new JMSException("Simulated JMS Error!")) .end(); } }); context.start(); DatatypeFactory dtf = DatatypeFactory.newInstance(); Set<String> expectedIds = new HashSet<String>(); AggregateRecordType agt = new AggregateRecordType(); agt.setDate(dtf.newXMLGregorianCalendar(new GregorianCalendar())); output.setExpectedMessageCount(9); for (int i = 0; i < 10; i++) { RecordType record = new RecordType(); record.setId(String.valueOf(i)); record.setDate(dtf.newXMLGregorianCalendar(new GregorianCalendar())); record.setDescription("Record number: " + i); agt.getRecord().add(record); if (i != 1) { expectedIds.add(String.valueOf(i)); } } createAndMoveFile(agt); output.assertIsSatisfied(); validateFileMove(true); for (Exchange exchange : output.getReceivedExchanges()) { assertTrue(expectedIds.remove(exchange.getIn().getBody(RecordType.class).getId())); } assertTrue(expectedIds.isEmpty()); }
### Question: DataManager { public Single<Token> login(String username, String password) { return mService.getToken(BuildConfig.CLIENT_ID, BuildConfig.CLIENT_SECRET, GRANT_TYPE_PASSWORD, username, password) .doOnSuccess(mPreferencesHelper::setToken) .compose(applySingleSchedulers()); } DataManager(@NonNull OkHttpClient client, @NonNull PreferencesHelper preferencesHelper); String buildAuthorization(); Single<Token> login(String username, String password); Single<List<Topic>> getTopics(int offset); Single<TopicDetail> createTopic(int nodeId, String title, String body); Single<List<News>> getAllNewses(Integer offset); Single<List<News>> getNewses(String nodeId, Integer offset); Single<List<NewsReply>> getNewsReplies(int newsId, int offset); Single<List<Topic>> getUserTopics(String userLogin, int offset); Single<List<Topic>> getUserFavorites(String userLogin, int offset); Single<List<UserReply>> getUserReplies(String userLogin, int offset); Single<UserDetail> getMe(); Single<UserDetail> getMe(boolean forced); Single<NotificationUnread> getNotificationsUnreadCount(); Single<List<Notification>> getNotifications(int offset); Single<TopicAndReplies> getTopicAndComments(int topicId); Single<TopicDetail> getTopicDetail(int id); Single<List<TopicReply>> getTopicReplies(int topicId, int offset); Single<TopicReply> publishComment(int id, String body); Single<ImageResult> uploadPhoto(String filePath); Single<Map<TopicNodeCategory, List<TopicNode>>> getTopicNodes(); Single<List<Project>> getProjects(int offset); Single<List<SiteListItem>> getSites(); Single<UserDetail> getUserDetail(String userLogin); static final int PAGE_LIMIT; static final String DATE_FORMAT; }### Answer: @Test public void login() throws Exception { TestObserver<Token> testObserver = mDataManager.login("abcd", "2222").test().await(); testObserver.assertError(HttpException.class); testObserver.assertNotComplete(); }
### Question: DataManager { public Single<NotificationUnread> getNotificationsUnreadCount() { return mService.getNotificationsUnreadCount(buildAuthorization()) .compose(applySingleSchedulers()); } DataManager(@NonNull OkHttpClient client, @NonNull PreferencesHelper preferencesHelper); String buildAuthorization(); Single<Token> login(String username, String password); Single<List<Topic>> getTopics(int offset); Single<TopicDetail> createTopic(int nodeId, String title, String body); Single<List<News>> getAllNewses(Integer offset); Single<List<News>> getNewses(String nodeId, Integer offset); Single<List<NewsReply>> getNewsReplies(int newsId, int offset); Single<List<Topic>> getUserTopics(String userLogin, int offset); Single<List<Topic>> getUserFavorites(String userLogin, int offset); Single<List<UserReply>> getUserReplies(String userLogin, int offset); Single<UserDetail> getMe(); Single<UserDetail> getMe(boolean forced); Single<NotificationUnread> getNotificationsUnreadCount(); Single<List<Notification>> getNotifications(int offset); Single<TopicAndReplies> getTopicAndComments(int topicId); Single<TopicDetail> getTopicDetail(int id); Single<List<TopicReply>> getTopicReplies(int topicId, int offset); Single<TopicReply> publishComment(int id, String body); Single<ImageResult> uploadPhoto(String filePath); Single<Map<TopicNodeCategory, List<TopicNode>>> getTopicNodes(); Single<List<Project>> getProjects(int offset); Single<List<SiteListItem>> getSites(); Single<UserDetail> getUserDetail(String userLogin); static final int PAGE_LIMIT; static final String DATE_FORMAT; }### Answer: @Test public void getNotificationsUnreadCount() throws Exception { TestObserver<NotificationUnread> testObserver = mDataManager.getNotificationsUnreadCount() .test().await(); testObserver.assertError(HttpException.class); testObserver.assertNotComplete(); }
### Question: DataManager { public Single<List<Notification>> getNotifications(int offset) { return mService.getNotifications(buildAuthorization(), offset, PAGE_LIMIT) .compose(applySingleSchedulers()); } DataManager(@NonNull OkHttpClient client, @NonNull PreferencesHelper preferencesHelper); String buildAuthorization(); Single<Token> login(String username, String password); Single<List<Topic>> getTopics(int offset); Single<TopicDetail> createTopic(int nodeId, String title, String body); Single<List<News>> getAllNewses(Integer offset); Single<List<News>> getNewses(String nodeId, Integer offset); Single<List<NewsReply>> getNewsReplies(int newsId, int offset); Single<List<Topic>> getUserTopics(String userLogin, int offset); Single<List<Topic>> getUserFavorites(String userLogin, int offset); Single<List<UserReply>> getUserReplies(String userLogin, int offset); Single<UserDetail> getMe(); Single<UserDetail> getMe(boolean forced); Single<NotificationUnread> getNotificationsUnreadCount(); Single<List<Notification>> getNotifications(int offset); Single<TopicAndReplies> getTopicAndComments(int topicId); Single<TopicDetail> getTopicDetail(int id); Single<List<TopicReply>> getTopicReplies(int topicId, int offset); Single<TopicReply> publishComment(int id, String body); Single<ImageResult> uploadPhoto(String filePath); Single<Map<TopicNodeCategory, List<TopicNode>>> getTopicNodes(); Single<List<Project>> getProjects(int offset); Single<List<SiteListItem>> getSites(); Single<UserDetail> getUserDetail(String userLogin); static final int PAGE_LIMIT; static final String DATE_FORMAT; }### Answer: @Test public void getNotifications() throws Exception { TestObserver<List<Notification>> testObserver = mDataManager.getNotifications(0) .test().await(); testObserver.assertError(HttpException.class); testObserver.assertNotComplete(); }
### Question: DataManager { public Single<TopicDetail> getTopicDetail(int id) { return mService.getTopicDetail(buildAuthorization(), id).compose(applySingleSchedulers()); } DataManager(@NonNull OkHttpClient client, @NonNull PreferencesHelper preferencesHelper); String buildAuthorization(); Single<Token> login(String username, String password); Single<List<Topic>> getTopics(int offset); Single<TopicDetail> createTopic(int nodeId, String title, String body); Single<List<News>> getAllNewses(Integer offset); Single<List<News>> getNewses(String nodeId, Integer offset); Single<List<NewsReply>> getNewsReplies(int newsId, int offset); Single<List<Topic>> getUserTopics(String userLogin, int offset); Single<List<Topic>> getUserFavorites(String userLogin, int offset); Single<List<UserReply>> getUserReplies(String userLogin, int offset); Single<UserDetail> getMe(); Single<UserDetail> getMe(boolean forced); Single<NotificationUnread> getNotificationsUnreadCount(); Single<List<Notification>> getNotifications(int offset); Single<TopicAndReplies> getTopicAndComments(int topicId); Single<TopicDetail> getTopicDetail(int id); Single<List<TopicReply>> getTopicReplies(int topicId, int offset); Single<TopicReply> publishComment(int id, String body); Single<ImageResult> uploadPhoto(String filePath); Single<Map<TopicNodeCategory, List<TopicNode>>> getTopicNodes(); Single<List<Project>> getProjects(int offset); Single<List<SiteListItem>> getSites(); Single<UserDetail> getUserDetail(String userLogin); static final int PAGE_LIMIT; static final String DATE_FORMAT; }### Answer: @Test public void getTopicDetail() throws Exception { TestObserver<TopicDetail> testObserver = mDataManager.getTopicDetail(4).test().await(); testObserver.assertNoErrors(); testObserver.assertComplete(); }
### Question: DataManager { public Single<List<TopicReply>> getTopicReplies(int topicId, int offset) { return mService.getTopicReplies(buildAuthorization(), topicId, offset, PAGE_LIMIT) .compose(applySingleSchedulers()); } DataManager(@NonNull OkHttpClient client, @NonNull PreferencesHelper preferencesHelper); String buildAuthorization(); Single<Token> login(String username, String password); Single<List<Topic>> getTopics(int offset); Single<TopicDetail> createTopic(int nodeId, String title, String body); Single<List<News>> getAllNewses(Integer offset); Single<List<News>> getNewses(String nodeId, Integer offset); Single<List<NewsReply>> getNewsReplies(int newsId, int offset); Single<List<Topic>> getUserTopics(String userLogin, int offset); Single<List<Topic>> getUserFavorites(String userLogin, int offset); Single<List<UserReply>> getUserReplies(String userLogin, int offset); Single<UserDetail> getMe(); Single<UserDetail> getMe(boolean forced); Single<NotificationUnread> getNotificationsUnreadCount(); Single<List<Notification>> getNotifications(int offset); Single<TopicAndReplies> getTopicAndComments(int topicId); Single<TopicDetail> getTopicDetail(int id); Single<List<TopicReply>> getTopicReplies(int topicId, int offset); Single<TopicReply> publishComment(int id, String body); Single<ImageResult> uploadPhoto(String filePath); Single<Map<TopicNodeCategory, List<TopicNode>>> getTopicNodes(); Single<List<Project>> getProjects(int offset); Single<List<SiteListItem>> getSites(); Single<UserDetail> getUserDetail(String userLogin); static final int PAGE_LIMIT; static final String DATE_FORMAT; }### Answer: @Test public void getTopicReplies() throws Exception { TestObserver<List<TopicReply>> testObserver = mDataManager.getTopicReplies(4, 0).test() .await(); testObserver.assertNoErrors(); testObserver.assertComplete(); }
### Question: DataManager { public Single<TopicReply> publishComment(int id, String body) { return mService.publishComment(buildAuthorization(), id, body) .compose(applySingleSchedulers()); } DataManager(@NonNull OkHttpClient client, @NonNull PreferencesHelper preferencesHelper); String buildAuthorization(); Single<Token> login(String username, String password); Single<List<Topic>> getTopics(int offset); Single<TopicDetail> createTopic(int nodeId, String title, String body); Single<List<News>> getAllNewses(Integer offset); Single<List<News>> getNewses(String nodeId, Integer offset); Single<List<NewsReply>> getNewsReplies(int newsId, int offset); Single<List<Topic>> getUserTopics(String userLogin, int offset); Single<List<Topic>> getUserFavorites(String userLogin, int offset); Single<List<UserReply>> getUserReplies(String userLogin, int offset); Single<UserDetail> getMe(); Single<UserDetail> getMe(boolean forced); Single<NotificationUnread> getNotificationsUnreadCount(); Single<List<Notification>> getNotifications(int offset); Single<TopicAndReplies> getTopicAndComments(int topicId); Single<TopicDetail> getTopicDetail(int id); Single<List<TopicReply>> getTopicReplies(int topicId, int offset); Single<TopicReply> publishComment(int id, String body); Single<ImageResult> uploadPhoto(String filePath); Single<Map<TopicNodeCategory, List<TopicNode>>> getTopicNodes(); Single<List<Project>> getProjects(int offset); Single<List<SiteListItem>> getSites(); Single<UserDetail> getUserDetail(String userLogin); static final int PAGE_LIMIT; static final String DATE_FORMAT; }### Answer: @Test public void sendReply() throws Exception { TestObserver<TopicReply> testObserver = mDataManager.publishComment(4, "body").test() .await(); testObserver.assertError(HttpException.class); testObserver.assertNotComplete(); }
### Question: DataManager { public Single<Map<TopicNodeCategory, List<TopicNode>>> getTopicNodes() { return mService.getTopicNodes() .compose(applySingleSchedulers()) .map(this::getTopicNodeCategoryListMap); } DataManager(@NonNull OkHttpClient client, @NonNull PreferencesHelper preferencesHelper); String buildAuthorization(); Single<Token> login(String username, String password); Single<List<Topic>> getTopics(int offset); Single<TopicDetail> createTopic(int nodeId, String title, String body); Single<List<News>> getAllNewses(Integer offset); Single<List<News>> getNewses(String nodeId, Integer offset); Single<List<NewsReply>> getNewsReplies(int newsId, int offset); Single<List<Topic>> getUserTopics(String userLogin, int offset); Single<List<Topic>> getUserFavorites(String userLogin, int offset); Single<List<UserReply>> getUserReplies(String userLogin, int offset); Single<UserDetail> getMe(); Single<UserDetail> getMe(boolean forced); Single<NotificationUnread> getNotificationsUnreadCount(); Single<List<Notification>> getNotifications(int offset); Single<TopicAndReplies> getTopicAndComments(int topicId); Single<TopicDetail> getTopicDetail(int id); Single<List<TopicReply>> getTopicReplies(int topicId, int offset); Single<TopicReply> publishComment(int id, String body); Single<ImageResult> uploadPhoto(String filePath); Single<Map<TopicNodeCategory, List<TopicNode>>> getTopicNodes(); Single<List<Project>> getProjects(int offset); Single<List<SiteListItem>> getSites(); Single<UserDetail> getUserDetail(String userLogin); static final int PAGE_LIMIT; static final String DATE_FORMAT; }### Answer: @Test public void getTopicNodes() throws Exception { TestObserver<Map<TopicNodeCategory, List<TopicNode>>> testObserver = mDataManager .getTopicNodes().test().await(); testObserver.assertNoErrors(); testObserver.assertComplete(); }
### Question: DataManager { public Single<List<Project>> getProjects(int offset) { return mService.getProjects(null, offset, PAGE_LIMIT).compose(applySingleSchedulers()); } DataManager(@NonNull OkHttpClient client, @NonNull PreferencesHelper preferencesHelper); String buildAuthorization(); Single<Token> login(String username, String password); Single<List<Topic>> getTopics(int offset); Single<TopicDetail> createTopic(int nodeId, String title, String body); Single<List<News>> getAllNewses(Integer offset); Single<List<News>> getNewses(String nodeId, Integer offset); Single<List<NewsReply>> getNewsReplies(int newsId, int offset); Single<List<Topic>> getUserTopics(String userLogin, int offset); Single<List<Topic>> getUserFavorites(String userLogin, int offset); Single<List<UserReply>> getUserReplies(String userLogin, int offset); Single<UserDetail> getMe(); Single<UserDetail> getMe(boolean forced); Single<NotificationUnread> getNotificationsUnreadCount(); Single<List<Notification>> getNotifications(int offset); Single<TopicAndReplies> getTopicAndComments(int topicId); Single<TopicDetail> getTopicDetail(int id); Single<List<TopicReply>> getTopicReplies(int topicId, int offset); Single<TopicReply> publishComment(int id, String body); Single<ImageResult> uploadPhoto(String filePath); Single<Map<TopicNodeCategory, List<TopicNode>>> getTopicNodes(); Single<List<Project>> getProjects(int offset); Single<List<SiteListItem>> getSites(); Single<UserDetail> getUserDetail(String userLogin); static final int PAGE_LIMIT; static final String DATE_FORMAT; }### Answer: @Test public void getProjects() throws Exception { TestObserver<List<Project>> testObserver = mDataManager.getProjects(0).test().await(); testObserver.assertNoErrors(); testObserver.assertComplete(); }
### Question: DataManager { public Single<List<SiteListItem>> getSites() { return mService.getSites().compose(applySingleSchedulers()).map(this::getSiteListItems); } DataManager(@NonNull OkHttpClient client, @NonNull PreferencesHelper preferencesHelper); String buildAuthorization(); Single<Token> login(String username, String password); Single<List<Topic>> getTopics(int offset); Single<TopicDetail> createTopic(int nodeId, String title, String body); Single<List<News>> getAllNewses(Integer offset); Single<List<News>> getNewses(String nodeId, Integer offset); Single<List<NewsReply>> getNewsReplies(int newsId, int offset); Single<List<Topic>> getUserTopics(String userLogin, int offset); Single<List<Topic>> getUserFavorites(String userLogin, int offset); Single<List<UserReply>> getUserReplies(String userLogin, int offset); Single<UserDetail> getMe(); Single<UserDetail> getMe(boolean forced); Single<NotificationUnread> getNotificationsUnreadCount(); Single<List<Notification>> getNotifications(int offset); Single<TopicAndReplies> getTopicAndComments(int topicId); Single<TopicDetail> getTopicDetail(int id); Single<List<TopicReply>> getTopicReplies(int topicId, int offset); Single<TopicReply> publishComment(int id, String body); Single<ImageResult> uploadPhoto(String filePath); Single<Map<TopicNodeCategory, List<TopicNode>>> getTopicNodes(); Single<List<Project>> getProjects(int offset); Single<List<SiteListItem>> getSites(); Single<UserDetail> getUserDetail(String userLogin); static final int PAGE_LIMIT; static final String DATE_FORMAT; }### Answer: @Test public void getSites() throws Exception { TestObserver<List<SiteListItem>> testObserver = mDataManager.getSites().test().await(); testObserver.assertNoErrors(); testObserver.assertComplete(); }
### Question: SitePresenter extends BasePresenter<ISiteView> { public void loadSite() { addDisposable(mDataManager.getSites().doOnSubscribe(disposable -> getView().showLoading()) .subscribe(this::handleNext, this::handleError)); } @Inject SitePresenter(DataManager dataManager); void loadSite(); }### Answer: @Test public void testLoadSiteSuccessful() throws Exception { List<SiteListItem> sites = mock(ArrayList.class); when(mDataManager.getSites()).thenReturn(Single.just(sites)); mSitePresenter.loadSite(); verify(mSiteView).showLoading(); verify(mSiteView).showSites(sites); } @Test public void testLoadSiteFailed() throws Exception { when(mDataManager.getSites()).thenReturn(Single.error(mock(HttpException.class))); mSitePresenter.loadSite(); verify(mSiteView).showLoading(); verify(mSiteView).showLoadSiteError(); }
### Question: DataManager { public Single<List<Topic>> getTopics(int offset) { return mService.getTopics(buildAuthorization(), null, null, offset, PAGE_LIMIT) .compose(applySingleSchedulers()); } DataManager(@NonNull OkHttpClient client, @NonNull PreferencesHelper preferencesHelper); String buildAuthorization(); Single<Token> login(String username, String password); Single<List<Topic>> getTopics(int offset); Single<TopicDetail> createTopic(int nodeId, String title, String body); Single<List<News>> getAllNewses(Integer offset); Single<List<News>> getNewses(String nodeId, Integer offset); Single<List<NewsReply>> getNewsReplies(int newsId, int offset); Single<List<Topic>> getUserTopics(String userLogin, int offset); Single<List<Topic>> getUserFavorites(String userLogin, int offset); Single<List<UserReply>> getUserReplies(String userLogin, int offset); Single<UserDetail> getMe(); Single<UserDetail> getMe(boolean forced); Single<NotificationUnread> getNotificationsUnreadCount(); Single<List<Notification>> getNotifications(int offset); Single<TopicAndReplies> getTopicAndComments(int topicId); Single<TopicDetail> getTopicDetail(int id); Single<List<TopicReply>> getTopicReplies(int topicId, int offset); Single<TopicReply> publishComment(int id, String body); Single<ImageResult> uploadPhoto(String filePath); Single<Map<TopicNodeCategory, List<TopicNode>>> getTopicNodes(); Single<List<Project>> getProjects(int offset); Single<List<SiteListItem>> getSites(); Single<UserDetail> getUserDetail(String userLogin); static final int PAGE_LIMIT; static final String DATE_FORMAT; }### Answer: @Test public void getTopics() throws Exception { TestObserver<List<Topic>> testObserver = mDataManager.getTopics(0).test().await(); testObserver.assertNoErrors(); testObserver.assertComplete(); }
### Question: LoginPresenter extends BasePresenter<ILoginView> { public void login(String username, String password) { final ILoginView view = getView(); view.showLoginDialog(); Disposable disposable = mDataManager.login(username, password) .subscribe(this::handleLoginSuccess, this::handleLoginError); addDisposable(disposable); } @Inject LoginPresenter(DataManager dataManager, PreferencesHelper preferencesHelper); @Override void onAttach(ILoginView view); void login(String username, String password); }### Answer: @Test public void testLoginSuccessful() throws Exception { Token token = mock(Token.class); String username = "xshengcn"; String password = "password"; when(mDataManager.login(username, password)).thenReturn(Single.just(token)); mPresenter.login(username, password); verify(mLoginView).showLoginDialog(); verify(mLoginView).hideLoginDialog(); verify(mLoginView).loginSuccess(); } @Test public void testLoginFailed() throws Exception { String username = "xshengcn"; String password = "password"; when(mDataManager.login(username, password)) .thenReturn(Single.error(mock(HttpException.class))); mPresenter.login(username, password); verify(mLoginView).showLoginDialog(); verify(mLoginView).hideLoginDialog(); verify(mLoginView).loginError(); }
### Question: TopicCreatorPresenter extends BasePresenter<ITopicCreatorView> { public void loadTopicNodes() { final ITopicCreatorView view = getView(); Disposable disposable = mDataManager.getTopicNodes() .subscribe(view::showNodes, throwable -> { }); addDisposable(disposable); } @Inject TopicCreatorPresenter(DataManager dataManager); void loadTopicNodes(); void createTopic(); }### Answer: @Test public void testLoadTopicNodesSuccess() throws Exception { Map<TopicNodeCategory, List<TopicNode>> nodesMap = mock(Map.class); when(mDataManager.getTopicNodes()).thenReturn(Single.just(nodesMap)); mPresenter.loadTopicNodes(); verify(mView).showNodes(nodesMap); }
### Question: DataManager { public Single<TopicDetail> createTopic(int nodeId, String title, String body) { return mService.createTopic(buildAuthorization(), nodeId, title, body) .compose(applySingleSchedulers()); } DataManager(@NonNull OkHttpClient client, @NonNull PreferencesHelper preferencesHelper); String buildAuthorization(); Single<Token> login(String username, String password); Single<List<Topic>> getTopics(int offset); Single<TopicDetail> createTopic(int nodeId, String title, String body); Single<List<News>> getAllNewses(Integer offset); Single<List<News>> getNewses(String nodeId, Integer offset); Single<List<NewsReply>> getNewsReplies(int newsId, int offset); Single<List<Topic>> getUserTopics(String userLogin, int offset); Single<List<Topic>> getUserFavorites(String userLogin, int offset); Single<List<UserReply>> getUserReplies(String userLogin, int offset); Single<UserDetail> getMe(); Single<UserDetail> getMe(boolean forced); Single<NotificationUnread> getNotificationsUnreadCount(); Single<List<Notification>> getNotifications(int offset); Single<TopicAndReplies> getTopicAndComments(int topicId); Single<TopicDetail> getTopicDetail(int id); Single<List<TopicReply>> getTopicReplies(int topicId, int offset); Single<TopicReply> publishComment(int id, String body); Single<ImageResult> uploadPhoto(String filePath); Single<Map<TopicNodeCategory, List<TopicNode>>> getTopicNodes(); Single<List<Project>> getProjects(int offset); Single<List<SiteListItem>> getSites(); Single<UserDetail> getUserDetail(String userLogin); static final int PAGE_LIMIT; static final String DATE_FORMAT; }### Answer: @Test public void createTopic() throws Exception { TestObserver<TopicDetail> testObserver = mDataManager.createTopic(0, "title", "body") .test() .await(); testObserver.assertError(HttpException.class); testObserver.assertNotComplete(); }
### Question: NewsPresenter extends BasePresenter<INewsView> { public void loadMore() { loadTopics(false); } @Inject NewsPresenter(DataManager dataManager); @Override void onAttach(INewsView view); void onRefresh(); void loadMore(); @Override void onDetach(); }### Answer: @Test public void testLoadMore() throws Exception { List<News> newses = mock(ArrayList.class); when(newses.size()).thenReturn(DataManager.PAGE_LIMIT); Integer offset = DataManager.PAGE_LIMIT; when(mNewsView.getItemOffset()).thenReturn(offset); when(mDataManager.getAllNewses(offset)).thenReturn(Single.just(newses)); mPresenter.loadMore(); verify(mNewsView).showNewes(newses, false); } @Test public void testLoadMoreError() throws Exception { Integer offset = DataManager.PAGE_LIMIT; when(mNewsView.getItemOffset()).thenReturn(offset); when(mDataManager.getAllNewses(offset)) .thenReturn(Single.error(mock(HttpException.class))); mPresenter.loadMore(); verify(mNewsView).showLoadMoreFailed(); } @Test public void testLoadNoMore() throws Exception { List<News> newses = mock(ArrayList.class); when(newses.size()).thenReturn(10); Integer offset = DataManager.PAGE_LIMIT; when(mNewsView.getItemOffset()).thenReturn(offset); when(mDataManager.getAllNewses(offset)).thenReturn(Single.just(newses)); mPresenter.loadMore(); verify(mNewsView).showNewes(newses, false); verify(mNewsView).showLoadNoMore(); }