method2testcases
stringlengths 118
3.08k
|
---|
### Question:
IAMPolicyManager { public String getReadOnlyArn(SecretsGroupIdentifier group) { return getArn(group, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; }### Answer:
@Test public void testGetReadOnlyArn() throws Exception { String arn = partiallyMockedPolicyManager.getReadOnlyArn(group); assertEquals(arn, READONLY_POLICY_ARN); } |
### Question:
FileEncryptionContext implements EncryptionContext { @Override public Map<String, String> toMap() { return ImmutableMap.of( "0", FILE_VERSION, "1", groupIdentifier.region.getName(), "2", groupIdentifier.name); } FileEncryptionContext(SecretsGroupIdentifier groupIdentifier); @Override Map<String, String> toMap(); final SecretsGroupIdentifier groupIdentifier; }### Answer:
@Test public void testToMap() { FileEncryptionContext context = new FileEncryptionContext( new SecretsGroupIdentifier(Region.EU_WEST_1, "test.group") ); Map<String, String> map = context.toMap(); assertEquals(map.get("0"), "1"); assertEquals(map.get("1"), "eu-west-1"); assertEquals(map.get("2"), "test.group"); } |
### Question:
FilterGenerator { public static String convertNumberToLetters(int number) { int range = 'z'-'a' + 1; StringBuilder sb = new StringBuilder(); do { int last = number % range; sb.append(Character.toChars('a' + last)); number /= range; } while (number != 0); return sb.reverse().toString(); } FilterGenerator(int startCount); FilterGenerator(); Filter process(RSEF.ParsedAttributeCondition<Entry> attributeCondition, Converters converters); Filter createTerm(RSEF.TypedTerm<T> typedTerm, Converters converters); static String getOperator(RSEF.BinaryOpType binaryOpType); static Map<A, B> merge(Map<A, B> left, Map<A, B> right); static String convertNumberToLetters(int number); public int count; }### Answer:
@Test public void test() { assertThat(FilterGenerator.convertNumberToLetters(0), is("a")); assertThat(FilterGenerator.convertNumberToLetters(1), is("b")); assertThat(FilterGenerator.convertNumberToLetters(26-1), is("z")); assertThat(FilterGenerator.convertNumberToLetters(26), is("ba")); assertThat(FilterGenerator.convertNumberToLetters(26+1), is("bb")); assertThat(FilterGenerator.convertNumberToLetters(26*26-1), is("zz")); assertThat(FilterGenerator.convertNumberToLetters(26*26), is("baa")); assertThat(FilterGenerator.convertNumberToLetters(26*26+1), is("bab")); assertThat(FilterGenerator.convertNumberToLetters(26*26*26-1), is("zzz")); } |
### Question:
IAMPolicyName { @Override public String toString() { return String.format("%s_%s_%s_%s", AWSResourceNameSerialization.GLOBAL_PREFIX, group.region.getName(), AWSResourceNameSerialization.encodeSecretsGroupName(group.name), accessLevel); } IAMPolicyName(SecretsGroupIdentifier group, AccessLevel accessLevel); @Override String toString(); static IAMPolicyName fromString(String wrappedAWSResourceName); @Override boolean equals(final Object obj); final SecretsGroupIdentifier group; final AccessLevel accessLevel; }### Answer:
@Test public void testToString() throws Exception { assertEquals(adminPolicyName.toString(), adminPolicyAsString); assertEquals(readonlyPolicyName.toString(), readonlyPolicyAsString); } |
### Question:
IAMPolicyName { @Override public boolean equals(final Object obj) { if (obj instanceof IAMPolicyName) { final IAMPolicyName other = (IAMPolicyName) obj; return Objects.equal(group, other.group) && Objects.equal(accessLevel, other.accessLevel); } else { return false; } } IAMPolicyName(SecretsGroupIdentifier group, AccessLevel accessLevel); @Override String toString(); static IAMPolicyName fromString(String wrappedAWSResourceName); @Override boolean equals(final Object obj); final SecretsGroupIdentifier group; final AccessLevel accessLevel; }### Answer:
@Test public void testEquals() throws Exception { assertTrue(adminPolicyName.equals(new IAMPolicyName(group, AccessLevel.ADMIN))); assertTrue(readonlyPolicyName.equals(new IAMPolicyName(group, AccessLevel.READONLY))); assertFalse(adminPolicyName.equals(readonlyPolicyName)); assertFalse(adminPolicyName.equals( new IAMPolicyName(new SecretsGroupIdentifier(Region.EU_WEST_1, "test.group"), AccessLevel.ADMIN))); assertFalse(adminPolicyName.equals( new IAMPolicyName(new SecretsGroupIdentifier(Region.US_WEST_1, "test.group2"), AccessLevel.ADMIN))); } |
### Question:
UserConfig { public void addLocalFilePath(SecretsGroupIdentifier group, File path) { checkUniqueGroup(group); checkUniqueFilePath(path); localFiles.put(group, path); } UserConfig(@JsonProperty("localFiles") Map<SecretsGroupIdentifier, File> localFiles); UserConfig(); Map<SecretsGroupIdentifier, File> getMap(); Optional<File> getLocalFilePath(SecretsGroupIdentifier group); void addLocalFilePath(SecretsGroupIdentifier group, File path); void updateLocalFilePath(SecretsGroupIdentifier group, File path); void removeLocalFilePath(SecretsGroupIdentifier group); }### Answer:
@Test(expectedExceptions = AlreadyExistsException.class) public void addSamePathToConfig() { SecretsGroupIdentifier anotherGroup = new SecretsGroupIdentifier(Region.EU_CENTRAL_1, "test2.group"); userConfig.addLocalFilePath(EU_GROUP, new File("path-eu")); userConfig.addLocalFilePath(anotherGroup, new File("path-eu")); }
@Test(expectedExceptions = AlreadyExistsException.class) public void addSameGroupToConfigWithDifferentPath() { userConfig.addLocalFilePath(EU_GROUP, new File("path-eu")); userConfig.addLocalFilePath(EU_GROUP, new File("path-foobar")); } |
### Question:
FileUserConfig extends UserConfig { @Override public Optional<File> getLocalFilePath(SecretsGroupIdentifier group) { return Optional.ofNullable(localFiles.get(group)); } FileUserConfig(File configFile); @Override Optional<File> getLocalFilePath(SecretsGroupIdentifier group); @Override void addLocalFilePath(SecretsGroupIdentifier group, File path); @Override void updateLocalFilePath(SecretsGroupIdentifier group, File path); @Override void removeLocalFilePath(SecretsGroupIdentifier group); }### Answer:
@Test public void testGetLocalFilePath() throws Exception { assertEquals(fileUserConfig.getLocalFilePath(GROUP1_US), Optional.of(new File("uswest1-test-group.sm"))); assertEquals(fileUserConfig.getLocalFilePath(GROUP1_EU), Optional.of(new File("euwest1-test-group.sm"))); assertEquals(fileUserConfig.getLocalFilePath(GROUP2_EU), Optional.of(new File("euwest1-test-group2.sm"))); assertEquals(fileUserConfig.getLocalFilePath( new SecretsGroupIdentifier(Region.EU_CENTRAL_1, "test.group")), Optional.empty()); } |
### Question:
FileUserConfig extends UserConfig { @Override public void updateLocalFilePath(SecretsGroupIdentifier group, File path) { checkUniqueFilePath(path); localFiles.put(group, path); persist(); } FileUserConfig(File configFile); @Override Optional<File> getLocalFilePath(SecretsGroupIdentifier group); @Override void addLocalFilePath(SecretsGroupIdentifier group, File path); @Override void updateLocalFilePath(SecretsGroupIdentifier group, File path); @Override void removeLocalFilePath(SecretsGroupIdentifier group); }### Answer:
@Test public void testUpdateLocalFilePath() throws Exception { assertEquals(fileUserConfig.getLocalFilePath(GROUP1_US), Optional.of(new File("uswest1-test-group.sm"))); fileUserConfig.updateLocalFilePath(GROUP1_US, new File("some-other-file.sm")); assertEquals(fileUserConfig.getLocalFilePath(GROUP1_US), Optional.of(new File("some-other-file.sm"))); } |
### Question:
FileUserConfig extends UserConfig { @Override public void removeLocalFilePath(SecretsGroupIdentifier group) { localFiles.remove(group); persist(); } FileUserConfig(File configFile); @Override Optional<File> getLocalFilePath(SecretsGroupIdentifier group); @Override void addLocalFilePath(SecretsGroupIdentifier group, File path); @Override void updateLocalFilePath(SecretsGroupIdentifier group, File path); @Override void removeLocalFilePath(SecretsGroupIdentifier group); }### Answer:
@Test public void testRemoveLocalFilePath() throws Exception { fileUserConfig.removeLocalFilePath(GROUP1_EU); fileUserConfig.removeLocalFilePath(GROUP2_EU); assertEquals(fileUserConfig.getLocalFilePath(GROUP1_EU), Optional.empty()); assertEquals(fileUserConfig.getLocalFilePath(GROUP2_EU), Optional.empty()); assertEquals(fileUserConfig.getLocalFilePath(GROUP1_US), Optional.of(new File("uswest1-test-group.sm"))); } |
### Question:
AWSResourceNameSerialization { public static String decodeSecretsGroupName(String encoded) { return encoded.replace('-', '.'); } static String decodeSecretsGroupName(String encoded); static String encodeSecretsGroupName(String name); static final String GLOBAL_PREFIX; static final String GLOBAL_STRING_DELIMITER; }### Answer:
@Test public void testDecodeSecretsGroupName() { String decoded = AWSResourceNameSerialization.decodeSecretsGroupName("test-group-1"); assertEquals(decoded, "test.group.1"); } |
### Question:
AWSResourceNameSerialization { public static String encodeSecretsGroupName(String name) { return name.replace('.', '-'); } static String decodeSecretsGroupName(String encoded); static String encodeSecretsGroupName(String name); static final String GLOBAL_PREFIX; static final String GLOBAL_STRING_DELIMITER; }### Answer:
@Test public void testEncodeSecretsGroupName() { String encoded = AWSResourceNameSerialization.encodeSecretsGroupName("test.group.1"); assertEquals(encoded, "test-group-1"); assertEquals(AWSResourceNameSerialization.encodeSecretsGroupName( AWSResourceNameSerialization.decodeSecretsGroupName("test-group-1")), "test-group-1"); } |
### Question:
RawSecretEntry implements BestEffortShred { public String toJsonBlob() { try { return objectMapper.writeValueAsString(this); } catch (JsonProcessingException e) { throw new SerializationException("Failed to serialize secret entry to JSON blob", e); } } @Deprecated RawSecretEntry(); RawSecretEntry(@JsonProperty("secretIdentifier") SecretIdentifier secretIdentifier,
@JsonProperty("version") long version,
@JsonProperty("state") State state,
@JsonProperty("notBefore") Optional<ZonedDateTime> notBefore,
@JsonProperty("notAfter") Optional<ZonedDateTime> notAfter,
@JsonProperty("encryptedPayload") byte[] encryptedPayload); String toJsonBlob(); static RawSecretEntry fromJsonBlob(String jsonBlob); byte[] sha1OfEncryptionPayload(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override void bestEffortShred(); @PartitionKey(position=Config.KEY, padding = 128)
@JsonProperty("secretIdentifier")
public SecretIdentifier secretIdentifier; @SortKey(position=Config.VERSION)
@JsonProperty("version")
public Long version; @Attribute(position=Config.STATE)
@JsonProperty("state")
public State state; @Attribute(position=Config.NOT_BEFORE)
@JsonProperty("notBefore")
public Optional<ZonedDateTime> notBefore; @Attribute(position=Config.NOT_AFTER)
@JsonProperty("notAfter")
public Optional<ZonedDateTime> notAfter; @Attribute(position=Config.VALUE)
@JsonProperty("encryptedPayload")
public byte[] encryptedPayload; }### Answer:
@Test public void serialize() { String serialized = rawSecretEntry.toJsonBlob(); assertThat(serialized, is(jsonBlob)); } |
### Question:
RawSecretEntry implements BestEffortShred { public static RawSecretEntry fromJsonBlob(String jsonBlob) { try { return objectMapper.readValue(jsonBlob, RawSecretEntry.class); } catch (IOException e) { throw new ParseException("Failed to deserialize secret entry from JSON blob", e); } } @Deprecated RawSecretEntry(); RawSecretEntry(@JsonProperty("secretIdentifier") SecretIdentifier secretIdentifier,
@JsonProperty("version") long version,
@JsonProperty("state") State state,
@JsonProperty("notBefore") Optional<ZonedDateTime> notBefore,
@JsonProperty("notAfter") Optional<ZonedDateTime> notAfter,
@JsonProperty("encryptedPayload") byte[] encryptedPayload); String toJsonBlob(); static RawSecretEntry fromJsonBlob(String jsonBlob); byte[] sha1OfEncryptionPayload(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override void bestEffortShred(); @PartitionKey(position=Config.KEY, padding = 128)
@JsonProperty("secretIdentifier")
public SecretIdentifier secretIdentifier; @SortKey(position=Config.VERSION)
@JsonProperty("version")
public Long version; @Attribute(position=Config.STATE)
@JsonProperty("state")
public State state; @Attribute(position=Config.NOT_BEFORE)
@JsonProperty("notBefore")
public Optional<ZonedDateTime> notBefore; @Attribute(position=Config.NOT_AFTER)
@JsonProperty("notAfter")
public Optional<ZonedDateTime> notAfter; @Attribute(position=Config.VALUE)
@JsonProperty("encryptedPayload")
public byte[] encryptedPayload; }### Answer:
@Test public void deserialize() { RawSecretEntry deserialized = RawSecretEntry.fromJsonBlob(jsonBlob); assertThat(deserialized, is(rawSecretEntry)); }
@Test(expectedExceptions = ParseException.class) public void deserializeInvalidJson() { RawSecretEntry.fromJsonBlob("{#$%^&*"); } |
### Question:
RoleARN extends ARN { public String getRoleName() { return this.resource; } RoleARN(final String arn); String getRoleName(); }### Answer:
@Test public void role() { RoleARN arn = new RoleARN("arn:aws:iam::12345:role/role-name"); assertThat(arn.getRoleName(), is("role-name")); } |
### Question:
SecretValue implements BestEffortShred { @Override public boolean equals(final Object obj) { if (obj instanceof SecretValue) { final SecretValue other = (SecretValue) obj; return Arrays.equals(secretValue, other.asByteArray()) && Objects.equal(type, other.type) && Objects.equal(encoding, other.encoding); } else { return false; } } SecretValue(byte[] secretValue, Encoding encoding, SecretType type); SecretValue(byte[] secretValue, SecretType type); SecretValue(String secretValue, SecretType type); byte[] asByteArray(); String asString(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override void bestEffortShred(); final SecretType type; final Encoding encoding; }### Answer:
@Test public void testEquals() { byte[] value1 = {1, 2, 3, 4}; byte[] value2 = {1, 2, 3, 4}; byte[] value3 = {1, 2, 3, 5}; SecretValue secretValue1 = new SecretValue(value1, SecretType.OPAQUE); SecretValue secretValue2 = new SecretValue(value2, SecretType.OPAQUE); SecretValue secretValue3 = new SecretValue(value3, SecretType.OPAQUE); assertTrue(secretValue1.equals(secretValue2)); assertFalse(secretValue1.equals(secretValue3)); } |
### Question:
Principal { @Override public String toString() { return String.format("%s [%s]", name, type.toString()); } Principal(PrincipalType type, String principalName); static Principal fromArn(String arn, String account); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); final PrincipalType type; final String name; }### Answer:
@Test public void testToString() { Principal principal = Principal.fromArn("arn:aws:iam::12345:user/bob", "12345"); assertEquals(principal.toString(), "bob [user]"); } |
### Question:
Principal { @Override public boolean equals(final Object obj) { if(obj instanceof Principal){ final Principal other = (Principal) obj; return Objects.equal(name, other.name) && Objects.equal(type, other.type); } else{ return false; } } Principal(PrincipalType type, String principalName); static Principal fromArn(String arn, String account); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); final PrincipalType type; final String name; }### Answer:
@Test public void testEquals() { Principal principal1 = Principal.fromArn("arn:aws:iam::12345:user/bob", "12345"); Principal principal2 = new Principal(PrincipalType.USER, "bob"); assertTrue(principal1.equals(principal2)); } |
### Question:
SecretsGroupIdentifier implements Comparable<SecretsGroupIdentifier> { @Override public String toString() { return String.format("%s [%s]", name, region.getName()); } SecretsGroupIdentifier(@JsonProperty("region") Region region,
@JsonProperty("name") String name); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override int compareTo(SecretsGroupIdentifier o); @JsonProperty("region")
final Region region; @JsonProperty("name")
final String name; }### Answer:
@Test public void testConstructWithValidNames() { SecretsGroupIdentifier group = new SecretsGroupIdentifier(Region.US_WEST_1, "project.service.group1"); assertEquals(group.name, "project.service.group1"); assertEquals(group.region, Region.US_WEST_1); assertEquals(group.toString(), "project.service.group1 [us-west-1]"); } |
### Question:
SecretsGroupIdentifier implements Comparable<SecretsGroupIdentifier> { @Override public boolean equals(final Object obj) { if(obj instanceof SecretsGroupIdentifier){ final SecretsGroupIdentifier other = (SecretsGroupIdentifier) obj; return Objects.equal(name, other.name) && Objects.equal(region, other.region); } else { return false; } } SecretsGroupIdentifier(@JsonProperty("region") Region region,
@JsonProperty("name") String name); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override int compareTo(SecretsGroupIdentifier o); @JsonProperty("region")
final Region region; @JsonProperty("name")
final String name; }### Answer:
@Test public void testEquals() throws Exception { SecretsGroupIdentifier group1 = new SecretsGroupIdentifier(Region.US_WEST_1, "project.service.group1"); SecretsGroupIdentifier group2 = new SecretsGroupIdentifier(Region.US_WEST_1, "project.service.group1"); SecretsGroupIdentifier group3 = new SecretsGroupIdentifier(Region.EU_WEST_1, "project.service.group1"); SecretsGroupIdentifier group4 = new SecretsGroupIdentifier(Region.US_WEST_1, "project.service.group2"); assertTrue(group1.equals(group2)); assertFalse(group1.equals(group3)); assertFalse(group1.equals(group4)); assertFalse(group1.equals("some string value")); } |
### Question:
SecretsGroupIdentifier implements Comparable<SecretsGroupIdentifier> { @Override public int compareTo(SecretsGroupIdentifier o) { if (region.compareTo(o.region) == 0) { return name.compareTo(o.name); } else { return region.compareTo(o.region); } } SecretsGroupIdentifier(@JsonProperty("region") Region region,
@JsonProperty("name") String name); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override int compareTo(SecretsGroupIdentifier o); @JsonProperty("region")
final Region region; @JsonProperty("name")
final String name; }### Answer:
@Test public void testCompareTo() throws Exception { SecretsGroupIdentifier group1 = new SecretsGroupIdentifier(Region.US_WEST_1, "project.service.group1"); SecretsGroupIdentifier group2 = new SecretsGroupIdentifier(Region.US_WEST_1, "project.service.group1"); SecretsGroupIdentifier group3 = new SecretsGroupIdentifier(Region.EU_WEST_1, "project.service.group1"); SecretsGroupIdentifier group4 = new SecretsGroupIdentifier(Region.US_WEST_1, "project.service.group2"); assertEquals(group1.compareTo(group1), 0); assertEquals(group1.compareTo(group2), 0); assertEquals(group1.compareTo(group3), -2); assertEquals(group1.compareTo(group4), -1); assertEquals(group3.compareTo(group4), 2); } |
### Question:
SecretIdentifier { @Override public String toString() { return name; } @JsonCreator SecretIdentifier(@JsonProperty("name") String name); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); final String name; }### Answer:
@Test public void testConstructWithValidNames() { SecretIdentifier secret = new SecretIdentifier("fooBar1"); assertEquals(secret.name, "fooBar1"); assertEquals(secret.toString(), "fooBar1"); }
@Test public void testConstructWithValidUnderscoreNames() { SecretIdentifier secret = new SecretIdentifier("foo_bar_1"); assertEquals(secret.name, "foo_bar_1"); assertEquals(secret.toString(), "foo_bar_1"); } |
### Question:
SecretIdentifier { @Override public boolean equals(final Object obj) { if(obj instanceof SecretIdentifier){ final SecretIdentifier other = (SecretIdentifier) obj; return Objects.equal(name, other.name); } else { return false; } } @JsonCreator SecretIdentifier(@JsonProperty("name") String name); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); final String name; }### Answer:
@Test public void testEquals() throws Exception { SecretIdentifier secret1 = new SecretIdentifier("fooBar1"); SecretIdentifier secret2 = new SecretIdentifier("fooBar1"); SecretIdentifier secret3 = new SecretIdentifier("fooBar2"); assertTrue(secret1.equals(secret2)); assertFalse(secret1.equals(secret3)); assertFalse(secret1.equals("some value")); } |
### Question:
IAMPolicyManager { public void detachAdmin(SecretsGroupIdentifier group, Principal principal) { detachPrincipal(group, principal, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; }### Answer:
@Test public void testDetachAdminUser() throws Exception { Principal principal = new Principal(PrincipalType.USER, "alice"); partiallyMockedPolicyManager.detachAdmin(group, principal); DetachUserPolicyRequest request = new DetachUserPolicyRequest() .withPolicyArn(ADMIN_POLICY_ARN) .withUserName(principal.name); verify(mockClient, times(1)).detachUserPolicy(request); } |
### Question:
LambdaHandler implements RequestStreamHandler { @Override public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException { I inputObject = deserializeEventJson(input, getInputType()); O handlerResult = handleRequest(inputObject, context); serializeOutput(output, handlerResult); } protected LambdaHandler(); @Override void handleRequest(InputStream input, OutputStream output, Context context); abstract O handleRequest(I input, Context context); }### Answer:
@Test public void handleRequest() throws Exception { String jsonInputAndExpectedOutput = "{\"value\":\"testValue\"}"; InputStream exampleInputStream = new ByteArrayInputStream(jsonInputAndExpectedOutput.getBytes(StandardCharsets.UTF_8)); OutputStream exampleOutputStream = new OutputStream() { private final StringBuilder stringBuilder = new StringBuilder(); @Override public void write(int b) { stringBuilder.append((char) b); } @Override public String toString() { return stringBuilder.toString(); } }; TestLambdaHandler lambdaHandler = new TestLambdaHandler(); lambdaHandler.handleRequest(exampleInputStream, exampleOutputStream, null); assertEquals(jsonInputAndExpectedOutput, exampleOutputStream.toString()); } |
### Question:
Handler extends LambdaHandler<AuthorizationInput, AuthorizationOutput> { @Override public AuthorizationOutput handleRequest(AuthorizationInput input, Context context) { final String authenticationToken = input.getAuthorizationToken(); final PolicyDocument policyDocument = new PolicyDocument(); PolicyStatement.Effect policyEffect = PolicyStatement.Effect.ALLOW; String principalId = null; try { User authenticatedUser = userService.getUserByToken(authenticationToken); principalId = String.valueOf(authenticatedUser.getId()); } catch (UserNotFoundException userNotFoundException) { policyEffect = PolicyStatement.Effect.DENY; LOGGER.info("User authentication failed for token " + authenticationToken); } policyDocument.withPolicyStatement(new PolicyStatement("execute-api:Invoke", policyEffect, input.getMethodArn())); return new AuthorizationOutput(principalId, policyDocument); } Handler(); @Inject void setUserService(UserService userService); @Override AuthorizationOutput handleRequest(AuthorizationInput input, Context context); }### Answer:
@Test public void testFailingToken() throws Exception { Handler testHandler = new Handler(); AuthorizationInput mockEvent = createNiceMock(AuthorizationInput.class); expect(mockEvent.getAuthorizationToken()).andReturn("INVALID_TOKEN").anyTimes(); replay(mockEvent); AuthorizationOutput authorizationOutput = testHandler.handleRequest(mockEvent, null); assertEquals(PolicyStatement.Effect.DENY, authorizationOutput.getPolicyDocument().getPolicyStatements().get(0).getEffect()); } |
### Question:
UserServiceImpl implements UserService { @Override public User registerNewUser(String username, String email) throws UserRegistrationException { checkEmailValidity(email); checkEmailUniqueness(email); checkUsernameUniqueness(username); User newUser = new User() .setId(UUID.randomUUID().toString()) .setUsername(username) .setEmail(email); userRepository.saveUser(newUser); return newUser; } @Inject UserServiceImpl(UserRepository userRepository); @Override User getUserByToken(String token); @Override User registerNewUser(String username, String email); }### Answer:
@Test public void failedUserRegistrationWithExistingUsernameTest() throws Exception { thrown.expect(AnotherUserWithSameUsernameExistsException.class); UserService userService = getUserService(); final String username = UUID.randomUUID() + "test-username"; userService.registerNewUser(username, UUID.randomUUID() + "@test.com"); userService.registerNewUser(username, UUID.randomUUID() + "@test.com"); }
@Test public void failedUserRegistrationWithExistingEMailTest() throws Exception { thrown.expect(AnotherUserWithSameEmailExistsException.class); UserService userService = getUserService(); final String email = UUID.randomUUID() + "@test.com"; userService.registerNewUser(UUID.randomUUID().toString(), email); userService.registerNewUser(UUID.randomUUID().toString(), email); }
@Test public void failedUserRegistrationWithInvalidEmailTest() throws Exception { thrown.expect(InvalidMailAddressException.class); UserService userService = getUserService(); userService.registerNewUser(UUID.randomUUID().toString(), "INVALID_EMAIL"); } |
### Question:
DataTypes { public static int parseSizeInt(String size, int def) { return parseNum(size, Integer.class, def); } static T parseNum(String num, Class<T> cls, T def); static int parseSizeInt(String size, int def); static boolean parseBool(final String val); static Object decodeValueType(char typeId, String value); static String valueToString(final Object value); static char decodeTypeIdFromName(String name); static String stripNameFromTypeId(String name); static String encodeTypeIdInName(String name, Object value); static char getTypeId(Object instance); static boolean getProperty(String key, Boolean def); static void main( String[] args ); static final Map<String, Character> typesMap; }### Answer:
@Test public void testParseSizeInt() { System.out.println( "parseSizeInt" ); assertEquals( 1, DataTypes.parseSizeInt( "1", 1 ) ); assertEquals( 1024, DataTypes.parseSizeInt( "1k", 1 ) ); assertEquals( 1024 * 1024, DataTypes.parseSizeInt( "1m", 1 ) ); assertEquals( 1024 * 1024 * 1024, DataTypes.parseSizeInt( "1g", 1 ) ); assertEquals( 1, DataTypes.parseSizeInt( "fail", 1 ) ); } |
### Question:
SSLContextContainer implements SSLContextContainerIfc { public static <T> T find(Map<String, T> data, String key) { if (data.containsKey(key)) { return data.get(key); } int idx = key.indexOf("."); if (idx >= 0) { String asteriskKey = "*" + key.substring(idx); T value = data.get(asteriskKey); if (value != null) { data.put(key, value); return value; } } return null; } @Override void addCertificates(Map<String, String> params); SSLContext getSSLContext(String protocol, String hostname, boolean clientMode); static T find(Map<String, T> data, String key); @Override SSLContext getSSLContext(String protocol, String hostname, boolean clientMode, TrustManager... tms); @Override KeyStore getTrustStore(); @Override void init(Map<String, Object> params); final static String PER_DOMAIN_CERTIFICATE_KEY; }### Answer:
@Test public void testFind() { final HashMap<String, String> domains = new HashMap<String, String>(); domains.put("one.com", "one.com"); domains.put("a.two.com", "a.two.com"); domains.put("*.two.com", "*.two.com"); assertEquals("one.com", SSLContextContainer.find(domains, "one.com")); assertNull(SSLContextContainer.find(domains, "tone.com")); assertNull(SSLContextContainer.find(domains, "zero.com")); assertEquals("a.two.com", SSLContextContainer.find(domains, "a.two.com")); assertEquals("*.two.com", SSLContextContainer.find(domains, "b.two.com")); assertEquals("*.two.com", SSLContextContainer.find(domains, "b.two.com")); assertNull(SSLContextContainer.find(domains, "btwo.com")); assertEquals("*.two.com", SSLContextContainer.find(domains, ".two.com")); } |
### Question:
WebSocketXMPPIOService extends XMPPIOService<RefObject> { protected int parseHttpHeaders(byte[] buf, Map<String, String> headers) { int i = 0; while (buf[i] != '\n') { i++; } i++; if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "parsing request = \n{0}", new String(buf)); } StringBuilder builder = new StringBuilder(64); String key = null; boolean skipWhitespace = false; for (; i < buf.length; i++) { switch (buf[i]) { case ':': if (key == null) { key = builder.toString().trim(); builder = new StringBuilder(64); skipWhitespace = true; } else { builder.append((char) buf[i]); } break; case '\r': headers.put(key, builder.toString().trim()); key = null; builder = new StringBuilder(64); if (buf[i + 2] == '\r') { i += 3; } else { i++; } break; case ' ': case '\t': if (!skipWhitespace) { builder.append((char) buf[i]); } break; default: skipWhitespace = false; builder.append((char) buf[i]); } } return i; } WebSocketXMPPIOService(WebSocketProtocolIfc[] enabledProtocols); @Override void stop(); void dumpHeaders(Map<String,String> headers); }### Answer:
@Test public void testHttpHeadersParsingWithSpaces() throws UnsupportedEncodingException { byte[] data = prepareHTTPRequest(headers, true); Map<String, String> parsedHeaders = new HashMap<>(); service.parseHttpHeaders(data, parsedHeaders); assertMaps(headers, parsedHeaders); }
@Test public void testHttpHeadersParsingWithoutSpaces() throws UnsupportedEncodingException { byte[] data = prepareHTTPRequest(headers, false); Map<String, String> parsedHeaders = new HashMap<>(); service.parseHttpHeaders(data, parsedHeaders); assertMaps(headers, parsedHeaders); } |
### Question:
NodeNameUtil { public static String createNodeName(String eventName, String xmlns) { return (eventName == null ? "*" : eventName) + "|" + (xmlns == null ? "*" : xmlns); } private NodeNameUtil(); static String createNodeName(String eventName, String xmlns); static EventName parseNodeName(String nodeName); }### Answer:
@Test public void testCreateNodeName() throws Exception { assertEquals("1|2", NodeNameUtil.createNodeName("1", "2")); assertEquals("*|2", NodeNameUtil.createNodeName(null, "2")); assertEquals("*|*", NodeNameUtil.createNodeName(null, null)); assertEquals("1|*", NodeNameUtil.createNodeName("1", null)); } |
### Question:
NodeNameUtil { public static EventName parseNodeName(String nodeName) { int i = nodeName.indexOf('|'); String n = nodeName.substring(0, i); String x = nodeName.substring(i + 1); return new EventName(n.equals("*") ? null : n, x.equals("*") ? null : x); } private NodeNameUtil(); static String createNodeName(String eventName, String xmlns); static EventName parseNodeName(String nodeName); }### Answer:
@Test public void testParseNodeName() throws Exception { assertEquals(new EventName("1", "2"), NodeNameUtil.parseNodeName("1|2")); assertEquals(new EventName(null, "2"), NodeNameUtil.parseNodeName("*|2")); assertEquals(new EventName(null, null), NodeNameUtil.parseNodeName("*|*")); assertEquals(new EventName("1", null), NodeNameUtil.parseNodeName("1|*")); assertEquals(new EventName("1", ""), NodeNameUtil.parseNodeName("1|")); assertEquals(new EventName("", ""), NodeNameUtil.parseNodeName("|")); } |
### Question:
EventName { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EventName other = (EventName) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (xmlns == null) { if (other.xmlns != null) return false; } else if (!xmlns.equals(other.xmlns)) return false; return true; } EventName(String name, String xmlns); @Override boolean equals(Object obj); String getName(); String getXmlns(); @Override int hashCode(); String toEventBusNode(); @Override String toString(); }### Answer:
@Test public void testEquals() throws Exception { assertEquals(new EventName(null, null), new EventName(null, null)); assertEquals(new EventName(null, "2"), new EventName(null, "2")); assertEquals(new EventName("1", "2"), new EventName("1", "2")); assertNotEquals(new EventName(null, null), new EventName("2", "2")); assertNotEquals(new EventName(null, null), new EventName(null, "2")); assertNotEquals(new EventName(null, null), new EventName("2", null)); assertNotEquals(new EventName("1", null), new EventName("2", "2")); assertNotEquals(new EventName(null, "2"), new EventName("2", "2")); assertNotEquals(new EventName("2", "1"), new EventName("2", "2")); } |
### Question:
ImageResizer { public byte[] resize(BufferedImage originalImage) throws IOException { if (originalImage == null) { throw new IIOException("Image is null. Did ImageIO fail to decode the image?"); } BufferedImage resized = ImageUtil.resizeImage(originalImage, size, size); originalImage.flush(); byte[] resizedBytes = com.github.dozedoff.similarImage.util.ImageUtil.imageToBytes(resized); resized.flush(); return resizedBytes; } ImageResizer(int size); byte[] resize(BufferedImage originalImage); }### Answer:
@Test(expected = IIOException.class) public void testResizeNullImage() throws Exception { cut.resize((BufferedImage) null); } |
### Question:
OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getByHash(long hash) throws RepositoryException { try { return imageDao.queryForMatching(new ImageRecord(null, hash)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", 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 testGetByHashNotFound() throws Exception { assertThat(cut.getByHash(HASH_NEW_RECORD), hasSize(0)); }
@Test public void testGetByHashExists() throws Exception { assertThat(cut.getByHash(HASH_EXISTING_RECORD), containsInAnyOrder(imageExisting)); } |
### 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:
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))); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.