method2testcases
stringlengths
118
3.08k
### Question: UserResourceTemplate implements UserResource { @Override public Me me() { return restTemplate.getForObject("https: } UserResourceTemplate(final RestTemplate restTemplate); @Override Me me(); }### Answer: @Test void me() { mockServer.expect(requestTo("https: .andExpect(method(GET)) .andRespond(withSuccess(new ClassPathResource("/user/me.json", getClass()), APPLICATION_JSON)); final Me me = userResource.me(); assertThat(me.getId()).isEqualTo("553d437215522ed4b3df8c50"); assertThat(me.getUsername()).isEqualTo("MadLittleMods"); assertThat(me.getDisplayName()).isEqualTo("Eric Eastwood"); assertThat(me.getUrl()).isEqualTo("/MadLittleMods"); assertThat(me.getAvatarUrl()).isEqualTo("https: }
### Question: RequestRestController { @GetMapping(value = "/github/{owner}/{repo}/{number}") public RequestView requestDetails(@PathVariable("owner") final String repoOwner, @PathVariable("repo") final String repo, @PathVariable("number") final String issueNumber) { final RequestDto request = requestService.findRequest(Platform.GITHUB, String.format("%s|FR|%s|FR|%s", repoOwner, repo, issueNumber)); return mappers.map(RequestDto.class, RequestView.class, request); } RequestRestController(final RequestService requestService, final Mappers mappers); @GetMapping(value = "/github/{owner}/{repo}/{number}/claimable") ClaimView claimDetails(@PathVariable("owner") final String repoOwner, @PathVariable("repo") final String repo, @PathVariable("number") final String issueNumber); @GetMapping(value = "/github/{owner}/{repo}/{number}") RequestView requestDetails(@PathVariable("owner") final String repoOwner, @PathVariable("repo") final String repo, @PathVariable("number") final String issueNumber); }### Answer: @Test void requestDetails() throws Exception { final String owner = "fundrequest"; final String repo = "platform"; final String issueNumber = "320"; final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); final RequestView requestView = mapper.map(requestDto); final String platformId = owner + "|FR|" + repo + "|FR|" + issueNumber; when(requestService.findRequest(GITHUB, platformId)).thenReturn(requestDto); when(mappers.map(RequestDto.class, RequestView.class, requestDto)).thenReturn(requestView); mockMvc.perform(get("/rest/requests/github/{owner}/{repo}/{number}", owner, repo, issueNumber).accept(MediaType.APPLICATION_JSON_UTF8)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().json(objectMapper.writeValueAsString(requestView))); }
### Question: GithubScraper { @Cacheable("github_issues") public GithubIssue fetchGithubIssue(final String owner, final String repo, final String number) { Document document; try { document = jsoup.connect("https: } catch (IOException e) { throw new RuntimeException(e); } return GithubIssue.builder() .owner(owner) .repo(repo) .number(number) .solver(solverResolver.resolve(document, GithubId.builder().owner(owner).repo(repo).number(number).build()).orElse(null)) .status(statusResolver.resolve(document)) .build(); } GithubScraper(final JsoupSpringWrapper jsoup, final GithubSolverResolver solverResolver, final GithubStatusResolver statusResolver); @Cacheable("github_issues") GithubIssue fetchGithubIssue(final String owner, final String repo, final String number); }### Answer: @Test public void fetchGithubIssue() throws IOException { final String owner = "fdv"; final String repo = "sdfgdh"; final String number = "46576"; final String expectedSolver = "gfhcgj"; final String expectedStatus = "Open"; final Document document = mock(Document.class); when(jsoup.connect("https: when(solverParser.resolve(document, GithubId.builder().owner(owner).repo(repo).number(number).build())).thenReturn(Optional.of(expectedSolver)); when(statusParser.resolve(document)).thenReturn(expectedStatus); final GithubIssue returnedIssue = scraper.fetchGithubIssue(owner, repo, number); assertThat(returnedIssue.getOwner()).isEqualTo(owner); assertThat(returnedIssue.getRepo()).isEqualTo(repo); assertThat(returnedIssue.getNumber()).isEqualTo(number); assertThat(returnedIssue.getSolver()).isEqualTo(expectedSolver); assertThat(returnedIssue.getStatus()).isEqualTo(expectedStatus); }
### Question: GithubStatusResolver { public String resolve(final Document document) { return document.select("#partial-discussion-header .State").first().text(); } String resolve(final Document document); }### Answer: @Test public void parseOpen() { final Document document = mock(Document.class, RETURNS_DEEP_STUBS); final String expectedStatus = "Open"; when(document.select("#partial-discussion-header .State").first().text()).thenReturn(expectedStatus); final String returnedStatus = parser.resolve(document); assertThat(returnedStatus).isEqualTo(expectedStatus); } @Test public void parseClosed() { final Document document = mock(Document.class, RETURNS_DEEP_STUBS); final String expectedStatus = "Closed"; when(document.select("#partial-discussion-header .State").first().text()).thenReturn(expectedStatus); final String returnedStatus = parser.resolve(document); assertThat(returnedStatus).isEqualTo(expectedStatus); }
### Question: GithubId { public static Optional<GithubId> fromPlatformId(final String platformId) { final Pattern pattern = Pattern.compile("^(?<owner>.+)\\|FR\\|(?<repo>.+)\\|FR\\|(?<number>\\d+)$"); final Matcher matcher = pattern.matcher(platformId); if (matcher.matches()) { return Optional.of(GithubId.builder() .owner(matcher.group("owner")) .repo(matcher.group("repo")) .number(matcher.group("number")) .build()); } return Optional.empty(); } static Optional<GithubId> fromString(final String githubIdAsString); static Optional<GithubId> fromPlatformId(final String platformId); }### Answer: @Test public void fromPlatformId() { final String owner = "fgagsfgfas"; final String repo = "bdfdb"; final String number = "213"; final Optional<GithubId> result = GithubId.fromPlatformId(String.format("%s|FR|%s|FR|%s", owner, repo, number)); assertThat(result).isPresent() .contains(GithubId.builder().owner(owner).repo(repo).number(number).build()); } @Test public void fromPlatformId_noMatchEmpty() { final Optional<GithubId> result = GithubId.fromPlatformId("fgagsfgfas|FR|bdfdb|FR"); assertThat(result).isEmpty(); }
### Question: GithubSolverResolver { public Optional<String> resolve(final Document document, final GithubId issueGithubId) { return document.select(".TimelineItem") .stream() .filter(this::isPullRequest) .filter(this::isMerged) .map(this::resolvePullRequestGithubId) .map(this::fetchPullrequest) .filter(pullRequest -> pullRequest != null && pullRequestFixesIssue(pullRequest, issueGithubId)) .map(pullRequest -> pullRequest.getUser().getLogin()) .filter(StringUtils::isNotEmpty) .findFirst(); } GithubSolverResolver(final GithubGateway githubGateway); Optional<String> resolve(final Document document, final GithubId issueGithubId); }### Answer: @Test void parse_noDiscussionItems() { final GithubId issueGithubId = GithubId.builder().owner("tfjgk").repo("hfcjgv").number("35").build(); final Document doc = DocumentMockBuilder.documentBuilder().build(); final Optional<String> result = parser.resolve(doc, issueGithubId); assertThat(result).isEmpty(); }
### Question: GithubTemplateResource implements ITemplateResource { @Override public String getDescription() { return String.format("%s/%s/%s/%s", owner, repo, branch, location); } GithubTemplateResource(final String owner, final String repo, final String branch, final String location, final GithubRawClient githubRawClient); @Override String getDescription(); @Override String getBaseName(); @Override boolean exists(); @Override Reader reader(); @Override GithubTemplateResource relative(String relativeLocation); }### Answer: @Test void getDescription() { assertThat(resource.getDescription()).isEqualTo(owner + "/" + repo + "/" + branch + "/" + location); }
### Question: GithubTemplateResource implements ITemplateResource { @Override public String getBaseName() { return location; } GithubTemplateResource(final String owner, final String repo, final String branch, final String location, final GithubRawClient githubRawClient); @Override String getDescription(); @Override String getBaseName(); @Override boolean exists(); @Override Reader reader(); @Override GithubTemplateResource relative(String relativeLocation); }### Answer: @Test void getBaseName() { assertThat(resource.getBaseName()).isEqualTo(location); }
### Question: GithubTemplateResource implements ITemplateResource { @Override public boolean exists() { return StringUtils.isNotBlank(fetchTemplateContents()); } GithubTemplateResource(final String owner, final String repo, final String branch, final String location, final GithubRawClient githubRawClient); @Override String getDescription(); @Override String getBaseName(); @Override boolean exists(); @Override Reader reader(); @Override GithubTemplateResource relative(String relativeLocation); }### Answer: @Test void exists() { when(githubRawClient.getContentsAsRaw(owner, repo, branch, location)).thenReturn("fasgzd"); final boolean result = resource.exists(); assertThat(result).isTrue(); } @Test void exists_contentsEmpty() { when(githubRawClient.getContentsAsRaw(owner, repo, branch, location)).thenReturn(""); final boolean result = resource.exists(); assertThat(result).isFalse(); } @Test void exists_githubclientException() { doThrow(new RuntimeException()).when(githubRawClient).getContentsAsRaw(owner, repo, branch, location); final boolean result = resource.exists(); assertThat(result).isFalse(); }
### Question: GithubTemplateResource implements ITemplateResource { @Override public Reader reader() { final String templateContents = fetchTemplateContents(); return StringUtils.isNotBlank(templateContents) ? new StringReader(templateContents) : null; } GithubTemplateResource(final String owner, final String repo, final String branch, final String location, final GithubRawClient githubRawClient); @Override String getDescription(); @Override String getBaseName(); @Override boolean exists(); @Override Reader reader(); @Override GithubTemplateResource relative(String relativeLocation); }### Answer: @Test void reader() throws IOException { final String expected = "fasgzd"; when(githubRawClient.getContentsAsRaw(owner, repo, branch, location)).thenReturn(expected); final Reader result = resource.reader(); assertThat(IOUtils.toString(result)).isEqualTo(expected); }
### Question: GithubTemplateResource implements ITemplateResource { @Override public GithubTemplateResource relative(String relativeLocation) { return new GithubTemplateResource(owner, repo, branch, relativeLocation, githubRawClient); } GithubTemplateResource(final String owner, final String repo, final String branch, final String location, final GithubRawClient githubRawClient); @Override String getDescription(); @Override String getBaseName(); @Override boolean exists(); @Override Reader reader(); @Override GithubTemplateResource relative(String relativeLocation); }### Answer: @Test void relative() { final String relativeLocation = "cxncvx"; final GithubTemplateResource result = resource.relative(relativeLocation); assertThat(result.getOwner()).isEqualTo(owner); assertThat(result.getRepo()).isEqualTo(repo); assertThat(result.getBranch()).isEqualTo(branch); assertThat(result.getLocation()).isEqualTo(relativeLocation); }
### Question: OpenRequestsNotificationsController extends AbstractController { @GetMapping("/notifications/open-requests") public ModelAndView showGenerateTemplateForm(final Model model) { return modelAndView(model).withView("notifications/open-requests") .withObject("projects", requestService.findAllProjects()) .withObject("technologies", requestService.findAllTechnologies()) .withObject("targetPlatforms", TargetPlatform.values()) .build(); } OpenRequestsNotificationsController(final NotificationsTemplateService notificationsTemplateService, final RequestService requestService); @GetMapping("/notifications/open-requests") ModelAndView showGenerateTemplateForm(final Model model); @GetMapping("/notifications/open-requests/template") ModelAndView showGeneratedTemplate(final Model model, @RequestParam(required = false) final List<String> projects, @RequestParam(required = false) final List<String> technologies, @RequestParam(name = "last-updated", required = false) String lastUpdatedSinceDays, @RequestParam(name = "target-platform") TargetPlatform targetPlatform); }### Answer: @Test void showGenerateTemplateForm() throws Exception { final HashSet<String> projects = new HashSet<>(); final HashSet<String> technologies = new HashSet<>(); when(requestService.findAllProjects()).thenReturn(projects); when(requestService.findAllTechnologies()).thenReturn(technologies); this.mockMvc.perform(get("/notifications/open-requests")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.view().name("notifications/open-requests")) .andExpect(MockMvcResultMatchers.model().attribute("projects", sameInstance(projects))) .andExpect(MockMvcResultMatchers.model().attribute("technologies", sameInstance(technologies))) .andExpect(MockMvcResultMatchers.model().attribute("targetPlatforms", TargetPlatform.values())); }
### Question: GithubCommentFactory { public String createFundedComment(final Long requestId, final String githubIssueNumber) { return String.format(FUNDED_COMMENT_TEMPLATE, platformBasePath, requestId, githubIssueNumber); } GithubCommentFactory(@Value("${io.fundrequest.platform.base-path}") final String platformBasePath, @Value("${io.fundrequest.etherscan.basepath}") final String etherscanBasePath); String createFundedComment(final Long requestId, final String githubIssueNumber); String createResolvedComment(final Long requestId, final String solver); String createClosedComment(final Long requestId, final String solver, final String transactionHash); }### Answer: @Test public void createFundedComment() { final long requestId = 156; final String githubIssueNumber = "8765"; final String result = githubCommentFactory.createFundedComment(requestId, githubIssueNumber); assertThat(result).isEqualTo(EXPECTED_FUNDED_COMMENT); }
### Question: GithubCommentFactory { public String createResolvedComment(final Long requestId, final String solver) { return String.format(RESOLVED_COMMENT_TEMPLATE, platformBasePath, requestId, solver); } GithubCommentFactory(@Value("${io.fundrequest.platform.base-path}") final String platformBasePath, @Value("${io.fundrequest.etherscan.basepath}") final String etherscanBasePath); String createFundedComment(final Long requestId, final String githubIssueNumber); String createResolvedComment(final Long requestId, final String solver); String createClosedComment(final Long requestId, final String solver, final String transactionHash); }### Answer: @Test public void createResolvedComment() { final long requestId = 635; final String solver = "dfghd-ghjgfg"; final String result = githubCommentFactory.createResolvedComment(requestId, solver); assertThat(result).isEqualTo(EXPECTED_RESOLVED_COMMENT); }
### Question: GithubCommentFactory { public String createClosedComment(final Long requestId, final String solver, final String transactionHash) { return String.format(CLOSED_COMMENT_TEMPLATE, platformBasePath, requestId, solver, etherscanBasePath, transactionHash); } GithubCommentFactory(@Value("${io.fundrequest.platform.base-path}") final String platformBasePath, @Value("${io.fundrequest.etherscan.basepath}") final String etherscanBasePath); String createFundedComment(final Long requestId, final String githubIssueNumber); String createResolvedComment(final Long requestId, final String solver); String createClosedComment(final Long requestId, final String solver, final String transactionHash); }### Answer: @Test public void createClosedComment() { final long requestId = 5473; final String solver = "ljn-ytd"; final String transactionHash = "ZWQ1R12QBPMI7AS6PCCQ"; final String result = githubCommentFactory.createClosedComment(requestId, solver, transactionHash); assertThat(result).isEqualTo(EXPECTED_CLOSED_COMMENT); }
### Question: GithubIssueService { public Optional<GithubIssue> findBy(final String platformId) { return GithubId.fromPlatformId(platformId) .map(githubId -> githubScraper.fetchGithubIssue(githubId.getOwner(), githubId.getRepo(), githubId.getNumber())); } GithubIssueService(final GithubScraper githubScraper); Optional<GithubIssue> findBy(final String platformId); }### Answer: @Test void findBy() { final String owner = "sfs"; final String repo = "fafsa"; final String number = "43"; final GithubIssue githubIssue = GithubIssue.builder().build(); when(githubScraper.fetchGithubIssue(owner, repo, number)).thenReturn(githubIssue); final Optional<GithubIssue> result = githubIssueService.findBy(owner + "|FR|" + repo + "|FR|" + number); assertThat(result).isPresent().containsSame(githubIssue); } @Test void findBy_invalidPlatformId() { final String owner = "sfs"; final String repo = "fafsa"; final Optional<GithubIssue> result = githubIssueService.findBy(owner + "|FR|" + repo + "|FR|"); assertThat(result).isEmpty(); } @Test void findBy_noIssueFound() { final String owner = "sfs"; final String repo = "fafsa"; final String number = "43"; when(githubScraper.fetchGithubIssue(owner, repo, number)).thenReturn(null); final Optional<GithubIssue> result = githubIssueService.findBy(owner + "|FR|" + repo + "|FR|" + number); assertThat(result).isEmpty(); }
### Question: EmptyFAQServiceImpl implements FAQService { public FaqItemsDto getFAQsForPage(final String pageName) { return new FaqItemsDto(DUMMY_FAQS_SUBTITLE, DUMMY_FAQ_ITEMS); } EmptyFAQServiceImpl(); FaqItemsDto getFAQsForPage(final String pageName); }### Answer: @Test void getFAQsForPage() { assertThat(new EmptyFAQServiceImpl().getFAQsForPage("").getFaqItems()).isEmpty(); }
### Question: UserProfile { public boolean userOwnsAddress(String address) { return getEtherAddresses().stream().anyMatch(x -> x.equalsIgnoreCase(address)); } boolean userOwnsAddress(String address); boolean hasEtherAddress(); }### Answer: @Test void userOwnsAddress() { Wallet wallet = WalletMother.aWallet(); UserProfile userProfile = UserProfile.builder() .etherAddresses(Collections.singletonList(wallet.getAddress())) .linkedin(null) .github(null) .arkane(null) .google(null) .wallets(Collections.singletonList(wallet)).build(); assertThat(userProfile.userOwnsAddress(wallet.getAddress())).isTrue(); }
### Question: BountyServiceImpl implements BountyService { @Override @Transactional(readOnly = true) public List<PaidBountyDto> getPaidBounties(Principal principal) { return bountyRepository.findByUserId(principal.getName()) .stream() .filter(f -> StringUtils.isNotBlank(f.getTransactionHash())) .sorted(Comparator.comparing(AbstractEntity::getCreationDate).reversed()) .map(b -> PaidBountyDto.builder() .type(b.getType()) .amount(b.getType().getReward()) .transactionHash(b.getTransactionHash()) .build() ) .collect(Collectors.toList()); } BountyServiceImpl(BountyRepository bountyRepository); @Transactional @Override void createBounty(CreateBountyCommand createBountyCommand); @Override BountyDTO getBounties(final Principal principal); @Override @Transactional(readOnly = true) List<PaidBountyDto> getPaidBounties(Principal principal); }### Answer: @Test void getPaidBounties() { Principal principal = () -> "davyvanroy"; Bounty bounty = Bounty.builder().type(BountyType.LINK_GITHUB).build(); ReflectionTestUtils.setField(bounty, "transactionHash", "0x0"); when(bountyRepository.findByUserId(principal.getName())).thenReturn(Collections.singletonList(bounty)); List<PaidBountyDto> result = bountyService.getPaidBounties(principal); assertThat(result).hasSize(1); }
### Question: GithubBountyServiceImpl implements GithubBountyService, ApplicationListener<AuthenticationSuccessEvent> { @Override @Transactional public void onApplicationEvent(AuthenticationSuccessEvent event) { Authentication principal = event.getAuthentication(); UserProfile userProfile = profileService.getUserProfile(principal); if (userProfile.getGithub() != null && StringUtils.isNotBlank(userProfile.getGithub().getUserId())) { createBountyWhenNecessary(principal, userProfile); } } GithubBountyServiceImpl(ProfileService profileService, GithubBountyRepository githubBountyRepository, BountyService bountyService, GithubGateway githubGateway, ApplicationEventPublisher eventPublisher); @EventListener @Transactional void onProviderLinked(UserLinkedProviderEvent event); @Override @Transactional void onApplicationEvent(AuthenticationSuccessEvent event); @Override @Transactional(readOnly = true) GithubVerificationDto getVerification(Principal principal); }### Answer: @Test public void onAuthenticationChecksGithubSignup() { Authentication authentication = mock(Authentication.class, RETURNS_DEEP_STUBS); when(authentication.getName()).thenReturn("davy"); when(profileService.getUserProfile(authentication)) .thenReturn(UserProfile.builder().github(UserProfileProvider.builder().userId("id").username("davy").build()).verifiedDeveloper(true).build()); when(githubGateway.getUser("davy")).thenReturn(GithubUser.builder().createdAt(LocalDateTime.of(2017, 1, 1, 1, 1)).location("Belgium").build()); githubBountyService.onApplicationEvent(new AuthenticationSuccessEvent(authentication)); verifyBountiesSaved(); }
### Question: GithubBountyServiceImpl implements GithubBountyService, ApplicationListener<AuthenticationSuccessEvent> { @EventListener @Transactional public void onProviderLinked(UserLinkedProviderEvent event) { if (event.getProvider() == Provider.GITHUB && event.getPrincipal() != null) { UserProfile userProfile = profileService.getUserProfile(event.getPrincipal()); createBountyWhenNecessary(event.getPrincipal(), userProfile); } } GithubBountyServiceImpl(ProfileService profileService, GithubBountyRepository githubBountyRepository, BountyService bountyService, GithubGateway githubGateway, ApplicationEventPublisher eventPublisher); @EventListener @Transactional void onProviderLinked(UserLinkedProviderEvent event); @Override @Transactional void onApplicationEvent(AuthenticationSuccessEvent event); @Override @Transactional(readOnly = true) GithubVerificationDto getVerification(Principal principal); }### Answer: @Test public void onProviderLinked() { Authentication authentication = mock(Authentication.class, RETURNS_DEEP_STUBS); when(authentication.getName()).thenReturn("davy"); when(profileService.getUserProfile(authentication)) .thenReturn(UserProfile.builder().github(UserProfileProvider.builder().userId("id").username("davy").build()).verifiedDeveloper(true).build()); when(githubGateway.getUser("davy")).thenReturn(GithubUser.builder().createdAt(LocalDateTime.of(2017, 1, 1, 1, 1)).location("Belgium").build()); githubBountyService.onProviderLinked(UserLinkedProviderEvent.builder().principal(authentication).provider(Provider.GITHUB).build()); verifyBountiesSaved(); }
### Question: EnumToCapitalizedStringMapper implements BaseMapper<Enum, String> { @Override public String map(final Enum anEnum) { if (anEnum == null) { return null; } return WordUtils.capitalizeFully(anEnum.name().replace('_', ' ')); } @Override String map(final Enum anEnum); }### Answer: @Test void map() { assertThat(mapper.map(TestEnum.BLABLABLA)).isEqualTo("Blablabla"); assertThat(mapper.map(TestEnum.BLIBLIBLI)).isEqualTo("Bliblibli"); assertThat(mapper.map(SomeOtherTestEnum.BLOBLOBLO)).isEqualTo("Blobloblo"); } @Test void map_null() { assertThat(mapper.map(null)).isNull(); }
### Question: UserServiceImpl implements UserService { @Override @Transactional(readOnly = true) public UserDto getUser(String email) { return userDtoMapper.map( userRepository.findOne(email).orElse(null) ); } UserServiceImpl(UserRepository userRepository, UserDtoMapper userDtoMapper); @Override @Transactional(readOnly = true) UserDto getUser(String email); @Override @Transactional @Cacheable("loginUserData") @Deprecated UserAuthentication login(UserLoginCommand loginCommand); }### Answer: @Test public void getUser() throws Exception { User user = UserMother.davy(); UserDto userDto = UserDtoMother.davy(); when(userRepository.findOne(user.getEmail())).thenReturn(Optional.of(user)); when(userDtoMapper.map(user)).thenReturn(userDto); UserDto result = userService.getUser(user.getEmail()); assertThat(result).isEqualToComparingFieldByField(userDto); }
### Question: GithubIssueToPlatformIssueDtoMapper implements BaseMapper<GithubIssue, PlatformIssueDto> { @Override public PlatformIssueDto map(final GithubIssue githubIssue) { return PlatformIssueDto.builder() .platform(GITHUB) .platformId(buildPlatformId(githubIssue)) .status(isClosed(githubIssue) ? CLOSED : OPEN) .build(); } @Override PlatformIssueDto map(final GithubIssue githubIssue); }### Answer: @Test void map_statusOpen() { final String owner = "dbfv"; final String repo = "sgs"; final String number = "435"; final PlatformIssueDto result = mapper.map(GithubIssue.builder().solver("svdzdv").owner(owner).repo(repo).number(number).status("Open").build()); assertThat(result.getPlatform()).isEqualTo(GITHUB); assertThat(result.getPlatformId()).isEqualTo(owner + PLATFORM_ID_GITHUB_DELIMTER + repo + PLATFORM_ID_GITHUB_DELIMTER + number); assertThat(result.getStatus()).isEqualTo(OPEN); } @Test void map_statusClosed() { final String owner = "gsb"; final String repo = "gukf"; final String number = "3278"; final PlatformIssueDto result = mapper.map(GithubIssue.builder().solver("svdzdv").owner(owner).repo(repo).number(number).status("Closed").build()); assertThat(result.getPlatform()).isEqualTo(GITHUB); assertThat(result.getPlatformId()).isEqualTo(owner + PLATFORM_ID_GITHUB_DELIMTER + repo + PLATFORM_ID_GITHUB_DELIMTER + number); assertThat(result.getStatus()).isEqualTo(CLOSED); }
### Question: MessageServiceImpl implements MessageService { @Transactional(readOnly = true) @Override public List<MessageDto> getMessagesByType(MessageType type) { return repository.findByType(type, new Sort(Sort.Direction.DESC, "name")) .stream() .parallel() .map(m -> objectMapper.convertValue(m, MessageDto.class)) .collect(Collectors.toList()); } MessageServiceImpl(MessageRepository repository, ObjectMapper objectMapper); @Transactional(readOnly = true) @Override List<MessageDto> getMessagesByType(MessageType type); @Override MessageDto getMessageByKey(String key); @Override MessageDto getMessageByTypeAndName(MessageType type, String name); @Transactional @Override Message update(MessageDto messageDto); @Transactional @Override Message add(MessageDto messageDto); @Transactional @Override void delete(MessageType type, String name); }### Answer: @Test void getMessagesByType() { Message message2 = mock(Message.class); Message message3 = mock(Message.class); MessageDto messageDto2 = mock(MessageDto.class); MessageDto messageDto3 = mock(MessageDto.class); when(objectMapper.convertValue(same(message2), eq(MessageDto.class))).thenReturn(messageDto2); when(objectMapper.convertValue(same(message3), eq(MessageDto.class))).thenReturn(messageDto3); when(messageRepository.findByType(MessageType.REFERRAL_SHARE, new Sort(Sort.Direction.DESC, "name"))) .thenReturn(Arrays.asList(message1, message2, message3)); List<MessageDto> result = messageService.getMessagesByType(MessageType.REFERRAL_SHARE); assertThat(result).containsExactly(messageDto1, messageDto2, messageDto3); }
### Question: MessageServiceImpl implements MessageService { @Override public MessageDto getMessageByKey(String key) { int indexSeperator = key.indexOf('.'); if (indexSeperator > 0) { String type = key.substring(0, indexSeperator); String name = key.substring(indexSeperator + 1); return getMessageByTypeAndName(MessageType.valueOf(type.toUpperCase()), name); } else { return null; } } MessageServiceImpl(MessageRepository repository, ObjectMapper objectMapper); @Transactional(readOnly = true) @Override List<MessageDto> getMessagesByType(MessageType type); @Override MessageDto getMessageByKey(String key); @Override MessageDto getMessageByTypeAndName(MessageType type, String name); @Transactional @Override Message update(MessageDto messageDto); @Transactional @Override Message add(MessageDto messageDto); @Transactional @Override void delete(MessageType type, String name); }### Answer: @Test void getMessageByKey() { MessageDto result = messageService.getMessageByKey("REFERRAL_SHARE.message1"); assertThat(result).isEqualTo(messageDto1); } @Test void getMessageByKey_invalidKey() { MessageDto result = messageService.getMessageByKey("INVALIDKEY"); assertThat(result).isNull(); }
### Question: MessageServiceImpl implements MessageService { @Override public MessageDto getMessageByTypeAndName(MessageType type, String name) { Message m = repository.findByTypeAndName(type, name).orElseThrow(() -> new RuntimeException("Message not found")); return objectMapper.convertValue(m, MessageDto.class); } MessageServiceImpl(MessageRepository repository, ObjectMapper objectMapper); @Transactional(readOnly = true) @Override List<MessageDto> getMessagesByType(MessageType type); @Override MessageDto getMessageByKey(String key); @Override MessageDto getMessageByTypeAndName(MessageType type, String name); @Transactional @Override Message update(MessageDto messageDto); @Transactional @Override Message add(MessageDto messageDto); @Transactional @Override void delete(MessageType type, String name); }### Answer: @Test void getMessageByTypeAndName() { MessageDto result = messageService.getMessageByTypeAndName(MessageType.REFERRAL_SHARE, "message1"); assertThat(result).isEqualTo(messageDto1); } @Test void getMessageByTypeAndName_throwsExceptionWhenNotFound() { when(messageRepository.findByTypeAndName(MessageType.REFERRAL_SHARE, "doesnotexist")) .thenReturn(Optional.empty()); try { messageService.getMessageByTypeAndName(MessageType.REFERRAL_SHARE, "doesnotexist"); failBecauseExceptionWasNotThrown(RuntimeException.class); } catch (RuntimeException e) { assertThat(e.getMessage()).isEqualTo("Message not found"); } }
### Question: MessageServiceImpl implements MessageService { @Transactional @Override public Message update(MessageDto messageDto) { Message m = repository.findByTypeAndName(messageDto.getType(), messageDto.getName()).orElseThrow(() -> new RuntimeException("Message not found")); messageDto.setId(m.getId()); Message newM = objectMapper.convertValue(messageDto, Message.class); return repository.save(newM); } MessageServiceImpl(MessageRepository repository, ObjectMapper objectMapper); @Transactional(readOnly = true) @Override List<MessageDto> getMessagesByType(MessageType type); @Override MessageDto getMessageByKey(String key); @Override MessageDto getMessageByTypeAndName(MessageType type, String name); @Transactional @Override Message update(MessageDto messageDto); @Transactional @Override Message add(MessageDto messageDto); @Transactional @Override void delete(MessageType type, String name); }### Answer: @Test void update() { when(objectMapper.convertValue(messageDto1, Message.class)).thenReturn(message1); when(messageRepository.save(message1)).thenReturn(message1); assertThat(messageService.update(messageDto1)).isEqualTo(message1); } @Test void update_throwsExceptionWhenNotExists() { MessageDto messageDto = mock(MessageDto.class); try { messageService.update(messageDto); failBecauseExceptionWasNotThrown(RuntimeException.class); } catch (RuntimeException e) { assertThat(e.getMessage()).isEqualTo("Message not found"); } }
### Question: MessageServiceImpl implements MessageService { @Transactional @Override public void delete(MessageType type, String name) { repository.deleteByTypeAndName(type, name); } MessageServiceImpl(MessageRepository repository, ObjectMapper objectMapper); @Transactional(readOnly = true) @Override List<MessageDto> getMessagesByType(MessageType type); @Override MessageDto getMessageByKey(String key); @Override MessageDto getMessageByTypeAndName(MessageType type, String name); @Transactional @Override Message update(MessageDto messageDto); @Transactional @Override Message add(MessageDto messageDto); @Transactional @Override void delete(MessageType type, String name); }### Answer: @Test void delete() { messageService.delete(message1.getType(), message1.getName()); verify(messageRepository).deleteByTypeAndName(message1.getType(), message1.getName()); }
### Question: TokenValueMapper { public TokenValueDto map(final String tokenAddress, final BigDecimal rawBalance) { final TokenInfoDto tokenInfo = tokenInfoService.getTokenInfo(tokenAddress); return tokenInfo == null ? null : TokenValueDto.builder() .tokenAddress(tokenInfo.getAddress()) .tokenSymbol(tokenInfo.getSymbol()) .totalAmount(fromWei(rawBalance, tokenInfo.getDecimals())) .build(); } TokenValueMapper(final TokenInfoService tokenInfoService); TokenValueDto map(final String tokenAddress, final BigDecimal rawBalance); }### Answer: @Test void map() { final String tokenAddress = "dafsd"; final String symbol = "ZRX"; final BigDecimal rawBalance = new BigDecimal("1000000000000000000"); final int decimals = 18; final TokenInfoDto tokenInfoDto = TokenInfoDto.builder().address(tokenAddress).symbol(symbol).decimals(decimals).build(); when(tokenInfoService.getTokenInfo(tokenAddress)).thenReturn(tokenInfoDto); final TokenValueDto result = mapper.map(tokenAddress, rawBalance); assertThat(result.getTokenAddress()).isEqualTo(tokenAddress); assertThat(result.getTokenSymbol()).isEqualTo(symbol); assertThat(result.getTotalAmount()).isEqualTo(fromWei(rawBalance, decimals)); } @Test void map_tokenInfoNull() { final String tokenAddress = "dafsd"; when(tokenInfoService.getTokenInfo(tokenAddress)).thenReturn(null); final TokenValueDto result = mapper.map(tokenAddress, new BigDecimal("1000000000000000000")); assertThat(result).isNull(); }
### Question: SecurityContextServiceImpl implements SecurityContextService { @Override public Optional<Authentication> getLoggedInUser() { return Optional.ofNullable(securityContextHolder.getContext().getAuthentication()); } SecurityContextServiceImpl(final SecurityContextHolderSpringDelegate securityContextHolder, final ProfileService profileService); @Override Optional<Authentication> getLoggedInUser(); @Override boolean isUserFullyAuthenticated(); @Override Optional<UserProfile> getLoggedInUserProfile(); }### Answer: @Test public void getLoggedInUser_present() { final Authentication expected = mock(Authentication.class); when(securityContextHolder.getContext().getAuthentication()).thenReturn(expected); final Optional<Authentication> loggedInUser = securityContextService.getLoggedInUser(); assertThat(loggedInUser).containsSame(expected); } @Test public void getLoggedInUser_notPresent() { when(securityContextHolder.getContext().getAuthentication()).thenReturn(null); final Optional<Authentication> loggedInUser = securityContextService.getLoggedInUser(); assertThat(loggedInUser).isEmpty(); }
### Question: SecurityContextServiceImpl implements SecurityContextService { @Override public boolean isUserFullyAuthenticated() { return isUserFullyAuthenticated(securityContextHolder.getContext().getAuthentication()); } SecurityContextServiceImpl(final SecurityContextHolderSpringDelegate securityContextHolder, final ProfileService profileService); @Override Optional<Authentication> getLoggedInUser(); @Override boolean isUserFullyAuthenticated(); @Override Optional<UserProfile> getLoggedInUserProfile(); }### Answer: @Test public void isUserFullyAuthenticated() { final Authentication authentication = mock(Authentication.class); when(authentication.isAuthenticated()).thenReturn(true); when(securityContextHolder.getContext().getAuthentication()).thenReturn(authentication); final boolean result = securityContextService.isUserFullyAuthenticated(); assertThat(result).isTrue(); } @Test public void isUserFullyAuthenticated_noAuthentication() { when(securityContextHolder.getContext().getAuthentication()).thenReturn(null); final boolean result = securityContextService.isUserFullyAuthenticated(); assertThat(result).isFalse(); } @Test public void isUserFullyAuthenticated_notAuthentciated() { final Authentication authentication = mock(Authentication.class); when(authentication.isAuthenticated()).thenReturn(false); when(securityContextHolder.getContext().getAuthentication()).thenReturn(authentication); final boolean result = securityContextService.isUserFullyAuthenticated(); assertThat(result).isFalse(); } @Test public void isUserFullyAuthenticated_AnonymousAuthenticationToken() { final Authentication authentication = spy(new AnonymousAuthenticationToken("dssg", "htesn", Arrays.asList((GrantedAuthority) () -> "dhfgj", (GrantedAuthority) () -> "dhfc"))); when(authentication.isAuthenticated()).thenReturn(true); when(securityContextHolder.getContext().getAuthentication()).thenReturn(authentication); final boolean result = securityContextService.isUserFullyAuthenticated(); assertThat(result).isFalse(); }
### Question: GithubLinkValidator implements ConstraintValidator<GithubLink, String> { public boolean isValid(String link, ConstraintValidatorContext context) { return StringUtils.isEmpty(link) || link.matches(regex); } GithubLinkValidator(); void initialize(GithubLink constraint); boolean isValid(String link, ConstraintValidatorContext context); }### Answer: @Test public void illegalNotGithub() throws Exception { assertThat( validator.isValid("https: ).isFalse(); } @Test public void illegalInvalidGithub() throws Exception { assertThat( validator.isValid("https: ).isFalse(); } @Test public void validGithubLink() throws Exception { assertThat( validator.isValid("https: ).isTrue(); }
### Question: ClaimDtoMapperDecorator implements ClaimDtoMapper { @Override public ClaimDto map(Claim r) { final ClaimDto dto = delegate.map(r); if (dto != null) { dto.setTransactionHash(blockchainEventService.findOne(r.getBlockchainEventId()) .map(BlockchainEventDto::getTransactionHash) .orElse("")); } return dto; } @Override ClaimDto map(Claim r); }### Answer: @Test void map() { final long blockchainEventId = 465L; final Claim claim = Claim.builder().blockchainEventId(blockchainEventId).build(); final String transactionHash = "rqwerwet"; when(delegate.map(claim)).thenReturn(new ClaimDto()); when(blockchainEventService.findOne(blockchainEventId)).thenReturn(Optional.of(BlockchainEventDto.builder().transactionHash(transactionHash).build())); final ClaimDto result = decorator.map(claim); assertThat(result.getTransactionHash()).isEqualTo(transactionHash); } @Test void map_null() { when(delegate.map(null)).thenReturn(null); final ClaimDto result = decorator.map(null); assertThat(result).isNull(); } @Test void map_blockchainEventEmpty() { final long blockchainEventId = 465L; final Claim claim = Claim.builder().blockchainEventId(blockchainEventId).build(); when(delegate.map(claim)).thenReturn(new ClaimDto()); when(blockchainEventService.findOne(blockchainEventId)).thenReturn(Optional.empty()); final ClaimDto result = decorator.map(claim); assertThat(result.getTransactionHash()).isEmpty(); }
### Question: ClaimServiceImpl implements ClaimService { @Override @Transactional(readOnly = true) public Optional<ClaimDto> findOne(final Long id) { return claimRepository.findOne(id).map(claim -> mappers.map(Claim.class, ClaimDto.class, claim)); } ClaimServiceImpl(final RequestRepository requestRepository, final ClaimRepository claimRepository, final RequestClaimRepository requestClaimRepository, final GithubClaimResolver githubClaimResolver, final Mappers mappers, final ClaimDtoAggregator claimDtoAggregator, final ApplicationEventPublisher eventPublisher); @Override @Transactional(readOnly = true) Optional<ClaimDto> findOne(final Long id); @Transactional @Override void claim(Principal user, UserClaimRequest userClaimRequest); @Override @Transactional(readOnly = true) ClaimsByTransactionAggregate getAggregatedClaimsForRequest(final long requestId); @EventListener void onClaimed(final RequestClaimedEvent claimedEvent); }### Answer: @Test public void findClaim() { final long claimId = 697L; final Claim claim = Claim.builder().build(); final ClaimDto expected = ClaimDtoMother.aClaimDto().build(); when(claimRepository.findOne(claimId)).thenReturn(Optional.of(claim)); when(mappers.map(eq(Claim.class), eq(ClaimDto.class), same(claim))).thenReturn(expected); final Optional<ClaimDto> result = claimService.findOne(claimId); assertThat(result).containsSame(expected); } @Test public void findClaim_notFound() { final long claimId = 697L; when(claimRepository.findOne(claimId)).thenReturn(Optional.empty()); final Optional<ClaimDto> result = claimService.findOne(claimId); assertThat(result).isEmpty(); }
### Question: ClaimServiceImpl implements ClaimService { @Override @Transactional(readOnly = true) public ClaimsByTransactionAggregate getAggregatedClaimsForRequest(final long requestId) { return claimDtoAggregator.aggregateClaims(mappers.mapList(Claim.class, ClaimDto.class, claimRepository.findByRequestId(requestId))); } ClaimServiceImpl(final RequestRepository requestRepository, final ClaimRepository claimRepository, final RequestClaimRepository requestClaimRepository, final GithubClaimResolver githubClaimResolver, final Mappers mappers, final ClaimDtoAggregator claimDtoAggregator, final ApplicationEventPublisher eventPublisher); @Override @Transactional(readOnly = true) Optional<ClaimDto> findOne(final Long id); @Transactional @Override void claim(Principal user, UserClaimRequest userClaimRequest); @Override @Transactional(readOnly = true) ClaimsByTransactionAggregate getAggregatedClaimsForRequest(final long requestId); @EventListener void onClaimed(final RequestClaimedEvent claimedEvent); }### Answer: @Test public void getClaimedBy() { final long requestId = 567L; final List<Claim> claims = new ArrayList<>(); final List<ClaimDto> claimDtos = new ArrayList<>(); final Principal principal = mock(Principal.class); final ClaimsByTransactionAggregate claimsByTransactionAggregate = mock(ClaimsByTransactionAggregate.class); when(principal.getName()).thenReturn("hfgj"); when(claimRepository.findByRequestId(requestId)).thenReturn(claims); when(mappers.mapList(eq(Claim.class), eq(ClaimDto.class), same(claims))).thenReturn(claimDtos); when(claimDtoAggregator.aggregateClaims(same(claimDtos))).thenReturn(claimsByTransactionAggregate); final ClaimsByTransactionAggregate result = claimService.getAggregatedClaimsForRequest(requestId); assertThat(result).isSameAs(claimsByTransactionAggregate); }
### Question: ClaimServiceImpl implements ClaimService { @EventListener public void onClaimed(final RequestClaimedEvent claimedEvent) { requestClaimRepository.findByRequestId(claimedEvent.getRequestDto().getId()) .forEach(requestClaim -> { requestClaim.setStatus(ClaimRequestStatus.PROCESSED); requestClaimRepository.save(requestClaim); }); } ClaimServiceImpl(final RequestRepository requestRepository, final ClaimRepository claimRepository, final RequestClaimRepository requestClaimRepository, final GithubClaimResolver githubClaimResolver, final Mappers mappers, final ClaimDtoAggregator claimDtoAggregator, final ApplicationEventPublisher eventPublisher); @Override @Transactional(readOnly = true) Optional<ClaimDto> findOne(final Long id); @Transactional @Override void claim(Principal user, UserClaimRequest userClaimRequest); @Override @Transactional(readOnly = true) ClaimsByTransactionAggregate getAggregatedClaimsForRequest(final long requestId); @EventListener void onClaimed(final RequestClaimedEvent claimedEvent); }### Answer: @Test public void onClaimed() { long requestId = 3124L; final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); requestDto.setId(requestId); final RequestClaim requestClaim1 = RequestClaim.builder().status(ClaimRequestStatus.PENDING).build(); final RequestClaim requestClaim2 = RequestClaim.builder().status(ClaimRequestStatus.PENDING).build(); when(requestClaimRepository.findByRequestId(requestId)).thenReturn(Arrays.asList(requestClaim1, requestClaim2)); claimService.onClaimed(RequestClaimedEvent.builder() .blockchainEventId(324L) .requestDto(requestDto) .build()); assertThat(requestClaim1.getStatus()).isEqualTo(PROCESSED); assertThat(requestClaim2.getStatus()).isEqualTo(PROCESSED); verify(requestClaimRepository).save(requestClaim1); verify(requestClaimRepository).save(requestClaim2); }
### Question: GitterService { @Cacheable("gitter_fund_notification_rooms") public List<String> listFundedNotificationRooms() { try { final String roomsRaw = githubRawClient.getContentsAsRaw("FundRequest", "content-management", branch, filePath); final GitterRooms gitterRooms = objectMapper.readValue(roomsRaw, GitterRooms.class); return gitterRooms.getFundedNotification(); } catch (IOException e) { throw new RuntimeException(e); } } GitterService(final GithubRawClient githubRawClient, final String branch, final String path, final ObjectMapper objectMapper); @Cacheable("gitter_fund_notification_rooms") List<String> listFundedNotificationRooms(); }### Answer: @Test void listFundedNotificationChannels() throws IOException { final String json = "json"; final List<String> expectedChannels = Arrays.asList("FundRequest/funded-requests-test", "FundRequest/funded-requests", "FundRequest/funded-requests-blablabla"); final GitterRooms gitterRooms = new GitterRooms(); gitterRooms.setFundedNotification(expectedChannels); when(githubRawClient.getContentsAsRaw("FundRequest", "content-management", branch, filePath)).thenReturn(json); when(objectMapper.readValue(json, GitterRooms.class)).thenReturn(gitterRooms); final List<String> result = gitterService.listFundedNotificationRooms(); assertThat(result).isEqualTo(expectedChannels); }
### Question: KafkaMetricsSet implements MetricSet { public Boolean connectionToKafkaTopicsIsSuccess() { if (nonNull(metricTopics) && nonNull(connectionTimeoutTopic)) { StopWatch executionTime = StopWatch.createStarted(); DescribeTopicsOptions describeTopicsOptions = new DescribeTopicsOptions().timeoutMs( connectionTimeoutTopic); try (AdminClient adminClient = AdminClient.create(kafkaAdmin.getConfig())) { try { DescribeTopicsResult describeTopicsResult = adminClient.describeTopics( metricTopics, describeTopicsOptions); Map<String, TopicDescription> topicDescriptionMap = describeTopicsResult.all().get(); boolean monitoringResult = nonNull(topicDescriptionMap); log.info("Connection to Kafka topics is {}, time: {}", monitoringResult, executionTime.getTime()); return monitoringResult; } catch (Exception e) { log.warn("Exception when try connect to kafka topics: {}, exception: {}, time: {}", metricTopics, e.getMessage(), executionTime.getTime()); return false; } } } log.warn("metricTopics or connectionTimeoutTopic not found: {}, {}", metricTopics, connectionTimeoutTopic); return null; } KafkaMetricsSet(KafkaAdmin kafkaAdmin, Integer connectionTimeoutTopic, List<String> metricTopics); @Override Map<String, Metric> getMetrics(); Boolean connectionToKafkaTopicsIsSuccess(); }### Answer: @Test public void connectionToKafkaTopicsIsSuccess() { KafkaMetricsSet kafkaMetricsSet = initKafkaMetricSet(); assertTrue(kafkaMetricsSet.connectionToKafkaTopicsIsSuccess()); } @Test @SneakyThrows public void connectionToKafkaTopicsIsNotSuccess() { KafkaMetricsSet kafkaMetricsSet = initKafkaMetricSet(); kafkaEmbedded.destroy(); assertFalse(kafkaMetricsSet.connectionToKafkaTopicsIsSuccess()); } @Test public void connectionToKafkaIsNotSuccessWithWrongTopic() { KafkaMetricsSet kafkaMetricsSet = initNotExistTopic(); assertFalse(kafkaMetricsSet.connectionToKafkaTopicsIsSuccess()); }
### Question: TenantConfigService implements RefreshableConfiguration { @IgnoreLogginAspect public Map<String, Object> getConfig() { return getTenantConfig(); } TenantConfigService(XmConfigProperties xmConfigProperties, TenantContextHolder tenantContextHolder); @IgnoreLogginAspect Map<String, Object> getConfig(); @Override void onRefresh(final String updatedKey, final String config); String getTenantKey(String updatedKey); @Override boolean isListeningConfiguration(final String updatedKey); @Override void onInit(final String configKey, final String configValue); static final String DEFAULT_TENANT_CONFIG_PATTERN; }### Answer: @Test public void testGetConfigValue() throws IOException { assertNotNull(tenantConfigService.getConfig()); assertEquals("value1", getConfig().get("testProperty")); } @Test public void testCanNotChangeConfigMapOutside() throws IOException { assertEquals("value1", getConfig().get("testProperty")); assertEquals(1, tenantConfigService.getConfig().size()); try { tenantConfigService.getConfig().put("newProperty", "You've been hacked!"); fail("should not be success!!!"); } catch (UnsupportedOperationException e) { assertEquals(1, tenantConfigService.getConfig().size()); } Map<String, Object> map = getConfig(); try { map.put("testProperty", "You've been hacked!"); fail("should not be success!!!"); } catch (UnsupportedOperationException e) { assertEquals("value1", getConfig().get("testProperty")); } List<Object> list = List.class.cast(getConfig().get("testList")); assertEquals("item2", list.get(1)); assertEquals(3, list.size()); try { list.set(1, "replaced item!"); fail("should not be success!!!"); } catch (UnsupportedOperationException e) { assertEquals("item2", List.class.cast(getConfig().get("testList")).get(1)); } }
### Question: AnnotatedFieldProcessor { static <X> void ensureNoConflictingAnnotationsPresentOn(final Class<X> type) throws ResolutionException { final Set<Field> fieldsHavingConflictingAnnotations = new HashSet<Field>(); for (final Field fieldToInspect : allFieldsAndSuperclassFieldsIn(type)) { if (isAnnotatedWithOneOf(fieldToInspect, CAMEL) && isAnnotatedWithOneOf(fieldToInspect, CDI_CONFLICTS)) { fieldsHavingConflictingAnnotations.add(fieldToInspect); } } if (!fieldsHavingConflictingAnnotations.isEmpty()) { final String error = buildErrorMessageFrom(fieldsHavingConflictingAnnotations); throw new ResolutionException(error); } } }### Answer: @Test public final void assertThatEnsureNoConflictingAnnotationsPresentOnCorrectlyRecognizesNoConflict() { AnnotatedFieldProcessor .ensureNoConflictingAnnotationsPresentOn(BeanHavingEndpointInjectAnnotatedField.class); } @Test(expected = ResolutionException.class) public final void assertThatEnsureNoConflictingAnnotationsPresentOnCorrectlyRecognizesAConflict() { AnnotatedFieldProcessor .ensureNoConflictingAnnotationsPresentOn(BeanHavingEndpointInjectAndInjectAnnotatedField.class); }
### Question: AnnotatedFieldProcessor { static <X> boolean hasCamelInjectAnnotatedFields(final Class<X> type) { return !camelInjectAnnotatedFieldsIn(type).isEmpty(); } }### Answer: @Test public final void assertThatHasCamelInjectAnnotatedFieldsRecognizesThatNoCamelInjectAnnotationIsPresentOnAnyField() { final boolean answer = AnnotatedFieldProcessor .hasCamelInjectAnnotatedFields(BeanHavingNoEndpointInjectAnnotatedField.class); assertFalse("AnnotatedFieldProcessor.hasCamelInjectAnnotatedFields(" + BeanHavingNoEndpointInjectAnnotatedField.class.getName() + ") should have recognized that no field is annotated with " + "@EndpointInject on the supplied class, yet it didn't", answer); } @Test public final void assertThatHasCamelInjectAnnotatedFieldsRecognizesEndpointInjectAnnotationOnField() { final boolean answer = AnnotatedFieldProcessor .hasCamelInjectAnnotatedFields(BeanHavingEndpointInjectAnnotatedField.class); assertTrue("AnnotatedFieldProcessor.hasCamelInjectAnnotatedFields(" + BeanHavingEndpointInjectAnnotatedField.class.getName() + ") should have recognized a field annotated with " + "@EndpointInject on the supplied class, yet it didn't", answer); }
### Question: AnnotatedFieldProcessor { static <X> Set<Field> camelInjectAnnotatedFieldsIn(final Class<X> type) { final Set<Field> camelInjectAnnotatedFields = new HashSet<Field>(); for (final Field fieldToInspect : allFieldsAndSuperclassFieldsIn(type)) { if (isAnnotatedWithOneOf(fieldToInspect, CAMEL)) { camelInjectAnnotatedFields.add(fieldToInspect); } } return Collections.unmodifiableSet(camelInjectAnnotatedFields); } }### Answer: @Test public final void assertThatCamelInjectAnnotatedFieldsInReturnsEnpointInjectAnnotatedField() { final Set<Field> camelInjectAnnotatedFields = AnnotatedFieldProcessor .camelInjectAnnotatedFieldsIn(BeanHavingEndpointInjectAnnotatedField.class); assertEquals("AnnotatedFieldProcessor.hasCamelInjectAnnotatedFields(" + BeanHavingEndpointInjectAnnotatedField.class.getName() + ") should have returned exactly one field annotated with " + "@EndpointInject on the supplied class, yet it didn't", 1, camelInjectAnnotatedFields.size()); }
### Question: LazyModuleLoader { public synchronized ServiceLike loadServiceModule(String moduleName, String className) throws LazyLoadingException { try { Class lazyLoadedClass = mLoaderAlgorithm.loadModule(moduleName, className); Constructor c = lazyLoadedClass.getConstructor(Context.class); ServiceLike serviceLike = (ServiceLike) c.newInstance(mContext); return serviceLike; } catch (Throwable t) { throw new LazyLoadingException(t); } } LazyModuleLoader(Context context, LoaderAlgorithm loaderAlgorithm); synchronized ServiceLike loadServiceModule(String moduleName, String className); synchronized SupportFragmentLike loadSupportFragmentModule( Fragment hostingFragment, String moduleName, String className); synchronized FragmentLike loadFragmentModule( android.app.Fragment hostingFragment, String moduleName, String className); synchronized ActivityLike loadActivityModule( Activity activity, String moduleName, String className); synchronized Class loadModule(String moduleName, String className); synchronized void installModule(String moduleName); }### Answer: @Test public void testThatLoadSucceedsForServiceModule() throws IOException, LazyLoadingException, ClassNotFoundException { Mockito.when(mModulePathsNo1Mock.containsDexFile()).thenReturn(true); Mockito.when(mModulePathsNo1Mock.getDexFile()).thenReturn(mDexFileNo1Mock); Mockito.when(mModulePathsNo1Mock.getOptimizedDexFile()).thenReturn(mOptDexFileNo1Mock); ServiceLike returnedService = mObjectUnderTest.loadServiceModule(MODULE_NAME_NO1, ServiceModule.class.getName()); Assert.assertEquals(returnedService.getClass(), ServiceModule.class); Mockito.verify(mCustomClassLoaderMock) .addDex(Mockito.eq(mDexFileNo1Mock), Mockito.eq(mOptDexFileNo1Mock)); Mockito.verify(mLazyLoadListenerMock) .moduleLazilyLoaded(Mockito.eq(MODULE_NAME_NO1), Mockito.anyLong()); Mockito.verify(mClassLoaderMock).loadClass(ServiceModule.class.getName()); Mockito.verifyZeroInteractions(mNativeModuleLoaderMock); }
### Question: LazyModuleLoader { public synchronized ActivityLike loadActivityModule( Activity activity, String moduleName, String className) throws LazyLoadingException { try { Class lazyLoadedClass = mLoaderAlgorithm.loadModule(moduleName, className); Constructor c = lazyLoadedClass.getConstructor(Activity.class); ActivityLike activityLike = (ActivityLike) c.newInstance(activity); return activityLike; } catch (Throwable t) { throw new LazyLoadingException(t); } } LazyModuleLoader(Context context, LoaderAlgorithm loaderAlgorithm); synchronized ServiceLike loadServiceModule(String moduleName, String className); synchronized SupportFragmentLike loadSupportFragmentModule( Fragment hostingFragment, String moduleName, String className); synchronized FragmentLike loadFragmentModule( android.app.Fragment hostingFragment, String moduleName, String className); synchronized ActivityLike loadActivityModule( Activity activity, String moduleName, String className); synchronized Class loadModule(String moduleName, String className); synchronized void installModule(String moduleName); }### Answer: @Test public void testThatLoadSucceedsForActivityModule() throws IOException, LazyLoadingException, ClassNotFoundException { Mockito.when(mModulePathsNo1Mock.containsDexFile()).thenReturn(true); Mockito.when(mModulePathsNo1Mock.getDexFile()).thenReturn(mDexFileNo1Mock); Mockito.when(mModulePathsNo1Mock.getOptimizedDexFile()).thenReturn(mOptDexFileNo1Mock); ActivityLike returnedActivity = mObjectUnderTest.loadActivityModule( mActivityMock, MODULE_NAME_NO1, ActivityModule.class.getName()); Assert.assertEquals(returnedActivity.getClass(), ActivityModule.class); Mockito.verify(mCustomClassLoaderMock) .addDex(Mockito.eq(mDexFileNo1Mock), Mockito.eq(mOptDexFileNo1Mock)); Mockito.verify(mLazyLoadListenerMock) .moduleLazilyLoaded(Mockito.eq(MODULE_NAME_NO1), Mockito.anyLong()); Mockito.verify(mClassLoaderMock).loadClass(ActivityModule.class.getName()); Mockito.verifyZeroInteractions(mNativeModuleLoaderMock); }
### Question: FilteredGuacamoleWriter implements GuacamoleWriter { @Override public void write(char[] chunk, int offset, int length) throws GuacamoleException { while (length > 0) { int parsed; while ((parsed = parser.append(chunk, offset, length)) != 0) { offset += parsed; length -= parsed; } if (!parser.hasNext()) throw new GuacamoleServerException("Filtered write() contained an incomplete instruction."); writeInstruction(parser.next()); } } FilteredGuacamoleWriter(GuacamoleWriter writer, GuacamoleFilter filter); @Override void write(char[] chunk, int offset, int length); @Override void write(char[] chunk); @Override void writeInstruction(GuacamoleInstruction instruction); }### Answer: @Test public void testFilter() throws Exception { StringWriter stringWriter = new StringWriter(); GuacamoleWriter writer = new FilteredGuacamoleWriter(new WriterGuacamoleWriter(stringWriter), new TestFilter()); writer.write("3.yes,1.A;2.no,1.B;3.yes,1.C;3.yes,1.D;4.nope,1.E;".toCharArray()); writer.write("1.n,3.abc;3.yes,5.hello;2.no,4.test;3.yes,5.world;".toCharArray()); assertEquals("3.yes,1.A;3.yes,1.C;3.yes,1.D;3.yes,5.hello;3.yes,5.world;", stringWriter.toString()); }
### Question: TokenFilter { public void filterValues(Map<?, String> map) { for (Map.Entry<?, String> entry : map.entrySet()) { String value = entry.getValue(); if (value != null) entry.setValue(filter(value)); } } TokenFilter(); TokenFilter(Map<String, String> tokenValues); void setToken(String name, String value); String getToken(String name); void unsetToken(String name); Map<String, String> getTokens(); void setTokens(Map<String, String> tokens); String filter(String input); void filterValues(Map<?, String> map); }### Answer: @Test public void testFilterValues() { TokenFilter tokenFilter = new TokenFilter(); tokenFilter.setToken("TOKEN_A", "value-of-a"); tokenFilter.setToken("TOKEN_B", "value-of-b"); Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "$$${NOPE}hello${TOKEN_A}world${TOKEN_B}$${NOT_A_TOKEN}"); map.put(2, "${NOPE}hello${TOKEN_A}world${TOKEN_C}"); map.put(3, null); tokenFilter.filterValues(map); assertEquals(3, map.size()); assertEquals( "$${NOPE}hellovalue-of-aworldvalue-of-b${NOT_A_TOKEN}", map.get(1) ); assertEquals( "${NOPE}hellovalue-of-aworld${TOKEN_C}", map.get(2) ); assertNull(map.get(3)); }
### Question: GuacamoleProtocolVersion { public static GuacamoleProtocolVersion parseVersion(String version) { Matcher versionMatcher = VERSION_PATTERN.matcher(version); if (!versionMatcher.matches()) return null; return new GuacamoleProtocolVersion( Integer.parseInt(versionMatcher.group(1)), Integer.parseInt(versionMatcher.group(2)), Integer.parseInt(versionMatcher.group(3)) ); } GuacamoleProtocolVersion(int major, int minor, int patch); int getMajor(); int getMinor(); int getPatch(); boolean atLeast(GuacamoleProtocolVersion otherVersion); static GuacamoleProtocolVersion parseVersion(String version); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final GuacamoleProtocolVersion VERSION_1_0_0; static final GuacamoleProtocolVersion VERSION_1_1_0; static final GuacamoleProtocolVersion LATEST; }### Answer: @Test public void testInvalidVersionParse() { Assert.assertNull(GuacamoleProtocolVersion.parseVersion("potato")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION_")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION___")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION__2_3")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION_1__3")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION_1_2_")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION_A_2_3")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION_1_B_3")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("VERSION_1_2_C")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("_1_2_3")); Assert.assertNull(GuacamoleProtocolVersion.parseVersion("version_1_2_3")); }
### Question: GuacamoleProtocolVersion { @Override public String toString() { return "VERSION_" + getMajor() + "_" + getMinor() + "_" + getPatch(); } GuacamoleProtocolVersion(int major, int minor, int patch); int getMajor(); int getMinor(); int getPatch(); boolean atLeast(GuacamoleProtocolVersion otherVersion); static GuacamoleProtocolVersion parseVersion(String version); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final GuacamoleProtocolVersion VERSION_1_0_0; static final GuacamoleProtocolVersion VERSION_1_1_0; static final GuacamoleProtocolVersion LATEST; }### Answer: @Test public void testToString() { Assert.assertEquals("VERSION_1_0_0", GuacamoleProtocolVersion.VERSION_1_0_0.toString()); Assert.assertEquals("VERSION_1_1_0", GuacamoleProtocolVersion.VERSION_1_1_0.toString()); Assert.assertEquals("VERSION_12_103_398", new GuacamoleProtocolVersion(12, 103, 398).toString()); }
### Question: FilteredGuacamoleReader implements GuacamoleReader { @Override public GuacamoleInstruction readInstruction() throws GuacamoleException { GuacamoleInstruction filteredInstruction; do { GuacamoleInstruction unfilteredInstruction = reader.readInstruction(); if (unfilteredInstruction == null) return null; filteredInstruction = filter.filter(unfilteredInstruction); } while (filteredInstruction == null); return filteredInstruction; } FilteredGuacamoleReader(GuacamoleReader reader, GuacamoleFilter filter); @Override boolean available(); @Override char[] read(); @Override GuacamoleInstruction readInstruction(); }### Answer: @Test public void testFilter() throws Exception { final String test = "3.yes,1.A;2.no,1.B;3.yes,1.C;3.yes,1.D;4.nope,1.E;"; GuacamoleReader reader = new FilteredGuacamoleReader(new ReaderGuacamoleReader(new StringReader(test)), new TestFilter()); GuacamoleInstruction instruction; instruction = reader.readInstruction(); assertNotNull(instruction); assertEquals("yes", instruction.getOpcode()); assertEquals(1, instruction.getArgs().size()); assertEquals("A", instruction.getArgs().get(0)); instruction = reader.readInstruction(); assertNotNull(instruction); assertEquals("yes", instruction.getOpcode()); assertEquals(1, instruction.getArgs().size()); assertEquals("C", instruction.getArgs().get(0)); instruction = reader.readInstruction(); assertNotNull(instruction); assertEquals("yes", instruction.getOpcode()); assertEquals(1, instruction.getArgs().size()); assertEquals("D", instruction.getArgs().get(0)); instruction = reader.readInstruction(); assertNull(instruction); }
### Question: QCParser { public static Map<String, String> parseQueryString(String queryStr) throws UnsupportedEncodingException { List<String> paramList = Arrays.asList(queryStr.split("&")); Map<String, String> parameters = new HashMap<String,String>(); for (String param : paramList) { String[] paramArray = param.split("=", 2); parameters.put(URLDecoder.decode(paramArray[0], "UTF-8"), URLDecoder.decode(paramArray[1], "UTF-8")); } return parameters; } static GuacamoleConfiguration getConfiguration(String uri); static Map<String, String> parseQueryString(String queryStr); static void parseUserInfo(String userInfo, GuacamoleConfiguration config); static String getName(GuacamoleConfiguration config); }### Answer: @Test public void testParseQueryString() throws UnsupportedEncodingException { final String queryString = "param1=value1&param2=value2=3&param3=value%3D3&param4=value%264"; Map<String, String> queryMap = QCParser.parseQueryString(queryString); assertEquals("value1", queryMap.get("param1")); assertEquals("value2=3", queryMap.get("param2")); assertEquals("value=3", queryMap.get("param3")); assertEquals("value&4", queryMap.get("param4")); }
### Question: QCParser { public static void parseUserInfo(String userInfo, GuacamoleConfiguration config) throws UnsupportedEncodingException { Matcher userinfoMatcher = userinfoPattern.matcher(userInfo); if (userinfoMatcher.matches()) { String username = userinfoMatcher.group(USERNAME_GROUP); String password = userinfoMatcher.group(PASSWORD_GROUP); if (username != null && !username.isEmpty()) config.setParameter("username", URLDecoder.decode(username, "UTF-8")); if (password != null && !password.isEmpty()) config.setParameter("password", URLDecoder.decode(password, "UTF-8")); } } static GuacamoleConfiguration getConfiguration(String uri); static Map<String, String> parseQueryString(String queryStr); static void parseUserInfo(String userInfo, GuacamoleConfiguration config); static String getName(GuacamoleConfiguration config); }### Answer: @Test public void testParseUserInfo() throws UnsupportedEncodingException { Map<String, String> userInfoMap; GuacamoleConfiguration config1 = new GuacamoleConfiguration(); QCParser.parseUserInfo("guacuser:secretpw", config1); assertEquals("guacuser", config1.getParameter("username")); assertEquals("secretpw", config1.getParameter("password")); GuacamoleConfiguration config2 = new GuacamoleConfiguration(); QCParser.parseUserInfo("guacuser", config2); assertEquals("guacuser", config2.getParameter("username")); assertNull(config2.getParameter("password")); GuacamoleConfiguration config3 = new GuacamoleConfiguration(); QCParser.parseUserInfo("guacuser:P%40ssw0rd%21", config3); assertEquals("guacuser", config3.getParameter("username")); assertEquals("P@ssw0rd!", config3.getParameter("password")); GuacamoleConfiguration config4 = new GuacamoleConfiguration(); QCParser.parseUserInfo("domain%5cguacuser:domain%2fpassword", config4); assertEquals("domain\\guacuser", config4.getParameter("username")); assertEquals("domain/password", config4.getParameter("password")); }
### Question: RootResource { @GET @PermitAll public APIRootResponse get(@Context SecurityContext context) { final Map<String, APIRestLink> links = new HashMap<>(); links.put("v1", new APIRestLink(URI.create(Constants.HTTP_V1_ROOT))); return new APIRootResponse(links); } @GET @PermitAll APIRootResponse get(@Context SecurityContext context); }### Answer: @Test public void testGetReturnsAResponse() { final RootResource resource = new RootResource(); final APIRootResponse response = resource.get(TestHelpers.generateSecureSecurityContext()); assertThat(response).isNotNull(); } @Test public void testGetResponseContainsALinkToTheV1Root() { final RootResource resource = new RootResource(); final APIRootResponse response = resource.get(TestHelpers.generateSecureSecurityContext()); assertHasKeyWithValue( response.getLinks(), "v1", Constants.HTTP_V1_ROOT); }
### Question: JsonWebTokenAuthenticator implements Authenticator<String, Principal> { @Override public Optional<Principal> authenticate(String s) throws NullPointerException, AuthenticationException { Objects.requireNonNull(s); try { final Jws<Claims> claims = Jwts.parser().setSigningKey(this.secretKey).parseClaimsJws(s); final String username = claims.getBody().getSubject(); final Principal principal = new PrincipalImpl(username); return Optional.of(principal); } catch (MalformedJwtException ex) { throw new AuthenticationException("The provided json web token was malformed.", ex); } catch (SignatureException ex) { throw new AuthenticationException("The provided json web token failed signature validation tests.", ex); } } JsonWebTokenAuthenticator(Key secretKey, SignatureAlgorithm algorithm); static String createJwtToken(SignatureAlgorithm alg, Key secretKey, Principal principal); @Override Optional<Principal> authenticate(String s); String createJwtToken(Principal principal); }### Answer: @Test(expected = NullPointerException.class) public void testAuthenticateThrowsIfProvidedANullString() throws AuthenticationException { final JsonWebTokenAuthenticator authenticator = createValidAuthenticatorInstance(); authenticator.authenticate(null); } @Test(expected = AuthenticationException.class) public void testAuthenticateThrowsIfProvidedAnInvalidString() throws AuthenticationException { final JsonWebTokenAuthenticator authenticator = createValidAuthenticatorInstance(); final String invalidString = TestHelpers.generateRandomString(); authenticator.authenticate(invalidString); }
### Question: JsonWebTokenAuthenticator implements Authenticator<String, Principal> { public static String createJwtToken(SignatureAlgorithm alg, Key secretKey, Principal principal) { return Jwts.builder().setSubject(principal.getName()).signWith(alg, secretKey).compact(); } JsonWebTokenAuthenticator(Key secretKey, SignatureAlgorithm algorithm); static String createJwtToken(SignatureAlgorithm alg, Key secretKey, Principal principal); @Override Optional<Principal> authenticate(String s); String createJwtToken(Principal principal); }### Answer: @Test(expected = NullPointerException.class) public void testCreateJwtTokenThrowsIfUserIsNull() { final JsonWebTokenAuthenticator authenticator = createValidAuthenticatorInstance(); authenticator.createJwtToken(null); } @Test public void testCreateJwtTokenDoesNotReturnNull() { final Principal Principal = generatePrincipal(); final JsonWebTokenAuthenticator authenticator = createValidAuthenticatorInstance(); final String returnedToken = authenticator.createJwtToken(Principal); assertThat(returnedToken).isNotNull(); } @Test public void testCreateJwtTokenReturnsValidJWTString() { final Key secretKey = createSecretKey(); final Principal Principal = generatePrincipal(); final JsonWebTokenAuthenticator authenticator = createAuthenticatorWithSecretKey(secretKey); final String returnedToken = authenticator.createJwtToken(Principal); assertIsValidJWT(secretKey, returnedToken); }
### Question: CustomAuthenticatorConfig implements AuthenticationConfig { @Override public AuthFilter<?, Principal> createAuthFilter(AuthenticationBootstrap bootstrap) { final ClassLoader classLoader = getClassLoader(classPath); final Class<?> klass = loadClass(classLoader, className); final Class<AuthenticationConfig> authConfigClass = toAuthConfigClass(klass); final AuthenticationConfig loadedConfig = loadAuthenticationConfig(properties, authConfigClass); return loadedConfig.createAuthFilter(bootstrap); } CustomAuthenticatorConfig(String className); CustomAuthenticatorConfig(String className, JsonNode properties); @JsonCreator CustomAuthenticatorConfig( @JsonProperty("className") String className, @JsonProperty("classPath") Optional<String> classPath, @JsonProperty("properties") Optional<JsonNode> properties); @Override AuthFilter<?, Principal> createAuthFilter(AuthenticationBootstrap bootstrap); }### Answer: @Test(expected = NullPointerException.class) public void testCreateAuthFilterThrowsIfClassNameIsNull() { final CustomAuthenticatorConfig config = new CustomAuthenticatorConfig(null); config.createAuthFilter(createTypicalAuthBootstrap()); } @Test(expected = RuntimeException.class) public void testCreateAuthFilterIfClassNameDoesNotExistOnClassPath() { final CustomAuthenticatorConfig config = new CustomAuthenticatorConfig(generateClassName()); config.createAuthFilter(createTypicalAuthBootstrap()); } @Test(expected = RuntimeException.class) public void testCreateAuthFilterIfClassDoesNotDeriveFromAuthenticationConfig() { final CustomAuthenticatorConfig config = new CustomAuthenticatorConfig(Object.class.getName()); config.createAuthFilter(createTypicalAuthBootstrap()); } @Test public void testCreateAuthFilterDoesNotThrowIfClassDoesDeriveFromAuthenticationConfig() { final CustomAuthenticatorConfig config = new CustomAuthenticatorConfig(NullCustomAuthConfig.class.getName()); config.createAuthFilter(createTypicalAuthBootstrap()); }
### Question: UserResource { @GET @Path("current") @PermitAll @Operation( summary = "Get the current user", description = "Returns the current user that Jobson believes is calling the API. This entrypoint *always* returns " + "*something*. If authentication is disabled (e.g. guest auth is enabled) then the client's ID is" + " handled as the guest username (usually, 'guest'). All other auth types have an associated username " + "that jobson will extract and return via this entrypoint") public APIUserDetails fetchCurrentUserDetails(@Context SecurityContext context) { return new APIUserDetails(new UserId(context.getUserPrincipal().getName())); } @GET @Path("current") @PermitAll @Operation( summary = "Get the current user", description = "Returns the current user that Jobson believes is calling the API. This entrypoint *always* returns " + "*something*. If authentication is disabled (e.g. guest auth is enabled) then the client's ID is" + " handled as the guest username (usually, 'guest'). All other auth types have an associated username " + "that jobson will extract and return via this entrypoint") APIUserDetails fetchCurrentUserDetails(@Context SecurityContext context); }### Answer: @Test public void testGetCurrentUserReturnsCurrentUserId() { final UserId userId = TestHelpers.generateUserId(); final SecurityContext securityContext = new SecurityContext() { @Override public Principal getUserPrincipal() { return new Principal() { @Override public String getName() { return userId.toString(); } }; } @Override public boolean isUserInRole(String s) { return false; } @Override public boolean isSecure() { return false; } @Override public String getAuthenticationScheme() { return null; } }; final UserResource userResource = new UserResource(); final APIUserDetails APIUserDetails = userResource.fetchCurrentUserDetails(securityContext); assertThat(APIUserDetails.getId()).isEqualTo(userId); }
### Question: JoinFunction implements FreeFunction { @Override public Object call(Object... args) { if (args.length != 2) { throw new RuntimeException(String.format("Invalid number of arguments (%s) supplied to a join function", args.length)); } else if (args[0].getClass() != String.class) { throw new RuntimeException(String.format("%s: Is not a valid first argument to join. It should be a string delimiter", args[0].getClass())); } else if (args[1].getClass() != StringArrayInput.class) { throw new RuntimeException(String.format("%s: Is not a valid second argument to join. It should be a list of strings", args[1].getClass())); } else { final String separator = (String)args[0]; final StringArrayInput entries = (StringArrayInput) args[1]; return String.join(separator, entries.getValues()); } } @Override Object call(Object... args); }### Answer: @Test public void testWhenCalledWithADelimiterAndAnArrayOfStringReturnsAStringJoinedByTheDelimiter() { final JoinFunction joinFunction = new JoinFunction(); final String delimiter = ","; final List<String> items = generateTestData(); final Object ret = joinFunction.call(delimiter, new StringArrayInput(items)); assertThat(ret.getClass()).isEqualTo(String.class); assertThat(ret).isEqualTo(String.join(delimiter, items)); } @Test(expected = RuntimeException.class) public void testWhenCalledWithInvalidTypesThrowsException() { final JoinFunction joinFunction = new JoinFunction(); joinFunction.call(new Object(), new Object()); joinFunction.call(",", new Object()); joinFunction.call(new Object(), generateTestData()); } @Test(expected = RuntimeException.class) public void testThrowsWhenCalledWithInvalidNumberOfArguments() { final JoinFunction joinFunction = new JoinFunction(); joinFunction.call(","); joinFunction.call(",", generateTestData(), new Object()); }
### Question: ToStringFunction implements FreeFunction { @Override public Object call(Object... args) { if (args.length != 1) { throw new RuntimeException(String.format("Incorrect number of arguments (%s), expected 1", args.length)); } else { return args[0].toString(); } } @Override Object call(Object... args); }### Answer: @Test(expected = RuntimeException.class) public void testCallingFunctionWithMoreThanOneArgThrowsException() throws Exception { final ToStringFunction f = new ToStringFunction(); f.call(new Object(), new Object()); } @Test public void testCallingFunctionWithOneArgResultsInToStringOfThatArg() { final ToStringFunction f = new ToStringFunction(); final Integer input = TestHelpers.randomIntBetween(50, 100000); final Object output = f.call(input); assertThat(output).isInstanceOf(String.class); assertThat(output).isEqualTo(input.toString()); }
### Question: FileInput implements JobInput { public String getFilename() { return this.filename; } @JsonCreator FileInput(@JsonProperty(value = "filename") String filename, @JsonProperty(value = "data", required = true) String b64data); FileInput(String filename, byte[] b64data); byte[] getData(); String getFilename(); }### Answer: @Test public void testDefaultsNameWhenNameIsMissing() { final FileInput fi = TestHelpers.readJSONFixture( "fixtures/jobinputs/file/valid-but-missing-name.json", FileInput.class); assertThat(fi.getFilename()).isEqualTo("unnamed"); }
### Question: FilesystemJobSpecDAO implements JobSpecDAO { @Override public Optional<JobSpecSummary> getJobSpecSummaryById(JobSpecId jobSpecId) { return getJobSpecById(jobSpecId).map(JobSpec::toSummary); } FilesystemJobSpecDAO(Path jobSpecsDir); @Override Optional<JobSpec> getJobSpecById(JobSpecId jobSpecId); @Override Map<String, HealthCheck> getHealthChecks(); @Override Optional<JobSpecSummary> getJobSpecSummaryById(JobSpecId jobSpecId); @Override List<JobSpecSummary> getJobSpecSummaries(int pageSize, int page); @Override List<JobSpecSummary> getJobSpecSummaries(int pageSize, int page, String query); }### Answer: @Test public void testGetJobSpecDetailsByIdReturnsEmptyOptionalIfJobSpecIdDoesntExistInTheDir() throws IOException { final Path jobSpecsDir = createTmpDir(FilesystemJobSpecDAOTest.class); final FilesystemJobSpecDAO filesystemJobSpecDAO = new FilesystemJobSpecDAO(jobSpecsDir); final JobSpecId jobSpecId = new JobSpecId(generateRandomBase36String(10)); final Optional<JobSpecSummary> jobSpecDetailsResponse = filesystemJobSpecDAO.getJobSpecSummaryById(jobSpecId); assertThat(jobSpecDetailsResponse.isPresent()).isFalse(); }
### Question: FilesystemJobSpecDAO implements JobSpecDAO { @Override public Map<String, HealthCheck> getHealthChecks() { return singletonMap( FILESYSTEM_SPECS_DAO_DISK_SPACE_HEALTHCHECK, new DiskSpaceHealthCheck( jobSpecsDir.toFile(), FILESYSTEM_SPECS_DAO_DISK_SPACE_WARNING_THRESHOLD_IN_BYTES)); } FilesystemJobSpecDAO(Path jobSpecsDir); @Override Optional<JobSpec> getJobSpecById(JobSpecId jobSpecId); @Override Map<String, HealthCheck> getHealthChecks(); @Override Optional<JobSpecSummary> getJobSpecSummaryById(JobSpecId jobSpecId); @Override List<JobSpecSummary> getJobSpecSummaries(int pageSize, int page); @Override List<JobSpecSummary> getJobSpecSummaries(int pageSize, int page, String query); }### Answer: @Test public void testGetHealthChecksReturnsHealthCheckThatTestsDiskSpace() throws IOException { final FilesystemJobSpecDAO dao = new FilesystemJobSpecDAO(createTmpDir(FilesystemJobsDAOTest.class)); assertThat(dao.getHealthChecks()).containsKeys(FILESYSTEM_SPECS_DAO_DISK_SPACE_HEALTHCHECK); assertThat(dao.getHealthChecks().get(FILESYSTEM_SPECS_DAO_DISK_SPACE_HEALTHCHECK)).isNotNull(); }
### Question: MathUtils { public static boolean isOdd(long value) { return !isEven(value); } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testIsOdd() throws Exception { Assert.assertTrue(MathUtils.isOdd(oddVal_EXPECTED)); Assert.assertFalse(MathUtils.isOdd(evenVal_EXPECTED)); }
### Question: MathUtils { public static boolean isEven(long value) { return value % 2 == 0; } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testIsEven() throws Exception { Assert.assertTrue(MathUtils.isEven(evenVal_EXPECTED)); Assert.assertFalse(MathUtils.isEven(oddVal_EXPECTED)); }
### Question: MathUtils { public static boolean isPower2(long value) { return value == 1 || value == 2 || value == 4 || value == 8 || value == 16 || value == 32 || value == 64 || value == 128 || value == 256 || value == 512 || value == 1024 || value == 2048 || value == 4096; } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testIsPower2() throws Exception { Assert.assertTrue(MathUtils.isPower2((long) powerOfTwo_EXPECTED)); Assert.assertFalse(MathUtils.isPower2((long) notPowerOfTwo_EXPECTED)); }
### Question: MathUtils { public static double rad2deg(double valueInRadians) { return valueInRadians * Constants.RTOD; } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testRad2deg() throws Exception { Assert.assertEquals(valInDegrees_EXPECTED, MathUtils.rad2deg(valInRadians_EXPECTED), DELTA); }
### Question: MathUtils { public static double deg2rad(double valueInDegrees) { return valueInDegrees * Constants.DTOR; } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testDeg2rad() throws Exception { Assert.assertEquals(valInRadians_EXPECTED, MathUtils.deg2rad(valInDegrees_EXPECTED), DELTA); }
### Question: MathUtils { public static double[] increment(int m, double begin, double pitch) { double[] array = new double[m]; for (int i = 0; i < m; i++) { array[i] = begin + i * pitch; } return array; } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testIncrement1D() throws Exception { double[] increment_1D_ACTUAL = MathUtils.increment(5, 0, 0.25); Assert.assertArrayEquals(increment_1D_EXPECTED, increment_1D_ACTUAL, DELTA); } @Test public void testIncrement2D() throws Exception { double[][] increment_2D_ACTUAL = MathUtils.increment(5, 2, 0, 0.25); for (int i = 0; i < increment_2D_ACTUAL.length; i++) { Assert.assertArrayEquals(increment_2D_EXPECTED[i], increment_2D_ACTUAL[i], DELTA); } }
### Question: MathUtils { @Deprecated public static double sqr(double value) { return Math.pow(value, 2); } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testSqr() throws Exception { Assert.assertEquals(Math.pow(VALUE, 2), MathUtils.sqr(VALUE), DELTA); }
### Question: MathUtils { @Deprecated public static double sqrt(double value) { return Math.sqrt(value); } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testSqrt() throws Exception { Assert.assertEquals(Math.sqrt(VALUE), MathUtils.sqrt(VALUE), DELTA); }
### Question: MathUtils { public static DoubleMatrix lying(DoubleMatrix inMatrix) { return new DoubleMatrix(inMatrix.toArray()).transpose(); } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testLying() throws Exception{ DoubleMatrix inMatrix = DoubleMatrix.ones(2, 2); DoubleMatrix lying_EXPECTED = DoubleMatrix.ones(1, 4); Assert.assertEquals(lying_EXPECTED, MathUtils.lying(inMatrix)); inMatrix = DoubleMatrix.ones(4, 1); Assert.assertEquals(lying_EXPECTED, MathUtils.lying(inMatrix)); }
### Question: MathUtils { public static DoubleMatrix ramp(final int nRows, final int nColumns) { final double maxHeight = 1; return DoubleMatrix.ones(nRows, 1).mmul(lying(new DoubleMatrix(increment(nColumns, 0, maxHeight / (nColumns - 1))))); } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testRamp() throws Exception { DoubleMatrix ramp_2D_ACTUAL = MathUtils.ramp(nRows, nCols); Assert.assertEquals(ramp_2D_EXPECTED, ramp_2D_ACTUAL); }
### Question: PolyUtils { public static DoubleMatrix normalize(DoubleMatrix t) { return t.sub(t.get(t.length / 2)).div(10.0); } static double normalize2(double data, final int min, final int max); static double normalize2(double data, final double min, final double max); static DoubleMatrix normalize(DoubleMatrix t); static int degreeFromCoefficients(int numOfCoefficients); static int numberOfCoefficients(final int degree); static double[] polyFitNormalized(DoubleMatrix t, DoubleMatrix y, final int degree); static double[] polyFit2D(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix z, final int degree); static double[] polyFit(DoubleMatrix t, DoubleMatrix y, final int degree); static double polyVal1D(double x, double[] coeffs); static double[][] polyval(final double[] x, final double[] y, final double coeff[], int degree); static DoubleMatrix polyval(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final double[] coeff); static double polyval(final double x, final double y, final double[] coeff, int degree); }### Answer: @Test public void testNormalize() throws Exception { double[] array_EXPECTED = {1, 2}; double[] normArray_EXPECTED = {-0.1, 0}; Assert.assertEquals(new DoubleMatrix(normArray_EXPECTED), PolyUtils.normalize(new DoubleMatrix(array_EXPECTED))); }
### Question: PolyUtils { public static int degreeFromCoefficients(int numOfCoefficients) { return (int) (0.5 * (-1 + (int) (Math.sqrt((double) (1 + 8 * numOfCoefficients))))) - 1; } static double normalize2(double data, final int min, final int max); static double normalize2(double data, final double min, final double max); static DoubleMatrix normalize(DoubleMatrix t); static int degreeFromCoefficients(int numOfCoefficients); static int numberOfCoefficients(final int degree); static double[] polyFitNormalized(DoubleMatrix t, DoubleMatrix y, final int degree); static double[] polyFit2D(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix z, final int degree); static double[] polyFit(DoubleMatrix t, DoubleMatrix y, final int degree); static double polyVal1D(double x, double[] coeffs); static double[][] polyval(final double[] x, final double[] y, final double coeff[], int degree); static DoubleMatrix polyval(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final double[] coeff); static double polyval(final double x, final double y, final double[] coeff, int degree); }### Answer: @Test public void testDegreeFromCoefficients() throws Exception { final int degree_EXPECTED = 5; int degree_ACTUAL = PolyUtils.degreeFromCoefficients(21); Assert.assertEquals(degree_EXPECTED, degree_ACTUAL); }
### Question: PolyUtils { public static int numberOfCoefficients(final int degree) { return (int) (0.5 * (Math.pow(degree + 1, 2) + degree + 1)); } static double normalize2(double data, final int min, final int max); static double normalize2(double data, final double min, final double max); static DoubleMatrix normalize(DoubleMatrix t); static int degreeFromCoefficients(int numOfCoefficients); static int numberOfCoefficients(final int degree); static double[] polyFitNormalized(DoubleMatrix t, DoubleMatrix y, final int degree); static double[] polyFit2D(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix z, final int degree); static double[] polyFit(DoubleMatrix t, DoubleMatrix y, final int degree); static double polyVal1D(double x, double[] coeffs); static double[][] polyval(final double[] x, final double[] y, final double coeff[], int degree); static DoubleMatrix polyval(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final double[] coeff); static double polyval(final double x, final double y, final double[] coeff, int degree); }### Answer: @Test public void testNumberOfCoefficients() throws Exception { final int coeffs_EXPECTED = 21; int coeffs_ACTUAL = PolyUtils.numberOfCoefficients(5); Assert.assertEquals(coeffs_EXPECTED, coeffs_ACTUAL); }
### Question: PolyUtils { public static double polyVal1D(double x, double[] coeffs) { double sum = 0.0; for (int d = coeffs.length - 1; d >= 0; --d) { sum *= x; sum += coeffs[d]; } return sum; } static double normalize2(double data, final int min, final int max); static double normalize2(double data, final double min, final double max); static DoubleMatrix normalize(DoubleMatrix t); static int degreeFromCoefficients(int numOfCoefficients); static int numberOfCoefficients(final int degree); static double[] polyFitNormalized(DoubleMatrix t, DoubleMatrix y, final int degree); static double[] polyFit2D(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix z, final int degree); static double[] polyFit(DoubleMatrix t, DoubleMatrix y, final int degree); static double polyVal1D(double x, double[] coeffs); static double[][] polyval(final double[] x, final double[] y, final double coeff[], int degree); static DoubleMatrix polyval(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final double[] coeff); static double polyval(final double x, final double y, final double[] coeff, int degree); }### Answer: @Test public void testPolyVal1d() throws Exception { double[] coeff = {1, 2, 3}; double[] input = {5, 7, 9}; double[] solutionArray_EXPECTED = {86, 162, 262}; for (int i = 0; i < solutionArray_EXPECTED.length; i++) { double solution_EXPECTED = solutionArray_EXPECTED[i]; Assert.assertEquals(solution_EXPECTED, PolyUtils.polyVal1D(input[i], coeff), DELTA_02); } }
### Question: SarUtils { public static DoubleMatrix intensity(final ComplexDoubleMatrix inputMatrix) { return pow(inputMatrix.real(), 2).add(pow(inputMatrix.imag(), 2)); } static ComplexDoubleMatrix oversample(ComplexDoubleMatrix inputMatrix, final int factorRow, final int factorCol); static DoubleMatrix intensity(final ComplexDoubleMatrix inputMatrix); static DoubleMatrix magnitude(final ComplexDoubleMatrix inputMatrix); static DoubleMatrix angle(final ComplexDoubleMatrix cplxData); @Deprecated static DoubleMatrix coherence(final ComplexDoubleMatrix inputMatrix, final ComplexDoubleMatrix normsMatrix, final int winL, final int winP); static DoubleMatrix coherence2(final ComplexDoubleMatrix input, final ComplexDoubleMatrix norms, final int winL, final int winP); static ComplexDoubleMatrix multilook(final ComplexDoubleMatrix inputMatrix, final int factorRow, final int factorColumn); static ComplexDoubleMatrix computeIfg(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData); static void computeIfg_inplace(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData); static ComplexDoubleMatrix computeIfg(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData, final int ovsFactorAz, final int ovsFactorRg); }### Answer: @Test public void testIntensity() throws Exception { DoubleMatrix intensity_ACTUAL = SarUtils.intensity(cplxData); Assert.assertEquals(DoubleMatrix.ones(cplxData.rows, cplxData.columns), intensity_ACTUAL); }
### Question: SarUtils { public static DoubleMatrix magnitude(final ComplexDoubleMatrix inputMatrix) { return sqrt(intensity(inputMatrix)); } static ComplexDoubleMatrix oversample(ComplexDoubleMatrix inputMatrix, final int factorRow, final int factorCol); static DoubleMatrix intensity(final ComplexDoubleMatrix inputMatrix); static DoubleMatrix magnitude(final ComplexDoubleMatrix inputMatrix); static DoubleMatrix angle(final ComplexDoubleMatrix cplxData); @Deprecated static DoubleMatrix coherence(final ComplexDoubleMatrix inputMatrix, final ComplexDoubleMatrix normsMatrix, final int winL, final int winP); static DoubleMatrix coherence2(final ComplexDoubleMatrix input, final ComplexDoubleMatrix norms, final int winL, final int winP); static ComplexDoubleMatrix multilook(final ComplexDoubleMatrix inputMatrix, final int factorRow, final int factorColumn); static ComplexDoubleMatrix computeIfg(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData); static void computeIfg_inplace(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData); static ComplexDoubleMatrix computeIfg(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData, final int ovsFactorAz, final int ovsFactorRg); }### Answer: @Test public void testMagnitude() throws Exception { DoubleMatrix magnitude_ACTUAL = SarUtils.magnitude(cplxData); Assert.assertEquals(DoubleMatrix.ones(cplxData.rows, cplxData.columns), magnitude_ACTUAL); }
### Question: Ellipsoid { public void showdata() { logger.info("ELLIPSOID: \tEllipsoid used (orbit, output): " + name + "."); logger.info("ELLIPSOID: a = " + a); logger.info("ELLIPSOID: b = " + b); logger.info("ELLIPSOID: e2 = " + e2); logger.info("ELLIPSOID: e2' = " + e2b); } Ellipsoid(); Ellipsoid(final double semiMajor, final double semiMinor); Ellipsoid(Ellipsoid ell); void showdata(); static double[] xyz2ell(final Point xyz); static Point ell2xyz(final double phi, final double lambda, final double height); static Point ell2xyz(final double[] phiLambdaHeight); static Point ell2xyz(final GeoPoint geoPoint, final double height); static Point ell2xyz(final GeoPoint geoPoint); static void ell2xyz(final GeoPoint geoPoint, double[] xyz); static void ell2xyz(final GeoPoint geoPoint, final double height, final double[] xyz); static double a; static double b; static String name; }### Answer: @Ignore @Test public void testShowdata() throws Exception { inputEll.showdata(); }
### Question: SLCImage { public double computeDeltaRange(double pixel) { return mlRg * (pix2range(pixel + 1) - pix2range(pixel)); } SLCImage(); SLCImage(MetadataElement element); void parseResFile(File resFileName); double pix2tr(double pixel); double pix2range(double pixel); double tr2pix(double rangeTime); double line2ta(double line); double ta2line(double azitime); Point lp2t(Point p); double getRadarWavelength(); Point getApproxRadarCentreOriginal(); GeoPoint getApproxGeoCentreOriginal(); Point getApproxXYZCentreOriginal(); void setCurrentWindow(final Window window); Window getCurrentWindow(); Window getOriginalWindow(); void setOriginalWindow(final Window window); double getPRF(); double getAzimuthBandwidth(); int getCoarseOffsetP(); double gettRange1(); void settRange1(double tRange1); double getRangeBandwidth(); void setRangeBandwidth(double rangeBandwidth); double getRsr2x(); void setRsr2x(double rsr2x); void setCoarseOffsetP(int offsetP); void setCoarseOffsetL(int offsetL); int getMlAz(); void setMlAz(int mlAz); int getMlRg(); void setMlRg(int mlRg); double getMjd(); long getOrbitNumber(); String getSensor(); String getMission(); int getOvsRg(); void setOvsRg(int ovsRg); void setSlaveMaterOffset(); SlaveWindow getSlaveMaterOffset(); void setSlaveMasterOffset(double ll00, double pp00, double ll0N, double pp0N, double llN0, double ppN0, double llNN, double ppNN); double computeDeltaRange(double pixel); double computeDeltaRange(Point sarPixel); double computeRangeResolution(double pixel); double computeRangeResolution(Point sarPixel); public Doppler doppler; }### Answer: @Test public void testComputeDeltaRange() throws Exception { Assert.assertEquals(deltaRange_EXPECTED, master.computeDeltaRange(CORNER_REFLECTOR_4), eps05); }
### Question: TimeData implements RowData<T> { @NonNull @Override public ContentProviderOperation.Builder updatedBuilder(@NonNull TransactionContext transactionContext, @NonNull ContentProviderOperation.Builder builder) { if (mDue.isPresent() && mStart.isAllDay() != mDue.value().isAllDay()) { throw new IllegalArgumentException("'start' and 'due' must have the same all-day flag"); } DateTime start = mStart; if (mDue.isPresent() && !mDue.value().isAllDay()) { start = mStart.shiftTimeZone(mDue.value().getTimeZone()); } return doUpdateBuilder(start, mDue, mDuration, builder); } private TimeData(@NonNull DateTime start, @NonNull Optional<DateTime> due, @NonNull Optional<Duration> duration); TimeData(@NonNull DateTime start, @NonNull DateTime due); TimeData(@NonNull DateTime start, @NonNull Duration duration); TimeData(@NonNull DateTime start); @NonNull @Override ContentProviderOperation.Builder updatedBuilder(@NonNull TransactionContext transactionContext, @NonNull ContentProviderOperation.Builder builder); }### Answer: @Test(expected = IllegalArgumentException.class) public void test_whenStartIsAllDayAndDueIsNot_throwsIllegalArgument() { new TimeData<>(DateTime.now().toAllDay(), DateTime.now()) .updatedBuilder(mock(TransactionContext.class), mock(ContentProviderOperation.Builder.class)); } @Test(expected = IllegalArgumentException.class) public void test_whenDueIsAllDayAndStartIsNot_throwsIllegalArgument() { new TimeData<>(DateTime.now(), DateTime.now().toAllDay()) .updatedBuilder(mock(TransactionContext.class), mock(ContentProviderOperation.Builder.class)); }
### Question: DateTimeIterableFieldAdapter extends SimpleFieldAdapter<Iterable<DateTime>, EntityType> { @Override String fieldName() { return mDateTimeListFieldName; } DateTimeIterableFieldAdapter(String datetimeListFieldName, String timezoneFieldName); @Override Iterable<DateTime> getFrom(ContentValues values); @Override Iterable<DateTime> getFrom(Cursor cursor); @Override Iterable<DateTime> getFrom(Cursor cursor, ContentValues values); @Override void setIn(ContentValues values, Iterable<DateTime> value); }### Answer: @Test public void testFieldName() { assertThat(new DateTimeIterableFieldAdapter<>("x", "y").fieldName(), is("x")); }
### Question: Toggled implements NotificationSignal { @Override public int value() { if (mFlag != Notification.DEFAULT_VIBRATE && mFlag != Notification.DEFAULT_SOUND && mFlag != Notification.DEFAULT_LIGHTS) { throw new IllegalArgumentException("Notification signal flag is not valid: " + mFlag); } return mEnable ? addFlag(mOriginal.value(), mFlag) : removeFlag(mOriginal.value(), mFlag); } Toggled(int flag, boolean enable, NotificationSignal original); @Override int value(); }### Answer: @Test public void testValidFlags_dontThrowException() { new Toggled(Notification.DEFAULT_SOUND, true, new NoSignal()).value(); new Toggled(Notification.DEFAULT_VIBRATE, true, new NoSignal()).value(); new Toggled(Notification.DEFAULT_LIGHTS, true, new NoSignal()).value(); } @Test(expected = IllegalArgumentException.class) public void testInValidFlag_throwsException() { new Toggled(15, true, new NoSignal()).value(); } @Test public void testAddingFlag() { assertThat(new Toggled(Notification.DEFAULT_SOUND, true, new NoSignal()).value(), is(new NoSignal().value() | Notification.DEFAULT_SOUND)); assertThat(new Toggled(Notification.DEFAULT_SOUND, false, new NoSignal()).value(), is(new NoSignal().value())); }
### Question: VanillaInstanceData implements Single<ContentValues> { @Override public ContentValues value() { ContentValues values = new ContentValues(6); values.putNull(TaskContract.Instances.INSTANCE_START); values.putNull(TaskContract.Instances.INSTANCE_START_SORTING); values.putNull(TaskContract.Instances.INSTANCE_DUE); values.putNull(TaskContract.Instances.INSTANCE_DUE_SORTING); values.putNull(TaskContract.Instances.INSTANCE_DURATION); values.put(TaskContract.Instances.DISTANCE_FROM_CURRENT, 0); values.putNull(TaskContract.Instances.INSTANCE_ORIGINAL_TIME); return values; } @Override ContentValues value(); }### Answer: @Test public void testValue() { ContentValues values = new VanillaInstanceData().value(); assertThat(values.get(TaskContract.Instances.INSTANCE_START), nullValue()); assertThat(values.get(TaskContract.Instances.INSTANCE_START_SORTING), nullValue()); assertThat(values.get(TaskContract.Instances.INSTANCE_DUE), nullValue()); assertThat(values.get(TaskContract.Instances.INSTANCE_DUE_SORTING), nullValue()); assertThat(values.get(TaskContract.Instances.INSTANCE_DURATION), nullValue()); assertThat(values.get(TaskContract.Instances.DISTANCE_FROM_CURRENT), is(0)); assertThat(values.get(TaskContract.Instances.INSTANCE_ORIGINAL_TIME), nullValue()); assertThat(values.size(), is(7)); }
### Question: TaskRelated implements Single<ContentValues> { @Override public ContentValues value() { ContentValues values = mDelegate.value(); values.put(TaskContract.Instances.TASK_ID, mTaskId); return values; } TaskRelated(long taskId, Single<ContentValues> delegate); @Override ContentValues value(); }### Answer: @Test public void testValue() { assertThat(new TaskRelated(123, ContentValues::new), hasValue(new ContentValuesWithLong(TaskContract.Instances.TASK_ID, 123))); }
### Question: MavenScm { public boolean isEmpty() { return this.connection == null && this.developerConnection == null && this.tag == null && this.url == null; } MavenScm(Builder builder); boolean isEmpty(); String getConnection(); String getDeveloperConnection(); String getTag(); String getUrl(); }### Answer: @Test void isEmptyWithNoData() { MavenScm mavenScm = new MavenScm.Builder().build(); assertThat(mavenScm.isEmpty()).isTrue(); } @Test void isEmptyWithData() { MavenScm mavenScm = new MavenScm.Builder().connection("some-connection").build(); assertThat(mavenScm.isEmpty()).isFalse(); }
### Question: MyFirstActor extends AbstractActor { static public Props props() { return Props.create(MyFirstActor.class, () -> new MyFirstActor()); } static Props props(); @Override Receive createReceive(); }### Answer: @Test public void testMyFirstActor_Greeting() { final TestKit probe = new TestKit(actorSystem); final ActorRef myFirstActor = actorSystem.actorOf(MyFirstActor.props()); myFirstActor.tell(new Greeting(HELLO_WORLD), probe.getRef()); final Greeting greeting = probe.expectMsgClass(Greeting.class); assertEquals(HELLO_WORLD, greeting.getMessage()); }
### Question: Calculator implements ICalculator { @Override public String add(int... values) { int sum = 0; for (int value : values) { sum += value; } return format(sum); } @Override String add(int... values); @Override String multiply(int... values); @Override String evaluate(String value); }### Answer: @Test public void testAdd() { assertEquals("3", mCalculator.evaluate(Matchers.anyString())); final String result = mCalculator.add(1,2); assertEquals("3", result); when(mCalculator.evaluate(Matchers.anyString())).thenReturn("5"); assertEquals("5", mCalculator.evaluate(Matchers.anyString())); }
### Question: CalcApi { public String getEvaluateSumUrl(final int a, final int b) { return getEvaluateUrl(a + "+" + b); } CalcApi(final String pBasePath); String getEvaluateSumUrl(final int a, final int b); String getEvaluateUrl(String input); }### Answer: @Test public void calculateSum() throws Exception { assertEquals(BASE_PATH + "/" + "calc?input=1%2B15", mCalcApi.getEvaluateSumUrl(1, 15)); }
### Question: CalcApi { public String getEvaluateUrl(String input) { try { return mBasePath + CALC + URLEncoder.encode(input, "UTF-8"); } catch (final UnsupportedEncodingException pE) { throw new IllegalStateException(pE); } } CalcApi(final String pBasePath); String getEvaluateSumUrl(final int a, final int b); String getEvaluateUrl(String input); }### Answer: @Test public void evaluate() throws Exception { assertEquals(BASE_PATH + "/" + "calc?input=I%27m+lucky", mCalcApi.getEvaluateUrl("I'm lucky")); }
### Question: ExcludeFilter implements ArtifactsFilter { @Override public boolean isArtifactIncluded(final Artifact artifact) throws ArtifactFilterException { return !(artifact.getGroupId().equals(excludedGroupId) && artifact.getArtifactId().equals(excludedArtifactId)); } ExcludeFilter(final String excludedGroupId, final String excludedArtifactId); @Override Set<Artifact> filter(final Set<Artifact> artifacts); @Override boolean isArtifactIncluded(final Artifact artifact); }### Answer: @Test public void shouldExcludeByGroupAndArtifactId() throws ArtifactFilterException { assertThat(filter.isArtifactIncluded(excluded)).isFalse(); assertThat(filter.isArtifactIncluded(included1)).isTrue(); assertThat(filter.isArtifactIncluded(included2)).isTrue(); }
### Question: EndpointCustomizer implements ComponentProxyCustomizer { @Override public void customize(final ComponentProxyComponent component, final Map<String, Object> options) { consumeOption(options, SERVICE_NAME, serviceObject -> { final String serviceName = (String) serviceObject; final QName service = QName.valueOf(serviceName); options.put(SERVICE_NAME, serviceName); consumeOption(options, ComponentProperties.PORT_NAME, portObject -> { final QName port = new QName(service.getNamespaceURI(), (String) portObject); options.put(ComponentProperties.PORT_NAME, port.toString()); }); }); } @Override void customize(final ComponentProxyComponent component, final Map<String, Object> options); }### Answer: @Test public void shouldAddEndpointName() { final EndpointCustomizer customizer = new EndpointCustomizer(); final Map<String, Object> options = new HashMap<>(); options.put(ComponentProperties.SERVICE_NAME, "{namespace}service1"); options.put(ComponentProperties.PORT_NAME, "port1"); customizer.customize(NOT_USED, options); assertThat(options).containsKeys("serviceName", "portName"); assertThat(ConnectorOptions.extractOption(options, "serviceName")).isEqualTo("{namespace}service1"); assertThat(ConnectorOptions.extractOption(options, "portName")).isEqualTo("{namespace}port1"); }
### Question: BoxVerifierExtension extends DefaultComponentVerifierExtension { @Override protected Result verifyParameters(Map<String, Object> parameters) { ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.PARAMETERS) .error(ResultErrorHelper.requiresOption("userName", parameters)) .error(ResultErrorHelper.requiresOption("userPassword", parameters)) .error(ResultErrorHelper.requiresOption("clientId", parameters)) .error(ResultErrorHelper.requiresOption("clientSecret", parameters)); return builder.build(); } protected BoxVerifierExtension(String defaultScheme, CamelContext context); }### Answer: @Test public void verifyParameters() { Result result = verifier.verifyParameters(parameters); assertEquals(errorDescriptions(result), Result.Status.OK, result.getStatus()); }
### Question: BoxVerifierExtension extends DefaultComponentVerifierExtension { @Override protected Result verifyConnectivity(Map<String, Object> parameters) { return ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY) .error(parameters, this::verifyCredentials).build(); } protected BoxVerifierExtension(String defaultScheme, CamelContext context); }### Answer: @Test public void verifyConnectivity() { Result result = verifier.verifyConnectivity(parameters); assertEquals(errorDescriptions(result), Result.Status.OK, result.getStatus()); }
### Question: BoxDownloadCustomizer implements ComponentProxyCustomizer { private void afterProducer(Exchange exchange) { BoxFile file = new BoxFile(); Message in = exchange.getIn(); file.setId(fileId); ByteArrayOutputStream output = in.getBody(ByteArrayOutputStream.class); try { file.setContent(new String(output.toByteArray(), encoding)); } catch (UnsupportedEncodingException e) { LOG.error("Failed to convert file content to String. Invalid file encoding: {}", encoding); } file.setSize(output.size()); in.setBody(file); } @Override void customize(ComponentProxyComponent component, Map<String, Object> options); }### Answer: @Test public void testAfterProducer() throws Exception { String id = "12345"; String content = "Test content: åäö"; String encoding = StandardCharsets.ISO_8859_1.name(); int size = content.getBytes(encoding).length; Map<String, Object> options = new HashMap<>(); options.put("fileId", id); options.put("encoding", encoding); customizer.customize(component, options); Exchange inbound = new DefaultExchange(createCamelContext()); setBody(inbound, content, encoding); component.getAfterProducer().process(inbound); BoxFile file = inbound.getIn().getBody(BoxFile.class); assertNotNull(file); assertEquals(id, file.getId()); assertEquals(content, file.getContent()); assertEquals(size, file.getSize()); }
### Question: CellCoordinate { public static CellCoordinate fromCellId(String cellId) { CellCoordinate coordinate = new CellCoordinate(); if (cellId != null) { coordinate.setRowIndex(getRowIndex(cellId)); coordinate.setColumnIndex(getColumnIndex(cellId)); } return coordinate; } CellCoordinate(); static CellCoordinate fromCellId(String cellId); static String getColumnName(int columnIndex); static String getColumnName(int columnIndex, int columnStartIndex, String ... columnNames); int getRowIndex(); void setRowIndex(int rowIndex); int getColumnIndex(); void setColumnIndex(int columnIndex); }### Answer: @Test public void testFromCellId() { CellCoordinate coordinate = CellCoordinate.fromCellId(cellId); Assert.assertEquals(rowIndexCheck, coordinate.getRowIndex()); Assert.assertEquals(columnIndexCheck, coordinate.getColumnIndex()); }
### Question: CellCoordinate { public static String getColumnName(int columnIndex) { String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; StringBuilder columnName = new StringBuilder(); int index = columnIndex; int overflowIndex = -1; while (index > 25) { overflowIndex++; index -= 26; } if (overflowIndex >= 0) { columnName.append(alphabet.toCharArray()[overflowIndex]); } columnName.append(alphabet.toCharArray()[index]); return columnName.toString(); } CellCoordinate(); static CellCoordinate fromCellId(String cellId); static String getColumnName(int columnIndex); static String getColumnName(int columnIndex, int columnStartIndex, String ... columnNames); int getRowIndex(); void setRowIndex(int rowIndex); int getColumnIndex(); void setColumnIndex(int columnIndex); }### Answer: @Test public void testGetColumnName() { Assert.assertEquals(columnName, CellCoordinate.getColumnName(columnIndexCheck)); String[] names = new String[columnIndexCheck]; Arrays.fill(names, "Foo"); Assert.assertEquals(columnName, CellCoordinate.getColumnName(columnIndexCheck, 0, names)); names = new String[columnIndexCheck + 1]; Arrays.fill(names, "Foo"); Assert.assertEquals("Foo", CellCoordinate.getColumnName(columnIndexCheck, 0, names)); Assert.assertEquals("Foo", CellCoordinate.getColumnName(columnIndexCheck, columnIndexCheck, names)); }
### Question: RangeCoordinate extends CellCoordinate { public static RangeCoordinate fromRange(String range) { RangeCoordinate coordinate = new RangeCoordinate(); String rangeExpression = normalizeRange(range); if (rangeExpression.contains(":")) { String[] coordinates = rangeExpression.split(":", -1); coordinate.setRowStartIndex(getRowIndex(coordinates[0])); coordinate.setColumnStartIndex(getColumnIndex(coordinates[0])); coordinate.setRowEndIndex(getRowIndex(coordinates[1]) + 1); coordinate.setColumnEndIndex(getColumnIndex(coordinates[1]) + 1); } else { CellCoordinate cellCoordinate = CellCoordinate.fromCellId(rangeExpression); coordinate.setRowIndex(cellCoordinate.getRowIndex()); coordinate.setColumnIndex(cellCoordinate.getColumnIndex()); coordinate.setRowStartIndex(cellCoordinate.getRowIndex()); coordinate.setColumnStartIndex(cellCoordinate.getColumnIndex()); coordinate.setRowEndIndex(cellCoordinate.getRowIndex() + 1); coordinate.setColumnEndIndex(cellCoordinate.getColumnIndex() + 1); } return coordinate; } private RangeCoordinate(); static RangeCoordinate fromRange(String range); String getColumnNames(); int getRowStartIndex(); void setRowStartIndex(int rowStartIndex); int getRowEndIndex(); void setRowEndIndex(int rowEndIndex); int getColumnStartIndex(); void setColumnStartIndex(int columnStartIndex); int getColumnEndIndex(); void setColumnEndIndex(int columnEndIndex); static final String DIMENSION_ROWS; static final String DIMENSION_COLUMNS; }### Answer: @Test public void testFromRange() { RangeCoordinate coordinate = RangeCoordinate.fromRange(range); Assert.assertEquals(rowStartIndex, coordinate.getRowStartIndex()); Assert.assertEquals(rowEndIndex, coordinate.getRowEndIndex()); Assert.assertEquals(columnStartIndex, coordinate.getColumnStartIndex()); Assert.assertEquals(columnEndIndex, coordinate.getColumnEndIndex()); }
### Question: GoogleSheetsGetValuesCustomizer implements ComponentProxyCustomizer { private void beforeConsumer(Exchange exchange) throws JsonProcessingException { final Message in = exchange.getIn(); if (splitResults) { in.setBody(createModelFromSplitValues(in)); } else { in.setBody(createModelFromValueRange(in)); } } @Override void customize(ComponentProxyComponent component, Map<String, Object> options); static final String SPREADSHEET_ID; }### Answer: @Test public void testBeforeConsumer() throws Exception { Map<String, Object> options = new HashMap<>(); options.put("spreadsheetId", getSpreadsheetId()); options.put("range", range); options.put("splitResults", false); customizer.customize(getComponent(), options); Exchange inbound = new DefaultExchange(createCamelContext()); ValueRange valueRange = new ValueRange(); valueRange.setRange(sheetName + "!" + range); valueRange.setMajorDimension(majorDimension); valueRange.setValues(values); inbound.getIn().setBody(valueRange); getComponent().getBeforeConsumer().process(inbound); Assert.assertEquals(GoogleSheetsApiCollection.getCollection().getApiName(SheetsSpreadsheetsValuesApiMethod.class).getName(), ConnectorOptions.extractOption(options, "apiName")); Assert.assertEquals("get", ConnectorOptions.extractOption(options, "methodName")); @SuppressWarnings("unchecked") List<String> model = inbound.getIn().getBody(List.class); Assert.assertEquals(expectedValueModel.size(), model.size()); Iterator<String> modelIterator = model.iterator(); for (String expected : expectedValueModel) { assertThatJson(modelIterator.next()).isEqualTo(String.format(expected, getSpreadsheetId())); } }
### Question: SwaggerProxyComponent extends ComponentProxyComponent { public SwaggerProxyComponent(final String componentId, final String componentScheme) { super(componentId, componentScheme); } SwaggerProxyComponent(final String componentId, final String componentScheme); @Override Endpoint createEndpoint(final String uri); void overrideEndpoint(final Function<Endpoint, Endpoint> endpointOverride); }### Answer: @Test public void testSwaggerProxyComponent() throws Exception { CamelContext context = new DefaultCamelContext(); ComponentProxyFactory factory = new ConnectorFactory(); ComponentProxyComponent proxy = factory.newInstance("swagger-1", "rest-openapi"); try { proxy.setCamelContext(context); proxy.start(); Endpoint endpoint = proxy.createEndpoint("swagger-1:http: assertThat(endpoint).isInstanceOfSatisfying(DelegateEndpoint.class, e -> { assertThat(e.getEndpoint()).isInstanceOf(RestOpenApiEndpoint.class); assertThat(e.getEndpoint()).hasFieldOrPropertyWithValue("componentName", SyndesisRestSwaggerComponent.COMPONENT_NAME); }); } finally { proxy.stop(); } }