method2testcases
stringlengths
118
3.08k
### Question: Not extends BaseExpression { @Override public void addChildren(Deque<Expression> expressions) { addChildren(expressions, 1); } Not(); @Override Result apply(PathData item); @Override boolean isOperator(); @Override int getPrecedence(); @Override void addChildren(Deque<Expression> expressions); static void registerExpression(ExpressionFactory factory); }### Answer: @Test public void testInit() throws IOException { Not not = new Not(); Expression child = mock(Expression.class); Deque<Expression> children = new LinkedList<Expression>(); children.add(child); not.addChildren(children); FindOptions options = mock(FindOptions.class); not.initialise(options); verify(child).initialise(options); verifyNoMoreInteractions(child); }
### Question: Depth extends BaseExpression { @Override public Result apply(PathData item) { return Result.PASS; } Depth(); @Override Result apply(PathData item); @Override void initialise(FindOptions options); static void registerExpression(ExpressionFactory factory); }### Answer: @Test public void apply() throws IOException{ Depth depth = new Depth(); depth.initialise(new FindOptions()); assertEquals(Result.PASS, depth.apply(new PathData("anything", new Configuration()))); }
### Question: Or extends BaseExpression { @Override public void addChildren(Deque<Expression> expressions) { addChildren(expressions, 2); } Or(); @Override Result apply(PathData item); @Override boolean isOperator(); @Override int getPrecedence(); @Override void addChildren(Deque<Expression> expressions); static void registerExpression(ExpressionFactory factory); }### Answer: @Test public void testInit() throws IOException { Or or = new Or(); Expression first = mock(Expression.class); Expression second = mock(Expression.class); Deque<Expression> children = new LinkedList<Expression>(); children.add(second); children.add(first); or.addChildren(children); FindOptions options = mock(FindOptions.class); or.initialise(options); verify(first).initialise(options); verify(second).initialise(options); verifyNoMoreInteractions(first); verifyNoMoreInteractions(second); }
### Question: Atime extends NumberExpression { @Override public Result apply(PathData item) throws IOException { return applyNumber(getOptions().getStartTime() - getFileStatus(item).getAccessTime()); } Atime(); Atime(long units); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }### Answer: @Test public void testExact() throws IOException { Atime atime = new Atime(); addArgument(atime, "5"); FindOptions options = new FindOptions(); options.setStartTime(NOW); atime.initialise(options); assertEquals(Result.FAIL, atime.apply(fourDays)); assertEquals(Result.FAIL, atime.apply(fiveDaysMinus)); assertEquals(Result.PASS, atime.apply(fiveDays)); assertEquals(Result.PASS, atime.apply(fiveDaysPlus)); assertEquals(Result.FAIL, atime.apply(sixDays)); } @Test public void testGreater() throws IOException { Atime atime = new Atime(); addArgument(atime, "+5"); FindOptions options = new FindOptions(); options.setStartTime(NOW); atime.initialise(options); assertEquals(Result.FAIL, atime.apply(fourDays)); assertEquals(Result.FAIL, atime.apply(fiveDaysMinus)); assertEquals(Result.FAIL, atime.apply(fiveDays)); assertEquals(Result.FAIL, atime.apply(fiveDaysPlus)); assertEquals(Result.PASS, atime.apply(sixDays)); } @Test public void testLess() throws IOException { Atime atime = new Atime(); addArgument(atime, "-5"); FindOptions options = new FindOptions(); options.setStartTime(NOW); atime.initialise(options); assertEquals(Result.PASS, atime.apply(fourDays)); assertEquals(Result.PASS, atime.apply(fiveDaysMinus)); assertEquals(Result.FAIL, atime.apply(fiveDays)); assertEquals(Result.FAIL, atime.apply(fiveDaysPlus)); assertEquals(Result.FAIL, atime.apply(sixDays)); }
### Question: Exec extends BaseExpression { @Override public void addArguments(Deque<String> args) { while(!args.isEmpty()) { String arg = args.pop(); if("+".equals(arg) && !getArguments().isEmpty() && "{}".equals(getArguments().get(getArguments().size() - 1))) { setBatch(true); break; } else if(";".equals(arg)) { break; } else { addArgument(arg); } } } Exec(); Exec(boolean prompt); @Override void addArguments(Deque<String> args); @Override void initialise(FindOptions options); @Override Result apply(PathData item); @Override void finish(); @Override boolean isAction(); static void registerExpression(ExpressionFactory factory); }### Answer: @Test public void addArguments() throws IOException { Exec exec = new Exec(); exec.addArguments(getArgs("one two three ; four")); assertEquals("Exec(one,two,three;)", exec.toString()); assertFalse(exec.isBatch()); }
### Question: Print extends BaseExpression { public Print(boolean appendNull) { super(); setUsage(USAGE); setHelp(HELP); setAppendNull(appendNull); } Print(boolean appendNull); Print(); @Override Result apply(PathData item); @Override boolean isAction(); static void registerExpression(ExpressionFactory factory); }### Answer: @Test public void testPrint() throws IOException{ Print print = new Print(); PrintStream out = mock(PrintStream.class); FindOptions options = new FindOptions(); options.setOut(out); print.initialise(options); String filename = "/one/two/test"; PathData item = new PathData(filename, conf); assertEquals(Result.PASS, print.apply(item)); verify(out).println(filename); verifyNoMoreInteractions(out); }
### Question: Prune extends BaseExpression { @Override public Result apply(PathData item) throws IOException { if(getOptions().isDepth()) { return Result.PASS; } return Result.STOP; } Prune(); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }### Answer: @Test public void apply() throws IOException { Prune prune = new Prune(); PathData item = mock(PathData.class); Result result = prune.apply(item); assertTrue(result.isPass()); assertFalse(result.isDescend()); } @Test public void applyDepth() throws IOException { Prune prune = new Prune(); FindOptions options = new FindOptions(); options.setDepth(true); prune.initialise(options); PathData item = mock(PathData.class); assertEquals(Result.PASS, prune.apply(item)); }
### Question: Nogroup extends BaseExpression { @Override public Result apply(PathData item) throws IOException { String group = getFileStatus(item).getGroup(); if((group == null) || (group.equals(""))) { return Result.PASS; } return Result.FAIL; } Nogroup(); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }### Answer: @Test public void applyPass() throws IOException{ when(fileStatus.getGroup()).thenReturn("user"); assertEquals(Result.FAIL, nogroup.apply(item)); } @Test public void applyFail() throws IOException { when(fileStatus.getGroup()).thenReturn("notuser"); assertEquals(Result.FAIL, nogroup.apply(item)); } @Test public void applyBlank() throws IOException { when(fileStatus.getGroup()).thenReturn(""); assertEquals(Result.PASS, nogroup.apply(item)); } @Test public void applyNull() throws IOException { when(fileStatus.getGroup()).thenReturn(null); assertEquals(Result.PASS, nogroup.apply(item)); }
### Question: Nouser extends BaseExpression { @Override public Result apply(PathData item) throws IOException { String user = getFileStatus(item).getOwner(); if((user == null) || (user.equals(""))) { return Result.PASS; } return Result.FAIL; } Nouser(); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }### Answer: @Test public void applyPass() throws IOException{ when(fileStatus.getOwner()).thenReturn("user"); assertEquals(Result.FAIL, nouser.apply(item)); } @Test public void applyFail() throws IOException { when(fileStatus.getOwner()).thenReturn("notuser"); assertEquals(Result.FAIL, nouser.apply(item)); } @Test public void applyBlank() throws IOException { when(fileStatus.getOwner()).thenReturn(""); assertEquals(Result.PASS, nouser.apply(item)); } @Test public void applyNull() throws IOException { when(fileStatus.getOwner()).thenReturn(null); assertEquals(Result.PASS, nouser.apply(item)); }
### Question: Blocksize extends NumberExpression { @Override public Result apply(PathData item) throws IOException { return applyNumber(getFileStatus(item).getBlockSize()); } Blocksize(); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }### Answer: @Test public void applyEquals() throws IOException { Blocksize blocksize = new Blocksize(); addArgument(blocksize, "3"); blocksize.initialise(new FindOptions()); assertEquals(Result.FAIL, blocksize.apply(one)); assertEquals(Result.FAIL, blocksize.apply(two)); assertEquals(Result.PASS, blocksize.apply(three)); assertEquals(Result.FAIL, blocksize.apply(four)); assertEquals(Result.FAIL, blocksize.apply(five)); } @Test public void applyGreaterThan() throws IOException { Blocksize blocksize = new Blocksize(); addArgument(blocksize, "+3"); blocksize.initialise(new FindOptions()); assertEquals(Result.FAIL, blocksize.apply(one)); assertEquals(Result.FAIL, blocksize.apply(two)); assertEquals(Result.FAIL, blocksize.apply(three)); assertEquals(Result.PASS, blocksize.apply(four)); assertEquals(Result.PASS, blocksize.apply(five)); } @Test public void applyLessThan() throws IOException { Blocksize blocksize = new Blocksize(); addArgument(blocksize, "-3"); blocksize.initialise(new FindOptions()); assertEquals(Result.PASS, blocksize.apply(one)); assertEquals(Result.PASS, blocksize.apply(two)); assertEquals(Result.FAIL, blocksize.apply(three)); assertEquals(Result.FAIL, blocksize.apply(four)); assertEquals(Result.FAIL, blocksize.apply(five)); }
### Question: Result { public Result combine(Result other) { return new Result(this.isPass() && other.isPass(), this.isDescend() && other.isDescend()); } private Result(boolean success, boolean recurse); boolean isDescend(); boolean isPass(); Result combine(Result other); Result negate(); String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static final Result PASS; static final Result FAIL; static final Result STOP; }### Answer: @Test public void equalsPass() { Result one = Result.PASS; Result two = Result.PASS.combine(Result.PASS); assertEquals(one, two); } @Test public void equalsFail() { Result one = Result.FAIL; Result two = Result.FAIL.combine(Result.FAIL); assertEquals(one, two); } @Test public void equalsStop() { Result one = Result.STOP; Result two = Result.STOP.combine(Result.STOP); assertEquals(one, two); }
### Question: Result { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Result other = (Result) obj; if (descend != other.descend) return false; if (success != other.success) return false; return true; } private Result(boolean success, boolean recurse); boolean isDescend(); boolean isPass(); Result combine(Result other); Result negate(); String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static final Result PASS; static final Result FAIL; static final Result STOP; }### Answer: @Test public void notEquals() { assertFalse(Result.PASS.equals(Result.FAIL)); assertFalse(Result.PASS.equals(Result.STOP)); assertFalse(Result.FAIL.equals(Result.PASS)); assertFalse(Result.FAIL.equals(Result.STOP)); assertFalse(Result.STOP.equals(Result.PASS)); assertFalse(Result.STOP.equals(Result.FAIL)); }
### Question: Newer extends BaseExpression { @Override public Result apply(PathData item) throws IOException { if(getFileStatus(item).getModificationTime() > filetime) { return Result.PASS; } return Result.FAIL; } Newer(); @Override void initialise(FindOptions options); @Override Result apply(PathData item); @Override void addArguments(Deque<String> args); static void registerExpression(ExpressionFactory factory); }### Answer: @Test public void applyPass() throws IOException{ FileStatus fileStatus = mock(FileStatus.class); when(fileStatus.getModificationTime()).thenReturn(NOW - (4l*86400000)); fs.setFileStatus("newer.file", fileStatus); PathData item = new PathData("/directory/path/newer.file", fs.getConf()); assertEquals(Result.PASS, newer.apply(item)); } @Test public void applyFail() throws IOException{ FileStatus fileStatus = mock(FileStatus.class); when(fileStatus.getModificationTime()).thenReturn(NOW - (6l*86400000)); fs.setFileStatus("older.file", fileStatus); PathData item = new PathData("/directory/path/older.file", fs.getConf()); assertEquals(Result.FAIL, newer.apply(item)); }
### Question: Group extends BaseExpression { @Override public Result apply(PathData item) throws IOException { String group = getFileStatus(item).getGroup(); if(requiredGroup.equals(group)) { return Result.PASS; } return Result.FAIL; } Group(); @Override void addArguments(Deque<String> args); @Override void initialise(FindOptions options); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }### Answer: @Test public void applyPass() throws IOException{ when(fileStatus.getGroup()).thenReturn("group"); assertEquals(Result.PASS, group.apply(item)); } @Test public void applyFail() throws IOException { when(fileStatus.getGroup()).thenReturn("notgroup"); assertEquals(Result.FAIL, group.apply(item)); } @Test public void applyBlank() throws IOException { when(fileStatus.getGroup()).thenReturn(""); assertEquals(Result.FAIL, group.apply(item)); } @Test public void applyNull() throws IOException { when(fileStatus.getGroup()).thenReturn(null); assertEquals(Result.FAIL, group.apply(item)); }
### Question: Mtime extends NumberExpression { @Override public Result apply(PathData item) throws IOException { return applyNumber(getOptions().getStartTime() - getFileStatus(item).getModificationTime()); } Mtime(); Mtime(long units); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }### Answer: @Test public void testExact() throws IOException { Mtime mtime = new Mtime(); addArgument(mtime, "5"); FindOptions options = new FindOptions(); options.setStartTime(NOW); mtime.initialise(options); assertEquals(Result.FAIL, mtime.apply(fourDays)); assertEquals(Result.FAIL, mtime.apply(fiveDaysMinus)); assertEquals(Result.PASS, mtime.apply(fiveDays)); assertEquals(Result.PASS, mtime.apply(fiveDaysPlus)); assertEquals(Result.FAIL, mtime.apply(sixDays)); } @Test public void testGreater() throws IOException { Mtime mtime = new Mtime(); addArgument(mtime, "+5"); FindOptions options = new FindOptions(); options.setStartTime(NOW); mtime.initialise(options); assertEquals(Result.FAIL, mtime.apply(fourDays)); assertEquals(Result.FAIL, mtime.apply(fiveDaysMinus)); assertEquals(Result.FAIL, mtime.apply(fiveDays)); assertEquals(Result.FAIL, mtime.apply(fiveDaysPlus)); assertEquals(Result.PASS, mtime.apply(sixDays)); } @Test public void testLess() throws IOException { Mtime mtime = new Mtime(); addArgument(mtime, "-5"); FindOptions options = new FindOptions(); options.setStartTime(NOW); mtime.initialise(options); assertEquals(Result.PASS, mtime.apply(fourDays)); assertEquals(Result.PASS, mtime.apply(fiveDaysMinus)); assertEquals(Result.FAIL, mtime.apply(fiveDays)); assertEquals(Result.FAIL, mtime.apply(fiveDaysPlus)); assertEquals(Result.FAIL, mtime.apply(sixDays)); }
### Question: Type extends BaseExpression { @Override public void initialise(FindOptions option) throws IOException { String arg = getArgument(1); if(FILE_TYPES.containsKey(arg)) { this.fileType = FILE_TYPES.get(arg); } else { throw new IOException("Invalid file type: " + arg); } } Type(); @Override void addArguments(Deque<String> args); @Override void initialise(FindOptions option); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); static final Map<String,FileType> FILE_TYPES; }### Answer: @Test public void testInvalidType() throws IOException { Type type = new Type(); addArgument(type, "a"); try { type.initialise(new FindOptions()); fail("Invalid file type not caught"); } catch (IOException e) {} }
### Question: Name extends BaseExpression { @Override public Result apply(PathData item) { String name = getPath(item).getName(); if(!caseSensitive) { name = name.toLowerCase(); } if(globPattern.matches(name)) { return Result.PASS; } else { return Result.FAIL; } } Name(); Name(boolean caseSensitive); @Override void addArguments(Deque<String> args); @Override void initialise(FindOptions options); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }### Answer: @Test public void applyPass() throws IOException{ PathData item = new PathData("/directory/path/name", conf); assertEquals(Result.PASS, name.apply(item)); } @Test public void applyFail() throws IOException{ PathData item = new PathData("/directory/path/notname", conf); assertEquals(Result.FAIL, name.apply(item)); } @Test public void applyMixedCase() throws IOException{ PathData item = new PathData("/directory/path/NaMe", conf); assertEquals(Result.FAIL, name.apply(item)); }
### Question: Replicas extends NumberExpression { @Override public Result apply(PathData item) throws IOException { return applyNumber(getFileStatus(item).getReplication()); } Replicas(); @Override Result apply(PathData item); static void registerExpression(ExpressionFactory factory); }### Answer: @Test public void applyEquals() throws IOException { Replicas rep = new Replicas(); addArgument(rep, "3"); rep.initialise(new FindOptions()); assertEquals(Result.FAIL, rep.apply(one)); assertEquals(Result.FAIL, rep.apply(two)); assertEquals(Result.PASS, rep.apply(three)); assertEquals(Result.FAIL, rep.apply(four)); assertEquals(Result.FAIL, rep.apply(five)); } @Test public void applyGreaterThan() throws IOException { Replicas rep = new Replicas(); addArgument(rep, "+3"); rep.initialise(new FindOptions()); assertEquals(Result.FAIL, rep.apply(one)); assertEquals(Result.FAIL, rep.apply(two)); assertEquals(Result.FAIL, rep.apply(three)); assertEquals(Result.PASS, rep.apply(four)); assertEquals(Result.PASS, rep.apply(five)); } @Test public void applyLessThan() throws IOException { Replicas rep = new Replicas(); addArgument(rep, "-3"); rep.initialise(new FindOptions()); assertEquals(Result.PASS, rep.apply(one)); assertEquals(Result.PASS, rep.apply(two)); assertEquals(Result.FAIL, rep.apply(three)); assertEquals(Result.FAIL, rep.apply(four)); assertEquals(Result.FAIL, rep.apply(five)); }
### Question: ClassExpression extends FilterExpression { @Override public boolean isOperator() { if(expression == null) { return false; } return expression.isOperator(); } ClassExpression(); static void registerExpression(ExpressionFactory factory); @Override void addArguments(Deque<String> args); @Override String[] getUsage(); @Override String[] getHelp(); @Override boolean isOperator(); }### Answer: @Test public void isOperator() throws IOException { when(expr.isOperator()).thenReturn(true).thenReturn(false); test.addArguments(getArgs(TestExpression.class.getName())); assertTrue(test.isOperator()); assertFalse(test.isOperator()); verify(expr).addArguments(new LinkedList<String>()); verify(expr, times(2)).isOperator(); verifyNoMoreInteractions(expr); }
### Question: JGitAPIExceptions { public static RuntimeException exceptionWithFriendlyMessageFor(Exception e) { Throwable cause = getRootCause(e); String message = cause.getMessage(); if (message == null) { message = cause.getClass().getSimpleName(); } if (cause instanceof JSchException) { message = "SSH: " + message; } return new RuntimeException(message, cause); } static RuntimeException exceptionWithFriendlyMessageFor(Exception e); }### Answer: @Test public void testExceptionWithFriendlyMessageFor() throws Exception { RuntimeException re = exceptionWithFriendlyMessageFor(new NullPointerException()); assertThat(re.getMessage(), equalTo("NullPointerException")); }
### Question: FilePathMatcher implements Predicate<FilePath> { public int[] match(CharSequence filePath) { Matcher matcher = pattern.matcher(filePath); if (matcher.find()) { for (int i = 0; i < matchingLetters.length; ++i) { matchingLetters[i] = matcher.start(i + 1); } return matchingLetters; } else { return null; } } FilePathMatcher(String constraint); @Override boolean apply(FilePath filePath); int[] match(CharSequence filePath); double score(FilePath fp); }### Answer: @Test public void shouldMatchEndOfCandidateString() { assertThat(match("xml", "pom.xml"), is(true)); } @Test public void shouldNotMatchDifferingEndOfCandidateString() { assertThat(match("xml", "pom.xmo"), is(false)); } @Test public void shouldMatch() { assertThat(match("attrib", "Documentation/.gitattributes"), is(true)); assertThat(match("att", "Documentation/.gitattributes"), is(true)); assertThat(match("docgit", "Documentation/.gitattributes"), is(true)); assertThat(match("agitt", "agitb"), is(false)); }
### Question: RDTTag extends RepoDomainType<TagSummary> { public List<TagSummary> getAll() { final RevWalk revWalk = new RevWalk(repository); List<TagSummary> tagSummaries = newArrayList(transform(repository.getTags().values(), new TagSummaryFactory(revWalk))); sort(tagSummaries, SORT_BY_TIME_AND_NAME); return tagSummaries; } @Inject RDTTag(Repository repository); @Override String name(); List<TagSummary> getAll(); @Override String idFor(TagSummary tagSummary); @Override CharSequence conciseSummaryTitle(); @Override CharSequence shortDescriptionOf(TagSummary tagSummary); }### Answer: @Test public void shouldHandleTheDatelessAnnotatedTagsThatGitUsedToHave() throws Exception { Repository repository = helper().unpackRepo("git-repo-has-dateless-tag.depth2.zip"); RDTTag rdtTag = new RDTTag(repository); List<TagSummary> listOfTagsInRepo = rdtTag.getAll(); assertThat(listOfTagsInRepo.size(), is(1)); TagSummary tagSummary = listOfTagsInRepo.get(0); assertThat(tagSummary.getTime(), equalTo(1121037394L)); } @Test public void shouldHaveTaggedObjectFieldCorrectlySetForAnAnnotatedTag() throws Exception { RDTTag rdtTag = new RDTTag(helper().unpackRepo("small-repo.with-tags.zip")); List<TagSummary> tags = rdtTag.getAll(); TagSummary tag = find(tags, tagNamed("annotated-tag-of-2nd-commit")); assertThat(tag.getTaggedObject(), instanceOf(RevCommit.class)); }
### Question: GitHubWebLaunchActivity extends WebLaunchActivity { Intent cloneLauncherForWebBrowseIntent(Uri uri) { Matcher matcher = projectPathPattern.matcher(uri.getPath()); matcher.find(); return cloneLauncherIntentFor("git: } }### Answer: @Test public void shouldSupplyCloneSourceForRegularGithubProjectPage() { Intent cloneIntent = activity.cloneLauncherForWebBrowseIntent(parse("https: assertThat(sourceUriFrom(cloneIntent), is("git: } @Test public void shouldSupplyOnlyUserepoOwnerAndNameForCloneUrl() { Intent cloneIntent = activity.cloneLauncherForWebBrowseIntent(parse("https: ".com/eddieringle/hubroid/issues/66")); assertThat(sourceUriFrom(cloneIntent), is("git: }
### Question: EmailCommandHandler { public void create(EmailCreateCommand command) throws Exception { EmailAggregate emailAggregate = getByUUID(command.getUuid()); emailAggregate = emailAggregate.create(command); List<AppEvent> pendingEvents = emailAggregate.getUncommittedChanges(); eventSourcingService.save(emailAggregate); pendingEvents.forEach(eventPublisher::publish); pendingEvents.forEach(eventPublisher::stream); } EmailCommandHandler( EventSourcingService eventSourcingService, EventPublisher eventPublisher ); void create(EmailCreateCommand command); void send(EmailSendCommand command); void delivery(EmailDeliveryCommand command); void delete(EmailDeleteCommand command); EmailAggregate getByUUID(String uuid); }### Answer: @Test public void create() throws Exception { String uuid = UUID.randomUUID().toString(); EmailCreateCommand command = new EmailCreateCommand( uuid, new Email("Alexsandro", "[email protected]", EmailState.CREATED) ); commandHandler.create(command); verify(eventPublisher, Mockito.times(1)).publish(Mockito.anyObject()); verify(eventPublisher, Mockito.times(1)).stream(Mockito.anyObject()); }
### Question: EmailCommandHandler { public void send(EmailSendCommand command) throws Exception { EmailAggregate emailAggregate = getByUUID(command.getUuid()); emailAggregate = emailAggregate.send(command); List<AppEvent> pendingEvents = emailAggregate.getUncommittedChanges(); pendingEvents.forEach(eventPublisher::stream); eventSourcingService.save(emailAggregate); } EmailCommandHandler( EventSourcingService eventSourcingService, EventPublisher eventPublisher ); void create(EmailCreateCommand command); void send(EmailSendCommand command); void delivery(EmailDeliveryCommand command); void delete(EmailDeleteCommand command); EmailAggregate getByUUID(String uuid); }### Answer: @Test public void send() throws Exception { String uuid = UUID.randomUUID().toString(); EmailSendCommand command = new EmailSendCommand(uuid, Instant.now()); commandHandler.send(command); verify(eventSourcingService, Mockito.times(1)).save(Mockito.any(Aggregate.class)); verify(eventPublisher, Mockito.times(1)).stream(Mockito.anyObject()); }
### Question: EmailCommandHandler { public EmailAggregate getByUUID(String uuid) { return EmailAggregate.from(uuid, eventSourcingService.getRelatedEvents(uuid)); } EmailCommandHandler( EventSourcingService eventSourcingService, EventPublisher eventPublisher ); void create(EmailCreateCommand command); void send(EmailSendCommand command); void delivery(EmailDeliveryCommand command); void delete(EmailDeleteCommand command); EmailAggregate getByUUID(String uuid); }### Answer: @Test public void getByUUID() { String uuid = "123"; Mockito.when(eventSourcingService.getAggregate(Mockito.anyString())) .thenReturn(new EventStream()); EmailAggregate byUUID = commandHandler.getByUUID(uuid); Assert.assertTrue(byUUID.getState().getEmail() == null); }
### Question: EmailAggregate extends AbstractAggregate implements Aggregate { public EmailAggregate create(EmailCreateCommand command) throws Exception { if (state.getState() != null) { throw new Exception("Is not possible to edit a deleted email"); } return applyChange(new EmailCreatedEvent(uuid, command.getEmail())); } EmailAggregate(String uuid, List<AppEvent> changes); EmailAggregate(String uuid, List<AppEvent> changes, Email state); EmailAggregate create(EmailCreateCommand command); EmailAggregate send(EmailSendCommand command); EmailAggregate delivery(EmailDeliveryCommand command); EmailAggregate delete(EmailDeleteCommand command); static EmailAggregate from(String uuid, List<AppEvent> history); @Override EmailAggregate markChangesAsCommitted(); Email getState(); }### Answer: @Test public void testCreate() throws Exception { final Email email = new Email("alex", "[email protected]", EmailState.CREATED); String uuid = UUID.randomUUID().toString(); EmailAggregate result = getAggregateWithStateCreated(email,uuid); assertEquals(email.getEmail(), result.getState().getEmail()); assertEquals(email.getName(), result.getState().getName()); AppEvent event = result.getUncommittedChanges().get(0); assertEquals(uuid, result.getUuid()); assertEquals(uuid, event.uuid()); assertEquals(EmailState.CREATED, result.getState().getState()); }
### Question: EmailAggregate extends AbstractAggregate implements Aggregate { public EmailAggregate send(EmailSendCommand command) throws Exception { if (state.getState() == EmailState.DELETED) { throw new Exception("Is not possible to edit a deleted email"); } return applyChange(new EmailSentEvent( command.getUuid(), getState().setState(EmailState.SENT))); } EmailAggregate(String uuid, List<AppEvent> changes); EmailAggregate(String uuid, List<AppEvent> changes, Email state); EmailAggregate create(EmailCreateCommand command); EmailAggregate send(EmailSendCommand command); EmailAggregate delivery(EmailDeliveryCommand command); EmailAggregate delete(EmailDeleteCommand command); static EmailAggregate from(String uuid, List<AppEvent> history); @Override EmailAggregate markChangesAsCommitted(); Email getState(); }### Answer: @Test public void testSend() throws Exception { final Email email = new Email("alex", "[email protected]", EmailState.CREATED); String uuid = UUID.randomUUID().toString(); EmailAggregate aggregateWithStateCreated = getAggregateWithStateCreated(email, uuid); EmailSendCommand command = new EmailSendCommand(uuid, Instant.MIN); EmailAggregate result = aggregateWithStateCreated.send(command); assertEquals(EmailState.SENT, result.getState().getState()); }
### Question: EmailAggregate extends AbstractAggregate implements Aggregate { @Override public EmailAggregate markChangesAsCommitted() { return new EmailAggregate(uuid, new CopyOnWriteArrayList(), state); } EmailAggregate(String uuid, List<AppEvent> changes); EmailAggregate(String uuid, List<AppEvent> changes, Email state); EmailAggregate create(EmailCreateCommand command); EmailAggregate send(EmailSendCommand command); EmailAggregate delivery(EmailDeliveryCommand command); EmailAggregate delete(EmailDeleteCommand command); static EmailAggregate from(String uuid, List<AppEvent> history); @Override EmailAggregate markChangesAsCommitted(); Email getState(); }### Answer: @Test public void testMarkChangesAsCommitted() throws Exception { final Email email = new Email("alex", "[email protected]", EmailState.CREATED); String uuid = UUID.randomUUID().toString(); EmailAggregate instance = getAggregateWithStateCreated(email,uuid); EmailAggregate result = instance.markChangesAsCommitted(); assertFalse(instance.getUncommittedChanges().isEmpty()); assertTrue(result.getUncommittedChanges().isEmpty()); }
### Question: EmailAggregate extends AbstractAggregate implements Aggregate { public EmailAggregate delete(EmailDeleteCommand command) throws Exception { if (state.getState() == EmailState.DELETED) { throw new Exception("Is not possible to delete a deleted email"); } return applyChange(new EmailDeletedEvent(uuid, getState().setState(EmailState.DELETED) )); } EmailAggregate(String uuid, List<AppEvent> changes); EmailAggregate(String uuid, List<AppEvent> changes, Email state); EmailAggregate create(EmailCreateCommand command); EmailAggregate send(EmailSendCommand command); EmailAggregate delivery(EmailDeliveryCommand command); EmailAggregate delete(EmailDeleteCommand command); static EmailAggregate from(String uuid, List<AppEvent> history); @Override EmailAggregate markChangesAsCommitted(); Email getState(); }### Answer: @Test public void testDelete() throws Exception { final Email email = new Email("alex", "[email protected]", EmailState.CREATED); String uuid = UUID.randomUUID().toString(); EmailAggregate aggregateWithStateCreated = getAggregateWithStateCreated(email, uuid); EmailDeleteCommand command = new EmailDeleteCommand(uuid); EmailAggregate result = aggregateWithStateCreated.delete(command); assertEquals(EmailState.DELETED, result.getState().getState()); }
### Question: Tables { public static String getSQL(Object[] sqlData, Version currentVersion) { try { for (int c = 0; c < sqlData.length; c += 2) { Version curSqlVersion = (Version) sqlData[c]; String curSql = (String) sqlData[c + 1]; if (currentVersion.isMinimum(curSqlVersion)) return curSql; } } catch (Exception e) { throw new IllegalStateException("Misconfigured system table type "); } throw new UnsupportedServerVersion(currentVersion); } static String getSQL(Object[] sqlData, Version currentVersion); static List<R> convertRows(Context context, T table, ResultBatch results); }### Answer: @Test public void testGetSQL() { assertEquals(Tables.getSQL(SQL, Version.parse("9.0.0")), SQL[3]); assertNotEquals(Tables.getSQL(SQL, Version.parse("9.0.0")), SQL[1]); assertEquals(Tables.getSQL(SQL, Version.parse("9.4.5")), SQL[1]); } @Test public void testIllegalStateException() { try { String sql = Tables.getSQL(SQLBad, Version.parse("9.0.0")); fail("Didn't hit IllegalStateException, usually from bad sqlData"); } catch (IllegalStateException e) { } } @Test public void testUnsupportedServerVersion() { thrown.expect(UnsupportedServerVersion.class); assertEquals(Tables.getSQL(SQL, Version.parse("8.3.0")), SQL[1]); }
### Question: PGTypeTable implements Table<PGTypeTable.Row> { @Override public String getSQL(Version currentVersion) { return Tables.getSQL(SQL, currentVersion); } private PGTypeTable(); @Override String getSQL(Version currentVersion); @Override Row createRow(Context context, ResultBatch resultBatch, int rowIdx); static final PGTypeTable INSTANCE; static final Object[] SQL; }### Answer: @Test public void testGetSQLVersionEqual() { assertEquals(INSTANCE.getSQL(Version.parse("9.2.0")), SQL[1]); assertNotEquals(INSTANCE.getSQL(Version.parse("9.1.0")), INSTANCE.getSQL(Version.parse("9.2.0"))); } @Test public void testGetSQLVersionGreater() { assertEquals(INSTANCE.getSQL(Version.parse("9.4.5")), SQL[1]); } @Test public void testGetSQLVersionLess() { assertEquals(INSTANCE.getSQL(Version.parse("9.1.9")), SQL[3]); } @Test public void testGetSQLVersionInvalid() { thrown.expect(UnsupportedServerVersion.class); assertEquals(INSTANCE.getSQL(Version.parse("8.0.0")), SQL[1]); }
### Question: PGTypeTable implements Table<PGTypeTable.Row> { @Override public Row createRow(Context context, ResultBatch resultBatch, int rowIdx) throws IOException { Row row = new Row(); row.load(context, resultBatch, rowIdx); return row; } private PGTypeTable(); @Override String getSQL(Version currentVersion); @Override Row createRow(Context context, ResultBatch resultBatch, int rowIdx); static final PGTypeTable INSTANCE; static final Object[] SQL; }### Answer: @Test public void testHashCode() { PGTypeTable.Row pgAttrOne = createRow(12345); PGTypeTable.Row pgAttrOneAgain = createRow(12345); PGTypeTable.Row pgAttrTwo = createRow(54321); assertEquals(pgAttrOne.hashCode(), pgAttrOne.hashCode()); assertEquals(pgAttrOne.hashCode(), pgAttrOneAgain.hashCode()); assertNotEquals(pgAttrOne.hashCode(), pgAttrTwo.hashCode()); } @Test public void testEquals() { PGTypeTable.Row pgAttrOne = createRow(12345); PGTypeTable.Row pgAttrOneAgain = createRow(12345); PGTypeTable.Row pgAttrTwo = createRow(54321); assertEquals(pgAttrOne, pgAttrOne); assertNotEquals(null, pgAttrOne); assertNotEquals("testStringNotSameClass", pgAttrOne); assertNotEquals(pgAttrOne, pgAttrTwo); assertEquals(pgAttrOne, pgAttrOneAgain); }
### Question: SearchHistoryEntity implements SearchHistory { @Override @NonNull public String getPlaceId() { return placeId; } SearchHistoryEntity(@NonNull String placeId, CarmenFeature carmenFeature); @Override @NonNull String getPlaceId(); @Override CarmenFeature getCarmenFeature(); }### Answer: @Test public void getPlaceId_doesReturnTheSetPlaceId() throws Exception { CarmenFeature feature = CarmenFeature.builder() .properties(new JsonObject()) .build(); SearchHistoryEntity entity = new SearchHistoryEntity("placeId", feature); assertThat(entity.getPlaceId(), equalTo("placeId")); }
### Question: LocalizationPlugin { public void setMapLanguage(@Languages String language) { setMapLanguage(new MapLocale(language)); } LocalizationPlugin(@NonNull MapView mapView, @NonNull final MapboxMap mapboxMap, @NonNull Style style); void matchMapLanguageWithDeviceDefault(); void matchMapLanguageWithDeviceDefault(boolean acceptFallback); void setMapLanguage(@Languages String language); void setMapLanguage(@NonNull Locale locale); void setMapLanguage(@NonNull Locale locale, boolean acceptFallback); void setMapLanguage(@NonNull MapLocale mapLocale); void setCameraToLocaleCountry(int padding); void setCameraToLocaleCountry(Locale locale, int padding); void setCameraToLocaleCountry(MapLocale mapLocale, int padding); }### Answer: @Test @Ignore public void setMapLanguage_localePassedInNotValid() throws Exception { when(style.isFullyLoaded()).thenReturn(true); thrown.expect(NullPointerException.class); thrown.expectMessage(containsString("has no matching MapLocale object. You need to create")); LocalizationPlugin localizationPlugin = new LocalizationPlugin(mock(MapView.class), mock(MapboxMap.class), style); localizationPlugin.setMapLanguage(new Locale("foo", "bar"), false); }
### Question: MapLocale { @Nullable public static MapLocale getMapLocale(@NonNull Locale locale) { return getMapLocale(locale, false); } MapLocale(@NonNull String mapLanguage); MapLocale(@NonNull LatLngBounds countryBounds); MapLocale(@NonNull @Languages String mapLanguage, @Nullable LatLngBounds countryBounds); @NonNull String getMapLanguage(); @Nullable LatLngBounds getCountryBounds(); static void addMapLocale(@NonNull Locale locale, @NonNull MapLocale mapLocale); @Nullable static MapLocale getMapLocale(@NonNull Locale locale); @Nullable static MapLocale getMapLocale(@NonNull Locale locale, boolean acceptFallback); static final String LOCAL_NAME; static final String ENGLISH; static final String FRENCH; static final String ARABIC; static final String SPANISH; static final String GERMAN; static final String PORTUGUESE; static final String RUSSIAN; static final String CHINESE; static final String SIMPLIFIED_CHINESE; static final String JAPANESE; static final String KOREAN; static final MapLocale FRANCE; static final MapLocale GERMANY; static final MapLocale JAPAN; static final MapLocale KOREA; static final MapLocale CHINA; static final MapLocale TAIWAN; static final MapLocale CHINESE_HANS; static final MapLocale CHINESE_HANT; static final MapLocale UK; static final MapLocale US; static final MapLocale CANADA; static final MapLocale CANADA_FRENCH; static final MapLocale RUSSIA; static final MapLocale SPAIN; static final MapLocale PORTUGAL; static final MapLocale BRAZIL; }### Answer: @Test public void regionalVariantsNoFallbackWhenNotRequested() throws Exception { Locale localeHN = new Locale("es_HN", "Honduras"); MapLocale mapLocale = MapLocale.getMapLocale(localeHN, false); assertNull(mapLocale); }
### Question: SearchHistoryEntity implements SearchHistory { @Override public CarmenFeature getCarmenFeature() { return carmenFeature; } SearchHistoryEntity(@NonNull String placeId, CarmenFeature carmenFeature); @Override @NonNull String getPlaceId(); @Override CarmenFeature getCarmenFeature(); }### Answer: @Test public void getCarmenFeature_doesReturnTheSetCarmenFeature() throws Exception { CarmenFeature feature = CarmenFeature.builder() .id("myCarmenFeature") .properties(new JsonObject()) .build(); SearchHistoryEntity entity = new SearchHistoryEntity("placeId", feature); assertNotNull(entity.getCarmenFeature()); assertThat(entity.getCarmenFeature().id(), equalTo("myCarmenFeature")); }
### Question: DraggableAnnotationController { boolean startDragging(@NonNull Annotation annotation, @NonNull AnnotationManager annotationManager) { if (annotation.isDraggable()) { for (OnAnnotationDragListener d : (List<OnAnnotationDragListener>) annotationManager.getDragListeners()) { d.onAnnotationDragStarted(annotation); } draggedAnnotation = annotation; draggedAnnotationManager = annotationManager; return true; } return false; } @SuppressLint("ClickableViewAccessibility") DraggableAnnotationController(MapView mapView, MapboxMap mapboxMap); @VisibleForTesting DraggableAnnotationController(MapView mapView, MapboxMap mapboxMap, final AndroidGesturesManager androidGesturesManager, int touchAreaShiftX, int touchAreaShiftY, int touchAreaMaxX, int touchAreaMaxY); static DraggableAnnotationController getInstance(MapView mapView, MapboxMap mapboxMap); }### Answer: @Test public void annotationNotDraggableTest() { when(annotation.isDraggable()).thenReturn(false); draggableAnnotationController.startDragging(annotation, annotationManager); verify(dragListener, times(0)).onAnnotationDragStarted(annotation); } @Test public void annotationDragStartTest() { when(annotation.isDraggable()).thenReturn(true); when(annotationManager.getDragListeners()).thenReturn(dragListenerList); draggableAnnotationController.startDragging(annotation, annotationManager); verify(dragListener, times(1)).onAnnotationDragStarted(annotation); }
### Question: DraggableAnnotationController { void stopDragging(@Nullable Annotation annotation, @Nullable AnnotationManager annotationManager) { if (annotation != null && annotationManager != null) { for (OnAnnotationDragListener d : (List<OnAnnotationDragListener>) annotationManager.getDragListeners()) { d.onAnnotationDragFinished(annotation); } } draggedAnnotation = null; draggedAnnotationManager = null; } @SuppressLint("ClickableViewAccessibility") DraggableAnnotationController(MapView mapView, MapboxMap mapboxMap); @VisibleForTesting DraggableAnnotationController(MapView mapView, MapboxMap mapboxMap, final AndroidGesturesManager androidGesturesManager, int touchAreaShiftX, int touchAreaShiftY, int touchAreaMaxX, int touchAreaMaxY); static DraggableAnnotationController getInstance(MapView mapView, MapboxMap mapboxMap); }### Answer: @Test public void annotationDragStopNoneTest() { draggableAnnotationController.stopDragging(null, null); verify(dragListener, times(0)).onAnnotationDragFinished(annotation); } @Test public void annotationDragStopTest() { when(annotation.isDraggable()).thenReturn(true); when(annotationManager.getDragListeners()).thenReturn(dragListenerList); draggableAnnotationController.stopDragging(annotation, annotationManager); verify(dragListener, times(1)).onAnnotationDragFinished(annotation); }
### Question: CarmenFeatureConverter { @TypeConverter public static String fromCarmenFeature(@NonNull CarmenFeature carmenFeature) { return carmenFeature.toJson(); } private CarmenFeatureConverter(); @TypeConverter static CarmenFeature toCarmenFeature(String serializedCarmenFeature); @TypeConverter static String fromCarmenFeature(@NonNull CarmenFeature carmenFeature); }### Answer: @Test public void fromCarmenFeature_doesSerializeCorrectly() { String json = "{\"type\":\"Feature\",\"id\":\"id\",\"geometry\":{\"type\":\"Point\"," + "\"coordinates\":[1.0,2.0]},\"properties\":{\"hello\":\"world\"},\"address\":\"address\"," + "\"matching_place_name\":\"matchingPlaceName\",\"language\":\"language\"}"; JsonObject obj = new JsonObject(); obj.addProperty("hello", "world"); CarmenFeature carmenFeature = CarmenFeature.builder() .geometry(Point.fromLngLat(1.0, 2.0)) .address("address") .bbox(null) .id("id") .language("language") .matchingPlaceName("matchingPlaceName") .properties(obj) .build(); String serializedFeature = CarmenFeatureConverter.fromCarmenFeature(carmenFeature); assertThat(serializedFeature, equalTo(json)); }
### Question: PlacePickerOptions implements BasePlaceOptions, Parcelable { public static Builder builder() { return new AutoValue_PlacePickerOptions.Builder() .includeReverseGeocode(true) .includeDeviceLocationButton(false); } @Override @Nullable abstract String language(); @Override @Nullable abstract String geocodingTypes(); @Nullable abstract LatLngBounds startingBounds(); @Nullable @Override abstract Integer toolbarColor(); @Nullable abstract CameraPosition statingCameraPosition(); abstract boolean includeReverseGeocode(); abstract boolean includeDeviceLocationButton(); static Builder builder(); }### Answer: @Test public void builder() throws Exception { PlaceOptions.Builder builder = PlaceOptions.builder(); assertNotNull(builder); }
### Question: PlacePicker { @Nullable public static CarmenFeature getPlace(Intent data) { String json = data.getStringExtra(PlaceConstants.RETURNING_CARMEN_FEATURE); if (json == null) { return null; } return CarmenFeature.fromJson(json); } private PlacePicker(); @Nullable static CarmenFeature getPlace(Intent data); static CameraPosition getLastCameraPosition(Intent data); }### Answer: @Test public void getPlace_returnsNullWhenJsonNotFound() throws Exception { Intent data = new Intent(); CarmenFeature carmenFeature = PlacePicker.getPlace(data); assertNull(carmenFeature); } @Test public void getPlace_returnsDeserializedCarmenFeature() throws Exception { String json = "{\"type\":\"Feature\",\"id\":\"id\",\"geometry\":{\"type\":\"Point\"," + "\"coordinates\":[1.0, 2.0]},\"properties\":{},\"address\":\"address\"," + "\"matching_place_name\":\"matchingPlaceName\",\"language\":\"language\"}"; Intent data = mock(Intent.class); data.putExtra(PlaceConstants.RETURNING_CARMEN_FEATURE, json); when(data.getStringExtra(PlaceConstants.RETURNING_CARMEN_FEATURE)).thenReturn(json); CarmenFeature carmenFeature = PlacePicker.getPlace(data); assertNotNull(carmenFeature); assertThat(carmenFeature.type(), equalTo("Feature")); assertThat(carmenFeature.id(), equalTo("id")); assertThat(carmenFeature.address(), equalTo("address")); assertThat(carmenFeature.matchingPlaceName(), equalTo("matchingPlaceName")); assertThat(carmenFeature.language(), equalTo("language")); }
### Question: PlacePicker { public static CameraPosition getLastCameraPosition(Intent data) { return data.getParcelableExtra(PlaceConstants.MAP_CAMERA_POSITION); } private PlacePicker(); @Nullable static CarmenFeature getPlace(Intent data); static CameraPosition getLastCameraPosition(Intent data); }### Answer: @Test @Ignore public void getLastCameraPosition() throws Exception { CameraPosition cameraPosition = new CameraPosition.Builder() .target(new LatLng(2.0, 3.0)) .bearing(30) .zoom(20) .build(); Parcel parcel = mock(Parcel.class); cameraPosition.writeToParcel(parcel, 0); parcel.setDataPosition(0); Intent data = mock(Intent.class); data.putExtra(PlaceConstants.MAP_CAMERA_POSITION, cameraPosition); CameraPosition position = PlacePicker.getLastCameraPosition(data); assertNotNull(position); }
### Question: TightCouplingProcessor { List<List<String>> subsets(List<String> set) { List<List<String>> subsets = new ArrayList<>(); int n = set.size(); for (int i = 0; i < (1 << n); i++) { List<String> combination = new ArrayList<>(); for (int j = 0; j < n; j++) if ((i & (1 << j)) > 0) combination.add(set.get(j)); if (combination.size() == 2) subsets.add(combination); } return subsets; } TightCouplingProcessor(); TightCouplingProcessor(ProjectEvent projectEvent, Project project, Commit commit); List<View> generateView(); }### Answer: @Test public void subsetReturnsCorrectCombinations() { TightCouplingProcessor tightCouplingProcessor = new TightCouplingProcessor(); List<String> input = Arrays.asList("a", "b", "c"); List<List<String>> expected = Arrays.asList(Arrays.asList("a", "b"), Arrays.asList("a", "c"), Arrays.asList("b", "c")); List<List<String>> actual = tightCouplingProcessor.subsets(input); Assert.assertArrayEquals(expected.stream().flatMap(Collection::stream).toArray(), actual.stream().flatMap(Collection::stream).toArray()); }
### Question: InvocationStatistics { public void addInvocation(Invocation invocation) { numberOfInvocations++; if (this.methodName != null) { this.methodName = invocation.getMethodName(); } this.recentDuration = invocation.getRecentDuration(); this.lastInvocationTimestamp = invocation.getCreationTime(); String currentException = invocation.getException(); if (currentException != null) { this.exception = currentException; numberOfExceptions++; } this.recalculate(); } InvocationStatistics(String methodName); InvocationStatistics(); void addInvocation(Invocation invocation); String getMethodName(); long getRecentDuration(); long getMinDuration(); long getMaxDuration(); long getAverageDuration(); long getNumberOfExceptions(); boolean isExceptional(); String getException(); long getLastInvocationTimestamp(); long getTotalDuration(); static Comparator<InvocationStatistics> recent(); static Comparator<InvocationStatistics> unstable(); static Comparator<InvocationStatistics> slowest(); }### Answer: @Test public void addInvocation() { Invocation first = new Invocation(null, 15, null, 1); Invocation second = new Invocation(null, 15, null, 2); Invocation another = new Invocation(null, 30, null, 2); this.cut.addInvocation(first); this.cut.addInvocation(second); this.cut.addInvocation(another); long averageDuration = this.cut.getAverageDuration(); assertThat(averageDuration, is(20l)); long maxDuration = this.cut.getMaxDuration(); assertThat(maxDuration, is(30l)); long minDuration = this.cut.getMinDuration(); assertThat(minDuration, is(15l)); long lastInvocation = this.cut.getLastInvocationTimestamp(); assertThat(lastInvocation, is(2l)); long totalDuration = this.cut.getTotalDuration(); assertThat(totalDuration, is(60l)); long recentDuration = this.cut.getRecentDuration(); assertThat(recentDuration, is(30l)); }
### Question: InvocationMonitoring { public void reset() { this.statistics.clear(); } @PostConstruct void init(); void onNewCall(@Observes Invocation invocation); List<InvocationStatistics> getExceptional(); List<InvocationStatistics> getUnstable(); List<InvocationStatistics> getSlowest(); List<InvocationStatistics> getRecent(); void reset(); }### Answer: @Test public void reset() { Invocation ex1 = new Invocation("unstable", 1, "lazy - don't call me", 1); Invocation ex2 = new Invocation("does not matter", 2, null, 2); this.cut.onNewCall(ex1); this.cut.onNewCall(ex2); List<InvocationStatistics> recent = this.cut.getRecent(); assertThat(recent.size(), is(2)); this.cut.reset(); recent = this.cut.getExceptional(); assertTrue(recent.isEmpty()); }
### Question: BluetoothController implements Closeable { public boolean isBluetoothEnabled() { return bluetooth.isEnabled(); } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }### Answer: @Test public void whenTryCheckThatBluetoothIsEnabledShouldCheckThatMethodReturnCorrectData() throws Exception { Activity activity = mock(Activity.class); BluetoothDiscoveryDeviceListener listener = mock(BluetoothDiscoveryDeviceListener.class); BluetoothAdapter adapter = mock(BluetoothAdapter.class); mockStatic(BluetoothAdapter.class); when(BluetoothAdapter.getDefaultAdapter()).thenReturn(adapter); when(adapter.isEnabled()).thenReturn(true); BluetoothController controller = new BluetoothController(activity, adapter, listener); assertThat(controller.isBluetoothEnabled(), is(true)); }
### Question: BluetoothController implements Closeable { public void turnOnBluetooth() { Log.d(TAG, "Enabling Bluetooth."); broadcastReceiverDelegator.onBluetoothTurningOn(); bluetooth.enable(); } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }### Answer: @Test public void whenTryEnableBluetoothShouldCheckThatBluetoothAdapterCallEnableMethod() throws Exception { Activity activity = mock(Activity.class); BluetoothDiscoveryDeviceListener listener = mock(BluetoothDiscoveryDeviceListener.class); BluetoothAdapter adapter = mock(BluetoothAdapter.class); mockStatic(BluetoothAdapter.class); when(BluetoothAdapter.getDefaultAdapter()).thenReturn(adapter); BluetoothController controller = new BluetoothController(activity, adapter, listener); controller.turnOnBluetooth(); verify(adapter).enable(); }
### Question: BluetoothController implements Closeable { public boolean isDiscovering() { return bluetooth.isDiscovering(); } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }### Answer: @Test public void whenTryCallDiscoveringMethodOnBluetoothShouldCheckThatIsCalled() throws Exception { Activity activity = mock(Activity.class); BluetoothDiscoveryDeviceListener listener = mock(BluetoothDiscoveryDeviceListener.class); BluetoothAdapter adapter = mock(BluetoothAdapter.class); mockStatic(BluetoothAdapter.class); when(BluetoothAdapter.getDefaultAdapter()).thenReturn(adapter); BluetoothController controller = new BluetoothController(activity, adapter, listener); controller.isDiscovering(); verify(adapter).isDiscovering(); }
### Question: BluetoothController implements Closeable { public int getPairingDeviceStatus() { if (this.boundingDevice == null) { throw new IllegalStateException("No device currently bounding"); } int bondState = this.boundingDevice.getBondState(); if (bondState != BluetoothDevice.BOND_BONDING) { this.boundingDevice = null; } return bondState; } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }### Answer: @Test(expected = IllegalStateException.class) public void whenTryBoundingDeviceButDeviceIsNullShouldCheckThatThrowException() throws Exception { Activity activity = mock(Activity.class); BluetoothDiscoveryDeviceListener listener = mock(BluetoothDiscoveryDeviceListener.class); BluetoothAdapter adapter = mock(BluetoothAdapter.class); mockStatic(BluetoothAdapter.class); when(BluetoothAdapter.getDefaultAdapter()).thenReturn(adapter); BluetoothController controller = new BluetoothController(activity, adapter, listener); controller.getPairingDeviceStatus(); }
### Question: BluetoothController implements Closeable { public static String getDeviceName(BluetoothDevice device) { String deviceName = device.getName(); if (deviceName == null) { deviceName = device.getAddress(); } return deviceName; } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }### Answer: @Test public void whenTryGetDeviceNameShouldCheckThatAllIsOK() throws Exception { BluetoothDevice device = mock(BluetoothDevice.class); when(device.getName()).thenReturn("android"); assertThat(BluetoothController.getDeviceName(device), is("android")); } @Test public void whenTryGetDeviceNameButItIsNullShouldCheckThatControllerReturnAddress() throws Exception { BluetoothDevice device = mock(BluetoothDevice.class); when(device.getName()).thenReturn(null); when(device.getName()).thenReturn("08-ED-B9-49-B2-E5"); assertThat(BluetoothController.getDeviceName(device), is("08-ED-B9-49-B2-E5")); }
### Question: BluetoothController implements Closeable { public boolean isAlreadyPaired(BluetoothDevice device) { return bluetooth.getBondedDevices().contains(device); } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }### Answer: @Test public void whenTryCheckThatDevicesAlreadyPairedShouldCheckThatMethodWorksCorrect() throws Exception { Activity activity = mock(Activity.class); Set<BluetoothDevice> devices = new HashSet<>(); BluetoothDevice device = mock(BluetoothDevice.class); devices.add(device); BluetoothDiscoveryDeviceListener listener = mock(BluetoothDiscoveryDeviceListener.class); BluetoothAdapter adapter = mock(BluetoothAdapter.class); mockStatic(BluetoothAdapter.class); when(BluetoothAdapter.getDefaultAdapter()).thenReturn(adapter); when(adapter.getBondedDevices()).thenReturn(devices); BluetoothController controller = new BluetoothController(activity, adapter, listener); assertThat(controller.isAlreadyPaired(device), is(true)); }
### Question: BluetoothController implements Closeable { public static String deviceToString(BluetoothDevice device) { return "[Address: " + device.getAddress() + ", Name: " + device.getName() + "]"; } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }### Answer: @Test public void whenTryCastDeviceToStringShouldCheckThatAllIsOk() throws Exception { BluetoothDevice device = mock(BluetoothDevice.class); when(device.getName()).thenReturn("device"); when(device.getAddress()).thenReturn("08-ED-B9-49-B2-E5"); String actual = "[Address: 08-ED-B9-49-B2-E5, Name: device]"; assertEquals(actual, BluetoothController.deviceToString(device)); }
### Question: BluetoothController implements Closeable { public void turnOnBluetoothAndScheduleDiscovery() { this.bluetoothDiscoveryScheduled = true; turnOnBluetooth(); } BluetoothController(Activity context,BluetoothAdapter adapter, BluetoothDiscoveryDeviceListener listener); boolean isBluetoothEnabled(); void startDiscovery(); void turnOnBluetooth(); boolean pair(BluetoothDevice device); boolean isAlreadyPaired(BluetoothDevice device); static String deviceToString(BluetoothDevice device); @Override void close(); boolean isDiscovering(); void cancelDiscovery(); void turnOnBluetoothAndScheduleDiscovery(); void onBluetoothStatusChanged(); int getPairingDeviceStatus(); String getPairingDeviceName(); static String getDeviceName(BluetoothDevice device); boolean isPairingInProgress(); BluetoothDevice getBoundingDevice(); }### Answer: @Test public void whenTurnOnBluetoothAndScheduleDiscoveryShouldCheckThatBTenabled() throws Exception { Activity activity = mock(Activity.class); BluetoothDiscoveryDeviceListener listener = mock(BluetoothDiscoveryDeviceListener.class); BluetoothAdapter adapter = mock(BluetoothAdapter.class); mockStatic(BluetoothAdapter.class); when(BluetoothAdapter.getDefaultAdapter()).thenReturn(adapter); BluetoothController controller = new BluetoothController(activity, adapter, listener); controller.turnOnBluetoothAndScheduleDiscovery(); verify(adapter).enable(); }
### Question: Regex extends KoryphePredicate<String> { @Override public boolean test(final String input) { return !(null == input || input.getClass() != String.class) && controlValue.matcher(input).matches(); } Regex(); Regex(final String controlValue); Regex(final Pattern controlValue); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Pattern getControlValue(); void setControlValue(final Pattern controlValue); @Override boolean test(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldAccepValidValue() { final Regex filter = new Regex("te[a-d]{3}st"); boolean accepted = filter.test("teaadst"); assertTrue(accepted); } @Test public void shouldRejectInvalidValue() { final Regex filter = new Regex("fa[a-d]{3}il"); boolean accepted = filter.test("favcdil"); assertFalse(accepted); }
### Question: Regex extends KoryphePredicate<String> { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") public Pattern getControlValue() { return controlValue; } Regex(); Regex(final String controlValue); Regex(final Pattern controlValue); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Pattern getControlValue(); void setControlValue(final Pattern controlValue); @Override boolean test(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final Regex filter = new Regex("test"); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.Regex\",%n" + " \"value\" : {%n" + " \"java.util.regex.Pattern\" : \"test\"%n" + " }%n" + "}"), json); final Regex deserialisedFilter = JsonSerialiser.deserialise(json, Regex.class); assertEquals(filter.getControlValue().pattern(), deserialisedFilter.getControlValue().pattern()); assertNotNull(deserialisedFilter); }
### Question: AreIn extends KoryphePredicate<Collection<?>> { @JsonIgnore public Collection<?> getValues() { return allowedValues; } AreIn(); AreIn(final Collection<?> allowedValues); AreIn(final Object... allowedValues); @JsonIgnore Collection<?> getValues(); void setValues(final Collection<?> allowedValues); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("values") Object[] getAllowedValuesArray(); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("values") void setAllowedValues(final Object[] allowedValuesArray); @Override boolean test(final Collection<?> input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final AreIn filter = new AreIn(VALUE1); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.AreIn\",%n" + " \"values\" : [{\"uk.gov.gchq.koryphe.util.CustomObj\":{\"value\":\"1\"}}]%n" + "}"), json); final AreIn deserialisedFilter = JsonSerialiser.deserialise(json, AreIn.class); assertNotNull(deserialisedFilter); assertArrayEquals(Collections.singleton(VALUE1).toArray(), deserialisedFilter.getValues().toArray()); }
### Question: IsMoreThan extends KoryphePredicate<Comparable> implements InputValidator { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") public Comparable getControlValue() { return controlValue; } IsMoreThan(); IsMoreThan(final Comparable<?> controlValue); IsMoreThan(final Comparable controlValue, final boolean orEqualTo); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Comparable getControlValue(); void setControlValue(final Comparable controlValue); boolean getOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Comparable input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); @Override ValidationResult isInputValid(final Class<?>... arguments); }### Answer: @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final CustomObj controlValue = new CustomObj(); final IsMoreThan filter = new IsMoreThan(controlValue); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.IsMoreThan\",%n" + " \"orEqualTo\" : false,%n" + " \"value\" : {\"uk.gov.gchq.koryphe.util.CustomObj\":{\"value\":\"1\"}}%n" + "}"), json); final IsMoreThan deserialisedFilter = JsonSerialiser.deserialise(json, IsMoreThan.class); assertNotNull(deserialisedFilter); assertEquals(controlValue, deserialisedFilter.getControlValue()); }
### Question: IsMoreThan extends KoryphePredicate<Comparable> implements InputValidator { @Override public ValidationResult isInputValid(final Class<?>... arguments) { final ValidationResult result = new ValidationResult(); if (null == controlValue) { result.addError("Control value has not been set"); return result; } if (null == arguments || 1 != arguments.length || null == arguments[0]) { result.addError("Incorrect number of arguments for " + getClass().getName() + ". 1 argument is required."); return result; } if (!controlValue.getClass().isAssignableFrom(arguments[0])) { result.addError("Control value class " + controlValue.getClass().getName() + " is not compatible with the input type: " + arguments[0]); } return result; } IsMoreThan(); IsMoreThan(final Comparable<?> controlValue); IsMoreThan(final Comparable controlValue, final boolean orEqualTo); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Comparable getControlValue(); void setControlValue(final Comparable controlValue); boolean getOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Comparable input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); @Override ValidationResult isInputValid(final Class<?>... arguments); }### Answer: @Test public void shouldCheckInputClass() { final IsMoreThan predicate = new IsMoreThan(1); assertTrue(predicate.isInputValid(Integer.class).isValid()); assertFalse(predicate.isInputValid(Double.class).isValid()); assertFalse(predicate.isInputValid(Integer.class, Integer.class).isValid()); }
### Question: IsXMoreThanY extends KoryphePredicate2<Comparable, Comparable> implements InputValidator { @Override public boolean test(final Comparable input1, final Comparable input2) { return null != input1 && null != input2 && input1.getClass() == input2.getClass() && (input1.compareTo(input2) > 0); } @Override boolean test(final Comparable input1, final Comparable input2); @Override ValidationResult isInputValid(final Class<?>... arguments); }### Answer: @Test public void shouldAcceptWhenMoreThan() { final IsXMoreThanY filter = new IsXMoreThanY(); boolean accepted = filter.test(2, 1); assertTrue(accepted); } @Test public void shouldRejectTheValueWhenMoreThan() { final IsXMoreThanY filter = new IsXMoreThanY(); boolean accepted = filter.test(5, 6); assertFalse(accepted); } @Test public void shouldRejectTheValueWhenEqualTo() { final IsXMoreThanY filter = new IsXMoreThanY(); boolean accepted = filter.test(5, 5); assertFalse(accepted); }
### Question: IsXMoreThanY extends KoryphePredicate2<Comparable, Comparable> implements InputValidator { @Override public ValidationResult isInputValid(final Class<?>... arguments) { final ValidationResult result = new ValidationResult(); if (null == arguments || 2 != arguments.length || null == arguments[0] || null == arguments[1]) { result.addError("Incorrect number of arguments for " + getClass().getName() + ". 2 arguments are required."); return result; } if (!arguments[0].equals(arguments[1]) || !Comparable.class.isAssignableFrom(arguments[0])) { result.addError("Inputs must be the same class type and comparable: " + arguments[0] + "," + arguments[1]); } return result; } @Override boolean test(final Comparable input1, final Comparable input2); @Override ValidationResult isInputValid(final Class<?>... arguments); }### Answer: @Test public void shouldCheckInputClass() { final IsXLessThanY predicate = new IsXLessThanY(); assertTrue(predicate.isInputValid(Integer.class, Integer.class).isValid()); assertTrue(predicate.isInputValid(String.class, String.class).isValid()); assertFalse(predicate.isInputValid(Double.class).isValid()); assertFalse(predicate.isInputValid(Integer.class, Double.class).isValid()); }
### Question: AreEqual extends KoryphePredicate2<Object, Object> { @Override public boolean test(final Object input1, final Object input2) { if (null == input1) { return null == input2; } return input1.equals(input2); } @Override boolean test(final Object input1, final Object input2); }### Answer: @Test public void shouldAcceptTheWhenEqualValues() { final AreEqual equals = new AreEqual(); boolean accepted = equals.test("test", "test"); assertTrue(accepted); } @Test public void shouldAcceptWhenAllNull() { final AreEqual equals = new AreEqual(); boolean accepted = equals.test(null, null); assertTrue(accepted); } @Test public void shouldRejectWhenOneIsNull() { final AreEqual equals = new AreEqual(); boolean accepted = equals.test(null, "test"); assertFalse(accepted); } @Test public void shouldRejectWhenNotEqual() { final AreEqual equals = new AreEqual(); boolean accepted = equals.test("test", "test2"); assertFalse(accepted); }
### Question: IsFalse extends KoryphePredicate<Boolean> { @Override public boolean test(final Boolean input) { return Boolean.FALSE.equals(input); } @Override boolean test(final Boolean input); }### Answer: @Test public void shouldAcceptTheValueWhenFalse() { final IsFalse filter = new IsFalse(); boolean accepted = filter.test(false); assertTrue(accepted); } @Test public void shouldAcceptTheValueWhenObjectFalse() { final IsFalse filter = new IsFalse(); boolean accepted = filter.test(Boolean.FALSE); assertTrue(accepted); } @Test public void shouldRejectTheValueWhenNull() { final IsFalse filter = new IsFalse(); boolean accepted = filter.test(null); assertFalse(accepted); } @Test public void shouldRejectTheValueWhenTrue() { final IsFalse filter = new IsFalse(); boolean accepted = filter.test(true); assertFalse(accepted); }
### Question: IsA extends KoryphePredicate<Object> { @Override public boolean test(final Object input) { return null == input || null == type || type.isAssignableFrom(input.getClass()); } IsA(); IsA(final Class<?> type); IsA(final String type); void setType(final String type); String getType(); @Override boolean test(final Object input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldAcceptTheValueWhenSameClass() { final IsA predicate = new IsA(String.class); boolean valid = predicate.test("Test"); assertTrue(valid); } @Test public void shouldRejectTheValueWhenDifferentClasses() { final IsA predicate = new IsA(String.class); boolean valid = predicate.test(5); assertFalse(valid); } @Test public void shouldAcceptTheValueWhenSuperClass() { final IsA predicate = new IsA(Number.class); boolean valid = predicate.test(5); assertTrue(valid); } @Test public void shouldAcceptTheValueWhenNullValue() { final IsA predicate = new IsA(String.class); boolean valid = predicate.test(null); assertTrue(valid); }
### Question: IsA extends KoryphePredicate<Object> { public String getType() { return null != type ? type.getName() : null; } IsA(); IsA(final Class<?> type); IsA(final String type); void setType(final String type); String getType(); @Override boolean test(final Object input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldCreateIsAFromClassName() { final String type = "java.lang.String"; final IsA predicate = new IsA(type); assertNotNull(predicate); assertEquals(predicate.getType(), type); } @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final Class<Integer> type = Integer.class; final IsA filter = new IsA(type); final String json = JsonSerialiser.serialise(filter); assertEquals("{\"class\":\"uk.gov.gchq.koryphe.impl.predicate.IsA\",\"type\":\"java.lang.Integer\"}", json); final IsA deserialisedFilter = JsonSerialiser.deserialise(json, IsA.class); assertNotNull(deserialisedFilter); assertEquals(type.getName(), deserialisedFilter.getType()); }
### Question: AbstractInTimeRange extends KoryphePredicate<T> { @Override public String toString() { return new ToStringBuilder(this) .appendSuper(predicate.toString()) .toString(); } protected AbstractInTimeRange(final AbstractInTimeRangeDual<T> predicate); @Override boolean test(final T value); String getStart(); Long getStartOffset(); Boolean isStartInclusive(); String getEnd(); Long getEndOffset(); Boolean isEndInclusive(); TimeUnit getOffsetUnit(); @JsonInclude(Include.NON_DEFAULT) TimeUnit getTimeUnit(); TimeZone getTimeZone(); @JsonGetter("timeZone") String getTimeZoneId(); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldAcceptValuesInRangeDayOffsetFromStart() { final long start = System.currentTimeMillis() - 100 * DAYS_TO_MILLISECONDS; final long end = System.currentTimeMillis() - 60 * DAYS_TO_MILLISECONDS; final AbstractInTimeRange<T> filter = createBuilder() .start(Long.toString(start)) .startOffset(-7L) .end(Long.toString(end)) .endOffset(-2L) .build(); final List<Long> validValues = Arrays.asList( start - 7 * DAYS_TO_MILLISECONDS, end - 3 * DAYS_TO_MILLISECONDS, end - 2 * DAYS_TO_MILLISECONDS ); final List<Long> invalidValues = Arrays.asList( start - 7 * DAYS_TO_MILLISECONDS - 1, end - 2 * DAYS_TO_MILLISECONDS + 1, end ); testValues(true, validValues, filter); testValues(false, invalidValues, filter); }
### Question: AbstractInTimeRangeDual extends KoryphePredicate2<Comparable<T>, Comparable<T>> { @JsonGetter("timeZone") public String getTimeZoneId() { return null != timeZone ? timeZone.getID() : null; } protected AbstractInTimeRangeDual(); protected AbstractInTimeRangeDual(final Function<Long, T> toT); void initialise(); @Override boolean test(final Comparable<T> startValue, final Comparable<T> endValue); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); Long getStartOffset(); String getStart(); Boolean isStartInclusive(); Boolean isStartFullyContained(); String getEnd(); Long getEndOffset(); Boolean isEndInclusive(); Boolean isEndFullyContained(); TimeUnit getOffsetUnit(); @JsonInclude(Include.NON_DEFAULT) TimeUnit getTimeUnit(); TimeZone getTimeZone(); @JsonGetter("timeZone") String getTimeZoneId(); }### Answer: @Test public void shouldSetSystemPropertyTimeZone() { final String timeZone = "Etc/GMT+6"; System.setProperty(DateUtil.TIME_ZONE, timeZone); final AbstractInTimeRangeDual predicate = createBuilder() .start("1") .end("10") .startFullyContained(true) .endFullyContained(true) .build(); assertEquals(timeZone, predicate.getTimeZoneId()); } @Test public void shouldNotOverrideUserTimeZone() { final String timeZone = "Etc/GMT+6"; final String userTimeZone = "Etc/GMT+4"; System.setProperty(DateUtil.TIME_ZONE, timeZone); final AbstractInTimeRangeDual predicate = createBuilder() .start("1") .end("10") .startFullyContained(true) .endFullyContained(true) .timeZone(userTimeZone) .build(); assertEquals(userTimeZone, predicate.getTimeZoneId()); }
### Question: Not extends KoryphePredicate<I> implements InputValidator { @Override public boolean test(final I input) { return null != predicate && !predicate.test(input); } Not(); Not(final Predicate<I> predicate); void setPredicate(final Predicate<I> predicate); Predicate<I> getPredicate(); @Override boolean test(final I input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); @Override ValidationResult isInputValid(final Class<?>... arguments); }### Answer: @Test public void shouldAcceptTheValueWhenTheWrappedFunctionReturnsFalse() { final Predicate<String> function = mock(Predicate.class); final Not<String> filter = new Not<>(function); given(function.test("some value")).willReturn(false); boolean accepted = filter.test("some value"); assertTrue(accepted); verify(function).test("some value"); } @Test public void shouldRejectTheValueWhenTheWrappedFunctionReturnsTrue() { final Predicate<String> function = mock(Predicate.class); final Not<String> filter = new Not<>(function); given(function.test("some value")).willReturn(true); boolean accepted = filter.test("some value"); assertFalse(accepted); verify(function).test("some value"); } @Test public void shouldRejectTheValueWhenNullFunction() { final Not<String> filter = new Not<>(); boolean accepted = filter.test("some value"); assertFalse(accepted); }
### Question: Not extends KoryphePredicate<I> implements InputValidator { public Predicate<I> getPredicate() { return predicate; } Not(); Not(final Predicate<I> predicate); void setPredicate(final Predicate<I> predicate); Predicate<I> getPredicate(); @Override boolean test(final I input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); @Override ValidationResult isInputValid(final Class<?>... arguments); }### Answer: @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final IsA isA = new IsA(String.class); final Not<Object> filter = new Not<>(isA); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.Not\",%n" + " \"predicate\" : {%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.IsA\",%n" + " \"type\" : \"java.lang.String\"%n" + " }%n" + "}"), json); final Not deserialisedFilter = JsonSerialiser.deserialise(json, Not.class); assertNotNull(deserialisedFilter); assertEquals(String.class.getName(), ((IsA) deserialisedFilter.getPredicate()).getType()); }
### Question: IsTrue extends KoryphePredicate<Boolean> { @Override public boolean test(final Boolean input) { return Boolean.TRUE.equals(input); } @Override boolean test(final Boolean input); }### Answer: @Test public void shouldAcceptTheValueWhenTrue() { final IsTrue filter = new IsTrue(); boolean accepted = filter.test(true); assertTrue(accepted); } @Test public void shouldAcceptTheValueWhenObjectTrue() { final IsTrue filter = new IsTrue(); boolean accepted = filter.test(Boolean.TRUE); assertTrue(accepted); } @Test public void shouldRejectTheValueWhenNull() { final IsTrue filter = new IsTrue(); boolean accepted = filter.test(null); assertFalse(accepted); } @Test public void shouldRejectTheValueWhenFalse() { final IsTrue filter = new IsTrue(); boolean accepted = filter.test(false); assertFalse(accepted); }
### Question: IsEqual extends KoryphePredicate<Object> { @Override public boolean test(final Object input) { if (null == controlValue) { return null == input; } return controlValue.equals(input); } IsEqual(); IsEqual(final Object controlValue); @JsonProperty("value") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) Object getControlValue(); void setControlValue(final Object controlValue); @Override boolean test(final Object input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldAcceptTheTestValue() { final IsEqual filter = new IsEqual("test"); boolean accepted = filter.test("test"); assertTrue(accepted); } @Test public void shouldAcceptWhenControlValueAndTestValueAreNull() { final IsEqual filter = new IsEqual(); boolean accepted = filter.test(null); assertTrue(accepted); } @Test public void shouldRejectWhenNotEqual() { final IsEqual filter = new IsEqual("test"); boolean accepted = filter.test("a different value"); assertFalse(accepted); }
### Question: IsEqual extends KoryphePredicate<Object> { @JsonProperty("value") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) public Object getControlValue() { return controlValue; } IsEqual(); IsEqual(final Object controlValue); @JsonProperty("value") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) Object getControlValue(); void setControlValue(final Object controlValue); @Override boolean test(final Object input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final CustomObj controlValue = new CustomObj(); final IsEqual filter = new IsEqual(controlValue); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.IsEqual\",%n" + " \"value\" : {\"uk.gov.gchq.koryphe.util.CustomObj\":{\"value\":\"1\"}}%n" + "}"), json); final IsEqual deserialisedFilter = JsonSerialiser.deserialise(json, IsEqual.class); assertNotNull(deserialisedFilter); assertEquals(controlValue, deserialisedFilter.getControlValue()); }
### Question: CollectionContains extends KoryphePredicate<Collection<?>> { @Override public boolean test(final Collection<?> input) { return input.contains(value); } CollectionContains(); CollectionContains(final Object value); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") Object getValue(); void setValue(final Object value); @Override boolean test(final Collection<?> input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldAcceptWhenValueInList() { final CollectionContains filter = new CollectionContains(VALUE1); boolean accepted = filter.test(list); assertTrue(accepted); } @Test public void shouldAcceptWhenValueInSet() { final CollectionContains filter = new CollectionContains(VALUE1); boolean accepted = filter.test(set); assertTrue(accepted); } @Test public void shouldRejectWhenValueNotPresentInList() { final CollectionContains filter = new CollectionContains(VALUE2); boolean accepted = filter.test(list); assertFalse(accepted); } @Test public void shouldRejectWhenValueNotPresentInSet() { final CollectionContains filter = new CollectionContains(VALUE2); boolean accepted = filter.test(set); assertFalse(accepted); } @Test public void shouldRejectEmptyLists() { final CollectionContains filter = new CollectionContains(VALUE1); boolean accepted = filter.test(new ArrayList<>()); assertFalse(accepted); } @Test public void shouldRejectEmptySets() { final CollectionContains filter = new CollectionContains(VALUE1); boolean accepted = filter.test(new HashSet<>()); assertFalse(accepted); }
### Question: CollectionContains extends KoryphePredicate<Collection<?>> { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") public Object getValue() { return value; } CollectionContains(); CollectionContains(final Object value); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") Object getValue(); void setValue(final Object value); @Override boolean test(final Collection<?> input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final CollectionContains filter = new CollectionContains(VALUE1); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.CollectionContains\",%n" + " \"value\" : {\"class\":\"uk.gov.gchq.koryphe.util.CustomObj\", \"value\":\"1\"}%n" + "}"), json); final CollectionContains deserialisedFilter = JsonSerialiser.deserialise(json, CollectionContains.class); assertNotNull(deserialisedFilter); assertEquals(VALUE1, deserialisedFilter.getValue()); }
### Question: MapContainsPredicate extends KoryphePredicate<Map> { @Override public boolean test(final Map input) { if (null != input && null != keyPredicate) { for (final Object key : input.keySet()) { if (keyPredicate.test(key)) { return true; } } } return false; } MapContainsPredicate(); MapContainsPredicate(final Predicate keyPredicate); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") Predicate getKeyPredicate(); void setKeyPredicate(final Predicate keyPredicate); @Override boolean test(final Map input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldAcceptWhenKeyEqualsInMap() { final MapContainsPredicate filter = new MapContainsPredicate(KEY_PREDICATE_1); boolean accepted = filter.test(map1); assertTrue(accepted); } @Test public void shouldAcceptWhenKeyRegexInMap() { final MapContainsPredicate filter = new MapContainsPredicate(KEY_PREDICATE_2); boolean accepted = filter.test(map1); assertTrue(accepted); } @Test public void shouldRejectWhenKeyNotPresent() { final MapContainsPredicate filter = new MapContainsPredicate(KEY_PREDICATE_NOT_IN_MAP); boolean accepted = filter.test(map1); assertFalse(accepted); } @Test public void shouldRejectEmptyMaps() { final MapContainsPredicate filter = new MapContainsPredicate(KEY_PREDICATE_1); boolean accepted = filter.test(new HashMap()); assertFalse(accepted); }
### Question: MapContainsPredicate extends KoryphePredicate<Map> { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") public Predicate getKeyPredicate() { return keyPredicate; } MapContainsPredicate(); MapContainsPredicate(final Predicate keyPredicate); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") Predicate getKeyPredicate(); void setKeyPredicate(final Predicate keyPredicate); @Override boolean test(final Map input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final MapContainsPredicate filter = new MapContainsPredicate(KEY_PREDICATE_1); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals("{" + "\"class\":\"uk.gov.gchq.koryphe.impl.predicate.MapContainsPredicate\"," + "\"keyPredicate\":{" + "\"class\":\"uk.gov.gchq.koryphe.impl.predicate.IsEqual\"," + "\"value\":\"key1\"" + "}" + "}", json); final MapContainsPredicate deserialisedFilter = JsonSerialiser.deserialise(json, MapContainsPredicate.class); assertNotNull(deserialisedFilter); assertEquals(KEY_PREDICATE_1, deserialisedFilter.getKeyPredicate()); }
### Question: AgeOffFromDays extends KoryphePredicate2<Long, Integer> { @Override public boolean test(final Long timestamp, final Integer days) { return null != timestamp && null != days && (System.currentTimeMillis() - (days * DAYS_TO_MILLISECONDS) < timestamp); } @Override boolean test(final Long timestamp, final Integer days); static final long DAYS_TO_MILLISECONDS; }### Answer: @Test public void shouldAcceptWhenWithinAgeOffLimit() { final AgeOffFromDays filter = new AgeOffFromDays(); final boolean accepted = filter.test(System.currentTimeMillis() - AGE_OFF_MILLISECONDS + MINUTE_IN_MILLISECONDS, AGE_OFF_DAYS); assertTrue(accepted); } @Test public void shouldAcceptWhenOutsideAgeOffLimit() { final AgeOffFromDays filter = new AgeOffFromDays(); final boolean accepted = filter.test(System.currentTimeMillis() - AGE_OFF_MILLISECONDS - DAY_IN_MILLISECONDS, AGE_OFF_DAYS); assertFalse(accepted); } @Test public void shouldNotAcceptWhenTimestampIsNull() { final AgeOffFromDays filter = new AgeOffFromDays(); final boolean accepted = filter.test(null, 0); assertFalse(accepted); } @Test public void shouldNotAcceptWhenDaysIsNull() { final AgeOffFromDays filter = new AgeOffFromDays(); final boolean accepted = filter.test(0L, null); assertFalse(accepted); }
### Question: IsLessThan extends KoryphePredicate<Comparable> implements InputValidator { @Override public ValidationResult isInputValid(final Class<?>... arguments) { final ValidationResult result = new ValidationResult(); if (null == controlValue) { result.addError("Control value has not been set"); return result; } if (null == arguments || 1 != arguments.length || null == arguments[0]) { result.addError("Incorrect number of arguments for " + getClass().getName() + ". 1 argument is required."); return result; } if (!controlValue.getClass().isAssignableFrom(arguments[0])) { result.addError("Control value class " + controlValue.getClass().getName() + " is not compatible with the input type: " + arguments[0]); } return result; } IsLessThan(); IsLessThan(final Comparable<?> controlValue); IsLessThan(final Comparable controlValue, final boolean orEqualTo); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Comparable getControlValue(); void setControlValue(final Comparable controlValue); boolean getOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Comparable input); @Override ValidationResult isInputValid(final Class<?>... arguments); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldCheckInputClass() { final IsLessThan predicate = new IsLessThan(1); assertTrue(predicate.isInputValid(Integer.class).isValid()); assertFalse(predicate.isInputValid(Double.class).isValid()); assertFalse(predicate.isInputValid(Integer.class, Integer.class).isValid()); }
### Question: IsLongerThan extends KoryphePredicate<Object> implements InputValidator { public int getMinLength() { return minLength; } IsLongerThan(); IsLongerThan(final int minLength); IsLongerThan(final int minLength, final boolean orEqualTo); int getMinLength(); void setMinLength(final int minLength); boolean isOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Object input); @Override ValidationResult isInputValid(final Class<?>... arguments); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final int min = 5; final IsLongerThan filter = new IsLongerThan(min); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.IsLongerThan\",%n" + " \"orEqualTo\" : false,%n" + " \"minLength\" : 5%n" + "}"), json); final IsLongerThan deserialisedFilter = JsonSerialiser.deserialise(json, IsLongerThan.class); assertNotNull(deserialisedFilter); assertEquals(min, deserialisedFilter.getMinLength()); }
### Question: MapContains extends KoryphePredicate<Map> { @Override public boolean test(final Map input) { return input.containsKey(key); } MapContains(); MapContains(final String key); String getKey(); void setKey(final String key); @Override boolean test(final Map input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldAcceptWhenKeyInMap() { final MapContains filter = new MapContains(KEY1); boolean accepted = filter.test(map1); assertTrue(accepted); } @Test public void shouldRejectWhenKeyNotPresent() { final MapContains filter = new MapContains(KEY2); boolean accepted = filter.test(map1); assertFalse(accepted); } @Test public void shouldRejectEmptyMaps() { final MapContains filter = new MapContains(KEY1); boolean accepted = filter.test(new HashMap<>()); assertFalse(accepted); }
### Question: MapContains extends KoryphePredicate<Map> { public String getKey() { return key; } MapContains(); MapContains(final String key); String getKey(); void setKey(final String key); @Override boolean test(final Map input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final MapContains filter = new MapContains(KEY1); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.MapContains\",%n" + " \"key\" : \"key1\"%n" + "}"), json); final MapContains deserialisedFilter = JsonSerialiser.deserialise(json, MapContains.class); assertNotNull(deserialisedFilter); assertEquals(KEY1, deserialisedFilter.getKey()); }
### Question: IsXLessThanY extends KoryphePredicate2<Comparable, Comparable> implements InputValidator { @Override public boolean test(final Comparable input1, final Comparable input2) { return null != input1 && null != input2 && input1.getClass() == input2.getClass() && (input1.compareTo(input2) < 0); } @Override boolean test(final Comparable input1, final Comparable input2); @Override ValidationResult isInputValid(final Class<?>... arguments); }### Answer: @Test public void shouldAcceptWhenLessThan() { final IsXLessThanY filter = new IsXLessThanY(); boolean accepted = filter.test(1, 2); assertTrue(accepted); } @Test public void shouldRejectTheValueWhenMoreThan() { final IsXLessThanY filter = new IsXLessThanY(); boolean accepted = filter.test(6, 5); assertFalse(accepted); } @Test public void shouldRejectTheValueWhenEqualTo() { final IsXLessThanY filter = new IsXLessThanY(); boolean accepted = filter.test(5, 5); assertFalse(accepted); }
### Question: IsXLessThanY extends KoryphePredicate2<Comparable, Comparable> implements InputValidator { @Override public ValidationResult isInputValid(final Class<?>... arguments) { final ValidationResult result = new ValidationResult(); if (null == arguments || 2 != arguments.length || null == arguments[0] || null == arguments[1]) { result.addError("Incorrect number of arguments for " + getClass().getName() + ". 2 arguments are required."); return result; } if (!arguments[0].equals(arguments[1]) || !Comparable.class.isAssignableFrom(arguments[0])) { result.addError("Inputs must be the same class type and comparable: " + arguments[0] + "," + arguments[1]); } return result; } @Override boolean test(final Comparable input1, final Comparable input2); @Override ValidationResult isInputValid(final Class<?>... arguments); }### Answer: @Test public void shouldCheckInputClass() { final IsXLessThanY predicate = new IsXLessThanY(); assertTrue(predicate.isInputValid(Integer.class, Integer.class).isValid()); assertTrue(predicate.isInputValid(String.class, String.class).isValid()); assertFalse(predicate.isInputValid(Double.class).isValid()); assertFalse(predicate.isInputValid(Integer.class, Double.class).isValid()); }
### Question: AgeOff extends KoryphePredicate<Long> { public long getAgeOffTime() { return ageOffTime; } AgeOff(); AgeOff(final long ageOffTime); @Override boolean test(final Long input); long getAgeOffTime(); void setAgeOffTime(final long ageOffTime); void setAgeOffDays(final int ageOfDays); void setAgeOffHours(final long ageOfHours); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); static final long HOURS_TO_MILLISECONDS; static final long DAYS_TO_MILLISECONDS; static final long AGE_OFF_TIME_DEFAULT; }### Answer: @Test public void shouldUseDefaultAgeOffTime() { final AgeOff filter = new AgeOff(); final long ageOfTime = filter.getAgeOffTime(); assertEquals(AgeOff.AGE_OFF_TIME_DEFAULT, ageOfTime); } @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final AgeOff filter = new AgeOff(CUSTOM_AGE_OFF); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.AgeOff\",%n" + " \"ageOffTime\" : 100000%n" + "}"), json); final AgeOff deserialisedFilter = JsonSerialiser.deserialise(json, AgeOff.class); assertNotNull(deserialisedFilter); assertEquals(CUSTOM_AGE_OFF, deserialisedFilter.getAgeOffTime()); }
### Question: AgeOff extends KoryphePredicate<Long> { @Override public boolean test(final Long input) { return null != input && (System.currentTimeMillis() - input) < ageOffTime; } AgeOff(); AgeOff(final long ageOffTime); @Override boolean test(final Long input); long getAgeOffTime(); void setAgeOffTime(final long ageOffTime); void setAgeOffDays(final int ageOfDays); void setAgeOffHours(final long ageOfHours); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); static final long HOURS_TO_MILLISECONDS; static final long DAYS_TO_MILLISECONDS; static final long AGE_OFF_TIME_DEFAULT; }### Answer: @Test public void shouldAcceptWhenWithinAgeOffLimit() { final AgeOff filter = new AgeOff(CUSTOM_AGE_OFF); final boolean accepted = filter.test(System.currentTimeMillis() - CUSTOM_AGE_OFF + MINUTE_IN_MILLISECONDS); assertTrue(accepted); } @Test public void shouldAcceptWhenOutsideAgeOffLimit() { final AgeOff filter = new AgeOff(CUSTOM_AGE_OFF); final boolean accepted = filter.test(System.currentTimeMillis() - CUSTOM_AGE_OFF - MINUTE_IN_MILLISECONDS); assertFalse(accepted); }
### Question: IsIn extends KoryphePredicate<Object> { @Override public boolean test(final Object input) { return null != allowedValues && allowedValues.contains(input); } IsIn(); IsIn(final Collection<Object> controlData); IsIn(final Object... controlData); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("values") Object[] getAllowedValuesArray(); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("values") void setAllowedValues(final Object[] allowedValuesArray); @JsonIgnore Set<Object> getAllowedValues(); void setAllowedValues(final Set<Object> allowedValues); @Override boolean test(final Object input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldAcceptWhenValueInList() { final IsIn filter = new IsIn(Arrays.asList("A", "B", "C")); boolean accepted = filter.test("B"); assertTrue(accepted); } @Test public void shouldRejectWhenValueNotInList() { final IsIn filter = new IsIn(Arrays.asList("A", "B", "C")); boolean accepted = filter.test("D"); assertFalse(accepted); }
### Question: IsIn extends KoryphePredicate<Object> { @JsonIgnore public Set<Object> getAllowedValues() { return allowedValues; } IsIn(); IsIn(final Collection<Object> controlData); IsIn(final Object... controlData); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("values") Object[] getAllowedValuesArray(); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("values") void setAllowedValues(final Object[] allowedValuesArray); @JsonIgnore Set<Object> getAllowedValues(); void setAllowedValues(final Set<Object> allowedValues); @Override boolean test(final Object input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final Object[] controlData = {1, new CustomObj(), 3}; final IsIn filter = new IsIn(Arrays.asList(controlData)); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.IsIn\",%n" + " \"values\" : [ 1, {\"uk.gov.gchq.koryphe.util.CustomObj\":{\"value\":\"1\"}}, 3 ]%n" + "}"), json); final IsIn deserialisedFilter = JsonSerialiser.deserialise(json, IsIn.class); assertNotNull(deserialisedFilter); assertEquals(Sets.newHashSet(controlData), deserialisedFilter.getAllowedValues()); }
### Question: Exists extends KoryphePredicate<Object> { @Override public boolean test(final Object input) { return null != input; } @Override boolean test(final Object input); }### Answer: @Test public void shouldAcceptTheValueWhenNotNull() { final Exists filter = new Exists(); boolean accepted = filter.test("Not null value"); assertTrue(accepted); } @Test public void shouldRejectTheValueWhenNull() { final Exists filter = new Exists(); boolean accepted = filter.test(null); assertFalse(accepted); }
### Question: MultiRegex extends KoryphePredicate<String> { @Override public boolean test(final String input) { if (null == input || input.getClass() != String.class) { return false; } for (final Pattern pattern : patterns) { if (pattern.matcher(input).matches()) { return true; } } return false; } MultiRegex(); MultiRegex(final Pattern... patterns); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Pattern[] getPatterns(); void setPatterns(final Pattern[] patterns); @Override boolean test(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldAcceptValidValue() { Pattern[] patterns = new Pattern[2]; patterns[0] = Pattern.compile("fail"); patterns[1] = Pattern.compile("pass"); final MultiRegex filter = new MultiRegex(patterns); boolean accepted = filter.test("pass"); assertTrue(accepted); } @Test public void shouldRejectInvalidValue() { Pattern[] patterns = new Pattern[2]; patterns[0] = Pattern.compile("fail"); patterns[1] = Pattern.compile("reallyFail"); final MultiRegex filter = new MultiRegex(patterns); boolean accepted = filter.test("pass"); assertFalse(accepted); }
### Question: MultiRegex extends KoryphePredicate<String> { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") public Pattern[] getPatterns() { return Arrays.copyOf(patterns, patterns.length); } MultiRegex(); MultiRegex(final Pattern... patterns); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("value") Pattern[] getPatterns(); void setPatterns(final Pattern[] patterns); @Override boolean test(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { Pattern[] patterns = new Pattern[2]; patterns[0] = Pattern.compile("test"); patterns[1] = Pattern.compile("test2"); final MultiRegex filter = new MultiRegex(patterns); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.MultiRegex\",%n" + " \"value\" : [ {%n" + " \"java.util.regex.Pattern\" : \"test\"%n" + " }, {%n" + " \"java.util.regex.Pattern\" : \"test2\"%n" + " } ]%n" + "}"), json); final MultiRegex deserialisedFilter = JsonSerialiser.deserialise(json, MultiRegex.class); assertNotNull(deserialisedFilter); assertEquals(patterns[0].pattern(), deserialisedFilter.getPatterns()[0].pattern()); assertEquals(patterns[1].pattern(), deserialisedFilter.getPatterns()[1].pattern()); }
### Question: IsShorterThan extends KoryphePredicate<Object> implements InputValidator { public int getMaxLength() { return maxLength; } IsShorterThan(); IsShorterThan(final int maxLength); IsShorterThan(final int maxLength, final boolean orEqualTo); int getMaxLength(); void setMaxLength(final int maxLength); boolean isOrEqualTo(); void setOrEqualTo(final boolean orEqualTo); @Override boolean test(final Object input); @Override ValidationResult isInputValid(final Class<?>... arguments); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final int max = 5; final IsShorterThan filter = new IsShorterThan(max); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.IsShorterThan\",%n" + " \"orEqualTo\" : false,%n" + " \"maxLength\" : 5%n" + "}"), json); final IsShorterThan deserialisedFilter = JsonSerialiser.deserialise(json, IsShorterThan.class); assertNotNull(deserialisedFilter); assertEquals(max, deserialisedFilter.getMaxLength()); }
### Question: StringConcat extends KorypheBinaryOperator<String> { public void setSeparator(final String separator) { this.separator = separator; } StringConcat(); StringConcat(final String separator); @Override String _apply(final String a, final String b); String getSeparator(); void setSeparator(final String separator); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldConcatStringsTogether() { final StringConcat function = new StringConcat(); function.setSeparator(";"); state = function.apply(state, "1"); state = function.apply(state, "2"); state = function.apply(state, null); assertEquals("1;2", state); }
### Question: StringDeduplicateConcat extends KorypheBinaryOperator<String> { @Override protected String _apply(final String a, final String b) { final Set<String> set = new LinkedHashSet<>(); Collections.addAll(set, p.split(StringUtils.removeStart(a, separator))); Collections.addAll(set, p.split(StringUtils.removeStart(b, separator))); return StringUtils.join(set, separator); } String getSeparator(); void setSeparator(final String separator); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldRemoveDuplicate() { final StringDeduplicateConcat sdc = new StringDeduplicateConcat(); String output = sdc._apply("test,string", "test,success"); assertEquals("test,string,success", output); } @Test public void shouldHandleTrailingDelimiter() { final StringDeduplicateConcat sdc = new StringDeduplicateConcat(); String output = sdc._apply("test,for,", "trailing,delimiters,"); assertEquals("test,for,trailing,delimiters", output); } @Test public void shouldHandleLeadingDelimiter() { final StringDeduplicateConcat sdc = new StringDeduplicateConcat(); String output = sdc._apply(",test,for", ",leading,delimiters"); assertEquals("test,for,leading,delimiters", output); }
### Question: ExtractKeys extends KorypheFunction<Map<K, V>, Iterable<K>> { @Override public Iterable<K> apply(final Map<K, V> map) { return null == map ? null : map.keySet(); } @Override Iterable<K> apply(final Map<K, V> map); }### Answer: @Test public void shouldExtractKeysFromGivenMap() { final ExtractKeys<String, Integer> function = new ExtractKeys<>(); final Map<String, Integer> input = new HashMap<>(); input.put("first", 1); input.put("second", 2); input.put("third", 3); final Iterable<String> results = function.apply(input); assertEquals(Sets.newHashSet("first", "second", "third"), results); } @Test public void shouldReturnEmptySetForEmptyMap() { final ExtractKeys<String, String> function = new ExtractKeys<>(); final Iterable<String> results = function.apply(new HashMap<>()); assertTrue(Iterables.isEmpty(results)); } @Test public void shouldReturnNullForNullInput() { final ExtractKeys<String, String> function = new ExtractKeys<>(); final Map<String, String> input = null; final Iterable result = function.apply(input); assertNull(result); }
### Question: DivideBy extends KorypheFunction<Integer, Tuple2<Integer, Integer>> { @Override public Tuple2<Integer, Integer> apply(final Integer input) { if (input == null) { return null; } else { return new Tuple2<>(input / by, input % by); } } DivideBy(); DivideBy(final int by); int getBy(); void setBy(final int by); @Override Tuple2<Integer, Integer> apply(final Integer input); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test public void shouldDivideBy2() { final DivideBy function = new DivideBy(2); Tuple2<Integer, Integer> output = function.apply(4); assertEquals(new Tuple2<>(2, 0), output); } @Test public void shouldDivideBy2WithRemainder() { final DivideBy function = new DivideBy(2); Tuple2<Integer, Integer> output = function.apply(5); assertEquals(new Tuple2<>(2, 1), output); } @Test public void shouldDivideBy1IfByIsNull() { final DivideBy function = new DivideBy(); Tuple2<Integer, Integer> output = function.apply(9); assertEquals(new Tuple2<>(9, 0), output); }
### Question: DivideBy extends KorypheFunction<Integer, Tuple2<Integer, Integer>> { public int getBy() { return by; } DivideBy(); DivideBy(final int by); int getBy(); void setBy(final int by); @Override Tuple2<Integer, Integer> apply(final Integer input); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test @Override public void shouldJsonSerialiseAndDeserialise() throws IOException { final DivideBy function = new DivideBy(4); final String json = JsonSerialiser.serialise(function); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.function.DivideBy\",%n" + " \"by\" : 4%n" + "}"), json); final DivideBy deserialisedDivideBy = JsonSerialiser.deserialise(json, DivideBy.class); assertNotNull(deserialisedDivideBy); assertEquals(4, deserialisedDivideBy.getBy()); }
### Question: StringRegexSplit extends KorypheFunction<String, List<String>> { @Override public List<String> apply(final String input) { if (null == input) { return null; } final Pattern pattern = Pattern.compile(regex); return Arrays.asList(pattern.split(input)); } StringRegexSplit(); StringRegexSplit(final String regex); @Override List<String> apply(final String input); String getRegex(); void setRegex(final String regex); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test public void shouldHandleNullInput() { final StringRegexSplit function = new StringRegexSplit(); final List<String> result = function.apply(null); assertNull(result); } @Test public void shouldSplitString() { final StringRegexSplit function = new StringRegexSplit(","); final String input = "first,second,third"; final List<String> result = function.apply(input); assertThat(result, hasItems("first", "second", "third")); }
### Question: FirstValid extends KorypheFunction<Iterable<I_ITEM>, I_ITEM> { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") public Predicate getPredicate() { return predicate; } FirstValid(); FirstValid(final Predicate predicate); @Override I_ITEM apply(final Iterable<I_ITEM> iterable); FirstValid<I_ITEM> predicate(final Predicate predicate); FirstValid<I_ITEM> setPredicate(final Predicate predicate); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") Predicate getPredicate(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test @Override public void shouldJsonSerialiseAndDeserialise() throws IOException { final FirstValid predicate = getInstance(); final String json = JsonSerialiser.serialise(predicate); JsonSerialiser.assertEquals("{" + "\"class\":\"uk.gov.gchq.koryphe.impl.function.FirstValid\"," + "\"predicate\":{\"class\":\"uk.gov.gchq.koryphe.impl.predicate.IsMoreThan\",\"orEqualTo\":false,\"value\":1}" + "}", json); final FirstValid deserialised = JsonSerialiser.deserialise(json, FirstValid.class); assertNotNull(deserialised); assertEquals(1, ((IsMoreThan) deserialised.getPredicate()).getControlValue()); }
### Question: ToLong extends KorypheFunction<Object, Long> { @Override public Long apply(final Object value) { if (null == value) { return null; } if (value instanceof Number) { return ((Number) value).longValue(); } if (value instanceof String) { return Long.valueOf(((String) value)); } throw new IllegalArgumentException("Could not convert value to Long: " + value); } @Override Long apply(final Object value); }### Answer: @Test public void shouldConvertToLong() { final ToLong function = new ToLong(); Object output = function.apply(5); assertEquals(5L, output); assertEquals(Long.class, output.getClass()); } @Test public void shouldReturnNullWhenValueIsNull() { final ToLong function = new ToLong(); final Object output = function.apply(null); assertNull(output); }
### Question: NthItem extends KorypheFunction<Iterable<T>, T> { public int getSelection() { return selection; } NthItem(); NthItem(final int selection); @Override @SuppressFBWarnings(value = "DE_MIGHT_IGNORE", justification = "Any exceptions are to be ignored") T apply(final Iterable<T> input); void setSelection(final int selection); int getSelection(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test @Override public void shouldJsonSerialiseAndDeserialise() throws IOException { final NthItem function = new NthItem(2); final String json = JsonSerialiser.serialise(function); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.function.NthItem\",%n" + " \"selection\" : 2%n" + "}"), json); final NthItem deserialised = JsonSerialiser.deserialise(json, NthItem.class); assertNotNull(deserialised); assertEquals(2, deserialised.getSelection()); }