method2testcases
stringlengths
118
6.63k
### Question: PersistNotificationHandler { @EventListener @Transactional(propagation = REQUIRES_NEW) public void handle(final RequestFundedNotificationDto notification) { notificationRepository.save(requestFundedNotificationMapper.map(notification)); } PersistNotificationHandler(final NotificationRepository notificationRepository, final RequestFundedNotificationMapper requestFundedNotificationMapper, final RequestClaimedNotificationMapper requestClaimedNotificationMapper); @EventListener @Transactional(propagation = REQUIRES_NEW) void handle(final RequestFundedNotificationDto notification); @EventListener @Transactional(propagation = REQUIRES_NEW) void handle(final RequestClaimedNotificationDto notification); }### Answer: @Test void handleRequestFunded() { final RequestFundedNotificationDto notificationDto = RequestFundedNotificationDto.builder().build(); final RequestFundedNotification notification = RequestFundedNotificationMother.aRequestFundedNotification(); when(requestFundedNotificationMapper.map(same(notificationDto))).thenReturn(notification); handler.handle(notificationDto); verify(notificationRepository).save(same(notification)); } @Test void handleRequestClaimed() { final RequestClaimedNotificationDto notificationDto = RequestClaimedNotificationDto.builder().build(); final RequestClaimedNotification notification = RequestClaimedNotificationMother.aRequestClaimedNotification(); when(requestClaimedNotificationMapper.map(same(notificationDto))).thenReturn(notification); handler.handle(notificationDto); verify(notificationRepository).save(same(notification)); }
### Question: PublicEnvironmentEndpoint extends AbstractEndpoint<Map<String, Object>> { @Override public Map<String, Object> invoke() { return filterOutNonPublicProperties(environmentEndpoint.invoke()); } PublicEnvironmentEndpoint(final EnvironmentEndpoint environmentEndpoint, @Value("${endpoints.pubenv.enabled:false}") final Boolean enabled, @Value("${endpoints.pubenv.sensitive:true}") final Boolean sensitive, Environment env); @Override Map<String, Object> invoke(); }### Answer: @Test void invoke() { when(env.getProperty("notAGroup2.public")).thenReturn("false"); when(env.getProperty("notAGroup3")).thenReturn("aefsd"); when(env.getProperty("notAGroup3.public")).thenReturn("true"); when(env.getProperty("aszgf.dsads")).thenReturn("sdf"); when(env.getProperty("aszgf.dsads.public")).thenReturn("true"); when(env.getProperty("group1.public")).thenReturn("false"); when(env.getProperty("vxvdf.dscvds.ad")).thenReturn("wqwe"); when(env.getProperty("vxvdf.dscvds.ad.public")).thenReturn("true"); when(env.getProperty("wdoij.oijda.acs")).thenReturn("efsef"); when(env.getProperty("wdoij.oijda.acs.public")).thenReturn("true"); when(env.getProperty("cgv.fgchv.dwf")).thenReturn("kjhg"); when(env.getProperty("cgv.fgchv.dwf.public")).thenReturn("true"); final Map<String, Object> envProperties = MapBuilder.<String, Object>builder() .put("notAGroup", "hgfjk") .put("notAGroup2", "hxfgcj") .put("notAGroup2.public", "false") .put("notAGroup3", "aefsd") .put("notAGroup3.public", "true") .put("group1", MapBuilder.<String, Object>builder() .put("sfdfsd.dfsfd.sdfsd", "aefg") .put("aszgf.dsads", "sdf") .put("aszgf.dsads.public", "true") .build()) .put("group2", MapBuilder.<String, Object>builder() .put("vxvdf.dscvds.ad", "wqwe") .put("wdoij.oijda.acs", "efsef") .put("aszgf.dsads", "blah") .put("wdoij.oijda.acs.public", "true") .build()) .put("group3", MapBuilder.<String, Object>builder() .put("ghfcv.jhgk", "khgj") .put("cgv.fgchv.dwf", "kjhg") .put("cgv.fgchv.dwf.public", "true") .build()) .build(); when(environmentEndpoint.invoke()).thenReturn(envProperties); final Map<String, Object> result = endpoint.invoke(); assertThat(result).isEqualTo(MapBuilder.<String, Object>builder() .put("notAGroup3", "aefsd") .put("aszgf.dsads", "sdf") .put("wdoij.oijda.acs", "efsef") .put("cgv.fgchv.dwf", "kjhg") .build()); } @Test void overwritten() { when(env.getProperty("network")).thenReturn("kovan"); when(env.getProperty("network.public")).thenReturn("true"); final Map<String, Object> envProperties = MapBuilder.<String, Object>builder() .put("network", "kovan") .put("network", "main") .put("network.public", "true") .build(); when(environmentEndpoint.invoke()).thenReturn(envProperties); final Map<String, Object> result = endpoint.invoke(); assertThat(result).isEqualTo(MapBuilder.<String, Object>builder() .put("network", "kovan") .build()); }
### Question: MessagesController extends AbstractController { @PostMapping("/messages/{type}/add") public ModelAndView add(WebRequest request, @PathVariable String type, RedirectAttributes redirectAttributes) { MessageDto messageDto = MessageDto.builder() .name(request.getParameter("name")) .type(MessageType.valueOf(type.toUpperCase())) .title(request.getParameter("title")) .description(request.getParameter("description")) .link(request.getParameter("link")) .build(); messageService.add(messageDto); return redirectView(redirectAttributes) .withSuccessMessage("Message added") .url("/messages/" + type) .build(); } MessagesController(final MessageService messageService); @RequestMapping("/messages") ModelAndView showAllMessagesPage(final Model model); @RequestMapping("/messages/{type}") ModelAndView showMessagesOfTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/add") ModelAndView showAddMessageToTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/{name}/edit") ModelAndView showEditPage(final Model model, @PathVariable String type, @PathVariable String name); @PostMapping("/messages/{type}/add") ModelAndView add(WebRequest request, @PathVariable String type, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/edit") ModelAndView update(WebRequest request, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/delete") ModelAndView delete(final Model model, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); }### Answer: @Test public void add() throws Exception { String type = MessageType.REFERRAL_SHARE.toString(); this.mockMvc.perform(post("/messages/{type}/add", type)) .andExpect(redirectAlert("success", "Message added")) .andExpect(redirectedUrl("/messages/" + type)); }
### Question: ThymeleafSvgConfig implements ApplicationContextAware { @Bean public ITemplateResolver svgTemplateResolver() { final SpringResourceTemplateResolver svgTemplateResolver = new SpringResourceTemplateResolver(); svgTemplateResolver.setApplicationContext(applicationContext); svgTemplateResolver.setPrefix("classpath:/templates/svg/"); svgTemplateResolver.setTemplateMode(TemplateMode.XML); svgTemplateResolver.setCharacterEncoding("UTF-8"); svgTemplateResolver.setOrder(0); svgTemplateResolver.setCheckExistence(true); return svgTemplateResolver; } @Bean ITemplateResolver svgTemplateResolver(); @Bean ThymeleafViewResolver svgViewResolver(final SpringTemplateEngine templateEngine); @Override void setApplicationContext(final ApplicationContext applicationContext); }### Answer: @Test public void svgTemplateResolver() { final ApplicationContext applicationContext = mock(ApplicationContext.class); config.setApplicationContext(applicationContext); final SpringResourceTemplateResolver templateResolver = (SpringResourceTemplateResolver) config.svgTemplateResolver(); assertThat(templateResolver).hasFieldOrPropertyWithValue("applicationContext", applicationContext); assertThat(templateResolver.getPrefix()).isEqualTo("classpath:/templates/svg/"); assertThat(templateResolver.getTemplateMode()).isEqualTo(TemplateMode.XML); assertThat(templateResolver.getCharacterEncoding()).isEqualTo("UTF-8"); }
### Question: ThymeleafSvgConfig implements ApplicationContextAware { @Bean public ThymeleafViewResolver svgViewResolver(final SpringTemplateEngine templateEngine) { final ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver(); thymeleafViewResolver.setTemplateEngine(templateEngine); thymeleafViewResolver.setOrder(0); thymeleafViewResolver.setCharacterEncoding("UTF-8"); thymeleafViewResolver.setContentType("image/svg+xml"); thymeleafViewResolver.setViewNames(new String[] {"*.svg"}); return thymeleafViewResolver; } @Bean ITemplateResolver svgTemplateResolver(); @Bean ThymeleafViewResolver svgViewResolver(final SpringTemplateEngine templateEngine); @Override void setApplicationContext(final ApplicationContext applicationContext); }### Answer: @Test public void svgViewResolver() { final SpringTemplateEngine templateEngine = mock(SpringTemplateEngine.class); final ThymeleafViewResolver viewResolver = config.svgViewResolver(templateEngine); assertThat(viewResolver.getTemplateEngine()).isEqualTo(templateEngine); assertThat(viewResolver.getOrder()).isEqualTo(0); assertThat(viewResolver.getCharacterEncoding()).isEqualTo("UTF-8"); assertThat(viewResolver.getContentType()).isEqualTo("image/svg+xml"); assertThat(viewResolver.getViewNames()).isEqualTo(new String[] {"*.svg"}); }
### Question: ProfileController { @GetMapping("/profile") public ModelAndView showProfile(Principal principal) throws Exception { final ModelAndView mav = new ModelAndView("pages/profile/index"); mav.addObject("isVerifiedGithub", isVerifiedGithub(principal)); mav.addObject("isVerifiedStackOverflow", isVerifiedStackOverflow(principal)); mav.addObject("refLink", getRefLink(principal, "web")); mav.addObject("refShareTwitter", processRefLinkMessage(messageService.getMessageByKey("REFERRAL_SHARE.twitter"), getRefLink(principal, "twitter"))); mav.addObject("refShareLinkedin", processRefLinkMessage(messageService.getMessageByKey("REFERRAL_SHARE.linkedin"), getRefLink(principal, "linkedin"))); mav.addObject("refShareFacebook", processRefLinkMessage(messageService.getMessageByKey("REFERRAL_SHARE.facebook"), getRefLink(principal, "facebook"))); mav.addObject("arkaneWalletEndpoint", getArkaneWalletEndpoint()); return mav; } ProfileController(final ApplicationEventPublisher eventPublisher, final ProfileService profileService, final MessageService messageService, final ReferralService referralService, final GithubBountyService githubBountyService, final @Value("${network.arkane.environment}") String arkaneEnvironment, final StackOverflowBountyService stackOverflowBountyService); @GetMapping("/profile") ModelAndView showProfile(Principal principal); @GetMapping("/profile/link/{provider}") ModelAndView linkProfile(@PathVariable String provider, HttpServletRequest request, Principal principal, @RequestParam(value = "redirectUrl", required = false) String redirectUrl); @GetMapping("/profile/managewallets") ModelAndView manageWallets(Principal principal, HttpServletRequest request); @PostMapping("/profile/headline") ModelAndView updateHeadline(Principal principal, @RequestParam("headline") String headline); @GetMapping("/profile/link/{provider}/redirect") ModelAndView redirectToHereAfterProfileLink(Principal principal, @PathVariable("provider") String provider, @RequestParam(value = "redirectUrl", required = false) String redirectUrl); }### Answer: @Test void showProfile() throws Exception { MessageDto messageDto1 = MessageDto.builder() .type(MessageType.REFERRAL_SHARE) .name("twitter") .title("title1") .description("desc1") .link("https: .build(); MessageDto messageDto2 = MessageDto.builder() .type(MessageType.REFERRAL_SHARE) .name("twitter") .title("title1") .description("desc1") .link("https: .build(); MessageDto messageDto3 = MessageDto.builder() .type(MessageType.REFERRAL_SHARE) .name("twitter") .title("title1") .description("desc1") .link("https: .build(); when(githubBountyService.getVerification(principal)).thenReturn(GithubVerificationDto.builder().approved(true).build()); when(stackOverflowBountyService.getVerification(principal)).thenReturn(StackOverflowVerificationDto.builder().approved(true).build()); when(messageService.getMessageByKey("REFERRAL_SHARE.twitter")).thenReturn(messageDto1); when(messageService.getMessageByKey("REFERRAL_SHARE.linkedin")).thenReturn(messageDto2); when(messageService.getMessageByKey("REFERRAL_SHARE.facebook")).thenReturn(messageDto3); mockMvc.perform(get("/profile").principal(principal)) .andExpect(status().isOk()) .andExpect(model().attribute("isVerifiedGithub", true)) .andExpect(model().attribute("isVerifiedStackOverflow", true)) .andExpect(model().attribute("refLink", "ref")) .andExpect(model().attribute("refShareTwitter", messageDto1)) .andExpect(model().attribute("refShareLinkedin", messageDto2)) .andExpect(model().attribute("refShareFacebook", messageDto3)); }
### Question: ProfileController { @GetMapping("/profile/managewallets") public ModelAndView manageWallets(Principal principal, HttpServletRequest request) throws UnsupportedEncodingException { String bearerToken = URLEncoder.encode(profileService.getArkaneAccessToken((KeycloakAuthenticationToken) principal), "UTF-8"); String redirectUri = request.getHeader("referer"); if (redirectUri == null) { redirectUri = "/profile"; } redirectUri = URLEncoder.encode(redirectUri, "UTF-8"); String url = getConnectEndpoint(bearerToken, redirectUri); profileService.walletsManaged(principal); return new ModelAndView(new RedirectView(url)); } ProfileController(final ApplicationEventPublisher eventPublisher, final ProfileService profileService, final MessageService messageService, final ReferralService referralService, final GithubBountyService githubBountyService, final @Value("${network.arkane.environment}") String arkaneEnvironment, final StackOverflowBountyService stackOverflowBountyService); @GetMapping("/profile") ModelAndView showProfile(Principal principal); @GetMapping("/profile/link/{provider}") ModelAndView linkProfile(@PathVariable String provider, HttpServletRequest request, Principal principal, @RequestParam(value = "redirectUrl", required = false) String redirectUrl); @GetMapping("/profile/managewallets") ModelAndView manageWallets(Principal principal, HttpServletRequest request); @PostMapping("/profile/headline") ModelAndView updateHeadline(Principal principal, @RequestParam("headline") String headline); @GetMapping("/profile/link/{provider}/redirect") ModelAndView redirectToHereAfterProfileLink(Principal principal, @PathVariable("provider") String provider, @RequestParam(value = "redirectUrl", required = false) String redirectUrl); }### Answer: @Test void manageWallets() throws Exception { KeycloakAuthenticationToken principal = mock(KeycloakAuthenticationToken.class); when(profileService.getArkaneAccessToken(principal)).thenReturn("token"); mockMvc.perform(get("/profile/managewallets") .principal(principal)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("https: }
### Question: ProfileController { @PostMapping("/profile/headline") public ModelAndView updateHeadline(Principal principal, @RequestParam("headline") String headline) { profileService.updateHeadline(principal, headline); return redirectToProfile(); } ProfileController(final ApplicationEventPublisher eventPublisher, final ProfileService profileService, final MessageService messageService, final ReferralService referralService, final GithubBountyService githubBountyService, final @Value("${network.arkane.environment}") String arkaneEnvironment, final StackOverflowBountyService stackOverflowBountyService); @GetMapping("/profile") ModelAndView showProfile(Principal principal); @GetMapping("/profile/link/{provider}") ModelAndView linkProfile(@PathVariable String provider, HttpServletRequest request, Principal principal, @RequestParam(value = "redirectUrl", required = false) String redirectUrl); @GetMapping("/profile/managewallets") ModelAndView manageWallets(Principal principal, HttpServletRequest request); @PostMapping("/profile/headline") ModelAndView updateHeadline(Principal principal, @RequestParam("headline") String headline); @GetMapping("/profile/link/{provider}/redirect") ModelAndView redirectToHereAfterProfileLink(Principal principal, @PathVariable("provider") String provider, @RequestParam(value = "redirectUrl", required = false) String redirectUrl); }### Answer: @Test void updateHeadline() throws Exception { KeycloakAuthenticationToken principal = mock(KeycloakAuthenticationToken.class); when(profileService.getArkaneAccessToken(principal)).thenReturn("token"); mockMvc.perform(post("/profile/headline") .param("headline", "headline") .principal(principal)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/profile")); verify(profileService).updateHeadline(principal, "headline"); }
### Question: FundrequestExpressionObjectFactory implements IExpressionObjectFactory { @Override public Set<String> getAllExpressionObjectNames() { return expressionObjectsMap.keySet(); } FundrequestExpressionObjectFactory(final Map<String, Object> expressionObjectsMap); @Override Set<String> getAllExpressionObjectNames(); @Override Object buildObject(IExpressionContext context, String expressionObjectName); @Override boolean isCacheable(String expressionObjectName); }### Answer: @Test void getAllExpressionObjectNames() { assertThat(objectFactory.getAllExpressionObjectNames()).containsExactlyInAnyOrder(expressionObjectsMap.keySet().toArray(new String[0])); }
### Question: FundrequestDialect extends AbstractDialect implements IExpressionObjectDialect { @Override public IExpressionObjectFactory getExpressionObjectFactory() { return fundrequestExpressionObjectFactory; } FundrequestDialect(final IExpressionObjectFactory fundrequestExpressionObjectFactory); @Override IExpressionObjectFactory getExpressionObjectFactory(); }### Answer: @Test void getExpressionObjectFactory() { assertThat(fundrequestDialect.getExpressionObjectFactory()).isSameAs(fundrequestExpressionObjectFactory); }
### Question: ProfilesExpressionObject { public Optional<UserProfile> findByUserId(final String userId) { try { return StringUtils.isBlank(userId) ? Optional.empty() : Optional.ofNullable(profileService.getNonLoggedInUserProfile(userId)); } catch (Exception e) { LOGGER.error("Error getting profile for: \"" + userId + "\"", e); return Optional.empty(); } } ProfilesExpressionObject(final ProfileService profileService); Optional<UserProfile> findByUserId(final String userId); Function<UserProfile, String> getName(); }### Answer: @Test public void findByUserId() { final UserProfile expected = mock(UserProfile.class); Principal principal = PrincipalMother.davyvanroy(); when(profileService.getNonLoggedInUserProfile(principal.getName())).thenReturn(expected); final Optional<UserProfile> result = profiles.findByUserId(principal.getName()); assertThat(result).contains(expected); } @Test public void findByUserId_profileNull() { final String userId = "hgj"; when(profileService.getUserProfile(() -> userId)).thenReturn(null); final Optional<UserProfile> result = profiles.findByUserId(userId); assertThat(result).isEmpty(); } @Test public void findByUserId_inputNull() { final Optional<UserProfile> result = profiles.findByUserId(null); verifyZeroInteractions(profileService); assertThat(result).isEmpty(); }
### Question: MessagesController extends AbstractController { @PostMapping("/messages/{type}/{name}/edit") public ModelAndView update(WebRequest request, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes) { MessageDto messageDto = MessageDto.builder() .name(name) .type(MessageType.valueOf(type.toUpperCase())) .title(request.getParameter("title")) .description(request.getParameter("description")) .link(request.getParameter("link")) .build(); messageService.update(messageDto); return redirectView(redirectAttributes) .withSuccessMessage("Saved") .url("/messages/" + type) .build(); } MessagesController(final MessageService messageService); @RequestMapping("/messages") ModelAndView showAllMessagesPage(final Model model); @RequestMapping("/messages/{type}") ModelAndView showMessagesOfTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/add") ModelAndView showAddMessageToTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/{name}/edit") ModelAndView showEditPage(final Model model, @PathVariable String type, @PathVariable String name); @PostMapping("/messages/{type}/add") ModelAndView add(WebRequest request, @PathVariable String type, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/edit") ModelAndView update(WebRequest request, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/delete") ModelAndView delete(final Model model, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); }### Answer: @Test public void update() throws Exception { String type = MessageType.REFERRAL_SHARE.toString(); String name = "name"; this.mockMvc.perform(post("/messages/{type}/{name}/edit", type, name)) .andExpect(redirectAlert("success", "Saved")) .andExpect(redirectedUrl("/messages/" + type)); }
### Question: ProfilesExpressionObject { public Function<UserProfile, String> getName() { return UserProfile::getName; } ProfilesExpressionObject(final ProfileService profileService); Optional<UserProfile> findByUserId(final String userId); Function<UserProfile, String> getName(); }### Answer: @Test public void getName() { final String name = "jhgk"; final UserProfile userProfile = UserProfile.builder().name(name).build(); final Function<UserProfile, String> result = profiles.getName(); assertThat(result.apply(userProfile)).isEqualTo(name); }
### Question: HomeController extends AbstractController { @RequestMapping("/") public ModelAndView home(@RequestParam(value = "ref", required = false) String ref, RedirectAttributes redirectAttributes, Principal principal) { final List<RequestView> requests = mappers.mapList(RequestDto.class, RequestView.class, requestService.findAll()) .stream() .filter(request -> request.getPhase().toLowerCase().equals("open") && (hasFunds(request.getFunds().getFndFunds()) || hasFunds(request.getFunds().getOtherFunds()))) .collect(toList()); if (principal != null && StringUtils.isNotBlank(ref)) { eventPublisher.publishEvent(RefSignupEvent.builder().principal(principal).ref(ref).build()); return redirectView(redirectAttributes).url("/").build(); } return redirectView(redirectAttributes) .url("/requests") .build(); } HomeController(ProfileService profileService, ApplicationEventPublisher eventPublisher, final RequestService requestService, final ObjectMapper objectMapper, final Mappers mappers); @RequestMapping("/") ModelAndView home(@RequestParam(value = "ref", required = false) String ref, RedirectAttributes redirectAttributes, Principal principal); @GetMapping(value = {"/requestsActiveCount"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody String getRequestsActiveCount(Principal principal); @RequestMapping("/user/login") ModelAndView login(RedirectAttributes redirectAttributes, HttpServletRequest request); @GetMapping(path = "/logout") String logout(Principal principal, HttpServletRequest request); }### Answer: @Test public void home() throws Exception { mockMvc.perform(get("/")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/requests")); }
### Question: HomeController extends AbstractController { @RequestMapping("/user/login") public ModelAndView login(RedirectAttributes redirectAttributes, HttpServletRequest request) { return redirectView(redirectAttributes) .url(request.getHeader("referer")) .build(); } HomeController(ProfileService profileService, ApplicationEventPublisher eventPublisher, final RequestService requestService, final ObjectMapper objectMapper, final Mappers mappers); @RequestMapping("/") ModelAndView home(@RequestParam(value = "ref", required = false) String ref, RedirectAttributes redirectAttributes, Principal principal); @GetMapping(value = {"/requestsActiveCount"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody String getRequestsActiveCount(Principal principal); @RequestMapping("/user/login") ModelAndView login(RedirectAttributes redirectAttributes, HttpServletRequest request); @GetMapping(path = "/logout") String logout(Principal principal, HttpServletRequest request); }### Answer: @Test public void login() throws Exception { mockMvc.perform(get("/user/login").header("referer", "localhost")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("localhost")); }
### Question: HomeController extends AbstractController { @GetMapping(path = "/logout") public String logout(Principal principal, HttpServletRequest request) throws ServletException { if (principal != null) { profileService.logout(principal); } request.logout(); return "redirect:/"; } HomeController(ProfileService profileService, ApplicationEventPublisher eventPublisher, final RequestService requestService, final ObjectMapper objectMapper, final Mappers mappers); @RequestMapping("/") ModelAndView home(@RequestParam(value = "ref", required = false) String ref, RedirectAttributes redirectAttributes, Principal principal); @GetMapping(value = {"/requestsActiveCount"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody String getRequestsActiveCount(Principal principal); @RequestMapping("/user/login") ModelAndView login(RedirectAttributes redirectAttributes, HttpServletRequest request); @GetMapping(path = "/logout") String logout(Principal principal, HttpServletRequest request); }### Answer: @Test public void logoutWithPrincipal() throws Exception { Principal principal = PrincipalMother.davyvanroy(); mockMvc.perform(get("/logout").principal(principal)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/")); verify(profileService).logout(principal); }
### Question: RequestDetailsViewMapperDecorator implements RequestDetailsViewMapper { @Override public RequestDetailsView map(RequestDto r) { RequestDetailsView view = delegate.map(r); if (view != null) { IssueInformationDto issueInfo = r.getIssueInformation(); view.setIcon("https: view.setPlatform(issueInfo.getPlatform().name()); view.setOwner(issueInfo.getOwner()); view.setRepo(issueInfo.getRepo()); view.setIssueNumber(issueInfo.getNumber()); view.setTitle(issueInfo.getTitle()); view.setStarred(r.isLoggedInUserIsWatcher()); view.setDescription(githubGateway.getIssue(issueInfo.getOwner(), issueInfo.getRepo(), issueInfo.getNumber()).getBodyHtml()); view.setPhase(enumToCapitalizedStringMapper.map(r.getStatus().getPhase())); view.setStatus(enumToCapitalizedStringMapper.map(r.getStatus())); } return view; } @Override RequestDetailsView map(RequestDto r); }### Answer: @Test public void map() { final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); final IssueInformationDto issueInformation = requestDto.getIssueInformation(); final String status = "rdfjcgv"; final GithubResult githubResult = new GithubResult(); githubResult.setBodyHtml("<html/>"); when(delegate.map(requestDto)).thenReturn(new RequestDetailsView()); when(githubGateway.getIssue(issueInformation.getOwner(), issueInformation.getRepo(), issueInformation.getNumber())).thenReturn(githubResult); when(enumToCapitalizedStringMapper.map(requestDto.getStatus())).thenReturn(status); final RequestDetailsView result = decorator.map(requestDto); assertThat(result.getIcon()).isEqualTo("https: assertThat(result.getPlatform()).isEqualTo(issueInformation.getPlatform().name()); assertThat(result.getOwner()).isEqualTo(issueInformation.getOwner()); assertThat(result.getRepo()).isEqualTo(issueInformation.getRepo()); assertThat(result.getIssueNumber()).isEqualTo(issueInformation.getNumber()); assertThat(result.getTitle()).isEqualTo(issueInformation.getTitle()); assertThat(result.getStarred()).isEqualTo(requestDto.isLoggedInUserIsWatcher()); assertThat(result.getStatus()).isEqualTo(status); assertThat(result.getDescription()).isEqualTo(githubResult.getBodyHtml()); } @Test public void map_null() { final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); when(delegate.map(requestDto)).thenReturn(null); final RequestDetailsView result = decorator.map(requestDto); assertThat(result).isNull(); }
### Question: RequestViewMapper implements BaseMapper<RequestDto, RequestView> { @Override public RequestView map(final RequestDto r) { if (r == null) { return null; } return RequestView.builder() .id(r.getId()) .icon("https: .owner(r.getIssueInformation().getOwner()) .repo(r.getIssueInformation().getRepo()) .issueNumber(r.getIssueInformation().getNumber()) .platform(r.getIssueInformation().getPlatform().name()) .title(r.getIssueInformation().getTitle()) .status(enumToCapitalizedStringMapper.map(r.getStatus())) .phase(enumToCapitalizedStringMapper.map(r.getStatus().getPhase())) .starred(r.isLoggedInUserIsWatcher()) .technologies(r.getTechnologies()) .funds(r.getFunds()) .creationDate(r.getCreationDate() != null ? r.getCreationDate().atZone(ZoneId.systemDefault()) : null) .lastModifiedDate(r.getLastModifiedDate() != null ? r.getLastModifiedDate().atZone(ZoneId.systemDefault()) : null) .build(); } RequestViewMapper(final EnumToCapitalizedStringMapper enumToCapitalizedStringMapper); @Override RequestView map(final RequestDto r); }### Answer: @Test public void map() { final String status = "szfgdhxf"; final String phase = "sgzdxhfc"; final RequestDto request = RequestDtoMother.fundRequestArea51(); when(enumToCapitalizedStringMapper.map(request.getStatus())).thenReturn(status); when(enumToCapitalizedStringMapper.map(request.getStatus().getPhase())).thenReturn(phase); final RequestView result = mapper.map(request); assertThat(result.getId()).isEqualTo(request.getId()); assertThat(result.getIcon()).isEqualTo("https: assertThat(result.getOwner()).isEqualTo(request.getIssueInformation().getOwner()); assertThat(result.getRepo()).isEqualTo(request.getIssueInformation().getRepo()); assertThat(result.getIssueNumber()).isEqualTo(request.getIssueInformation().getNumber()); assertThat(result.getPlatform()).isEqualTo(request.getIssueInformation().getPlatform().name()); assertThat(result.getTitle()).isEqualTo(request.getIssueInformation().getTitle()); assertThat(result.getStatus()).isEqualTo(status); assertThat(result.getPhase()).isEqualTo(phase); assertThat(result.getStarred()).isEqualTo(request.isLoggedInUserIsWatcher()); assertThat(result.getTechnologies()).isEqualTo(request.getTechnologies()); assertThat(result.getFunds()).isEqualTo(request.getFunds()); assertThat(result.getCreationDate()).isEqualTo(request.getCreationDate()); assertThat(result.getLastModifiedDate()).isEqualTo(request.getLastModifiedDate()); } @Test public void map_null() { assertThat(mapper.map(null)).isNull(); }
### Question: MessagesController extends AbstractController { @PostMapping("/messages/{type}/{name}/delete") public ModelAndView delete(final Model model, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes) { messageService.delete(MessageType.valueOf(type.toUpperCase()), name); return redirectView(redirectAttributes) .withSuccessMessage("Deleted") .url("/messages/" + type) .build(); } MessagesController(final MessageService messageService); @RequestMapping("/messages") ModelAndView showAllMessagesPage(final Model model); @RequestMapping("/messages/{type}") ModelAndView showMessagesOfTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/add") ModelAndView showAddMessageToTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/{name}/edit") ModelAndView showEditPage(final Model model, @PathVariable String type, @PathVariable String name); @PostMapping("/messages/{type}/add") ModelAndView add(WebRequest request, @PathVariable String type, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/edit") ModelAndView update(WebRequest request, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/delete") ModelAndView delete(final Model model, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); }### Answer: @Test public void delete() throws Exception { String type = MessageType.REFERRAL_SHARE.toString(); String name = "name"; this.mockMvc.perform(post("/messages/{type}/{name}/delete", type, name)) .andExpect(redirectAlert("success", "Deleted")) .andExpect(redirectedUrl("/messages/" + type)); }
### 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: RequestController extends AbstractController { @GetMapping("/requests/{id}/actions") public ModelAndView detailActions(final Principal principal, @PathVariable final Long id) { final RequestDto request = requestService.findRequest(id); if (request != null) { final IssueInformationDto issueInformation = request.getIssueInformation(); return modelAndView().withObject("userClaimable", requestService.getUserClaimableResult(principal, id)) .withObject("request", request) .withObject("isAuthenticated", getAsJson(securityContextService.isUserFullyAuthenticated())) .withObject("platformIssue", platformIssueService.findBy(issueInformation.getPlatform(), issueInformation.getPlatformId()) .orElseThrow(ResourceNotFoundException::new)) .withView("pages/requests/detail-actions :: details") .build(); } else { throw new ResourceNotFoundException(); } } RequestController(final SecurityContextService securityContextService, final RequestService requestService, final PendingFundService pendingFundService, final StatisticsService statisticsService, final ProfileService profileService, FundService fundService, final RefundService refundService, final ClaimService claimService, final FiatService fiatService, final PlatformIssueService platformIssueService, final ObjectMapper objectMapper, final Mappers mappers); @GetMapping("/requests") ModelAndView requests(); @RequestMapping("/requests/{type}") ModelAndView details(@PathVariable String type, @RequestParam Map<String, String> queryParameters); @GetMapping("/requests/{id}") ModelAndView details(@PathVariable Long id, Model model); @GetMapping("/requests/github/{owner}/{repo}/{number}") ModelAndView details(@PathVariable String owner, @PathVariable String repo, @PathVariable String number, Model model); @GetMapping(value = "/requests/{id}/badge", produces = "image/svg+xml") ModelAndView detailsBadge(@PathVariable final Long id, final Model model, final HttpServletResponse response); @PostMapping("/requests/{id}/claim") ModelAndView claimRequest(Principal principal, @PathVariable Long id, @Valid UserClaimRequest userClaimRequest, RedirectAttributes redirectAttributes); @GetMapping("/requests/{id}/actions") ModelAndView detailActions(final Principal principal, @PathVariable final Long id); @PostMapping(value = {"/requests/{id}/watch"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody String toggleWatchRequest(Principal principal, @PathVariable Long id); @GetMapping("/user/requests") ModelAndView userRequests(Principal principal); @PostMapping(value = {"/rest/requests/erc67/fund"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody ERC67FundDto generateERC67ForFunding(@RequestBody @Valid CreateERC67FundRequest createERC67FundRequest); }### Answer: @Test public void detailActions() throws Exception { final RequestDto request = RequestDtoMother.freeCodeCampNoUserStories(); final IssueInformationDto issueInformation = request.getIssueInformation(); final UserClaimableDto userClaimableDto = mock(UserClaimableDto.class); final PlatformIssueDto platformIssue = mock(PlatformIssueDto.class); when(requestService.findRequest(1L)).thenReturn(request); when(requestService.getUserClaimableResult(principal, 1L)).thenReturn(userClaimableDto); when(platformIssueService.findBy(issueInformation.getPlatform(), issueInformation.getPlatformId())).thenReturn(Optional.of(platformIssue)); this.mockMvc.perform(get("/requests/{id}/actions", 1L).principal(principal)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.view().name("pages/requests/detail-actions :: details")) .andExpect(MockMvcResultMatchers.model().attribute("request", sameInstance(request))) .andExpect(MockMvcResultMatchers.model().attribute("userClaimable", sameInstance(userClaimableDto))) .andExpect(MockMvcResultMatchers.model().attribute("platformIssue", sameInstance(platformIssue))); }
### Question: RequestController extends AbstractController { @PostMapping("/requests/{id}/claim") public ModelAndView claimRequest(Principal principal, @PathVariable Long id, @Valid UserClaimRequest userClaimRequest, RedirectAttributes redirectAttributes) { if (!profileService.getUserProfile(principal).userOwnsAddress(userClaimRequest.getAddress())) { return redirectView(redirectAttributes) .withDangerMessage("Please update <a href=\"/profile\">your profile</a> with a correct ether address.") .url("/requests/" + id) .build(); } RequestDto request = requestService.findRequest(id); claimService.claim(principal, userClaimRequest); return redirectView(redirectAttributes) .withSuccessMessage("Your claim has been requested and is waiting for approval.") .url("/requests/" + id) .build(); } RequestController(final SecurityContextService securityContextService, final RequestService requestService, final PendingFundService pendingFundService, final StatisticsService statisticsService, final ProfileService profileService, FundService fundService, final RefundService refundService, final ClaimService claimService, final FiatService fiatService, final PlatformIssueService platformIssueService, final ObjectMapper objectMapper, final Mappers mappers); @GetMapping("/requests") ModelAndView requests(); @RequestMapping("/requests/{type}") ModelAndView details(@PathVariable String type, @RequestParam Map<String, String> queryParameters); @GetMapping("/requests/{id}") ModelAndView details(@PathVariable Long id, Model model); @GetMapping("/requests/github/{owner}/{repo}/{number}") ModelAndView details(@PathVariable String owner, @PathVariable String repo, @PathVariable String number, Model model); @GetMapping(value = "/requests/{id}/badge", produces = "image/svg+xml") ModelAndView detailsBadge(@PathVariable final Long id, final Model model, final HttpServletResponse response); @PostMapping("/requests/{id}/claim") ModelAndView claimRequest(Principal principal, @PathVariable Long id, @Valid UserClaimRequest userClaimRequest, RedirectAttributes redirectAttributes); @GetMapping("/requests/{id}/actions") ModelAndView detailActions(final Principal principal, @PathVariable final Long id); @PostMapping(value = {"/requests/{id}/watch"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody String toggleWatchRequest(Principal principal, @PathVariable Long id); @GetMapping("/user/requests") ModelAndView userRequests(Principal principal); @PostMapping(value = {"/rest/requests/erc67/fund"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody ERC67FundDto generateERC67ForFunding(@RequestBody @Valid CreateERC67FundRequest createERC67FundRequest); }### Answer: @Test public void claimRequest() throws Exception { RequestDto request = RequestDtoMother.freeCodeCampNoUserStories(); when(requestService.findRequest(1L)).thenReturn(request); UserClaimableDto userClaimableDto = UserClaimableDto.builder().build(); when(requestService.getUserClaimableResult(principal, 1L)).thenReturn(userClaimableDto); when(profileService.getUserProfile(principal).getEtherAddresses()).thenReturn(Collections.singletonList("0x0000000")); when(profileService.getUserProfile(principal).userOwnsAddress("0x0000000")).thenReturn(true); this.mockMvc.perform(post("/requests/{id}/claim", 1L) .param("address", "0x0000000") .param("platform", request.getIssueInformation().getPlatform().name()) .param("platformId", request.getIssueInformation().getPlatformId()) .principal(principal)) .andExpect(redirectAlert("success", "Your claim has been requested and is waiting for approval.")) .andExpect(redirectedUrl("/requests/" + 1L)); }
### Question: RequestController extends AbstractController { @PostMapping(value = {"/requests/{id}/watch"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public String toggleWatchRequest(Principal principal, @PathVariable Long id) { RequestDto request = requestService.findRequest(id); if (request.isLoggedInUserIsWatcher()) { request.setLoggedInUserIsWatcher(false); requestService.removeWatcherFromRequest(principal, id); } else { request.setLoggedInUserIsWatcher(true); requestService.addWatcherToRequest(principal, id); } RequestView requestview = mappers.map(RequestDto.class, RequestView.class, request); return getAsJson(requestview); } RequestController(final SecurityContextService securityContextService, final RequestService requestService, final PendingFundService pendingFundService, final StatisticsService statisticsService, final ProfileService profileService, FundService fundService, final RefundService refundService, final ClaimService claimService, final FiatService fiatService, final PlatformIssueService platformIssueService, final ObjectMapper objectMapper, final Mappers mappers); @GetMapping("/requests") ModelAndView requests(); @RequestMapping("/requests/{type}") ModelAndView details(@PathVariable String type, @RequestParam Map<String, String> queryParameters); @GetMapping("/requests/{id}") ModelAndView details(@PathVariable Long id, Model model); @GetMapping("/requests/github/{owner}/{repo}/{number}") ModelAndView details(@PathVariable String owner, @PathVariable String repo, @PathVariable String number, Model model); @GetMapping(value = "/requests/{id}/badge", produces = "image/svg+xml") ModelAndView detailsBadge(@PathVariable final Long id, final Model model, final HttpServletResponse response); @PostMapping("/requests/{id}/claim") ModelAndView claimRequest(Principal principal, @PathVariable Long id, @Valid UserClaimRequest userClaimRequest, RedirectAttributes redirectAttributes); @GetMapping("/requests/{id}/actions") ModelAndView detailActions(final Principal principal, @PathVariable final Long id); @PostMapping(value = {"/requests/{id}/watch"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody String toggleWatchRequest(Principal principal, @PathVariable Long id); @GetMapping("/user/requests") ModelAndView userRequests(Principal principal); @PostMapping(value = {"/rest/requests/erc67/fund"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody ERC67FundDto generateERC67ForFunding(@RequestBody @Valid CreateERC67FundRequest createERC67FundRequest); }### Answer: @Test public void toggleWatchRequest() throws Exception { RequestDto request = RequestDtoMother.freeCodeCampNoUserStories(); RequestView requestView = new RequestView(); when(requestService.findRequest(1L)).thenReturn(request); when(mappers.map(RequestDto.class, RequestView.class, request)).thenReturn(requestView); when(objectMapper.writeValueAsString(requestView)).thenReturn("{ starred: true }"); this.mockMvc.perform(post("/requests/{id}/watch", 1L).principal(principal)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().json("{ starred: true }")); }
### 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: RequestRestController { @GetMapping(value = "/github/{owner}/{repo}/{number}/claimable") public ClaimView claimDetails(@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)); final ClaimableResultDto claimableResult = requestService.getClaimableResult(request.getId()); return new ClaimView(claimableResult.isClaimable(), claimableResult.getClaimableByPlatformUserName()); } 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 claimDetails() throws Exception { final String owner = "fundrequest"; final String repo = "platform"; final String issueNumber = "320"; final String claimableBy = "hgfgh"; final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); final ClaimView claimView = new ClaimView(true, claimableBy); final String platformId = owner + "|FR|" + repo + "|FR|" + issueNumber; when(requestService.findRequest(GITHUB, platformId)).thenReturn(requestDto); when(requestService.getClaimableResult(requestDto.getId())).thenReturn(ClaimableResultDto.builder() .claimableByPlatformUserName(claimableBy) .claimable(true) .platform(GITHUB) .build()); mockMvc.perform(get("/rest/requests/github/{owner}/{repo}/{number}/claimable", owner, repo, issueNumber).accept(MediaType.APPLICATION_JSON_UTF8)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().json(objectMapper.writeValueAsString(claimView))); }
### Question: RequestVacuumer { @Scheduled(fixedDelay = 300_000L) public void cleanClaims() { final List<RequestClaim> claims = requestClaimRepository.findByStatus(ClaimRequestStatus.APPROVED); claims.stream() .filter(x -> x.getTransactionHash() != null) .filter(x -> azraelClient.getTransactionStatus(x.getTransactionHash()).equals(TransactionStatus.FAILED)) .forEach(x -> { x.setStatus(ClaimRequestStatus.TRANSACTION_FAILED); requestClaimRepository.save(x); }); } RequestVacuumer(final RequestClaimRepository requestClaimRepository, final RefundRequestRepository refundRequestRepository, final AzraelClient azraelClient); @Scheduled(fixedDelay = 300_000L) void cleanClaims(); @Scheduled(fixedDelay = 300_000L) void cleanRefunds(); }### Answer: @Test void cleanClaims() { final RequestClaim requestClaim1 = RequestClaim.builder().status(ClaimRequestStatus.APPROVED).transactionHash("0x213").build(); final RequestClaim requestClaim2 = RequestClaim.builder().status(ClaimRequestStatus.APPROVED).transactionHash("0x3243").build(); final RequestClaim requestClaim3 = RequestClaim.builder().status(ClaimRequestStatus.APPROVED).transactionHash(null).build(); final RequestClaim requestClaim4 = RequestClaim.builder().status(ClaimRequestStatus.APPROVED).transactionHash("0x687").build(); when(requestClaimRepository.findByStatus(ClaimRequestStatus.APPROVED)).thenReturn(Arrays.asList(requestClaim1, requestClaim2, requestClaim3, requestClaim4)); when(azraelClient.getTransactionStatus(requestClaim1.getTransactionHash())).thenReturn(TransactionStatus.SUCCEEDED); when(azraelClient.getTransactionStatus(requestClaim2.getTransactionHash())).thenReturn(TransactionStatus.NOT_FOUND); when(azraelClient.getTransactionStatus(requestClaim4.getTransactionHash())).thenReturn(TransactionStatus.FAILED); requestVacuumer.cleanClaims(); assertThat(requestClaim1.getStatus()).isEqualTo(ClaimRequestStatus.APPROVED); assertThat(requestClaim2.getStatus()).isEqualTo(ClaimRequestStatus.APPROVED); assertThat(requestClaim3.getStatus()).isEqualTo(ClaimRequestStatus.APPROVED); assertThat(requestClaim4.getStatus()).isEqualTo(ClaimRequestStatus.TRANSACTION_FAILED); verify(requestClaimRepository).findByStatus(ClaimRequestStatus.APPROVED); verify(requestClaimRepository).save(requestClaim4); verifyNoMoreInteractions(requestClaimRepository); }
### Question: FundController extends AbstractController { @PostMapping(value = "/requests/{requestId}/refunds") public ModelAndView requestRefund(final Principal principal, @PathVariable("requestId") final Long requestId, @RequestParam("funder_address") final String funderAddress, final RedirectAttributes redirectAttributes) { final RedirectBuilder redirectBuilder = redirectView(redirectAttributes).url("/requests/" + requestId + "#details"); if (isValid(redirectBuilder, principal, requestId, funderAddress)) { refundService.requestRefund(RequestRefundCommand.builder() .requestId(requestId) .funderAddress(funderAddress) .requestedBy(principal.getName()) .build()); return redirectBuilder.withSuccessMessage("Your refund has been requested and is waiting for approval.").build(); } else { return redirectBuilder.build(); } } FundController(final RequestService requestService, final RefundService refundService, final ProfileService profileService); @RequestMapping("/fund/{type}") ModelAndView details(Principal principal, @PathVariable String type, @RequestParam(name = "url", required = false) String url); @RequestMapping("/requests/{request-id}/fund") ModelAndView fundRequestById(Principal principal, @PathVariable("request-id") Long requestId); @PostMapping(value = "/requests/{requestId}/refunds") ModelAndView requestRefund(final Principal principal, @PathVariable("requestId") final Long requestId, @RequestParam("funder_address") final String funderAddress, final RedirectAttributes redirectAttributes); }### Answer: @Test public void requestRefund() throws Exception { final long requestId = 38L; final RequestDto request = RequestDtoMother.fundRequestArea51(); request.setStatus(RequestStatus.FUNDED); final String funderAddress = "0x24356789"; when(profileService.getUserProfile(principal)).thenReturn(UserProfile.builder().etherAddresses(Collections.singletonList(funderAddress)).build()); when(requestService.findRequest(requestId)).thenReturn(request); when(refundService.findAllRefundRequestsFor(requestId, PENDING, APPROVED)).thenReturn(Collections.singletonList(RefundRequestDto.builder() .funderAddress("0xeab43f") .build())); mockMvc.perform(post("/requests/{request-id}/refunds", requestId).principal(principal).param("funder_address", funderAddress)) .andExpect(status().is3xxRedirection()) .andExpect(redirectAlert("success", "Your refund has been requested and is waiting for approval.")) .andExpect(redirectedUrl("/requests/38#details")); verify(refundService).requestRefund(RequestRefundCommand.builder().requestId(requestId).funderAddress(funderAddress).requestedBy(principal.getName()).build()); }
### 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> fromString(final String githubIdAsString) { final Pattern pattern = Pattern.compile("^.*/(?<owner>.+)/(?<repo>.+)/.+/(?<number>\\d+)$"); final Matcher matcher = pattern.matcher(githubIdAsString); 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 fromString_issue() { final String owner = "FundRequest"; final String repo = "area51"; final String number = "38"; final Optional<GithubId> result = GithubId.fromString(String.format("/%s/%s/issues/%s", owner, repo, number)); assertThat(result).isPresent() .contains(GithubId.builder().owner(owner).repo(repo).number(number).build()); } @Test public void fromString_issueFullURL() { final String owner = "trufflesuite"; final String repo = "truffle"; final String number = "501"; final Optional<GithubId> result = GithubId.fromString(String.format("https: assertThat(result).isPresent() .contains(GithubId.builder().owner(owner).repo(repo).number(number).build()); } @Test public void fromString_pullrequest() { final String owner = "smartcontractkit"; final String repo = "chainlink"; final String number = "276"; final Optional<GithubId> result = GithubId.fromString(String.format("/%s/%s/pull/%s", owner, repo, number)); assertThat(result).isPresent() .contains(GithubId.builder().owner(owner).repo(repo).number(number).build()); } @Test public void fromString_pullrequestFullURL() { final String owner = "aragon"; final String repo = "aragonOS"; final String number = "204"; final Optional<GithubId> result = GithubId.fromString(String.format("https: assertThat(result).isPresent() .contains(GithubId.builder().owner(owner).repo(repo).number(number).build()); } @Test public void fromString_noMatchEmtpy() { final Optional<GithubId> result = GithubId.fromString("/hfgdjfgk"); assertThat(result).isEmpty(); }
### Question: RequestVacuumer { @Scheduled(fixedDelay = 300_000L) public void cleanRefunds() { final List<RefundRequest> refundRequests = refundRequestRepository.findAllByStatus(RefundRequestStatus.APPROVED); refundRequests.stream() .filter(refundRequest -> refundRequest.getTransactionHash() != null) .filter(refundRequest -> azraelClient.getTransactionStatus(refundRequest.getTransactionHash()).equals(TransactionStatus.FAILED)) .forEach(refundRequest -> { refundRequest.setStatus(RefundRequestStatus.TRANSACTION_FAILED); refundRequestRepository.save(refundRequest); }); } RequestVacuumer(final RequestClaimRepository requestClaimRepository, final RefundRequestRepository refundRequestRepository, final AzraelClient azraelClient); @Scheduled(fixedDelay = 300_000L) void cleanClaims(); @Scheduled(fixedDelay = 300_000L) void cleanRefunds(); }### Answer: @Test void cleanRefunds() { final RefundRequest refundRequest1 = RefundRequest.builder().status(RefundRequestStatus.APPROVED).transactionHash("0x213").build(); final RefundRequest refundRequest2 = RefundRequest.builder().status(RefundRequestStatus.APPROVED).transactionHash("0x3243").build(); final RefundRequest refundRequest3 = RefundRequest.builder().status(RefundRequestStatus.APPROVED).transactionHash(null).build(); final RefundRequest refundRequest4 = RefundRequest.builder().status(RefundRequestStatus.APPROVED).transactionHash("0x687").build(); when(refundRequestRepository.findAllByStatus(RefundRequestStatus.APPROVED)).thenReturn(Arrays.asList(refundRequest1, refundRequest2, refundRequest3, refundRequest4)); when(azraelClient.getTransactionStatus(refundRequest1.getTransactionHash())).thenReturn(TransactionStatus.SUCCEEDED); when(azraelClient.getTransactionStatus(refundRequest2.getTransactionHash())).thenReturn(TransactionStatus.NOT_FOUND); when(azraelClient.getTransactionStatus(refundRequest4.getTransactionHash())).thenReturn(TransactionStatus.FAILED); requestVacuumer.cleanRefunds(); assertThat(refundRequest1.getStatus()).isEqualTo(RefundRequestStatus.APPROVED); assertThat(refundRequest2.getStatus()).isEqualTo(RefundRequestStatus.APPROVED); assertThat(refundRequest3.getStatus()).isEqualTo(RefundRequestStatus.APPROVED); assertThat(refundRequest4.getStatus()).isEqualTo(RefundRequestStatus.TRANSACTION_FAILED); verify(refundRequestRepository).findAllByStatus(RefundRequestStatus.APPROVED); verify(refundRequestRepository).save(refundRequest4); verifyNoMoreInteractions(refundRequestRepository); }
### 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: GithubRateHealthCheck implements HealthIndicator { @Override public Health health() { final GithubRateLimit rateLimit = githubGateway.getRateLimit().getCore(); if (rateLimit.getRemaining() == 0) { return addDetails(Health.down(), rateLimit).build(); } if (rateLimit.getRemaining() > calculateThreshold(rateLimit.getLimit())) { return addDetails(Health.up(), rateLimit).build(); } return addDetails(Health.status(new Status("THRESHOLD REACHED")), rateLimit).build(); } GithubRateHealthCheck(final GithubGateway githubGateway, @Value("${io.fundrequest.health.github.api-rate-limit.threshold-percentage:20}") final int thresholdPercentage); @Override Health health(); }### Answer: @Test public void testHealth_up() { final int limit = 5000; final int remaining = 1001; final long reset = 1372700873; final ZonedDateTime verwachteReset = ZonedDateTime.ofInstant(Instant.ofEpochSecond(reset), ZoneId.systemDefault()); when(githubGateway.getRateLimit()).thenReturn(GithubRateLimits.with() .core(GithubRateLimit.with() .limit(limit) .remaining(remaining) .reset(reset) .build()) .build()); final Health result = githubRateHealthCheck.health(); assertThat(result.getStatus()).isEqualTo(Status.UP); assertThat(result.getDetails().get("limit")).isEqualTo(limit); assertThat(result.getDetails().get("remaining")).isEqualTo(remaining); assertThat(result.getDetails().get("reset")).isEqualTo(verwachteReset); } @Test public void testHealth_thresholdReached() { final int limit = 5000; final int remaining = 1000; final long reset = 1372700873; final ZonedDateTime verwachteReset = ZonedDateTime.ofInstant(Instant.ofEpochSecond(reset), ZoneId.systemDefault()); when(githubGateway.getRateLimit()).thenReturn(GithubRateLimits.with() .core(GithubRateLimit.with() .limit(limit) .remaining(remaining) .reset(reset) .build()) .build()); final Health result = githubRateHealthCheck.health(); assertThat(result.getStatus().getCode()).isEqualTo("THRESHOLD REACHED"); assertThat(result.getDetails().get("limit")).isEqualTo(limit); assertThat(result.getDetails().get("remaining")).isEqualTo(remaining); assertThat(result.getDetails().get("reset")).isEqualTo(verwachteReset); } @Test public void testHealth_down() { final int limit = 5000; final int remaining = 0; final long reset = 1372700873; final ZonedDateTime verwachteReset = ZonedDateTime.ofInstant(Instant.ofEpochSecond(reset), ZoneId.systemDefault()); when(githubGateway.getRateLimit()).thenReturn(GithubRateLimits.with() .core(GithubRateLimit.with() .limit(limit) .remaining(remaining) .reset(reset) .build()) .build()); final Health result = githubRateHealthCheck.health(); assertThat(result.getStatus()).isEqualTo(Status.DOWN); assertThat(result.getDetails().get("limit")).isEqualTo(limit); assertThat(result.getDetails().get("remaining")).isEqualTo(remaining); assertThat(result.getDetails().get("reset")).isEqualTo(verwachteReset); }
### 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: KeycloakRepositoryImpl implements KeycloakRepository { public Stream<UserIdentity> getUserIdentities(String userId) { return resource.users().get(userId).getFederatedIdentity() .stream() .map(fi -> UserIdentity.builder().provider(Provider.fromString(fi.getIdentityProvider())).username(fi.getUserName()).userId(fi.getUserId()).build()); } KeycloakRepositoryImpl(RealmResource resource, @Value("${keycloak.auth-server-url}") String keycloakUrl); Stream<UserIdentity> getUserIdentities(String userId); UserRepresentation getUser(String userId); void updateEtherAddress(String userId, String newAddress); @Override void updateEtherAddressVerified(final String userId, final Boolean isVerified); void updateTelegramName(String userId, String telegramName); void updateHeadline(String userId, String headline); void updateVerifiedDeveloper(String userId, Boolean isVerified); @Override boolean isEtherAddressVerified(final UserRepresentation userRepresentation); boolean isVerifiedDeveloper(UserRepresentation userRepresentation); boolean isVerifiedDeveloper(final String userId); String getAttribute(UserRepresentation userRepresentation, String property); String getTelegramName(UserRepresentation userRepresentation); String getPicture(UserRepresentation userRepresentation); String getHeadline(UserRepresentation userRepresentation); String getAccessToken(@NonNull KeycloakAuthenticationToken token, @NonNull Provider provider); boolean userExists(String userId); }### Answer: @Test public void getUserIdentities() { String userId = "123"; FederatedIdentityRepresentation fi = new FederatedIdentityRepresentation(); fi.setUserId(userId); fi.setUserName("davyvanroy"); fi.setIdentityProvider("GITHUB"); when(realmResource.users().get(userId).getFederatedIdentity() .stream()).thenReturn(Stream.of(fi)); Stream<UserIdentity> result = keycloakRepository.getUserIdentities(userId); Java6Assertions.assertThat(result.collect(Collectors.toList())).containsExactly( UserIdentity.builder() .provider(Provider.GITHUB) .userId(userId) .username("davyvanroy") .build()); }
### Question: ReferralServiceImpl implements ReferralService { @Override @Transactional public void createNewRef(CreateRefCommand command) { String referrer = command.getRef(); String referee = command.getPrincipal().getName(); validReferral(referrer, referee); if (!repository.existsByReferee(referee)) { Referral referral = Referral.builder() .referrer(referrer) .referee(referee) .status(ReferralStatus.PENDING) .build(); repository.save(referral); sendBountyIfPossible(referral); } else { throw new RuntimeException("This ref already exists!"); } } ReferralServiceImpl(ReferralRepository repository, KeycloakRepository keycloakRepository, BountyService bountyService); @EventListener @Transactional void onProviderLinked(UserLinkedProviderEvent event); @Transactional(readOnly = true) @Override ReferralOverviewDto getOverview(Principal principal); @Override @Cacheable("ref_links") String generateRefLink(String userId, String source); @Transactional(readOnly = true) @Override List<ReferralDto> getReferrals(Principal principal); @Override @Transactional void createNewRef(CreateRefCommand command); }### Answer: @Test void savesReferralAndCreatesBounty() { Principal referee = () -> "davyvanroy"; CreateRefCommand command = CreateRefCommand.builder().principal(referee).ref("referrer").build(); when(keycloakRepository.userExists(referee.getName())).thenReturn(true); when(keycloakRepository.userExists(command.getRef())).thenReturn(true); when(referralRepository.existsByReferee(referee.getName())).thenReturn(false); when(keycloakRepository.isVerifiedDeveloper(referee.getName())).thenReturn(true); referralService.createNewRef(command); verify(referralRepository, times(2)).save(Referral.builder() .referrer(command.getRef()) .referee(referee.getName()) .status(ReferralStatus.PENDING) .build()); verify(bountyService).createBounty(CreateBountyCommand.builder() .type(BountyType.REFERRAL) .userId(command.getRef()) .build()); }
### 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: PlatformIssueServiceImpl implements PlatformIssueService { @Override public Optional<PlatformIssueDto> findBy(final Platform platform, final String platformId) { if (Platform.GITHUB == platform) { return githubIssueService.findBy(platformId) .map(githubIssue -> mappers.map(GithubIssue.class, PlatformIssueDto.class, githubIssue)); } return Optional.empty(); } PlatformIssueServiceImpl(final GithubIssueService githubIssueService, final Mappers mappers); @Override Optional<PlatformIssueDto> findBy(final Platform platform, final String platformId); }### Answer: @Test void findBy() { final String platformId = "dfsfd|FR|wfgwar|FR|243"; final GithubIssue githubIssue = GithubIssue.builder().build(); final PlatformIssueDto platformIssueDto = PlatformIssueDto.builder().build(); when(githubIssueService.findBy(platformId)).thenReturn(Optional.of(githubIssue)); when(mappers.map(GithubIssue.class, PlatformIssueDto.class, githubIssue)).thenReturn(platformIssueDto); final Optional<PlatformIssueDto> result = platformIssueService.findBy(Platform.GITHUB, platformId); assertThat(result).isPresent().containsSame(platformIssueDto); } @Test void findBy_noGithubIssueFound() { final String platformId = "dfsfd|FR|wfgwar|FR|243"; when(githubIssueService.findBy(platformId)).thenReturn(Optional.empty()); final Optional<PlatformIssueDto> result = platformIssueService.findBy(Platform.GITHUB, platformId); assertThat(result).isEmpty(); } @Test void findBy_platformNotGithub() { final String platformId = "dfsfd|FR|wfgwar|FR|243"; final GithubIssue githubIssue = GithubIssue.builder().build(); final PlatformIssueDto platformIssueDto = PlatformIssueDto.builder().build(); when(githubIssueService.findBy(platformId)).thenReturn(Optional.of(githubIssue)); when(mappers.map(GithubIssue.class, PlatformIssueDto.class, githubIssue)).thenReturn(platformIssueDto); final Optional<PlatformIssueDto> result = platformIssueService.findBy(Platform.STACK_OVERFLOW, platformId); assertThat(result).isEmpty(); }
### 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 Message add(MessageDto messageDto) { int minlength = 3; if (messageDto.getName().length() < 3) { throw new RuntimeException(String.format("Message name should be at least %s characters long", minlength)); } if (repository.findByTypeAndName(messageDto.getType(), messageDto.getName()).isPresent()) { throw new RuntimeException(String.format("Message with type %s and name %s already exists", messageDto.getType().toString(), messageDto.getName())); } 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 add() { Message message = Message.builder().type(MessageType.REFERRAL_SHARE).name("myNewItem").build(); MessageDto messageDto = MessageDto.builder().type(MessageType.REFERRAL_SHARE).name("myNewItem").build(); when(objectMapper.convertValue(messageDto, Message.class)).thenReturn(message); when(messageRepository.save(message)).thenReturn(message); Message result = messageService.add(messageDto); assertThat(result).isEqualTo(message); } @Test void add_throwsExceptionWhenExists() { try { messageService.add(messageDto1); failBecauseExceptionWasNotThrown(RuntimeException.class); } catch (RuntimeException e) { assertThat(e.getMessage()).isEqualTo(String.format("Message with type %s and name %s already exists", messageDto1.getType().toString(), messageDto1.getName())); } } @Test void add_throwsExceptionWhenNameIsToShort() { MessageDto messageDto = MessageDto.builder().type(MessageType.REFERRAL_SHARE).name("m1").build(); try { messageService.add(messageDto); failBecauseExceptionWasNotThrown(RuntimeException.class); } catch (RuntimeException e) { assertThat(e.getMessage()).isEqualTo("Message name should be at least 3 characters long"); } }
### 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: KeycloakRepositoryImpl implements KeycloakRepository { @Override public boolean isEtherAddressVerified(final UserRepresentation userRepresentation) { return "true".equalsIgnoreCase(getAttribute(userRepresentation, ETHER_ADDRESS_VERIFIED_KEY)); } KeycloakRepositoryImpl(RealmResource resource, @Value("${keycloak.auth-server-url}") String keycloakUrl); Stream<UserIdentity> getUserIdentities(String userId); UserRepresentation getUser(String userId); void updateEtherAddress(String userId, String newAddress); @Override void updateEtherAddressVerified(final String userId, final Boolean isVerified); void updateTelegramName(String userId, String telegramName); void updateHeadline(String userId, String headline); void updateVerifiedDeveloper(String userId, Boolean isVerified); @Override boolean isEtherAddressVerified(final UserRepresentation userRepresentation); boolean isVerifiedDeveloper(UserRepresentation userRepresentation); boolean isVerifiedDeveloper(final String userId); String getAttribute(UserRepresentation userRepresentation, String property); String getTelegramName(UserRepresentation userRepresentation); String getPicture(UserRepresentation userRepresentation); String getHeadline(UserRepresentation userRepresentation); String getAccessToken(@NonNull KeycloakAuthenticationToken token, @NonNull Provider provider); boolean userExists(String userId); }### Answer: @Test public void isVerifiedEtherAddress_attribute_not_present() { final UserRepresentation userRepresentation = mock(UserRepresentation.class); final Map<String, List<String>> userAttributes = new HashMap<>(); userAttributes.put("djghfh", new ArrayList<>()); when(userRepresentation.getAttributes()).thenReturn(userAttributes); final boolean result = keycloakRepository.isEtherAddressVerified(userRepresentation); assertThat(result).isFalse(); } @Test public void isVerifiedEtherAddress_attributes_empty() { final UserRepresentation userRepresentation = mock(UserRepresentation.class); final Map<String, List<String>> userAttributes = new HashMap<>(); when(userRepresentation.getAttributes()).thenReturn(userAttributes); final boolean result = keycloakRepository.isEtherAddressVerified(userRepresentation); assertThat(result).isFalse(); } @Test public void isVerifiedEtherAddress_attributes_null() { final UserRepresentation userRepresentation = mock(UserRepresentation.class); final Map<String, List<String>> userAttributes = null; when(userRepresentation.getAttributes()).thenReturn(userAttributes); final boolean result = keycloakRepository.isEtherAddressVerified(userRepresentation); assertThat(result).isFalse(); }
### 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: SecurityContextServiceImpl implements SecurityContextService { @Override public Optional<UserProfile> getLoggedInUserProfile() { return getLoggedInUser().filter(this::isUserFullyAuthenticated) .map(authentication -> (Principal) authentication.getPrincipal()) .map(profileService::getUserProfile); } SecurityContextServiceImpl(final SecurityContextHolderSpringDelegate securityContextHolder, final ProfileService profileService); @Override Optional<Authentication> getLoggedInUser(); @Override boolean isUserFullyAuthenticated(); @Override Optional<UserProfile> getLoggedInUserProfile(); }### Answer: @Test public void getLoggedInUserProfile() { final Authentication authentication = mock(Authentication.class); final String userId = "fdsgzdg"; final Principal principal = mock(Principal.class); final UserProfile userProfile = mock(UserProfile.class); when(authentication.isAuthenticated()).thenReturn(true); when(authentication.getPrincipal()).thenReturn(principal); when(principal.getName()).thenReturn(userId); when(profileService.getUserProfile(principal)).thenReturn(userProfile); when(securityContextHolder.getContext().getAuthentication()).thenReturn(authentication); final Optional<UserProfile> result = securityContextService.getLoggedInUserProfile(); assertThat(result).containsSame(userProfile); } @Test public void getLoggedInUserProfile_noPrincipal() { final Authentication authentication = mock(Authentication.class); final String userId = "fdsgzdg"; when(authentication.isAuthenticated()).thenReturn(true); when(authentication.getPrincipal()).thenReturn(null); when(securityContextHolder.getContext().getAuthentication()).thenReturn(authentication); final Optional<UserProfile> result = securityContextService.getLoggedInUserProfile(); assertThat(result).isEmpty(); } @Test public void getLoggedInUserProfile_noUserProfile() { final Authentication authentication = mock(Authentication.class); final String userId = "fdsgzdg"; final Principal principal = mock(Principal.class); when(authentication.isAuthenticated()).thenReturn(true); when(authentication.getPrincipal()).thenReturn(principal); when(principal.getName()).thenReturn(userId); when(profileService.getUserProfile(principal)).thenReturn(null); when(securityContextHolder.getContext().getAuthentication()).thenReturn(authentication); final Optional<UserProfile> result = securityContextService.getLoggedInUserProfile(); assertThat(result).isEmpty(); } @Test public void getLoggedInUserProfile_noAuthentication() { when(securityContextHolder.getContext().getAuthentication()).thenReturn(null); final Optional<UserProfile> result = securityContextService.getLoggedInUserProfile(); assertThat(result).isEmpty(); } @Test public void getLoggedInUserProfile_notAuthentciated() { final Authentication authentication = mock(Authentication.class); when(authentication.isAuthenticated()).thenReturn(false); when(securityContextHolder.getContext().getAuthentication()).thenReturn(authentication); final Optional<UserProfile> result = securityContextService.getLoggedInUserProfile(); assertThat(result).isEmpty(); } @Test public void getLoggedInUserProfile_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 Optional<UserProfile> result = securityContextService.getLoggedInUserProfile(); assertThat(result).isEmpty(); }
### 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: RequestClaimDtoDecorator implements RequestClaimDtoMapper { @Override public RequestClaimDto map(RequestClaim r) { RequestClaimDto dto = delegate.map(r); if (dto != null) { RequestDto request = requestService.findRequest(r.getRequestId()); dto.setUrl(createLink(request.getIssueInformation())); dto.setTitle(request.getIssueInformation().getTitle()); dto.setFundRequestUrl(createFundRequestLink(request.getId())); } return dto; } @Override RequestClaimDto map(RequestClaim r); }### Answer: @Test public void map() { final RequestClaim requestClaim = RequestClaim.builder() .id(657L) .address("0xE51551D3B11eF7559164D051D9714E59A1c4E486") .status(ClaimRequestStatus.PENDING) .flagged(false) .requestId(9L) .solver("ghjgfhg") .build(); final RequestClaimDto requestClaimDto = new RequestClaimDto(); final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); final IssueInformationDto issueInformation = requestDto.getIssueInformation(); when(delegate.map(requestClaim)).thenReturn(requestClaimDto); when(requestService.findRequest(requestClaim.getRequestId())).thenReturn(requestDto); final RequestClaimDto result = decorator.map(requestClaim); assertThat(result.getTitle()).isEqualTo(requestDto.getIssueInformation().getTitle()); assertThat(result.getUrl()).isEqualTo("https: assertThat(result.getFundRequestUrl()).isEqualTo("https: } @Test public void map_null() { final RequestClaim requestClaim = RequestClaim.builder() .id(657L) .address("0xE51551D3B11eF7559164D051D9714E59A1c4E486") .status(ClaimRequestStatus.PENDING) .flagged(false) .requestId(9L) .solver("ghjgfhg") .build(); when(delegate.map(requestClaim)).thenReturn(null); final RequestClaimDto result = decorator.map(requestClaim); assertThat(result).isNull(); }
### 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 { @Transactional @Override public void claim(Principal user, UserClaimRequest userClaimRequest) { Request request = requestRepository.findByPlatformAndPlatformId(userClaimRequest.getPlatform(), userClaimRequest.getPlatformId()) .orElseThrow(() -> new RuntimeException("Request not found")); RequestDto requestDto = mappers.map(Request.class, RequestDto.class, request); String solver = githubClaimResolver.getUserPlatformUsername(user, request.getIssueInformation().getPlatform()) .orElseThrow(() -> new RuntimeException("You are not linked to github")); final RequestClaim requestClaim = RequestClaim.builder() .address(userClaimRequest.getAddress()) .requestId(request.getId()) .flagged(!githubClaimResolver.canClaim(user, requestDto)) .solver(solver) .status(ClaimRequestStatus.PENDING) .build(); requestClaimRepository.save(requestClaim); request.setStatus(RequestStatus.CLAIM_REQUESTED); eventPublisher.publishEvent(ClaimRequestedEvent.builder() .requestClaim(requestClaim) .build()); requestRepository.save(request); } 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 claim() { Principal solver = PrincipalMother.davyvanroy(); UserClaimRequest userClaimRequest = UserClaimRequestMother.kazuki43zooApiStub().build(); Request request = RequestMother.freeCodeCampNoUserStories().build(); when(requestRepository.findByPlatformAndPlatformId(userClaimRequest.getPlatform(), userClaimRequest.getPlatformId())) .thenReturn(Optional.of(request)); RequestDto requestDto = RequestDtoMother.freeCodeCampNoUserStories(); when(mappers.map(Request.class, RequestDto.class, request)).thenReturn(requestDto); when(githubClaimResolver.getUserPlatformUsername(solver, request.getIssueInformation().getPlatform())) .thenReturn(Optional.of(solver.getName())); when(githubClaimResolver.canClaim(solver, requestDto)).thenReturn(true); claimService.claim(solver, userClaimRequest); assertThat(request.getStatus()).isEqualTo(RequestStatus.CLAIM_REQUESTED); verify(requestRepository).save(request); ArgumentCaptor<RequestClaim> requestClaimArgumentCaptor = ArgumentCaptor.forClass(RequestClaim.class); verify(requestClaimRepository).save(requestClaimArgumentCaptor.capture()); RequestClaim requestClaim = requestClaimArgumentCaptor.getValue(); assertThat(requestClaim.getRequestId()).isEqualTo(request.getId()); assertThat(requestClaim.getAddress()).isEqualTo(userClaimRequest.getAddress()); assertThat(requestClaim.getSolver()).isEqualTo(solver.getName()); assertThat(requestClaim.getFlagged()).isFalse(); assertThat(requestClaim.getStatus()).isEqualTo(ClaimRequestStatus.PENDING); }
### 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: ClaimDtoAggregator { ClaimsByTransactionAggregate aggregateClaims(final List<ClaimDto> claims) { TokenValueDto totalFndValue = null; TokenValueDto totalOtherValue = null; final Map<String, ClaimByTransactionAggregate.Builder> claimsPerTransaction = new HashMap<>(); for (final ClaimDto claim : claims) { final ClaimByTransactionAggregate.Builder builder = resolveClaimByTransactionBuilder(claimsPerTransaction, claim); if (isFNDToken(claim)) { totalFndValue = sumTokenValue(totalFndValue, claim.getTokenValue()); builder.fndValue(claim.getTokenValue()); } else { totalOtherValue = sumTokenValue(totalOtherValue, claim.getTokenValue()); builder.otherValue(claim.getTokenValue()); } claimsPerTransaction.put(claim.getTransactionHash(), builder); } return ClaimsByTransactionAggregate.builder() .claims(Collections.unmodifiableList(claimsPerTransaction.keySet() .stream() .map(transactionHash -> claimsPerTransaction.get(transactionHash).build()) .collect(toList()))) .fndValue(totalFndValue) .otherValue(totalOtherValue) .usdValue(fiatService.getUsdPrice(totalFndValue, totalOtherValue)) .build(); } ClaimDtoAggregator(@Value("${io.fundrequest.contract.token.address}") final String fndContractAdress, final FiatService fiatService); }### Answer: @Test void aggregateClaims() { final String solver1 = "dgh"; final String solver2 = "hdxhg"; final TokenValueDto fndValue1 = FND().totalAmount(new BigDecimal("50")).build(); final TokenValueDto fndValue2 = FND().totalAmount(new BigDecimal("4.26")).build(); final TokenValueDto zrxValue1 = ZRX().totalAmount(new BigDecimal("48")).build(); final TokenValueDto zrxValue2 = ZRX().totalAmount(new BigDecimal("7")).build(); final TokenValueDto fndTotal = TokenValueDtoMother.FND().totalAmount(new BigDecimal("54.26")).build(); final TokenValueDto zrxTotal = TokenValueDtoMother.ZRX().totalAmount(new BigDecimal("55")).build(); final String txHash1 = "txHash1"; final String txHash2 = "txHash2"; final ClaimDto claim1 = ClaimDtoMother.aClaimDto().tokenValue(fndValue1).transactionHash(txHash1).solver(solver1).build(); final ClaimDto claim2 = ClaimDtoMother.aClaimDto().tokenValue(fndValue2).transactionHash(txHash2).solver(solver2).build(); final ClaimDto claim3 = ClaimDtoMother.aClaimDto().tokenValue(zrxValue1).transactionHash(txHash2).solver(solver1).build(); final ClaimDto claim4 = ClaimDtoMother.aClaimDto().tokenValue(zrxValue2).transactionHash(txHash1).solver(solver1).build(); final ClaimByTransactionAggregate transaction1 = ClaimByTransactionAggregate.builder() .solver(claim1.getSolver()) .transactionHash(txHash1) .timestamp(claim1.getTimestamp()) .fndValue(fndValue1) .otherValue(zrxValue2) .build(); final ClaimByTransactionAggregate transaction2 = ClaimByTransactionAggregate.builder() .solver(claim2.getSolver()) .transactionHash(txHash2) .timestamp(claim2.getTimestamp()) .fndValue(fndValue2) .otherValue(zrxValue1) .build(); final double expectedUSD = 3456.3D; when(fiatService.getUsdPrice(fndTotal, zrxTotal)).thenReturn(expectedUSD); final ClaimsByTransactionAggregate claims = claimDtoAggregator.aggregateClaims(Arrays.asList(claim1, claim2, claim3, claim4)); assertThat(claims.getClaims()).isEqualTo(Arrays.asList(transaction1, transaction2)); assertThat(claims.getFndValue()).isEqualTo(fndTotal); assertThat(claims.getOtherValue()).isEqualTo(zrxTotal); assertThat(claims.getUsdValue()).isEqualTo(expectedUSD); }
### Question: CreateGithubCommentOnResolvedHandler { @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) public void createGithubCommentOnRequestClaimable(final RequestClaimableEvent event) { if (addComment) { final RequestDto request = event.getRequestDto(); final IssueInformationDto issueInformation = request.getIssueInformation(); if (issueInformation.getPlatform() == Platform.GITHUB) { final String solver = Optional.ofNullable(githubScraper.fetchGithubIssue(issueInformation.getOwner(), issueInformation.getRepo(), issueInformation.getNumber()).getSolver()) .orElseThrow(() -> new RuntimeException("No solver found for request " + request.getId())); final CreateGithubComment comment = new CreateGithubComment(); comment.setBody(githubCommentFactory.createResolvedComment(request.getId(), solver)); githubGateway.createCommentOnIssue(issueInformation.getOwner(), issueInformation.getRepo(), issueInformation.getNumber(), comment); } } } CreateGithubCommentOnResolvedHandler(final GithubGateway githubGateway, final GithubScraper githubScraper, final GithubCommentFactory githubCommentFactory, @Value("${github.add-comments:false}") final Boolean addComment); @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) void createGithubCommentOnRequestClaimable(final RequestClaimableEvent event); }### Answer: @Test public void ignoresGithubComment() { handler = new CreateGithubCommentOnResolvedHandler(githubGateway, githubScraper, githubCommentFactory, false); handler.createGithubCommentOnRequestClaimable(mock((RequestClaimableEvent.class))); verifyZeroInteractions(githubGateway); } @Test public void postsGithubComment() { final RequestClaimableEvent event = new RequestClaimableEvent(RequestDtoMother.freeCodeCampNoUserStories(), LocalDateTime.now()); final String expectedMessage = "ytufg"; final RequestDto request = event.getRequestDto(); final IssueInformationDto issueInformation = request.getIssueInformation(); final String solver = "gdhfjghiuyutfyd"; final ArgumentCaptor<CreateGithubComment> createGithubCommentArgumentCaptor = ArgumentCaptor.forClass(CreateGithubComment.class); when(githubScraper.fetchGithubIssue(issueInformation.getOwner(), issueInformation.getRepo(), issueInformation.getNumber())).thenReturn(GithubIssue.builder() .solver(solver) .build()); when(githubCommentFactory.createResolvedComment(request.getId(), solver)).thenReturn(expectedMessage); handler.createGithubCommentOnRequestClaimable(event); verify(githubGateway).createCommentOnIssue(eq(issueInformation.getOwner()), eq(issueInformation.getRepo()), eq(issueInformation.getNumber()), createGithubCommentArgumentCaptor.capture()); assertThat(createGithubCommentArgumentCaptor.getValue().getBody()).isEqualTo(expectedMessage); } @Test public void postsGithubComment_noSolverFound() { final RequestClaimableEvent event = new RequestClaimableEvent(RequestDtoMother.freeCodeCampNoUserStories(), LocalDateTime.now()); final RequestDto request = event.getRequestDto(); final IssueInformationDto issueInformation = request.getIssueInformation(); when(githubScraper.fetchGithubIssue(issueInformation.getOwner(), issueInformation.getRepo(), issueInformation.getNumber())).thenReturn(GithubIssue.builder().build()); try { handler.createGithubCommentOnRequestClaimable(event); fail("RuntimeException expected"); } catch (RuntimeException e) { assertThat(e.getMessage()).isEqualTo("No solver found for request " + request.getId()); } }
### 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 SupportFragmentLike loadSupportFragmentModule( Fragment hostingFragment, String moduleName, String className) throws LazyLoadingException { try { Class lazyLoadedClass = mLoaderAlgorithm.loadModule(moduleName, className); Constructor c = lazyLoadedClass.getConstructor(Fragment.class); SupportFragmentLike fragmentLike = (SupportFragmentLike) c.newInstance(hostingFragment); return fragmentLike; } 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 testThatLoadSucceedsForSupportFragmentModule() throws IOException, LazyLoadingException, ClassNotFoundException { Mockito.when(mModulePathsNo1Mock.containsDexFile()).thenReturn(true); Mockito.when(mModulePathsNo1Mock.getDexFile()).thenReturn(mDexFileNo1Mock); Mockito.when(mModulePathsNo1Mock.getOptimizedDexFile()).thenReturn(mOptDexFileNo1Mock); SupportFragmentLike returnedFragment = mObjectUnderTest.loadSupportFragmentModule( mSupportFragmentMock, MODULE_NAME_NO1, SupportFragmentModule.class.getName()); Assert.assertEquals(returnedFragment.getClass(), SupportFragmentModule.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(SupportFragmentModule.class.getName()); Mockito.verifyZeroInteractions(mNativeModuleLoaderMock); }
### Question: LazyModuleLoader { public synchronized FragmentLike loadFragmentModule( android.app.Fragment hostingFragment, String moduleName, String className) throws LazyLoadingException { try { Class lazyLoadedClass = mLoaderAlgorithm.loadModule(moduleName, className); Constructor c = lazyLoadedClass.getConstructor(android.app.Fragment.class); FragmentLike fragmentLike = (FragmentLike) c.newInstance(hostingFragment); return fragmentLike; } 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 testThatLoadSucceedsForFragmentModule() throws IOException, LazyLoadingException, ClassNotFoundException { Mockito.when(mModulePathsNo1Mock.containsDexFile()).thenReturn(true); Mockito.when(mModulePathsNo1Mock.getDexFile()).thenReturn(mDexFileNo1Mock); Mockito.when(mModulePathsNo1Mock.getOptimizedDexFile()).thenReturn(mOptDexFileNo1Mock); FragmentLike returnedFragment = mObjectUnderTest.loadFragmentModule( mAppFragmentMock, MODULE_NAME_NO1, AppFragmentModule.class.getName()); Assert.assertEquals(returnedFragment.getClass(), AppFragmentModule.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(AppFragmentModule.class.getName()); Mockito.verifyZeroInteractions(mNativeModuleLoaderMock); }
### 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: QCParser { public static GuacamoleConfiguration getConfiguration(String uri) throws GuacamoleException { URI qcUri; try { qcUri = new URI(uri); if (!qcUri.isAbsolute()) throw new TranslatableGuacamoleClientException("URI must be absolute.", "QUICKCONNECT.ERROR_NOT_ABSOLUTE_URI"); } catch (URISyntaxException e) { throw new TranslatableGuacamoleClientException("Invalid URI Syntax", "QUICKCONNECT.ERROR_INVALID_URI"); } String protocol = qcUri.getScheme(); String host = qcUri.getHost(); int port = qcUri.getPort(); String userInfo = qcUri.getUserInfo(); String query = qcUri.getQuery(); GuacamoleConfiguration qcConfig = new GuacamoleConfiguration(); if (protocol != null && !protocol.isEmpty()) qcConfig.setProtocol(protocol); else throw new TranslatableGuacamoleClientException("No protocol specified.", "QUICKCONNECT.ERROR_NO_PROTOCOL"); if (port > 0) qcConfig.setParameter("port", Integer.toString(port)); if (host != null && !host.isEmpty()) qcConfig.setParameter("hostname", host); else throw new TranslatableGuacamoleClientException("No host specified.", "QUICKCONNECT.ERROR_NO_HOST"); if (query != null && !query.isEmpty()) { try { Map<String, String> queryParams = parseQueryString(query); if (queryParams != null) for (Map.Entry<String, String> entry: queryParams.entrySet()) qcConfig.setParameter(entry.getKey(), entry.getValue()); } catch (UnsupportedEncodingException e) { throw new GuacamoleServerException("Unexpected lack of UTF-8 encoding support.", e); } } if (userInfo != null && !userInfo.isEmpty()) { try { parseUserInfo(userInfo, qcConfig); } catch (UnsupportedEncodingException e) { throw new GuacamoleServerException("Unexpected lack of UTF-8 encoding support.", e); } } return qcConfig; } 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 testGetConfiguration() throws GuacamoleException { String uri1 = "ssh: GuacamoleConfiguration config1 = QCParser.getConfiguration(uri1); assertEquals("ssh", config1.getProtocol()); assertEquals("hostname1.domain.local", config1.getParameter("hostname")); assertEquals("guacuser", config1.getParameter("username")); assertEquals("guacpassword", config1.getParameter("password")); assertEquals("value1", config1.getParameter("param1")); assertEquals("value2", config1.getParameter("param2")); String uri2 = "rdp: GuacamoleConfiguration config2 = QCParser.getConfiguration(uri2); assertEquals("rdp", config2.getProtocol()); assertEquals("windows1.domain.tld", config2.getParameter("hostname")); assertEquals("domain\\guacuser", config2.getParameter("username")); assertEquals("adPassword123", config2.getParameter("password")); assertEquals("true", config2.getParameter("enable-sftp")); String uri3 = "vnc: GuacamoleConfiguration config3 = QCParser.getConfiguration(uri3); assertEquals("vnc", config3.getProtocol()); assertEquals("mirror1.example.com", config3.getParameter("hostname")); assertEquals("5910", config3.getParameter("port")); }
### Question: EnumGuacamoleProperty implements GuacamoleProperty<T> { @Override public T parseValue(String value) throws GuacamoleException { if (value == null) return null; T parsedValue = valueMapping.get(value); if (parsedValue != null) return parsedValue; List<String> legalValues = new ArrayList<>(valueMapping.keySet()); Collections.sort(legalValues); throw new GuacamoleServerException(String.format("\"%s\" is not a " + "valid value for property \"%s\". Valid values are: \"%s\"", value, getName(), String.join("\", \"", legalValues))); } EnumGuacamoleProperty(Map<String, T> valueMapping); EnumGuacamoleProperty(Class<T> enumClass); EnumGuacamoleProperty(String key, T value, Object... additional); @Override T parseValue(String value); }### Answer: @Test public void testParseValue() throws GuacamoleException { assertEquals(Fish.SALMON, FAVORITE_FISH.parseValue("salmon")); assertEquals(Fish.TROUT, FAVORITE_FISH.parseValue("trout")); assertEquals(Fish.MACKEREL, FAVORITE_FISH.parseValue("mackerel")); assertEquals(Fish.TUNA, FAVORITE_FISH.parseValue("tuna")); assertEquals(Fish.SARDINE, FAVORITE_FISH.parseValue("sardine")); } @Test public void testParseNullValue() throws GuacamoleException { assertNull(FAVORITE_FISH.parseValue(null)); } @Test public void testParseInvalidValue() { try { FAVORITE_FISH.parseValue("anchovy"); fail("Invalid EnumGuacamoleProperty values should fail to parse with an exception."); } catch (GuacamoleException e) { String message = e.getMessage(); assertTrue(message.contains("\"mackerel\", \"salmon\", \"sardine\", \"trout\", \"tuna\"")); } } @Test public void testUnannotatedEnum() throws GuacamoleException { EnumGuacamoleProperty<Vegetable> favoriteVegetable = new EnumGuacamoleProperty<Vegetable>( "potato", Vegetable.POTATO, "carrot", Vegetable.CARROT ) { @Override public String getName() { return "favorite-vegetable"; } }; assertEquals(Vegetable.POTATO, favoriteVegetable.parseValue("potato")); assertEquals(Vegetable.CARROT, favoriteVegetable.parseValue("carrot")); } @Test public void testAnnotationPrecedence() throws GuacamoleException { EnumGuacamoleProperty<Fish> favoriteFish = new EnumGuacamoleProperty<Fish>( "chinook", Fish.SALMON, "rainbow", Fish.TROUT ) { @Override public String getName() { return "favorite-fish"; } }; assertEquals(Fish.SALMON, favoriteFish.parseValue("chinook")); assertEquals(Fish.TROUT, favoriteFish.parseValue("rainbow")); try { favoriteFish.parseValue("salmon"); fail("Explicit key/value mapping should take priority over annotations."); } catch (GuacamoleException e) { } try { favoriteFish.parseValue("trout"); fail("Explicit key/value mapping should take priority over annotations."); } catch (GuacamoleException e) { } try { favoriteFish.parseValue("tuna"); fail("Annotations should not have any effect if explicit key/value mapping is used."); } catch (GuacamoleException e) { } }
### Question: TokenFilter { public String filter(String input) { StringBuilder output = new StringBuilder(); Matcher tokenMatcher = tokenPattern.matcher(input); int endOfLastMatch = 0; while (tokenMatcher.find()) { String literal = tokenMatcher.group(LEADING_TEXT_GROUP); String escape = tokenMatcher.group(ESCAPE_CHAR_GROUP); String modifier = tokenMatcher.group(TOKEN_MODIFIER); output.append(literal); if ("$".equals(escape)) { String notToken = tokenMatcher.group(TOKEN_GROUP); output.append(notToken); } else { output.append(escape); String tokenName = tokenMatcher.group(TOKEN_NAME_GROUP); String tokenValue = getToken(tokenName); if (tokenValue == null) { String notToken = tokenMatcher.group(TOKEN_GROUP); output.append(notToken); } else { if (modifier != null && !modifier.isEmpty()) { switch (modifier) { case "upper": output.append(tokenValue.toUpperCase()); break; case "lower": output.append(tokenValue.toLowerCase()); break; default: output.append(tokenValue); } } else output.append(tokenValue); } } endOfLastMatch = tokenMatcher.end(); } output.append(input.substring(endOfLastMatch)); return output.toString(); } 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 testFilter() { TokenFilter tokenFilter = new TokenFilter(); tokenFilter.setToken("TOKEN_A", "value-of-a"); tokenFilter.setToken("TOKEN_B", "value-of-b"); tokenFilter.setToken("TOKEN_C", "Value-of-C"); assertEquals( "$${NOPE}hellovalue-of-aworldvalue-of-b${NOT_A_TOKEN}", tokenFilter.filter("$$${NOPE}hello${TOKEN_A}world${TOKEN_B}$${NOT_A_TOKEN}") ); assertEquals( "${NOPE}hellovalue-of-aworld${TOKEN_D}", tokenFilter.filter("${NOPE}hello${TOKEN_A}world${TOKEN_D}") ); assertEquals( "Value-of-C", tokenFilter.filter("${TOKEN_C}") ); assertEquals( "value-of-c", tokenFilter.filter("${TOKEN_C:lower}") ); assertEquals( "VALUE-OF-C", tokenFilter.filter("${TOKEN_C:upper}") ); }
### 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: TokenName { public static String canonicalize(final String name, final String prefix) { Matcher groupMatcher = STRING_NAME_GROUPING.matcher(name); if (!groupMatcher.find()) return prefix + name.toUpperCase(); StringBuilder builder = new StringBuilder(prefix); builder.append(groupMatcher.group(0).toUpperCase()); while (groupMatcher.find()) { builder.append("_"); builder.append(groupMatcher.group(0).toUpperCase()); } return builder.toString(); } private TokenName(); static String canonicalize(final String name, final String prefix); static String canonicalize(final String name); }### Answer: @Test public void testCanonicalize() { assertEquals("A", TokenName.canonicalize("a")); assertEquals("B", TokenName.canonicalize("b")); assertEquals("1", TokenName.canonicalize("1")); assertEquals("SOME_URL", TokenName.canonicalize("someURL")); assertEquals("LOWERCASE_WITH_DASHES", TokenName.canonicalize("lowercase-with-dashes")); assertEquals("HEADLESS_CAMEL_CASE", TokenName.canonicalize("headlessCamelCase")); assertEquals("CAMEL_CASE", TokenName.canonicalize("CamelCase")); assertEquals("CAMEL_CASE", TokenName.canonicalize("CamelCase")); assertEquals("LOWERCASE_WITH_UNDERSCORES", TokenName.canonicalize("lowercase_with_underscores")); assertEquals("UPPERCASE_WITH_UNDERSCORES", TokenName.canonicalize("UPPERCASE_WITH_UNDERSCORES")); assertEquals("A_VERY_INCONSISTENT_MIX_OF_ALL_STYLES", TokenName.canonicalize("aVery-INCONSISTENTMix_ofAllStyles")); assertEquals("ABC_123_DEF_456", TokenName.canonicalize("abc123def456")); assertEquals("ABC_123_DEF_456", TokenName.canonicalize("ABC123DEF456")); assertEquals("WORD_A_WORD_AB_WORD_ABC_WORD", TokenName.canonicalize("WordAWordABWordABCWord")); assertEquals("AUTH_ATTRIBUTE", TokenName.canonicalize("Attribute", "AUTH_")); assertEquals("auth_SOMETHING", TokenName.canonicalize("Something", "auth_")); }
### 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: ReaderGuacamoleReader implements GuacamoleReader { @Override public GuacamoleInstruction readInstruction() throws GuacamoleException { char[] instructionBuffer = read(); if (instructionBuffer == null) return null; int elementStart = 0; Deque<String> elements = new LinkedList<String>(); while (elementStart < instructionBuffer.length) { int lengthEnd = -1; for (int i=elementStart; i<instructionBuffer.length; i++) { if (instructionBuffer[i] == '.') { lengthEnd = i; break; } } if (lengthEnd == -1) throw new GuacamoleServerException("Read returned incomplete instruction."); int length = Integer.parseInt(new String( instructionBuffer, elementStart, lengthEnd - elementStart )); elementStart = lengthEnd + 1; String element = new String( instructionBuffer, elementStart, length ); elements.addLast(element); elementStart += length; char terminator = instructionBuffer[elementStart]; elementStart++; if (terminator == ';') break; } String opcode = elements.removeFirst(); GuacamoleInstruction instruction = new GuacamoleInstruction( opcode, elements.toArray(new String[elements.size()]) ); return instruction; } ReaderGuacamoleReader(Reader input); @Override boolean available(); @Override char[] read(); @Override GuacamoleInstruction readInstruction(); }### Answer: @Test public void testReader() throws GuacamoleException { final String test = "1.a,2.bc,3.def,10.helloworld;4.test,5.test2;0.;3.foo;"; GuacamoleReader reader = new ReaderGuacamoleReader(new StringReader(test)); GuacamoleInstruction instruction; instruction = reader.readInstruction(); assertNotNull(instruction); assertEquals(3, instruction.getArgs().size()); assertEquals("a", instruction.getOpcode()); assertEquals("bc", instruction.getArgs().get(0)); assertEquals("def", instruction.getArgs().get(1)); assertEquals("helloworld", instruction.getArgs().get(2)); instruction = reader.readInstruction(); assertNotNull(instruction); assertEquals(1, instruction.getArgs().size()); assertEquals("test", instruction.getOpcode()); assertEquals("test2", instruction.getArgs().get(0)); instruction = reader.readInstruction(); assertNotNull(instruction); assertEquals(0, instruction.getArgs().size()); assertEquals("", instruction.getOpcode()); instruction = reader.readInstruction(); assertNotNull(instruction); assertEquals(0, instruction.getArgs().size()); assertEquals("foo", instruction.getOpcode()); 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: JsonWebTokenConfig implements AuthenticationConfig { @Override public AuthFilter<?, Principal> createAuthFilter(AuthenticationBootstrap bootstrap) { final byte[] decodedSecretKey = Base64.getDecoder().decode(secretKey); final Key secretKeyKey = new SecretKeySpec(decodedSecretKey, 0, decodedSecretKey.length, this.getSignatureAlgorithm().toString()); return new JsonWebTokenAuthFilter.Builder<>() .setAuthenticator(new JsonWebTokenAuthenticator(secretKeyKey, this.getSignatureAlgorithm())) .setAuthorizer(new PermitAllAuthorizer()) .buildAuthFilter(); } JsonWebTokenConfig(); JsonWebTokenConfig(String secretKey); String getSecretKey(); SignatureAlgorithm getSignatureAlgorithm(); @Override AuthFilter<?, Principal> createAuthFilter(AuthenticationBootstrap bootstrap); }### Answer: @Test public void testCreateAuthFilterReturnsAnAuthFilter() { final String secretKey = TestHelpers.generateBase64SecretKey(); final JsonWebTokenConfig jwtConfig = new JsonWebTokenConfig(secretKey); final AuthenticationBootstrap authBootstrap = TestHelpers.createTypicalAuthBootstrap(); final AuthFilter ret = jwtConfig.createAuthFilter(authBootstrap); assertThat(ret).isNotNull(); } @Test public void testTheReturnedAuthFilterAppliesASecurityContextToAValidRequest() throws IOException { final String secretKey = TestHelpers.generateBase64SecretKey(); final String username = TestHelpers.generateRandomString(); final JsonWebTokenConfig jwtConfig = new JsonWebTokenConfig(secretKey); final AuthenticationBootstrap authBootstrap = TestHelpers.createTypicalAuthBootstrap(); final AuthFilter filter = jwtConfig.createAuthFilter(authBootstrap); final ContainerRequestContext ctx = mock(ContainerRequestContext.class); final String jwt = createJWT(secretKey, username); when(ctx.getHeaderString("Authorization")).thenReturn(String.format("Bearer %s", jwt)); final ArgumentCaptor<SecurityContext> captor = ArgumentCaptor.forClass(SecurityContext.class); filter.filter(ctx); verify(ctx).setSecurityContext(captor.capture()); final SecurityContext capture = captor.getValue(); assertThat(capture.getUserPrincipal().getName()).isEqualTo(username); }
### 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); }