method2testcases
stringlengths
118
3.08k
### Question: DuplicateUtil { public static void removeDuplicateSets(Multimap<Long, ImageRecord> records) { logger.info("Checking {} groups for duplicates", records.keySet().size()); Stopwatch sw = Stopwatch.createStarted(); Set<Collection<ImageRecord>> uniqueRecords = new HashSet<Collection<ImageRecord>>(records.keySet().size()); Iterator<Collection<ImageRecord>> recordIter = records.asMap().values().iterator(); long removedGroups = 0; while (recordIter.hasNext()) { Collection<ImageRecord> next = recordIter.next(); if (!uniqueRecords.add(next)) { recordIter.remove(); removedGroups++; } } logger.info("Checked groups in {}, removed {} identical groups", sw, removedGroups); } static Multimap<Long, ImageRecord> groupByHash(Collection<ImageRecord> dbRecords); static void removeSingleImageGroups(Multimap<Long, ImageRecord> sourceGroups); static void removeDuplicateSets(Multimap<Long, ImageRecord> records); }### Answer: @Test public void testRemoveDuplicateSetsIdenticalSets() throws Exception { Multimap<Long, ImageRecord> map = MultimapBuilder.hashKeys().hashSetValues().build(); map.putAll(1L, records); map.putAll(2L, records); DuplicateUtil.removeDuplicateSets(map); assertThat(map.keySet().size(), is(1)); } @Test public void testRemoveDuplicateSetsNonIdenticalSets() throws Exception { Multimap<Long, ImageRecord> map = MultimapBuilder.hashKeys().hashSetValues().build(); map.putAll(1L, records); map.putAll(2L, records); map.put(2L, new ImageRecord("foo", 1L)); DuplicateUtil.removeDuplicateSets(map); assertThat(map.keySet().size(), is(2)); }
### Question: DuplicateUtil { protected static final BigInteger hashSum(Collection<Long> hashes) { BigInteger hashSum = BigInteger.ZERO; for (Long hash : hashes) { hashSum = hashSum.add(BigInteger.valueOf(hash)); } return hashSum; } static Multimap<Long, ImageRecord> groupByHash(Collection<ImageRecord> dbRecords); static void removeSingleImageGroups(Multimap<Long, ImageRecord> sourceGroups); static void removeDuplicateSets(Multimap<Long, ImageRecord> records); }### Answer: @Test public void testHashSumNoHashes() throws Exception { assertThat(DuplicateUtil.hashSum(Collections.emptyList()), is(BigInteger.ZERO)); } @Test public void testHashSum() throws Exception { List<Long> hashes = new LinkedList<Long>(); hashes.add(2L); hashes.add(3L); assertThat(DuplicateUtil.hashSum(hashes), is(new BigInteger("5"))); }
### Question: ImageRecordComperator implements Comparator<ImageRecord>, Serializable { @Override public int compare(ImageRecord o1, ImageRecord o2) { long l1 = o1.getpHash(); long l2 = o2.getpHash(); if (l1 < l2) { return -1; } else if (l1 == l2) { return 0; } else { return 1; } } @Override int compare(ImageRecord o1, ImageRecord o2); }### Answer: @Test public void testCompareEqual() throws Exception { assertThat(irc.compare(a, new ImageRecord("", 1L)), is(0)); } @Test public void testCompareLess() throws Exception { assertThat(irc.compare(a, b), is(-1)); } @Test public void testCompareLessLargerNumber() throws Exception { assertThat(irc.compare(a, c), is(-1)); } @Test public void testCompareGreater() throws Exception { assertThat(irc.compare(b, a), is(1)); } @Test public void testCompareGreaterLargerNumber() throws Exception { assertThat(irc.compare(c, a), is(1)); } @Test(expected = NullPointerException.class) public void testCompareFirstNull() throws Exception { irc.compare(null, b); } @Test(expected = NullPointerException.class) public void testCompareSecondNull() throws Exception { irc.compare(a, null); } @Test(expected = NullPointerException.class) public void testCompareBothNull() throws Exception { irc.compare(null, null); }
### Question: DuplicateOperations { public void moveToDnw(Path path) { logger.info("Method not implemented"); } @Inject DuplicateOperations(FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); DuplicateOperations(FileSystem fileSystem, FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); void moveToDnw(Path path); void deleteAll(Collection<Result> records); void remove(Collection<ImageRecord> records); void deleteFile(Result result); void deleteFile(Path path); void markAll(Collection<Result> records, Tag tag); void markDnwAndDelete(Collection<Result> records); void markAs(Result result, Tag tag); void markAs(Path path, Tag tag); void markAs(ImageRecord image, Tag tag); void markDirectoryAs(Path directory, Tag tag); void markDirectoryAndChildrenAs(Path rootDirectory, Tag tag); List<ImageRecord> findMissingFiles(Path directory); void ignore(Result result); List<Tag> getFilterTags(); }### Answer: @Ignore("Not implemented yet") @Test public void testMoveToDnw() throws Exception { List<Path> files = createTempTestFiles(1); Path file = files.get(0); dupOp.moveToDnw(file); assertThat(Files.exists(file), is(true)); verify(imageRepository).remove(new ImageRecord(file.toString(), TEST_HASH)); verify(filterRepository).store(new FilterRecord(anyLong(), TAG_DNW)); }
### Question: DuplicateOperations { public void deleteAll(Collection<Result> records) { for (Result result : records) { deleteFile(result); } } @Inject DuplicateOperations(FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); DuplicateOperations(FileSystem fileSystem, FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); void moveToDnw(Path path); void deleteAll(Collection<Result> records); void remove(Collection<ImageRecord> records); void deleteFile(Result result); void deleteFile(Path path); void markAll(Collection<Result> records, Tag tag); void markDnwAndDelete(Collection<Result> records); void markAs(Result result, Tag tag); void markAs(Path path, Tag tag); void markAs(ImageRecord image, Tag tag); void markDirectoryAs(Path directory, Tag tag); void markDirectoryAndChildrenAs(Path rootDirectory, Tag tag); List<ImageRecord> findMissingFiles(Path directory); void ignore(Result result); List<Tag> getFilterTags(); }### Answer: @Test public void testDeleteAll() throws Exception { List<Path> files = createTempTestFiles(10); LinkedList<Result> records = new LinkedList<>(); for (Path p : files) { records.add(new Result(resultGroup, new ImageRecord(p.toString(), 0))); } dupOp.deleteAll(records); assertFilesDoNotExist(files); verify(imageRepository, times(10)).remove(any(ImageRecord.class)); }
### Question: DuplicateOperations { public void deleteFile(Result result) { deleteFile(fileSystem.getPath(result.getImageRecord().getPath())); result.remove(); } @Inject DuplicateOperations(FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); DuplicateOperations(FileSystem fileSystem, FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); void moveToDnw(Path path); void deleteAll(Collection<Result> records); void remove(Collection<ImageRecord> records); void deleteFile(Result result); void deleteFile(Path path); void markAll(Collection<Result> records, Tag tag); void markDnwAndDelete(Collection<Result> records); void markAs(Result result, Tag tag); void markAs(Path path, Tag tag); void markAs(ImageRecord image, Tag tag); void markDirectoryAs(Path directory, Tag tag); void markDirectoryAndChildrenAs(Path rootDirectory, Tag tag); List<ImageRecord> findMissingFiles(Path directory); void ignore(Result result); List<Tag> getFilterTags(); }### Answer: @Test public void testDeleteFile() throws Exception { List<Path> files = createTempTestFiles(1); Path file = files.get(0); assertThat(GUARD_MSG, Files.exists(file), is(true)); dupOp.deleteFile(file); assertThat(Files.exists(file), is(false)); verify(imageRepository).remove(new ImageRecord(file.toString(), 0)); }
### Question: DuplicateOperations { public void markDnwAndDelete(Collection<Result> records) { for (Result result : records) { ImageRecord ir = result.getImageRecord(); Path path = fileSystem.getPath(ir.getPath()); try { markAs(ir, TAG_DNW); deleteFile(result); } catch (RepositoryException e) { logger.warn("Failed to add filter entry for {} - {}", path, e.getMessage()); } } } @Inject DuplicateOperations(FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); DuplicateOperations(FileSystem fileSystem, FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); void moveToDnw(Path path); void deleteAll(Collection<Result> records); void remove(Collection<ImageRecord> records); void deleteFile(Result result); void deleteFile(Path path); void markAll(Collection<Result> records, Tag tag); void markDnwAndDelete(Collection<Result> records); void markAs(Result result, Tag tag); void markAs(Path path, Tag tag); void markAs(ImageRecord image, Tag tag); void markDirectoryAs(Path directory, Tag tag); void markDirectoryAndChildrenAs(Path rootDirectory, Tag tag); List<ImageRecord> findMissingFiles(Path directory); void ignore(Result result); List<Tag> getFilterTags(); }### Answer: @Test public void testMarkDnwAndDelete() throws Exception { List<Path> files = createTempTestFiles(RECORD_NUMBER); LinkedList<Result> records = new LinkedList<>(); for (Path p : files) { records.add(new Result(resultGroup, new ImageRecord(p.toString(), 0))); } dupOp.markDnwAndDelete(records); assertFilesDoNotExist(files); ArgumentCaptor<FilterRecord> capture = ArgumentCaptor.forClass(FilterRecord.class); verify(filterRepository, times(RECORD_NUMBER)).store(capture.capture()); verify(imageRepository, times(RECORD_NUMBER)).remove(any(ImageRecord.class)); for (FilterRecord record : capture.getAllValues()) { assertThat(record.getTag(), is(TAG_DNW)); } }
### Question: DuplicateOperations { public void markAll(Collection<Result> records, Tag tag) { for (Result result : records) { ImageRecord record = result.getImageRecord(); try { markAs(record, tag); logger.info("Adding pHash {} to filter, tag {}, source file {}", record.getpHash(), tag, record.getPath()); } catch (RepositoryException e) { logger.warn("Failed to add tag for {}: {}", record.getPath(), e.toString()); } } } @Inject DuplicateOperations(FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); DuplicateOperations(FileSystem fileSystem, FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); void moveToDnw(Path path); void deleteAll(Collection<Result> records); void remove(Collection<ImageRecord> records); void deleteFile(Result result); void deleteFile(Path path); void markAll(Collection<Result> records, Tag tag); void markDnwAndDelete(Collection<Result> records); void markAs(Result result, Tag tag); void markAs(Path path, Tag tag); void markAs(ImageRecord image, Tag tag); void markDirectoryAs(Path directory, Tag tag); void markDirectoryAndChildrenAs(Path rootDirectory, Tag tag); List<ImageRecord> findMissingFiles(Path directory); void ignore(Result result); List<Tag> getFilterTags(); }### Answer: @Test public void testMarkAll() throws Exception { LinkedList<Result> records = new LinkedList<>(); records.add(new Result(resultGroup, new ImageRecord(TAG_FOO.getTag(), 0))); records.add(new Result(resultGroup, new ImageRecord(TAG_BAR.getTag(), 1))); dupOp.markAll(records, TAG_ALL); verify(filterRepository).store(new FilterRecord(0, TAG_ALL)); verify(filterRepository).store(new FilterRecord(1, TAG_ALL)); }
### Question: DuplicateOperations { public void ignore(Result result) { logger.info("Ignoring {}", result); try { ignoreRepository.store(new IgnoreRecord(result.getImageRecord())); } catch (RepositoryException e) { logger.error("Failed to store ignored image: {}, cause: {}", e.toString(), e.getCause().toString()); } } @Inject DuplicateOperations(FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); DuplicateOperations(FileSystem fileSystem, FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); void moveToDnw(Path path); void deleteAll(Collection<Result> records); void remove(Collection<ImageRecord> records); void deleteFile(Result result); void deleteFile(Path path); void markAll(Collection<Result> records, Tag tag); void markDnwAndDelete(Collection<Result> records); void markAs(Result result, Tag tag); void markAs(Path path, Tag tag); void markAs(ImageRecord image, Tag tag); void markDirectoryAs(Path directory, Tag tag); void markDirectoryAndChildrenAs(Path rootDirectory, Tag tag); List<ImageRecord> findMissingFiles(Path directory); void ignore(Result result); List<Tag> getFilterTags(); }### Answer: @Test public void testIgnoreImage() throws Exception { dupOp.ignore(result); verify(ignoreRepository).store(new IgnoreRecord(result.getImageRecord())); }
### Question: CompareHammingDistance implements Distance<Long> { protected static int getHammingDistance(long a, long b) { long xor = a ^ b; int distance = Long.bitCount(xor); return distance; } @Override double eval(Long e1, Long e2); }### Answer: @Test public void testGetHammingDistance() throws Exception { assertThat(CompareHammingDistance.getHammingDistance(2L, 3L), is(1)); } @Test public void testGetHammingDistance2() throws Exception { assertThat(CompareHammingDistance.getHammingDistance(2L, 4L), is(2)); } @Test public void testGetHammingDistance3() throws Exception { assertThat(CompareHammingDistance.getHammingDistance(3L, 5L), is(2)); }
### Question: CompareHammingDistance implements Distance<Long> { @Override public double eval(Long e1, Long e2) { int distance = getHammingDistance(e1, e2); return distance; } @Override double eval(Long e1, Long e2); }### Answer: @Test public void testEvalDistanceAxiom1() throws Exception { assertThat(chd.eval(a, c), is(0.0)); assertThat(a, is(c)); } @Test public void testEvalDistanceAxiom2() throws Exception { double ab, ba; ab = chd.eval(a, b); ba = chd.eval(b, a); assertThat(ab, is(ba)); } @Test public void testEvalDistanceAxiom3() throws Exception { double ad, ab, bd; ab = chd.eval(a, b); ad = chd.eval(a, d); bd = chd.eval(b, d); assertThat(ad, is(lessThanOrEqualTo(ab + bd))); }
### Question: SimilarImage { protected static boolean isNoWorkersMode(Namespace args) { return args.getBoolean("no_workers"); } static void main(String[] args); void init(boolean noWorkers); }### Answer: @Test public void testIsNoWorkersMode() throws Exception { assertThat(SimilarImage.isNoWorkersMode(noWorkersArgs), is(true)); } @Test public void testIsLocalMode() throws Exception { assertThat(SimilarImage.isNoWorkersMode(localModeArgs), is(false)); }
### Question: ImageInfo { public Path getPath() { return path; } ImageInfo(Path path, long pHash); Path getPath(); Dimension getDimension(); long getSize(); long getpHash(); double getSizePerPixel(); }### Answer: @Test public void testGetPath() throws Exception { assertThat(imageInfo.getPath(), is(testImage)); } @Test public void testGetPathInvalidImage() throws Exception { assertThat(imageInfoInvalid.getPath(), is(invalidImage)); }
### Question: ImageInfo { public Dimension getDimension() { return dimension; } ImageInfo(Path path, long pHash); Path getPath(); Dimension getDimension(); long getSize(); long getpHash(); double getSizePerPixel(); }### Answer: @Test public void testGetDimension() throws Exception { assertThat(imageInfo.getDimension(), is(new Dimension(40, 40))); } @Test public void testGetDimensionInvalidImage() throws Exception { assertThat(imageInfoInvalid.getDimension(), is(new Dimension(0, 0))); }
### Question: ImageInfo { public long getSize() { return size; } ImageInfo(Path path, long pHash); Path getPath(); Dimension getDimension(); long getSize(); long getpHash(); double getSizePerPixel(); }### Answer: @Test public void testGetSize() throws Exception { assertThat(imageInfo.getSize(), is(1782L)); } @Test public void testGetSizeInvalidImage() throws Exception { assertThat(imageInfoInvalid.getSize(), is(-1L)); } @Test public void testGetSizeInvalidFile() throws Exception { ImageInfo info = new ImageInfo(Paths.get("foo"), 2); assertThat(info.getSize(), is(-1L)); }
### Question: ImageInfo { public long getpHash() { return pHash; } ImageInfo(Path path, long pHash); Path getPath(); Dimension getDimension(); long getSize(); long getpHash(); double getSizePerPixel(); }### Answer: @Test public void testGetpHash() throws Exception { assertThat(imageInfo.getpHash(), is(42L)); } @Test public void testGetpHashInvalidImage() throws Exception { assertThat(imageInfoInvalid.getpHash(), is(0L)); } @Test public void testGetpHashInvalidFile() throws Exception { ImageInfo info = new ImageInfo(Paths.get("foo"), 2); assertThat(info.getpHash(), is(2L)); }
### Question: HashAttribute { public long readHash(Path path) throws InvalidAttributeValueException, IOException { if (!areAttributesValid(path)) { throw new InvalidAttributeValueException("The required attributes are not set or invalid"); } String encodedHash = ExtendedAttribute.readExtendedAttributeAsString(path, hashFQN); return Long.parseUnsignedLong(encodedHash, HEXADECIMAL_RADIX); } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }### Answer: @Test(expected = InvalidAttributeValueException.class) public void testReadHashInvalidFile() throws Exception { cut.readHash(fs.getPath(INVALID_FILE_PATH)); }
### Question: ImageInfo { public double getSizePerPixel() { return sizePerPixel; } ImageInfo(Path path, long pHash); Path getPath(); Dimension getDimension(); long getSize(); long getpHash(); double getSizePerPixel(); }### Answer: @Test public void testGetSizePerPixel() throws Exception { assertThat(imageInfo.getSizePerPixel(), is(1.11375)); } @Test public void testGetSizePerPixelInvalidImage() throws Exception { assertThat(imageInfoInvalid.getSizePerPixel(), is(0.0)); }
### Question: IgnoredImagePresenter { public void setView(IgnoredImageView view) { this.view = view; refreshList(); } IgnoredImagePresenter(IgnoreRepository ignoreRepository); void setView(IgnoredImageView view); DefaultListModel<IgnoreRecord> getModel(); void refreshList(); void removeIgnoredImages(List<IgnoreRecord> toRemove); }### Answer: @Test public void testSetView() throws Exception { cut.setView(ignoredImageView); verify(ignoredImageView, timeout(CONCURRENT_TIMEOUT)).pack(); }
### Question: IgnoredImagePresenter { public DefaultListModel<IgnoreRecord> getModel() { return model; } IgnoredImagePresenter(IgnoreRepository ignoreRepository); void setView(IgnoredImageView view); DefaultListModel<IgnoreRecord> getModel(); void refreshList(); void removeIgnoredImages(List<IgnoreRecord> toRemove); }### Answer: @Test public void testGetModel() throws Exception { assertThat(cut.getModel(), is(not(nullValue()))); }
### Question: IgnoredImagePresenter { public void refreshList() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { model.clear(); try { ignoreRepository.getAll().forEach(new Consumer<IgnoreRecord>() { @Override public void accept(IgnoreRecord t) { model.addElement(t); } }); } catch (RepositoryException e) { LOGGER.error("Failed to load ignored image list: {} cause:{}", e.getCause()); } view.pack(); } }); } IgnoredImagePresenter(IgnoreRepository ignoreRepository); void setView(IgnoredImageView view); DefaultListModel<IgnoreRecord> getModel(); void refreshList(); void removeIgnoredImages(List<IgnoreRecord> toRemove); }### Answer: @Test public void testRefreshList() throws Exception { cut.setView(ignoredImageView); cut.refreshList(); Awaitility.await().atMost(CONCURRENT_TIMEOUT, TimeUnit.MILLISECONDS).until(() -> cut.getModel().getSize(), is(2)); }
### Question: IgnoredImagePresenter { public void removeIgnoredImages(List<IgnoreRecord> toRemove) { LOGGER.info("Removing {} ignored images", toRemove.size()); toRemove.forEach(this::removeIgnoredImage); } IgnoredImagePresenter(IgnoreRepository ignoreRepository); void setView(IgnoredImageView view); DefaultListModel<IgnoreRecord> getModel(); void refreshList(); void removeIgnoredImages(List<IgnoreRecord> toRemove); }### Answer: @Test public void testRemoveIgnoredImages() throws Exception { cut.removeIgnoredImages(Arrays.asList(ignoreA)); verify(ignoreRepository).remove(ignoreA); } @Test public void testRemoveIgnoredImagesWithRepositoryError() throws Exception { Mockito.doThrow(new RepositoryException("")).when(ignoreRepository).remove(ignoreA); cut.removeIgnoredImages(Arrays.asList(ignoreA, ignoreB)); verify(ignoreRepository, times(2)).remove(any()); }
### Question: ThumbnailCacheLoader extends CacheLoader<Result, BufferedImage> { @Override public BufferedImage load(Result key) throws Exception { BufferedImage bi = ImageUtil.loadImage(Paths.get(key.getImageRecord().getPath())); return Scalr.resize(bi, Method.AUTOMATIC, THUMBNAIL_SIZE); } @Override BufferedImage load(Result key); }### Answer: @Test public void testLoadImage() throws Exception { assertThat(cut.load(key), is(notNullValue())); } @Test(expected = NoSuchFileException.class) public void testLoadInvalidPath() throws Exception { assertThat(cut.load(invalidImagePath), is(notNullValue())); }
### Question: HashAttribute { public String getHashFQN() { return hashFQN; } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }### Answer: @Test public void testGetHashFQN() throws Exception { assertThat(cut.getHashFQN(), is(ExtendedAttribute.createName("hash", TEST_HASH_NAME))); }
### Question: ResultPresenter { public Path getImagePath() { return imageInfo.getPath(); } ResultPresenter(Result result, LoadingCache<Result, BufferedImage> thumbnailCache); Path getImagePath(); void displayFullImage(); void setView(ResultView view); }### Answer: @Test public void testGetImagePath() throws Exception { assertThat(duplicateEntryController.getImagePath(), is(Paths.get(testImage.toString()))); }
### Question: ResultPresenter { public void setView(ResultView view) { this.view = view; loadThumbnail(); addImageInfo(); } ResultPresenter(Result result, LoadingCache<Result, BufferedImage> thumbnailCache); Path getImagePath(); void displayFullImage(); void setView(ResultView view); }### Answer: @Test public void testSetView() throws Exception { verify(view).setImage(any(JLabel.class)); verify(view).createLable(eq("Path: " + testImage.toString())); verify(view).createLable(eq("Size: 1 kb")); verify(view).createLable(eq("Dimension: 40x40")); verify(view).createLable(eq("pHash: 42")); verify(view).createLable(eq("Size per Pixel: 1.11375")); }
### Question: ResultPresenter { public void displayFullImage() { JLabel largeImage = new JLabel("No Image"); try { BufferedImage bi = ImageUtil.loadImage(getImagePath()); largeImage = imageAsLabel(bi); } catch (Exception e) { LOGGER.warn("Unable to load full image {} - {}", getImagePath(), e.getMessage()); } view.displayFullImage(largeImage, getImagePath()); } ResultPresenter(Result result, LoadingCache<Result, BufferedImage> thumbnailCache); Path getImagePath(); void displayFullImage(); void setView(ResultView view); }### Answer: @Test public void testDisplayFullImage() throws Exception { duplicateEntryController.displayFullImage(); verify(view).displayFullImage(any(JLabel.class), eq(testImage)); }
### Question: ProgressVisitor extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (!imageFileFilter.accept(file)) { return FileVisitResult.CONTINUE; } foundFiles.inc(); filesPerSecond.mark(); if (hashAttribute.isCorrupted(file)) { failedFiles.inc(); } else if (hashAttribute.areAttributesValid(file)) { processedFiles.inc(); } return FileVisitResult.CONTINUE; } ProgressVisitor(MetricRegistry metrics, HashAttribute hashAttribute); @Override FileVisitResult visitFile(Path file, BasicFileAttributes attrs); }### Answer: @Test public void testProcessedFileFoundCountForNonImage() throws Exception { cut.visitFile(pathNonImage, null); assertThat(foundFiles.getCount(), is(0L)); }
### Question: ArgumentPasrser { public void parseArgs(String[] args) throws ArgumentParserException { Namespace parsedArgs = parser.parseArgs(args); if (parsedArgs.get("subcommand") == Subcommand.local) { localCommand(parsedArgs); } if (parsedArgs.get("subcommand") == Subcommand.node) { nodeCommand(parsedArgs); } } ArgumentPasrser(FileVisitor<Path> visitor); void parseArgs(String[] args); }### Answer: @Test(expected = ArgumentParserException.class) public void testParseArgsInvalidOption() throws Exception { cut.parseArgs(new String[] { LOCAL_SUBCOMMAND, "--foo" }); } @Test public void testParseArgsUpdateOption() throws Exception { cut.parseArgs(new String[] { LOCAL_SUBCOMMAND, "--update", "foo" }); } @Test public void testParseArgsNodeOption() throws Exception { cut.parseArgs(new String[] { NODE_SUBCOMMAND, "--port", "123" }); }
### Question: ProgressCalc { public double totalProgressPercent() { if (foundFiles.getCount() == 0) { return 0; } else { return (PERCENT_100 / foundFiles.getCount()) * (processedFiles.getCount() + failedFiles.getCount()); } } ProgressCalc(MetricRegistry metrics); double totalProgressPercent(); double corruptPercent(); @Override String toString(); static final String METRIC_NAME_FOUND; static final String METRIC_NAME_PROCESSED; static final String METRIC_NAME_FAILED; static final String METRIC_NAME_FILES_PER_SECOND; }### Answer: @Test public void testTotalProgressPercent() throws Exception { assertThat(cut.totalProgressPercent(), closeTo(TOTAL_PROGRESS_PERCENT, ALLOWED_COMAPRE_ERROR)); } @Test public void testTotalProgressPercentWithNoFiles() throws Exception { setCounter(ProgressCalc.METRIC_NAME_FOUND, 0); setCounter(ProgressCalc.METRIC_NAME_PROCESSED, 0); assertThat(cut.totalProgressPercent(), is(0.0)); }
### Question: HashAttribute { public String getTimestampFQN() { return timestampFQN; } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }### Answer: @Test public void testGetTimestampFQN() throws Exception { assertThat(cut.getTimestampFQN(), is(ExtendedAttribute.createName("timestamp", TEST_HASH_NAME))); }
### Question: ProgressCalc { public double corruptPercent() { if (foundFiles.getCount() == 0) { return 0; } else { return (PERCENT_100 / foundFiles.getCount()) * failedFiles.getCount(); } } ProgressCalc(MetricRegistry metrics); double totalProgressPercent(); double corruptPercent(); @Override String toString(); static final String METRIC_NAME_FOUND; static final String METRIC_NAME_PROCESSED; static final String METRIC_NAME_FAILED; static final String METRIC_NAME_FILES_PER_SECOND; }### Answer: @Test public void testCorruptPercent() throws Exception { assertThat(cut.corruptPercent(), closeTo(CORRUPT_PERCENT, ALLOWED_COMAPRE_ERROR)); } @Test public void testCorruptPercentWithNoFiles() throws Exception { setCounter(ProgressCalc.METRIC_NAME_FOUND, 0); setCounter(ProgressCalc.METRIC_NAME_FAILED, 0); assertThat(cut.corruptPercent(), is(0.0)); }
### Question: ProgressCalc { @Override public String toString() { return String.format("Total progress: %.2f%%, corrupt images: %.2f%%, files per second processed: %.2f", totalProgressPercent(), corruptPercent(), filesPerSecond.getMeanRate()); } ProgressCalc(MetricRegistry metrics); double totalProgressPercent(); double corruptPercent(); @Override String toString(); static final String METRIC_NAME_FOUND; static final String METRIC_NAME_PROCESSED; static final String METRIC_NAME_FAILED; static final String METRIC_NAME_FILES_PER_SECOND; }### Answer: @Test public void testToString() throws Exception { assertThat(cut.toString(), is("Total progress: 23.81%, corrupt images: 9.52%, files per second processed: 0.00")); }
### Question: MessageFactory { public ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid) { ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeLong(uuid.getMostSignificantBits()); message.getBodyBuffer().writeLong(uuid.getLeastSignificantBits()); message.getBodyBuffer().writeBytes(resizedImage); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer: @Test public void testHashRequestMessageTrackingId() throws Exception { ClientMessage result = cut.hashRequestMessage(IMAGE_DATA, UUID); UUID id = new UUID(result.getBodyBuffer().readLong(), result.getBodyBuffer().readLong()); assertThat(id, is(UUID)); } @Test public void testHashRequestMessageImageData() throws Exception { ClientMessage result = cut.hashRequestMessage(IMAGE_DATA, UUID); result.getBodyBuffer().readLong(); result.getBodyBuffer().readLong(); byte[] data = new byte[IMAGE_DATA.length]; result.getBodyBuffer().readBytes(data); assertArrayEquals(data, IMAGE_DATA); } @Test public void testHashRequestMessageImageSize() throws Exception { ClientMessage result = cut.hashRequestMessage(IMAGE_DATA, UUID); result.getBodyBuffer().readLong(); result.getBodyBuffer().readLong(); byte[] data = new byte[result.getBodySize()]; result.getBodyBuffer().readBytes(data); assertArrayEquals(data, IMAGE_DATA); }
### Question: MessageFactory { public ClientMessage resultMessage(long hash, long most, long least) { ClientMessage message = session.createMessage(true); setTaskType(message, TaskType.result); ActiveMQBuffer buffer = message.getBodyBuffer(); buffer.writeLong(most); buffer.writeLong(least); buffer.writeLong(hash); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer: @Test public void testResultMessageTask() throws Exception { ClientMessage result = cut.resultMessage(HASH, UUID.getMostSignificantBits(), UUID.getLeastSignificantBits()); assertThat(result.getStringProperty(MessageProperty.task.toString()), is(TaskType.result.toString())); } @Test public void testResultMessageUuid() throws Exception { ClientMessage result = cut.resultMessage(HASH, UUID.getMostSignificantBits(), UUID.getLeastSignificantBits()); UUID id = new UUID(result.getBodyBuffer().readLong(), result.getBodyBuffer().readLong()); assertThat(id, is(UUID)); } @Test public void testResultMessageHash() throws Exception { ClientMessage result = cut.resultMessage(HASH, UUID.getMostSignificantBits(), UUID.getLeastSignificantBits()); result.getBodyBuffer().readLong(); result.getBodyBuffer().readLong(); long hash = result.getBodyBuffer().readLong(); assertThat(hash, is(HASH)); }
### Question: MessageFactory { public ClientMessage pendingImageQuery() { ClientMessage message = session.createMessage(false); message.putStringProperty(MessageProperty.repository_query.toString(), QueryType.pending.toString()); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer: @Test public void testPendingImageQuery() throws Exception { ClientMessage result = cut.pendingImageQuery(); assertThat(result.getStringProperty(MessageFactory.MessageProperty.repository_query.toString()), is(MessageFactory.QueryType.pending.toString())); }
### Question: HashAttribute { public void markCorrupted(Path path) throws IOException { ExtendedAttribute.setExtendedAttribute(path, corruptNameFQN, ""); } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }### Answer: @Test public void testMarkCorrupted() throws Exception { cut.markCorrupted(tempFile); assertThat(ExtendedAttribute.isExtendedAttributeSet(tempFile, cut.getCorruptNameFQN()), is(true)); }
### Question: MessageFactory { public ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages) throws IOException { List<String> pendingPaths = new LinkedList<String>(); for (PendingHashImage p : pendingImages) { pendingPaths.add(p.getPath()); } try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos)) { ClientMessage message = session.createMessage(false); oos.writeObject(pendingPaths); message.writeBodyBufferBytes(baos.toByteArray()); return message; } } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer: @Test public void testPendingImageResponse() throws Exception { ClientMessage result = cut.pendingImageResponse(Arrays.asList(new PendingHashImage(PATH, UUID))); assertThat(result.getBodySize(), is(EXPECTED_MESSAGE_SIZE)); }
### Question: MessageFactory { public ClientMessage corruptMessage(Path path) { ClientMessage message = session.createMessage(true); message.putStringProperty(MessageProperty.path.toString(), path.toString()); message.putStringProperty(MessageProperty.task.toString(), TaskType.corr.toString()); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer: @Test public void testCorruptMessagePath() throws Exception { ClientMessage result = cut.corruptMessage(PATH); assertThat(result.getStringProperty(MessageProperty.path.toString()), is(PATH.toString())); } @Test public void testCorruptMessageTask() throws Exception { ClientMessage result = cut.corruptMessage(PATH); assertThat(result.getStringProperty(MessageProperty.task.toString()), is(TaskType.corr.toString())); }
### Question: MessageFactory { public ClientMessage eaUpdate(Path path, long hash) { ClientMessage message = session.createMessage(true); setTaskType(message, TaskType.eaupdate); setPath(message, path); message.getBodyBuffer().writeLong(hash); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer: @Test public void testEaUpdatePath() throws Exception { ClientMessage result = cut.eaUpdate(PATH, HASH); assertThat(result.getStringProperty(MessageProperty.path.toString()), is(PATH.toString())); } @Test public void testEaUpdateHash() throws Exception { ClientMessage result = cut.eaUpdate(PATH, HASH); assertThat(result.getBodyBuffer().readLong(), is(HASH)); } @Test public void testEaUpdateTask() throws Exception { ClientMessage result = cut.eaUpdate(PATH, HASH); assertThat(result.getStringProperty(MessageProperty.task.toString()), is(TaskType.eaupdate.toString())); }
### Question: MessageFactory { public ClientMessage resizeRequest(Path path, InputStream is) throws IOException { ClientMessage message = session.createMessage(true); copyInputStreamToMessage(is, message); setTaskType(message, TaskType.hash); setPath(message, path); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer: @Test public void testResizeRequestPath() throws Exception { ClientMessage result = cut.resizeRequest(PATH, is); assertThat(result.getStringProperty(MessageProperty.path.toString()), is(PATH.toString())); } @Test public void testResizeRequestTask() throws Exception { ClientMessage result = cut.resizeRequest(PATH, is); assertThat(result.getStringProperty(MessageProperty.task.toString()), is(TaskType.hash.toString())); }
### Question: MessageFactory { public ClientMessage trackPath(Path path, UUID uuid) { ClientMessage message = session.createMessage(false); setTaskType(message, TaskType.track); setPath(message, path); message.getBodyBuffer().writeLong(uuid.getMostSignificantBits()); message.getBodyBuffer().writeLong(uuid.getLeastSignificantBits()); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer: @Test public void testTrackPathPathProperty() throws Exception { ClientMessage result = cut.trackPath(PATH, UUID); assertThat(result.getStringProperty(MessageProperty.path.toString()), is(PATH.toString())); } @Test public void testTrackPathTaskProperty() throws Exception { ClientMessage result = cut.trackPath(PATH, UUID); assertThat(result.getStringProperty(MessageProperty.task.toString()), is(TaskType.track.toString())); } @Test public void testTrackPathMessageBody() throws Exception { ClientMessage result = cut.trackPath(PATH, UUID); long most = result.getBodyBuffer().readLong(); long least = result.getBodyBuffer().readLong(); assertThat(new UUID(most, least), is(UUID)); }
### Question: HashAttribute { public String getCorruptNameFQN() { return corruptNameFQN; } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }### Answer: @Test public void testGetCorruptNameFQN() throws Exception { assertThat(cut.getCorruptNameFQN(), is(ExtendedAttribute.createName("corrupt"))); }
### Question: QueueToDatabaseTransaction implements CollectedMessageConsumer { @Override public void onDrain(List<ClientMessage> messages) { try { transactionManager.callInTransaction(new Callable<Void>() { @Override public Void call() throws Exception { onCall(messages); return null; } }); } catch (SQLException e) { LOGGER.warn("Failed to store {} messages: {}", messages.size(), e.toString(), e.getCause()); try { session.rollback(); } catch (ActiveMQException mqException) { String message = "Failed to rollback message transaction"; LOGGER.error(message, mqException); throw new RuntimeException(message, mqException); } } } QueueToDatabaseTransaction(ClientSession transactedSession, TransactionManager transactionManager, String eaQueueName, PendingHashImageRepository pendingRepository, ImageRepository imageRepository, MetricRegistry metrics); @Inject QueueToDatabaseTransaction(@Named("transacted") ClientSession transactedSession, TransactionManager transactionManager, PendingHashImageRepository pendingRepository, ImageRepository imageRepository, MetricRegistry metrics); @Override void onDrain(List<ClientMessage> messages); static final String METRIC_NAME_PENDING_MESSAGES_MISSING; static final String METRIC_NAME_PENDING_MESSAGES; static final String METRIC_NAME_PROCESSED_IMAGES; }### Answer: @Test public void testOnDrainInTransaction() throws Exception { cut.onDrain(messages); verify(transactionManager).callInTransaction(any()); } @Test public void testMessageRollbackOnDatabaseFailure() throws Exception { when(transactionManager.callInTransaction(any())) .thenThrow(new SQLException(EXCEPTION_MESSAGE)); cut.onDrain(messages); verify(session).rollback(); } @Test(expected = RuntimeException.class) public void testMessageRollbackFailure() throws Exception { when(transactionManager.callInTransaction(any())).thenThrow(new SQLException(EXCEPTION_MESSAGE)); Mockito.doThrow(new ActiveMQException()).when(session).rollback(); cut.onDrain(messages); }
### Question: HashAttribute { public boolean isCorrupted(Path path) throws IOException { return ExtendedAttribute.isExtendedAttributeSet(path, corruptNameFQN); } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }### Answer: @Test public void testIsCorruptedNotSet() throws Exception { assertThat(cut.isCorrupted(tempFile), is(false)); }
### Question: ResizerNode implements MessageHandler, Node { protected void allocateNewBuffer(int messageSize) { messageBuffer = ByteBuffer.allocateDirect(calcNewBufferSize(messageSize)); } @Inject ResizerNode(ClientSession session, ImageResizer resizer, MetricRegistry metrics); protected ResizerNode(ClientSession session, ImageResizer resizer, String requestAddress, String resultAddress, QueryMessage queryMessage, MetricRegistry metrics); @Override void onMessage(ClientMessage message); @Override void stop(); @Override String toString(); static final String METRIC_NAME_RESIZE_MESSAGES; static final String METRIC_NAME_RESIZE_DURATION; static final String METRIC_NAME_PENDING_CACHE_HIT; static final String METRIC_NAME_PENDING_CACHE_MISS; static final String METRIC_NAME_IMAGE_SIZE; static final String METRIC_NAME_BUFFER_RESIZE; }### Answer: @Test public void testBufferResize() throws Exception { for (byte i = 0; i < BUFFER_TEST_DATA_SIZE; i++) { message.getBodyBuffer().writeByte(i); } cut.allocateNewBuffer(1); producer.send(message); await().atMost(MESSAGE_TIMEOUT).until(() -> metrics.getCounters().get(ResizerNode.METRIC_NAME_BUFFER_RESIZE).getCount(), is(1L)); }
### Question: ByteBufferInputstream extends InputStream { @Override public int read() throws IOException { if (buffer.hasRemaining()) { return buffer.get() & 0xFF; } else { return -1; } } ByteBufferInputstream(ByteBuffer buffer); @Override int read(); @Override int available(); }### Answer: @Test public void testReadFirstByte() throws Exception { assertThat(input.read(), is(2)); } @Test public void testReadAllData() throws Exception { byte[] read = new byte[TEST_DATA.length]; input.read(read); assertThat(read, is(TEST_DATA)); } @Test public void testReadAllDataByteRead() throws Exception { byte[] read = new byte[BUFFER_CAPACITY *2]; int actualRead = input.read(read); assertThat(actualRead, is(TEST_DATA.length)); } @Test public void testReadAllDataBuffered() throws Exception { byte[] read = new byte[TEST_DATA.length]; BufferedInputStream bis = new BufferedInputStream(input); bis.read(read); assertThat(read, is(TEST_DATA)); }
### Question: MessageCollector { private void onDrain() { ImmutableList<ClientMessage> immutable; LOGGER.trace("Draining {} collected messsages...", collectedMessages.size()); synchronized (collectedMessages) { immutable = ImmutableList.copyOf(collectedMessages); collectedMessages.clear(); } for (CollectedMessageConsumer drain : consumers) { drain.onDrain(immutable); } } MessageCollector(int collectedMessageThreshold, CollectedMessageConsumer... consumers); void addMessage(ClientMessage message); void drain(); }### Answer: @Test public void testAddMessageAboveThreshold() throws Exception { addNumberOfMessages(MESSAGE_THRESHOLD); verify(collector).onDrain(anyListOf(ClientMessage.class)); } @Test public void testAddMessageReTrigger() throws Exception { addNumberOfMessages(2 * MESSAGE_THRESHOLD); verify(collector, times(2)).onDrain(anyListOf(ClientMessage.class)); }
### Question: TaskMessageHandler implements MessageHandler { @Override public void onMessage(ClientMessage msg) { try { if (isTaskType(msg, TaskType.track)) { String path = msg.getStringProperty(MessageProperty.path.toString()); long most = msg.getBodyBuffer().readLong(); long least = msg.getBodyBuffer().readLong(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Tracking new path {} with UUID {}", path, new UUID(most, least)); } pendingMessages.inc(); pendingRepository.store(new PendingHashImage(path, most, least)); } else { LOGGER.error("Unhandled message: {}", msg); } } catch (RepositoryException e) { String cause = "unknown"; if(e.getCause() != null) { cause = e.getCause().toString(); } LOGGER.warn("Failed to store result message: {}, cause:{}", e.toString(), cause); } } @Inject TaskMessageHandler(PendingHashImageRepository pendingRepository, ImageRepository imageRepository, MetricRegistry metrics); @Deprecated TaskMessageHandler(PendingHashImageRepository pendingRepository, ImageRepository imageRepository, ClientSession session, MetricRegistry metrics); @Deprecated TaskMessageHandler(PendingHashImageRepository pendingRepository, ImageRepository imageRepository, ClientSession session, String eaUpdateAddress, MetricRegistry metrics); TaskMessageHandler(PendingHashImageRepository pendingRepository, ImageRepository imageRepository, String eaUpdateAddress, MetricRegistry metrics); @Override void onMessage(ClientMessage msg); static final String METRIC_NAME_PENDING_MESSAGES; }### Answer: @Test public void testMetricPendingMessagesTrack() throws Exception { ClientMessage message = messageFactory.trackPath(Paths.get(TEST_PATH), UUID); cut.onMessage(message); assertThat(metrics.getCounters().get(TaskMessageHandler.METRIC_NAME_PENDING_MESSAGES).getCount(), is(1L)); }
### Question: ResultMessageSink implements Node { @Override public void stop() { LOGGER.info("Stopping {}", WORKER_THREAD_NAME); sink.interrupt(); try { sink.join(); } catch (InterruptedException ie) { LOGGER.warn("Interrupted while wating for sink to terminate: {}", ie.toString()); } try { consumer.close(); } catch (ActiveMQException e) { LOGGER.warn("Failed to close consumer: {}", e.toString()); } } ResultMessageSink(ClientSession transactedSession, MessageCollector collector, String resultQueueName, long messageIdleTimeout); ResultMessageSink(ClientSession transactedSession, MessageCollector collector); @Override void stop(); }### Answer: @Test public void testStop() throws Exception { cut.stop(); verify(collector, timeout(VERIFY_TIMEOUT)).drain(); verify(consumer).close(); } @Test(timeout = TEST_TIMEOUT) public void testDrainOnNoMessage() throws Exception { cut.stop(); Mockito.reset(collector); when(consumer.receive(anyLong())).thenReturn(null); cut = new ResultMessageSink(session, collector); verify(collector, timeout(VERIFY_TIMEOUT).atLeastOnce()).drain(); verify(collector, never()).addMessage(message); } @Test public void testMessageReadFailure() throws Exception { cut.stop(); Mockito.reset(collector); when(consumer.receive(anyLong())).thenThrow(new ActiveMQException("test")); cut = new ResultMessageSink(session, collector); verify(collector, atMost(1)).drain(); verify(collector, never()).addMessage(any(ClientMessage.class)); }
### Question: HasherNode implements MessageHandler, Node { @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(HasherNode.class.getSimpleName()).append(" {").append(identity.toString()).append("}"); return sb.toString(); } HasherNode(ClientSession session, ImagePHash hasher, String requestAddress, String resultAddress, MetricRegistry metrics); @Override void stop(); @Override String toString(); @Override void onMessage(ClientMessage message); static final String METRIC_NAME_HASH_MESSAGES; static final String METRIC_NAME_HASH_DURATION; static final String METRIC_NAME_BUFFER_RESIZE; }### Answer: @Test public void testToStringStart() throws Exception { assertThat(cut.toString(), startsWith("HasherNode {")); } @Test public void testToStringEnd() throws Exception { assertThat(cut.toString(), endsWith("}")); }
### Question: HasherNode implements MessageHandler, Node { @Override public void stop() { LOGGER.info("Stopping {}...", this.toString()); MessagingUtil.silentClose(consumer); MessagingUtil.silentClose(producer); MessagingUtil.silentClose(session); } HasherNode(ClientSession session, ImagePHash hasher, String requestAddress, String resultAddress, MetricRegistry metrics); @Override void stop(); @Override String toString(); @Override void onMessage(ClientMessage message); static final String METRIC_NAME_HASH_MESSAGES; static final String METRIC_NAME_HASH_DURATION; static final String METRIC_NAME_BUFFER_RESIZE; }### Answer: @Test public void testStop() throws Exception { cut.stop(); assertThat(session.isClosed(), is(true)); }
### Question: RepositoryNode implements MessageHandler, Node { @Override public String toString() { return RepositoryNode.class.getSimpleName(); } RepositoryNode(ClientSession session, String queryAddress, String taskAddress, PendingHashImageRepository pendingRepository, ImageRepository imageRepository, TaskMessageHandler taskMessageHandler, MetricRegistry metrics); @Inject RepositoryNode(@Named("normal") ClientSession session, PendingHashImageRepository pendingRepository, TaskMessageHandler taskMessageHandler, MetricRegistry metrics); @Override void onMessage(ClientMessage message); @Override void stop(); @Override String toString(); }### Answer: @Test public void testQueryPending() throws Exception { List<String> pending = queryMessage.pendingImagePaths(); assertThat(pending, hasItem(PATH.toString())); } @Test public void testToString() throws Exception { assertThat(cut.toString(), is("RepositoryNode")); }
### Question: StorageNode implements MessageHandler, Node { public boolean processFile(Path path) { LOGGER.trace("Processing {}", path); if (isAlreadySent(path)) { LOGGER.trace("File {} has already been sent, ignoring...", path); return true; } try (InputStream bis = new BufferedInputStream(Files.newInputStream(path))) { ClientMessage request = messageFactory.resizeRequest(path, bis); producer.send(request); sentRequests.put(path, 0); LOGGER.trace("Sent resize request for {}", path); return true; } catch (IOException e) { LOGGER.warn("Failed to access file {}: {}", path, e.toString()); } catch (ActiveMQException e) { LOGGER.warn("Failed to send resize request for {}: {}", path, e.toString()); } return false; } StorageNode(ClientSession session, ExtendedAttributeQuery eaQuery, HashAttribute hashAttribute, List<Path> pendingPaths, String resizeAddress, String eaUpdateAddress); @Inject StorageNode(@Named("normal") ClientSession session, ExtendedAttributeQuery eaQuery, HashAttribute hashAttribute, @Named("pending") List<Path> pendingPaths); @Override void onMessage(ClientMessage message); boolean processFile(Path path); @Override void stop(); @Override String toString(); }### Answer: @Test public void testProcessFile() throws Exception { cut.processFile(testFile); await().until(messages::size, is(1)); ClientMessage message = messages.get(0); assertThat(message.getStringProperty(MessageProperty.path.toString()), is(testFile.toString())); } @Test public void testProcessFileSkipDuplicateCached() throws Exception { cut.processFile(cachedFile); await().pollDelay(1, TimeUnit.SECONDS).until(messages::size, is(0)); }
### Question: StorageNode implements MessageHandler, Node { @Override public String toString() { return StorageNode.class.getSimpleName(); } StorageNode(ClientSession session, ExtendedAttributeQuery eaQuery, HashAttribute hashAttribute, List<Path> pendingPaths, String resizeAddress, String eaUpdateAddress); @Inject StorageNode(@Named("normal") ClientSession session, ExtendedAttributeQuery eaQuery, HashAttribute hashAttribute, @Named("pending") List<Path> pendingPaths); @Override void onMessage(ClientMessage message); boolean processFile(Path path); @Override void stop(); @Override String toString(); }### Answer: @Test public void testToString() throws Exception { assertThat(cut.toString(), is("StorageNode")); }
### Question: ByteBufferInputstream extends InputStream { @Override public int available() throws IOException { return buffer.remaining(); } ByteBufferInputstream(ByteBuffer buffer); @Override int read(); @Override int available(); }### Answer: @Test public void testAvailable() throws Exception { assertThat(input.available(), is(TEST_DATA.length)); }
### Question: ImageFileFilter implements Filter<Path> { @Override public boolean accept(Path entry) throws IOException { return extFilter.accept(entry); } ImageFileFilter(); @Override boolean accept(Path entry); }### Answer: @Test public void testJpg() throws Exception { assertThat(cut.accept(createFile("foo.jpg")), is(true)); } @Test public void testJpeg() throws Exception { assertThat(cut.accept(createFile("foo.jpeg")), is(true)); } @Test public void testPng() throws Exception { assertThat(cut.accept(createFile("foo.png")), is(true)); } @Test public void testGif() throws Exception { assertThat(cut.accept(createFile("foo.gif")), is(true)); } @Test public void testNonLowerCase() throws Exception { assertThat(cut.accept(createFile("foo.Jpg")), is(true)); } @Test public void testNonImageExtension() throws Exception { assertThat(cut.accept(createFile("foo.txt")), is(false)); }
### Question: ImageUtil { public static BufferedImage loadImage(Path path) throws IOException { try (InputStream is = new BufferedInputStream(Files.newInputStream(path))) { BufferedImage bi; try { bi = ImageIO.read(is); } catch (ArrayIndexOutOfBoundsException e) { bi = GifDecoder.read(is).getFrame(0); } return bi; } } static BufferedImage bytesToImage(byte[] data); static byte[] imageToBytes(BufferedImage image); static BufferedImage loadImage(Path path); }### Answer: @Test public void testLoadImageJpg() throws Exception { BufferedImage image = ImageUtil.loadImage(jpgPath); assertThat(image.getHeight(), is(IMAGE_SIZE)); assertThat(image.getWidth(), is(IMAGE_SIZE)); } @Test public void testLoadImageGif() throws Exception { BufferedImage image = ImageUtil.loadImage(gifPath); assertThat(image.getHeight(), is(IMAGE_SIZE)); assertThat(image.getWidth(), is(IMAGE_SIZE)); }
### Question: Statistics { public void incrementFailedFiles() { dispatchEvent(StatisticsEvent.FAILED_FILES, failedFiles.incrementAndGet()); } int getFoundFiles(); void incrementFoundFiles(); int getProcessedFiles(); void incrementProcessedFiles(); int getFailedFiles(); void incrementFailedFiles(); int getSkippedFiles(); void incrementSkippedFiles(); void reset(); void addStatisticsListener(StatisticsChangedListener listener); void removeStatisticsListener(StatisticsChangedListener listener); }### Answer: @Test public void testIncrementFailedFilesEvent() throws Exception { cut.incrementFailedFiles(); verify(listener).statisticsChangedEvent(eq(StatisticsEvent.FAILED_FILES), eq(1)); }
### Question: Statistics { public void incrementFoundFiles() { dispatchEvent(StatisticsEvent.FOUND_FILES, foundFiles.incrementAndGet()); } int getFoundFiles(); void incrementFoundFiles(); int getProcessedFiles(); void incrementProcessedFiles(); int getFailedFiles(); void incrementFailedFiles(); int getSkippedFiles(); void incrementSkippedFiles(); void reset(); void addStatisticsListener(StatisticsChangedListener listener); void removeStatisticsListener(StatisticsChangedListener listener); }### Answer: @Test public void testIncrementFoundFilesEvent() throws Exception { cut.incrementFoundFiles(); verify(listener).statisticsChangedEvent(eq(StatisticsEvent.FOUND_FILES), eq(1)); }
### Question: Statistics { public void incrementProcessedFiles() { dispatchEvent(StatisticsEvent.PROCESSED_FILES, processedFiles.incrementAndGet()); } int getFoundFiles(); void incrementFoundFiles(); int getProcessedFiles(); void incrementProcessedFiles(); int getFailedFiles(); void incrementFailedFiles(); int getSkippedFiles(); void incrementSkippedFiles(); void reset(); void addStatisticsListener(StatisticsChangedListener listener); void removeStatisticsListener(StatisticsChangedListener listener); }### Answer: @Test public void testIncrementProcessedFilesFiles() throws Exception { cut.incrementProcessedFiles(); verify(listener).statisticsChangedEvent(eq(StatisticsEvent.PROCESSED_FILES), eq(1)); }
### Question: Statistics { public void incrementSkippedFiles() { dispatchEvent(StatisticsEvent.SKIPPED_FILES, skippedFiles.incrementAndGet()); } int getFoundFiles(); void incrementFoundFiles(); int getProcessedFiles(); void incrementProcessedFiles(); int getFailedFiles(); void incrementFailedFiles(); int getSkippedFiles(); void incrementSkippedFiles(); void reset(); void addStatisticsListener(StatisticsChangedListener listener); void removeStatisticsListener(StatisticsChangedListener listener); }### Answer: @Test public void testIncrementSkippedFilesEvent() throws Exception { cut.incrementSkippedFiles(); verify(listener).statisticsChangedEvent(eq(StatisticsEvent.SKIPPED_FILES), eq(1)); }
### Question: Statistics { public void removeStatisticsListener(StatisticsChangedListener listener) { statisticsChangedListners.remove(listener); } int getFoundFiles(); void incrementFoundFiles(); int getProcessedFiles(); void incrementProcessedFiles(); int getFailedFiles(); void incrementFailedFiles(); int getSkippedFiles(); void incrementSkippedFiles(); void reset(); void addStatisticsListener(StatisticsChangedListener listener); void removeStatisticsListener(StatisticsChangedListener listener); }### Answer: @Test public void testRemoveStatisticsListener() throws Exception { cut.removeStatisticsListener(listener); cut.incrementFailedFiles(); cut.incrementFoundFiles(); cut.incrementProcessedFiles(); cut.incrementSkippedFiles(); verifyZeroInteractions(listener); }
### Question: GroupList { public void remove(Result result) { Collection<ResultGroup> groupsToRemoveFrom = resultsToGroups.removeAll(result); LOGGER.debug("Removing {} from {} group(s).", result, groupsToRemoveFrom.size()); for (ResultGroup g : groupsToRemoveFrom) { g.remove(result, false); checkAndremoveEmptyGroup(g); } } GroupList(); GroupList(DefaultListModel<ResultGroup> mappedListModel); void populateList(Collection<ResultGroup> groupsToAdd); int groupCount(); void remove(Result result); ResultGroup getGroup(long hash); List<ResultGroup> getAllGroups(); void setMappedListModel(DefaultListModel<ResultGroup> mappedListeModel); ResultGroup nextGroup(ResultGroup currentGroup); ResultGroup previousGroup(ResultGroup currentGroup); }### Answer: @Test public void testRemoveViaGroup() throws Exception { Result result = new Result(groupB, recordC); assertThat(groupB.getResults(), hasItem(result)); groupA.remove(result); assertThat(groupB.getResults(), not(hasItem(result))); } @Test public void testEmptyGroupRemovedFromGui() throws Exception { cut = new GroupList(dlm); initGroupList(); groupA.remove(new Result(groupA, recordC)); groupA.remove(new Result(groupA, recordA)); assertThat(dlm.contains(groupA), is(false)); }
### Question: GroupList { public int groupCount() { return groups.size(); } GroupList(); GroupList(DefaultListModel<ResultGroup> mappedListModel); void populateList(Collection<ResultGroup> groupsToAdd); int groupCount(); void remove(Result result); ResultGroup getGroup(long hash); List<ResultGroup> getAllGroups(); void setMappedListModel(DefaultListModel<ResultGroup> mappedListeModel); ResultGroup nextGroup(ResultGroup currentGroup); ResultGroup previousGroup(ResultGroup currentGroup); }### Answer: @Test public void testGroupCount() throws Exception { assertThat(cut.groupCount(), is(2)); }
### Question: GroupList { public ResultGroup getGroup(long hash) throws IllegalArgumentException { ResultGroup group = hashToGroup.get(hash); if (group == null) { throw new IllegalArgumentException("Query for unknown hash"); } return group; } GroupList(); GroupList(DefaultListModel<ResultGroup> mappedListModel); void populateList(Collection<ResultGroup> groupsToAdd); int groupCount(); void remove(Result result); ResultGroup getGroup(long hash); List<ResultGroup> getAllGroups(); void setMappedListModel(DefaultListModel<ResultGroup> mappedListeModel); ResultGroup nextGroup(ResultGroup currentGroup); ResultGroup previousGroup(ResultGroup currentGroup); }### Answer: @Test public void testGetGroup() throws Exception { assertThat(cut.getGroup(HASH_A), is(groupA)); } @Test(expected = IllegalArgumentException.class) public void testGetInvalidHash() throws Exception { cut.getGroup(-1); }
### Question: GroupList { public ResultGroup previousGroup(ResultGroup currentGroup) { int index = groups.indexOf(currentGroup); index = boundsCheckedIndex(--index); return groups.get(index); } GroupList(); GroupList(DefaultListModel<ResultGroup> mappedListModel); void populateList(Collection<ResultGroup> groupsToAdd); int groupCount(); void remove(Result result); ResultGroup getGroup(long hash); List<ResultGroup> getAllGroups(); void setMappedListModel(DefaultListModel<ResultGroup> mappedListeModel); ResultGroup nextGroup(ResultGroup currentGroup); ResultGroup previousGroup(ResultGroup currentGroup); }### Answer: @Test public void testPreviousGroup() throws Exception { assertThat(cut.previousGroup(groupB), is(groupA)); } @Test public void testPreviousGroupWithFirstGroup() throws Exception { assertThat(cut.previousGroup(groupA), is(groupA)); } @Test public void testPreviousGroupWithUnknownGroup() throws Exception { assertThat(cut.previousGroup(groupUnknown), is(groupA)); }
### Question: GroupList { public ResultGroup nextGroup(ResultGroup currentGroup) { int index = groups.indexOf(currentGroup); index = boundsCheckedIndex(++index); return groups.get(index); } GroupList(); GroupList(DefaultListModel<ResultGroup> mappedListModel); void populateList(Collection<ResultGroup> groupsToAdd); int groupCount(); void remove(Result result); ResultGroup getGroup(long hash); List<ResultGroup> getAllGroups(); void setMappedListModel(DefaultListModel<ResultGroup> mappedListeModel); ResultGroup nextGroup(ResultGroup currentGroup); ResultGroup previousGroup(ResultGroup currentGroup); }### Answer: @Test public void testNextGroup() throws Exception { assertThat(cut.nextGroup(groupA), is(groupB)); } @Test public void testNextGroupWithLastGroup() throws Exception { assertThat(cut.nextGroup(groupB), is(groupB)); } @Test public void testNextGroupWithUnknownGroup() throws Exception { assertThat(cut.nextGroup(groupUnknown), is(groupA)); }
### Question: Result { public ImageRecord getImageRecord() { return imageRecord; } Result(ResultGroup parentGroup, ImageRecord imageRecord); ImageRecord getImageRecord(); void remove(); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); }### Answer: @Test public void testGetImageRecord() throws Exception { assertThat(cut.getImageRecord(), is(imageRecord)); }
### Question: StringUtil { public static String sanitizeTag(String tagFromGui) { if (tagFromGui == null || "".equals(tagFromGui)) { return MATCH_ALL_TAGS; } return tagFromGui; } private StringUtil(); static String sanitizeTag(String tagFromGui); static final String MATCH_ALL_TAGS; }### Answer: @Test public void testSanitizeTag() throws Exception { assertThat(StringUtil.sanitizeTag(TEST_TAG), is(TEST_TAG)); } @Test public void testSanitizeTagNull() throws Exception { assertThat(StringUtil.sanitizeTag(null), is(StringUtil.MATCH_ALL_TAGS)); } @Test public void testSanitizeTagEmpty() throws Exception { assertThat(StringUtil.sanitizeTag(""), is(StringUtil.MATCH_ALL_TAGS)); }
### Question: Result { public void remove() { LOGGER.debug("Removing result {}", this); parentGroup.remove(this); } Result(ResultGroup parentGroup, ImageRecord imageRecord); ImageRecord getImageRecord(); void remove(); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); }### Answer: @Test public void testRemoveResult() throws Exception { cut.remove(); verify(parentGroup).remove(cut); }
### Question: ResultGroup { public long getHash() { return hash; } ResultGroup(GroupList parent, long hash, Collection<ImageRecord> records); long getHash(); List<Result> getResults(); boolean remove(Result result); boolean remove(Result result, boolean notifyParent); @Override String toString(); boolean hasResults(); @Override final int hashCode(); @Override final boolean equals(Object obj); }### Answer: @Test public void testGetHash() throws Exception { assertThat(cut.getHash(), is(HASH)); }
### Question: ResultGroup { public List<Result> getResults() { return results; } ResultGroup(GroupList parent, long hash, Collection<ImageRecord> records); long getHash(); List<Result> getResults(); boolean remove(Result result); boolean remove(Result result, boolean notifyParent); @Override String toString(); boolean hasResults(); @Override final int hashCode(); @Override final boolean equals(Object obj); }### Answer: @Test public void testGetResults() throws Exception { assertThat(cut.getResults(), hasItems(resultA, new Result(cut, recordB))); }
### Question: ResultGroup { public boolean remove(Result result) { return remove(result, true); } ResultGroup(GroupList parent, long hash, Collection<ImageRecord> records); long getHash(); List<Result> getResults(); boolean remove(Result result); boolean remove(Result result, boolean notifyParent); @Override String toString(); boolean hasResults(); @Override final int hashCode(); @Override final boolean equals(Object obj); }### Answer: @Test public void testRemove() throws Exception { assertThat(cut.remove(resultA), is(true)); } @Test public void testRemoveNonExistingResult() throws Exception { cut.remove(resultA); assertThat(cut.remove(resultA), is(false)); } @Test public void testNotifyParentOnResultRemoval() throws Exception { cut.remove(resultA); verify(parent).remove(resultA); } @Test public void testRemoveWithoutNotification() throws Exception { cut.remove(resultA, false); verify(parent, never()).remove(resultA); }
### Question: ResultGroup { public boolean hasResults() { return !results.isEmpty(); } ResultGroup(GroupList parent, long hash, Collection<ImageRecord> records); long getHash(); List<Result> getResults(); boolean remove(Result result); boolean remove(Result result, boolean notifyParent); @Override String toString(); boolean hasResults(); @Override final int hashCode(); @Override final boolean equals(Object obj); }### Answer: @Test public void testHasResults() throws Exception { assertThat(cut.hasResults(), is(true)); }
### Question: ResultGroup { @Override public String toString() { return String.format("%d (%d)", this.hash, results.size()); } ResultGroup(GroupList parent, long hash, Collection<ImageRecord> records); long getHash(); List<Result> getResults(); boolean remove(Result result); boolean remove(Result result, boolean notifyParent); @Override String toString(); boolean hasResults(); @Override final int hashCode(); @Override final boolean equals(Object obj); }### Answer: @Test public void testToString() throws Exception { assertThat(cut.toString(), is("42 (2)")); }
### Question: ImageRecord implements Comparable<ImageRecord> { public String getPath() { return path; } @Deprecated ImageRecord(); ImageRecord(String path, long pHash); String getPath(); long getpHash(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(ImageRecord o); @Override String toString(); static final String PATH_COLUMN_NAME; }### Answer: @Test public void testGetPath() throws Exception { assertThat(imageRecord.getPath(), is("foo")); }
### Question: ImageRecord implements Comparable<ImageRecord> { public long getpHash() { return pHash; } @Deprecated ImageRecord(); ImageRecord(String path, long pHash); String getPath(); long getpHash(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(ImageRecord o); @Override String toString(); static final String PATH_COLUMN_NAME; }### Answer: @Test public void testGetpHash() throws Exception { assertThat(imageRecord.getpHash(), is(42L)); }
### Question: ImageRecord implements Comparable<ImageRecord> { @Override public int compareTo(ImageRecord o) { if (o == null) { throw new NullPointerException(); } if (this.pHash == o.getpHash()) { return 0; } else if (this.getpHash() > o.pHash) { return 1; } else { return -1; } } @Deprecated ImageRecord(); ImageRecord(String path, long pHash); String getPath(); long getpHash(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(ImageRecord o); @Override String toString(); static final String PATH_COLUMN_NAME; }### Answer: @Test public void testCompareToSelf() throws Exception { assertThat(imageRecord.compareTo(imageRecord), is(0)); } @Test(expected = NullPointerException.class) public void testCompareToNull() throws Exception { imageRecord.compareTo(null); } @Test public void testCompareToBigger() throws Exception { assertThat(imageRecord.compareTo(new ImageRecord("bar", 55)), is(-1)); } @Test public void testCompareToSmaller() throws Exception { assertThat(imageRecord.compareTo(new ImageRecord("bar", 7)), is(1)); } @Test public void testCompareToEqual() throws Exception { assertThat(imageRecord.compareTo(new ImageRecord("bar", 42)), is(0)); }
### Question: ImageRecord implements Comparable<ImageRecord> { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ImageRecord other = (ImageRecord) obj; if (pHash != other.pHash) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; return true; } @Deprecated ImageRecord(); ImageRecord(String path, long pHash); String getPath(); long getpHash(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(ImageRecord o); @Override String toString(); static final String PATH_COLUMN_NAME; }### Answer: @Test public void testEquals() throws Exception { EqualsVerifier.forClass(ImageRecord.class).suppress(Warning.NONFINAL_FIELDS).verify(); }
### Question: ImageRecord implements Comparable<ImageRecord> { @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("ImageRecord"); sb.append("{"); sb.append("path:"); sb.append(path); sb.append(","); sb.append("hash:"); sb.append(pHash); sb.append("}"); return sb.toString(); } @Deprecated ImageRecord(); ImageRecord(String path, long pHash); String getPath(); long getpHash(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(ImageRecord o); @Override String toString(); static final String PATH_COLUMN_NAME; }### Answer: @Test public void testToString() throws Exception { assertThat(imageRecord.toString(), is(EXPECTED_TO_STRING)); }
### Question: BadFileRecord { public String getPath() { return path; } @Deprecated BadFileRecord(); BadFileRecord(Path path); String getPath(); }### Answer: @Test public void testGetPath() throws Exception { assertThat(badFileRecord.getPath(), is("bad")); }
### Question: RepositoryException extends Exception { public final String getMessage() { return message; } RepositoryException(String message, Throwable cause); RepositoryException(String message); final String getMessage(); final Throwable getCause(); }### Answer: @Test public void testRepositoryExceptionStringThrowableMessage() throws Exception { cut = new RepositoryException(TEST_MESSAGE, testException); assertThat(cut.getMessage(), is(TEST_MESSAGE)); } @Test public void testRepositoryExceptionStringMessage() throws Exception { cut = new RepositoryException(TEST_MESSAGE); assertThat(cut.getMessage(), is(TEST_MESSAGE)); }
### Question: RepositoryException extends Exception { public final Throwable getCause() { return cause; } RepositoryException(String message, Throwable cause); RepositoryException(String message); final String getMessage(); final Throwable getCause(); }### Answer: @Test public void testRepositoryExceptionStringThrowableCause() throws Exception { cut = new RepositoryException(TEST_MESSAGE, testException); assertThat(cut.getCause(), is(testException)); } @Test public void testRepositoryExceptionStringCause() throws Exception { cut = new RepositoryException(TEST_MESSAGE); assertThat(cut.getCause(), nullValue()); }
### Question: OrmliteRepositoryFactory implements RepositoryFactory { @Override public FilterRepository buildFilterRepository() throws RepositoryException { return new OrmliteFilterRepository(filterRecordDao, thumbnailDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildImageRepository(); @Override TagRepository buildTagRepository(); @Override PendingHashImageRepository buildPendingHashImageRepository(); @Override IgnoreRepository buildIgnoreRepository(); }### Answer: @Test public void testBuildFilterRepository() throws Exception { FilterRepository fr = cut.buildFilterRepository(); fr.store(new FilterRecord(0, new Tag(TEST_STRING))); }
### Question: OrmliteRepositoryFactory implements RepositoryFactory { @Override public ImageRepository buildImageRepository() throws RepositoryException { return new OrmliteImageRepository(imageRecordDao, ignoreDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildImageRepository(); @Override TagRepository buildTagRepository(); @Override PendingHashImageRepository buildPendingHashImageRepository(); @Override IgnoreRepository buildIgnoreRepository(); }### Answer: @Test public void testBuildImageRepository() throws Exception { ImageRepository ir = cut.buildImageRepository(); ir.store(new ImageRecord(TEST_STRING, 0)); }
### Question: OrmliteRepositoryFactory implements RepositoryFactory { @Override public TagRepository buildTagRepository() throws RepositoryException { return new OrmliteTagRepository(tagDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildImageRepository(); @Override TagRepository buildTagRepository(); @Override PendingHashImageRepository buildPendingHashImageRepository(); @Override IgnoreRepository buildIgnoreRepository(); }### Answer: @Test public void testBuildTagRepository() throws Exception { TagRepository tr = cut.buildTagRepository(); tr.store(new Tag(TEST_STRING)); }
### Question: OrmliteRepositoryFactory implements RepositoryFactory { @Override public PendingHashImageRepository buildPendingHashImageRepository() throws RepositoryException { return new OrmlitePendingHashImage(pendingDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildImageRepository(); @Override TagRepository buildTagRepository(); @Override PendingHashImageRepository buildPendingHashImageRepository(); @Override IgnoreRepository buildIgnoreRepository(); }### Answer: @Test public void testBuildPendingImageRepository() throws Exception { PendingHashImageRepository phir = cut.buildPendingHashImageRepository(); phir.store(new PendingHashImage(TEST_STRING, 0, 0)); }
### Question: OrmliteRepositoryFactory implements RepositoryFactory { @Override public IgnoreRepository buildIgnoreRepository() throws RepositoryException { return new OrmliteIgnoreRepository(ignoreDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildImageRepository(); @Override TagRepository buildTagRepository(); @Override PendingHashImageRepository buildPendingHashImageRepository(); @Override IgnoreRepository buildIgnoreRepository(); }### Answer: @Test public void testBuildIgnoreRepository() throws Exception { IgnoreRepository ir = cut.buildIgnoreRepository(); ir.store(new IgnoreRecord(new ImageRecord(TEST_STRING, 0))); }
### Question: OrmlitePendingHashImage implements PendingHashImageRepository { @Override public synchronized boolean store(PendingHashImage image) throws RepositoryException { try { if (pendingDao.queryForMatchingArgs(image).isEmpty()) { pendingDao.create(image); return true; } else { return false; } } catch (SQLException e) { throw new RepositoryException("Failed to store entry", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integer> pendingDao); @Override synchronized boolean store(PendingHashImage image); @Override boolean exists(PendingHashImage image); @Override List<PendingHashImage> getAll(); @Override PendingHashImage getByUUID(long most, long least); @Override void remove(PendingHashImage image); }### Answer: @Test public void testStoreQueryDatabase() throws Exception { cut.store(newEntry); assertThat(dao.queryForMatchingArgs(newEntry), hasSize(1)); } @Test public void testStoreReturnValue() throws Exception { assertThat(cut.store(newEntry), is(true)); } @Test public void testStoreDuplicate() throws Exception { assertThat(cut.store(existingEntry), is(false)); }
### Question: ExtendedAttribute implements ExtendedAttributeQuery { public static boolean supportsExtendedAttributes(Path path) { try { return Files.getFileStore(path).supportsFileAttributeView(UserDefinedFileAttributeView.class); } catch (IOException e) { LOGGER.debug("Failed to check extended attributes via FileStore ({}) for {}, falling back to write test...", e.toString(), path); return checkSupportWithWrite(path); } } static String createName(String... names); static boolean supportsExtendedAttributes(Path path); static void deleteExtendedAttribute(Path path, String name); static void setExtendedAttribute(Path path, String name, String value); static void setExtendedAttribute(Path path, String name, ByteBuffer value); static ByteBuffer readExtendedAttribute(Path path, String name); static String readExtendedAttributeAsString(Path path, String name); static boolean isExtendedAttributeSet(Path path, String name); @Override boolean isEaSupported(Path path); static final String SIMILARIMAGE_NAMESPACE; }### Answer: @Test public void testSupportsExtendedAttributes() throws Exception { assertThat(ExtendedAttribute.supportsExtendedAttributes(tempFile), is(true)); } @Test public void testSupportsExtendedAttributesNoFile() throws Exception { assertThat(ExtendedAttribute.supportsExtendedAttributes(Jimfs.newFileSystem().getPath("noEAsupport")), is(false)); }
### Question: OrmlitePendingHashImage implements PendingHashImageRepository { @Override public boolean exists(PendingHashImage image) throws RepositoryException { try { if (pendingDao.refresh(image) == 0) { return !pendingDao.queryForMatching(image).isEmpty(); } else { return true; } } catch (SQLException e) { throw new RepositoryException("Failed to lookup entry", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integer> pendingDao); @Override synchronized boolean store(PendingHashImage image); @Override boolean exists(PendingHashImage image); @Override List<PendingHashImage> getAll(); @Override PendingHashImage getByUUID(long most, long least); @Override void remove(PendingHashImage image); }### Answer: @Test public void testExistsById() throws Exception { assertThat(cut.exists(existingEntry), is(true)); } @Test public void testExistsByPath() throws Exception { assertThat(cut.exists(new PendingHashImage(EXISTING_PATH, UUID_EXISTING)), is(true)); } @Test public void testExistsNotFound() throws Exception { assertThat(cut.exists(newEntry), is(false)); }
### Question: OrmlitePendingHashImage implements PendingHashImageRepository { @Override public List<PendingHashImage> getAll() throws RepositoryException { try { return pendingDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query for all entries", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integer> pendingDao); @Override synchronized boolean store(PendingHashImage image); @Override boolean exists(PendingHashImage image); @Override List<PendingHashImage> getAll(); @Override PendingHashImage getByUUID(long most, long least); @Override void remove(PendingHashImage image); }### Answer: @Test public void testGetAll() throws Exception { dao.create(newEntry); assertThat(cut.getAll(), containsInAnyOrder(newEntry, existingEntry)); }
### Question: OrmlitePendingHashImage implements PendingHashImageRepository { @Override public PendingHashImage getByUUID(long most, long least) throws RepositoryException { try { synchronized (uuidQuery) { mostParam.setValue(most); leastParam.setValue(least); return pendingDao.queryForFirst(uuidQuery); } } catch (SQLException e) { throw new RepositoryException("Failed to get entry by id", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integer> pendingDao); @Override synchronized boolean store(PendingHashImage image); @Override boolean exists(PendingHashImage image); @Override List<PendingHashImage> getAll(); @Override PendingHashImage getByUUID(long most, long least); @Override void remove(PendingHashImage image); }### Answer: @Test public void testGetByUuidNonExisting() throws Exception { assertThat(cut.getByUUID(UUID_NEW.getMostSignificantBits(), UUID_NEW.getLeastSignificantBits()), is(nullValue())); } @Test public void testGetByUuidExisting() throws Exception { assertThat(cut.getByUUID(UUID_EXISTING.getMostSignificantBits(), UUID_EXISTING.getLeastSignificantBits()), is(existingEntry)); }
### Question: OrmlitePendingHashImage implements PendingHashImageRepository { @Override public void remove(PendingHashImage image) throws RepositoryException { try { pendingDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove entry", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integer> pendingDao); @Override synchronized boolean store(PendingHashImage image); @Override boolean exists(PendingHashImage image); @Override List<PendingHashImage> getAll(); @Override PendingHashImage getByUUID(long most, long least); @Override void remove(PendingHashImage image); }### Answer: @Test public void testRemove() throws Exception { assertThat(dao.queryForSameId(existingEntry), is(notNullValue())); cut.remove(existingEntry); assertThat(dao.queryForSameId(existingEntry), is(nullValue())); }
### Question: OrmliteImageRepository implements ImageRepository { @Override public void store(ImageRecord image) throws RepositoryException { try { imageDao.createOrUpdate(image); } catch (SQLException e) { throw new RepositoryException("Failed to store image", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); }### Answer: @Test public void testStore() throws Exception { cut.store(imageNew); assertThat(imageDao.queryForId(pathNew), is(imageNew)); }
### Question: SeedPeers implements PeerDiscovery { public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); InetSocketAddress getPeer(); InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit); void shutdown(); static int[] seedAddrs; }### Answer: @Test public void getPeer_one() throws Exception{ SeedPeers seedPeers = new SeedPeers(NetworkParameters.prodNet()); assertThat(seedPeers.getPeer(), notNullValue()); } @Test public void getPeer_all() throws Exception{ SeedPeers seedPeers = new SeedPeers(NetworkParameters.prodNet()); for(int i = 0; i < SeedPeers.seedAddrs.length; ++i){ assertThat("Failed on index: "+i, seedPeers.getPeer(), notNullValue()); } assertThat(seedPeers.getPeer(), equalTo(null)); }
### Question: Address extends VersionedChecksummedBytes { public byte[] getHash160() { return bytes; } Address(NetworkParameters params, byte[] hash160); Address(NetworkParameters params, String address); byte[] getHash160(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); static final int LENGTH; }### Answer: @Test public void decoding() throws Exception { Address a = new Address(testParams, "n4eA2nbYqErp7H6jebchxAN59DmNpksexv"); assertEquals("fda79a24e50ff70ff42f7d89585da5bd19d9e5cc", Utils.bytesToHexString(a.getHash160())); Address b = new Address(prodParams, "LQz2pJYaeqntA9BFB8rDX5AL2TTKGd5AuN"); assertEquals("3f2ebb6c8d88e586b551303d2c29eba15518d8d1", Utils.bytesToHexString(b.getHash160())); }
### Question: Address extends VersionedChecksummedBytes { public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return new Address(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } Address(NetworkParameters params, byte[] hash160); Address(NetworkParameters params, String address); byte[] getHash160(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); static final int LENGTH; }### Answer: @Test public void getNetwork() throws Exception { NetworkParameters params = Address.getParametersFromAddress("LQz2pJYaeqntA9BFB8rDX5AL2TTKGd5AuN"); assertEquals(NetworkParameters.prodNet().getId(), params.getId()); params = Address.getParametersFromAddress("n4eA2nbYqErp7H6jebchxAN59DmNpksexv"); assertEquals(NetworkParameters.testNet().getId(), params.getId()); }
### Question: Block extends Message { public BigInteger getWork() throws VerificationException { BigInteger target = getDifficultyTargetAsInteger(); return LARGEST_HASH.divide(target.add(BigInteger.ONE)); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); static final int HEADER_SIZE; static final int MAX_BLOCK_SIZE; static final int MAX_BLOCK_SIGOPS; }### Answer: @Test public void testWork() throws Exception { BigInteger work = params.genesisBlock.getWork(); assertEquals(BigInteger.valueOf(536879104L), work); }