method2testcases
stringlengths 118
3.08k
|
---|
### Question:
ManageInvitationsModelPopulator { public ManageInvitationsViewModel populateManageInvitationsViewModel(long projectId) { ProjectResource project = projectService.getById(projectId); List<SentGrantsInviteResource> grants = grantsInviteRestService.getAllForProject(projectId).getSuccess() .stream().filter(grant -> InviteStatus.SENT == grant.getStatus()) .collect(Collectors.toList()); return new ManageInvitationsViewModel(project.getCompetition(), project.getCompetitionName(), project.getId(), project.getName(), project.getApplication(), grants); } ManageInvitationsViewModel populateManageInvitationsViewModel(long projectId); }### Answer:
@Test public void shouldPopulate() { Long projectId = 5L; ProjectResource project = ProjectResourceBuilder.newProjectResource() .withCompetition(4L) .withCompetitionName("compName") .withId(projectId) .withName("projName") .withApplication(6L).build(); when(projectService.getById(projectId)).thenReturn(project); List<SentGrantsInviteResource> grants = newSentGrantsInviteResource() .withStatus(InviteStatus.SENT, InviteStatus.CREATED, InviteStatus.SENT, InviteStatus.OPENED) .build(4); when(grantsInviteRestService.getAllForProject(projectId)).thenReturn(restSuccess(grants)); ManageInvitationsViewModel result = populator.populateManageInvitationsViewModel(projectId); assertEquals(4L, result.getCompetitionId()); assertEquals("compName", result.getCompetitionName()); assertEquals(projectId, result.getProjectId()); assertEquals("projName", result.getProjectName()); assertEquals(6L, result.getApplicationId()); assertEquals(Arrays.asList(grants.get(0), grants.get(2)), result.getGrants()); } |
### Question:
MonitoringOfficerAssignRoleViewModelPopulator { public MonitoringOfficerAssignRoleViewModel populate(long userId) { UserResource userResource = userRestService.retrieveUserById(userId).getSuccess(); return new MonitoringOfficerAssignRoleViewModel( userId, userResource.getFirstName(), userResource.getLastName(), userResource.getEmail(), userResource.getPhoneNumber()); } MonitoringOfficerAssignRoleViewModelPopulator(); MonitoringOfficerAssignRoleViewModel populate(long userId); }### Answer:
@Test public void populate() { UserResource userResource = newUserResource() .withId(999L) .withEmail("[email protected]") .withFirstName("first") .withLastName("last") .build(); when(userRestService.retrieveUserById(999L)).thenReturn(restSuccess(userResource)); MonitoringOfficerAssignRoleViewModel actual = target.populate(userResource.getId()); assertThat(actual, instanceOf(MonitoringOfficerAssignRoleViewModel.class)); assertThat(actual.getUserId(), is(999L)); assertThat(actual.getEmailAddress(), is("[email protected]")); assertThat(actual.getFirstName(), is("first")); assertThat(actual.getLastName(), is("last")); }
@Test(expected = ObjectNotFoundException.class) public void populateWhenUserNotFound() { long userId = 999L; when(userRestService.retrieveUserById(userId)).thenReturn(restFailure(notFoundError(UserResource.class, userId))); target.populate(userId); } |
### Question:
ActivityLogController { @GetMapping public String viewActivityLog(@PathVariable long projectId, Model model, UserResource user) { model.addAttribute("model", activityLogViewModelPopulator.populate(projectId, user)); return "project/activity-log"; } @GetMapping String viewActivityLog(@PathVariable long projectId,
Model model,
UserResource user); }### Answer:
@Test public void viewActivityLog() throws Exception { long competitionId = 123L; long projectId = 1L; ActivityLogViewModel viewModel = mock(ActivityLogViewModel.class); when(activityLogViewModelPopulator.populate(projectId, getLoggedInUser())).thenReturn(viewModel); mockMvc.perform(get("/competition/{competitionId}/project/{projectId}/activity-log", competitionId, projectId)) .andExpect(view().name("project/activity-log")) .andExpect(model().attribute("model", viewModel)); } |
### Question:
FlywayVersionComparator implements Comparator<List<Integer>> { @Override public int compare(final List<Integer> o1,final List<Integer> o2) { if (o1.isEmpty() && o2.isEmpty()){ return 0; } else if (o1.isEmpty()){ return -1; } else if (o2.isEmpty()) { return 1; } else if (o1.get(0).compareTo(o2.get(0)) == 0) { return compare(o1.subList(1, o1.size()), o2.subList(1, o2.size())); } else { return o1.get(0).compareTo(o2.get(0)); } } @Override int compare(final List<Integer> o1,final List<Integer> o2); }### Answer:
@Test public void testCompareTo(){ final FlywayVersionComparator comparator = new FlywayVersionComparator(); assertEquals(0, comparator.compare(new ArrayList<>(), new ArrayList<>())); assertEquals(1, comparator.compare(asList(10), asList(1))); assertEquals(-1, comparator.compare(asList(1), asList(10))); assertEquals(1, comparator.compare(asList(1, 1), asList(1))); assertEquals(-1, comparator.compare(asList(1), asList(1, 1))); assertEquals(1, comparator.compare(asList(1, 2), asList(1, 1))); assertEquals(0, comparator.compare(asList(1, 2), asList(1, 2))); assertEquals(1, comparator.compare(asList(1, 2, 3, 4, 6), asList(1, 2, 3, 4, 5))); assertEquals(1, comparator.compare(asList(127, 2), asList(127, 1))); assertEquals(1, comparator.compare(asList(128, 2), asList(128, 1))); } |
### Question:
FlywayVersionContentTreeCallback extends AbstractContentTreeCallback { static Pair<String, List<Integer>> versionFromName(final String name) { final List<Integer> version = new ArrayList<>(); final Matcher matcher = FLYWAY_PATCH_PATTERN.matcher(name); if (matcher.find()) { final Matcher major = FLYWAY_MAJOR_PATCH_PATTERN.matcher(name); major.find(); version.add(parseInt(major.group(1))); for (final Matcher minor = FLYWAY_MINOR_PATCH_PATTERN.matcher(name); minor.find(); ) { version.add(parseInt(minor.group(1))); } } return of(name, version); } FlywayVersionContentTreeCallback(final Consumer<List<Pair<String, List<Integer>>>> callBack); @Override boolean onTreeNode(final ContentTreeNode node); @Override void onEnd(final ContentTreeSummary summary); }### Answer:
@Test public void testVersionFromName(){ assertEquals(of("V12_22_1_7__test.sql", asList(12,22,1,7)), versionFromName("V12_22_1_7__test.sql")); assertEquals(of("V12__test.sql", asList(12)), versionFromName("V12__test.sql")); assertEquals(of("V12__test__some_more.sql", asList(12)), versionFromName("V12__test__some_more.sql")); assertEquals(of("12__not_valid.sql", asList()), versionFromName("12__not_valid.sql")); assertEquals(of("V12_22_not_valid.sql", asList()), versionFromName("V12_22_not_valid.sql")); assertEquals(of("V12_22__not_valid.java", asList()), versionFromName("V12_22__not_valid.java")); } |
### Question:
FileFunctions { public static final List<String> pathElementsToAbsolutePathElements(List<String> pathElements, String absolutePathPrefix) { if (pathElements.get(0).startsWith(absolutePathPrefix)) { return pathElements; } String absoluteFirstSegment = absolutePathPrefix + pathElements.get(0); return combineLists(absoluteFirstSegment, pathElements.subList(1, pathElements.size())); } private FileFunctions(); static final String pathElementsToPathString(List<String> pathElements); static final List<String> pathStringToPathElements(final String pathString); static final String pathElementsToAbsolutePathString(List<String> pathElements, String absolutePathPrefix); static final List<String> pathElementsToAbsolutePathElements(List<String> pathElements, String absolutePathPrefix); static final File pathElementsToFile(List<String> pathElements); static final Path pathElementsToPath(List<String> pathElements); }### Answer:
@Test public void testPathElementsToAbsolutePathElements() { List<String> absolutePath = FileFunctions.pathElementsToAbsolutePathElements(asList("path", "to", "file"), "/"); assertEquals(asList("/path", "to", "file"), absolutePath); }
@Test public void testPathElementsToAbsolutePathElementsButAlreadyAbsolute() { List<String> absolutePath = FileFunctions.pathElementsToAbsolutePathElements(asList("/path", "to", "file"), "/"); assertEquals(asList("/path", "to", "file"), absolutePath); } |
### Question:
ApplicationValidatorServiceImpl extends BaseTransactionalService implements ApplicationValidatorService { @Override public FinanceRowHandler getCostHandler(FinanceRowItem costItem) { return financeRowCostsService.getCostHandler(costItem.getId()); } @Override List<BindingResult> validateFormInputResponse(Long applicationId, Long formInputId); @Override ValidationMessages validateFormInputResponse(Application application, long formInputId, long markedAsCompleteById); @Override List<ValidationMessages> validateCostItem(Long applicationId, FinanceRowType type, Long markedAsCompleteById); @Override FinanceRowHandler getCostHandler(FinanceRowItem costItem); @Override FinanceRowHandler getProjectCostHandler(FinanceRowItem costItem); @Override ValidationMessages validateAcademicUpload(Application application, Long markedAsCompleteById); @Override Boolean isApplicationComplete(Application application); @Override Boolean isFinanceOverviewComplete(Application application); }### Answer:
@Test public void getCostHandler() { TravelCost travelCost = new TravelCost(1L, "transport", new BigDecimal("25.00"), 5, 1L); FinanceRowHandler expected = new TravelCostHandler(); when(financeRowCostsService.getCostHandler(1L)).thenReturn(expected); FinanceRowHandler result = service.getCostHandler(travelCost); assertEquals(expected, result); verify(financeRowCostsService, only()).getCostHandler(1L); } |
### Question:
ApplicationValidatorServiceImpl extends BaseTransactionalService implements ApplicationValidatorService { @Override public FinanceRowHandler getProjectCostHandler(FinanceRowItem costItem) { return projectFinanceRowService.getCostHandler(costItem); } @Override List<BindingResult> validateFormInputResponse(Long applicationId, Long formInputId); @Override ValidationMessages validateFormInputResponse(Application application, long formInputId, long markedAsCompleteById); @Override List<ValidationMessages> validateCostItem(Long applicationId, FinanceRowType type, Long markedAsCompleteById); @Override FinanceRowHandler getCostHandler(FinanceRowItem costItem); @Override FinanceRowHandler getProjectCostHandler(FinanceRowItem costItem); @Override ValidationMessages validateAcademicUpload(Application application, Long markedAsCompleteById); @Override Boolean isApplicationComplete(Application application); @Override Boolean isFinanceOverviewComplete(Application application); }### Answer:
@Test public void getProjectCostHandler() { GrantClaimPercentage grantClaim = new GrantClaimPercentage(1L, BigDecimal.valueOf(20), 1L); FinanceRowHandler expected = new GrantClaimPercentageHandler(); when(projectFinanceRowService.getCostHandler(grantClaim)).thenReturn(expected); FinanceRowHandler result = service.getProjectCostHandler(grantClaim); assertEquals(expected, result); verify(projectFinanceRowService, only()).getCostHandler(grantClaim); } |
### Question:
QuestionSetupController { @GetMapping("/get-statuses/{competitionId}/{parentSection}") public RestResult<Map<Long, Boolean>> getQuestionStatuses(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection){ return questionSetupService.getQuestionStatuses(competitionId, parentSection).toGetResponse(); } @PutMapping("/mark-as-complete/{competitionId}/{parentSection}/{questionId}") RestResult<Void> markQuestionSetupAsComplete(@PathVariable("competitionId") final Long competitionId,
@PathVariable("parentSection") final CompetitionSetupSection parentSection,
@PathVariable("questionId") final Long questionId); @PutMapping("/mark-as-incomplete/{competitionId}/{parentSection}/{questionId}") RestResult<Void> markQuestionSetupAsInComplete(@PathVariable("competitionId") final Long competitionId,
@PathVariable("parentSection") final CompetitionSetupSection parentSection,
@PathVariable("questionId") final Long questionId); @GetMapping("/get-statuses/{competitionId}/{parentSection}") RestResult<Map<Long, Boolean>> getQuestionStatuses(@PathVariable("competitionId") final Long competitionId,
@PathVariable("parentSection") final CompetitionSetupSection parentSection); }### Answer:
@Test public void testGetQuestionStatuses() throws Exception { final Long competitionId = 24L; final CompetitionSetupSection parentSection = CompetitionSetupSection.APPLICATION_FORM; final Map<Long, Boolean> resultMap = asMap(1L, Boolean.FALSE); when(questionSetupService.getQuestionStatuses(competitionId, parentSection)).thenReturn(serviceSuccess(resultMap)); mockMvc.perform(get(BASE_URL + "/get-statuses/{competitionId}/{parentSection}", competitionId, parentSection)) .andExpect(status().isOk()) .andExpect(content().string(objectMapper.writeValueAsString(resultMap))); verify(questionSetupService, only()).getQuestionStatuses(competitionId, parentSection); } |
### Question:
ApplicationAssessmentSummaryController { @GetMapping("/{applicationId}") public RestResult<ApplicationAssessmentSummaryResource> getApplicationAssessmentSummary(@PathVariable long applicationId) { return applicationAssessmentSummaryService.getApplicationAssessmentSummary(applicationId).toGetResponse(); } @GetMapping("/{applicationId}/assigned-assessors") RestResult<List<ApplicationAssessorResource>> getAssignedAssessors(@PathVariable long applicationId); @GetMapping("/{applicationId}/available-assessors") RestResult<ApplicationAvailableAssessorPageResource> getAvailableAssessors(@PathVariable long applicationId,
@RequestParam(value = "page", defaultValue = "0") int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize,
@RequestParam(value = "assessorNameFilter", required = false) String assessorNameFilter,
@RequestParam(value = "sort", required = false, defaultValue = "ASSESSOR") ApplicationAvailableAssessorResource.Sort sort); @GetMapping("/{applicationId}/available-assessors-ids") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long applicationId,
@RequestParam(value = "assessorNameFilter", required = false) String assessorNameFilter); @GetMapping("/{applicationId}") RestResult<ApplicationAssessmentSummaryResource> getApplicationAssessmentSummary(@PathVariable long applicationId); }### Answer:
@Test public void getApplicationAssessmentSummary() throws Exception { ApplicationAssessmentSummaryResource expected = newApplicationAssessmentSummaryResource() .build(); Long applicationId = 1L; when(applicationAssessmentSummaryServiceMock.getApplicationAssessmentSummary(applicationId)).thenReturn(serviceSuccess(expected)); mockMvc.perform(get("/application-assessment-summary/{id}", applicationId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(expected))); verify(applicationAssessmentSummaryServiceMock, only()).getApplicationAssessmentSummary(applicationId); } |
### Question:
ApplicationInnovationAreaController { @PostMapping("/innovation-area/{applicationId}") public RestResult<ApplicationResource> setInnovationArea(@PathVariable("applicationId") final Long applicationId, @RequestBody Long innovationAreaId) { return applicationInnovationAreaService.setInnovationArea(applicationId, innovationAreaId).toGetResponse(); } @PostMapping("/innovation-area/{applicationId}") RestResult<ApplicationResource> setInnovationArea(@PathVariable("applicationId") final Long applicationId, @RequestBody Long innovationAreaId); @PostMapping("/no-innovation-area-applicable/{applicationId}") RestResult<ApplicationResource> setNoInnovationAreaApplies(@PathVariable("applicationId") final Long applicationId); @GetMapping("/available-innovation-areas/{applicationId}") RestResult<List<InnovationAreaResource>> getAvailableInnovationAreas(@PathVariable("applicationId") final Long applicationId); }### Answer:
@Test public void setInnovationArea() throws Exception { Long innovationAreaId = 1L; Long applicationId = 1L; when(applicationInnovationAreaServiceMock.setInnovationArea(applicationId, innovationAreaId)).thenReturn(serviceSuccess(newApplicationResource().build())); mockMvc.perform(post("/application-innovation-area/innovation-area/"+applicationId) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(innovationAreaId))) .andExpect(status().isOk()); } |
### Question:
ApplicationInnovationAreaController { @PostMapping("/no-innovation-area-applicable/{applicationId}") public RestResult<ApplicationResource> setNoInnovationAreaApplies(@PathVariable("applicationId") final Long applicationId) { return applicationInnovationAreaService.setNoInnovationAreaApplies(applicationId).toGetResponse(); } @PostMapping("/innovation-area/{applicationId}") RestResult<ApplicationResource> setInnovationArea(@PathVariable("applicationId") final Long applicationId, @RequestBody Long innovationAreaId); @PostMapping("/no-innovation-area-applicable/{applicationId}") RestResult<ApplicationResource> setNoInnovationAreaApplies(@PathVariable("applicationId") final Long applicationId); @GetMapping("/available-innovation-areas/{applicationId}") RestResult<List<InnovationAreaResource>> getAvailableInnovationAreas(@PathVariable("applicationId") final Long applicationId); }### Answer:
@Test public void setNoInnovationAreaApplies() throws Exception { Long applicationId = 1L; when(applicationInnovationAreaServiceMock.setNoInnovationAreaApplies(applicationId)).thenReturn(serviceSuccess(newApplicationResource().build())); mockMvc.perform(post("/application-innovation-area/no-innovation-area-applicable/"+applicationId) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } |
### Question:
ApplicationInnovationAreaController { @GetMapping("/available-innovation-areas/{applicationId}") public RestResult<List<InnovationAreaResource>> getAvailableInnovationAreas(@PathVariable("applicationId") final Long applicationId) { return applicationInnovationAreaService.getAvailableInnovationAreas(applicationId).toGetResponse(); } @PostMapping("/innovation-area/{applicationId}") RestResult<ApplicationResource> setInnovationArea(@PathVariable("applicationId") final Long applicationId, @RequestBody Long innovationAreaId); @PostMapping("/no-innovation-area-applicable/{applicationId}") RestResult<ApplicationResource> setNoInnovationAreaApplies(@PathVariable("applicationId") final Long applicationId); @GetMapping("/available-innovation-areas/{applicationId}") RestResult<List<InnovationAreaResource>> getAvailableInnovationAreas(@PathVariable("applicationId") final Long applicationId); }### Answer:
@Test public void getAvailableInnovationAreas() throws Exception { Long applicationId = 1L; when(applicationInnovationAreaServiceMock.getAvailableInnovationAreas(applicationId)).thenReturn(serviceSuccess(newInnovationAreaResource().build(5))); mockMvc.perform(get("/application-innovation-area/available-innovation-areas/"+applicationId) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } |
### Question:
NotEmptyValidator extends BaseValidator { @Override public void validate(Object target, Errors errors) { LOG.debug("do NotEmpty validation "); FormInputResponse response = (FormInputResponse) target; if (StringUtils.isEmpty(response.getValue()) || "".equals(response.getValue().trim())) { LOG.debug("NotEmpty validation message for: " + response.getId()); rejectValue(errors, "value", "validation.field.please.enter.some.text"); } } @Override void validate(Object target, Errors errors); }### Answer:
@Test public void testInvalidEmpty() { formInputResponse.setValue(""); validator.validate(formInputResponse, bindingResult); assertTrue(bindingResult.hasErrors()); }
@Test public void testInvalidNull() { formInputResponse.setValue(null); validator.validate(formInputResponse, bindingResult); assertTrue(bindingResult.hasErrors()); }
@Test public void testInvalidWhiteSpace() { formInputResponse.setValue(" "); validator.validate(formInputResponse, bindingResult); assertTrue(bindingResult.hasErrors()); }
@Test public void testValid() { formInputResponse.setValue("asdf"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); }
@Test public void testValidSingleChar() { formInputResponse.setValue("a"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); }
@Test public void testValidNotAlpha() { formInputResponse.setValue("-"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); } |
### Question:
SignedLongIntegerValidator extends IntegerValidator { @Override protected void validate(BigDecimal bd, Errors errors) { } }### Answer:
@Test public void testDecimal() { formInputResponse.setValue("1.1"); validator.validate(formInputResponse, bindingResult); assertTrue(bindingResult.hasErrors()); assertEquals(1, bindingResult.getAllErrors().size()); assertEquals("validation.standard.integer.non.decimal.format", bindingResult.getAllErrors().get(0).getDefaultMessage()); }
@Test public void testGreaterThanMAX_VALUE() { String greaterThanMaxValue = Long.MAX_VALUE + "1"; formInputResponse.setValue(greaterThanMaxValue); validator.validate(formInputResponse, bindingResult); assertTrue(bindingResult.hasErrors()); assertEquals(1, bindingResult.getAllErrors().size()); assertEquals("validation.standard.integer.max.value.format", bindingResult.getAllErrors().get(0).getDefaultMessage()); }
@Test public void testMultipleFailures() { String multipleFailures = Long.MAX_VALUE + ".1"; formInputResponse.setValue(multipleFailures); validator.validate(formInputResponse, bindingResult); assertEquals(2, bindingResult.getAllErrors().size()); assertEquals("validation.standard.integer.non.decimal.format", bindingResult.getAllErrors().get(0).getDefaultMessage()); assertEquals("validation.standard.integer.max.value.format", bindingResult.getAllErrors().get(1).getDefaultMessage()); }
@Test public void testZero() { formInputResponse.setValue("0"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); }
@Test public void testValid() { formInputResponse.setValue("10000"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); } |
### Question:
ApplicationResearchMarkAsCompleteValidator implements Validator { @Override public void validate(Object target, Errors errors) { LOG.debug("do ApplicationResearchMarkAsComplete Validation"); Application application = (Application) target; if (application.getResearchCategory() == null) { LOG.debug("MarkAsComplete application validation message for research category is null"); rejectValue(errors, "researchCategory", "validation.application.research.category.required"); } } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); }### Answer:
@Test public void validate() { Application application = ApplicationBuilder .newApplication() .withResearchCategory(newResearchCategory().build()) .build(); DataBinder binder = new DataBinder(application); BindingResult bindingResult = binder.getBindingResult(); validator.validate(application, bindingResult); assertFalse(bindingResult.hasErrors()); }
@Test public void validate_nullResearchCategory() { Application application = ApplicationBuilder .newApplication() .withResearchCategory((ResearchCategory) null) .build(); DataBinder binder = new DataBinder(application); BindingResult bindingResult = binder.getBindingResult(); validator.validate(application, bindingResult); assertTrue(bindingResult.hasErrors()); assertEquals(bindingResult.getFieldError("researchCategory").getDefaultMessage(), "validation.application.research.category.required"); } |
### Question:
RequiredMultipleChoiceValidator extends BaseValidator { @Override public void validate(Object target, Errors errors) { FormInputResponse response = (FormInputResponse) target; if (response.getMultipleChoiceOption() == null) { rejectValue(errors, "value", "validation.multiple.choice.required"); return; } Optional<MultipleChoiceOption> option = multipleChoiceOptionRepository.findById(Long.valueOf(response.getMultipleChoiceOption().getId())); if (!(option.isPresent() && option.get().getFormInput().getId().equals(response.getFormInput().getId()))) { rejectValue(errors, "value", "validation.multiple.choice.invalid"); } } @Override void validate(Object target, Errors errors); }### Answer:
@Test public void valid() { MultipleChoiceOption multipleChoiceOption =newMultipleChoiceOption() .withId(1L) .withText("Yes") .withFormInput(formInputResponse.getFormInput()).build(); formInputResponse.setMultipleChoiceOption(multipleChoiceOption); when(multipleChoiceOptionRepository.findById(1L)).thenReturn(Optional.of(multipleChoiceOption)); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); }
@Test public void missingValue() { formInputResponse.setMultipleChoiceOption(null); validator.validate(formInputResponse, bindingResult); assertTrue(bindingResult.hasErrors()); }
@Test public void missingOption() { MultipleChoiceOption multipleChoiceOption =newMultipleChoiceOption() .withId(5L) .withText("No") .withFormInput(formInputResponse.getFormInput()).build(); formInputResponse.setMultipleChoiceOption(multipleChoiceOption); when(multipleChoiceOptionRepository.findById(5L)).thenReturn(Optional.empty()); validator.validate(formInputResponse, bindingResult); assertTrue(bindingResult.hasErrors()); } |
### Question:
NonNegativeLongIntegerValidator extends IntegerValidator { @Override protected void validate(BigDecimal value, Errors errors) { if (ZERO.compareTo(value) > 0){ rejectValue(errors, "value", "validation.standard.non.negative.integer.non.negative.format"); } } }### Answer:
@Test public void testNegativeNumber() { formInputResponse.setValue("-1"); validator.validate(formInputResponse, bindingResult); assertTrue(bindingResult.hasErrors()); assertEquals(1, bindingResult.getAllErrors().size()); assertEquals("validation.standard.non.negative.integer.non.negative.format", bindingResult.getAllErrors().get(0).getDefaultMessage()); } |
### Question:
EmailValidator extends BaseValidator { @Override public void validate(Object target, Errors errors) { LOG.debug("do Email validation "); FormInputResponse response = (FormInputResponse) target; CharSequence responseValue = response.getValue(); org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator externalEmailValidator = new org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator(); if (!externalEmailValidator.isValid(responseValue, null)) { rejectValue(errors, "value", "validation.standard.email.format"); } } @Override void validate(Object target, Errors errors); }### Answer:
@Test public void testInvalidNoDomainBeforeExtension() { formInputResponse.setValue("[email protected]"); validator.validate(formInputResponse, bindingResult); assertTrue(bindingResult.hasErrors()); }
@Test public void testValidNoDomainExtension() { formInputResponse.setValue("info@company"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); }
@Test public void testValidShortDomain() { formInputResponse.setValue("[email protected]"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); }
@Test public void testValidWithSubdomain() throws Exception { formInputResponse.setValue("[email protected]"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); }
@Test public void testValid() throws Exception { formInputResponse.setValue("[email protected]"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); }
@Test public void testValidLongAddress() throws Exception { formInputResponse.setValue("[email protected]"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); } |
### Question:
ApplicationDetailsMarkAsCompleteValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Application.class.isAssignableFrom(clazz); } @Override boolean supports(Class<?> clazz); @Override void validate(Object target, Errors errors); }### Answer:
@Test public void supportsApplicationAndSubclasses() { assertTrue(validator.supports(Application.class)); assertTrue(validator.supports(new Application() { }.getClass())); } |
### Question:
AutoCompleteSectionsAction extends BaseApplicationAction { @Override protected void doExecute(final Application application, final StateContext<ApplicationState, ApplicationEvent> context) { autoCompleteSectionsUtil.intitialiseCompleteSectionsForOrganisation(application , application.getLeadOrganisationId(), application.getLeadApplicantProcessRole().getId()); } }### Answer:
@Test public void doExecute() { ProcessRole processRole = newProcessRole().withRole(Role.LEADAPPLICANT).withOrganisationId(1L).build(); Application application = newApplication() .withCompetition(newCompetition() .withCompetitionType(newCompetitionType().withName("Expression of interest").build()) .build()) .withProcessRole(processRole) .build(); StateContext<ApplicationState, ApplicationEvent> stateContext = mock(StateContext.class); autoCompleteSectionsAction.doExecute(application, stateContext); verify(autoCompleteSectionsUtil).intitialiseCompleteSectionsForOrganisation(application, processRole.getOrganisationId(), processRole.getId()); } |
### Question:
SendFinanceTotalsAction extends BaseApplicationAction { @Override protected void doExecute(final Application application, final StateContext<ApplicationState, ApplicationEvent> context) { if(financeTotalsEnabled) { LOG.info("Calling totals sender for applicationId: {}", application.getId()); applicationFinanceTotalsSender.sendFinanceTotalsForApplication(application.getId()); } else { LOG.info("Not calling totals sender for applicationId: {}", application.getId()); } } }### Answer:
@Test public void doExecute_toggleOn() { setFinanceTotalsToggle(true); Application application = newApplication().build(); sendFinanceTotalsAction.doExecute(application, null); verify(financeTotalsSender).sendFinanceTotalsForApplication(application.getId()); }
@Test public void doExecute_toggleOff() { setFinanceTotalsToggle(false); Application application = newApplication().build(); sendFinanceTotalsAction.doExecute(application, null); verifyNoMoreInteractions(financeTotalsSender); } |
### Question:
AutoCompleteSectionsUtil { public void intitialiseCompleteSectionsForOrganisation(Application application, long organisationId, long processRoleId) { Competition competition = application.getCompetition(); OrganisationResource lead = organisationService.findById(organisationId).getSuccess(); competition.getSections().stream() .filter(section -> section.getType().isSectionTypeNotRequiredForOrganisationAndCompetition(competition, lead.getOrganisationTypeEnum(), application.getLeadOrganisationId().equals(organisationId))) .forEach(section -> sectionStatusService.markSectionAsNotRequired(section.getId(), application.getId(), processRoleId)); } void intitialiseCompleteSectionsForOrganisation(Application application, long organisationId, long processRoleId); }### Answer:
@Test public void intitialiseCompleteSectionsForOrganisation() { SectionType type = mock(SectionType.class); Section section = newSection().withSectionType(type).build(); Competition competition = newCompetition() .withSections(newArrayList(section)) .build(); OrganisationResource organisation = newOrganisationResource() .withOrganisationType(OrganisationTypeEnum.BUSINESS.getId()) .build(); Application application = newApplication() .withCompetition(competition) .withProcessRoles(newProcessRole().withRole(Role.LEADAPPLICANT).withOrganisationId(organisation.getId()).build()) .build(); long processRoleId = 2L; when(type.isSectionTypeNotRequiredForOrganisationAndCompetition(competition, OrganisationTypeEnum.BUSINESS, true)).thenReturn(true); when(sectionStatusService.markSectionAsNotRequired(section.getId(), application.getId(), processRoleId)).thenReturn(serviceSuccess()); when(organisationService.findById(organisation.getId())).thenReturn(serviceSuccess(organisation)); util.intitialiseCompleteSectionsForOrganisation(application, organisation.getId(), processRoleId); verify(sectionStatusService).markSectionAsNotRequired(section.getId(), application.getId(), processRoleId); } |
### Question:
ApplicationOrganisationAddressServiceImpl extends BaseTransactionalService implements ApplicationOrganisationAddressService { @Override public ServiceResult<AddressResource> getAddress(long applicationId, long organisationId, OrganisationAddressType type) { return find(applicationOrganisationAddressRepository.findByApplicationIdAndOrganisationAddressOrganisationIdAndOrganisationAddressAddressTypeId(applicationId, organisationId, type.getId()), notFoundError(ApplicationOrganisationAddress.class, applicationId, organisationId, type)) .andOnSuccessReturn(applicationOrganisationAddress -> addressMapper.mapToResource(applicationOrganisationAddress.getOrganisationAddress().getAddress())); } @Override ServiceResult<AddressResource> getAddress(long applicationId, long organisationId, OrganisationAddressType type); @Override @Transactional ServiceResult<AddressResource> updateAddress(long applicationId, long organisationId, OrganisationAddressType type, AddressResource address); }### Answer:
@Test public void getAddress() { long applicationId = 1L; long organisationId = 2L; OrganisationAddressType type = OrganisationAddressType.INTERNATIONAL; Address address = newAddress().build(); ApplicationOrganisationAddress applicationOrganisationAddress = new ApplicationOrganisationAddress( newOrganisationAddress().withAddress(address).build(), newApplication().build() ); AddressResource addressResource = newAddressResource().build(); when(applicationOrganisationAddressRepository.findByApplicationIdAndOrganisationAddressOrganisationIdAndOrganisationAddressAddressTypeId(applicationId, organisationId, type.getId())) .thenReturn(Optional.of(applicationOrganisationAddress)); when(addressMapper.mapToResource(address)).thenReturn(addressResource); ServiceResult<AddressResource> result = service.getAddress(applicationId, organisationId, type); assertEquals(result.getSuccess(), addressResource); } |
### Question:
ApplicationOrganisationAddressServiceImpl extends BaseTransactionalService implements ApplicationOrganisationAddressService { @Override @Transactional public ServiceResult<AddressResource> updateAddress(long applicationId, long organisationId, OrganisationAddressType type, AddressResource address) { return find(applicationOrganisationAddressRepository.findByApplicationIdAndOrganisationAddressOrganisationIdAndOrganisationAddressAddressTypeId(applicationId, organisationId, type.getId()), notFoundError(ApplicationOrganisationAddress.class, applicationId, organisationId, type)) .andOnSuccessReturn(applicationOrganisationAddress -> { applicationOrganisationAddress.getOrganisationAddress().getAddress().copyFrom(address); applicationOrganisationAddress.getOrganisationAddress().setModifiedOn(ZonedDateTime.now()); return addressMapper.mapToResource(applicationOrganisationAddress.getOrganisationAddress().getAddress()); }); } @Override ServiceResult<AddressResource> getAddress(long applicationId, long organisationId, OrganisationAddressType type); @Override @Transactional ServiceResult<AddressResource> updateAddress(long applicationId, long organisationId, OrganisationAddressType type, AddressResource address); }### Answer:
@Test public void updateAddress() { long applicationId = 1L; long organisationId = 2L; OrganisationAddressType type = OrganisationAddressType.INTERNATIONAL; AddressResource addressResource = newAddressResource().build(); Address address = mock(Address.class); ApplicationOrganisationAddress applicationOrganisationAddress = new ApplicationOrganisationAddress( newOrganisationAddress().withAddress(address).build(), newApplication().build() ); when(applicationOrganisationAddressRepository.findByApplicationIdAndOrganisationAddressOrganisationIdAndOrganisationAddressAddressTypeId(applicationId, organisationId, type.getId())) .thenReturn(Optional.of(applicationOrganisationAddress)); when(addressMapper.mapToResource(address)).thenReturn(addressResource); ServiceResult<AddressResource> result = service.updateAddress(applicationId, organisationId, type, addressResource); assertEquals(result.getSuccess(), addressResource); verify(address).copyFrom(addressResource); } |
### Question:
ApplicationCountSummaryServiceImpl extends BaseTransactionalService implements ApplicationCountSummaryService { @Override public ServiceResult<List<Long>> getApplicationIdsByCompetitionIdAndAssessorId(long competitionId, long assessorId, String filter) { return serviceSuccess(applicationStatisticsRepository.findApplicationIdsNotAssignedTo(competitionId, assessorId, filter)); } @Override ServiceResult<ApplicationCountSummaryPageResource> getApplicationCountSummariesByCompetitionId(long competitionId,
int pageIndex,
int pageSize,
Optional<String> filter); @Override ServiceResult<ApplicationCountSummaryPageResource> getApplicationCountSummariesByCompetitionIdAndAssessorId(
long competitionId,
long assessorId,
int page,
int size,
ApplicationCountSummaryResource.Sort sort,
String filter); @Override ServiceResult<List<Long>> getApplicationIdsByCompetitionIdAndAssessorId(long competitionId, long assessorId, String filter); }### Answer:
@Test public void getApplicationIdsByCompetitionIdAndAssessorId() { List<Long> list = asList(1L, 2L); when(applicationStatisticsRepository.findApplicationIdsNotAssignedTo(eq(competitionId), eq(1L), eq("asd"))).thenReturn(list); ServiceResult<List<Long>> result = service.getApplicationIdsByCompetitionIdAndAssessorId(competitionId, 1L, "asd"); assertTrue(result.isSuccess()); } |
### Question:
ApplicationDeletionServiceImpl extends RootTransactionalService implements ApplicationDeletionService { @Override @Transactional public ServiceResult<Void> hideApplicationFromDashboard(ApplicationUserCompositeId id) { return getApplication(id.getApplicationId()).andOnSuccessReturnVoid((application) -> getUser(id.getUserId()).andOnSuccessReturnVoid(user -> applicationHiddenFromDashboardRepository.save(new ApplicationHiddenFromDashboard(application, user)))); } @Override @Transactional ServiceResult<Void> deleteApplication(long applicationId); @Override @Transactional ServiceResult<Void> hideApplicationFromDashboard(ApplicationUserCompositeId id); }### Answer:
@Test public void hideApplicationFromDashboard() { long applicationId = 1L; long userId = 2L; Application application = newApplication() .build(); User user = new User(); when(applicationRepository.findById(applicationId)).thenReturn(Optional.of(application)); when(userRepository.findById(userId)).thenReturn(Optional.of(user)); ServiceResult<Void> result = service.hideApplicationFromDashboard(ApplicationUserCompositeId.id(applicationId, userId)); verify(applicationHiddenFromDashboardRepository).save(any()); } |
### Question:
ApplicationAssessmentSummaryServiceImpl extends BaseTransactionalService implements ApplicationAssessmentSummaryService { @Override public ServiceResult<List<Long>> getAvailableAssessorIds(long applicationId, String assessorNameFilter) { return find(applicationRepository.findById(applicationId), notFoundError(Application.class, applicationId)).andOnSuccessReturn(application -> assessmentParticipantRepository.findAvailableAssessorIdsForApplication( application.getCompetition().getId(), applicationId, EncodingUtils.urlDecode(assessorNameFilter) ) ); } @Override ServiceResult<ApplicationAvailableAssessorPageResource> getAvailableAssessors(long applicationId, int pageIndex, int pageSize, String assessorNameFilter, ApplicationAvailableAssessorResource.Sort sort); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long applicationId, String assessorNameFilter); @Override ServiceResult<List<ApplicationAssessorResource>> getAssignedAssessors(long applicationId); @Override ServiceResult<ApplicationAssessmentSummaryResource> getApplicationAssessmentSummary(long applicationId); }### Answer:
@Test public void getAvailableAssessorIds() { long applicationId = 1L; long competitionId = 2L; String filter = "Filter"; List<Long> expectedIds = asList(1L, 2L); when(applicationRepositoryMock.findById(applicationId)).thenReturn(of(newApplication().withCompetition(newCompetition().withId(competitionId).build()).build())); when(assessmentParticipantRepositoryMock.findAvailableAssessorIdsForApplication(competitionId, applicationId, filter)).thenReturn(expectedIds); List<Long> ids = service.getAvailableAssessorIds(applicationId, filter).getSuccess(); assertEquals(ids, expectedIds); } |
### Question:
ApplicationInnovationAreaServiceImpl extends BaseTransactionalService implements ApplicationInnovationAreaService { @Override @Transactional public ServiceResult<ApplicationResource> setNoInnovationAreaApplies(Long applicationId) { return find(application(applicationId)).andOnSuccess(this::saveWithNoInnovationAreaApplies) .andOnSuccess(application -> serviceSuccess(applicationMapper.mapToResource(application))); } @Override @Transactional ServiceResult<ApplicationResource> setInnovationArea(Long applicationId, Long innovationAreaId); @Override @Transactional ServiceResult<ApplicationResource> setNoInnovationAreaApplies(Long applicationId); @Override ServiceResult<List<InnovationAreaResource>> getAvailableInnovationAreas(Long applicationId); }### Answer:
@Test public void setApplicationNoInnovationAreaApplies() throws Exception { Long applicationId = 1L; Application application = newApplication().withId(applicationId).build(); Application expectedApplication = newApplication().withId(applicationId).withNoInnovationAreaApplicable(true).build(); ApplicationResource expectedApplicationResource = newApplicationResource().withId(applicationId).withNoInnovationAreaApplicable(true).build(); when(applicationRepositoryMock.findById(applicationId)).thenReturn(Optional.of(application)); when(applicationRepositoryMock.save(any(Application.class))).thenReturn(expectedApplication); when(applicationMapperMock.mapToResource(expectedApplication)).thenReturn(expectedApplicationResource); ServiceResult<ApplicationResource> result = service.setNoInnovationAreaApplies(applicationId); assertTrue(result.isSuccess()); assertNull(result.getSuccess().getInnovationArea()); assertEquals(true, result.getSuccess().getNoInnovationAreaApplicable()); verify(applicationRepositoryMock, times(1)).save(any(Application.class)); } |
### Question:
FlatFolderFileStorageStrategy extends BaseFileStorageStrategy { @Override public Pair<List<String>, String> getAbsoluteFilePathAndName(Long fileEntryId) { return Pair.of(getAbsolutePathToFileUploadFolder(), fileEntryId + ""); } FlatFolderFileStorageStrategy(String pathToStorageBase, String containingFolder); @Override Pair<List<String>, String> getAbsoluteFilePathAndName(Long fileEntryId); @Override List<Pair<List<String>, String>> all(); @Override ServiceResult<Long> fileEntryIdFromPath(Pair<List<String>, String> path); }### Answer:
@Test public void testGetAbsoluteFilePathAndName() { FlatFolderFileStorageStrategy strategy = new FlatFolderFileStorageStrategy(tempFolderPathAsString, "BaseFolder"); FileEntry fileEntry = newFileEntry().with(id(123L)).build(); assertEquals(tempFolderPathSegmentsWithBaseFolder, strategy.getAbsoluteFilePathAndName(fileEntry).getKey()); assertEquals("123", strategy.getAbsoluteFilePathAndName(fileEntry).getValue()); } |
### Question:
FormInputResponse { @JsonIgnore public Integer getWordCountLeft() { return formInput.getWordCount() - this.getWordCount(); } FormInputResponse(); FormInputResponse(ZonedDateTime updateDate, String value, ProcessRole updatedBy, FormInput formInput, Application application); FormInputResponse(ZonedDateTime updateDate, List<FileEntry> fileEntries, ProcessRole updatedBy, FormInput formInput, Application application); FormInputResponse(ZonedDateTime updateDate, MultipleChoiceOption multipleChoiceOption, ProcessRole updatedBy, FormInput formInput, Application application); Long getId(); ZonedDateTime getUpdateDate(); String getValue(); @JsonIgnore Integer getWordCount(); @JsonIgnore Integer getWordCountLeft(); FormInput getFormInput(); void setValue(String value); void setUpdateDate(ZonedDateTime updateDate); void setFormInput(FormInput formInput); ProcessRole getUpdatedBy(); void setUpdatedBy(ProcessRole updatedBy); @JsonIgnore Application getApplication(); void setApplication(Application application); MultipleChoiceOption getMultipleChoiceOption(); void setMultipleChoiceOption(MultipleChoiceOption multipleChoiceOption); List<FileEntry> getFileEntries(); void setFileEntries(List<FileEntry> fileEntries); void addFileEntry(FileEntry fileEntry); }### Answer:
@Test public void testGetWordCountLeft() throws Exception { } |
### Question:
ApplicationStatistics { public int getAssessors() { return assessments.stream().filter(a -> ASSESSOR_STATES.contains(a.getProcessState())).mapToInt(e -> 1).sum(); } Long getId(); String getName(); Long getCompetition(); ApplicationState getApplicationState(); Long getLeadOrganisationId(); List<ProcessRole> getProcessRoles(); List<Assessment> getAssessments(); int getAssessors(); int getAccepted(); int getSubmitted(); }### Answer:
@Test public void assessorCount() { int expectedCount = EnumSet.of(CREATED, PENDING, ACCEPTED, OPEN, DECIDE_IF_READY_TO_SUBMIT, READY_TO_SUBMIT, SUBMITTED).size(); assertEquals(expectedCount, applicationStatistics.getAssessors()); } |
### Question:
ApplicationStatistics { public int getAccepted() { return assessments.stream().filter(a -> ACCEPTED_STATES.contains(a.getProcessState())).mapToInt(e -> 1).sum(); } Long getId(); String getName(); Long getCompetition(); ApplicationState getApplicationState(); Long getLeadOrganisationId(); List<ProcessRole> getProcessRoles(); List<Assessment> getAssessments(); int getAssessors(); int getAccepted(); int getSubmitted(); }### Answer:
@Test public void acceptedCount() { int expectedCount = EnumSet.of(ACCEPTED, OPEN, DECIDE_IF_READY_TO_SUBMIT, READY_TO_SUBMIT, SUBMITTED).size(); assertEquals(expectedCount, applicationStatistics.getAccepted()); } |
### Question:
ApplicationStatistics { public int getSubmitted() { return assessments.stream().filter(a -> a.isInState(SUBMITTED)).mapToInt(e -> 1).sum(); } Long getId(); String getName(); Long getCompetition(); ApplicationState getApplicationState(); Long getLeadOrganisationId(); List<ProcessRole> getProcessRoles(); List<Assessment> getAssessments(); int getAssessors(); int getAccepted(); int getSubmitted(); }### Answer:
@Test public void submittedCount() { int expectedCount = EnumSet.of(SUBMITTED).size(); assertEquals(expectedCount, applicationStatistics.getSubmitted()); } |
### Question:
FileStorageHealthIndicator implements HealthIndicator { @Override public Health health() { LOG.debug("checking filesystem health"); if (allowCreateStoragePath) { createStoragePathIfNotExist(fileStoragePath); } return createStatus(fileStoragePath).build(); } void setFileOperationsWrapper(FileOperationsWrapper fileOperationsWrapper); void setFileStoragePath(String fileStoragePath); void setAllowCreateStoragePath(boolean allowCreateStoragePath); @Override Health health(); }### Answer:
@Test public void shouldReportHealthy() { when(fileOperationsWrapper.isWritable("files")).thenReturn(true); Health result = indicator.health(); assertThat(result.getStatus()).isEqualTo(Status.UP); }
@Test public void shouldReportUnhealthy() { when(fileOperationsWrapper.isWritable("files")).thenReturn(false); Health result = indicator.health(); assertThat(result.getStatus()).isEqualTo(Status.DOWN); } |
### Question:
ByFileIdFileStorageStrategy extends BaseFileStorageStrategy { @Override public Pair<List<String>, String> getAbsoluteFilePathAndName(Long fileEntryId) { return getFilePathAndName(fileEntryId); } @Autowired ByFileIdFileStorageStrategy(String pathToStorageBase, String containingFolder); @Override Pair<List<String>, String> getAbsoluteFilePathAndName(Long fileEntryId); @Override List<Pair<List<String>, String>> all(); @Override ServiceResult<Long> fileEntryIdFromPath(Pair<List<String>, String> path); }### Answer:
@Test public void testGetAbsoluteFilePathAndName() { ByFileIdFileStorageStrategy strategy = new ByFileIdFileStorageStrategy(tempFolderPathAsString, "BaseFolder"); FileEntry fileEntry = newFileEntry().with(id(123L)).build(); assertEquals(combineLists(tempFolderPathSegmentsWithBaseFolder, "000000000_999999999", "000000_999999", "000_999"), strategy.getAbsoluteFilePathAndName(fileEntry).getKey()); assertEquals("123", strategy.getAbsoluteFilePathAndName(fileEntry).getValue()); } |
### Question:
IncomingConnectionCountHealthIndicator implements HealthIndicator { @Override public Health health() { if(countFilter.canAcceptConnection()){ return Health.up().build(); } else { LOG.warn("Cannot accept more incoming connections - reporting this service as unavailable"); return Health.outOfService().build(); } } @Autowired IncomingConnectionCountHealthIndicator(ConnectionCountFilter countFilter); @Override Health health(); }### Answer:
@Test public void testFilterReportsCanAcceptConnections() { when(filter.canAcceptConnection()).thenReturn(true); assertEquals(Health.up().build(), indicator.health()); verify(filter).canAcceptConnection(); }
@Test public void testFilterReportsCannotAcceptConnections() { when(filter.canAcceptConnection()).thenReturn(false); assertEquals(Health.outOfService().build(), indicator.health()); verify(filter).canAcceptConnection(); } |
### Question:
TokenServiceImpl implements TokenService { @Override public ServiceResult<Token> getPasswordResetToken(final String hash) { return find(repository.findByHashAndTypeAndClassName(hash, RESET_PASSWORD, User.class.getName()), notFoundError(Token.class, hash)); } @Override ServiceResult<Token> getEmailToken(final String hash); @Override ServiceResult<Token> getPasswordResetToken(final String hash); @Override @Transactional void removeToken(Token token); @Override @Transactional void handleExtraAttributes(Token token); }### Answer:
@Test public void test_getPasswordResetToken() throws Exception { final String hash = "ffce0dbb58bd7780cba3a6c64a666d7d3481604722c55400fd5356195407144259de4c9ec75f8edb"; final Token expected = new Token(RESET_PASSWORD, User.class.getName(), 1L, hash, expiredTokenDate(), JsonNodeFactory.instance.objectNode()); when(tokenRepositoryMock.findByHashAndTypeAndClassName(hash, RESET_PASSWORD, User.class.getName())).thenReturn(of(expected)); final Token token = tokenService.getPasswordResetToken(hash).getSuccess(); assertEquals(expected, token); verify(tokenRepositoryMock, only()).findByHashAndTypeAndClassName(hash, RESET_PASSWORD, User.class.getName()); } |
### Question:
TokenServiceImpl implements TokenService { @Override @Transactional public void removeToken(Token token) { repository.delete(token); } @Override ServiceResult<Token> getEmailToken(final String hash); @Override ServiceResult<Token> getPasswordResetToken(final String hash); @Override @Transactional void removeToken(Token token); @Override @Transactional void handleExtraAttributes(Token token); }### Answer:
@Test public void test_removeToken() throws Exception { final Token token = new Token(RESET_PASSWORD, User.class.getName(), 1L, "ffce0dbb58bd7780cba3a6c64a666d7d3481604722c55400fd5356195407144259de4c9ec75f8edb", now(), JsonNodeFactory.instance.objectNode()); tokenService.removeToken(token); verify(tokenRepositoryMock, only()).delete(token); } |
### Question:
AssessorFormInputResponsePermissionRules extends BasePermissionRules { @PermissionRule(value = "UPDATE", description = "Only Assessors can update Assessor Form Input Responses") public boolean userCanUpdateAssessorFormInputResponses(AssessorFormInputResponsesResource responses, UserResource user) { return responses.getResponses().stream().allMatch(response -> isAssessorForFormInputResponse(response, user)); } @PermissionRule(value = "UPDATE", description = "Only Assessors can update Assessor Form Input Responses") boolean userCanUpdateAssessorFormInputResponses(AssessorFormInputResponsesResource responses, UserResource user); }### Answer:
@Test public void ownersCanUpdateAssessorFormInputResponses() { AssessorFormInputResponsesResource responses = new AssessorFormInputResponsesResource( newAssessorFormInputResponseResource() .withAssessment(assessment.getId()) .build(2)); assertTrue("the owner of all responses should be able to update those responses", rules.userCanUpdateAssessorFormInputResponses(responses, assessorUser)); }
@Test public void otherUsersCannotUpdateAssessorFormInputResponses() { AssessorFormInputResponsesResource responses = new AssessorFormInputResponsesResource( newAssessorFormInputResponseResource() .withAssessment(assessment.getId()) .build(2)); assertFalse("other users should not be able to update responses", rules.userCanUpdateAssessorFormInputResponses(responses, applicantUser)); } |
### Question:
BaseFileStorageStrategy implements FileStorageStrategy { @Override public ServiceResult<File> moveFile(Long fileEntryId, File temporaryFile) { final Pair<List<String>, String> absoluteFilePathAndName = getAbsoluteFilePathAndName(fileEntryId); final List<String> pathElements = absoluteFilePathAndName.getLeft(); final String filename = absoluteFilePathAndName.getRight(); return moveFileForFileEntry(pathElements, filename, temporaryFile); } BaseFileStorageStrategy(String pathToStorageBase, String containingFolder); @Override Pair<List<String>, String> getAbsoluteFilePathAndName(FileEntry file); @Override boolean exists(FileEntry file); @Override ServiceResult<File> getFile(FileEntry file); @Override ServiceResult<File> createFile(FileEntry fileEntry, File temporaryFile); @Override ServiceResult<File> updateFile(FileEntry fileEntry, File temporaryFile); @Override ServiceResult<File> moveFile(Long fileEntryId, File temporaryFile); @Override ServiceResult<Void> deleteFile(FileEntry fileEntry); @Override List<Pair<Long, Pair<List<String>, String>>> allWithIds(); }### Answer:
@Test public void testMoveFileNoFileToMove() { BaseFileStorageStrategy strategy = createFileStorageStrategy("/tmp/path/to/containing/folder", "BaseFolder"); final ServiceResult<File> fileServiceResult = strategy.moveFile(1L, new File("/does/not/exist")); assertTrue(fileServiceResult.isFailure()); assertTrue(fileServiceResult.getFailure().is(FILES_NO_SUCH_FILE)); } |
### Question:
BaseFileStorageStrategy implements FileStorageStrategy { protected List<String> getAbsolutePathToFileUploadFolder() { return getAbsolutePathToFileUploadFolder(separator); } BaseFileStorageStrategy(String pathToStorageBase, String containingFolder); @Override Pair<List<String>, String> getAbsoluteFilePathAndName(FileEntry file); @Override boolean exists(FileEntry file); @Override ServiceResult<File> getFile(FileEntry file); @Override ServiceResult<File> createFile(FileEntry fileEntry, File temporaryFile); @Override ServiceResult<File> updateFile(FileEntry fileEntry, File temporaryFile); @Override ServiceResult<File> moveFile(Long fileEntryId, File temporaryFile); @Override ServiceResult<Void> deleteFile(FileEntry fileEntry); @Override List<Pair<Long, Pair<List<String>, String>>> allWithIds(); }### Answer:
@Test public void testGetFullPathToFileUploadFolderWithUnixSeparator() { BaseFileStorageStrategy strategy = createFileStorageStrategy("/tmp/path/to/containing/folder", "BaseFolder"); List<String> fullPathToFileUploadFolder = strategy.getAbsolutePathToFileUploadFolder("/"); assertEquals(asList("/tmp", "path", "to", "containing", "folder", "BaseFolder"), fullPathToFileUploadFolder); }
@Test public void testGetFullPathToFileUploadFolderWithWindowsSeparator() { BaseFileStorageStrategy strategy = createFileStorageStrategy("c:\\tmp\\path\\to\\containing\\folder", "BaseFolder"); List<String> fullPathToFileUploadFolder = strategy.getAbsolutePathToFileUploadFolder("\\"); assertEquals(asList("c:", "tmp", "path", "to", "containing", "folder", "BaseFolder"), fullPathToFileUploadFolder); } |
### Question:
AssessorController { @GetMapping("/has-applications-assigned/{assessorId}") public RestResult<Boolean> hasApplicationsAssigned(@PathVariable("assessorId") long assessorId) { return assessorService.hasApplicationsAssigned(assessorId).toGetResponse(); } @PostMapping("/register/{hash}") RestResult<Void> registerAssessorByHash(@PathVariable("hash") String hash,
@Valid @RequestBody UserRegistrationResource userResource); @GetMapping("/profile/{assessorId}") RestResult<AssessorProfileResource> getAssessorProfile(@PathVariable("assessorId") Long assessorId); @PutMapping("/notify-assessors/competition/{competitionId}") RestResult<Void> notifyAssessors(@PathVariable("competitionId") long competitionId); @GetMapping("/has-applications-assigned/{assessorId}") RestResult<Boolean> hasApplicationsAssigned(@PathVariable("assessorId") long assessorId); }### Answer:
@Test public void hasApplicationsAssigned() throws Exception { when(assessorServiceMock.hasApplicationsAssigned(1L)).thenReturn(serviceSuccess(TRUE)); mockMvc.perform(get("/assessor/has-applications-assigned/{id}", 1L)) .andExpect(status().isOk()); verify(assessorServiceMock, only()).hasApplicationsAssigned(1L); } |
### Question:
AssessorController { @PutMapping("/notify-assessors/competition/{competitionId}") public RestResult<Void> notifyAssessors(@PathVariable("competitionId") long competitionId) { return competitionService.notifyAssessors(competitionId) .andOnSuccess(() -> assessorService.notifyAssessorsByCompetition(competitionId)) .toPutResponse(); } @PostMapping("/register/{hash}") RestResult<Void> registerAssessorByHash(@PathVariable("hash") String hash,
@Valid @RequestBody UserRegistrationResource userResource); @GetMapping("/profile/{assessorId}") RestResult<AssessorProfileResource> getAssessorProfile(@PathVariable("assessorId") Long assessorId); @PutMapping("/notify-assessors/competition/{competitionId}") RestResult<Void> notifyAssessors(@PathVariable("competitionId") long competitionId); @GetMapping("/has-applications-assigned/{assessorId}") RestResult<Boolean> hasApplicationsAssigned(@PathVariable("assessorId") long assessorId); }### Answer:
@Test public void notifyAssessors() throws Exception { long competitionId = 1L; when(competitionServiceMock.notifyAssessors(competitionId)).thenReturn(serviceSuccess()); when(assessorServiceMock.notifyAssessorsByCompetition(competitionId)).thenReturn(serviceSuccess()); mockMvc.perform(put("/assessor/notify-assessors/competition/{id}", competitionId)) .andExpect(status().isOk()); verify(competitionServiceMock, only()).notifyAssessors(competitionId); verify(assessorServiceMock).notifyAssessorsByCompetition(competitionId); } |
### Question:
CompetitionKeyAssessmentStatisticsController { @GetMapping({"/ready-to-open"}) public RestResult<CompetitionReadyToOpenKeyAssessmentStatisticsResource> getReadyToOpenKeyStatistics( @PathVariable("id") long id) { return competitionKeyAssessmentStatisticsService.getReadyToOpenKeyStatisticsByCompetition(id).toGetResponse(); } CompetitionKeyAssessmentStatisticsController(); @Autowired CompetitionKeyAssessmentStatisticsController(CompetitionKeyAssessmentStatisticsService
competitionKeyAssessmentStatisticsService); @GetMapping({"/ready-to-open"}) RestResult<CompetitionReadyToOpenKeyAssessmentStatisticsResource> getReadyToOpenKeyStatistics(
@PathVariable("id") long id); @GetMapping("/open") RestResult<CompetitionOpenKeyAssessmentStatisticsResource> getOpenKeyStatistics(
@PathVariable("id") long id); @GetMapping("/closed") RestResult<CompetitionClosedKeyAssessmentStatisticsResource> getClosedKeyStatistics(
@PathVariable("id") long id); @GetMapping({"/in-assessment"}) RestResult<CompetitionInAssessmentKeyAssessmentStatisticsResource> getInAssessmentKeyStatistics(
@PathVariable("id") long id); }### Answer:
@Test public void getReadyToOpenKeyStatistics() throws Exception { final long competitionId = 1L; CompetitionReadyToOpenKeyAssessmentStatisticsResource keyStatisticsResource = newCompetitionReadyToOpenKeyAssessmentStatisticsResource().build(); when(competitionKeyAssessmentStatisticsServiceMock.getReadyToOpenKeyStatisticsByCompetition(competitionId)) .thenReturn(serviceSuccess(keyStatisticsResource)); mockMvc.perform(get("/competition-assessment-statistics/{id}/ready-to-open", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(keyStatisticsResource))); } |
### Question:
CompetitionKeyAssessmentStatisticsController { @GetMapping("/open") public RestResult<CompetitionOpenKeyAssessmentStatisticsResource> getOpenKeyStatistics( @PathVariable("id") long id) { return competitionKeyAssessmentStatisticsService.getOpenKeyStatisticsByCompetition(id).toGetResponse(); } CompetitionKeyAssessmentStatisticsController(); @Autowired CompetitionKeyAssessmentStatisticsController(CompetitionKeyAssessmentStatisticsService
competitionKeyAssessmentStatisticsService); @GetMapping({"/ready-to-open"}) RestResult<CompetitionReadyToOpenKeyAssessmentStatisticsResource> getReadyToOpenKeyStatistics(
@PathVariable("id") long id); @GetMapping("/open") RestResult<CompetitionOpenKeyAssessmentStatisticsResource> getOpenKeyStatistics(
@PathVariable("id") long id); @GetMapping("/closed") RestResult<CompetitionClosedKeyAssessmentStatisticsResource> getClosedKeyStatistics(
@PathVariable("id") long id); @GetMapping({"/in-assessment"}) RestResult<CompetitionInAssessmentKeyAssessmentStatisticsResource> getInAssessmentKeyStatistics(
@PathVariable("id") long id); }### Answer:
@Test public void getOpenKeyStatistics() throws Exception { final long competitionId = 1L; CompetitionOpenKeyAssessmentStatisticsResource keyStatisticsResource = newCompetitionOpenKeyAssessmentStatisticsResource().build(); when(competitionKeyAssessmentStatisticsServiceMock.getOpenKeyStatisticsByCompetition(competitionId)) .thenReturn(serviceSuccess(keyStatisticsResource)); mockMvc.perform(get("/competition-assessment-statistics/{id}/open", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(keyStatisticsResource))); } |
### Question:
CompetitionKeyAssessmentStatisticsController { @GetMapping("/closed") public RestResult<CompetitionClosedKeyAssessmentStatisticsResource> getClosedKeyStatistics( @PathVariable("id") long id) { return competitionKeyAssessmentStatisticsService.getClosedKeyStatisticsByCompetition(id).toGetResponse(); } CompetitionKeyAssessmentStatisticsController(); @Autowired CompetitionKeyAssessmentStatisticsController(CompetitionKeyAssessmentStatisticsService
competitionKeyAssessmentStatisticsService); @GetMapping({"/ready-to-open"}) RestResult<CompetitionReadyToOpenKeyAssessmentStatisticsResource> getReadyToOpenKeyStatistics(
@PathVariable("id") long id); @GetMapping("/open") RestResult<CompetitionOpenKeyAssessmentStatisticsResource> getOpenKeyStatistics(
@PathVariable("id") long id); @GetMapping("/closed") RestResult<CompetitionClosedKeyAssessmentStatisticsResource> getClosedKeyStatistics(
@PathVariable("id") long id); @GetMapping({"/in-assessment"}) RestResult<CompetitionInAssessmentKeyAssessmentStatisticsResource> getInAssessmentKeyStatistics(
@PathVariable("id") long id); }### Answer:
@Test public void getClosedKeyStatistics() throws Exception { final long competitionId = 1L; CompetitionClosedKeyAssessmentStatisticsResource keyStatisticsResource = newCompetitionClosedKeyAssessmentStatisticsResource().build(); when(competitionKeyAssessmentStatisticsServiceMock.getClosedKeyStatisticsByCompetition(competitionId)) .thenReturn(serviceSuccess(keyStatisticsResource)); mockMvc.perform(get("/competition-assessment-statistics/{id}/closed", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(keyStatisticsResource))); } |
### Question:
CompetitionKeyAssessmentStatisticsController { @GetMapping({"/in-assessment"}) public RestResult<CompetitionInAssessmentKeyAssessmentStatisticsResource> getInAssessmentKeyStatistics( @PathVariable("id") long id) { return competitionKeyAssessmentStatisticsService.getInAssessmentKeyStatisticsByCompetition(id).toGetResponse(); } CompetitionKeyAssessmentStatisticsController(); @Autowired CompetitionKeyAssessmentStatisticsController(CompetitionKeyAssessmentStatisticsService
competitionKeyAssessmentStatisticsService); @GetMapping({"/ready-to-open"}) RestResult<CompetitionReadyToOpenKeyAssessmentStatisticsResource> getReadyToOpenKeyStatistics(
@PathVariable("id") long id); @GetMapping("/open") RestResult<CompetitionOpenKeyAssessmentStatisticsResource> getOpenKeyStatistics(
@PathVariable("id") long id); @GetMapping("/closed") RestResult<CompetitionClosedKeyAssessmentStatisticsResource> getClosedKeyStatistics(
@PathVariable("id") long id); @GetMapping({"/in-assessment"}) RestResult<CompetitionInAssessmentKeyAssessmentStatisticsResource> getInAssessmentKeyStatistics(
@PathVariable("id") long id); }### Answer:
@Test public void getInAssessmentKeyStatistics() throws Exception { final long competitionId = 1L; CompetitionInAssessmentKeyAssessmentStatisticsResource keyStatisticsResource = newCompetitionInAssessmentKeyAssessmentStatisticsResource().build(); when(competitionKeyAssessmentStatisticsServiceMock.getInAssessmentKeyStatisticsByCompetition(competitionId)) .thenReturn(serviceSuccess(keyStatisticsResource)); mockMvc.perform(get("/competition-assessment-statistics/{id}/in-assessment", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(keyStatisticsResource))); } |
### Question:
AssessorCompetitionSummaryController { @GetMapping("/summary") public RestResult<AssessorCompetitionSummaryResource> getAssessorSummary(@PathVariable("assessorId") long assessorId, @PathVariable("competitionId") long competitionId) { return assessorCompetitionSummaryService.getAssessorSummary(assessorId, competitionId).toGetResponse(); } @GetMapping("/summary") RestResult<AssessorCompetitionSummaryResource> getAssessorSummary(@PathVariable("assessorId") long assessorId,
@PathVariable("competitionId") long competitionId); }### Answer:
@Test public void getAssessorSummary() throws Exception { long assessorId = 1L; long competitionId = 2L; AssessorCompetitionSummaryResource assessorCompetitionSummaryResource = newAssessorCompetitionSummaryResource() .withCompetitionId(competitionId) .withCompetitionName("Test Competition") .build(); when(assessorCompetitionSummaryServiceMock.getAssessorSummary(assessorId, competitionId)) .thenReturn(serviceSuccess(assessorCompetitionSummaryResource)); mockMvc.perform(get("/assessor/{assessorId}/competition/{competitionId}/summary", assessorId, competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(assessorCompetitionSummaryResource))); verify(assessorCompetitionSummaryServiceMock).getAssessorSummary(assessorId, competitionId); } |
### Question:
BaseFileStorageStrategy implements FileStorageStrategy { @Override public ServiceResult<File> createFile(FileEntry fileEntry, File temporaryFile) { Pair<List<String>, String> absoluteFilePathAndName = getAbsoluteFilePathAndName(fileEntry); List<String> pathElements = absoluteFilePathAndName.getLeft(); String filename = absoluteFilePathAndName.getRight(); LOG.info("[FileLogging] Creating file with FileEntry ID " + fileEntry.getId() + " and size: " + fileEntry.getFilesizeBytes()); return createFileForFileEntry(pathElements, filename, temporaryFile); } BaseFileStorageStrategy(String pathToStorageBase, String containingFolder); @Override Pair<List<String>, String> getAbsoluteFilePathAndName(FileEntry file); @Override boolean exists(FileEntry file); @Override ServiceResult<File> getFile(FileEntry file); @Override ServiceResult<File> createFile(FileEntry fileEntry, File temporaryFile); @Override ServiceResult<File> updateFile(FileEntry fileEntry, File temporaryFile); @Override ServiceResult<File> moveFile(Long fileEntryId, File temporaryFile); @Override ServiceResult<Void> deleteFile(FileEntry fileEntry); @Override List<Pair<Long, Pair<List<String>, String>>> allWithIds(); }### Answer:
@Test public void testCreateFileFailureToCreateFoldersHandledGracefully() { BaseFileStorageStrategy strategy = createFileStorageStrategy(tempFolderPathAsString, "cantcreatethisfolder"); File tempFolder = pathElementsToFile(tempFolderPathSegments); tempFolder.setReadOnly(); try { ServiceResult<File> result = strategy.createFile(newFileEntry().build(), new File("dontneedthis")); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(FILES_UNABLE_TO_CREATE_FOLDERS)); } finally { tempFolder.setWritable(true); } } |
### Question:
AssessorScopeValidator extends BaseValidator { @Override public void validate(Object target, Errors errors) { FormInputResponse response = (FormInputResponse) target; if (ASSESSOR_APPLICATION_IN_SCOPE == response.getFormInput().getType()) { String value = response.getValue(); if (!TRUE.equalsIgnoreCase(value) && !FALSE.equalsIgnoreCase(value)) { rejectValue(errors, "value", "validation.assessor.scope.invalidScope", response.getFormInput().getId()); } } } @Override void validate(Object target, Errors errors); }### Answer:
@Test public void validate_true() { formInputResponse.setValue("true"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); }
@Test public void validate_true_uppercase() { formInputResponse.setValue("TRUE"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); }
@Test public void validate_false() { formInputResponse.setValue("false"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); }
@Test public void validate_false_uppercase() { formInputResponse.setValue("FALSE"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); }
@Test public void validate_none() { formInputResponse.setValue("none"); validator.validate(formInputResponse, bindingResult); assertTrue(bindingResult.hasErrors()); assertEquals(1, bindingResult.getAllErrors().size()); assertEquals("validation.assessor.scope.invalidScope", bindingResult.getAllErrors().get(0).getDefaultMessage()); }
@Test public void validate_null() { formInputResponse.setValue(null); validator.validate(formInputResponse, bindingResult); assertTrue(bindingResult.hasErrors()); assertEquals(1, bindingResult.getAllErrors().size()); assertEquals("validation.assessor.scope.invalidScope", bindingResult.getAllErrors().get(0).getDefaultMessage()); } |
### Question:
ResearchCategoryValidator extends BaseValidator { @Override public void validate(Object target, Errors errors) { FormInputResponse response = (FormInputResponse) target; if (ASSESSOR_RESEARCH_CATEGORY == response.getFormInput().getType()) { List<ResearchCategory> researchCategories = researchCategoryRepository.findAll(); Long value; try { value = Long.parseLong(response.getValue()); } catch (NumberFormatException exception) { rejectValue(errors, "value", "validation.assessor.category.invalidCategory", response.getFormInput().getId()); return; } List<ResearchCategory> matchingCategories = researchCategories .stream() .filter(category -> value.equals(category.getId())) .collect(toList()); if (matchingCategories.isEmpty()) { rejectValue(errors, "value", "validation.assessor.category.invalidCategory", response.getFormInput().getId()); } } } @Override void validate(Object target, Errors errors); }### Answer:
@Test public void validate() { formInputResponse.setValue("1"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); }
@Test public void validate_invalid() { formInputResponse.setValue("4"); validator.validate(formInputResponse, bindingResult); assertTrue(bindingResult.hasErrors()); assertEquals(1, bindingResult.getAllErrors().size()); assertEquals("validation.assessor.category.invalidCategory", bindingResult.getAllErrors().get(0).getDefaultMessage()); }
@Test public void validate_null() { formInputResponse.setValue(null); validator.validate(formInputResponse, bindingResult); assertTrue(bindingResult.hasErrors()); assertEquals(1, bindingResult.getAllErrors().size()); assertEquals("validation.assessor.category.invalidCategory", bindingResult.getAllErrors().get(0).getDefaultMessage()); }
@Test public void validate_wrongQuestionType() { formInputResponse.getFormInput().setType(FormInputType.ASSESSOR_SCORE); formInputResponse.setValue("1"); validator.validate(formInputResponse, bindingResult); assertFalse(bindingResult.hasErrors()); } |
### Question:
ContentGroupPermissionRules extends BasePermissionRules { @PermissionRule(value = "DOWNLOAD_CONTENT_GROUP_FILE", description = "Internal users can see all content group files") public boolean internalUsersCanViewAllContentGroupFiles(ContentGroupCompositeId contentGroupCompositeId, UserResource user) { return isInternal(user); } @PermissionRule(value = "DOWNLOAD_CONTENT_GROUP_FILE", description = "Internal users can see all content group files") boolean internalUsersCanViewAllContentGroupFiles(ContentGroupCompositeId contentGroupCompositeId, UserResource user); @PermissionRule(value = "DOWNLOAD_CONTENT_GROUP_FILE", description = "External users can only see published content group files") boolean externalUsersCanViewPublishedContentGroupFiles(ContentGroupCompositeId contentGroupCompositeId, UserResource user); }### Answer:
@Test public void internalUsersCanViewAllContentGroupFiles() { allGlobalRoleUsers.forEach(user -> { if (allInternalUsers.contains(user)) { assertTrue(rules.internalUsersCanViewAllContentGroupFiles(ContentGroupCompositeId.id(1L), user)); } else { assertFalse(rules.internalUsersCanViewAllContentGroupFiles(ContentGroupCompositeId.id(1L), user)); } }); } |
### Question:
ContentGroupPermissionRules extends BasePermissionRules { @PermissionRule(value = "DOWNLOAD_CONTENT_GROUP_FILE", description = "External users can only see published content group files") public boolean externalUsersCanViewPublishedContentGroupFiles(ContentGroupCompositeId contentGroupCompositeId, UserResource user) { Optional<ContentGroup> contentGroup = contentGroupRepository.findById(contentGroupCompositeId.id()); if (contentGroup.isPresent()) { return isSystemRegistrationUser(user) && isPublished(contentGroup.get()); } return false; } @PermissionRule(value = "DOWNLOAD_CONTENT_GROUP_FILE", description = "Internal users can see all content group files") boolean internalUsersCanViewAllContentGroupFiles(ContentGroupCompositeId contentGroupCompositeId, UserResource user); @PermissionRule(value = "DOWNLOAD_CONTENT_GROUP_FILE", description = "External users can only see published content group files") boolean externalUsersCanViewPublishedContentGroupFiles(ContentGroupCompositeId contentGroupCompositeId, UserResource user); }### Answer:
@Test public void externalUsersCanViewPublishedContentGroupFiles() { ContentGroupCompositeId unpublishedContentGroupId = ContentGroupCompositeId.id(1L); when(contentGroupRepository.findById(unpublishedContentGroupId.id())).thenReturn( Optional.of(newContentGroup().withContentSection(newContentSection() .withPublicContent(newPublicContent().build()).build()).build())); ContentGroupCompositeId publishedContentGroupId = ContentGroupCompositeId.id(2L); when(contentGroupRepository.findById(publishedContentGroupId.id())).thenReturn( Optional.of(newContentGroup().withContentSection(newContentSection() .withPublicContent(newPublicContent().withPublishDate(ZonedDateTime.now()).build()).build()).build())); assertFalse(rules.externalUsersCanViewPublishedContentGroupFiles(unpublishedContentGroupId, systemRegistrationUser())); assertTrue(rules.externalUsersCanViewPublishedContentGroupFiles(publishedContentGroupId, systemRegistrationUser())); } |
### Question:
PublicContentItemPermissionRules extends BasePermissionRules { @PermissionRule(value = "READ_PUBLISHED", description = "All users can access published competitions public content") public boolean allUsersCanViewPublishedContent(CompetitionCompositeId competitionCompositeId, final UserResource user) { PublicContent content = contentRepository.findByCompetitionId(competitionCompositeId.id()); if (content != null) { return isPublished(content); } return false; } @PermissionRule(value = "READ_PUBLISHED", description = "All users can access published competitions content") boolean allUsersCanViewPublishedContent(CompetitionCompositeId competitionCompositeId, final UserResource user); }### Answer:
@Test public void canViewAllPublishedContent() { when(contentRepository.findByCompetitionId(1L)).thenReturn(newPublicContent().withPublishDate(ZonedDateTime.now()).build()); assertTrue(rules.allUsersCanViewPublishedContent(CompetitionCompositeId.id(1L), allGlobalRoleUsers.get(0))); }
@Test public void cannotViewUnpublishedContent() { when(contentRepository.findByCompetitionId(1L)).thenReturn(newPublicContent().build()); assertFalse(rules.allUsersCanViewPublishedContent(CompetitionCompositeId.id(1L), allGlobalRoleUsers.get(0))); } |
### Question:
ContentGroupServiceImpl extends BaseTransactionalService implements ContentGroupService { @Override @Transactional public ServiceResult<Void> uploadFile(long contentGroupId, FileEntryResource fileEntryResource, Supplier<InputStream> inputStreamSupplier) { BasicFileAndContents fileAndContents = new BasicFileAndContents(fileEntryResource, inputStreamSupplier); return fileService.createFile(fileAndContents.getFileEntry(), fileAndContents.getContentsSupplier()) .andOnSuccess(fileEntry -> find(contentGroupRepository.findById(contentGroupId), notFoundError(ContentGroup.class, contentGroupId)) .andOnSuccessReturnVoid(contentGroup -> contentGroup.setFileEntry(fileEntry.getRight()))); } @Override @Transactional ServiceResult<Void> uploadFile(long contentGroupId, FileEntryResource fileEntryResource, Supplier<InputStream> inputStreamSupplier); @Override @Transactional ServiceResult<Void> removeFile(Long contentGroupId); @Override @Transactional ServiceResult<Void> saveContentGroups(PublicContentResource resource, PublicContent publicContent, PublicContentSectionType sectionType); @Override ServiceResult<FileEntryResource> getFileDetails(long contentGroupId); @Override ServiceResult<FileAndContents> getFileContents(long contentGroupId); }### Answer:
@Test public void testUploadFile() { long contentGroupId = 1L; FileEntryResource fileEntryResource = mock(FileEntryResource.class); Supplier<InputStream> inputStreamSupplier = mock(Supplier.class); FileEntry fileEntry = mock(FileEntry.class); ContentGroup group = mock(ContentGroup.class); when(fileServiceMock.createFile(fileEntryResource, inputStreamSupplier)).thenReturn(serviceSuccess(new ImmutablePair<>(null, fileEntry))); when(contentGroupRepository.findById(contentGroupId)).thenReturn(Optional.of(group)); service.uploadFile(contentGroupId, fileEntryResource, inputStreamSupplier); verify(group).setFileEntry(fileEntry); verify(fileServiceMock).createFile(fileEntryResource, inputStreamSupplier); } |
### Question:
ContentGroupServiceImpl extends BaseTransactionalService implements ContentGroupService { @Override @Transactional public ServiceResult<Void> removeFile(Long contentGroupId) { return find(contentGroupRepository.findById(contentGroupId), notFoundError(ContentGroup.class, contentGroupId)) .andOnSuccess(contentGroup -> { FileEntry fileEntry = contentGroup.getFileEntry(); if (fileEntry != null) { contentGroup.setFileEntry(null); return fileService.deleteFileIgnoreNotFound(fileEntry.getId()).andOnSuccessReturnVoid(); } else { return serviceSuccess(); } }); } @Override @Transactional ServiceResult<Void> uploadFile(long contentGroupId, FileEntryResource fileEntryResource, Supplier<InputStream> inputStreamSupplier); @Override @Transactional ServiceResult<Void> removeFile(Long contentGroupId); @Override @Transactional ServiceResult<Void> saveContentGroups(PublicContentResource resource, PublicContent publicContent, PublicContentSectionType sectionType); @Override ServiceResult<FileEntryResource> getFileDetails(long contentGroupId); @Override ServiceResult<FileAndContents> getFileContents(long contentGroupId); }### Answer:
@Test public void testRemoveFile() { long contentGroupId = 1L; FileEntry fileEntry = mock(FileEntry.class); ContentGroup group = mock(ContentGroup.class); long fileEntryId = 2L; when(contentGroupRepository.findById(contentGroupId)).thenReturn(Optional.of(group)); when(group.getFileEntry()).thenReturn(fileEntry); when(fileEntry.getId()).thenReturn(fileEntryId); when(fileServiceMock.deleteFileIgnoreNotFound(fileEntryId)).thenReturn(serviceSuccess(fileEntry)); service.removeFile(contentGroupId); verify(fileServiceMock).deleteFileIgnoreNotFound(fileEntryId); } |
### Question:
ContentGroupServiceImpl extends BaseTransactionalService implements ContentGroupService { @Override public ServiceResult<FileEntryResource> getFileDetails(long contentGroupId) { return find(contentGroupRepository.findById(contentGroupId), notFoundError(ContentGroup.class, contentGroupId)) .andOnSuccessReturn(contentGroup -> fileEntryMapper.mapToResource(contentGroup.getFileEntry())); } @Override @Transactional ServiceResult<Void> uploadFile(long contentGroupId, FileEntryResource fileEntryResource, Supplier<InputStream> inputStreamSupplier); @Override @Transactional ServiceResult<Void> removeFile(Long contentGroupId); @Override @Transactional ServiceResult<Void> saveContentGroups(PublicContentResource resource, PublicContent publicContent, PublicContentSectionType sectionType); @Override ServiceResult<FileEntryResource> getFileDetails(long contentGroupId); @Override ServiceResult<FileAndContents> getFileContents(long contentGroupId); }### Answer:
@Test public void testGetFileDetails() { long contentGroupId = 1L; FileEntry fileEntry = mock(FileEntry.class); FileEntryResource fileEntryResource = mock(FileEntryResource.class); ContentGroup group = mock(ContentGroup.class); when(contentGroupRepository.findById(contentGroupId)).thenReturn(Optional.of(group)); when(group.getFileEntry()).thenReturn(fileEntry); when(fileEntryMapperMock.mapToResource(fileEntry)).thenReturn(fileEntryResource); ServiceResult<FileEntryResource> result = service.getFileDetails(contentGroupId); assertThat(result.getSuccess(), equalTo(fileEntryResource)); } |
### Question:
ContentGroupServiceImpl extends BaseTransactionalService implements ContentGroupService { @Override public ServiceResult<FileAndContents> getFileContents(long contentGroupId) { return find(contentGroupRepository.findById(contentGroupId), notFoundError(ContentGroup.class, contentGroupId)) .andOnSuccess(contentGroup -> { ServiceResult<Supplier<InputStream>> getFileResult = fileService.getFileByFileEntryId(contentGroup.getFileEntry().getId()); return getFileResult.andOnSuccessReturn(inputStream -> new BasicFileAndContents(fileEntryMapper.mapToResource(contentGroup.getFileEntry()), inputStream)); }); } @Override @Transactional ServiceResult<Void> uploadFile(long contentGroupId, FileEntryResource fileEntryResource, Supplier<InputStream> inputStreamSupplier); @Override @Transactional ServiceResult<Void> removeFile(Long contentGroupId); @Override @Transactional ServiceResult<Void> saveContentGroups(PublicContentResource resource, PublicContent publicContent, PublicContentSectionType sectionType); @Override ServiceResult<FileEntryResource> getFileDetails(long contentGroupId); @Override ServiceResult<FileAndContents> getFileContents(long contentGroupId); }### Answer:
@Test public void testGetFileContents() { long contentGroupId = 1L; long fileEntryId = 2L; FileEntry fileEntry = mock(FileEntry.class); FileEntryResource fileEntryResource = mock(FileEntryResource.class); ContentGroup group = mock(ContentGroup.class); Supplier<InputStream> inputStreamSupplier = mock(Supplier.class); when(contentGroupRepository.findById(contentGroupId)).thenReturn(Optional.of(group)); when(group.getFileEntry()).thenReturn(fileEntry); when(fileEntryMapperMock.mapToResource(fileEntry)).thenReturn(fileEntryResource); when(fileEntry.getId()).thenReturn(fileEntryId); when(fileServiceMock.getFileByFileEntryId(fileEntryId)).thenReturn(serviceSuccess(inputStreamSupplier)); ServiceResult<FileAndContents> result = service.getFileContents(contentGroupId); assertThat(result.getSuccess().getFileEntry(), equalTo(fileEntryResource)); assertThat(result.getSuccess().getContentsSupplier(), equalTo(inputStreamSupplier)); } |
### Question:
AssessmentParticipant extends CompetitionParticipant<AssessmentInvite> { @Override public AssessmentInvite getInvite() { return this.invite; } AssessmentParticipant(); AssessmentParticipant(AssessmentInvite invite); @Override AssessmentInvite getInvite(); @Override void setStatus(ParticipantStatus status); @Override void setRole(CompetitionParticipantRole role); AssessmentParticipant acceptAndAssignUser(User user); AssessmentParticipant reject(RejectionReason rejectionReason, Optional<String> rejectionComment); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void constructor() { User user = newUser().build(); AssessmentInvite createdInvite = newAssessmentInvite() .withCompetition(newCompetition().withName("my competition")) .withStatus(SENT) .withUser(user) .build(); AssessmentParticipant competitionParticipant = new AssessmentParticipant(createdInvite); assertSame(createdInvite.getUser(), competitionParticipant.getUser()); assertSame(createdInvite.getTarget(), competitionParticipant.getProcess()); assertSame(createdInvite, competitionParticipant.getInvite()); assertSame(ASSESSOR, competitionParticipant.getRole()); assertSame(PENDING, competitionParticipant.getStatus()); } |
### Question:
AssessmentParticipant extends CompetitionParticipant<AssessmentInvite> { private AssessmentParticipant accept() { if (getUser() == null) { throw new IllegalStateException("Illegal attempt to accept a AssessmentParticipant with no User"); } if (getInvite().getStatus() != OPENED) { throw new IllegalStateException("Cannot accept a AssessmentInvite that hasn't been opened"); } if (getStatus() == REJECTED) { throw new IllegalStateException("Cannot accept a AssessmentParticipant that has been rejected"); } if (getStatus() == ACCEPTED) { throw new IllegalStateException("AssessmentParticipant has already been accepted"); } super.setStatus(ACCEPTED); return this; } AssessmentParticipant(); AssessmentParticipant(AssessmentInvite invite); @Override AssessmentInvite getInvite(); @Override void setStatus(ParticipantStatus status); @Override void setRole(CompetitionParticipantRole role); AssessmentParticipant acceptAndAssignUser(User user); AssessmentParticipant reject(RejectionReason rejectionReason, Optional<String> rejectionComment); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void accept() { AssessmentParticipant competitionParticipant = new AssessmentParticipant(invite); User user = newUser().build(); invite.open(); competitionParticipant.acceptAndAssignUser(user); assertEquals(ACCEPTED, competitionParticipant.getStatus()); } |
### Question:
AssessmentParticipant extends CompetitionParticipant<AssessmentInvite> { public AssessmentParticipant acceptAndAssignUser(User user) { super.setUser(user); return accept(); } AssessmentParticipant(); AssessmentParticipant(AssessmentInvite invite); @Override AssessmentInvite getInvite(); @Override void setStatus(ParticipantStatus status); @Override void setRole(CompetitionParticipantRole role); AssessmentParticipant acceptAndAssignUser(User user); AssessmentParticipant reject(RejectionReason rejectionReason, Optional<String> rejectionComment); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test(expected = IllegalStateException.class) public void accept_unopened() { AssessmentParticipant competitionParticipant = new AssessmentParticipant(invite); User user = newUser().build(); competitionParticipant.acceptAndAssignUser(user); }
@Test(expected = IllegalStateException.class) public void accept_alreadyAccepted() { AssessmentParticipant competitionParticipant = new AssessmentParticipant(invite); User user = newUser().build(); invite.open(); competitionParticipant.acceptAndAssignUser(user); competitionParticipant.acceptAndAssignUser(user); } |
### Question:
CompetitionKeyApplicationStatisticsController { @GetMapping({"/review"}) public RestResult<ReviewKeyStatisticsResource> getReviewStatistics(@PathVariable("id") long id) { return reviewStatisticsService.getReviewPanelKeyStatistics(id).toGetResponse(); } CompetitionKeyApplicationStatisticsController(); @Autowired CompetitionKeyApplicationStatisticsController(CompetitionKeyApplicationStatisticsService competitionKeyApplicationStatisticsService,
ReviewStatisticsService reviewStatisticsService,
InterviewStatisticsService interviewStatisticsService); @GetMapping("/open") RestResult<CompetitionOpenKeyApplicationStatisticsResource> getOpenKeyStatistics(@PathVariable("id") long id); @GetMapping("/closed") RestResult<CompetitionClosedKeyApplicationStatisticsResource> getClosedKeyStatistics(@PathVariable("id") long id); @GetMapping("/funded") RestResult<CompetitionFundedKeyApplicationStatisticsResource> getFundedKeyStatistics(@PathVariable("id") long id); @GetMapping({"/review"}) RestResult<ReviewKeyStatisticsResource> getReviewStatistics(@PathVariable("id") long id); @GetMapping({"/review-invites"}) RestResult<ReviewInviteStatisticsResource> getReviewInviteStatistics(@PathVariable("id") long id); @GetMapping("/interview-assignment") RestResult<InterviewAssignmentKeyStatisticsResource> getInterviewAssignmentStatistics(@PathVariable("id") long id); @GetMapping("/interview-invites") RestResult<InterviewInviteStatisticsResource> getInterviewInviteStatistics(@PathVariable("id") long id); @GetMapping("/interview") RestResult<InterviewStatisticsResource> getInterviewStatistics(@PathVariable("id") long id); }### Answer:
@Test public void getReviewStatistics() throws Exception { final long competitionId = 1L; ReviewKeyStatisticsResource reviewKeyStatisticsResource = newReviewKeyStatisticsResource().build(); when(reviewStatisticsServiceMock.getReviewPanelKeyStatistics(competitionId)).thenReturn(serviceSuccess (reviewKeyStatisticsResource)); mockMvc.perform(get("/competition-application-statistics/{id}/review", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(reviewKeyStatisticsResource))); } |
### Question:
CompetitionKeyApplicationStatisticsController { @GetMapping({"/review-invites"}) public RestResult<ReviewInviteStatisticsResource> getReviewInviteStatistics(@PathVariable("id") long id) { return reviewStatisticsService.getReviewInviteStatistics(id).toGetResponse(); } CompetitionKeyApplicationStatisticsController(); @Autowired CompetitionKeyApplicationStatisticsController(CompetitionKeyApplicationStatisticsService competitionKeyApplicationStatisticsService,
ReviewStatisticsService reviewStatisticsService,
InterviewStatisticsService interviewStatisticsService); @GetMapping("/open") RestResult<CompetitionOpenKeyApplicationStatisticsResource> getOpenKeyStatistics(@PathVariable("id") long id); @GetMapping("/closed") RestResult<CompetitionClosedKeyApplicationStatisticsResource> getClosedKeyStatistics(@PathVariable("id") long id); @GetMapping("/funded") RestResult<CompetitionFundedKeyApplicationStatisticsResource> getFundedKeyStatistics(@PathVariable("id") long id); @GetMapping({"/review"}) RestResult<ReviewKeyStatisticsResource> getReviewStatistics(@PathVariable("id") long id); @GetMapping({"/review-invites"}) RestResult<ReviewInviteStatisticsResource> getReviewInviteStatistics(@PathVariable("id") long id); @GetMapping("/interview-assignment") RestResult<InterviewAssignmentKeyStatisticsResource> getInterviewAssignmentStatistics(@PathVariable("id") long id); @GetMapping("/interview-invites") RestResult<InterviewInviteStatisticsResource> getInterviewInviteStatistics(@PathVariable("id") long id); @GetMapping("/interview") RestResult<InterviewStatisticsResource> getInterviewStatistics(@PathVariable("id") long id); }### Answer:
@Test public void getReviewInviteStatistics() throws Exception { final long competitionId = 1L; ReviewInviteStatisticsResource reviewInviteStatisticsResource = newReviewInviteStatisticsResource().build(); when(reviewStatisticsServiceMock.getReviewInviteStatistics(competitionId)).thenReturn(serviceSuccess (reviewInviteStatisticsResource)); mockMvc.perform(get("/competition-application-statistics/{id}/review-invites", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(reviewInviteStatisticsResource))); } |
### Question:
CompetitionKeyApplicationStatisticsController { @GetMapping("/interview") public RestResult<InterviewStatisticsResource> getInterviewStatistics(@PathVariable("id") long id) { return interviewStatisticsService.getInterviewStatistics(id).toGetResponse(); } CompetitionKeyApplicationStatisticsController(); @Autowired CompetitionKeyApplicationStatisticsController(CompetitionKeyApplicationStatisticsService competitionKeyApplicationStatisticsService,
ReviewStatisticsService reviewStatisticsService,
InterviewStatisticsService interviewStatisticsService); @GetMapping("/open") RestResult<CompetitionOpenKeyApplicationStatisticsResource> getOpenKeyStatistics(@PathVariable("id") long id); @GetMapping("/closed") RestResult<CompetitionClosedKeyApplicationStatisticsResource> getClosedKeyStatistics(@PathVariable("id") long id); @GetMapping("/funded") RestResult<CompetitionFundedKeyApplicationStatisticsResource> getFundedKeyStatistics(@PathVariable("id") long id); @GetMapping({"/review"}) RestResult<ReviewKeyStatisticsResource> getReviewStatistics(@PathVariable("id") long id); @GetMapping({"/review-invites"}) RestResult<ReviewInviteStatisticsResource> getReviewInviteStatistics(@PathVariable("id") long id); @GetMapping("/interview-assignment") RestResult<InterviewAssignmentKeyStatisticsResource> getInterviewAssignmentStatistics(@PathVariable("id") long id); @GetMapping("/interview-invites") RestResult<InterviewInviteStatisticsResource> getInterviewInviteStatistics(@PathVariable("id") long id); @GetMapping("/interview") RestResult<InterviewStatisticsResource> getInterviewStatistics(@PathVariable("id") long id); }### Answer:
@Test public void getInterviewStatistics() throws Exception { final long competitionId = 1L; InterviewStatisticsResource interviewInviteStatisticsResource = newInterviewStatisticsResource().build(); when(interviewStatisticsServiceMock.getInterviewStatistics(competitionId)).thenReturn(serviceSuccess(interviewInviteStatisticsResource)); mockMvc.perform(get("/competition-application-statistics/{id}/interview", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(interviewInviteStatisticsResource))); } |
### Question:
CompetitionResearchCategoryController { @GetMapping("/{id}") public RestResult<List<CompetitionResearchCategoryLinkResource>> findByCompetition(@PathVariable("id") final long id) { return competitionResearchCategoryService.findByCompetition(id).toGetResponse(); } CompetitionResearchCategoryController(CompetitionResearchCategoryService competitionResearchCategoryService); @GetMapping("/{id}") RestResult<List<CompetitionResearchCategoryLinkResource>> findByCompetition(@PathVariable("id") final long id); }### Answer:
@Test public void findByCompetition() throws Exception { final Long competitionId = 1L; when(competitionResearchCategoryService.findByCompetition(competitionId)) .thenReturn(serviceSuccess(competitionResearchCategoryLinkBuilder.build(3))); mockMvc.perform(get("/competition-research-category/{id}", competitionId)) .andExpect(jsonPath("$", hasSize(3))) .andExpect(status().isOk()); verify(competitionResearchCategoryService, only()).findByCompetition(competitionId); } |
### Question:
CompetitionOrganisationConfigController { @GetMapping("/find-by-competition-id/{competitionId}") public RestResult<CompetitionOrganisationConfigResource> findOneByCompetitionId(@PathVariable final long competitionId) { return competitionOrganisationConfigService.findOneByCompetitionId(competitionId).toGetResponse(); } @GetMapping("/find-by-competition-id/{competitionId}") RestResult<CompetitionOrganisationConfigResource> findOneByCompetitionId(@PathVariable final long competitionId); @PutMapping("/update/{competitionId}") RestResult<Void> update(@PathVariable final long competitionId, @RequestBody CompetitionOrganisationConfigResource competitionOrganisationConfigResource); }### Answer:
@Test public void findOneByCompetitionId() throws Exception { long competitionId = 100L; CompetitionOrganisationConfigResource resource = new CompetitionOrganisationConfigResource(); when(competitionOrganisationConfigService.findOneByCompetitionId(competitionId)).thenReturn(serviceSuccess(resource)); mockMvc.perform(get("/competition-organisation-config/find-by-competition-id/{competitionId}", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(resource))); verify(competitionOrganisationConfigService).findOneByCompetitionId(competitionId); } |
### Question:
CompetitionPostSubmissionController { @PutMapping("/{id}/release-feedback") public RestResult<Void> releaseFeedback(@PathVariable("id") final long competitionId) { return competitionService.releaseFeedback(competitionId) .andOnSuccess(() -> applicationNotificationService.notifyApplicantsByCompetition(competitionId)) .toPutResponse(); } @PutMapping("/{id}/release-feedback") RestResult<Void> releaseFeedback(@PathVariable("id") final long competitionId); @PutMapping("/{id}/close-assessment") RestResult<Void> closeAssessment(@PathVariable("id") final Long id); @GetMapping("/{id}/queries/open") RestResult<List<CompetitionOpenQueryResource>> getOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{id}/queries/open/count") RestResult<Long> countOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{competitionId}/pending-spend-profiles") RestResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); @GetMapping("/{competitionId}/count-pending-spend-profiles") RestResult<Long> countPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); }### Answer:
@Test public void releaseFeedback() throws Exception { final Long competitionId = 1L; when(competitionServiceMock.releaseFeedback(competitionId)).thenReturn(serviceSuccess()); when(applicationNotificationServiceMock.notifyApplicantsByCompetition(competitionId)).thenReturn(serviceSuccess()); mockMvc.perform(put("/competition/post-submission/{id}/release-feedback", competitionId)) .andExpect(status().isOk()); verify(competitionServiceMock, only()).releaseFeedback(competitionId); verify(applicationNotificationServiceMock).notifyApplicantsByCompetition(competitionId); } |
### Question:
CompetitionPostSubmissionController { @PutMapping("/{id}/close-assessment") public RestResult<Void> closeAssessment(@PathVariable("id") final Long id) { return competitionService.closeAssessment(id).toPutResponse(); } @PutMapping("/{id}/release-feedback") RestResult<Void> releaseFeedback(@PathVariable("id") final long competitionId); @PutMapping("/{id}/close-assessment") RestResult<Void> closeAssessment(@PathVariable("id") final Long id); @GetMapping("/{id}/queries/open") RestResult<List<CompetitionOpenQueryResource>> getOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{id}/queries/open/count") RestResult<Long> countOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{competitionId}/pending-spend-profiles") RestResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); @GetMapping("/{competitionId}/count-pending-spend-profiles") RestResult<Long> countPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); }### Answer:
@Test public void closeAssessment() throws Exception { final Long competitionId = 1L; when(competitionServiceMock.closeAssessment(competitionId)).thenReturn(serviceSuccess()); mockMvc.perform(put("/competition/post-submission/{id}/close-assessment", competitionId)) .andExpect(status().isOk()) .andExpect(content().string("")); verify(competitionServiceMock, only()).closeAssessment(competitionId); } |
### Question:
CompetitionPostSubmissionController { @GetMapping("/{competitionId}/pending-spend-profiles") public RestResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId) { return competitionService.getPendingSpendProfiles(competitionId).toGetResponse(); } @PutMapping("/{id}/release-feedback") RestResult<Void> releaseFeedback(@PathVariable("id") final long competitionId); @PutMapping("/{id}/close-assessment") RestResult<Void> closeAssessment(@PathVariable("id") final Long id); @GetMapping("/{id}/queries/open") RestResult<List<CompetitionOpenQueryResource>> getOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{id}/queries/open/count") RestResult<Long> countOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{competitionId}/pending-spend-profiles") RestResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); @GetMapping("/{competitionId}/count-pending-spend-profiles") RestResult<Long> countPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); }### Answer:
@Test public void getPendingSpendProfiles() throws Exception { final Long competitionId = 1L; List<SpendProfileStatusResource> pendingSpendProfiles = new ArrayList<>(); when(competitionServiceMock.getPendingSpendProfiles(competitionId)).thenReturn(serviceSuccess(pendingSpendProfiles)); mockMvc.perform(get("/competition/post-submission/{competitionId}/pending-spend-profiles", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(pendingSpendProfiles))); verify(competitionServiceMock, only()).getPendingSpendProfiles(competitionId); } |
### Question:
CompetitionPostSubmissionController { @GetMapping("/{competitionId}/count-pending-spend-profiles") public RestResult<Long> countPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId) { return competitionService.countPendingSpendProfiles(competitionId).toGetResponse(); } @PutMapping("/{id}/release-feedback") RestResult<Void> releaseFeedback(@PathVariable("id") final long competitionId); @PutMapping("/{id}/close-assessment") RestResult<Void> closeAssessment(@PathVariable("id") final Long id); @GetMapping("/{id}/queries/open") RestResult<List<CompetitionOpenQueryResource>> getOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{id}/queries/open/count") RestResult<Long> countOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{competitionId}/pending-spend-profiles") RestResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); @GetMapping("/{competitionId}/count-pending-spend-profiles") RestResult<Long> countPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); }### Answer:
@Test public void countPendingSpendProfiles() throws Exception { final Long competitionId = 1L; final Long pendingSpendProfileCount = 3L; when(competitionServiceMock.countPendingSpendProfiles(competitionId)).thenReturn(serviceSuccess(pendingSpendProfileCount)); mockMvc.perform(get("/competition/post-submission/{competitionId}/count-pending-spend-profiles", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(pendingSpendProfileCount))); verify(competitionServiceMock, only()).countPendingSpendProfiles(competitionId); } |
### Question:
TermsAndConditionsController { @GetMapping("get-by-id/{id}") public RestResult<GrantTermsAndConditionsResource> getById(@PathVariable("id") final Long id) { return termsAndConditionsService.getById(id).toGetResponse(); } @GetMapping("/get-latest") RestResult<List<GrantTermsAndConditionsResource>> getLatestVersionsForAllTermsAndConditions(); @GetMapping("get-by-id/{id}") RestResult<GrantTermsAndConditionsResource> getById(@PathVariable("id") final Long id); @GetMapping("/site") RestResult<SiteTermsAndConditionsResource> getLatestSiteTermsAndConditions(); }### Answer:
@Test public void getById() throws Exception { final Long competitionId = 1L; when(termsAndConditionsService.getById(competitionId)).thenReturn(serviceSuccess (newGrantTermsAndConditionsResource().build())); mockMvc.perform(get("/terms-and-conditions/get-by-id/{id}", competitionId)) .andExpect(status().isOk()); verify(termsAndConditionsService, only()).getById(competitionId); } |
### Question:
TermsAndConditionsController { @GetMapping("/get-latest") public RestResult<List<GrantTermsAndConditionsResource>> getLatestVersionsForAllTermsAndConditions() { return termsAndConditionsService.getLatestVersionsForAllTermsAndConditions().toGetResponse(); } @GetMapping("/get-latest") RestResult<List<GrantTermsAndConditionsResource>> getLatestVersionsForAllTermsAndConditions(); @GetMapping("get-by-id/{id}") RestResult<GrantTermsAndConditionsResource> getById(@PathVariable("id") final Long id); @GetMapping("/site") RestResult<SiteTermsAndConditionsResource> getLatestSiteTermsAndConditions(); }### Answer:
@Test public void getLatest() throws Exception { List<GrantTermsAndConditionsResource> termsAndConditionsResourceList = newGrantTermsAndConditionsResource() .build(2); when(termsAndConditionsService.getLatestVersionsForAllTermsAndConditions()).thenReturn(serviceSuccess (termsAndConditionsResourceList)); mockMvc.perform(get("/terms-and-conditions/get-latest")) .andExpect(status().isOk()) .andExpect(content().json(toJson(termsAndConditionsResourceList))); verify(termsAndConditionsService, only()).getLatestVersionsForAllTermsAndConditions(); } |
### Question:
TermsAndConditionsController { @GetMapping("/site") public RestResult<SiteTermsAndConditionsResource> getLatestSiteTermsAndConditions() { return termsAndConditionsService.getLatestSiteTermsAndConditions().toGetResponse(); } @GetMapping("/get-latest") RestResult<List<GrantTermsAndConditionsResource>> getLatestVersionsForAllTermsAndConditions(); @GetMapping("get-by-id/{id}") RestResult<GrantTermsAndConditionsResource> getById(@PathVariable("id") final Long id); @GetMapping("/site") RestResult<SiteTermsAndConditionsResource> getLatestSiteTermsAndConditions(); }### Answer:
@Test public void getLatestSiteTermsAndConditions() throws Exception { SiteTermsAndConditionsResource expected = newSiteTermsAndConditionsResource().build(); when(termsAndConditionsService.getLatestSiteTermsAndConditions()).thenReturn(serviceSuccess(expected)); mockMvc.perform(RestDocumentationRequestBuilders.get("/terms-and-conditions/site")) .andExpect(status().isOk()) .andExpect(content().json(toJson(expected))); verify(termsAndConditionsService, only()).getLatestSiteTermsAndConditions(); } |
### Question:
MilestoneServiceImpl extends BaseTransactionalService implements MilestoneService { @Override @Transactional public ServiceResult<Void> updateMilestone(MilestoneResource milestoneResource) { milestoneRepository.save(milestoneMapper.mapToDomain(milestoneResource)); return serviceSuccess(); } @Override ServiceResult<List<MilestoneResource>> getAllPublicMilestonesByCompetitionId(Long id); @Override ServiceResult<Boolean> allPublicDatesComplete(Long competitionId); @Override ServiceResult<List<MilestoneResource>> getAllMilestonesByCompetitionId(Long id); @Override ServiceResult<MilestoneResource> getMilestoneByTypeAndCompetitionId(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateMilestones(List<MilestoneResource> milestones); @Override @Transactional ServiceResult<Void> updateMilestone(MilestoneResource milestoneResource); @Override @Transactional ServiceResult<MilestoneResource> create(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateCompletionStage(long competitionId, CompetitionCompletionStage completionStage); }### Answer:
@Test public void updateMilestone() { ZonedDateTime milestoneDate = ZonedDateTime.now(); ServiceResult<Void> result = service.updateMilestone(newMilestoneResource().withType(BRIEFING_EVENT).withDate(milestoneDate.plusMonths(1)).build()); assertTrue(result.isSuccess()); } |
### Question:
MilestoneServiceImpl extends BaseTransactionalService implements MilestoneService { @Override public ServiceResult<List<MilestoneResource>> getAllMilestonesByCompetitionId(Long id) { return serviceSuccess((List<MilestoneResource>) milestoneMapper.mapToResource(milestoneRepository.findAllByCompetitionId(id))); } @Override ServiceResult<List<MilestoneResource>> getAllPublicMilestonesByCompetitionId(Long id); @Override ServiceResult<Boolean> allPublicDatesComplete(Long competitionId); @Override ServiceResult<List<MilestoneResource>> getAllMilestonesByCompetitionId(Long id); @Override ServiceResult<MilestoneResource> getMilestoneByTypeAndCompetitionId(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateMilestones(List<MilestoneResource> milestones); @Override @Transactional ServiceResult<Void> updateMilestone(MilestoneResource milestoneResource); @Override @Transactional ServiceResult<MilestoneResource> create(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateCompletionStage(long competitionId, CompetitionCompletionStage completionStage); }### Answer:
@Test public void getAllMilestones() { List<Milestone> milestones = newMilestone().withType(BRIEFING_EVENT, LINE_DRAW, NOTIFICATIONS).build(3); when(milestoneRepository.findAllByCompetitionId(1L)).thenReturn(milestones); ServiceResult<List<MilestoneResource>> result = service.getAllMilestonesByCompetitionId(1L); assertTrue(result.isSuccess()); assertNotNull(result); assertEquals(3, milestones.size()); } |
### Question:
CompetitionSearchServiceImpl extends BaseTransactionalService implements CompetitionSearchService { @Override public ServiceResult<List<CompetitionSearchResultItem>> findLiveCompetitions() { List<Competition> competitions = competitionRepository.findLive(); return serviceSuccess(competitions.stream() .map(this::toLiveCompetitionResult) .collect(toList())); } @Override ServiceResult<List<CompetitionSearchResultItem>> findLiveCompetitions(); @Override ServiceResult<CompetitionSearchResult> findProjectSetupCompetitions(int page, int size); @Override ServiceResult<List<CompetitionSearchResultItem>> findUpcomingCompetitions(); @Override ServiceResult<CompetitionSearchResult> findNonIfsCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> findPreviousCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> searchCompetitions(String searchQuery, int page, int size); @Override ServiceResult<CompetitionCountResource> countCompetitions(); }### Answer:
@Test public void findLiveCompetitions() { List<Competition> competitions = Lists.newArrayList(newCompetition().withId(competitionId).build()); when(competitionRepositoryMock.findLive()).thenReturn(competitions); List<CompetitionSearchResultItem> response = service.findLiveCompetitions().getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(competitions, response); } |
### Question:
CompetitionSearchServiceImpl extends BaseTransactionalService implements CompetitionSearchService { @Override public ServiceResult<List<CompetitionSearchResultItem>> findUpcomingCompetitions() { List<Competition> competitions = competitionRepository.findUpcoming(); return serviceSuccess(competitions.stream() .map(this::toUpcomingCompetitionResult) .collect(toList())); } @Override ServiceResult<List<CompetitionSearchResultItem>> findLiveCompetitions(); @Override ServiceResult<CompetitionSearchResult> findProjectSetupCompetitions(int page, int size); @Override ServiceResult<List<CompetitionSearchResultItem>> findUpcomingCompetitions(); @Override ServiceResult<CompetitionSearchResult> findNonIfsCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> findPreviousCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> searchCompetitions(String searchQuery, int page, int size); @Override ServiceResult<CompetitionCountResource> countCompetitions(); }### Answer:
@Test public void findUpcomingCompetitions() { List<Competition> competitions = Lists.newArrayList(newCompetition().withId(competitionId).build()); when(competitionRepositoryMock.findUpcoming()).thenReturn(competitions); List<CompetitionSearchResultItem> response = service.findUpcomingCompetitions().getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(competitions, response); } |
### Question:
CompetitionSearchServiceImpl extends BaseTransactionalService implements CompetitionSearchService { @Override public ServiceResult<CompetitionSearchResult> findNonIfsCompetitions(int page, int size) { PageRequest pageRequest = PageRequest.of(page, size); Page<Competition> competitions = competitionRepository.findNonIfs(pageRequest); return handleCompetitionSearchResultPage(competitions, this::toNonIfsCompetitionSearchResult); } @Override ServiceResult<List<CompetitionSearchResultItem>> findLiveCompetitions(); @Override ServiceResult<CompetitionSearchResult> findProjectSetupCompetitions(int page, int size); @Override ServiceResult<List<CompetitionSearchResultItem>> findUpcomingCompetitions(); @Override ServiceResult<CompetitionSearchResult> findNonIfsCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> findPreviousCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> searchCompetitions(String searchQuery, int page, int size); @Override ServiceResult<CompetitionCountResource> countCompetitions(); }### Answer:
@Test public void findNonIfsCompetitions() { int page = 0; int size = 20; List<Competition> competitions = Lists.newArrayList(newCompetition().withId(competitionId).build()); when(publicContentRepository.findByCompetitionId(competitionId)).thenReturn(newPublicContent().build()); when(competitionRepositoryMock.findNonIfs(any())).thenReturn(new PageImpl<>(competitions, PageRequest.of(page, size), 1L)); CompetitionSearchResult response = service.findNonIfsCompetitions(page, size).getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(competitions, response.getContent()); } |
### Question:
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override public ServiceResult<CompetitionResource> getCompetitionById(long id) { return findCompetitionById(id).andOnSuccess(comp -> serviceSuccess(competitionMapper.mapToResource(comp))); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); }### Answer:
@Test public void getCompetitionById() { Competition competition = new Competition(); CompetitionResource resource = new CompetitionResource(); when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(competition)); when(competitionMapperMock.mapToResource(competition)).thenReturn(resource); CompetitionResource response = service.getCompetitionById(competitionId).getSuccess(); assertEquals(resource, response); } |
### Question:
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override public ServiceResult<List<CompetitionResource>> findAll() { return serviceSuccess((List) competitionMapper.mapToResource( competitionRepository.findAll().stream().filter(comp -> !comp.isTemplate()).collect(toList()) )); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); }### Answer:
@Test public void findAll() { List<Competition> competitions = Lists.newArrayList(new Competition()); List<CompetitionResource> resources = Lists.newArrayList(new CompetitionResource()); when(competitionRepositoryMock.findAll()).thenReturn(competitions); when(competitionMapperMock.mapToResource(competitions)).thenReturn(resources); List<CompetitionResource> response = service.findAll().getSuccess(); assertEquals(resources, response); } |
### Question:
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override public ServiceResult<Long> countAllOpenQueries(long competitionId) { return serviceSuccess(competitionRepository.countOpenQueriesByCompetitionAndProjectStateNotIn(competitionId, asList(WITHDRAWN, HANDLED_OFFLINE, COMPLETED_OFFLINE))); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); }### Answer:
@Test public void countCompetitionOpenQueries() { Long countOpenQueries = 4l; when(competitionRepositoryMock.countOpenQueriesByCompetitionAndProjectStateNotIn(competitionId, asList(WITHDRAWN, HANDLED_OFFLINE, COMPLETED_OFFLINE))).thenReturn(countOpenQueries); Long response = service.countAllOpenQueries(competitionId).getSuccess(); assertEquals(countOpenQueries, response); } |
### Question:
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override public ServiceResult<Long> countPendingSpendProfiles(long competitionId) { return serviceSuccess(competitionRepository.countPendingSpendProfiles(competitionId).longValue()); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); }### Answer:
@Test public void countPendingSpendProfiles() { final BigDecimal pendingSpendProfileCount = BigDecimal.TEN; when(competitionRepositoryMock.countPendingSpendProfiles(competitionId)).thenReturn(pendingSpendProfileCount); ServiceResult<Long> result = service.countPendingSpendProfiles(competitionId); assertTrue(result.isSuccess()); assertEquals(Long.valueOf(pendingSpendProfileCount.longValue()), result.getSuccess()); } |
### Question:
CompetitionOrganisationConfigServiceImpl implements CompetitionOrganisationConfigService { @Override public ServiceResult<CompetitionOrganisationConfigResource> findOneByCompetitionId(long competitionId) { Optional<CompetitionOrganisationConfig> config = competitionOrganisationConfigRepository.findOneByCompetitionId(competitionId); if (config.isPresent()) { return serviceSuccess(mapper.mapToResource(config.get())); } return serviceSuccess(new CompetitionOrganisationConfigResource(false, false)); } @Override ServiceResult<CompetitionOrganisationConfigResource> findOneByCompetitionId(long competitionId); @Override @Transactional ServiceResult<Void> update(long competitionId, CompetitionOrganisationConfigResource competitionOrganisationConfigResource); }### Answer:
@Test public void findOneByCompetitionId() { CompetitionOrganisationConfigResource resource = new CompetitionOrganisationConfigResource(); when(competitionOrganisationConfigRepository.findOneByCompetitionId(competitionId)).thenReturn(Optional.of(config)); when(mapper.mapToResource(config)).thenReturn(resource); ServiceResult<CompetitionOrganisationConfigResource> result = service.findOneByCompetitionId(competitionId); assertTrue(result.isSuccess()); assertEquals(config.getId(), result.getSuccess().getId()); } |
### Question:
TermsAndConditionsServiceImpl implements TermsAndConditionsService { @Override public ServiceResult<List<GrantTermsAndConditionsResource>> getLatestVersionsForAllTermsAndConditions() { return serviceSuccess((List<GrantTermsAndConditionsResource>) grantTermsAndConditionsMapper.mapToResource(grantTermsAndConditionsRepository.findLatestVersions()) ); } @Autowired TermsAndConditionsServiceImpl(
GrantTermsAndConditionsRepository grantTermsAndConditionsRepository,
SiteTermsAndConditionsRepository siteTermsAndConditionsRepository,
GrantTermsAndConditionsMapper grantTermsAndConditionsMapper,
SiteTermsAndConditionsMapper siteTermsAndConditionsMapper); @Override ServiceResult<List<GrantTermsAndConditionsResource>> getLatestVersionsForAllTermsAndConditions(); @Override ServiceResult<GrantTermsAndConditionsResource> getById(Long id); @Override @Cacheable(cacheNames="siteTerms", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<SiteTermsAndConditionsResource> getLatestSiteTermsAndConditions(); }### Answer:
@Test public void test_getLatestVersionsForAllTermsAndConditions() { List<GrantTermsAndConditions> termsAndConditionsList = newGrantTermsAndConditions().build(3); List<GrantTermsAndConditionsResource> termsAndConditionsResourceList = newGrantTermsAndConditionsResource() .build(3); when(grantTermsAndConditionsRepository.findLatestVersions()).thenReturn(termsAndConditionsList); when(grantTermsAndConditionsMapper.mapToResource(termsAndConditionsList)).thenReturn (termsAndConditionsResourceList); ServiceResult<List<GrantTermsAndConditionsResource>> result = service .getLatestVersionsForAllTermsAndConditions(); assertTrue(result.isSuccess()); assertNotNull(result); assertEquals(3, result.getSuccess().size()); } |
### Question:
CompetitionSetupInnovationLeadServiceImpl extends BaseTransactionalService implements CompetitionSetupInnovationLeadService { @Override public ServiceResult<List<UserResource>> findInnovationLeads(long competitionId) { List<User> innovationLeads = innovationLeadRepository.findAvailableInnovationLeadsNotAssignedToCompetition(competitionId); List<UserResource> innovationLeadUsers = simpleMap(innovationLeads, user -> userMapper .mapToResource(user)); return serviceSuccess(innovationLeadUsers); } @Override ServiceResult<List<UserResource>> findInnovationLeads(long competitionId); @Override ServiceResult<List<UserResource>> findAddedInnovationLeads(long competitionId); @Override @Transactional ServiceResult<Void> addInnovationLead(long competitionId, long innovationLeadUserId); @Override @Transactional ServiceResult<Void> removeInnovationLead(long competitionId, long innovationLeadUserId); }### Answer:
@Test public void findInnovationLeads() { User innovationLead1 = newUser().withRoles(singleton(INNOVATION_LEAD)).build(); User innovationLead2 = newUser().withRoles(singleton(INNOVATION_LEAD)).build(); List<User> innovationLeads = asList(innovationLead1, innovationLead2); UserResource userResource1 = UserResourceBuilder.newUserResource().build(); UserResource userResource2 = UserResourceBuilder.newUserResource().build(); when(innovationLeadRepository.findAvailableInnovationLeadsNotAssignedToCompetition(competitionId)).thenReturn(innovationLeads); when(userMapper.mapToResource(innovationLead1)).thenReturn(userResource1); when(userMapper.mapToResource(innovationLead2)).thenReturn(userResource2); List<UserResource> result = service.findInnovationLeads(competitionId).getSuccess(); assertEquals(2, result.size()); assertEquals(userResource1, result.get(0)); assertEquals(userResource2, result.get(1)); } |
### Question:
CompetitionSetupInnovationLeadServiceImpl extends BaseTransactionalService implements CompetitionSetupInnovationLeadService { @Override @Transactional public ServiceResult<Void> addInnovationLead(long competitionId, long innovationLeadUserId) { return findCompetitionById(competitionId) .andOnSuccessReturnVoid(competition -> find(userRepository.findById(innovationLeadUserId), notFoundError(User.class, innovationLeadUserId)) .andOnSuccess(innovationLead -> { innovationLeadRepository.save(new InnovationLead(competition, innovationLead)); return serviceSuccess(); }) ); } @Override ServiceResult<List<UserResource>> findInnovationLeads(long competitionId); @Override ServiceResult<List<UserResource>> findAddedInnovationLeads(long competitionId); @Override @Transactional ServiceResult<Void> addInnovationLead(long competitionId, long innovationLeadUserId); @Override @Transactional ServiceResult<Void> removeInnovationLead(long competitionId, long innovationLeadUserId); }### Answer:
@Test public void addInnovationLeadWhenCompetitionNotFound() { Long innovationLeadUserId = 2L; when(competitionRepository.findById(competitionId)).thenReturn(Optional.empty()); ServiceResult<Void> result = service.addInnovationLead(competitionId, innovationLeadUserId); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(Competition.class, competitionId))); }
@Test public void addInnovationLead() { long innovationLeadUserId = 2L; Competition competition = newCompetition().build(); User innovationLead = newUser().build(); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(competition)); when(userRepository.findById(innovationLeadUserId)).thenReturn(Optional.of(innovationLead)); ServiceResult<Void> result = service.addInnovationLead(competitionId, innovationLeadUserId); assertTrue(result.isSuccess()); InnovationLead savedCompetitionParticipant = new InnovationLead(competition, innovationLead); verify(innovationLeadRepository).save(savedCompetitionParticipant); } |
### Question:
CompetitionSetupInnovationLeadServiceImpl extends BaseTransactionalService implements CompetitionSetupInnovationLeadService { @Override @Transactional public ServiceResult<Void> removeInnovationLead(long competitionId, long innovationLeadUserId) { return find(innovationLeadRepository.findInnovationLead(competitionId, innovationLeadUserId), notFoundError(InnovationLead.class, competitionId, innovationLeadUserId)) .andOnSuccessReturnVoid(innovationLead -> innovationLeadRepository.delete(innovationLead)); } @Override ServiceResult<List<UserResource>> findInnovationLeads(long competitionId); @Override ServiceResult<List<UserResource>> findAddedInnovationLeads(long competitionId); @Override @Transactional ServiceResult<Void> addInnovationLead(long competitionId, long innovationLeadUserId); @Override @Transactional ServiceResult<Void> removeInnovationLead(long competitionId, long innovationLeadUserId); }### Answer:
@Test public void removeInnovationLeadWhenCompetitionParticipantNotFound() { long innovationLeadUserId = 2L; when(innovationLeadRepository.findInnovationLead(competitionId, innovationLeadUserId)).thenReturn(null); ServiceResult<Void> result = service.removeInnovationLead(competitionId, innovationLeadUserId); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(InnovationLead.class, competitionId, innovationLeadUserId))); }
@Test public void removeInnovationLead() { long innovationLeadUserId = 2L; InnovationLead innovationLead = newInnovationLead().build(); when(innovationLeadRepository.findInnovationLead(competitionId, innovationLeadUserId)).thenReturn (innovationLead); ServiceResult<Void> result = service.removeInnovationLead(competitionId, innovationLeadUserId); assertTrue(result.isSuccess()); verify(innovationLeadRepository).delete(innovationLead); } |
### Question:
PublicContentServiceImpl extends BaseTransactionalService implements PublicContentService { @Override public ServiceResult<PublicContentResource> findByCompetitionId(long id) { return find(publicContentRepository.findByCompetitionId(id), notFoundError(PublicContent.class, id)) .andOnSuccessReturn(publicContent -> sortGroups(publicContentMapper.mapToResource(publicContent))); } @Override ServiceResult<PublicContentResource> findByCompetitionId(long id); @Override @Transactional ServiceResult<Void> initialiseByCompetitionId(long competitionId); @Override @Transactional ServiceResult<Void> publishByCompetitionId(long competitionId); @Override @Transactional ServiceResult<Void> updateSection(PublicContentResource resource, PublicContentSectionType section); @Override @Transactional ServiceResult<Void> markSectionAsComplete(PublicContentResource resource, PublicContentSectionType section); }### Answer:
@Test public void testGetById() { PublicContent publicContent = newPublicContent().build(); PublicContentResource resource = newPublicContentResource().withContentSections(COMPLETE_SECTIONS).build(); when(publicContentRepository.findByCompetitionId(COMPETITION_ID)).thenReturn(publicContent); when(publicContentMapper.mapToResource(publicContent)).thenReturn(resource); ServiceResult<PublicContentResource> result = service.findByCompetitionId(COMPETITION_ID); assertThat(result.getSuccess(), equalTo(resource)); verify(publicContentRepository).findByCompetitionId(COMPETITION_ID); assertTrue(isSortedByPriority(result.getSuccess())); } |
### Question:
Milestone { public boolean isSet() { assert date != null || !type.isPresetDate(); return date != null; } private Milestone(); Milestone(MilestoneType type, Competition competition); Milestone(MilestoneType type, ZonedDateTime date, Competition competition); Long getId(); void setId(Long id); void setCompetition(Competition competition); Competition getCompetition(); MilestoneType getType(); void setType(MilestoneType type); ZonedDateTime getDate(); void setDate(ZonedDateTime date); boolean isSet(); void ifSet(Consumer<ZonedDateTime> consumer); boolean isReached(ZonedDateTime now); }### Answer:
@Test public void isSet() { Milestone assessorsNotifiedMilestone = new Milestone(MilestoneType.ASSESSORS_NOTIFIED, newCompetition().build()); assertFalse(assessorsNotifiedMilestone.isSet()); assessorsNotifiedMilestone.setDate(ZonedDateTime.now()); assertTrue(assessorsNotifiedMilestone.isSet()); } |
### Question:
Milestone { public boolean isReached(ZonedDateTime now) { return date != null && !date.isAfter(now); } private Milestone(); Milestone(MilestoneType type, Competition competition); Milestone(MilestoneType type, ZonedDateTime date, Competition competition); Long getId(); void setId(Long id); void setCompetition(Competition competition); Competition getCompetition(); MilestoneType getType(); void setType(MilestoneType type); ZonedDateTime getDate(); void setDate(ZonedDateTime date); boolean isSet(); void ifSet(Consumer<ZonedDateTime> consumer); boolean isReached(ZonedDateTime now); }### Answer:
@Test public void isReached() { ZonedDateTime now = ZonedDateTime.now(); ZonedDateTime future = now.plusNanos(1); ZonedDateTime past = now.minusNanos(1); assertFalse( new Milestone(MilestoneType.ALLOCATE_ASSESSORS, future, newCompetition().build()).isReached(now) ); assertTrue( new Milestone(MilestoneType.ALLOCATE_ASSESSORS, now, newCompetition().build()).isReached(now) ); assertTrue( new Milestone(MilestoneType.ALLOCATE_ASSESSORS, past, newCompetition().build()).isReached(now) ); } |
### Question:
InterviewPermissionRules extends BasePermissionRules { @PermissionRule(value = "READ_INTERVIEW_DASHBOARD", description = "Assessors can view all Assessment Interviews on the competition " + "dashboard") public boolean userCanReadInterviewOnDashboard(InterviewResource interview, UserResource user) { Set<InterviewState> allowedStates = EnumSet.of(ASSIGNED); return isAssessorForInterview(interview, user, allowedStates); } @PermissionRule(value = "READ_INTERVIEW_DASHBOARD", description = "Assessors can view all Assessment Interviews on the competition " + "dashboard") boolean userCanReadInterviewOnDashboard(InterviewResource interview, UserResource user); @PermissionRule(value = "UPDATE", description = "An assessor may only update their own invites to assessment Interviews") boolean userCanUpdateInterview(InterviewResource interview, UserResource loggedInUser); @PermissionRule(value = "READ", description = "An assessor may only read their own invites to assessment Interviews") boolean userCanReadInterviews(InterviewResource interview, UserResource loggedInUser); }### Answer:
@Test public void ownersCanReadAssessmentsOnDashboard() { EnumSet<InterviewState> allowedStates = EnumSet.of(ASSIGNED); allowedStates.forEach(state -> assertTrue("the owner of an assessment Interview should be able to read that assessment Interview on the dashboard", rules.userCanReadInterviewOnDashboard(assessmentInterviews.get(state), assessorUser))); EnumSet.complementOf(allowedStates).forEach(state -> assertFalse("the owner of an assessment Interview should not be able to read that assessment Interview on the dashboard", rules.userCanReadInterviewOnDashboard(assessmentInterviews.get(state), assessorUser))); }
@Test public void otherUsersCanNotReadAssessmentsOnDashboard() { EnumSet.allOf(InterviewState.class).forEach(state -> assertFalse("other users should not be able to read any assessment Interviews", rules.userCanReadInterviewOnDashboard(assessmentInterviews.get(state), otherUser))); } |
### Question:
InterviewParticipantPermissionRules extends BasePermissionRules { @PermissionRule(value = "READ", description = "only the same user can read their interview panel participation") public boolean userCanViewTheirOwnInterviewParticipation(InterviewParticipantResource assessmentInterviewPanelParticipant, UserResource user) { return isSameParticipant(assessmentInterviewPanelParticipant, user); } @PermissionRule(value = "ACCEPT", description = "only the same user can accept an interview panel invitation") boolean userCanAcceptInterviewInvite(InterviewParticipantResource interviewParticipant, UserResource user); @PermissionRule(value = "READ", description = "only the same user can read their interview panel participation") boolean userCanViewTheirOwnInterviewParticipation(InterviewParticipantResource assessmentInterviewPanelParticipant, UserResource user); }### Answer:
@Test public void userCanViewTheirOwnAssessmentPanelParticipation() { InterviewParticipantResource interviewParticipantResource = newInterviewParticipantResource() .withUser(7L) .withInvite(newInterviewInviteResource().withStatus(SENT).build()) .build(); UserResource userResource = newUserResource() .withId(7L) .withRolesGlobal(singletonList(ASSESSOR)) .build(); assertTrue(rules.userCanViewTheirOwnInterviewParticipation(interviewParticipantResource, userResource)); }
@Test public void userCanViewTheirOwnAssessmentPanelParticipation_differentUser() { InterviewParticipantResource interviewParticipantResource = newInterviewParticipantResource() .withUser(7L) .build(); UserResource userResource = newUserResource() .withId(11L) .withRolesGlobal(singletonList(ASSESSOR)) .build(); assertFalse(rules.userCanViewTheirOwnInterviewParticipation(interviewParticipantResource, userResource)); } |
### Question:
PublicContentServiceImpl extends BaseTransactionalService implements PublicContentService { @Override @Transactional public ServiceResult<Void> markSectionAsComplete(PublicContentResource resource, PublicContentSectionType section) { return saveSection(resource, section) .andOnSuccessReturnVoid(publicContent -> markSectionAsComplete(publicContent, section)); } @Override ServiceResult<PublicContentResource> findByCompetitionId(long id); @Override @Transactional ServiceResult<Void> initialiseByCompetitionId(long competitionId); @Override @Transactional ServiceResult<Void> publishByCompetitionId(long competitionId); @Override @Transactional ServiceResult<Void> updateSection(PublicContentResource resource, PublicContentSectionType section); @Override @Transactional ServiceResult<Void> markSectionAsComplete(PublicContentResource resource, PublicContentSectionType section); }### Answer:
@Test public void testMarkAsComplete() { PublicContent publicContent = mock(PublicContent.class); PublicContentResource publicContentResource = newPublicContentResource().withKeywords(Collections.emptyList()).build(); when(publicContentMapper.mapToDomain(publicContentResource)).thenReturn(publicContent); when(publicContentRepository.save(publicContent)).thenReturn(publicContent); ContentSection section = newContentSection().withType(PublicContentSectionType.SEARCH).withStatus(IN_PROGRESS).build(); when(publicContent.getContentSections()).thenReturn(asList(section)); when(publicContent.getId()).thenReturn(1L); when(publicContent.getPublishDate()).thenReturn(null); ServiceResult<Void> result = service.markSectionAsComplete(publicContentResource, PublicContentSectionType.SEARCH); assertThat(section.getStatus(), equalTo(COMPLETE)); assertTrue(result.isSuccess()); } |
### Question:
EmailAddressResolver { public static EmailAddress fromNotificationSource(NotificationSource notificationSource) { return new EmailAddress(notificationSource.getEmailAddress(), notificationSource.getName()); } private EmailAddressResolver(); static EmailAddress fromNotificationSource(NotificationSource notificationSource); static EmailAddress fromNotificationTarget(NotificationTarget notificationTarget); }### Answer:
@Test public void testFromNotificationSourceWithUserNotificationSource() { User user = newUser().withFirstName("My").withLastName("User").withEmailAddress("[email protected]").build(); UserNotificationSource notificationSource = new UserNotificationSource(user.getName(), user.getEmail()); EmailAddress resolvedEmailAddress = EmailAddressResolver.fromNotificationSource(notificationSource); assertEquals("My User", resolvedEmailAddress.getName()); assertEquals("[email protected]", resolvedEmailAddress.getEmailAddress()); } |
### Question:
PartitionSortRepeats { public static void groupByAge(List<Person> people) { } static void groupByAge(List<Person> people); }### Answer:
@Test public void groupByAge() throws Exception { expected = new HashMap<>(); expected.put(23, new AtomicInteger(2)); expected.put(25, new AtomicInteger(3)); expected.put(26, new AtomicInteger(2)); people = Arrays.asList( new PartitionSortRepeats.Person(25, "Rita"), new PartitionSortRepeats.Person(23, "Felipe"), new PartitionSortRepeats.Person(25, "Vera"), new PartitionSortRepeats.Person(25, "Nathan"), new PartitionSortRepeats.Person(26, "Daniel"), new PartitionSortRepeats.Person(23, "Zach"), new PartitionSortRepeats.Person(26, "Tom") ); test(expected, people); } |
### Question:
LRUCache { public LRUCache(int capacity) { this.capacity = capacity; } LRUCache(int capacity); Integer lookup(Integer key); Integer insert(Integer key, Integer value); Integer remove(Integer key); }### Answer:
@Test public void lruCache() { final int capacity = 8; final Map<Integer, Integer> map = new HashMap<>(); final List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10); final LRUCache cache = new LRUCache(capacity); list.forEach(i -> { cache.insert(i, i); }); assertNull(cache.lookup(1)); assertNull(cache.lookup(2)); assertEquals(list.get(3), cache.lookup(3)); cache.insert(1, 1); assertNull(cache.lookup(4)); cache.remove(1); assertNull(cache.lookup(1)); } |
### Question:
InsertionAndDeletionBST extends BinaryTree<Integer> { public boolean insert(Integer key) { return false; } InsertionAndDeletionBST(Integer data); boolean insert(Integer key); boolean delete(Integer key); }### Answer:
@Test public void test1() { InsertionAndDeletionBST tree = new InsertionAndDeletionBST(2); tree.insert(0); tree.insert(1); assertEquals(tree, BinaryTreeUtil.getEvenBST()); }
@Test public void test2() { InsertionAndDeletionBST tree = new InsertionAndDeletionBST(4); tree.insert(6); tree.insert(1); tree.insert(2); tree.insert(5); tree.insert(7); tree.insert(3); assertEquals(tree, BinaryTreeUtil.getFullBST()); } |
### Question:
AuthenticationContextClassReferencePrincipal implements CloneablePrincipal { @Override public boolean equals(final Object other) { if (other == null) { return false; } if (this == other) { return true; } if (other instanceof AuthenticationContextClassReferencePrincipal) { return authnContextClassReference.equals(((AuthenticationContextClassReferencePrincipal) other).getName()); } return false; } AuthenticationContextClassReferencePrincipal(
@Nonnull @NotEmpty @ParameterName(name = "classRef") final String classRef); @Override @Nonnull @NotEmpty String getName(); @Override int hashCode(); @Override boolean equals(final Object other); @Override String toString(); @Override AuthenticationContextClassReferencePrincipal clone(); static final String UNSPECIFIED; }### Answer:
@Test public void testEquals() { Assert.assertNotEquals(principal, null); Assert.assertEquals(principal, principal); Assert.assertEquals(principal, new AuthenticationContextClassReferencePrincipal("testvalue")); Assert.assertNotEquals(principal, new AuthenticationContextClassReferencePrincipal("testvalue2")); } |
### Question:
ServiceableProviderMetadataProvider extends AbstractServiceableComponent<ProviderMetadataResolver> implements RefreshableProviderMetadataResolver, Comparable<ServiceableProviderMetadataProvider> { @Override public void setId(@Nonnull @NotEmpty final String componentId) { super.setId(componentId); } ServiceableProviderMetadataProvider(); void setSortKey(final int key); @Nonnull void setEmbeddedResolver(@Nonnull final ProviderMetadataResolver theResolver); @Nonnull ProviderMetadataResolver getEmbeddedResolver(); @Override @Nonnull Iterable<OIDCProviderMetadata> resolve(final ProfileRequestContext profileRequestContext); @Override @Nullable OIDCProviderMetadata resolveSingle(@Nullable final ProfileRequestContext profileRequestContext); @Override void setId(@Nonnull @NotEmpty final String componentId); @Override @Nonnull ProviderMetadataResolver getComponent(); @Override void refresh(); @Override DateTime getLastRefresh(); @Override DateTime getLastUpdate(); @Override int compareTo(final ServiceableProviderMetadataProvider other); @Override boolean equals(final Object other); @Override int hashCode(); }### Answer:
@Test(expectedExceptions = ComponentInitializationException.class) public void testNoResolver() throws ComponentInitializationException { provider.setId("mockId"); provider.initialize(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.