auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Collection<CohortMembership> getMemberships() { if (memberships == null) { memberships = new TreeSet<>(); START } END return memberships; return memberships.stream().filter(m -> !m.isVoided()).collect(Collectors.toList()); } I think you may have forgotten to delete this line.

Target:
public Collection<CohortMembership> getMemberships() { if (memberships == null) { memberships = new TreeSet<>(); } return memberships; }
Source:
public void authenticate_shouldAuthenticateUserWithAlternateScheme() { // replay START Context.logout(); END Authenticated authenticated = Context.authenticate(new TestUsernameCredentials("admin")); // verif Assert.assertEquals("test-scheme", authenticated.getAuthenticationScheme()); Assert.assertEquals(Context.getAuthenticatedUser().getUuid(), authenticated.getUser().getUuid()); Assert.assertEquals("admin", Context.getAuthenticatedUser().getUsername()); } Do we need the above line? What happens if we get rid of it?

Target:
public void authenticate_shouldAuthenticateUserWithAlternateScheme() { // replay Authenticated authenticated = Context.authenticate(new TestUsernameCredentials("admin")); // verif Assert.assertEquals("test-scheme", authenticated.getAuthenticationScheme()); Assert.assertEquals(Context.getAuthenticatedUser().getUuid(), authenticated.getUser().getUuid()); Assert.assertEquals("admin", Context.getAuthenticatedUser().getUsername()); }
Source:
public void equal_shouldReturnFalseIfObjectIsNull() { // A null argument to equal should not lead to an exception CohortMembership cohortMembership = new CohortMembership(12); START boolean result = cohortMembership.equals(null); END assertFalse(result); } I guess we could just assert without the temporary result variable.

Target:
public void equal_shouldReturnFalseIfObjectIsNull() { // A null argument to equal should not lead to an exception CohortMembership cohortMembership = new CohortMembership(12); assertFalse(cohortMembership.equals(null)); }
Source:
START public void confirmNoKnownAllergies() throws RuntimeException { END if (!allergies.isEmpty()) { throw new APIException("Cannot confirm no known allergies if allergy list is not empty"); } allergyStatus = NO_KNOWN_ALLERGIES; } @manuelkollus Are you sure this is what was required? According to me, Its quiet superfluous to add a `throws` clause of a ` RuntimeException` since as a matter of fact its an unchecked `Exception`.

Target:
public void confirmNoKnownAllergies() throws APIException { if (!allergies.isEmpty()) { throw new APIException("Cannot confirm no known allergies if allergy list is not empty"); } allergyStatus = NO_KNOWN_ALLERGIES; }
Source:
START public Optional<String> getLatestSchemaSnapshotFilename() { Optional<String> snapshotVersion = getLatestSnapshotVersion(); if (snapshotVersion.isPresent()) { return Optional .of(SCHEMA_ONLY_FOLDER_NAME + File.separator + SCHEMA_ONLY_BASE_NAME + snapshotVersion.get() + DOT_XML); } return Optional.empty(); } END This can be reduced to: ```java return getLatestLiquibaseSnapshotVersion().map( snapshotVersion -> LIQUIBASE_SNAPSHOTS_FOLDER + File.separator + snapshotVersion + File.separator + LIQUIBASE_CORE_DATA_FILENAME); ``` Not that you need to make that change.

Target:
public Optional<String> getLatestSchemaSnapshotFilename() { return getLatestSnapshotVersion().map( snapshotVersion -> SCHEMA_ONLY_FOLDER_NAME + File.separator + SCHEMA_ONLY_BASE_NAME + snapshotVersion + DOT_XML); }
Source:
protected void dropAllDatabaseObjects() throws SQLException { Statement statement = null; try { statement = connection.createStatement(); String query = "DROP ALL OBJECTS"; statement.execute(query); } catch (JdbcSQLNonTransientException e) { START log.info("connection is already closed, most likely a test method already dropped all database objects"); END } finally { connection.close(); } } `log.info` or `log.error`?

Target:
protected void dropAllDatabaseObjects() throws SQLException { Statement statement = null; try { statement = connection.createStatement(); String query = "DROP ALL OBJECTS"; statement.execute(query); } catch (JdbcSQLNonTransientException e) { log.error("connection is already closed, most likely a test method already dropped all database objects"); } finally { connection.close(); } }
Source:
public User getUserByUsernameOrEmail(String usernameOrEmail) { if (StringUtils.isNotBlank(usernameOrEmail)) { User user = dao.getUserByEmail(usernameOrEmail); if (user == null) { return getUserByUsername(usernameOrEmail); START } else { END return user; } } throw new APIException("error.usernameOrEmail.notNullOrBlank", (Object[]) null); } This else clause is redundant since the else clause always returns, just return the user

Target:
public User getUserByUsernameOrEmail(String usernameOrEmail) { if (StringUtils.isNotBlank(usernameOrEmail)) { User user = dao.getUserByEmail(usernameOrEmail); if (user == null) { return getUserByUsername(usernameOrEmail); } return user; } throw new APIException("error.usernameOrEmail.notNullOrBlank", (Object[]) null); }
Source:
public void removeGlobalPropertyListener_shouldNotFailOnNullListener() { GlobalPropertyListener globalPropertyListener = null; START assertNull(globalPropertyListener); END adminService.removeGlobalPropertyListener(globalPropertyListener); } no need to assert its null, you set it to null the line above. you can simply inline this temp variable to ```java adminService.removeGlobalPropertyListener(null) ```

Target:
public void removeGlobalPropertyListener_shouldNotFailOnNullListener() { adminService.removeGlobalPropertyListener(null); }
Source:
public List<Diagnosis> getDiagnoses(Patient patient, Date fromDate) { START return diagnosisDAO.getActiveDiagnoses(patient); END } Did you intentionally ignore the fromDate parameter?

Target:
public List<Diagnosis> getDiagnoses(Patient patient, Date fromDate) { return diagnosisDAO.getActiveDiagnoses(patient, fromDate); }
Source:
public void shouldGetDiagnoses() { Encounter encounter = new Encounter(3); START List<Diagnosis> firstDiagnoses= diagnosisDAO.getDiagnoses(encounter); END assertEquals(2, firstDiagnoses.size()); Encounter otherEncounter = new Encounter(9); List<Diagnosis> secondDiagnoses= diagnosisDAO.getDiagnoses(otherEncounter); assertEquals(0, secondDiagnoses.size()); } Does the patient actually have any voided diagnoses to make this test more solid?

Target:
public void shouldGetDiagnoses() { assertEquals(2, diagnosisDAO.getDiagnoses(new Encounter(3)).size()); assertEquals(0, diagnosisDAO.getDiagnoses(new Encounter(9)).size()); }
Source:
public void shouldGetActiveDiagnoses() { START Patient patient = new Patient(2); END List<Diagnosis> activeDiagnosis = diagnosisDAO.getActiveDiagnoses(patient); assertEquals(2, activeDiagnosis.size()); } We can get rid of the above variable

Target:
public void shouldGetActiveDiagnoses() { assertEquals(2, diagnosisDAO.getActiveDiagnoses(new Patient(2)).size()); }
Source:
START public Condition getConditionByUuid(String uuid) { END if(log.isInfoEnabled()){ log.info("Getting condition with uuid " + uuid); } return conditionDAO.getConditionByUuid(uuid); } This is unncessary

Target:
public Condition getConditionByUuid(String uuid) { return conditionDAO.getConditionByUuid(uuid); }
Source:
START public List<Condition> getActiveConditions(Patient patient) { END if(log.isInfoEnabled()){ log.info("Getting active conditions with patient " + patient); } return conditionDAO.getActiveConditions(patient); } Can you remove this too

Target:
public List<Condition> getActiveConditions(Patient patient) { return conditionDAO.getActiveConditions(patient); }
Source:
START public Condition unvoidCondition(Condition condition) throws APIException { END condition.setVoided(false); condition.setVoidedBy(null); condition.setDateVoided(null); condition.setVoidReason(null); Context.getConditionService().saveCondition(condition); return condition; } Did you look at the ObsServiceImpl's unvoidObs()?

Target:
public Condition unvoidCondition(Condition condition) { return Context.getConditionService().saveCondition(condition); }
Source:
START public Condition saveCondition(Condition condition) throws APIException { END return conditionDAO.saveCondition(condition); } You will not need this after putting it at the class level

Target:
public Condition saveCondition(Condition condition) { return conditionDAO.saveCondition(condition); }
Source:
START public void purgeCondition(Condition condition) throws APIException { END conditionDAO.deleteCondition(condition); } Actually it's pointless to include the throws clause since APIException is a runtime exception that doesn't need to be caught.

Target:
public void purgeCondition(Condition condition) { conditionDAO.deleteCondition(condition); }
Source:
public User getUserByUsername(String username) throws APIException { START User user = dao.getUserByUsername(username); END if (isDaemon(user)) { log.warn("requested User '" + username + "' is Daemon"); return null; } return user; } This should not be changed, you should only be changing search methods

Target:
public User getUserByUsername(String username) throws APIException { return dao.getUserByUsername(username); }
Source:
public User getUser(Integer userId) throws APIException { START User user = dao.getUser(userId); END if (isDaemon(user)) { log.warn("requested User of Id '" + userId + "' is Daemon"); return null; } return user; } This should not be changed, you should only be changing search methods

Target:
public User getUser(Integer userId) throws APIException { return dao.getUser(userId); }
Source:
public List<User> getUsersByRole(Role role) throws APIException { List<Role> roles = new ArrayList<>(); roles.add(role); START return removeDaemonUsers(Context.getUserService().getUsers(null, roles, false)); END } Shouldn't you be doing in this DAO in the query?

Target:
public List<User> getUsersByRole(Role role) throws APIException { List<Role> roles = new ArrayList<>(); roles.add(role); return Context.getUserService().getUsers(null, roles, false); }
Source:
public void validate(Object object, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "condition", "field.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "clinicalStatus", "field.required"); if(object == null){ throw new IllegalArgumentException("The object parameter should not be null"); } if(!(object instanceof Condition)){ throw new IllegalArgumentException("The object parameter should be of type " + Condition.class); } START END } Are you in position to create some tests for this class? Take a look at these examples: https://github.com/openmrs/openmrs-core/tree/master/api/src/test/java/org/openmrs/validator

Target:
public void validate(Object object, Errors errors) { if(object == null){ throw new IllegalArgumentException("The object parameter should not be null"); } if(!(object instanceof Condition)){ throw new IllegalArgumentException("The object parameter should be of type " + Condition.class); } }
Source:
public void getGlobalPropertyValue_shouldFailIfDefaultValueIsNull() { exception.expect(IllegalArgumentException.class); START exception.expectMessage("The defaultValue argument cannot be null"); END adminService.getGlobalPropertyValue("valid.double", null); } in this test I suggest not to use the junit rule. since `getGlobalPropertyValue` only throws an `IllegalArgumentException` in one case, therefore its clear what case you are testing and we do not have to bind our test to the exception message. you can thus remove the junit rule code and replace it with ```java @Test(expected = IllegalArgumentException.class) ```

Target:
public void getGlobalPropertyValue_shouldFailIfDefaultValueIsNull() { adminService.getGlobalPropertyValue("valid.double", null); }
Source:
private static String getPasswordEncodeFailMessage(String algo) { START String errorMessage = "Can't encode password because the given algorithm: " + algo + " was not found! (fail)"; END return errorMessage; } Why assign to a variable just for the sake of returning?

Target:
private static String getPasswordEncodeFailMessage(String algo) { return "Can't encode password because the given algorithm: " + algo + " was not found! (fail)"; }
Source:
public void setPatientProgram(PatientProgram patientProgram) { START setOwner(new PatientProgram()); END } Did you intentionally ignore the patientProgram parameter?

Target:
public void setPatientProgram(PatientProgram patientProgram) { setOwner(patientProgram); }
Source:
public static List<Integer> delimitedStringToIntegerList(String delimitedString, String delimiter) { List<Integer> ret = new ArrayList<>(); String[] tokens = delimitedString.split(delimiter); for (String token : tokens) { token = token.trim(); if (token.length() == 0) { } else { ret.add(Integer.valueOf(token)); START } END } return ret; } Can't we simplify this by only having an if statement without else?

Target:
public static List<Integer> delimitedStringToIntegerList(String delimitedString, String delimiter) { List<Integer> ret = new ArrayList<>(); String[] tokens = delimitedString.split(delimiter); for (String token : tokens) { token = token.trim(); if (token.length() != 0) { ret.add(Integer.valueOf(token)); } } return ret; }
Source:
public void setPatientProgram(PatientProgram patientProgram) { START setOwner(new PatientProgram(patientProgram)); END } This should just set patientProgram without creating another instance

Target:
public void setPatientProgram(PatientProgram patientProgram) { setOwner(patientProgram); }
Source:
private void ensureProgramIsSet(ProgramWorkflow workflow, Program program) throws APIException { START if (workflow.getConcept() == null) { END throw new APIException("ProgramWorkflow.concept.required", (Object[]) null); } if (workflow.getProgram() == null) { workflow.setProgram(program); } else if (!workflow.getProgram().equals(program)) { throw new APIException("Program.error.contains.ProgramWorkflow", new Object[] { workflow.getProgram() }); } } please move the getConcept branch out of this one since this has nothing to do with ensuring the program is set. sorry for this, was probably due to the line numbers in the issue have moved since the code changed in the meanwhile.

Target:
private void ensureProgramIsSet(ProgramWorkflow workflow, Program program) { if (workflow.getProgram() == null) { workflow.setProgram(program); } else if (!workflow.getProgram().equals(program)) { throw new APIException("Program.error.contains.ProgramWorkflow", new Object[] { workflow.getProgram() }); } }
Source:
public Obs getRevisionObs(Obs initialObs) { Obs revisedObs = dao.getRevisionObs(initialObs); if (revisedObs != null && revisedObs.getVoided()) { START revisedObs = getRevisionObs(revisedObs); END } return revisedObs; } The api shouldn't be the one to recursively fetch revisions, the api caller could actually be interested in the immediate revision for some reason, so it's up to the client code to recursively do this.

Target:
public Obs getRevisionObs(Obs initialObs) { return dao.getRevisionObs(initialObs); }
Source:
public void retireConcept_shouldRetireTheGivenConcept() throws Exception { START int drugId = 3; END String retireReason = "dummy reason"; Concept concept = conceptService.getConcept(drugId); assertFalse(concept.isRetired()); conceptService.retireConcept(concept, retireReason); assertTrue(concept.isRetired()); assertEquals(retireReason, concept.getRetireReason()); } you dont need this local variable, only when using the same value more than once. like you did with the retireReason.

Target:
public void retireConcept_shouldRetireTheGivenConcept() throws Exception { String retireReason = "dummy reason"; Concept concept = conceptService.getConcept(3); assertFalse(concept.isRetired()); conceptService.retireConcept(concept, retireReason); assertTrue(concept.isRetired()); assertEquals(retireReason, concept.getRetireReason()); }
Source:
START public static boolean copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { END if (inputStream == null || outputStream == null) { if (outputStream != null) { IOUtils.closeQuietly(outputStream); } return false; } try { IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(outputStream); return true; } } dear @lkukielka changing the method signature was not part of the ticket. this would break compatibility with users of this method so please revert that change.

Target:
public static void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { if (inputStream == null || outputStream == null) { if (outputStream != null) { IOUtils.closeQuietly(outputStream); } return; } try { IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(outputStream); } }
Source:
START public void expandJar_shouldExpandEntireJarIfNameIsNull() throws IOException { END // Arrange final int numberOfFilesInJar = 6; File destinationFolder = this.getEmptyJarDestinationFolder(); // Act ModuleUtil.expandJar(getJarFile(), destinationFolder, null, false); // Assert Assert.assertEquals(numberOfFilesInJar, FileUtils.listFiles(destinationFolder, null, true).size()); // Clean up FileUtils.deleteDirectory(destinationFolder); } Can you please use the openmrs generate test case plugin, see https://wiki.openmrs.org/display/docs/Generate+Test+Case+Plugin You used the old test style and the generator will easily create the scaffold for you in the new style :)

Target:
public void expandJar_shouldExpandEntireJarIfNameIsNull() throws Exception { final int numberOfFilesInJar = 6; File destinationFolder = this.getEmptyJarDestinationFolder(); ModuleUtil.expandJar(getJarFile(), destinationFolder, null, false); Assert.assertEquals(numberOfFilesInJar, FileUtils.listFiles(destinationFolder, null, true).size()); FileUtils.deleteDirectory(destinationFolder); }
Source:
public boolean contains(Patient patient) { START return getMembers() != null && getMembers().stream() END .anyMatch(m -> m.getPatientId().getPatientId().equals(patient.getPatientId())); } Probably we should add a TODO item here that this needs to be changed to compare the Patient objects instead of their ids when we finally remove the deprecated methods that take ids

Target:
public boolean contains(Patient patient) { return contains(patient.getPatientId()); }
Source:
START private void setCohort(Cohort cohort) { END this.cohort = cohort; } With access set to field in the hbm file you probably don't need this private setter

Target:
protected void setCohort(Cohort cohort) { this.cohort = cohort; }
Source:
START private Cohort getCohort() { END return cohort; } The getter has to be public, only the setter should be private

Target:
public Cohort getCohort() { return cohort; }
Source:
public Cohort addMembershipToCohort(Cohort cohort, CohortMembership cohortMembership) throws APIException { if (!cohort.contains(cohortMembership)) { START ValidateUtil.validate(cohortMembership); END cohort.addMembership(cohortMembership); Context.getCohortService().saveCohort(cohort); } return cohort; } All validation should be handled in the CohortValidator, if it doesn't exist we need to add it

Target:
public Cohort addMembershipToCohort(Cohort cohort, CohortMembership cohortMembership) throws APIException { cohort.addMembership(cohortMembership); Context.getCohortService().saveCohort(cohort); return cohort; }
Source:
public void removePatientFromCohort_shouldNotFailIfCohortDoesNotContainPatient() throws Exception { executeDataSet(COHORT_XML); // make a patient Patient patientToAddThenRemove = new Patient(4); // verify that the patient is not already in the Cohort START assertFalse(service.getCohort(2).contains(patientToAddThenRemove.getPatientId())); END // try to remove it from the cohort without failing try { service.removePatientFromCohort(service.getCohort(2), patientToAddThenRemove); } catch (Exception e) { Assert.fail("removePatientFromCohort(Cohort,Patient) should not fail if cohort doesn't contain patient"); } } I would imagine that you have a new contains method that takes in patient object that internally delegates to the old one so you wouldn't need these changes

Target:
public void removePatientFromCohort_shouldNotFailIfCohortDoesNotContainPatient() throws Exception { executeDataSet(COHORT_XML); // make a patient Patient patientToAddThenRemove = new Patient(4); // verify that the patient is not already in the Cohort assertFalse(service.getCohort(2).contains(patientToAddThenRemove)); // try to remove it from the cohort without failing try { service.removePatientFromCohort(service.getCohort(2), patientToAddThenRemove); } catch (Exception e) { Assert.fail("removePatientFromCohort(Cohort,Patient) should not fail if cohort doesn't contain patient"); } }
Source:
public void addMembershipToCohort_shouldAddMembershipToCohort() throws Exception { executeDataSet(COHORT_XML); START END CohortMembership memberToAdd = new CohortMembership(new Patient(4)); service.addMembershipToCohort(service.getCohort(1), memberToAdd); assertTrue(service.getCohort(1).contains(memberToAdd)); } Would nice to have a sanity check that the cohort doesn't contain an active membership for the patient before

Target:
public void addMembershipToCohort_shouldAddMembershipToCohort() throws Exception { executeDataSet(COHORT_XML); Patient p = new Patient(4); CohortMembership memberToAdd = new CohortMembership(p); service.addMembershipToCohort(service.getCohort(1), memberToAdd); assertTrue(service.getCohort(1).contains(p)); }
Source:
public boolean isMemberActive() { START return this.getStartDate().before(new Date()) && this.getEndDate() == null; END } End could be null and the memebership is active depending on the passed in asOfDate that I mentioned above

Target:
public boolean isMemberActive() { return this.getStartDate() != null && this.getStartDate().before(new Date()) && this.getEndDate() == null; }
Source:
public void getAttribute_shouldReturnNullWhenExistingPersonAttributeTypeIsVoided () throws Exception { Person person = personHelper(true, 1, 2, 3, "name1", "name2", "name3", "value1", "value2", "value3"); PersonAttributeType type = new PersonAttributeType(new Integer(3)); type.setName("name3"); START Assert.assertNull(null, person.getAttribute(type)); END } This is incorrect, it should be `Assert.assertNull(person.getAttribute(type));`

Target:
public void getAttribute_shouldReturnNullWhenExistingPersonAttributeTypeIsVoided () throws Exception { Person person = personHelper(true, 1, 2, 3, "name1", "name2", "name3", "value1", "value2", "value3"); PersonAttributeType type = new PersonAttributeType(new Integer(3)); type.setName("name3"); Assert.assertNull(person.getAttribute(type)); }
Source:
public OrderSet retireOrderSet(OrderSet orderSet, String retireReason) throws APIException { if (!StringUtils.hasLength(retireReason)) { throw new IllegalArgumentException("reitreReason cannot be empty or null"); } START orderSet.setRetireReason(retireReason); END return saveOrderSetInternal(orderSet); } AOP around retire methods i believe already sets the reason

Target:
public OrderSet retireOrderSet(OrderSet orderSet, String retireReason) throws APIException { if (!StringUtils.hasLength(retireReason)) { throw new IllegalArgumentException("reitreReason cannot be empty or null"); } return saveOrderSetInternal(orderSet); }
Source:
public void copy_shouldCopyAllDrugOrderFields() throws Exception { DrugOrder drugOrder = new DrugOrder(); Drug drug = new Drug(); drug.setConcept(new Concept()); drugOrder.setDrug(drug); START OrderTest.assertThatAllFieldsAreCopied(drugOrder, null, "orderGroup", "sortWeight"); END } This is not correct, orderGroup and sortWeight need to be copied too, this should stay unchanged instead you update Order.copy to copy over these fields too

Target:
public void copy_shouldCopyAllDrugOrderFields() throws Exception { DrugOrder drugOrder = new DrugOrder(); Drug drug = new Drug(); drug.setConcept(new Concept()); drugOrder.setDrug(drug); OrderTest.assertThatAllFieldsAreCopied(drugOrder, null); }
Source:
public void cloneForRevision_shouldSetAllTheRelevantFields() throws Exception { DrugOrder drugOrder = new DrugOrder(); Drug drug = new Drug(); drug.setConcept(new Concept()); drugOrder.setDrug(drug); OrderTest.assertThatAllFieldsAreCopied(drugOrder, "cloneForRevision", "creator", "dateCreated", "action", "changedBy", "dateChanged", "voided", "dateVoided", "voidedBy", "voidReason", "encounter", "orderNumber", START "orderer", "previousOrder", "dateActivated", "dateStopped", "accessionNumber", "orderGroup", END "sortWeight"); } Same here, orderGroup and sortWeight need to be cloned and you undo this change

Target:
public void cloneForRevision_shouldSetAllTheRelevantFields() throws Exception { DrugOrder drugOrder = new DrugOrder(); Drug drug = new Drug(); drug.setConcept(new Concept()); drugOrder.setDrug(drug); OrderTest.assertThatAllFieldsAreCopied(drugOrder, "cloneForRevision", "creator", "dateCreated", "action", "changedBy", "dateChanged", "voided", "dateVoided", "voidedBy", "voidReason", "encounter", "orderNumber", "orderer", "previousOrder", "dateActivated", "dateStopped", "accessionNumber"); }
Source:
public void copy_shouldCopyAllFields() throws Exception { START assertThatAllFieldsAreCopied(new Order(), null, "orderGroup", "sortWeight"); END assertThatAllFieldsAreCopied(new TestOrder(), null, "orderGroup", "sortWeight"); } This needs to be undone

Target:
public void copy_shouldCopyAllFields() throws Exception { assertThatAllFieldsAreCopied(new Order(), null); assertThatAllFieldsAreCopied(new TestOrder(), null); }
Source:
public void copy_shouldCopyAllTestOrderFields() throws Exception { START OrderTest.assertThatAllFieldsAreCopied(new TestOrder(), null, "orderGroup", "sortWeight"); END } You need to undo this

Target:
public void copy_shouldCopyAllTestOrderFields() throws Exception { OrderTest.assertThatAllFieldsAreCopied(new TestOrder(), null); }
Source:
protected TestOrder cloneForRevisionHelper(TestOrder target) { super.cloneForRevisionHelper(target); target.setSpecimenSource(getSpecimenSource()); target.setLaterality(getLaterality()); target.setClinicalHistory(getClinicalHistory()); target.setFrequency(getFrequency()); target.setNumberOfRepeats(getNumberOfRepeats()); target.setOrderGroup(getOrderGroup()); START target.setSortWeight(getSortWeight()); END return target; } Aren't we doing this in the superclass?

Target:
protected TestOrder cloneForRevisionHelper(TestOrder target) { super.cloneForRevisionHelper(target); target.setSpecimenSource(getSpecimenSource()); target.setLaterality(getLaterality()); target.setClinicalHistory(getClinicalHistory()); target.setFrequency(getFrequency()); target.setNumberOfRepeats(getNumberOfRepeats()); return target; }
Source:
public String getMessage(MessageSourceResolvable resolvable, Locale locale) { START if((resolvable.getCodes()[0]) == (activeMessageSource.getMessage(resolvable, locale))){ END return (resolvable.getCodes()[(resolvable.getCodes().length) - 1]); } else{ return activeMessageSource.getMessage(resolvable, locale); } } I thought you are comparing strings, right? So i would expect use of equals

Target:
public String getMessage(MessageSourceResolvable resolvable, Locale locale) { if((resolvable.getCodes()[0]).equals((activeMessageSource.getMessage(resolvable, locale)))){ return (resolvable.getCodes()[(resolvable.getCodes().length) - 1]); } else{ return activeMessageSource.getMessage(resolvable, locale); } }
Source:
public void hasSameOrderableAs_shouldReturnFalseIfTheConceptsMatchAndHaveDifferentDrugNonCoded() throws Exception { DrugOrder order = new DrugOrder(); Concept concept = new Concept(); START order.setDrugNonCoded("Chrocine"); END DrugOrder otherOrder = new DrugOrder(); otherOrder.setConcept(concept); otherOrder.setDrugNonCoded("paracetemol"); assertFalse(order.hasSameOrderableAs(otherOrder)); } You forgot to set concept on this first order

Target:
public void hasSameOrderableAs_shouldReturnFalseIfTheConceptsMatchAndHaveDifferentDrugNonCoded() throws Exception { DrugOrder order = new DrugOrder(); Concept concept = new Concept(); order.setConcept(concept); order.setDrugNonCoded("Chrocine"); DrugOrder otherOrder = new DrugOrder(); otherOrder.setConcept(concept); otherOrder.setDrugNonCoded("paracetemol"); assertFalse(order.hasSameOrderableAs(otherOrder)); }
Source:
public void hasSameOrderableAs_shouldReturnTrueIfTheConceptsMatchAndHaveSameDrugNonCoded() throws Exception { DrugOrder order = new DrugOrder(); Concept concept = new Concept(); Drug drug1 = new Drug(); drug1.setConcept(concept); START order.setDrug(drug1); END order.setDrugNonCoded("Chrocine"); DrugOrder otherOrder = new DrugOrder(); otherOrder.setConcept(concept); otherOrder.setDrug(drug1); otherOrder.setDrugNonCoded("chrocine"); assertTrue(order.hasSameOrderableAs(otherOrder)); } I thought drug should be null for a nonCoded order, but i see you are setting it here

Target:
public void hasSameOrderableAs_shouldReturnTrueIfTheConceptsMatchAndHaveSameDrugNonCoded() throws Exception { DrugOrder order = new DrugOrder(); Concept concept = new Concept(); order.setConcept(concept); order.setDrugNonCoded("Chrocine"); DrugOrder otherOrder = new DrugOrder(); otherOrder.setConcept(concept); otherOrder.setDrugNonCoded("chrocine"); assertTrue(order.hasSameOrderableAs(otherOrder)); }
Source:
public void hasSameOrderableAs_shouldReturnFalseIfTheConceptsMatchAndEitherOfDrugNonCodedIsNull() throws Exception { START DrugOrder order = new DrugOrder(); END Concept concept = new Concept(); order.setDrugNonCoded("Chrocine"); DrugOrder otherOrder = new DrugOrder(); otherOrder.setConcept(concept); assertFalse(order.hasSameOrderableAs(otherOrder)); } Forgot to set set concept on this order

Target:
public void hasSameOrderableAs_shouldReturnFalseIfTheConceptsMatchAndEitherOfDrugNonCodedIsNull() throws Exception { DrugOrder order = new DrugOrder(); Concept concept = new Concept(); order.setConcept(concept); order.setDrugNonCoded("Chrocine"); DrugOrder otherOrder = new DrugOrder(); otherOrder.setConcept(concept); assertFalse(order.hasSameOrderableAs(otherOrder)); }
Source:
private DrugOrder checkDrugOrdersForDiscontinuing(DrugOrder drugOrder1, DrugOrder drugOrder2){ if (OpenmrsUtil.nullSafeEquals(drugOrder1.getDrug(), drugOrder2.getDrug())) { return drugOrder2; START }else{ END return null; } } You don't need the else clause, it is redundant, just return null

Target:
private DrugOrder checkDrugOrdersForDiscontinuing(DrugOrder drugOrder1, DrugOrder drugOrder2){ if (OpenmrsUtil.nullSafeEquals(drugOrder1.getDrug(), drugOrder2.getDrug())) { return drugOrder2; } return null; }
Source:
START public ServletInputStream getInputStream() throws IOException { END if (stream == null) { stream = createInputStream(); } return (stream); } Any methods that override should be annotated with @Override. Otherwise I can't quickly say if it is correct or not.

Target:
public ServletInputStream getInputStream() throws IOException { return stream; }
Source:
START public static void setStaticUnknownConcept(Concept currentUnknownConcept) { END ConceptServiceImpl.unknownConcept = currentUnknownConcept; } It should be private.

Target:
private static void setStaticUnknownConcept(Concept currentUnknownConcept) { ConceptServiceImpl.unknownConcept = currentUnknownConcept; }
Source:
START public static void setStaticHandlers(Map<String, ComplexObsHandler> currentHandlers) { END ObsServiceImpl.handlers = currentHandlers; } It should be private.

Target:
private static void setStaticHandlers(Map<String, ComplexObsHandler> currentHandlers) { ObsServiceImpl.handlers = currentHandlers; }
Source:
START public static void setStaticIdentifierValidators( END Map<Class<? extends IdentifierValidator>, IdentifierValidator> currentIdentifierValidators) { PatientServiceImpl.identifierValidators = currentIdentifierValidators; } It should be private.

Target:
private static void setStaticIdentifierValidators( Map<Class<? extends IdentifierValidator>, IdentifierValidator> currentIdentifierValidators) { PatientServiceImpl.identifierValidators = currentIdentifierValidators; }
Source:
public static Thread runInNewDaemonThread(final Runnable runnable) { // make sure we're already in a daemon thread if (!isDaemonThread()) { throw new APIAuthenticationException("Only daemon threads can spawn new daemon threads"); } // we should consider making DaemonThread public, so the caller can access returnedObject and exceptionThrown DaemonThread thread = new DaemonThread() { @Override public void run() { isDaemonThread.set(true); try { Context.openSession(); START new Thread(runnable).start(); END } finally { Context.closeSession(); } } }; thread.start(); return thread; } This is actually intended as you can see the start method is called below in line 189: thread.start() so please revert it. We need to annotate the run method (line 177) with: @SuppressWarnings("squid:3AS1217") //We intentionally do not start a new thread yet, rather wrap the run call in a session.

Target:
public static Thread runInNewDaemonThread(final Runnable runnable) { // make sure we're already in a daemon thread if (!isDaemonThread()) { throw new APIAuthenticationException("Only daemon threads can spawn new daemon threads"); } // we should consider making DaemonThread public, so the caller can access returnedObject and exceptionThrown DaemonThread thread = new DaemonThread() { @Override public void run() { isDaemonThread.set(true); try { Context.openSession(); runnable.run(); } finally { Context.closeSession(); } } }; thread.start(); return thread; }
Source:
public static Thread runInDaemonThread(final Runnable runnable, DaemonToken token) { if (!ModuleFactory.isTokenValid(token)) { throw new ContextAuthenticationException("Invalid token " + token); } DaemonThread thread = new DaemonThread() { @Override public void run() { isDaemonThread.set(true); try { Context.openSession(); START new Thread(runnable).start(); END } finally { Context.closeSession(); } } }; thread.start(); return thread; } This is actually intended as you can see the start method is called below. Please revert it. We need to annotate the run method (line 270) with: @SuppressWarnings("squid:3AS1217") //We intentionally do not start a new thread yet, rather wrap the run call in a session.

Target:
public static Thread runInDaemonThread(final Runnable runnable, DaemonToken token) { if (!ModuleFactory.isTokenValid(token)) { throw new ContextAuthenticationException("Invalid token " + token); } DaemonThread thread = new DaemonThread() { @Override public void run() { isDaemonThread.set(true); try { Context.openSession(); runnable.run(); } finally { Context.closeSession(); } } }; thread.start(); return thread; }
Source:
public void saveGlobalProperties_shouldAssignUuidToAllNewProperties() throws Exception { // get the current global properties List<GlobalProperty> globalProperties = Context.getAdministrationService().getAllGlobalProperties(); START globalProperties.remove(3); END // and now add a new one to it and save it globalProperties.add(new GlobalProperty("new prop", "new prop value", "desc")); Context.getAdministrationService().saveGlobalProperties(globalProperties); Assert.assertNotNull(Context.getAdministrationService().getGlobalPropertyObject("new prop").getUuid()); } If you have to remove it then seems like there is something else wrong that needs to get fixed, could be the test data that is invalid because you should never have to do this.

Target:
public void saveGlobalProperties_shouldAssignUuidToAllNewProperties() throws Exception { // get the current global properties List<GlobalProperty> globalProperties = Context.getAdministrationService().getAllGlobalProperties(); // and now add a new one to it and save it globalProperties.add(new GlobalProperty("new prop", "new prop value", "desc")); Context.getAdministrationService().saveGlobalProperties(globalProperties); Assert.assertNotNull(Context.getAdministrationService().getGlobalPropertyObject("new prop").getUuid()); }
Source:
public boolean isOrderTypeInUse(OrderType orderType) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Order.class); criteria.add(Restrictions.eq("orderType", orderType)); START if (criteria.list().size() > 0) { END return true; } return false; } this could all be one line i.e: return criteria.list() > 0

Target:
public boolean isOrderTypeInUse(OrderType orderType) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Order.class); criteria.add(Restrictions.eq("orderType", orderType)); return criteria.list().size() > 0; }
Source:
public OrderType unretireOrderType(OrderType orderType) { START orderType.setRetired(false); END return dao.saveOrderType(orderType); } same here, don't set fields, just call save here

Target:
public OrderType unretireOrderType(OrderType orderType) { orderType.setRetired(false); return saveOrderType(orderType); }
Source:
public Order cloneForDiscontinuing() { DrugOrder newOrder = new DrugOrder(); newOrder.setCareSetting(this.getCareSetting()); newOrder.setConcept(this.getConcept()); newOrder.setAction(Action.DISCONTINUE); newOrder.setPreviousOrder(this); newOrder.setPatient(this.getPatient()); newOrder.setDrug(this.getDrug()); newOrder.setStartDate(this.getStartDate()); START newOrder.setOrderer(this.getOrderer()); END return newOrder; } This is not right because the provider who prescribed the order is not always going to be the same person to discontinue it, so don't copy this field

Target:
public Order cloneForDiscontinuing() { DrugOrder newOrder = new DrugOrder(); newOrder.setCareSetting(this.getCareSetting()); newOrder.setConcept(this.getConcept()); newOrder.setAction(Action.DISCONTINUE); newOrder.setPreviousOrder(this); newOrder.setPatient(this.getPatient()); newOrder.setDrug(this.getDrug()); newOrder.setStartDate(this.getStartDate()); return newOrder; }
Source:
public Order cloneForDiscontinuing() { Order newOrder = new Order(); newOrder.setCareSetting(this.getCareSetting()); newOrder.setConcept(this.getConcept()); newOrder.setAction(Action.DISCONTINUE); newOrder.setPreviousOrder(this); newOrder.setPatient(this.getPatient()); START newOrder.setOrderer(this.getOrderer()); END newOrder.setStartDate(this.getStartDate()); return newOrder; } same here, don't copy orderer

Target:
public Order cloneForDiscontinuing() { Order newOrder = new Order(); newOrder.setCareSetting(this.getCareSetting()); newOrder.setConcept(this.getConcept()); newOrder.setAction(Action.DISCONTINUE); newOrder.setPreviousOrder(this); newOrder.setPatient(this.getPatient()); newOrder.setStartDate(this.getStartDate()); return newOrder; }
Source:
START public Collection<DrugReferenceMap> getDrugReferenceMaps() { END if (drugReferenceMaps == null) { drugReferenceMaps = Collections.EMPTY_LIST; } return drugReferenceMaps; } I think this should be a set, @djazayeri isn't the convention supposed to be a set

Target:
public Set<DrugReferenceMap> getDrugReferenceMaps() { if (drugReferenceMaps == null) { drugReferenceMaps = new HashSet<DrugReferenceMap>(); } return drugReferenceMaps; }
Source:
START public CustomDatatype.Summary toHtmlSummary(CustomDatatype<T> datatype, String valueReference) { END SerializingCustomDatatype<T> dt = (SerializingCustomDatatype<T>) datatype; return new CustomDatatype.Summary(dt.deserialize(valueReference).getName(), true); } To avoid duplicating code, you should call to to Html() below to fetch the name

Target:
public CustomDatatype.Summary toHtmlSummary(CustomDatatype<T> datatype, String valueReference) { return toHtmlSummary(datatype, valueReference); }
Source:
START public EncounterType saveEncounterType(EncounterType encounterType) throws EncounterTypeLockedException { END sessionFactory.getCurrentSession().saveOrUpdate(encounterType); return encounterType; } In the DAO we don't throw APIExceptions and its subclasses in general, so you can remove this

Target:
public EncounterType saveEncounterType(EncounterType encounterType) { sessionFactory.getCurrentSession().saveOrUpdate(encounterType); return encounterType; }
Source:
public ActiveListItem deleteActiveListItem(ActiveListItem item) throws DAOException { sessionFactory.getCurrentSession().delete(item); START return null; END } No reason to return null. make this a void

Target:
public void deleteActiveListItem(ActiveListItem item) throws DAOException { sessionFactory.getCurrentSession().delete(item); }
Source:
private String setupState(Response response) { String sessionId = UUID.randomUUID().toString(); byte[] secret = new byte[20]; random.nextBytes(secret); START String state = java.util.Base64.getEncoder().encodeToString(secret); END CookieSetting cs = new CookieSetting("_state", sessionId); response.getCookieSettings().add(cs); getContext().getAttributes().put(sessionId, state); return state; } Why the fully qualified class name ?

Target:
private String setupState(Response response) { String sessionId = UUID.randomUUID().toString(); byte[] secret = new byte[20]; random.nextBytes(secret); String state = Base64.getEncoder().encodeToString(secret); CookieSetting cs = new CookieSetting("_state", sessionId); response.getCookieSettings().add(cs); getContext().getAttributes().put(sessionId, state); return state; }
Source:
public static String processResourceName(String uri) { START String processedUri = ""; END String[] split = uri.replaceAll("\\{", "").replaceAll("\\}", "") .split("/"); for (String str : split) { processedUri += StringUtils.firstUpper(str); } return processedUri; } If you need to build a string on several instruction (other that `"a" + "b" + "c"`), use a `StringBuilder`

Target:
public static String processResourceName(String uri) { StringBuilder sb = new StringBuilder(); String[] split = uri.replaceAll("\\{", "").replaceAll("\\}", "") .split("/"); for (String str : split) { sb.append(StringUtils.firstUpper(str)); } return sb.toString(); }
Source:
START public List<InvoiceItem> createExternalCharges(final Iterable<InvoiceItem> externalCharges, @Nullable final LocalDate requestedDate, final Boolean autoPay, final Boolean autoCommit, final String createdBy, final String reason, final String comment) throws KillBillClientException { END return createExternalCharges(externalCharges, requestedDate, autoPay, autoCommit, null, null, RequestOptions.builder() .withCreatedBy(createdBy) .withReason(reason) .withComment(comment).build()); } That one should be `@Deprecated` (no `RequestOptions`).

Target:
public List<InvoiceItem> createExternalCharges(final Iterable<InvoiceItem> externalCharges, @Nullable final LocalDate requestedDate, final Boolean autoPay, final Boolean autoCommit, final String createdBy, final String reason, final String comment) throws KillBillClientException { return createExternalCharges(externalCharges, requestedDate, autoPay, autoCommit, RequestOptions.builder() .withCreatedBy(createdBy) .withReason(reason) .withComment(comment).build()); }
Source:
START } catch (ClassNotFoundException onlyIfOpenTestIsNotAvailable) { END try { Class.forName("junit.framework.ComparisonFailure"); theFactory = new ExceptionFactoryImpl() { @Override public AssertionError create(String message, String wanted, String actual) { return new org.mockito.exceptions.verification.junit.ArgumentsAreDifferent(message, wanted, actual); } }; } catch (ClassNotFoundException onlyIfJUnitIsNotAvailable) { } } Great feedback. Thanks for taking the time. mostly what prompted by suggestion is that I was concerned that `Class.forName(...);` may be optimized away by an aggressive optimizer if its result is unused. Though my concerns may be unfounded, since it throws checked exceptions, so it has a potential side-effect. 🤷‍♂

Target:
} catch (ClassNotFoundException onlyIfOpenTestIsNotAvailable) { try { Class.forName("junit.framework.ComparisonFailure"); theFactory = org.mockito.exceptions.verification.junit.ArgumentsAreDifferent::new; } catch (ClassNotFoundException onlyIfJUnitIsNotAvailable) { } }
Source:
START protected void validateMatchers(Invocation invocation, List<LocalizedMatcher> lastMatchers) { END if (!lastMatchers.isEmpty()) { int recordedMatchersSize = lastMatchers.size(); int expectedMatchersSize = invocation.getArguments().length; if (expectedMatchersSize != recordedMatchersSize) { throw invalidUseOfMatchers(expectedMatchersSize, lastMatchers); } } } What is the reasoning for making this protected? It is an internal class, so it should not be subclassed.

Target:
private void validateMatchers(Invocation invocation, List<LocalizedMatcher> lastMatchers) { if (!lastMatchers.isEmpty()) { int recordedMatchersSize = lastMatchers.size(); int expectedMatchersSize = invocation.getArguments().length; if (expectedMatchersSize != recordedMatchersSize) { throw invalidUseOfMatchers(expectedMatchersSize, lastMatchers); } } }
Source:
public OngoingStubbing<T> thenThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown) { if (nextToBeThrown == null) { START return abortNullExceptionType(); END } OngoingStubbing<T> stubbing = thenThrow(toBeThrown); for (Class<? extends Throwable> t : nextToBeThrown) { stubbing = stubbing.thenThrow(t); } return stubbing; } This looks like a change in behavior. What is driving this? We are very careful when making changes in behavior that can cause issues when migrating to newer version of Mockito.

Target:
public OngoingStubbing<T> thenThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown) { if (nextToBeThrown == null) { return thenThrow((Class<Throwable>) null); } OngoingStubbing<T> stubbing = thenThrow(toBeThrown); for (Class<? extends Throwable> t : nextToBeThrown) { stubbing = stubbing.thenThrow(t); } return stubbing; }
Source:
public Object answer(InvocationOnMock invocation) throws Throwable { if (throwable == null) { START throw new IllegalStateException("throwable is null: " + END "you shall not call #answer if #validateFor fails!"); } if (MockUtil.isMock(throwable)) { throw throwable; } throwable.fillInStackTrace(); filter.filter(throwable); throw throwable; } This exception message is not consistent with how we handle exceptions. Take a look at a Reporter class. Typically we throw an exception that is or derives from MockitoException. The message needs to be very clean, actionable to the end user. I suggest to create a high level unit test that demonstrates this use case from the standpoint of the end user. Run this test, observe the exception, would a newbie Mockito understand the exception message and was able to resolve the problem quickly?

Target:
public Object answer(InvocationOnMock invocation) throws Throwable { if (throwable == null) { throw new IllegalStateException("throwable is null: " + "you shall not call #answer if #validateFor fails!"); } if (MockUtil.isMock(throwable)) { throw throwable; } Throwable t = throwable.fillInStackTrace(); if (t == null) { //Custom exceptions sometimes return null, see #866 throw throwable; } filter.filter(t); throw t; }
Source:
private static String createAllLocationsMessage(List<Location> locations) { if (locations == null) { return "\n"; } StringBuilder sb = new StringBuilder(); for (Location invocation : locations) { START sb.append(invocation).append("\n"); END } return sb.toString(); } `infocation` → `location`?

Target:
private static String createAllLocationsMessage(List<Location> locations) { if (locations == null) { return "\n"; } StringBuilder sb = new StringBuilder(); for (Location location : locations) { sb.append(location).append("\n"); } return sb.toString(); }
Source:
START public Invocation createInvocation(Object target, MockCreationSettings settings, Method method, final Callable realMethod, Object... args) { END RealMethod.FromCallable superMethod = new RealMethod.FromCallable(realMethod); return MockMethodInterceptor.createInvocation(target, method, args, superMethod, settings); } Nit: no need to add `final` here

Target:
public Invocation createInvocation(Object target, MockCreationSettings settings, Method method, final Callable realMethod, Object... args) { RealMethod superMethod = new RealMethod.FromCallable(realMethod); return createInvocation(target, settings, method, superMethod, args); }
Source:
public MockMethodAdvice(WeakConcurrentMap<Object, MockMethodInterceptor> interceptors, String identifier) { this.interceptors = interceptors; this.identifier = identifier; try { Field field = WeakConcurrentMap.class.getDeclaredField("target"); field.setAccessible(true); backingMap = field.get(interceptors); } catch (Exception e) { START throw new MockitoException("Could not resolve backing map from concurrent hash map", e); END } } Can we make the message more actionable? Is there anything the user can do? File a ticket?

Target:
public MockMethodAdvice(WeakConcurrentMap<Object, MockMethodInterceptor> interceptors, String identifier) { this.interceptors = interceptors; this.identifier = identifier; }