method2testcases
stringlengths
118
6.63k
### Question: OrmliteImageRepository implements ImageRepository { @Override public ImageRecord getByPath(Path path) throws RepositoryException { try { return imageDao.queryForId(path.toString()); } catch (SQLException e) { throw new RepositoryException("Failed to query for path", 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 testGetByPathExists() throws Exception { assertThat(cut.getByPath(Paths.get(pathExisting)), is(imageExisting)); } @Test public void testGetByPathNotFound() throws Exception { assertThat(cut.getByPath(Paths.get(pathNew)), is(nullValue())); }
### Question: OrmliteImageRepository implements ImageRepository { @Override public synchronized List<ImageRecord> startsWithPath(Path directory) throws RepositoryException { argStartsWithPath.setValue(directory.toString() + STRING_QUERY_WILDCARD); try { return imageDao.query(queryStartsWithPath); } catch (SQLException e) { throw new RepositoryException("Failed to query for starts with path", 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 testStartsWithPath() throws Exception { assertThat(cut.startsWithPath(Paths.get("exi")), containsInAnyOrder(imageExisting)); }
### Question: OrmliteImageRepository implements ImageRepository { @Override public void remove(ImageRecord image) throws RepositoryException { try { imageDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove 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 testRemoveImageRecord() throws Exception { cut.remove(imageExisting); assertThat(imageDao.queryForMatching(imageExisting), hasSize(0)); } @Test public void testRemoveImageRecordCollection() throws Exception { imageDao.create(imageNew); List<ImageRecord> toRemove = new LinkedList<ImageRecord>(); toRemove.add(imageExisting); toRemove.add(imageNew); assertThat(imageDao.queryForAll(), hasSize(2)); cut.remove(toRemove); assertThat(imageDao.queryForMatching(imageExisting), hasSize(0)); }
### Question: OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAll() throws RepositoryException { try { return imageDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query all", 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 testGetAll() throws Exception { imageDao.create(imageNew); assertThat(cut.getAll(), containsInAnyOrder(imageExisting, imageNew)); }
### Question: OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", 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 testGetAllWithoutIgnored() throws Exception { imageDao.create(imageNew); List<ImageRecord> result = cut.getAllWithoutIgnored(); assertThat(result, hasItem(imageNew)); assertThat(result, hasSize(1)); } @Test public void testGetAllWithoutIgnoredPath() throws Exception { imageDao.create(imageNew); List<ImageRecord> result = cut.getAllWithoutIgnored(Paths.get(pathNew)); assertThat(result, hasItem(imageNew)); assertThat(result, hasSize(1)); } @Test public void testGetAllWithoutIgnoredPathNoMatch() throws Exception { imageDao.create(imageNew); List<ImageRecord> result = cut.getAllWithoutIgnored(Paths.get(pathExisting)); assertThat(result, is(empty())); }
### Question: ExtendedAttribute implements ExtendedAttributeQuery { public static void setExtendedAttribute(Path path, String name, String value) throws IOException { setExtendedAttribute(path, name, StandardCharsets.US_ASCII.encode(value)); } 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 testSetExtendedAttributePathStringString() throws Exception { ExtendedAttribute.setExtendedAttribute(tempFile, TEST_NAME, TEST_VALUE); }
### Question: OrmliteTagRepository implements TagRepository { @Override public synchronized Tag getByName(String name) throws RepositoryException { try { nameArg.setValue(name); return tagDao.queryForFirst(nameQuery); } catch (SQLException e) { throw new RepositoryException("Failed to query by name", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); }### Answer: @Test public void testGetByName() throws Exception { Tag result = cut.getByName(TAG_EXSTING); assertThat(result, is(tagExsting)); }
### Question: OrmliteTagRepository implements TagRepository { @Override public void store(Tag tag) throws RepositoryException { try { tagDao.createOrUpdate(tag); } catch (SQLException e) { throw new RepositoryException("Failed to store", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); }### Answer: @Test public void testStore() throws Exception { cut.store(tagNew); Tag result = cut.getByName(TAG_NEW); assertThat(result, is(tagNew)); } @Test(expected = RepositoryException.class) public void testStoreDuplicate() throws Exception { cut.store(tagNew); cut.store(new Tag(TAG_NEW)); }
### Question: OrmliteTagRepository implements TagRepository { @Override public void remove(Tag tag) throws RepositoryException { try { tagDao.delete(tag); } catch (SQLException e) { throw new RepositoryException("Failed to delete", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); }### Answer: @Test public void testRemove() throws Exception { cut.remove(tagExsting); Tag result = cut.getByName(TAG_EXSTING); assertThat(result, is(nullValue())); }
### Question: OrmliteTagRepository implements TagRepository { @Override public List<Tag> getAll() throws RepositoryException { try { return tagDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query all", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); }### Answer: @Test public void testGetAll() throws Exception { List<Tag> results = cut.getAll(); assertThat(results, containsInAnyOrder(tagContext, tagExsting)); }
### Question: OrmliteTagRepository implements TagRepository { @Override public List<Tag> getWithContext() throws RepositoryException { try { return tagDao.queryForMatching(new Tag(null, true)); } catch (SQLException e) { throw new RepositoryException("Failed to query by context flag", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); }### Answer: @Test public void testGetWithContext() throws Exception { List<Tag> results = cut.getWithContext(); assertThat(results, containsInAnyOrder(tagContext)); }
### Question: OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByHash(long hash) throws RepositoryException { try { return filterDao.queryForMatching(new FilterRecord(hash, null, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); }### Answer: @Test public void testGetByHash() throws Exception { List<FilterRecord> filters = cut.getByHash(HASH_TWO); assertThat(filters, containsInAnyOrder(new FilterRecord(HASH_TWO, TAG_TWO, null))); } @Test(expected = RepositoryException.class) public void testGetByHashException() throws Exception { deleteFilterTable(); cut.getByHash(HASH_TWO); }
### Question: OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByTag(Tag tag) throws RepositoryException { try { return filterDao.queryForMatchingArgs(new FilterRecord(0, tag, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by tag", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); }### Answer: @Test public void testGetByTag() throws Exception { List<FilterRecord> filters = cut.getByTag(TAG_ONE); assertThat(filters, containsInAnyOrder(new FilterRecord(HASH_ONE, TAG_ONE, null))); } @Test(expected = RepositoryException.class) public void testGetByTagException() throws Exception { deleteFilterTable(); cut.getByTag(TAG_ONE); }
### Question: ExtendedAttribute implements ExtendedAttributeQuery { public static String readExtendedAttributeAsString(Path path, String name) throws IOException { ByteBuffer buffer = readExtendedAttribute(path, name); return StandardCharsets.US_ASCII.decode(buffer).toString(); } 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 testReadExtendedAttributeAsString() throws Exception { ExtendedAttribute.setExtendedAttribute(tempFile, TEST_NAME, TEST_VALUE); assertThat(ExtendedAttribute.readExtendedAttributeAsString(tempFile, TEST_NAME), is(TEST_VALUE)); }
### Question: OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getAll() throws RepositoryException { try { return filterDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to get all filters", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); }### Answer: @Test public void testGetAll() throws Exception { List<FilterRecord> filters = cut.getAll(); assertThat(filters, containsInAnyOrder(allFilters.toArray(new FilterRecord[0]))); } @Test(expected = RepositoryException.class) public void testGetAllException() throws Exception { deleteFilterTable(); cut.getAll(); }
### Question: OrmliteFilterRepository implements FilterRepository { @Override public void store(FilterRecord toStore) throws RepositoryException { if (toStore.hasThumbnail()) { checkAndCreateThumbnail(toStore); } try { if (filterDao.queryForMatchingArgs(toStore).isEmpty()) { filterDao.create(toStore); } } catch (SQLException e) { throw new RepositoryException(STORE_FILTER_ERROR_MSG, e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); }### Answer: @Test(expected = RepositoryException.class) public void testStoreThumbnailException() throws Exception { TableUtils.dropTable(cs, Thumbnail.class, false); cut.store(new FilterRecord(HASH_NEW_THUMBNAIL, TAG_ONE, newThumbnail)); } @Test(expected = RepositoryException.class) public void testStoreFilterException() throws Exception { TableUtils.dropTable(cs, FilterRecord.class, false); cut.store(new FilterRecord(HASH_NEW_THUMBNAIL, TAG_ONE, null)); }
### Question: OrmliteFilterRepository implements FilterRepository { @Override public void remove(FilterRecord filter) throws RepositoryException { try { filterDao.delete(filter); } catch (SQLException e) { throw new RepositoryException("Failed to remove Filter", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); }### Answer: @Test public void testRemove() throws Exception { FilterRecord toRemove = allFilters.get(0); cut.remove(toRemove); assertThat(cut.getAll(), not(hasItem(toRemove))); }
### Question: OrmliteIgnoreRepository implements IgnoreRepository { @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); }### Answer: @Test public void testStoreNew() throws Exception { cut.store(newIgnore); assertThat(dao.queryForAll(), hasItem(newIgnore)); } @Test public void testStoreDuplicate() throws Exception { cut.store(existingIgnore); assertThat(dao.queryForAll(), hasSize(1)); } @Test public void testStoreNewSize() throws Exception { cut.store(newIgnore); assertThat(dao.queryForAll(), hasSize(2)); }
### Question: OrmliteIgnoreRepository implements IgnoreRepository { @Override public void remove(IgnoreRecord toRemove) throws RepositoryException { try { ignoreDao.delete(toRemove); } catch (SQLException e) { throw new RepositoryException("Failed to delete ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); }### Answer: @Test public void testRemove() throws Exception { cut.remove(existingIgnore); assertThat(dao.queryForAll(), not(hasItem(existingIgnore))); } @Test public void testRemoveSize() throws Exception { cut.remove(existingIgnore); assertThat(dao.queryForAll(), is(empty())); }
### Question: ExtendedAttribute implements ExtendedAttributeQuery { public static boolean isExtendedAttributeSet(Path path, String name) throws IOException { return createUserDefinedFileAttributeView(path).list().contains(name); } 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 testExtendedAttributeIsNotSet() throws Exception { assertThat(ExtendedAttribute.isExtendedAttributeSet(tempFile, TEST_NAME), is(false)); }
### Question: OrmliteIgnoreRepository implements IgnoreRepository { @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); }### Answer: @Test public void testFindByPathPath() throws Exception { assertThat(cut.findByPath(toPath(PATH_A)), is(existingIgnore)); } @Test public void testFindByPathPathNotFound() throws Exception { assertThat(cut.findByPath(toPath(PATH_B)), is(nullValue())); } @Test public void testFindByPathString() throws Exception { assertThat(cut.findByPath(PATH_A), is(existingIgnore)); }
### Question: OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); }### Answer: @Test public void testFindByPathStringNotFound() throws Exception { assertThat(cut.isPathIgnored(PATH_B), is(false)); } @Test public void testIsPathIgnoredString() throws Exception { assertThat(cut.isPathIgnored(PATH_A), is(true)); } @Test public void testIsPathIgnoredStringNope() throws Exception { assertThat(cut.isPathIgnored(PATH_B), is(false)); } @Test public void testIsPathIgnoredPath() throws Exception { assertThat(cut.isPathIgnored(toPath(PATH_A)), is(true)); }
### Question: OrmliteIgnoreRepository implements IgnoreRepository { @Override public List<IgnoreRecord> getAll() throws RepositoryException { try { return ignoreDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query for all ingored images: " + e.toString(), e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); }### Answer: @Test public void testGetAll() throws Exception { dao.create(newIgnore); assertThat(cut.getAll(), containsInAnyOrder(newIgnore, existingIgnore)); }
### Question: Tag { @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Tag)) { return false; } Tag other = (Tag) obj; if (contextMenu != other.contextMenu) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } return true; } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); static final String NAME_FIELD_NAME; }### Answer: @Test public void testEquals() throws Exception { EqualsVerifier.forClass(Tag.class).withIgnoredFields("userTagId") .suppress(Warning.NONFINAL_FIELDS).verify();; }
### Question: Tag { public final String getTag() { return tag; } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); static final String NAME_FIELD_NAME; }### Answer: @Test public void testTagStringName() throws Exception { assertThat(cut.getTag(), is(TEST_TAG)); }
### Question: ExtendedAttribute implements ExtendedAttributeQuery { public static String createName(String... names) { StringBuilder sb = new StringBuilder(SIMILARIMAGE_NAMESPACE); for (String name : names) { sb.append("."); sb.append(name); } return sb.toString(); } 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 testCreateName() throws Exception { assertThat(ExtendedAttribute.createName("foo", "bar"), is(ExtendedAttribute.SIMILARIMAGE_NAMESPACE + ".foo.bar")); }
### Question: Tag { public final boolean isContextMenu() { return contextMenu; } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); static final String NAME_FIELD_NAME; }### Answer: @Test public void testTagStringContextMenu() throws Exception { assertThat(cut.isContextMenu(), is(false)); }
### Question: Tag { public boolean isMatchAll() { return StringUtil.MATCH_ALL_TAGS.equals(tag); } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); static final String NAME_FIELD_NAME; }### Answer: @Test public void testIsMatchAll() throws Exception { assertThat(cut.isMatchAll(), is(false)); } @Test public void testIsMatchAllAsterisk() throws Exception { cut = new Tag(StringUtil.MATCH_ALL_TAGS); assertThat(cut.isMatchAll(), is(true)); }
### Question: SQLiteDatabase implements Database { @Override public ConnectionSource getCs() { return connectionSource; } SQLiteDatabase(); SQLiteDatabase(Path dbPath); SQLiteDatabase(String dbPath); @Override ConnectionSource getCs(); @Override void close(); }### Answer: @Test public void testGetCs() throws Exception { assertThat(cut.getCs().isOpen(EMPTY_STRING), is(true)); }
### Question: SQLiteDatabase implements Database { @Override public void close() { connectionSource.closeQuietly(); } SQLiteDatabase(); SQLiteDatabase(Path dbPath); SQLiteDatabase(String dbPath); @Override ConnectionSource getCs(); @Override void close(); }### Answer: @Ignore("Closing a closed connection when using pooled connections results in NPE") @Test public void testClose() throws Exception { ConnectionSource cs = cut.getCs(); assertThat(cs.isOpen(EMPTY_STRING), is(true)); cut.close(); assertThat(cs.isOpen(EMPTY_STRING), is(false)); }
### Question: FilterRecord { public long getpHash() { return pHash; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); }### Answer: @Test public void testGetpHash() throws Exception { assertThat(filterRecord.getpHash(), is(HASH_ONE)); }
### Question: FilterRecord { public void setpHash(long pHash) { this.pHash = pHash; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); }### Answer: @Test public void testSetpHash() throws Exception { assertThat(GUARD_MSG, filterRecord.getpHash(), is(HASH_ONE)); filterRecord.setpHash(HASH_TWO); assertThat(filterRecord.getpHash(), is(HASH_TWO)); }
### Question: FilterRecord { public Tag getTag() { return tag; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); }### Answer: @Test public void testGetReason() throws Exception { assertThat(filterRecord.getTag(), is(TEST_TAG_ONE)); }
### Question: FilterRecord { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } FilterRecord other = (FilterRecord) obj; if (pHash != other.pHash) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } if (thumbnail == null) { if (other.thumbnail != null) { return false; } } else if (!thumbnail.equals(other.thumbnail)) { return false; } return true; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); }### Answer: @Test public void testEqualsIsEqual() throws Exception { FilterRecord other = new FilterRecord(HASH_ONE, TEST_TAG_ONE, null); assertThat(filterRecord.equals(other), is(true)); } @Test public void testEquals() throws Exception { EqualsVerifier.forClass(FilterRecord.class).withIgnoredFields("id").suppress(Warning.NONFINAL_FIELDS).verify(); }
### Question: ExtendedAttributeDirectoryCache implements ExtendedAttributeQuery { @Override public boolean isEaSupported(Path path) { Path parent = path.getParent(); if (path.getRoot() != null && path.equals(path.getRoot())) { parent = path; } if (parent == null) { return false; } return eaSupport.getUnchecked(parent); } @Inject ExtendedAttributeDirectoryCache(ExtendedAttributeQuery eaQuery); ExtendedAttributeDirectoryCache(ExtendedAttributeQuery eaQuery, int expireTime, TimeUnit expireUnit); @Override boolean isEaSupported(Path path); }### Answer: @Test public void testIsEaSupportedUseCache() throws Exception { assertThat(cut.isEaSupported(subDirectory), is(true)); when(eaQuery.isEaSupported(any(Path.class))).thenReturn(false); assertThat(cut.isEaSupported(subDirectory), is(true)); } @Test public void testIsEaSupportedExpireCache() throws Exception { cut = new ExtendedAttributeDirectoryCache(eaQuery, 1, TimeUnit.MICROSECONDS); assertThat(cut.isEaSupported(subDirectory), is(true)); when(eaQuery.isEaSupported(any(Path.class))).thenReturn(false); assertThat(cut.isEaSupported(subDirectory), is(false)); } @Test public void testIsEaSupportedRootParent() throws Exception { assertThat(cut.isEaSupported(rootDirectory), is(true)); } @Test public void testIsEaSupportedRoot() throws Exception { assertThat(cut.isEaSupported(root), is(true)); } @Test public void testIsEaSupportedNoParent() throws Exception { assertThat(cut.isEaSupported(relative), is(false)); }
### Question: FilterRecord { public static List<FilterRecord> getTags(FilterRepository repository, Tag tag) throws RepositoryException { if (tag.isMatchAll()) { return repository.getAll(); } else { return repository.getByTag(tag); } } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); }### Answer: @Test public void testGetTags() throws Exception { FilterRecord.getTags(filterRepository, TEST_TAG_ONE); verify(filterRepository).getByTag(TEST_TAG_ONE); } @Test public void testGetTagsAllTags() throws Exception { FilterRecord.getTags(filterRepository, new Tag(StringUtil.MATCH_ALL_TAGS)); verify(filterRepository).getAll(); }
### Question: IgnoreRecord { public ImageRecord getImage() { return image; } @Deprecated IgnoreRecord(); IgnoreRecord(ImageRecord image); ImageRecord getImage(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static final String IMAGEPATH_FIELD_NAME; }### Answer: @Test public void testGetPathAsString() throws Exception { assertThat(cut.getImage(), is(IMAGE)); }
### Question: IgnoreRecord { @Override public boolean equals(Object obj) { if (obj instanceof IgnoreRecord) { IgnoreRecord other = (IgnoreRecord) obj; return Objects.equals(this.image, other.image); } return false; } @Deprecated IgnoreRecord(); IgnoreRecord(ImageRecord image); ImageRecord getImage(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static final String IMAGEPATH_FIELD_NAME; }### Answer: @Test public void testEquals() throws Exception { assertThat(cut.equals(new IgnoreRecord(IMAGE)), is(true)); }
### Question: MainSettingValidator { public static void validate(MainSetting mainSetting) throws IllegalArgumentException { if (mainSetting.threads() < 1) { throw new IllegalArgumentException("Thread number must be greater than zero"); } } private MainSettingValidator(); static void validate(MainSetting mainSetting); }### Answer: @Test public void testValidatePositiveThread() throws Exception { MainSettingValidator.validate(mainSetting); } @Test(expected = IllegalArgumentException.class) public void testValidateZeroThread() throws Exception { when(mainSetting.threads()).thenReturn(0); MainSettingValidator.validate(mainSetting); } @Test(expected = IllegalArgumentException.class) public void testValidateNegativeThread() throws Exception { when(mainSetting.threads()).thenReturn(-1); MainSettingValidator.validate(mainSetting); }
### Question: HashingHandler implements HashHandler { @Override public boolean handle(Path file) { LOGGER.trace("Handling {} with {}", file, HashingHandler.class.getSimpleName()); ImageHashJob job = new ImageHashJob(file, hasher, imageRepository, statistics); job.setHashAttribute(hashAttribute); threadPool.execute(job); return true; } HashingHandler(ExecutorService threadPool, ImagePHash hasher, ImageRepository imageRepository, Statistics statistics, HashAttribute hashAttribute); @Override boolean handle(Path file); }### Answer: @Test public void testHandleAlwaysTrue() throws Exception { assertThat(cut.handle(testPath), is(true)); } @Test public void testHandleJobIsExecuted() throws Exception { cut.handle(testPath); verify(threadPool).execute(any(ImageHashJob.class)); }
### Question: ExtendedAttributeHandler implements HashHandler { @Override public boolean handle(Path file) { LOGGER.trace("Handling {} with {}", file, ExtendedAttributeHandler.class.getSimpleName()); if (eaQuery.isEaSupported(file)) { try { if (ExtendedAttribute.isExtendedAttributeSet(file, CORRUPT_EA_NAMESPACE)) { LOGGER.trace("{} is corrupt", file); return true; } } catch (IOException e1) { LOGGER.error("Failed to read attributes from {}", file); } if (hashAttribute.areAttributesValid(file)) { LOGGER.trace("{} has valid extended attributes", file); try { imageRepository.store(new ImageRecord(file.toString(), hashAttribute.readHash(file))); LOGGER.trace("Successfully read and stored the hash for {}", file); return true; } catch (InvalidAttributeValueException | IOException e) { LOGGER.error("Failed to read extended attribute from {} ({})", file, e.toString()); } catch (RepositoryException e) { LOGGER.error("Failed to access database for {} ({})", file, e.toString()); } } } return false; } ExtendedAttributeHandler(HashAttribute hashAttribute, ImageRepository imageRepository, ExtendedAttributeQuery eaQuery); @Override boolean handle(Path file); static final String CORRUPT_EA_NAMESPACE; }### Answer: @Test public void testHandleFileHasHash() throws Exception { assertThat(cut.handle(testFile), is(true)); } @Test public void testHandleFileHasNoHash() throws Exception { when(hashAttribute.areAttributesValid(testFile)).thenReturn(false); assertThat(cut.handle(testFile), is(false)); } @Test public void testHandleDbError() throws Exception { Mockito.doThrow(RepositoryException.class).when(imageRepository).store(any(ImageRecord.class)); assertThat(cut.handle(testFile), is(false)); } @Test public void testHandleFileReadError() throws Exception { when(hashAttribute.readHash(testFile)).thenThrow(new IOException()); assertThat(cut.handle(testFile), is(false)); } @Test public void testHandleAttributeError() throws Exception { when(hashAttribute.readHash(testFile)).thenThrow(new InvalidAttributeValueException()); assertThat(cut.handle(testFile), is(false)); } @Test public void testHandleCorruptFileIsHandled() throws Exception { when(eaQuery.isEaSupported(testFile)).thenReturn(true); when(hashAttribute.areAttributesValid(testFile)).thenReturn(false); ExtendedAttribute.setExtendedAttribute(testFile, ExtendedAttributeHandler.CORRUPT_EA_NAMESPACE, ""); assertThat(cut.handle(testFile), is(true)); }
### Question: DatabaseHandler implements HashHandler { @Override public boolean handle(Path file) { LOGGER.trace("Handling {} with {}", file, ExtendedAttributeHandler.class.getSimpleName()); try { if (isInDatabase(file)) { LOGGER.trace("{} was found in the database"); statistics.incrementSkippedFiles(); statistics.incrementProcessedFiles(); return true; } } catch (RepositoryException e) { LOGGER.error("Failed to check the database for {} ({})", file, e.toString()); } return false; } DatabaseHandler(ImageRepository imageRepository, Statistics statistics); @Override boolean handle(Path file); }### Answer: @Test public void testHandleFileFoundGood() throws Exception { when(imageRepository.getByPath(testFile)).thenReturn(existingImage); assertThat(cut.handle(testFile), is(true)); } @Test public void testHandleFileNotFound() throws Exception { assertThat(cut.handle(testFile), is(false)); } @Test public void testHandleDatabaseError() throws Exception { when(imageRepository.getByPath(testFile)).thenThrow(new RepositoryException("test")); assertThat(cut.handle(testFile), is(false)); }
### Question: ExtendedAttributeUpdateHandler implements HashHandler { @Override public boolean handle(Path file) { if (!hashAttribute.areAttributesValid(file)) { try { long hash = hasher.getLongHash(Files.newInputStream(file)); hashAttribute.writeHash(file, hash); } catch (IOException e) { LOGGER.warn("Failed to hash {}, {}", file, e.toString()); return false; } } return true; } ExtendedAttributeUpdateHandler(HashAttribute hashAttribute, ImagePHash hasher); @Override boolean handle(Path file); }### Answer: @Test public void testHandleValidExtendedAttribute() throws Exception { when(hashAttribute.areAttributesValid(testFile)).thenReturn(true); assertThat(cut.handle(testFile), is(true)); } @Test public void testHandleInvalidExtendedAttribute() throws Exception { when(hashAttribute.areAttributesValid(testFile)).thenReturn(false); assertThat(cut.handle(testFile), is(true)); } @Test public void testHandleIOError() throws Exception { when(hashAttribute.areAttributesValid(testFile)).thenReturn(false); when(hasher.getLongHash(any(InputStream.class))).thenThrow(new IOException()); assertThat(cut.handle(testFile), is(false)); }
### Question: IgnoredImageQueryStage implements Function<Path, List<ImageRecord>> { @Override public List<ImageRecord> apply(Path path) { List<ImageRecord> result = Collections.emptyList(); try { if (path == null || Paths.get("").equals(path)) { result = imageRepository.getAllWithoutIgnored(); } else { result = imageRepository.getAllWithoutIgnored(path); } } catch (RepositoryException e) { LOGGER.error("Failed to query non-ignored images: {}, cause: {}", e.toString(), e.getCause()); } return result; } IgnoredImageQueryStage(ImageRepository imageRepository); @Override List<ImageRecord> apply(Path path); }### Answer: @Test public void testQueryForNull() throws Exception { cut.apply(null); verify(imageRepository).getAllWithoutIgnored(); } @Test public void testQueryForEmpty() throws Exception { cut.apply(Paths.get("")); verify(imageRepository).getAllWithoutIgnored(); } @Test public void testQueryForPath() throws Exception { cut.apply(PATH); verify(imageRepository).getAllWithoutIgnored(PATH); } @Test public void testRepositoryError() throws Exception { when(imageRepository.getAllWithoutIgnored()).thenThrow(new RepositoryException("")); assertThat(cut.apply(null), is(empty())); }
### Question: ImageQueryStage implements Function<Path, List<ImageRecord>> { @Override public List<ImageRecord> apply(Path path) { List<ImageRecord> result = Collections.emptyList(); try { if (path == null || Paths.get("").equals(path)) { result = imageRepository.getAll(); } else { result = imageRepository.startsWithPath(path); } } catch (RepositoryException e) { LOGGER.error("Failed to query images: {}, cause: {}", e.toString(), e.getCause()); } return result; } ImageQueryStage(ImageRepository imageRepository); @Override List<ImageRecord> apply(Path path); }### Answer: @Test public void testQueryForNull() throws Exception { cut.apply(null); verify(imageRepository).getAll(); } @Test public void testQueryForEmpty() throws Exception { cut.apply(Paths.get("")); verify(imageRepository).getAll(); } @Test public void testQueryForPath() throws Exception { cut.apply(PATH); verify(imageRepository).startsWithPath(PATH); } @Test public void testRepositoryError() throws Exception { when(imageRepository.getAll()).thenThrow(new RepositoryException("")); assertThat(cut.apply(null), is(empty())); }
### Question: ImageQueryPipeline implements Function<Path, Multimap<Long, ImageRecord>> { @Override public Multimap<Long, ImageRecord> apply(Path path) { List<ImageRecord> images = imageQueryStage.apply(path); Multimap<Long, ImageRecord> groups = imageGrouper.apply(images); return postProcessing(groups); } ImageQueryPipeline(Function<Path, List<ImageRecord>> imageQueryStage, Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> imageGrouper, Collection<Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>>> postProcessingStages); @Override Multimap<Long, ImageRecord> apply(Path path); Collection<Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>>> getPostProcessingStages(); Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> getImageGrouper(); }### Answer: @Test public void testQueryExecuted() throws Exception { verify(imageQueryStage).apply(any()); } @Test public void testGroupingExecuted() throws Exception { verify(grouper).apply(images); } @Test public void testPostprocessingAExecuted() throws Exception { verify(postProcessingStageA).apply(groups); } @Test public void testPostprocessingBExecuted() throws Exception { verify(postProcessingStageB).apply(groups); } @Test public void testPipelineReturnsGroups() throws Exception { assertThat(cut.apply(null), is(groups)); }
### Question: ImageQueryPipeline implements Function<Path, Multimap<Long, ImageRecord>> { public Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> getImageGrouper() { return imageGrouper; } ImageQueryPipeline(Function<Path, List<ImageRecord>> imageQueryStage, Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> imageGrouper, Collection<Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>>> postProcessingStages); @Override Multimap<Long, ImageRecord> apply(Path path); Collection<Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>>> getPostProcessingStages(); Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> getImageGrouper(); }### Answer: @Test public void testGrouperInstance() throws Exception { assertThat(cut.getImageGrouper(), is(instanceOf(GroupImagesStage.class))); }
### Question: ImageQueryPipeline implements Function<Path, Multimap<Long, ImageRecord>> { public Collection<Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>>> getPostProcessingStages() { return ImmutableList.copyOf(postProcessingStages); } ImageQueryPipeline(Function<Path, List<ImageRecord>> imageQueryStage, Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> imageGrouper, Collection<Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>>> postProcessingStages); @Override Multimap<Long, ImageRecord> apply(Path path); Collection<Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>>> getPostProcessingStages(); Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> getImageGrouper(); }### Answer: @Test public void testGetPostProcessingStages() throws Exception { assertThat(cut.getPostProcessingStages(), hasSize(2)); }
### Question: GroupByTagStage implements Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> { @Override public Multimap<Long, ImageRecord> apply(Collection<ImageRecord> t) { Multimap<Long, ImageRecord> result = MultimapBuilder.hashKeys().hashSetValues().build(); rs.build(t); TagFilter tagFilter = new TagFilter(filterRepository); result = tagFilter.getFilterMatches(rs, tag, hammingDistance); return result; } GroupByTagStage(FilterRepository filterRepository, Tag tag, int hammingDistance); GroupByTagStage(FilterRepository filterRepository, Tag tag); @Override Multimap<Long, ImageRecord> apply(Collection<ImageRecord> t); }### Answer: @Test public void testGroupedByTag() throws Exception { assertThat(cut.apply(images).get(HASH_A), containsInAnyOrder(imageA)); } @Test public void testTagsWithDistance() throws Exception { cut = new GroupByTagStage(filterRepository, TAG, 1); assertThat(cut.apply(images).get(HASH_A), containsInAnyOrder(imageA, imageB)); } @Test public void testRepositoryError() throws Exception { when(filterRepository.getByTag(TAG)).thenThrow(new RepositoryException("")); assertThat(cut.apply(images), is(EMPTY_MAP)); }
### Question: ImageQueryPipelineBuilder { public ImageQueryPipeline build() { if (imageGrouper == null) { imageGrouper = new GroupImagesStage(hammingDistance); LOGGER.warn("No image group stage set, using {}", imageGrouper.getClass().getSimpleName()); } return new ImageQueryPipeline(imageQuery, imageGrouper, postProcessing); } ImageQueryPipelineBuilder(ImageRepository imageRepository, FilterRepository filterRepository); ImageQueryPipelineBuilder excludeIgnored(); ImageQueryPipelineBuilder excludeIgnored(boolean exclude); ImageQueryPipelineBuilder removeSingleImageGroups(); ImageQueryPipelineBuilder removeDuplicateGroups(); ImageQueryPipelineBuilder distance(int distance); ImageQueryPipelineBuilder groupByTag(Tag tag); ImageQueryPipelineBuilder groupAll(); ImageQueryPipeline build(); static ImageQueryPipelineBuilder newBuilder(ImageRepository imageRepository, FilterRepository filterRepository); }### Answer: @Test public void testImagesWithIgnore() throws Exception { cut.build().apply(null); verify(imageRepository).getAll(); }
### Question: ImageQueryPipelineBuilder { public ImageQueryPipelineBuilder removeSingleImageGroups() { this.postProcessing.add(new RemoveSingleImageSetStage()); return this; } ImageQueryPipelineBuilder(ImageRepository imageRepository, FilterRepository filterRepository); ImageQueryPipelineBuilder excludeIgnored(); ImageQueryPipelineBuilder excludeIgnored(boolean exclude); ImageQueryPipelineBuilder removeSingleImageGroups(); ImageQueryPipelineBuilder removeDuplicateGroups(); ImageQueryPipelineBuilder distance(int distance); ImageQueryPipelineBuilder groupByTag(Tag tag); ImageQueryPipelineBuilder groupAll(); ImageQueryPipeline build(); static ImageQueryPipelineBuilder newBuilder(ImageRepository imageRepository, FilterRepository filterRepository); }### Answer: @Test public void testRemoveSingleImageGroups() throws Exception { assertThat(cut.removeSingleImageGroups().build().getPostProcessingStages(), hasItem(instanceOf(RemoveSingleImageSetStage.class))); }
### Question: ImageQueryPipelineBuilder { public ImageQueryPipelineBuilder removeDuplicateGroups() { this.postProcessing.add(new RemoveDuplicateSetStage()); return this; } ImageQueryPipelineBuilder(ImageRepository imageRepository, FilterRepository filterRepository); ImageQueryPipelineBuilder excludeIgnored(); ImageQueryPipelineBuilder excludeIgnored(boolean exclude); ImageQueryPipelineBuilder removeSingleImageGroups(); ImageQueryPipelineBuilder removeDuplicateGroups(); ImageQueryPipelineBuilder distance(int distance); ImageQueryPipelineBuilder groupByTag(Tag tag); ImageQueryPipelineBuilder groupAll(); ImageQueryPipeline build(); static ImageQueryPipelineBuilder newBuilder(ImageRepository imageRepository, FilterRepository filterRepository); }### Answer: @Test public void testRemoveDuplicateGroups() throws Exception { assertThat(cut.removeDuplicateGroups().build().getPostProcessingStages(), hasItem(instanceOf(RemoveDuplicateSetStage.class))); }
### Question: ImageQueryPipelineBuilder { public static ImageQueryPipelineBuilder newBuilder(ImageRepository imageRepository, FilterRepository filterRepository) { return new ImageQueryPipelineBuilder(imageRepository, filterRepository); } ImageQueryPipelineBuilder(ImageRepository imageRepository, FilterRepository filterRepository); ImageQueryPipelineBuilder excludeIgnored(); ImageQueryPipelineBuilder excludeIgnored(boolean exclude); ImageQueryPipelineBuilder removeSingleImageGroups(); ImageQueryPipelineBuilder removeDuplicateGroups(); ImageQueryPipelineBuilder distance(int distance); ImageQueryPipelineBuilder groupByTag(Tag tag); ImageQueryPipelineBuilder groupAll(); ImageQueryPipeline build(); static ImageQueryPipelineBuilder newBuilder(ImageRepository imageRepository, FilterRepository filterRepository); }### Answer: @Test public void testNewBuilder() throws Exception { assertThat(ImageQueryPipelineBuilder.newBuilder(imageRepository, filterRepository), is(instanceOf(ImageQueryPipelineBuilder.class))); }
### Question: ImageQueryPipelineBuilder { public ImageQueryPipelineBuilder groupAll() { this.imageGrouper = new GroupImagesStage(hammingDistance); return this; } ImageQueryPipelineBuilder(ImageRepository imageRepository, FilterRepository filterRepository); ImageQueryPipelineBuilder excludeIgnored(); ImageQueryPipelineBuilder excludeIgnored(boolean exclude); ImageQueryPipelineBuilder removeSingleImageGroups(); ImageQueryPipelineBuilder removeDuplicateGroups(); ImageQueryPipelineBuilder distance(int distance); ImageQueryPipelineBuilder groupByTag(Tag tag); ImageQueryPipelineBuilder groupAll(); ImageQueryPipeline build(); static ImageQueryPipelineBuilder newBuilder(ImageRepository imageRepository, FilterRepository filterRepository); }### Answer: @Test public void testGroupAll() throws Exception { ImageQueryPipeline pipeline = cut.groupAll().build(); assertThat(pipeline.getImageGrouper(), is(instanceOf(GroupImagesStage.class))); }
### Question: RemoveDuplicateSetStage implements Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>> { @Override public Multimap<Long, ImageRecord> apply(Multimap<Long, ImageRecord> toPrune) { DuplicateUtil.removeDuplicateSets(toPrune); return toPrune; } @Override Multimap<Long, ImageRecord> apply(Multimap<Long, ImageRecord> toPrune); }### Answer: @Test public void testRemoveDuplicateGroups() throws Exception { cut.apply(testMap); assertThat(testMap.containsKey(HASH_C), is(false)); } @Test public void testParameterReturned() throws Exception { assertThat(cut.apply(testMap), is(sameInstance(testMap))); }
### Question: RemoveSingleImageSetStage implements Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>> { @Override public Multimap<Long, ImageRecord> apply(Multimap<Long, ImageRecord> toPrune) { DuplicateUtil.removeSingleImageGroups(toPrune); return toPrune; } @Override Multimap<Long, ImageRecord> apply(Multimap<Long, ImageRecord> toPrune); }### Answer: @Test public void testRemoveSingleImageGroup() throws Exception { cut.apply(testMap); assertThat(testMap.containsKey(HASH_A), is(false)); } @Test public void testParameterReturned() throws Exception { assertThat(cut.apply(testMap), is(sameInstance(testMap))); }
### Question: GroupImagesStage implements Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> { @Override public Multimap<Long, ImageRecord> apply(Collection<ImageRecord> toGroup) { Multimap<Long, ImageRecord> resultMap = MultimapBuilder.hashKeys().hashSetValues().build(); rs.build(toGroup); Stopwatch sw = Stopwatch.createStarted(); toGroup.forEach(new Consumer<ImageRecord>() { @Override public void accept(ImageRecord t) { resultMap.putAll(t.getpHash(), rs.distanceMatch(t.getpHash(), hammingDistance).values()); } }); LOGGER.info("Built result map with {} pairs in {}, using hamming distance {}", resultMap.size(), sw, hammingDistance); return resultMap; } GroupImagesStage(); GroupImagesStage(int hammingDistance); @Override Multimap<Long, ImageRecord> apply(Collection<ImageRecord> toGroup); int getHammingDistance(); }### Answer: @Test public void testNoDuplicatesInGroup() throws Exception { assertThat(cut.apply(images).get(HASH_B), hasSize(1)); } @Test public void testSortedByHash() throws Exception { assertThat(cut.apply(images).get(HASH_A), hasItem(imageA)); } @Test public void testHammingDistance() throws Exception { cut = new GroupImagesStage(1); assertThat(cut.apply(images).get(HASH_B), hasItems(imageA, imageB)); }
### Question: HashAttribute { public void writeHash(Path path, long hash) { try { ExtendedAttribute.setExtendedAttribute(path, hashFQN, Long.toHexString(hash)); ExtendedAttribute.setExtendedAttribute(path, timestampFQN, Long.toString(Files.getLastModifiedTime(path).toMillis())); } catch (IOException e) { LOGGER.warn("Failed to write hash to file {} ({})", path, e.toString()); } } 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 testWrittenHashValue() throws Exception { cut.writeHash(tempFile, TEST_VALUE); assertThat(Long.parseUnsignedLong(ExtendedAttribute.readExtendedAttributeAsString(tempFile, testHashFullName), HEXADECIMAL_RADIX), is(TEST_VALUE)); } @Test public void testWrittenTimeStamp() throws Exception { cut.writeHash(tempFile, TEST_VALUE); long timestamp = Files.getLastModifiedTime(tempFile).toMillis(); assertThat(Long.parseUnsignedLong(ExtendedAttribute.readExtendedAttributeAsString(tempFile, timestampFullName)), is(allOf(greaterThan(timestamp - TIMESTAMP_TOLERANCE), lessThan(timestamp + TIMESTAMP_TOLERANCE)))); }
### Question: DCTKernel extends Kernel { public synchronized double[] transformDCT(double[] matrix) { for (int i = 0; i < matrixArea; i++) { this.matrix[i] = matrix[i]; } execute(range); return Doubles.concat(result); } DCTKernel(); DCTKernel(int matrixSize); void setDevice(Device device); @Override void run(); synchronized double[] transformDCT(double[] matrix); static final int DEFAULT_MATRIX_SIZE; }### Answer: @Test public void testTransformDCT() throws Exception { double[] result = cut.transformDCT(Doubles.concat(testMatrix)); assertArrayEquals(EXPECTED, Doubles.concat(result), 0.1); } @Test public void testTransformDCT2() throws Exception { double[] result = cut.transformDCT(Doubles.concat(testMatrix2)); assertArrayEquals(EXPECTED2, Doubles.concat(result), 0.1); }
### Question: GroupImagesStage implements Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> { public int getHammingDistance() { return hammingDistance; } GroupImagesStage(); GroupImagesStage(int hammingDistance); @Override Multimap<Long, ImageRecord> apply(Collection<ImageRecord> toGroup); int getHammingDistance(); }### Answer: @Test public void testGetHammingDistance() throws Exception { cut = new GroupImagesStage(DISTANCE); assertThat(cut.getHammingDistance(), is(DISTANCE)); } @Test public void testDefaultDistance() throws Exception { assertThat(cut.getHammingDistance(), is(0)); }
### Question: GroupListPopulator implements Runnable { @Override public void run() { this.logger.info("Populating group list with {} groups", groups.groupCount()); groupListModel.clear(); List<ResultGroup> resultGroups = groups.getAllGroups(); Collections.sort(resultGroups, new Comparator<ResultGroup>() { @Override public int compare(ResultGroup o1, ResultGroup o2) { return Long.compare(o1.getHash(), o2.getHash()); } }); for (ResultGroup g : resultGroups) { groupListModel.addElement(g); } this.logger.info("Finished populating group list"); } GroupListPopulator(GroupList groups, DefaultListModel<ResultGroup> groupListModel); @Override void run(); }### Answer: @Test public void testElementsAddedInOrder() { glp.run(); List<ResultGroup> testList = Lists.reverse(results); InOrder inOrder = inOrder(dlm); for (ResultGroup rg : testList) { inOrder.verify(dlm).addElement(rg); } } @Test public void testElementsAdded() { glp.run(); for (ResultGroup rg : results) { verify(dlm).addElement(rg); } }
### Question: TagFilter { public Multimap<Long, ImageRecord> getFilterMatches(RecordSearch recordSearch, Tag tagToMatch, int hammingDistance) { Multimap<Long, ImageRecord> uniqueGroups = MultimapBuilder.hashKeys().hashSetValues().build(); List<FilterRecord> matchingFilters = Collections.emptyList(); try { matchingFilters = FilterRecord.getTags(filterRepository, tagToMatch); LOGGER.info("Found {} filters for tag {}", matchingFilters.size(), tagToMatch.getTag()); } catch (RepositoryException e) { LOGGER.error("Failed to query hashes for tag {}, reason: {}, cause: {}", tagToMatch.getTag(), e.toString(), e.getCause()); } Multimap<Long, ImageRecord> parallelGroups = Multimaps.synchronizedMultimap(uniqueGroups); matchingFilters.parallelStream().forEach(filter -> { Multimap<Long, ImageRecord> match = recordSearch.distanceMatch(filter.getpHash(), hammingDistance); parallelGroups.putAll(filter.getpHash(), match.values()); }); return uniqueGroups; } TagFilter(FilterRepository filterRepository); Multimap<Long, ImageRecord> getFilterMatches(RecordSearch recordSearch, Tag tagToMatch, int hammingDistance); }### Answer: @Test public void testRepositoryException() throws Exception { when(filterRepository.getAll()).thenThrow(new RepositoryException("just testing!")); assertThat(cut.getFilterMatches(recordSearch, TAG_ALL, DISTANCE), is(emptyMultimap)); } @Test public void testMatchingTag() throws Exception { assertThat(cut.getFilterMatches(recordSearch, TAG, DISTANCE).get(1L), hasItem(image1)); } @Test public void testMatchingTagSecondImageNotIncluded() throws Exception { assertThat(cut.getFilterMatches(recordSearch, TAG, DISTANCE).get(1L), not(hasItem(image2))); }
### Question: NamedThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread thread = defaultThreadFactory.newThread(r); thread.setName(threadPrefix + " thread " + threadNumber); threadNumber++; return thread; } NamedThreadFactory(String threadPrefix); @Override Thread newThread(Runnable r); }### Answer: @Test public void testNewThread() throws Exception { Thread t = ntf.newThread(runnableMock); assertThat(t.getName(), is("test thread 0")); } @Test public void testNewThreadTwo() throws Exception { ntf.newThread(runnableMock); Thread t2 = ntf.newThread(runnableMock); assertThat(t2.getName(), is("test thread 1")); }
### Question: ImageFindJobVisitor extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (isAcceptedFile(file)) { statistics.incrementFoundFiles(); fileCount++; boolean isHandled = false; for (HashHandler handler : handlers) { if (handler.handle(file)) { isHandled = true; break; } } statistics.incrementProcessedFiles(); if (!isHandled) { statistics.incrementFailedFiles(); LOGGER.error("No handler was able to process {}", file); } } return FileVisitResult.CONTINUE; } ImageFindJobVisitor(Filter<Path> fileFilter, Collection<HashHandler> handlers, Statistics statistics); @Override FileVisitResult visitFile(Path file, BasicFileAttributes attrs); @Deprecated int getFileCount(); }### Answer: @Test public void testVisitFileOkProcessedFiles() throws Exception { cut.visitFile(path, attrs); assertThat(statistics.getProcessedFiles(), is(1)); } @Test public void testVisitFileOkFailedFiles() throws Exception { cut.visitFile(path, attrs); assertThat(statistics.getFailedFiles(), is(0)); } @Test public void testVisitNotHandled() throws Exception { when(handler.handle(path)).thenReturn(false); cut.visitFile(path, attrs); assertThat(statistics.getFailedFiles(), is(1)); }
### Question: ImageFindJobVisitor extends SimpleFileVisitor<Path> { @Deprecated public int getFileCount() { return fileCount; } ImageFindJobVisitor(Filter<Path> fileFilter, Collection<HashHandler> handlers, Statistics statistics); @Override FileVisitResult visitFile(Path file, BasicFileAttributes attrs); @Deprecated int getFileCount(); }### Answer: @Test public void testGetFileCount() throws Exception { cut.visitFile(path, attrs); assertThat(cut.getFileCount(), is(1)); }
### Question: ImageHashJob implements Runnable { @Override public void run() { try { long hash = processFile(image); if (hashAttribute != null) { hashAttribute.writeHash(image, hash); } } catch (IIOException e) { LOGGER.warn("Failed to process image {} (IIO Error): {}", image, e.toString()); LOGGER.debug(EXCEPTION_STACKTRACE, image, e); statistics.incrementFailedFiles(); } catch (IOException e) { LOGGER.warn("Failed to load file {}: {}", image, e.toString()); statistics.incrementFailedFiles(); } catch (RepositoryException e) { LOGGER.warn("Failed to query repository for {}: {}", image, e.toString()); statistics.incrementFailedFiles(); } catch (ArrayIndexOutOfBoundsException e) { LOGGER.error("Failed to process image {}: {}", image, e.toString()); LOGGER.debug(EXCEPTION_STACKTRACE, image, e); statistics.incrementFailedFiles(); } } ImageHashJob(Path image, ImagePHash hasher, ImageRepository imageRepository, Statistics statistics); final void setHashAttribute(HashAttribute hashAttribute); @Override void run(); }### Answer: @Test public void testRunAddFile() throws Exception { imageLoadJob.run(); verify(imageRepository).store(new ImageRecord(testImage.toString(), 0)); } @Test public void testRunIIOException() throws Exception { when(phw.getLongHash(any(InputStream.class))).thenThrow(IIOException.class); imageLoadJob.run(); verify(statistics).incrementFailedFiles(); }
### Question: DuplicateUtil { public static Multimap<Long, ImageRecord> groupByHash(Collection<ImageRecord> dbRecords) { Multimap<Long, ImageRecord> groupedByHash = MultimapBuilder.hashKeys().hashSetValues().build(); logger.info("Grouping records by hash..."); for (ImageRecord ir : dbRecords) { groupedByHash.put(ir.getpHash(), ir); } logger.info("{} records, in {} groups", dbRecords.size(), groupedByHash.keySet().size()); return groupedByHash; } 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 testGroupByHashNumberOfGroups() throws Exception { Multimap<Long, ImageRecord> group = DuplicateUtil.groupByHash(records); assertThat(group.keySet().size(), is(10)); } @Test public void testGroupByHashSizeOfGroup() throws Exception { Multimap<Long, ImageRecord> group = DuplicateUtil.groupByHash(records); assertThat(group.get(5L).size(), is(3)); } @Test public void testGroupByHashEntryPath() throws Exception { Multimap<Long, ImageRecord> group = DuplicateUtil.groupByHash(records); assertThat(group.get(2L), hasItem(new ImageRecord("foo", 2L))); }
### 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: HashAttribute { public boolean areAttributesValid(Path path) { try { return ExtendedAttribute.isExtendedAttributeSet(path, hashFQN) && verifyTimestamp(path); } catch (IOException e) { LOGGER.error("Failed to check hash for {} ({})", path, e.toString()); } return false; } 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 testAreAttributesValidNoHashOrTimestamp() throws Exception { assertThat(cut.areAttributesValid(tempFile), is(false)); } @Test public void testAreAttributesValidHashButNoTimestamp() throws Exception { ExtendedAttribute.setExtendedAttribute(tempFile, testHashFullName, Long.toString(TEST_VALUE)); assertThat(cut.areAttributesValid(tempFile), is(false)); } @Test public void testAreAttributesValidHashAndModifiedFile() throws Exception { ExtendedAttribute.setExtendedAttribute(tempFile, testHashFullName, Long.toString(TEST_VALUE)); long timestamp = Files.getLastModifiedTime(tempFile).toMillis(); timestamp += TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS); ExtendedAttribute.setExtendedAttribute(tempFile, timestampFullName, Long.toString(timestamp)); assertThat(cut.areAttributesValid(tempFile), is(false)); } @Test public void testAreAttributesValidHashAndTimestampBefore() throws Exception { ExtendedAttribute.setExtendedAttribute(tempFile, testHashFullName, Long.toString(TEST_VALUE)); long timestamp = Files.getLastModifiedTime(tempFile).toMillis(); timestamp -= TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS); ExtendedAttribute.setExtendedAttribute(tempFile, timestampFullName, Long.toString(timestamp)); assertThat(cut.areAttributesValid(tempFile), is(false)); } @Test public void testAreAttributesValidHashAndTimestampOK() throws Exception { ExtendedAttribute.setExtendedAttribute(tempFile, testHashFullName, Long.toString(TEST_VALUE)); long timestamp = Files.getLastModifiedTime(tempFile).toMillis(); ExtendedAttribute.setExtendedAttribute(tempFile, timestampFullName, Long.toString(timestamp)); assertThat(cut.areAttributesValid(tempFile), is(true)); }
### 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: RecordSearch { public Multimap<Long, ImageRecord> distanceMatch(long hash, long hammingDistance) { Multimap<Long, ImageRecord> searchResult = MultimapBuilder.hashKeys().hashSetValues().build(); Set<Long> resultKeys = bkTree.searchWithin(hash, (double) hammingDistance); for (Long key : resultKeys) { searchResult.putAll(key, imagesGroupedByHash.get(key)); } return searchResult; } RecordSearch(); void build(Collection<ImageRecord> dbRecords); List<Long> exactMatch(); Multimap<Long, ImageRecord> distanceMatch(long hash, long hammingDistance); }### Answer: @Test public void testDistanceMatchRadius0Size() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 0L); assertThat(result.keySet().size(), is(1)); } @Test public void testDistanceMatchRadius0Hash() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 0L); assertThat(result.get(2L).size(), is(2)); } @Test public void testDistanceMatchRadius1Size() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 1L); assertThat(result.keySet().size(), is(3)); } @Test public void testDistanceMatchRadius1Hash2() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 1L); assertThat(result.containsKey(2L), is(true)); } @Test public void testDistanceMatchRadius1Hash3() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 1L); assertThat(result.containsKey(3L), is(true)); } @Test public void testDistanceMatchRadius1Hash6() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 1L); assertThat(result.containsKey(6L), is(true)); } @Test public void testDistanceMatchRadius2Size() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 2L); assertThat(result.keySet().size(), is(4)); } @Test public void testDistanceMatchRadius2Hash1() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 2L); assertThat(result.containsKey(1L), is(true)); }
### 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 markAs(Result result, Tag tag) { try { markAs(result.getImageRecord(), tag); } catch (RepositoryException e) { logger.warn(FILTER_ADD_FAILED_MESSAGE, result.getImageRecord().getPath(), 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 testMarkAsNotInDb() throws Exception { List<Path> files = createTempTestFiles(1); Path file = files.get(0); dupOp.markAs(file, TAG_FOO); verify(imageRepository).getByPath(any(Path.class)); verify(filterRepository, never()).store(any(FilterRecord.class)); } @Test public void testMarkAsNoFilterExists() throws Exception { List<Path> files = createTempTestFiles(1); Path file = files.get(0); when(imageRepository.getByPath(file)).thenReturn(new ImageRecord(file.toString(), TEST_HASH)); dupOp.markAs(file, TAG_FOO); verify(filterRepository).store(fooFilter); } @Test public void testMarkAsDBerror() throws Exception { List<Path> files = createTempTestFiles(1); Path file = files.get(0); when(imageRepository.getByPath(file)).thenThrow(new RepositoryException("This is a test")); dupOp.markAs(file, TAG_FOO); verify(filterRepository, never()).store(any(FilterRecord.class)); } @Test public void testMarkAsFilterExists() throws Exception { List<Path> files = createTempTestFiles(1); Path file = files.get(0); when(imageRepository.getByPath(file)).thenReturn(new ImageRecord(file.toString(), 42)); dupOp.markAs(file, TAG_FOO); verify(filterRepository).store(new FilterRecord(42, TAG_FOO)); }
### Question: DuplicateOperations { public void markDirectoryAs(Path directory, Tag tag) { if (!isDirectory(directory)) { logger.warn("Directory {} not valid, aborting.", directory); return; } try { int addCount = 0; Iterator<Path> iter = Files.newDirectoryStream(directory).iterator(); while (iter.hasNext()) { Path current = iter.next(); if (Files.isRegularFile(current)) { markAs(current, tag); addCount++; } } logger.info("Added {} images from {} to filter list", addCount, directory); } catch (IOException e) { logger.error("Failed to add images to filter list, {}", e); } } @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 testMarkDirectory() throws Exception { createTempTestFiles(3); dupOp.markDirectoryAs(tempDirectory, TAG_FOO); verify(imageRepository, times(3)).getByPath(any(Path.class)); verify(filterRepository, never()).store(any(FilterRecord.class)); } @Test public void testMarkDirectoryNotAdirectory() throws Exception { List<Path> files = createTempTestFiles(3); Path file = files.get(0); dupOp.markDirectoryAs(file, TAG_FOO); verify(imageRepository, never()).getByPath(any(Path.class)); verify(filterRepository, never()).store(any(FilterRecord.class)); } @Test public void testMarkDirectoryDirectoryIsNull() throws Exception { createTempTestFiles(3); dupOp.markDirectoryAs(null, TAG_FOO); verify(imageRepository, never()).getByPath(any(Path.class)); verify(filterRepository, never()).store(any(FilterRecord.class)); } @Test public void testMarkDirectoryDirectoryNonExistantDirectory() throws Exception { createTempTestFiles(3); dupOp.markDirectoryAs(tempDirectory.resolve("foobar"), TAG_FOO); verify(imageRepository, never()).getByPath(any(Path.class)); verify(filterRepository, never()).store(any(FilterRecord.class)); }
### 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 List<ImageRecord> findMissingFiles(Path directory) { if (!isDirectory(directory)) { logger.error("Directory is null or missing, aborting"); return Collections.emptyList(); } if (!Files.exists(directory)) { logger.warn("Directory {} does not exist.", directory); } List<ImageRecord> records = Collections.emptyList(); try { records = imageRepository.startsWithPath(directory); } catch (RepositoryException e) { logger.error("Failed to get records from database: {}", e.toString()); } LinkedList<ImageRecord> toPrune = new LinkedList<>(); for (ImageRecord ir : records) { Path path = fileSystem.getPath(ir.getPath()); if (!Files.exists(path)) { toPrune.add(ir); } } logger.info("Found {} non-existant records", toPrune.size()); return toPrune; } @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 testFindMissingFiles() throws Exception { Path testFile = Files.createTempFile(tempDirectory, "findmissingfilestest", null); ImageRecord missingRecord = new ImageRecord(testFile.getParent().resolve("foo").toString(), 0); when(imageRepository.startsWithPath(tempDirectory)) .thenReturn(Arrays.asList(new ImageRecord(testFile.toString(), 0), missingRecord)); List<ImageRecord> missing = dupOp.findMissingFiles(tempDirectory); assertThat(missing, containsInAnyOrder(missingRecord)); }
### 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)); }