diff --git a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/AllergyIntoleranceMapperTest.java b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/AllergyIntoleranceMapperTest.java index dc18c4dcb..7066fadce 100644 --- a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/AllergyIntoleranceMapperTest.java +++ b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/AllergyIntoleranceMapperTest.java @@ -44,6 +44,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.api.Nested; import org.mockito.ArgumentCaptor; import org.mockito.Captor; @@ -113,478 +114,478 @@ class AllergyIntoleranceMapperTest { @InjectMocks private AllergyIntoleranceMapper allergyIntoleranceMapper; - @BeforeEach - void beforeEach() { - Mockito.lenient() - .when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - any(String.class), any(Optional.class), any(Optional.class) - )).thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); - } - - @Test - void testGivenDrugAllergyWithAllDataThenAllDataPopulated() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("drug-allergy-structure.xml"); - - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(defaultCodeableConcept()) - .thenReturn(secondaryCodeableConcept()); - - final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), - getEncounterList(), PRACTISE_CODE); - - assertThat(allergyIntolerances).hasSize(1); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); - - assertFixedValues(allergyIntolerance); - assertExtension(allergyIntolerance); - - assertThat(allergyIntolerance.getCategory().getFirst().getValue()).isEqualTo(MEDICATION); - assertThat(allergyIntolerance.getAssertedDateElement().asStringValue()).isEqualTo("1978-12-31"); - assertThat(allergyIntolerance.getRecorder().getReference()).isEqualTo("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D"); - assertThat(allergyIntolerance.getOnsetDateTimeType().asStringValue()) - .isEqualTo(DateFormatUtil.parseToDateTimeType("19781231").asStringValue()); - assertThat(allergyIntolerance.getAsserter().getReference()).isEqualTo("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D"); - assertThat(allergyIntolerance.getNote().getFirst().getText()).isEqualTo(EPISODICITY_WITH_ORIGINAL_TEXT_NOTE_TEXT); - assertThat(allergyIntolerance.getNote().get(1).getText()).isEqualTo(PERTINENT_NOTE_TEXT); - assertThat(allergyIntolerance.getNote().get(2).getText()).isEqualTo(ALLERGY_NOTE_TEXT); - assertThat(allergyIntolerance.getCode().getCodingFirstRep()).isEqualTo(DegradedCodeableConcepts.DEGRADED_DRUG_ALLERGY); - assertThat(allergyIntolerance.getCode().getCoding().get(1).getDisplay()).isEqualTo(CODING_DISPLAY_2); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); - } - - @Test - void testGivenAuthorAndParticipantThenMapsToRecorderAndAsserterAllergyIntolerance() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("allergy-structure-with-valid-author-and-participant2.xml"); - - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(defaultCodeableConcept()) - .thenReturn(secondaryCodeableConcept()); - - final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), - getEncounterList(), PRACTISE_CODE); - - assertEquals(1, allergyIntolerances.size()); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); - - assertAll( - () -> assertExtension(allergyIntolerance), - () -> assertEquals("Practitioner/9F2ABD26-1682-FDFE-1E88-19673307C67A", allergyIntolerance.getAsserter().getReference()), - () -> assertEquals("Practitioner/E7E7B550-09EF-BE85-C20F-34598014166C", allergyIntolerance.getRecorder().getReference()) - ); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); - } - - /** - * At this moment it is not very clear if this is the correct behavior. - * We haven't seen a supplier send over a HL7 in this form, but we want to specify some behaviour. - */ @Test - void testGivenAuthorAndAutParticipant2AuthorAndRecorderThenPopulatedWithParticipant2() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("allergy-structure-with-participant-of-aut-typecode.xml"); + void testGivenAllergyIntoleranceWithNopatConfidentialityCodePresentWithinEhrCompositionExpectMetaSecurityAdded() { + final Meta stubbedMeta = MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE); + final RCMRMT030101UKEhrExtract ehrExtract = + unmarshallEhrExtract("allergy-structure-with-ehr-composition-nopat-confidentiality-code.xml"); - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(defaultCodeableConcept()) - .thenReturn(secondaryCodeableConcept()); + Mockito + .when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( + any(String.class), any(Optional.class), any(Optional.class) + )).thenReturn(stubbedMeta); - final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), - getEncounterList(), PRACTISE_CODE); + final RCMRMT030101UKEhrComposition ehrComposition = TestUtility.GET_EHR_COMPOSITION.apply(ehrExtract); + final List allergyIntolerance = allergyIntoleranceMapper + .mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); - assertEquals(1, allergyIntolerances.size()); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + final Meta meta = allergyIntolerance.getFirst().getMeta(); - assertAll( - () -> assertExtension(allergyIntolerance), - () -> assertEquals("Practitioner/9F2ABD26-1682-FDFE-1E88-19673307C67A", allergyIntolerance.getRecorder().getReference()), - () -> assertEquals("Practitioner/9F2ABD26-1682-FDFE-1E88-19673307C67A", allergyIntolerance.getAsserter().getReference()) - ); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + assertMetaSecurityPresent(meta); + verifyConfidentialityServiceCalled(1, ehrComposition.getConfidentialityCode(), Optional.empty()); } - /** - * At this moment it is not very clear if this is the correct behavior with such number of participants. - * We haven't seen a supplier send over a HL7 in this form, but we want to specify some behaviour. - */ @Test - void testGivenAuthorAndMultipleParticipant2sAndOneAutParticipant2AuthorAndRecorderThenPopulatedWithAuthorAndParticipant2() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("allergy-structure-with-author-and-multiple-participants.xml"); - - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(defaultCodeableConcept()) - .thenReturn(secondaryCodeableConcept()); + void testGivenAllergyIntoleranceWithNopatConfidentialityCodePresentWithinObservationStatementExpectMetaSecurityAdded() { + final Meta stubbedMeta = MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE); + final RCMRMT030101UKEhrExtract ehrExtract = + unmarshallEhrExtract("allergy-structure-with-observation-statement-nopat-confidentiality-code.xml"); - final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), - getEncounterList(), PRACTISE_CODE); + Mockito + .when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( + any(String.class), any(Optional.class), any(Optional.class) + )).thenReturn(stubbedMeta); - assertEquals(1, allergyIntolerances.size()); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + final RCMRMT030101UKObservationStatement observationStatement = GET_OBSERVATION_STATEMENT.apply(ehrExtract); + final List allergyIntolerance = allergyIntoleranceMapper + .mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); - assertAll( - () -> assertExtension(allergyIntolerance), - () -> assertEquals("Practitioner/9F2ABD26-1682-FDFE-1E88-19673307C67A", allergyIntolerance.getAsserter().getReference()), - () -> assertEquals("Practitioner/E7E7B550-09EF-BE85-C20F-34598014166C", allergyIntolerance.getRecorder().getReference()) - ); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); - } + final Meta meta = allergyIntolerance.getFirst().getMeta(); - @Test - void testGivenNonDrugAllergyWithAllDataThenMapsSuccessfully() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("non-drug-allergy-structure.xml"); - - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(defaultCodeableConcept()) - .thenReturn(secondaryCodeableConcept()); - - final List allergyIntolerances - = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); - - assertEquals(1, allergyIntolerances.size()); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); - - assertFixedValues(allergyIntolerance); - - assertExtension(allergyIntolerance); - assertEquals(ENVIRONMENT, allergyIntolerance.getCategory().getFirst().getValue()); - assertEquals("1978-12-31", allergyIntolerance.getAssertedDateElement().asStringValue()); - assertEquals("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D", allergyIntolerance.getRecorder().getReference()); - assertEquals(DateFormatUtil.parseToDateTimeType("19781231").asStringValue(), - allergyIntolerance.getOnsetDateTimeType().asStringValue()); - assertEquals("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D", allergyIntolerance.getAsserter().getReference()); - assertEquals(PERTINENT_NOTE_TEXT, allergyIntolerance.getNote().getFirst().getText()); - assertEquals(DegradedCodeableConcepts.DEGRADED_NON_DRUG_ALLERGY, allergyIntolerance.getCode().getCodingFirstRep()); - assertEquals(CODING_DISPLAY_1, allergyIntolerance.getCode().getCoding().get(1).getDisplay()); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + assertMetaSecurityPresent(meta); + verifyConfidentialityServiceCalled(1, Optional.empty(), observationStatement.getConfidentialityCode()); } - @Test - void testGivenCompoundStatementCodeOfNonDrugAllergyCodeThenSetsCodeToTransferDegradedNonDrugAllergy() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("degraded-non-drug-allergy-structure.xml"); - - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(new CodeableConcept()); - - final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), - getEncounterList(), PRACTISE_CODE); + @Nested + class MetaAndSecurityCodesPresentTests { + @BeforeEach + void beforeEach() { + Mockito.when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( + any(String.class), any(Optional.class), any(Optional.class) + )).thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); + } - assertThat(allergyIntolerances).hasSize(1); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + @Test + void testGivenDrugAllergyWithAllDataThenAllDataPopulated() { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("drug-allergy-structure.xml"); - assertThat(allergyIntolerance.getCode().getCodingFirstRep()) - .isEqualTo(DegradedCodeableConcepts.DEGRADED_NON_DRUG_ALLERGY); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); - } - - @Test - void testGivenCompoundStatementCodeOfDrugAllergyCodeThenSetsCodeToTransferDegradedDrugAllergy() { - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(nonSnomedCodeableConcept()); + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(defaultCodeableConcept()) + .thenReturn(secondaryCodeableConcept()); - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("degraded-drug-allergy-structure.xml"); - final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), + final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); - assertThat(allergyIntolerances).hasSize(1); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); - - assertThat(allergyIntolerance.getCode().getCodingFirstRep()) - .isEqualTo(DegradedCodeableConcepts.DEGRADED_DRUG_ALLERGY); - - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); - } + assertThat(allergyIntolerances).hasSize(1); + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + + assertFixedValues(allergyIntolerance); + assertExtension(allergyIntolerance); + + assertThat(allergyIntolerance.getCategory().getFirst().getValue()).isEqualTo(MEDICATION); + assertThat(allergyIntolerance.getAssertedDateElement().asStringValue()).isEqualTo("1978-12-31"); + assertThat(allergyIntolerance.getRecorder().getReference()).isEqualTo("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D"); + assertThat(allergyIntolerance.getOnsetDateTimeType().asStringValue()) + .isEqualTo(DateFormatUtil.parseToDateTimeType("19781231").asStringValue()); + assertThat(allergyIntolerance.getAsserter().getReference()).isEqualTo("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D"); + assertThat(allergyIntolerance.getNote().getFirst().getText()).isEqualTo(EPISODICITY_WITH_ORIGINAL_TEXT_NOTE_TEXT); + assertThat(allergyIntolerance.getNote().get(1).getText()).isEqualTo(PERTINENT_NOTE_TEXT); + assertThat(allergyIntolerance.getNote().get(2).getText()).isEqualTo(ALLERGY_NOTE_TEXT); + assertThat(allergyIntolerance.getCode().getCodingFirstRep()).isEqualTo(DegradedCodeableConcepts.DEGRADED_DRUG_ALLERGY); + assertThat(allergyIntolerance.getCode().getCoding().get(1).getDisplay()).isEqualTo(CODING_DISPLAY_2); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } + + @Test + void testGivenAuthorAndParticipantThenMapsToRecorderAndAsserterAllergyIntolerance() { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("allergy-structure-with-valid-author-and-participant2.xml"); + + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(defaultCodeableConcept()) + .thenReturn(secondaryCodeableConcept()); + + final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), + getEncounterList(), PRACTISE_CODE); - @Test - void testGivenAllergyWithOriginalTextAndNoValueThenMapsCodingTextFromCodeOriginalText() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("allergy-structure-with-original-text-in-code.xml"); + assertEquals(1, allergyIntolerances.size()); + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + + assertAll( + () -> assertExtension(allergyIntolerance), + () -> assertEquals("Practitioner/9F2ABD26-1682-FDFE-1E88-19673307C67A", allergyIntolerance.getAsserter().getReference()), + () -> assertEquals("Practitioner/E7E7B550-09EF-BE85-C20F-34598014166C", allergyIntolerance.getRecorder().getReference()) + ); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } + + /** + * At this moment it is not very clear if this is the correct behavior. + * We haven't seen a supplier send over a HL7 in this form, but we want to specify some behaviour. + */ + @Test + void testGivenAuthorAndAutParticipant2AuthorAndRecorderThenPopulatedWithParticipant2() { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("allergy-structure-with-participant-of-aut-typecode.xml"); + + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(defaultCodeableConcept()) + .thenReturn(secondaryCodeableConcept()); + + final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), + getEncounterList(), PRACTISE_CODE); - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(defaultCodeableConcept()) - .thenReturn(secondaryCodeableConcept()); + assertEquals(1, allergyIntolerances.size()); + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + + assertAll( + () -> assertExtension(allergyIntolerance), + () -> assertEquals("Practitioner/9F2ABD26-1682-FDFE-1E88-19673307C67A", allergyIntolerance.getRecorder().getReference()), + () -> assertEquals("Practitioner/9F2ABD26-1682-FDFE-1E88-19673307C67A", allergyIntolerance.getAsserter().getReference()) + ); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } + + /** + * At this moment it is not very clear if this is the correct behavior with such number of participants. + * We haven't seen a supplier send over a HL7 in this form, but we want to specify some behaviour. + */ + @Test + void testGivenAuthorAndMultipleParticipant2sAndOneAutParticipant2AuthorAndRecorderThenPopulatedWithAuthorAndParticipant2() { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("allergy-structure-with-author-and-multiple-participants.xml"); + + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(defaultCodeableConcept()) + .thenReturn(secondaryCodeableConcept()); + + final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), + getEncounterList(), PRACTISE_CODE); - final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), - getEncounterList(), PRACTISE_CODE); + assertEquals(1, allergyIntolerances.size()); + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + + assertAll( + () -> assertExtension(allergyIntolerance), + () -> assertEquals("Practitioner/9F2ABD26-1682-FDFE-1E88-19673307C67A", allergyIntolerance.getAsserter().getReference()), + () -> assertEquals("Practitioner/E7E7B550-09EF-BE85-C20F-34598014166C", allergyIntolerance.getRecorder().getReference()) + ); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } + + @Test + void testGivenNonDrugAllergyWithAllDataThenMapsSuccessfully() { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("non-drug-allergy-structure.xml"); + + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(defaultCodeableConcept()) + .thenReturn(secondaryCodeableConcept()); + + final List allergyIntolerances + = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); + + assertEquals(1, allergyIntolerances.size()); + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + + assertFixedValues(allergyIntolerance); + + assertExtension(allergyIntolerance); + assertEquals(ENVIRONMENT, allergyIntolerance.getCategory().getFirst().getValue()); + assertEquals("1978-12-31", allergyIntolerance.getAssertedDateElement().asStringValue()); + assertEquals("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D", allergyIntolerance.getRecorder().getReference()); + assertEquals(DateFormatUtil.parseToDateTimeType("19781231").asStringValue(), + allergyIntolerance.getOnsetDateTimeType().asStringValue()); + assertEquals("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D", allergyIntolerance.getAsserter().getReference()); + assertEquals(PERTINENT_NOTE_TEXT, allergyIntolerance.getNote().getFirst().getText()); + assertEquals(DegradedCodeableConcepts.DEGRADED_NON_DRUG_ALLERGY, allergyIntolerance.getCode().getCodingFirstRep()); + assertEquals(CODING_DISPLAY_1, allergyIntolerance.getCode().getCoding().get(1).getDisplay()); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } + + @Test + void testGivenCompoundStatementCodeOfNonDrugAllergyCodeThenSetsCodeToTransferDegradedNonDrugAllergy() { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("degraded-non-drug-allergy-structure.xml"); + + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(new CodeableConcept()); + + final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), + getEncounterList(), PRACTISE_CODE); - assertThat(allergyIntolerances).hasSize(1); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + assertThat(allergyIntolerances).hasSize(1); + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); - assertFixedValues(allergyIntolerance); + assertThat(allergyIntolerance.getCode().getCodingFirstRep()) + .isEqualTo(DegradedCodeableConcepts.DEGRADED_NON_DRUG_ALLERGY); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } - assertThat(allergyIntolerance.getCode().getText()).isEqualTo(ORIGINAL_TEXT_IN_CODE); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); - } + @Test + void testGivenCompoundStatementCodeOfDrugAllergyCodeThenSetsCodeToTransferDegradedDrugAllergy() { + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(nonSnomedCodeableConcept()); - @Test - void testGivenAllergyWithNoOptionalData() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("allergy-structure-with-optional-data.xml"); - - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(defaultCodeableConcept()); - - final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), - getEncounterList(), PRACTISE_CODE); - - assertThat(allergyIntolerances).hasSize(1); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); - assertFixedValues(allergyIntolerance); - assertThat(allergyIntolerance.getCode().getCodingFirstRep()).isEqualTo(DegradedCodeableConcepts.DEGRADED_DRUG_ALLERGY); - assertThat(allergyIntolerance.getCode().getCoding().get(1).getDisplay()).isEqualTo(CODING_DISPLAY_1); - assertThat(allergyIntolerance.getAssertedDateElement().asStringValue()).isEqualTo("2019-07-08T13:35:00+00:00"); - assertNull(allergyIntolerance.getRecorder().getReference()); // this is added later in the UnknownPractitionerHandler - assertNull(allergyIntolerance.getAsserter().getReference()); - assertNull(allergyIntolerance.getOnset()); - assertThat(allergyIntolerance.getNote()).isEmpty(); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); - } + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("degraded-drug-allergy-structure.xml"); + final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), + getEncounterList(), PRACTISE_CODE); - @Test - void testGivenUnkAvailabilityTimeThenAssertedDateIsAuthorTime() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("allergy-structure-with-asserted-date-fallback.xml"); + assertThat(allergyIntolerances).hasSize(1); + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(defaultCodeableConcept()); + assertThat(allergyIntolerance.getCode().getCodingFirstRep()) + .isEqualTo(DegradedCodeableConcepts.DEGRADED_DRUG_ALLERGY); - final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), - getEncounterList(), PRACTISE_CODE); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } - assertThat(allergyIntolerances).hasSize(1); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + @Test + void testGivenAllergyWithOriginalTextAndNoValueThenMapsCodingTextFromCodeOriginalText() { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("allergy-structure-with-original-text-in-code.xml"); - assertFixedValues(allergyIntolerance); + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(defaultCodeableConcept()) + .thenReturn(secondaryCodeableConcept()); - assertThat(allergyIntolerance.getAssertedDateElement().asStringValue()).isEqualTo("2010-02-09T12:31:51+00:00"); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); - } + final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), + getEncounterList(), PRACTISE_CODE); - @Test - void testGivenMultipleAllergiesThenExpectAllToBePresent() { - final RCMRMT030101UKEhrExtract ehrExtract = - unmarshallEhrExtract("allergy-structure-with-multiple-allergy.xml"); + assertThat(allergyIntolerances).hasSize(1); + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(defaultCodeableConcept()); + assertFixedValues(allergyIntolerance); - final List allergyIntolerances - = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); + assertThat(allergyIntolerance.getCode().getText()).isEqualTo(ORIGINAL_TEXT_IN_CODE); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } - assertEquals(THREE, allergyIntolerances.size()); - verifyConfidentialityServiceCalled(THREE, Optional.empty(), Optional.empty()); - } + @Test + void testGivenAllergyWithNoOptionalData() { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("allergy-structure-with-optional-data.xml"); - @Test - void testGivenAllergyIntoleranceWithNopatConfidentialityCodePresentWithinEhrCompositionExpectMetaSecurityAdded() { - final Meta stubbedMeta = MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE); - final RCMRMT030101UKEhrExtract ehrExtract = - unmarshallEhrExtract("allergy-structure-with-ehr-composition-nopat-confidentiality-code.xml"); + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(defaultCodeableConcept()); - Mockito - .lenient() - .when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - any(String.class), any(Optional.class), any(Optional.class) - )).thenReturn(stubbedMeta); + final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), + getEncounterList(), PRACTISE_CODE); - final RCMRMT030101UKEhrComposition ehrComposition = TestUtility.GET_EHR_COMPOSITION.apply(ehrExtract); - final List allergyIntolerance = allergyIntoleranceMapper - .mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); + assertThat(allergyIntolerances).hasSize(1); + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + assertFixedValues(allergyIntolerance); + assertThat(allergyIntolerance.getCode().getCodingFirstRep()).isEqualTo(DegradedCodeableConcepts.DEGRADED_DRUG_ALLERGY); + assertThat(allergyIntolerance.getCode().getCoding().get(1).getDisplay()).isEqualTo(CODING_DISPLAY_1); + assertThat(allergyIntolerance.getAssertedDateElement().asStringValue()).isEqualTo("2019-07-08T13:35:00+00:00"); + assertNull(allergyIntolerance.getRecorder().getReference()); // this is added later in the UnknownPractitionerHandler + assertNull(allergyIntolerance.getAsserter().getReference()); + assertNull(allergyIntolerance.getOnset()); + assertThat(allergyIntolerance.getNote()).isEmpty(); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } + + @Test + void testGivenUnkAvailabilityTimeThenAssertedDateIsAuthorTime() { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("allergy-structure-with-asserted-date-fallback.xml"); + + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(defaultCodeableConcept()); + + final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), + getEncounterList(), PRACTISE_CODE); - final Meta meta = allergyIntolerance.getFirst().getMeta(); + assertThat(allergyIntolerances).hasSize(1); + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); - assertMetaSecurityPresent(meta); - verifyConfidentialityServiceCalled(1, ehrComposition.getConfidentialityCode(), Optional.empty()); - } + assertFixedValues(allergyIntolerance); - @Test - void testGivenAllergyIntoleranceWithNopatConfidentialityCodePresentWithinObservationStatementExpectMetaSecurityAdded() { - final Meta stubbedMeta = MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE); - final RCMRMT030101UKEhrExtract ehrExtract = - unmarshallEhrExtract("allergy-structure-with-observation-statement-nopat-confidentiality-code.xml"); + assertThat(allergyIntolerance.getAssertedDateElement().asStringValue()).isEqualTo("2010-02-09T12:31:51+00:00"); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } - Mockito - .lenient() - .when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - any(String.class), any(Optional.class), any(Optional.class) - )).thenReturn(stubbedMeta); + @Test + void testGivenMultipleAllergiesThenExpectAllToBePresent() { + final RCMRMT030101UKEhrExtract ehrExtract = + unmarshallEhrExtract("allergy-structure-with-multiple-allergy.xml"); - final RCMRMT030101UKObservationStatement observationStatement = GET_OBSERVATION_STATEMENT.apply(ehrExtract); - final List allergyIntolerance = allergyIntoleranceMapper - .mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(defaultCodeableConcept()); - final Meta meta = allergyIntolerance.getFirst().getMeta(); + final List allergyIntolerances + = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); - assertMetaSecurityPresent(meta); - verifyConfidentialityServiceCalled(1, Optional.empty(), observationStatement.getConfidentialityCode()); - } + assertEquals(THREE, allergyIntolerances.size()); + verifyConfidentialityServiceCalled(THREE, Optional.empty(), Optional.empty()); + } - @Test - void testGivenAllergyIntoleranceWithNoscrubConfidentialityCodePresentWithinObservationStatementExpectMetaSecurityNotAdded() { - final RCMRMT030101UKEhrExtract ehrExtract = - unmarshallEhrExtract("allergy-structure-with-observation-statement-noscrub-confidentiality-code.xml"); + @Test + void testGivenAllergyIntoleranceWithNoscrubConfidentialityCodePresentWithinObservationStatementExpectMetaSecurityNotAdded() { + final RCMRMT030101UKEhrExtract ehrExtract = + unmarshallEhrExtract("allergy-structure-with-observation-statement-noscrub-confidentiality-code.xml"); - final RCMRMT030101UKObservationStatement observationStatement = GET_OBSERVATION_STATEMENT.apply(ehrExtract); - final List allergyIntolerance = allergyIntoleranceMapper - .mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); + final RCMRMT030101UKObservationStatement observationStatement = GET_OBSERVATION_STATEMENT.apply(ehrExtract); + final List allergyIntolerance = allergyIntoleranceMapper + .mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); - assertThat(allergyIntolerance.getFirst().getMeta().getSecurity()).isEmpty(); - verifyConfidentialityServiceCalled(1, Optional.empty(), observationStatement.getConfidentialityCode()); - } + assertThat(allergyIntolerance.getFirst().getMeta().getSecurity()).isEmpty(); + verifyConfidentialityServiceCalled(1, Optional.empty(), observationStatement.getConfidentialityCode()); + } - @Test - void testGivenStandaloneAllergyThenNoExtensionPresent() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("allergy-structure-invalid-encounter-reference.xml"); + @Test + void testGivenStandaloneAllergyThenNoExtensionPresent() { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("allergy-structure-invalid-encounter-reference.xml"); - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(defaultCodeableConcept()); + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(defaultCodeableConcept()); - final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), - getEncounterList(), PRACTISE_CODE); + final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), + getEncounterList(), PRACTISE_CODE); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); - assertThat(allergyIntolerance.getExtension()).isEmpty(); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); - } + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + assertThat(allergyIntolerance.getExtension()).isEmpty(); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } - @Test - void testGivenAllergyWithSameTermTexts() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("drug-allergy-structure-with-term-text.xml"); - - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(defaultCodeableConcept()); - - final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), - getEncounterList(), PRACTISE_CODE); - - assertThat(allergyIntolerances).hasSize(1); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); - - assertFixedValues(allergyIntolerance); - - assertExtension(allergyIntolerance); - assertThat(allergyIntolerance.getCategory().getFirst().getValue()).isEqualTo(MEDICATION); - assertThat(allergyIntolerance.getAssertedDateElement().asStringValue()).isEqualTo("1978-12-31"); - assertThat(allergyIntolerance.getRecorder().getReference()).isEqualTo("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D"); - assertThat(allergyIntolerance.getOnsetDateTimeType().asStringValue()) - .isEqualTo(DateFormatUtil.parseToDateTimeType("19781231").asStringValue()); - assertThat(allergyIntolerance.getAsserter().getReference()).isEqualTo("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D"); - assertThat(allergyIntolerance.getNote().getFirst().getText()).isEqualTo(PERTINENT_NOTE_TEXT); - assertThat(allergyIntolerance.getCode().getCodingFirstRep()).isEqualTo(DegradedCodeableConcepts.DEGRADED_DRUG_ALLERGY); - assertThat(allergyIntolerance.getCode().getCoding().get(1).getDisplay()).isEqualTo(CODING_DISPLAY_1); - assertThat(allergyIntolerance.getNote().size()).isOne(); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); - } + @Test + void testGivenAllergyWithSameTermTexts() { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("drug-allergy-structure-with-term-text.xml"); - @Test - void testMapAllergyWithDrugTermText() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("drug-allergy-structure-with-term-text.xml"); - - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(tertiaryCodeableConcept()) - .thenReturn(tertiaryCodeableConcept()); - - final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), - getEncounterList(), PRACTISE_CODE); - - assertThat(allergyIntolerances).hasSize(1); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); - - assertFixedValues(allergyIntolerance); - - assertExtension(allergyIntolerance); - assertThat(allergyIntolerance.getCategory().getFirst().getValue()).isEqualTo(MEDICATION); - assertThat(allergyIntolerance.getAssertedDateElement().asStringValue()).isEqualTo("1978-12-31"); - assertThat(allergyIntolerance.getRecorder().getReference()).isEqualTo("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D"); - assertThat(allergyIntolerance.getOnsetDateTimeType().asStringValue()) - .isEqualTo(DateFormatUtil.parseToDateTimeType("19781231").asStringValue()); - assertThat(allergyIntolerance.getAsserter().getReference()).isEqualTo("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D"); - assertThat(allergyIntolerance.getNote().getFirst().getText()).isEqualTo(PERTINENT_NOTE_TEXT); - assertThat(allergyIntolerance.getCode().getCodingFirstRep()).isEqualTo(DegradedCodeableConcepts.DEGRADED_DRUG_ALLERGY); - assertThat(allergyIntolerance.getCode().getCoding().get(1).getDisplay()).isEqualTo(CODING_DISPLAY_3); - assertThat(allergyIntolerance.getNote().size()).isOne(); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); - } + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(defaultCodeableConcept()); - @Test - void testGivenDrugAllergyWithValueElementThenMapsCodingTextFromValueDescription() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("drug-allergy-with-value.xml"); + final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), + getEncounterList(), PRACTISE_CODE); - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(defaultCodeableConcept()) - .thenReturn(secondaryCodeableConcept()); + assertThat(allergyIntolerances).hasSize(1); + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + + assertFixedValues(allergyIntolerance); + + assertExtension(allergyIntolerance); + assertThat(allergyIntolerance.getCategory().getFirst().getValue()).isEqualTo(MEDICATION); + assertThat(allergyIntolerance.getAssertedDateElement().asStringValue()).isEqualTo("1978-12-31"); + assertThat(allergyIntolerance.getRecorder().getReference()).isEqualTo("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D"); + assertThat(allergyIntolerance.getOnsetDateTimeType().asStringValue()) + .isEqualTo(DateFormatUtil.parseToDateTimeType("19781231").asStringValue()); + assertThat(allergyIntolerance.getAsserter().getReference()).isEqualTo("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D"); + assertThat(allergyIntolerance.getNote().getFirst().getText()).isEqualTo(PERTINENT_NOTE_TEXT); + assertThat(allergyIntolerance.getCode().getCodingFirstRep()).isEqualTo(DegradedCodeableConcepts.DEGRADED_DRUG_ALLERGY); + assertThat(allergyIntolerance.getCode().getCoding().get(1).getDisplay()).isEqualTo(CODING_DISPLAY_1); + assertThat(allergyIntolerance.getNote().size()).isOne(); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } + + @Test + void testMapAllergyWithDrugTermText() { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("drug-allergy-structure-with-term-text.xml"); + + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(tertiaryCodeableConcept()) + .thenReturn(tertiaryCodeableConcept()); + + final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), + getEncounterList(), PRACTISE_CODE); - final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), - getEncounterList(), PRACTISE_CODE); + assertThat(allergyIntolerances).hasSize(1); + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + + assertFixedValues(allergyIntolerance); + + assertExtension(allergyIntolerance); + assertThat(allergyIntolerance.getCategory().getFirst().getValue()).isEqualTo(MEDICATION); + assertThat(allergyIntolerance.getAssertedDateElement().asStringValue()).isEqualTo("1978-12-31"); + assertThat(allergyIntolerance.getRecorder().getReference()).isEqualTo("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D"); + assertThat(allergyIntolerance.getOnsetDateTimeType().asStringValue()) + .isEqualTo(DateFormatUtil.parseToDateTimeType("19781231").asStringValue()); + assertThat(allergyIntolerance.getAsserter().getReference()).isEqualTo("Practitioner/2D70F602-6BB1-47E0-B2EC-39912A59787D"); + assertThat(allergyIntolerance.getNote().getFirst().getText()).isEqualTo(PERTINENT_NOTE_TEXT); + assertThat(allergyIntolerance.getCode().getCodingFirstRep()).isEqualTo(DegradedCodeableConcepts.DEGRADED_DRUG_ALLERGY); + assertThat(allergyIntolerance.getCode().getCoding().get(1).getDisplay()).isEqualTo(CODING_DISPLAY_3); + assertThat(allergyIntolerance.getNote().size()).isOne(); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } + + @Test + void testGivenDrugAllergyWithValueElementThenMapsCodingTextFromValueDescription() { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("drug-allergy-with-value.xml"); + + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(defaultCodeableConcept()) + .thenReturn(secondaryCodeableConcept()); + + final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), + getEncounterList(), PRACTISE_CODE); - assertThat(allergyIntolerances).hasSize(1); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + assertThat(allergyIntolerances).hasSize(1); + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); - assertFixedValues(allergyIntolerance); + assertFixedValues(allergyIntolerance); - assertExtension(allergyIntolerance); + assertExtension(allergyIntolerance); - assertThat(allergyIntolerance.getCode().getText()).isEqualTo(DISPLAY_NAME_IN_VALUE); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); - } + assertThat(allergyIntolerance.getCode().getText()).isEqualTo(DISPLAY_NAME_IN_VALUE); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } - @Test - void testGivenAllergyIntoleranceWithQualifierAndOriginalTextThenNotesContainsEpisodicity() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("drug_allergy_with_qualifier_and_original_text.xml"); + @Test + void testGivenAllergyIntoleranceWithQualifierAndOriginalTextThenNotesContainsEpisodicity() { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("drug_allergy_with_qualifier_and_original_text.xml"); - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(defaultCodeableConcept()); + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(defaultCodeableConcept()); - final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), - getEncounterList(), PRACTISE_CODE); + final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), + getEncounterList(), PRACTISE_CODE); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); - assertThat(allergyIntolerance.getNote().getFirst().getText()).isEqualTo(EPISODICITY_WITH_ORIGINAL_TEXT_NOTE_TEXT); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); - } + assertThat(allergyIntolerance.getNote().getFirst().getText()).isEqualTo(EPISODICITY_WITH_ORIGINAL_TEXT_NOTE_TEXT); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } - @Test - void testGivenAllergyIntoleranceWithQualifierAndWithoutOriginalTextThenNotesContainsEpisodicity() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("drug_allergy_with_qualifier_without_original_text.xml"); + @Test + void testGivenAllergyIntoleranceWithQualifierAndWithoutOriginalTextThenNotesContainsEpisodicity() { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("drug_allergy_with_qualifier_without_original_text.xml"); - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(defaultCodeableConcept()); + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(defaultCodeableConcept()); - final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), - getEncounterList(), PRACTISE_CODE); + final List allergyIntolerances = allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), + getEncounterList(), PRACTISE_CODE); - final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); + final AllergyIntolerance allergyIntolerance = allergyIntolerances.getFirst(); - assertThat(allergyIntolerance.getNote().getFirst().getText()).isEqualTo(EPISODICITY_WITHOUT_ORIGINAL_TEXT_NOTE_TEXT); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); - } + assertThat(allergyIntolerance.getNote().getFirst().getText()).isEqualTo(EPISODICITY_WITHOUT_ORIGINAL_TEXT_NOTE_TEXT); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } - @ParameterizedTest - @MethodSource("allergyStructuresWithTranslations") - void testTppNamedSchemaInValue(String filename) { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract(filename); + @ParameterizedTest + @MethodSource("allergyStructuresWithTranslations") + void testTppNamedSchemaInValue(String filename) { + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract(filename); - when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) - .thenReturn(tertiaryCodeableConcept()); + when(codeableConceptMapper.mapToCodeableConcept(any(CD.class))) + .thenReturn(tertiaryCodeableConcept()); - allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); + allergyIntoleranceMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); - verify(codeableConceptMapper, times(2)).mapToCodeableConcept(cdCaptor.capture()); + verify(codeableConceptMapper, times(2)).mapToCodeableConcept(cdCaptor.capture()); - final CD cd = cdCaptor.getAllValues().get(1); + final CD cd = cdCaptor.getAllValues().get(1); - assertThat(cd.getCode()).isEqualTo(MULTILEX_COCONUT_OIL); - assertThat(cd.getCodeSystem()).isEqualTo(MULTILEX_CODE_SYSTEM); - assertThat(cd.getDisplayName()).isEqualTo(CODING_DISPLAY_4); - assertThat(cd.getTranslation().size()).isOne(); + assertThat(cd.getCode()).isEqualTo(MULTILEX_COCONUT_OIL); + assertThat(cd.getCodeSystem()).isEqualTo(MULTILEX_CODE_SYSTEM); + assertThat(cd.getDisplayName()).isEqualTo(CODING_DISPLAY_4); + assertThat(cd.getTranslation().size()).isOne(); - final CD translation = cd.getTranslation().getFirst(); + final CD translation = cd.getTranslation().getFirst(); - assertThat(translation.getCodeSystem()).isEqualTo(SNOMED_CODE_SYSTEM); - assertThat(translation.getCode()).isEqualTo(SNOMED_COCONUT_OIL); - assertThat(translation.getDisplayName()).isEqualTo(CODING_DISPLAY_4); - verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); - } + assertThat(translation.getCodeSystem()).isEqualTo(SNOMED_CODE_SYSTEM); + assertThat(translation.getCode()).isEqualTo(SNOMED_COCONUT_OIL); + assertThat(translation.getDisplayName()).isEqualTo(CODING_DISPLAY_4); + verifyConfidentialityServiceCalled(1, Optional.empty(), Optional.empty()); + } - private static Stream allergyStructuresWithTranslations() { - return Stream.of( - Arguments.of("allergy-structure-tpp-named-schema.xml"), - Arguments.of("allergy-structure-with-translations.xml") - ); + private static Stream allergyStructuresWithTranslations() { + return Stream.of( + Arguments.of("allergy-structure-tpp-named-schema.xml"), + Arguments.of("allergy-structure-with-translations.xml") + ); + } } private void assertFixedValues(AllergyIntolerance allergyIntolerance) { @@ -612,11 +613,11 @@ private void assertMetaSecurityPresent(Meta meta) { assertAll( () -> assertThat(meta.getSecurity()).hasSize(1), () -> assertThat(meta.getSecurity().getFirst().getCode()) - .isEqualTo("NOPAT"), + .isEqualTo("NOPAT"), () -> assertThat(meta.getSecurity().getFirst().getSystem()) - .isEqualTo("http://hl7.org/fhir/v3/ActCode"), + .isEqualTo("http://hl7.org/fhir/v3/ActCode"), () -> assertThat(meta.getSecurity().getFirst().getDisplay()) - .isEqualTo("no disclosure to patient, family or caregivers without attending provider's authorization") + .isEqualTo("no disclosure to patient, family or caregivers without attending provider's authorization") ); } @@ -660,7 +661,6 @@ private RCMRMT030101UKEhrExtract unmarshallEhrExtract(String fileName) { @SafeVarargs private void verifyConfidentialityServiceCalled(int expectedCalls, Optional... cvs) { - verify(confidentialityService, times(expectedCalls)) - .createMetaAndAddSecurityIfConfidentialityCodesPresent(META_PROFILE, cvs); + verify(confidentialityService, times(expectedCalls)).createMetaAndAddSecurityIfConfidentialityCodesPresent(META_PROFILE, cvs); } } \ No newline at end of file diff --git a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/BloodPressureMapperTest.java b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/BloodPressureMapperTest.java index bc7e8cb17..95cdbd5a6 100644 --- a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/BloodPressureMapperTest.java +++ b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/BloodPressureMapperTest.java @@ -8,7 +8,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.util.ResourceUtils.getFile; @@ -31,11 +30,10 @@ import org.hl7.v3.CV; import org.hl7.v3.RCMRMT030101UKEhrExtract; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; @@ -65,29 +63,29 @@ public class BloodPressureMapperTest { private static final String ISSUED_EXAMPLE = "2020-01-01T01:01:01.000+00:00"; private static final String PPRF_PARTICIPANT_ID = "Practitioner/5DE8CDDA-866F-4CD9-9BB3-527A86DD49A9"; private static final String COMMENT_EXAMPLE_1 = "Systolic Note: Test systolic pressure text " - + "Diastolic Note: Test diastolic pressure text BP Note: Systolic Measurement Absent: Unknown"; + + "Diastolic Note: Test diastolic pressure text BP Note: Systolic Measurement Absent: Unknown"; private static final String COMMENT_EXAMPLE_2 = "Systolic Note: Test systolic pressure text"; private static final String COMMENT_EXAMPLE_3 = "Diastolic Note: Test diastolic pressure text"; private static final String COMMENT_EXAMPLE_4 = "BP Note: Systolic Measurement Absent: Unknown"; private static final BigDecimal COMPONENT_1_VALUE_QUANTITY_VALUE_BASE = new BigDecimal(80); private static final BigDecimal COMPONENT_1_VALUE_QUANTITY_VALUE = COMPONENT_1_VALUE_QUANTITY_VALUE_BASE. - setScale(3, DOWN); + setScale(3, DOWN); private static final String COMPONENT_1_INTERPRETATION_TEXT = "High Text"; private static final String COMPONENT_1_REFERENCE_RANGE_TEXT = "Test Range 1"; private static final BigDecimal COMPONENT_2_VALUE_QUANTITY_VALUE_BASE = new BigDecimal(90); private static final BigDecimal COMPONENT_2_VALUE_QUANTITY_VALUE = COMPONENT_2_VALUE_QUANTITY_VALUE_BASE - .setScale(3, DOWN); + .setScale(3, DOWN); private static final String COMPONENT_2_INTERPRETATION_TEXT = "Low Text"; private static final String COMPONENT_2_REFERENCE_RANGE_TEXT = "Test Range 2"; public static final String NOPAT_CODE = "NOPAT"; public static final String NOPAT_URL_CODESYSTEM = "http://hl7.org/fhir/v3/ActCode"; public static final String NOPAT_DISPLAY = - "no disclosure to patient, family or caregivers without attending provider's authorization"; + "no disclosure to patient, family or caregivers without attending provider's authorization"; public static final String NOPAT_OID_CODESYSTEM = "2.16.840.1.113883.4.642.3.47"; private static final CodeableConcept CODEABLE_CONCEPT = createCodeableConcept(null, null, CODING_DISPLAY_MOCK); private static final List ENCOUNTER_LIST = List.of( - (Encounter) new Encounter().setId("TEST_ID_MATCHING_ENCOUNTER") + (Encounter) new Encounter().setId("TEST_ID_MATCHING_ENCOUNTER") ); @Mock @@ -105,204 +103,6 @@ public class BloodPressureMapperTest { @Captor private ArgumentCaptor> confidentialityCodesCaptor; - @BeforeEach - @SuppressWarnings("unchecked") - public void setupDefaultStubs() { - lenient() - .when(codeableConceptMapper.mapToCodeableConcept(any())) - .thenReturn(CODEABLE_CONCEPT); - lenient() - .when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - any(), - any(Optional[].class))) - .thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); - } - - @Test - public void mapBloodPressureObservationWithValidData() { - var ehrExtract = unmarshallEhrExtractElement("full_valid_data_bp_example.xml"); - - var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); - - assertFixedValues(bloodPressure); - assertThat(bloodPressure.getId()).isEqualTo(EXAMPLE_ID); - assertThat(bloodPressure.getComponent().getFirst().getCode().getCodingFirstRep()) - .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); - assertThat(bloodPressure.getComponent().getFirst().getCode().getCoding().get(1).getDisplay()) - .isEqualTo(CODING_DISPLAY_MOCK); - assertTrue(bloodPressure.hasSubject()); - assertThat(bloodPressure.getIssuedElement().asStringValue()).isEqualTo(ISSUED_EXAMPLE); - assertThat(bloodPressure.getEffective().toString()).isEqualTo(DateFormatUtil.parseToDateTimeType(EFFECTIVE_EXAMPLE).toString()); - assertThat(bloodPressure.getPerformer().getFirst().getReference()).isEqualTo(PPRF_PARTICIPANT_ID); - assertThat(bloodPressure.getComment()).isEqualTo(COMMENT_EXAMPLE_1); - - assertThat(bloodPressure.getComponent().getFirst().getCode().getCodingFirstRep()) - .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); - assertThat(bloodPressure.getComponent().getFirst().getCode().getCoding().get(1).getDisplay()) - .isEqualTo(CODING_DISPLAY_MOCK); - assertThat(bloodPressure.getComponent().getFirst().getValueQuantity().getValue()).isEqualTo(COMPONENT_1_VALUE_QUANTITY_VALUE); - assertThat(bloodPressure.getComponent().getFirst().getInterpretation().getText()).isEqualTo(COMPONENT_1_INTERPRETATION_TEXT); - assertThat(bloodPressure.getComponent().getFirst().getReferenceRange().getFirst().getText()) - .isEqualTo(COMPONENT_1_REFERENCE_RANGE_TEXT); - - assertThat(bloodPressure.getComponent().get(1).getCode().getCodingFirstRep()) - .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); - assertThat(bloodPressure.getComponent().get(1).getCode().getCoding().get(1).getDisplay()) - .isEqualTo(CODING_DISPLAY_MOCK); - assertThat(bloodPressure.getComponent().get(1).getValueQuantity().getValue()).isEqualTo(COMPONENT_2_VALUE_QUANTITY_VALUE); - assertThat(bloodPressure.getComponent().get(1).getInterpretation().getText()).isEqualTo(COMPONENT_2_INTERPRETATION_TEXT); - assertThat(bloodPressure.getComponent().get(1).getReferenceRange().getFirst().getText()) - .isEqualTo(COMPONENT_2_REFERENCE_RANGE_TEXT); - } - - @Test - public void mapBloodPressureWithNoOptionalData() { - var ehrExtract = unmarshallEhrExtractElement("no_optional_data_bp_example.xml"); - - var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); - - assertFixedValues(bloodPressure); - assertThat(bloodPressure.getId()).isEqualTo(EXAMPLE_ID); - assertThat(bloodPressure.getCode().getCodingFirstRep()).isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); - assertThat(bloodPressure.getCode().getCoding().get(1).getDisplay()).isEqualTo(CODING_DISPLAY_MOCK); - assertThat(bloodPressure.hasSubject()).isTrue(); - assertThat(bloodPressure.getIssuedElement().asStringValue()).isEqualTo(ISSUED_EXAMPLE); - assertThat(bloodPressure.getPerformer().getFirst().getReference()).isEqualTo(PPRF_PARTICIPANT_ID); - - assertNull(bloodPressure.getEffective()); - assertTrue(StringUtils.isEmpty(bloodPressure.getComment())); - - assertThat(bloodPressure.getComponent().getFirst().getCode().getCodingFirstRep()) - .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); - assertThat(bloodPressure.getComponent().getFirst().getCode().getCoding().get(1).getDisplay()) - .isEqualTo(CODING_DISPLAY_MOCK); - assertNull(bloodPressure.getComponent().getFirst().getValueQuantity()); - assertThat(bloodPressure.getComponent().getFirst().getInterpretation().getCoding()).isEmpty(); - assertThat(bloodPressure.getComponent().getFirst().getReferenceRange()).isEmpty(); - - assertThat(bloodPressure.getComponent().get(1).getCode().getCodingFirstRep()) - .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); - assertThat(bloodPressure.getComponent().get(1).getCode().getCoding().get(1).getDisplay()) - .isEqualTo(CODING_DISPLAY_MOCK); - assertNull(bloodPressure.getComponent().get(1).getValueQuantity()); - assertThat(bloodPressure.getComponent().get(1).getInterpretation().getCoding()).isEmpty(); - assertThat(bloodPressure.getComponent().get(1).getReferenceRange()).isEmpty(); - } - - @ParameterizedTest(name = "[{index}] {0}") - @ValueSource(strings = { - "ehr_composition_containing_confidentiality_code", - "battery_compound_statement_containing_confidentiality_code", - "systolic_observation_containing_confidentiality_code", - "diastolic_observation_containing_confidentiality_code" - }) - public void When_MappingBloodPressureWithConfidentialityCodes_Expect_BloodPressureObservationContainsSecurityMeta( - String inputXml) { - - final var metaFromConfidentialityService = MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE); - when( - confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - eq(META_PROFILE), - confidentialityCodesCaptor.capture(), - confidentialityCodesCaptor.capture(), - confidentialityCodesCaptor.capture(), - confidentialityCodesCaptor.capture() - ) - ).thenReturn(metaFromConfidentialityService); - final var ehrExtract = unmarshallEhrExtractElement(inputXml + ".xml"); - - final var bloodPressure = bloodPressureMapper - .mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE) - .getFirst(); - - assertAll( - () -> assertThat(confidentialityCodesCaptor.getAllValues()) - .usingRecursiveFieldByFieldElementComparator() - .containsExactlyInAnyOrder( - Optional.of(TestUtility.createCv(NOPAT_CODE, NOPAT_OID_CODESYSTEM, NOPAT_DISPLAY)), - Optional.empty(), - Optional.empty(), - Optional.empty() - ), - () -> assertThat(bloodPressure.getMeta()).usingRecursiveComparison() - .isEqualTo(metaFromConfidentialityService) - ); - } - - @Test - public void When_MappingBloodPressureWithoutConfidentialityCodes_Expect_ConfidentialityServiceCalledWithEmpty() { - var ehrExtract = unmarshallEhrExtractElement("no_optional_data_bp_example.xml"); - - bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE); - - verify(confidentialityService).createMetaAndAddSecurityIfConfidentialityCodesPresent( - META_PROFILE, - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty() - ); - } - - @Test - public void mapBloodPressureObservationWithCompositionIdMatchingEncounter() { - var ehrExtract = unmarshallEhrExtractElement("ehr_composition_id_matching_encounter_bp_example.xml"); - - var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); - - assertTrue(bloodPressure.hasContext()); - } - - @Test - public void mapBloodPressureObservationWithSystolicOnlyComment() { - var ehrExtract = unmarshallEhrExtractElement("systolic_comment_only_bp_example.xml"); - - var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); - - assertThat(bloodPressure.getComment()).isEqualTo(COMMENT_EXAMPLE_2); - } - - @Test - public void mapBloodPressureObservationWithDiastolicOnlyComment() { - var ehrExtract = unmarshallEhrExtractElement("diastolic_comment_only_blood_pressure_example.xml"); - - var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); - - assertThat(bloodPressure.getComment()).isEqualTo(COMMENT_EXAMPLE_3); - } - - @Test - public void mapBloodPressureObservationWithNarrativeStatementOnlyComment() { - var ehrExtract = unmarshallEhrExtractElement("narrative_statement_comment_only_bp_example.xml"); - - var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); - - assertThat(bloodPressure.getComment()).isEqualTo(COMMENT_EXAMPLE_4); - } - - @Test - public void mapBloodPressureObservationWithEffectiveDateTime() { - var ehrExtract = unmarshallEhrExtractElement( - "effective_date_time_using_effective_time_center_bp_example.xml"); - - var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); - - assertThat(bloodPressure.getEffective()).isInstanceOf(DateTimeType.class); - assertThat(bloodPressure.getEffectiveDateTimeType().getValueAsString()).isEqualTo("2006-04-25"); - } - - @Test - public void mapBloodPressureObservationWithEffectivePeriod() { - var ehrExtract = unmarshallEhrExtractElement( - "effective_period_start_end_using_effective_time_bp_example.xml"); - - var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); - - assertThat(bloodPressure.getEffective()).isInstanceOf(Period.class); - assertThat(bloodPressure.getEffectivePeriod().getStartElement().getValueAsString()).isEqualTo("2006-04-25"); - assertThat(bloodPressure.getEffectivePeriod().getEndElement().getValueAsString()).isEqualTo("2006-04-26"); - } - @Test public void nonConformantBloodPressureTripleNotMapped() { var ehrExtract = unmarshallEhrExtractElement("non-conformant-blood-pressure-triple-not-mapped.xml"); @@ -312,40 +112,218 @@ public void nonConformantBloodPressureTripleNotMapped() { assertThat(bloodPressures).isEmpty(); } - @Test - public void mapBloodPressureWithNoSnomedCodeInCoding() { - var ehrExtract = unmarshallEhrExtractElement("full_valid_data_bp_example.xml"); - - var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); - - assertThat(bloodPressure.getCode().getCodingFirstRep()) - .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); - assertThat(bloodPressure.getCode().getCoding().get(1).getDisplay()) - .isEqualTo(CODING_DISPLAY_MOCK); - assertThat(bloodPressure.getComponent().getFirst().getCode().getCodingFirstRep()) - .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); - assertThat(bloodPressure.getComponent().getFirst().getCode().getCoding().get(1).getDisplay()) - .isEqualTo(CODING_DISPLAY_MOCK); - assertThat(bloodPressure.getComponent().get(1).getCode().getCodingFirstRep()) - .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); - assertThat(bloodPressure.getComponent().get(1).getCode().getCoding().get(1).getDisplay()) - .isEqualTo(CODING_DISPLAY_MOCK); - } - - @Test - public void mapBloodPressureWithSnomedCodeInCoding() { - var codeableConcept = createCodeableConcept("http://snomed.info/sct", "123456", "Display"); - when(codeableConceptMapper.mapToCodeableConcept(any())).thenReturn(codeableConcept); + @Nested + public class TestsWithCodeableConceptAndConfidentialityService { + @BeforeEach + @SuppressWarnings("unchecked") + public void setupDefaultStubs() { + when(codeableConceptMapper.mapToCodeableConcept(any())) + .thenReturn(CODEABLE_CONCEPT); + when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( + any(), + any(Optional[].class))) + .thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); + } + + @Test + public void When_MappingBP_EhrCompositionWithConfidentialityCode_Expect_BloodPressureObservationContainsSecurityMeta() { + executeConfidentialityCodeTest("ehr_composition_containing_confidentiality_code"); + } + + @Test + public void When_MappingBP_BatteryCompoundStatementWithConfidentialityCode_Expect_BPObservationContainsSecurityMeta() { + executeConfidentialityCodeTest("battery_compound_statement_containing_confidentiality_code"); + } + + @Test + public void When_MappingBP_SystolicObservationWithConfidentialityCode_Expect_BPObservationContainsSecurityMeta() { + executeConfidentialityCodeTest("systolic_observation_containing_confidentiality_code"); + } + + @Test + public void When_MappingBP_DiastolicObservationWithConfidentialityCode_Expect_BPObservationContainsSecurityMeta() { + executeConfidentialityCodeTest("diastolic_observation_containing_confidentiality_code"); + } + @Test + public void mapBloodPressureObservationWithValidData() { + var ehrExtract = unmarshallEhrExtractElement("full_valid_data_bp_example.xml"); + + var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); + + assertFixedValues(bloodPressure); + assertThat(bloodPressure.getId()).isEqualTo(EXAMPLE_ID); + assertThat(bloodPressure.getComponent().getFirst().getCode().getCodingFirstRep()) + .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); + assertThat(bloodPressure.getComponent().getFirst().getCode().getCoding().get(1).getDisplay()) + .isEqualTo(CODING_DISPLAY_MOCK); + assertTrue(bloodPressure.hasSubject()); + assertThat(bloodPressure.getIssuedElement().asStringValue()).isEqualTo(ISSUED_EXAMPLE); + assertThat(bloodPressure.getEffective().toString()).isEqualTo(DateFormatUtil.parseToDateTimeType(EFFECTIVE_EXAMPLE).toString()); + assertThat(bloodPressure.getPerformer().getFirst().getReference()).isEqualTo(PPRF_PARTICIPANT_ID); + assertThat(bloodPressure.getComment()).isEqualTo(COMMENT_EXAMPLE_1); + + assertThat(bloodPressure.getComponent().getFirst().getCode().getCodingFirstRep()) + .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); + assertThat(bloodPressure.getComponent().getFirst().getCode().getCoding().get(1).getDisplay()) + .isEqualTo(CODING_DISPLAY_MOCK); + assertThat(bloodPressure.getComponent().getFirst().getValueQuantity().getValue()).isEqualTo(COMPONENT_1_VALUE_QUANTITY_VALUE); + assertThat(bloodPressure.getComponent().getFirst().getInterpretation().getText()).isEqualTo(COMPONENT_1_INTERPRETATION_TEXT); + assertThat(bloodPressure.getComponent().getFirst().getReferenceRange().getFirst().getText()) + .isEqualTo(COMPONENT_1_REFERENCE_RANGE_TEXT); + + assertThat(bloodPressure.getComponent().get(1).getCode().getCodingFirstRep()) + .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); + assertThat(bloodPressure.getComponent().get(1).getCode().getCoding().get(1).getDisplay()) + .isEqualTo(CODING_DISPLAY_MOCK); + assertThat(bloodPressure.getComponent().get(1).getValueQuantity().getValue()).isEqualTo(COMPONENT_2_VALUE_QUANTITY_VALUE); + assertThat(bloodPressure.getComponent().get(1).getInterpretation().getText()).isEqualTo(COMPONENT_2_INTERPRETATION_TEXT); + assertThat(bloodPressure.getComponent().get(1).getReferenceRange().getFirst().getText()) + .isEqualTo(COMPONENT_2_REFERENCE_RANGE_TEXT); + } + + @Test + public void mapBloodPressureWithNoOptionalData() { + var ehrExtract = unmarshallEhrExtractElement("no_optional_data_bp_example.xml"); + + var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); + + assertFixedValues(bloodPressure); + assertThat(bloodPressure.getId()).isEqualTo(EXAMPLE_ID); + assertThat(bloodPressure.getCode().getCodingFirstRep()).isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); + assertThat(bloodPressure.getCode().getCoding().get(1).getDisplay()).isEqualTo(CODING_DISPLAY_MOCK); + assertThat(bloodPressure.hasSubject()).isTrue(); + assertThat(bloodPressure.getIssuedElement().asStringValue()).isEqualTo(ISSUED_EXAMPLE); + assertThat(bloodPressure.getPerformer().getFirst().getReference()).isEqualTo(PPRF_PARTICIPANT_ID); + + assertNull(bloodPressure.getEffective()); + assertTrue(StringUtils.isEmpty(bloodPressure.getComment())); + + assertThat(bloodPressure.getComponent().getFirst().getCode().getCodingFirstRep()) + .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); + assertThat(bloodPressure.getComponent().getFirst().getCode().getCoding().get(1).getDisplay()) + .isEqualTo(CODING_DISPLAY_MOCK); + assertNull(bloodPressure.getComponent().getFirst().getValueQuantity()); + assertThat(bloodPressure.getComponent().getFirst().getInterpretation().getCoding()).isEmpty(); + assertThat(bloodPressure.getComponent().getFirst().getReferenceRange()).isEmpty(); + + assertThat(bloodPressure.getComponent().get(1).getCode().getCodingFirstRep()) + .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); + assertThat(bloodPressure.getComponent().get(1).getCode().getCoding().get(1).getDisplay()) + .isEqualTo(CODING_DISPLAY_MOCK); + assertNull(bloodPressure.getComponent().get(1).getValueQuantity()); + assertThat(bloodPressure.getComponent().get(1).getInterpretation().getCoding()).isEmpty(); + assertThat(bloodPressure.getComponent().get(1).getReferenceRange()).isEmpty(); + } + + @Test + public void When_MappingBloodPressureWithoutConfidentialityCodes_Expect_ConfidentialityServiceCalledWithEmpty() { + var ehrExtract = unmarshallEhrExtractElement("no_optional_data_bp_example.xml"); + + bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE); + + verify(confidentialityService).createMetaAndAddSecurityIfConfidentialityCodesPresent( + META_PROFILE, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty() + ); + } + + @Test + public void mapBloodPressureObservationWithCompositionIdMatchingEncounter() { + var ehrExtract = unmarshallEhrExtractElement("ehr_composition_id_matching_encounter_bp_example.xml"); + + var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); + + assertTrue(bloodPressure.hasContext()); + } + + @Test + public void mapBloodPressureObservationWithSystolicOnlyComment() { + var ehrExtract = unmarshallEhrExtractElement("systolic_comment_only_bp_example.xml"); + + var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); + + assertThat(bloodPressure.getComment()).isEqualTo(COMMENT_EXAMPLE_2); + } + + @Test + public void mapBloodPressureObservationWithDiastolicOnlyComment() { + var ehrExtract = unmarshallEhrExtractElement("diastolic_comment_only_blood_pressure_example.xml"); + + var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); + + assertThat(bloodPressure.getComment()).isEqualTo(COMMENT_EXAMPLE_3); + } + + @Test + public void mapBloodPressureObservationWithNarrativeStatementOnlyComment() { + var ehrExtract = unmarshallEhrExtractElement("narrative_statement_comment_only_bp_example.xml"); + + var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); + + assertThat(bloodPressure.getComment()).isEqualTo(COMMENT_EXAMPLE_4); + } + + @Test + public void mapBloodPressureObservationWithEffectiveDateTime() { + var ehrExtract = unmarshallEhrExtractElement( + "effective_date_time_using_effective_time_center_bp_example.xml"); + + var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); + + assertThat(bloodPressure.getEffective()).isInstanceOf(DateTimeType.class); + assertThat(bloodPressure.getEffectiveDateTimeType().getValueAsString()).isEqualTo("2006-04-25"); + } + + @Test + public void mapBloodPressureObservationWithEffectivePeriod() { + var ehrExtract = unmarshallEhrExtractElement( + "effective_period_start_end_using_effective_time_bp_example.xml"); + + var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); + + assertThat(bloodPressure.getEffective()).isInstanceOf(Period.class); + assertThat(bloodPressure.getEffectivePeriod().getStartElement().getValueAsString()).isEqualTo("2006-04-25"); + assertThat(bloodPressure.getEffectivePeriod().getEndElement().getValueAsString()).isEqualTo("2006-04-26"); + } + + @Test + public void mapBloodPressureWithNoSnomedCodeInCoding() { + var ehrExtract = unmarshallEhrExtractElement("full_valid_data_bp_example.xml"); + + var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); + + assertThat(bloodPressure.getCode().getCodingFirstRep()) + .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); + assertThat(bloodPressure.getCode().getCoding().get(1).getDisplay()) + .isEqualTo(CODING_DISPLAY_MOCK); + assertThat(bloodPressure.getComponent().getFirst().getCode().getCodingFirstRep()) + .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); + assertThat(bloodPressure.getComponent().getFirst().getCode().getCoding().get(1).getDisplay()) + .isEqualTo(CODING_DISPLAY_MOCK); + assertThat(bloodPressure.getComponent().get(1).getCode().getCodingFirstRep()) + .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); + assertThat(bloodPressure.getComponent().get(1).getCode().getCoding().get(1).getDisplay()) + .isEqualTo(CODING_DISPLAY_MOCK); + } + + @Test + public void mapBloodPressureWithSnomedCodeInCoding() { + var codeableConcept = createCodeableConcept("http://snomed.info/sct", "123456", "Display"); + when(codeableConceptMapper.mapToCodeableConcept(any())).thenReturn(codeableConcept); - var ehrExtract = unmarshallEhrExtractElement("full_valid_data_bp_example.xml"); + var ehrExtract = unmarshallEhrExtractElement("full_valid_data_bp_example.xml"); - var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); + var bloodPressure = bloodPressureMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); - assertAll( - () -> assertEquals(codeableConcept, bloodPressure.getCode()), - () -> assertEquals(codeableConcept, bloodPressure.getComponent().getFirst().getCode()), - () -> assertEquals(codeableConcept, bloodPressure.getComponent().get(1).getCode()) - ); + assertAll( + () -> assertEquals(codeableConcept, bloodPressure.getCode()), + () -> assertEquals(codeableConcept, bloodPressure.getComponent().getFirst().getCode()), + () -> assertEquals(codeableConcept, bloodPressure.getComponent().get(1).getCode()) + ); + } } private void assertFixedValues(Observation bloodPressure) { @@ -355,9 +333,37 @@ private void assertFixedValues(Observation bloodPressure) { assertThat(bloodPressure.getStatus()).isEqualTo(Observation.ObservationStatus.FINAL); } + private void executeConfidentialityCodeTest(String inputXml) { + final var metaFromConfidentialityService = MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE); + when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( + eq(META_PROFILE), + confidentialityCodesCaptor.capture(), + confidentialityCodesCaptor.capture(), + confidentialityCodesCaptor.capture(), + confidentialityCodesCaptor.capture() + )).thenReturn(metaFromConfidentialityService); + final var ehrExtract = unmarshallEhrExtractElement(inputXml + ".xml"); + + final var bloodPressure = bloodPressureMapper + .mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE) + .getFirst(); + + assertAll( + () -> assertThat(confidentialityCodesCaptor.getAllValues()) + .usingRecursiveFieldByFieldElementComparator() + .containsExactlyInAnyOrder( + Optional.of(TestUtility.createCv(NOPAT_CODE, NOPAT_OID_CODESYSTEM, NOPAT_DISPLAY)), + Optional.empty(), + Optional.empty(), + Optional.empty() + ), + () -> assertThat(bloodPressure.getMeta()).usingRecursiveComparison() + .isEqualTo(metaFromConfidentialityService) + ); + } + @SneakyThrows private RCMRMT030101UKEhrExtract unmarshallEhrExtractElement(String fileName) { return unmarshallFile(getFile("classpath:" + XML_RESOURCES_BASE + fileName), RCMRMT030101UKEhrExtract.class); } - -} +} \ No newline at end of file diff --git a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ConditionMapperTest.java b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ConditionMapperTest.java index 749f4aaff..e29fa2ada 100644 --- a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ConditionMapperTest.java +++ b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ConditionMapperTest.java @@ -67,19 +67,17 @@ class ConditionMapperTest { private static final String PATIENT_ID = "PATIENT_ID"; private static final String PRACTISE_CODE = "TESTPRACTISECODE"; private static final String ENCOUNTER_ID = "EHR_COMPOSITION_ENCOUNTER_ID"; - private static final String ASSERTER_ID_REFERENCE = "Practitioner/ASSERTER_ID"; - private static final String ASSERTER_PARTICIPANT_ID_REFERENCE = "Practitioner/ASSERTER_PARTICIPANT_ID"; private static final String LINKSET_ID = "LINKSET_ID"; private static final String CODING_DISPLAY = "THIS IS A TEST"; private static final DateTimeType EHR_EXTRACT_AVAILABILITY_DATETIME = parseToDateTimeType("20101209114846.00"); private static final String NOPAT = "NOPAT"; private static final String ACTUAL_PROBLEM_URL = "https://fhir.hl7.org.uk/STU3/StructureDefinition/Extension-CareConnect" - + "-ActualProblem-1"; + + "-ActualProblem-1"; private static final String PROBLEM_SIGNIFICANCE_URL = "https://fhir.hl7.org.uk/STU3/StructureDefinition/Extension-CareConnect" - + "-ProblemSignificance-1"; + + "-ProblemSignificance-1"; private static final String RELATED_CLINICAL_CONTENT_URL = "https://fhir.hl7.org.uk/STU3/StructureDefinition/Extension-CareConnect" - + "-RelatedClinicalContent-1"; + + "-RelatedClinicalContent-1"; private static final String MEDICATION_STATEMENT_PLAN_ID = "PLAN_REF_ID"; private static final String AUTHORISE_ID = "AUTHORISE_ID"; private static final String MEDICATION_STATEMENT_ORDER_ID = "ORDER_REF_ID"; @@ -105,82 +103,85 @@ class ConditionMapperTest { @BeforeEach void beforeEach() { - configureCommonStubs(); patient = (Patient) new Patient().setId(PATIENT_ID); } - @Test - void testConditionAsserterIsMappedCorrectly() { - - when(dateTimeMapper.mapDateTime(any())).thenReturn(EHR_EXTRACT_AVAILABILITY_DATETIME); - - final List encounters = List.of((Encounter) new Encounter().setId(ENCOUNTER_ID)); - - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_valid_with_author.xml"); - final List conditions = conditionMapper.mapResources(ehrExtract, patient, encounters, PRACTISE_CODE); - - assertThat(conditions).isNotEmpty(); - assertEquals(ASSERTER_ID_REFERENCE, conditions.getFirst().getAsserter().getReference()); + private void registerDependencies(Object... dependencies) { + for (Object dependency : dependencies) { + if (dependency == dateTimeMapper) { + Mockito.when(dateTimeMapper.mapDateTime( + any(String.class) + )).thenReturn(EHR_EXTRACT_AVAILABILITY_DATETIME); + } + if (dependency == confidentialityService) { + Mockito.when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( + eq(META_PROFILE), + confidentialityCodeCaptor.capture(), + confidentialityCodeCaptor.capture(), + confidentialityCodeCaptor.capture() + )).thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); + } + if (dependency == codeableConceptMapper) { + var codeableConcept = new CodeableConcept() + .addCoding(new Coding().setDisplay(CODING_DISPLAY)); + when(codeableConceptMapper.mapToCodeableConcept(any())) + .thenReturn(codeableConcept); + } + } } @Test - void testConditionIsMappedCorrectlyWithNamedStatementRefPointingtoObservationStatementNopat() { + void When_Condition_With_NopatConfidentialityCode_Expect_MetaFromConfidentialityServiceWithSecurity() { + registerDependencies(dateTimeMapper, confidentialityService); final Meta metaWithSecurity = MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE); - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_valid_with_reference_to_nopat_observation.xml"); + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_valid_nopat_confidentiality_code.xml"); - when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - eq(META_PROFILE), - confidentialityCodeCaptor.capture(), - confidentialityCodeCaptor.capture(), - confidentialityCodeCaptor.capture() - )).thenReturn(MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE)); + final List conditions = conditionMapper + .mapResources(ehrExtract, patient, Collections.emptyList(), PRACTISE_CODE); - final List conditions = conditionMapper.mapResources(ehrExtract, patient, Collections.emptyList(), PRACTISE_CODE); + final CV linksetConfidentialityCode = confidentialityCodeCaptor + .getAllValues() + .get(1) // linkSet.getConfidentialityCode() + .orElseThrow(); assertAllConditionsHaveMeta(conditions, metaWithSecurity); assertAll( - () -> assertThat(confidentialityCodeCaptor.getAllValues().getFirst()).isPresent(), - () -> assertThat(confidentialityCodeCaptor.getAllValues().getFirst().get().getCode()).isEqualTo(NOPAT)); + () -> assertThat(linksetConfidentialityCode.getCode()).isEqualTo(NOPAT), + () -> assertThat(confidentialityCodeCaptor.getAllValues().get(2)).isNotPresent() + ); } @Test - void testConditionIsMappedCorrectlyNoReferences() { - when(dateTimeMapper.mapDateTime(any())).thenReturn(EHR_EXTRACT_AVAILABILITY_DATETIME); + void testConditionIsMappedCorrectlyWithRelatedClinicalContentReference() { + registerDependencies(dateTimeMapper); - final List emptyEncounterList = List.of(); final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_valid.xml"); - final List conditions = conditionMapper.mapResources(ehrExtract, patient, emptyEncounterList, PRACTISE_CODE); - - assertThat(conditions).isNotEmpty(); - - final Condition condition = conditions.getFirst(); - - assertGeneratedComponentsAreCorrect(condition); - assertThat(condition.getId()).isEqualTo(LINKSET_ID); + final List conditions = conditionMapper.mapResources(ehrExtract, patient, List.of(), PRACTISE_CODE); - assertThat(condition.getExtensionsByUrl(ACTUAL_PROBLEM_URL)).isEmpty(); - assertThat(condition.getExtensionsByUrl(PROBLEM_SIGNIFICANCE_URL)).hasSize(1); - assertThat(condition.getExtensionsByUrl(RELATED_CLINICAL_CONTENT_URL)).isEmpty(); + conditionMapper.addReferences(buildBundleWithStatementRefObservations(), conditions, ehrExtract); - assertThat(condition.getClinicalStatus().getDisplay()).isEqualTo("Active"); - assertFalse(condition.getCode().getCodingFirstRep().hasDisplay()); + assertThat(conditions).isNotEmpty(); + assertThat(conditions.getFirst().getExtensionsByUrl(RELATED_CLINICAL_CONTENT_URL)).isNotEmpty(); + assertRelatedClinicalContentExtension(conditions.getFirst()); + } - assertThat(condition.getSubject().getResource().getIdElement().getIdPart()).isEqualTo(PATIENT_ID); - assertThat(condition.getAsserter().getReference()).isEqualTo(ASSERTER_PARTICIPANT_ID_REFERENCE); - assertFalse(condition.getContext().hasReference()); + @Test + void testConditionIsMappedCorrectlyWithNamedStatementRefPointingtoObservationStatementNopat() { + registerDependencies(dateTimeMapper, confidentialityService); + final Meta metaWithSecurity = MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE); + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_valid_with_reference_to_nopat_observation.xml"); - assertThat(condition.getOnsetDateTimeType()).isEqualTo(EHR_EXTRACT_AVAILABILITY_DATETIME); - assertThat(condition.getAbatementDateTimeType()).isEqualTo(EHR_EXTRACT_AVAILABILITY_DATETIME); - assertNull(condition.getAssertedDateElement().getValue()); + final List conditions = conditionMapper.mapResources(ehrExtract, patient, Collections.emptyList(), PRACTISE_CODE); - assertThat(condition.getNote()).isEmpty(); + assertAllConditionsHaveMeta(conditions, metaWithSecurity); + assertAll( + () -> assertThat(confidentialityCodeCaptor.getAllValues().getFirst()).isPresent(), + () -> assertThat(confidentialityCodeCaptor.getAllValues().getFirst().get().getCode()).isEqualTo(NOPAT)); } @Test void testConditionIsMappedCorrectlyWithNamedStatementRef() { - when(dateTimeMapper.mapDateTime(any(String.class))).thenCallRealMethod(); - var codeableConcept = new CodeableConcept().addCoding(new Coding().setDisplay(CODING_DISPLAY)); - when(codeableConceptMapper.mapToCodeableConcept(any())).thenReturn(codeableConcept); + registerDependencies(dateTimeMapper, codeableConceptMapper); final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_valid_with_reference.xml"); final List conditions = conditionMapper.mapResources(ehrExtract, patient, List.of(), PRACTISE_CODE); @@ -192,7 +193,7 @@ void testConditionIsMappedCorrectlyWithNamedStatementRef() { @Test void testConditionIsMappedCorrectlyWithActualProblemReference() { - when(dateTimeMapper.mapDateTime(any())).thenReturn(EHR_EXTRACT_AVAILABILITY_DATETIME); + registerDependencies(dateTimeMapper); final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_valid.xml"); final List conditions = conditionMapper.mapResources(ehrExtract, patient, List.of(), PRACTISE_CODE); @@ -204,23 +205,9 @@ void testConditionIsMappedCorrectlyWithActualProblemReference() { assertActualProblemExtension(conditions.getFirst()); } - @Test - void testConditionIsMappedCorrectlyWithRelatedClinicalContentReference() { - when(dateTimeMapper.mapDateTime(any())).thenReturn(EHR_EXTRACT_AVAILABILITY_DATETIME); - - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_valid.xml"); - final List conditions = conditionMapper.mapResources(ehrExtract, patient, List.of(), PRACTISE_CODE); - - conditionMapper.addReferences(buildBundleWithStatementRefObservations(), conditions, ehrExtract); - - assertThat(conditions).isNotEmpty(); - assertThat(conditions.getFirst().getExtensionsByUrl(RELATED_CLINICAL_CONTENT_URL)).isNotEmpty(); - assertRelatedClinicalContentExtension(conditions.getFirst()); - } - @Test void testConditionIsMappedCorrectlyWithContext() { - when(dateTimeMapper.mapDateTime(any())).thenReturn(EHR_EXTRACT_AVAILABILITY_DATETIME); + registerDependencies(dateTimeMapper); final List encounters = List.of((Encounter) new Encounter().setId(ENCOUNTER_ID)); @@ -233,6 +220,8 @@ void testConditionIsMappedCorrectlyWithContext() { @Test void testLinkSetWithNoDatesIsMappedWithNullOnsetDateTime() { + registerDependencies(confidentialityService); + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_no_dates.xml"); final List conditions = conditionMapper.mapResources(ehrExtract, patient, List.of(), PRACTISE_CODE); @@ -245,20 +234,9 @@ void testLinkSetWithNoDatesIsMappedWithNullOnsetDateTime() { assertNull(conditions.getFirst().getAssertedDateElement().getValue()); } - @Test - void testLinkSetWithEffectiveTimeLowNullFlavorUnkIsMappedWithNullOnsetDateTime() { - when(dateTimeMapper.mapDateTime(any())).thenReturn(EHR_EXTRACT_AVAILABILITY_DATETIME); - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_with_null_flavor_unk.xml"); - final List conditions = conditionMapper.mapResources(ehrExtract, patient, List.of(), PRACTISE_CODE); - - assertGeneratedComponentsAreCorrect(conditions.getFirst()); - assertThat(conditions.getFirst().getId()).isEqualTo(LINKSET_ID); - - assertNull(conditions.getFirst().getOnsetDateTimeType()); - } - @Test void testLinkSetWithEffectiveTimeCenterNullFlavorUnkIsMappedCorrectly() { + registerDependencies(confidentialityService); final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_with_center_null_flavor_unk.xml"); final List conditions = conditionMapper.mapResources(ehrExtract, patient, List.of(), PRACTISE_CODE); @@ -271,18 +249,23 @@ void testLinkSetWithEffectiveTimeCenterNullFlavorUnkIsMappedCorrectly() { @Test void testConditionWithMedicationRequestsIsMappedCorrectly() { - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_medication_refs.xml"); + registerDependencies(dateTimeMapper); + + final RCMRMT030101UKEhrExtract ehrExtract = + unmarshallEhrExtract("linkset_medication_refs.xml"); - MockedStatic mockedMedicationMapperUtils = Mockito.mockStatic(MedicationMapperUtils.class); + MockedStatic mockedMedicationMapperUtils = + Mockito.mockStatic(MedicationMapperUtils.class); - // spotbugs doesn't allow try with resources due to de-referenced null check try { - mockedMedicationMapperUtils.when(() -> MedicationMapperUtils.getMedicationStatements(ehrExtract)) - .thenReturn(getMedicationStatements()); + mockedMedicationMapperUtils + .when(() -> MedicationMapperUtils.getMedicationStatements(ehrExtract)) + .thenReturn(getMedicationStatements()); - final List conditions = conditionMapper.mapResources(ehrExtract, patient, List.of(), PRACTISE_CODE); + final List conditions = + conditionMapper.mapResources(ehrExtract, patient, List.of(), PRACTISE_CODE); - assertThat(conditions.size()).isOne(); + assertThat(conditions).hasSize(1); var bundle = new Bundle(); bundle.addEntry(new BundleEntryComponent().setResource(conditions.getFirst())); @@ -293,31 +276,29 @@ void testConditionWithMedicationRequestsIsMappedCorrectly() { var extensions = conditions.getFirst().getExtension(); assertThat(extensions).hasSize(EXPECTED_NUMBER_OF_EXTENSIONS); + var relatedClinicalContentExtensions = extensions.stream() - .filter(extension -> extension.getUrl().equals(RELATED_CLINICAL_CONTENT_URL)) - .toList(); + .filter(extension -> extension.getUrl().equals(RELATED_CLINICAL_CONTENT_URL)) + .toList(); assertThat(relatedClinicalContentExtensions).hasSize(2); List clinicalContextReferences = relatedClinicalContentExtensions.stream() - .map(Extension::getValue) - .map(Reference.class::cast) - .map(reference -> reference.getReferenceElement().getValue()) - .toList(); + .map(Extension::getValue) + .map(Reference.class::cast) + .map(reference -> reference.getReferenceElement().getValue()) + .toList(); - assertThat(clinicalContextReferences).contains(AUTHORISE_ID); - assertThat(clinicalContextReferences).contains(PRESCRIBE_ID); + assertThat(clinicalContextReferences).contains(AUTHORISE_ID, PRESCRIBE_ID); } finally { mockedMedicationMapperUtils.close(); } - } + @Test void mapConditionWithoutSnomedCodeInCoding() { - var codeableConcept = new CodeableConcept().addCoding(new Coding().setDisplay(CODING_DISPLAY)); - when(codeableConceptMapper.mapToCodeableConcept(any())).thenReturn(codeableConcept); - when(dateTimeMapper.mapDateTime(any(String.class))).thenCallRealMethod(); + registerDependencies(dateTimeMapper); final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_valid_with_reference.xml"); final List conditions = conditionMapper.mapResources(ehrExtract, patient, List.of(), PRACTISE_CODE); @@ -325,14 +306,13 @@ void mapConditionWithoutSnomedCodeInCoding() { assertThat(conditions).isNotEmpty(); assertThat(conditions.getFirst().getCode().getCodingFirstRep()) - .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); + .isEqualTo(DegradedCodeableConcepts.DEGRADED_OTHER); assertThat(conditions.getFirst().getCode().getCoding().get(1).getDisplay()) - .isEqualTo(CODING_DISPLAY); + .isEqualTo(CODING_DISPLAY); } @Test void mapConditionWithSnomedCodeInCoding() { - var codeableConcept = createCodeableConcept("123456", "http://snomed.info/sct", "Display"); when(codeableConceptMapper.mapToCodeableConcept(any())).thenReturn(codeableConcept); when(dateTimeMapper.mapDateTime(any(String.class))).thenCallRealMethod(); @@ -345,66 +325,33 @@ void mapConditionWithSnomedCodeInCoding() { assertEquals(codeableConcept, conditions.getFirst().getCode()); } - @Test - void When_Condition_With_NopatConfidentialityCode_Expect_MetaFromConfidentialityServiceWithSecurity() { - final Meta metaWithSecurity = MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE); - final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_valid_nopat_confidentiality_code.xml"); - - when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - eq(META_PROFILE), - confidentialityCodeCaptor.capture(), - confidentialityCodeCaptor.capture(), - confidentialityCodeCaptor.capture() - )).thenReturn(MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE)); - - final List conditions = conditionMapper - .mapResources(ehrExtract, patient, Collections.emptyList(), PRACTISE_CODE); - - final CV linksetConfidentialityCode = confidentialityCodeCaptor - .getAllValues() - .get(1) // linkSet.getConfidentialityCode() - .orElseThrow(); - - assertAllConditionsHaveMeta(conditions, metaWithSecurity); - assertAll( - () -> assertThat(linksetConfidentialityCode.getCode()).isEqualTo(NOPAT), - () -> assertThat(confidentialityCodeCaptor.getAllValues().get(2)).isNotPresent() - ); - } - @Test void When_Condition_With_NopatConfidentialityCodeInEhrComposition_Expect_MetaFromConfidentialityServiceWithSecurity() { + registerDependencies(dateTimeMapper, confidentialityService); final Meta metaWithSecurity = MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE); final RCMRMT030101UKEhrExtract ehrExtract = - unmarshallEhrExtract("linkset_valid_ehr_composition_nopat_confidentiality_code.xml"); - - when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - eq(META_PROFILE), - confidentialityCodeCaptor.capture(), - confidentialityCodeCaptor.capture(), - confidentialityCodeCaptor.capture() - )).thenReturn(MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE)); + unmarshallEhrExtract("linkset_valid_ehr_composition_nopat_confidentiality_code.xml"); final List conditions = conditionMapper - .mapResources(ehrExtract, patient, Collections.emptyList(), PRACTISE_CODE); + .mapResources(ehrExtract, patient, Collections.emptyList(), PRACTISE_CODE); final CV ehrCompositionConfidentialityCode = confidentialityCodeCaptor - .getAllValues() - .get(2) // ehrComposition.getConfidentialityCode() - .orElseThrow(); + .getAllValues() + .get(2) // ehrComposition.getConfidentialityCode() + .orElseThrow(); assertAllConditionsHaveMeta(conditions, metaWithSecurity); assertAll( - () -> assertThat(ehrCompositionConfidentialityCode.getCode()).isEqualTo(NOPAT), - () -> assertThat(confidentialityCodeCaptor.getAllValues().getFirst()).isNotPresent() + () -> assertThat(ehrCompositionConfidentialityCode.getCode()).isEqualTo(NOPAT), + () -> assertThat(confidentialityCodeCaptor.getAllValues().getFirst()).isNotPresent() ); } @Test void When_MappingLinksetWhichIsAReferralRequestToExternalDocumentLinkSet_Expect_ConditionNotToBeMapped() { final var ehrExtract = unmarshallEhrExtract( - "ResourceFilter", - "ehr_extract_with_referral_request_to_external_document_linkset.xml" + "ResourceFilter", + "ehr_extract_with_referral_request_to_external_document_linkset.xml" ); final List conditions = conditionMapper.mapResources(ehrExtract, patient, Collections.emptyList(), PRACTISE_CODE); @@ -412,8 +359,51 @@ void When_MappingLinksetWhichIsAReferralRequestToExternalDocumentLinkSet_Expect_ assertThat(conditions).isEmpty(); } + @Test + void testConditionIsMappedCorrectlyNoReferences() { + registerDependencies(dateTimeMapper, confidentialityService); + + final List emptyEncounterList = List.of(); + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_valid.xml"); + final List conditions = + conditionMapper.mapResources(ehrExtract, patient, emptyEncounterList, PRACTISE_CODE); + + assertThat(conditions).isNotEmpty(); + + final Condition condition = conditions.getFirst(); + + assertGeneratedComponentsAreCorrect(condition); + assertThat(condition.getId()).isEqualTo(LINKSET_ID); + + assertThat(condition.getExtensionsByUrl(ACTUAL_PROBLEM_URL)).isEmpty(); + assertThat(condition.getExtensionsByUrl(PROBLEM_SIGNIFICANCE_URL)).hasSize(1); + assertThat(condition.getExtensionsByUrl(RELATED_CLINICAL_CONTENT_URL)).isEmpty(); + + assertThat(condition.getClinicalStatus().getDisplay()).isEqualTo("Active"); + assertFalse(condition.getCode().getCodingFirstRep().hasDisplay()); + + assertThat(condition.getSubject().getResource().getIdElement().getIdPart()) + .isEqualTo(PATIENT_ID); + + assertThat(condition.getAsserter().getReference()) + .isEqualTo("Practitioner/ASSERTER_PARTICIPANT_ID"); + + assertFalse(condition.getContext().hasReference()); + + assertThat(condition.getOnsetDateTimeType()) + .isEqualTo(EHR_EXTRACT_AVAILABILITY_DATETIME); + assertThat(condition.getAbatementDateTimeType()) + .isEqualTo(EHR_EXTRACT_AVAILABILITY_DATETIME); + + assertNull(condition.getAssertedDateElement().getValue()); + assertThat(condition.getNote()).isEmpty(); + } + + + @Test void When_MappingLinksetWithNotMajorCode_Expect_DefaultedToMinor() { + registerDependencies(dateTimeMapper, confidentialityService); final var ehrExtract = unmarshallEhrExtract( "Condition", "linkset_with_minor_severity_code.xml" @@ -428,6 +418,7 @@ void When_MappingLinksetWithNotMajorCode_Expect_DefaultedToMinor() { @Test void When_MappingLinksetWithUnknownSeverityCode_Expect_DefaultedToMinor() { + registerDependencies(dateTimeMapper, confidentialityService); final var ehrExtract = unmarshallEhrExtract("Condition", "linkset_with_unknown_severity_code.xml"); final List conditions = conditionMapper.mapResources(ehrExtract, patient, List.of(), PRACTISE_CODE); @@ -437,41 +428,16 @@ void When_MappingLinksetWithUnknownSeverityCode_Expect_DefaultedToMinor() { assertEquals(DEFAULTED_TO_MINOR, conditions.getFirst().getNote().getFirst().getText()); } - private void addMedicationRequestsToBundle(Bundle bundle) { - var planMedicationRequest = new MedicationRequest().setId(AUTHORISE_ID); - var orderMedicationRequest = new MedicationRequest().setId(PRESCRIBE_ID); - - bundle.addEntry(new BundleEntryComponent().setResource(planMedicationRequest)); - bundle.addEntry(new BundleEntryComponent().setResource(orderMedicationRequest)); - } - - private List getMedicationStatements() { - - var planMedicationStatement = new RCMRMT030101UKMedicationStatement(); - planMedicationStatement.setId(createIdWithRoot(MEDICATION_STATEMENT_PLAN_ID)); - planMedicationStatement.getMoodCode().add("INT"); - - var authorise = new RCMRMT030101UKAuthorise(); - authorise.setId(createIdWithRoot(AUTHORISE_ID)); - - var planComponent = new RCMRMT030101UKComponent2(); - planComponent.setEhrSupplyAuthorise(authorise); - - planMedicationStatement.getComponent().add(planComponent); - - var orderMedicationStatement = new RCMRMT030101UKMedicationStatement(); - orderMedicationStatement.setId(createIdWithRoot(MEDICATION_STATEMENT_ORDER_ID)); - orderMedicationStatement.getMoodCode().add("ORD"); - - var prescribe = new RCMRMT030101UKPrescribe(); - prescribe.setId(createIdWithRoot(PRESCRIBE_ID)); - - var orderComponent = new RCMRMT030101UKComponent2(); - orderComponent.setEhrSupplyPrescribe(prescribe); + @Test + void testLinkSetWithEffectiveTimeLowNullFlavorUnkIsMappedWithNullOnsetDateTime() { + registerDependencies(dateTimeMapper, confidentialityService); + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("linkset_with_null_flavor_unk.xml"); + final List conditions = conditionMapper.mapResources(ehrExtract, patient, List.of(), PRACTISE_CODE); - orderMedicationStatement.getComponent().add(orderComponent); + assertGeneratedComponentsAreCorrect(conditions.getFirst()); + assertThat(conditions.getFirst().getId()).isEqualTo(LINKSET_ID); - return List.of(planMedicationStatement, orderMedicationStatement); + assertNull(conditions.getFirst().getOnsetDateTimeType()); } private II createIdWithRoot(String rootValue) { @@ -481,11 +447,21 @@ private II createIdWithRoot(String rootValue) { return id; } - private void assertActualProblemExtension(Condition condition) { - var extension = condition.getExtensionsByUrl(ACTUAL_PROBLEM_URL).getFirst(); - assertThat(extension.getValue()).isInstanceOf(Reference.class); - assertThat(((Reference) extension.getValue()).getResource()).isInstanceOf(Observation.class); - assertThat(((Observation) ((Reference) extension.getValue()).getResource()).getId()).isEqualTo(NAMED_STATEMENT_REF_ID); + private void assertAllConditionsHaveMeta(List conditions, Meta expectedMeta) { + assertAll(conditions.stream().map(condition -> + () -> assertThat(condition.getMeta()).usingRecursiveComparison().isEqualTo(expectedMeta) + )); + } + + @SneakyThrows + private RCMRMT030101UKEhrExtract unmarshallEhrExtract(String testFilesDirectory, String filename) { + final File file = FileFactory.getXmlFileFor(testFilesDirectory, filename); + return unmarshallFile(file, RCMRMT030101UKEhrExtract.class); + } + + @SneakyThrows + private RCMRMT030101UKEhrExtract unmarshallEhrExtract(String filename) { + return unmarshallEhrExtract(TEST_FILES_DIRECTORY, filename); } private void assertRelatedClinicalContentExtension(Condition condition) { @@ -495,6 +471,21 @@ private void assertRelatedClinicalContentExtension(Condition condition) { assertThat(((Reference) extensions.get(1).getValue()).getResource().getIdElement().getValue()).isEqualTo(STATEMENT_REF_ID_1); } + private Bundle buildBundleWithStatementRefObservations() { + return new Bundle() + .addEntry(new BundleEntryComponent() + .setResource(new Observation().setId(STATEMENT_REF_ID))) + .addEntry(new BundleEntryComponent() + .setResource(new Observation().setId(STATEMENT_REF_ID_1))); + } + + private void assertActualProblemExtension(Condition condition) { + var extension = condition.getExtensionsByUrl(ACTUAL_PROBLEM_URL).getFirst(); + assertThat(extension.getValue()).isInstanceOf(Reference.class); + assertThat(((Reference) extension.getValue()).getResource()).isInstanceOf(Observation.class); + assertThat(((Observation) ((Reference) extension.getValue()).getResource()).getId()).isEqualTo(NAMED_STATEMENT_REF_ID); + } + private void assertGeneratedComponentsAreCorrect(Condition condition) { assertNotNull(condition.getMeta().getProfile().getFirst()); assertThat(condition.getIdentifierFirstRep().getValue()).isEqualTo(LINKSET_ID); @@ -503,45 +494,44 @@ private void assertGeneratedComponentsAreCorrect(Condition condition) { private Bundle buildBundleWithNamedStatementObservation() { return new Bundle() - .addEntry(new BundleEntryComponent() - .setResource(new Observation().setId(NAMED_STATEMENT_REF_ID))); + .addEntry(new BundleEntryComponent() + .setResource(new Observation().setId(NAMED_STATEMENT_REF_ID))); } - private Bundle buildBundleWithStatementRefObservations() { - return new Bundle() - .addEntry(new BundleEntryComponent() - .setResource(new Observation().setId(STATEMENT_REF_ID))) - .addEntry(new BundleEntryComponent() - .setResource(new Observation().setId(STATEMENT_REF_ID_1))); - } + private void addMedicationRequestsToBundle(Bundle bundle) { + var planMedicationRequest = new MedicationRequest().setId(AUTHORISE_ID); + var orderMedicationRequest = new MedicationRequest().setId(PRESCRIBE_ID); - private void assertAllConditionsHaveMeta(List conditions, Meta expectedMeta) { - assertAll(conditions.stream().map(condition -> - () -> assertThat(condition.getMeta()).usingRecursiveComparison().isEqualTo(expectedMeta) - )); + bundle.addEntry(new BundleEntryComponent().setResource(planMedicationRequest)); + bundle.addEntry(new BundleEntryComponent().setResource(orderMedicationRequest)); } - @SneakyThrows - private RCMRMT030101UKEhrExtract unmarshallEhrExtract(String testFilesDirectory, String filename) { - final File file = FileFactory.getXmlFileFor(testFilesDirectory, filename); - return unmarshallFile(file, RCMRMT030101UKEhrExtract.class); - } + private List getMedicationStatements() { - @SneakyThrows - private RCMRMT030101UKEhrExtract unmarshallEhrExtract(String filename) { - return unmarshallEhrExtract(TEST_FILES_DIRECTORY, filename); - } + var planMedicationStatement = new RCMRMT030101UKMedicationStatement(); + planMedicationStatement.setId(createIdWithRoot(MEDICATION_STATEMENT_PLAN_ID)); + planMedicationStatement.getMoodCode().add("INT"); + + var authorise = new RCMRMT030101UKAuthorise(); + authorise.setId(createIdWithRoot(AUTHORISE_ID)); + + var planComponent = new RCMRMT030101UKComponent2(); + planComponent.setEhrSupplyAuthorise(authorise); - private void configureCommonStubs() { - Mockito.lenient().when(dateTimeMapper.mapDateTime( - any(String.class) - )).thenReturn(EHR_EXTRACT_AVAILABILITY_DATETIME); - - Mockito.lenient().when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - eq(META_PROFILE), - confidentialityCodeCaptor.capture(), - confidentialityCodeCaptor.capture(), - confidentialityCodeCaptor.capture() - )).thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); + planMedicationStatement.getComponent().add(planComponent); + + var orderMedicationStatement = new RCMRMT030101UKMedicationStatement(); + orderMedicationStatement.setId(createIdWithRoot(MEDICATION_STATEMENT_ORDER_ID)); + orderMedicationStatement.getMoodCode().add("ORD"); + + var prescribe = new RCMRMT030101UKPrescribe(); + prescribe.setId(createIdWithRoot(PRESCRIBE_ID)); + + var orderComponent = new RCMRMT030101UKComponent2(); + orderComponent.setEhrSupplyPrescribe(prescribe); + + orderMedicationStatement.getComponent().add(orderComponent); + + return List.of(planMedicationStatement, orderMedicationStatement); } } \ No newline at end of file diff --git a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/DocumentReferenceMapperTest.java b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/DocumentReferenceMapperTest.java index ceebf2db4..d29d5eabd 100644 --- a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/DocumentReferenceMapperTest.java +++ b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/DocumentReferenceMapperTest.java @@ -21,24 +21,24 @@ import java.util.List; import java.util.Optional; -import org.hl7.fhir.dstu3.model.CodeableConcept; + import org.hl7.fhir.dstu3.model.DocumentReference; -import org.hl7.fhir.dstu3.model.Encounter; import org.hl7.fhir.dstu3.model.Identifier; import org.hl7.fhir.dstu3.model.Meta; import org.hl7.fhir.dstu3.model.Organization; +import org.hl7.fhir.dstu3.model.Encounter; +import org.hl7.fhir.dstu3.model.CodeableConcept; import org.hl7.fhir.dstu3.model.Patient; + import org.hl7.v3.CD; import org.hl7.v3.CV; import org.hl7.v3.RCMRMT030101UKEhrExtract; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import lombok.SneakyThrows; @@ -87,13 +87,9 @@ class DocumentReferenceMapperTest { @Captor private ArgumentCaptor> externalDocumentCaptor; - @BeforeEach - void setup() { - configureCommonStubs(); - } - @Test void mapNarrativeStatementToDocumentReferenceWithValidData() { + registerDefaultDependencies(codeableConceptMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("narrative_statement_has_referred_to_external_document.xml"); List documentReferences = documentReferenceMapper.mapResources(ehrExtract, createPatient(), getEncounterList(), AUTHOR_ORG, createAttachmentList()); @@ -104,11 +100,10 @@ void mapNarrativeStatementToDocumentReferenceWithValidData() { @Test void mapNarrativeStatementToDocumentReferenceWithNopatSecurity() { + registerDefaultDependencies(codeableConceptMapper); final Meta stubbedMeta = MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE); - Mockito - .lenient() - .when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( + when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( any(String.class), any(Optional.class), any(Optional.class), any(Optional.class))).thenReturn(stubbedMeta); var ehrExtract = unmarshallEhrExtract("narrative_statement_has_referred_to_external_document_with_optional_data.xml"); @@ -127,7 +122,7 @@ void mapNarrativeStatementToDocumentReferenceWithNopatSecurity() { @Test void mapNarrativeStatementToDocumentReferenceWithOptionalData() { - + registerDefaultDependencies(codeableConceptMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("narrative_statement_has_referred_to_external_document_with_optional_data.xml"); List documentReferences = documentReferenceMapper.mapResources(ehrExtract, createPatient(), getEncounterList(), AUTHOR_ORG, createAttachmentList()); @@ -138,7 +133,7 @@ void mapNarrativeStatementToDocumentReferenceWithOptionalData() { @Test void mapMultipleNarrativeStatementToDocumentReference() { - + registerDefaultDependencies(codeableConceptMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("multiple_narrative_statements_has_referred_to_external_document.xml"); List documentReferences = documentReferenceMapper.mapResources(ehrExtract, createPatient(), getEncounterList(), AUTHOR_ORG, createAttachmentList()); @@ -148,6 +143,7 @@ void mapMultipleNarrativeStatementToDocumentReference() { @Test void mapNarrativeStatementToDocumentReferenceWithAttachments() { + registerDefaultDependencies(codeableConceptMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("narrative_statement_has_referred_to_external_document.xml"); List documentReferences = documentReferenceMapper.mapResources(ehrExtract, createPatient(), getEncounterList(), AUTHOR_ORG, createAttachmentList()); @@ -158,6 +154,7 @@ void mapNarrativeStatementToDocumentReferenceWithAttachments() { @Test void mapNarrativeStatementToDocumentReferenceWithAbsentAttachment() { + registerDefaultDependencies(codeableConceptMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("narrative_statement_has_referred_to_external_document_with_absent_attachment.xml"); List documentReferences = documentReferenceMapper.mapResources(ehrExtract, createPatient(), getEncounterList(), AUTHOR_ORG, new ArrayList<>()); @@ -168,6 +165,7 @@ void mapNarrativeStatementToDocumentReferenceWithAbsentAttachment() { @Test void mapNarrativeStatementToDocumentReferenceWithInvalidEncounterReference() { + registerDefaultDependencies(codeableConceptMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("narrative_statement_with_invalid_encounter.xml"); List documentReferences = documentReferenceMapper.mapResources(ehrExtract, createPatient(), getEncounterList(), AUTHOR_ORG, createAttachmentList()); @@ -178,6 +176,7 @@ void mapNarrativeStatementToDocumentReferenceWithInvalidEncounterReference() { @Test void mapNestedNarrativeStatement() { + registerDefaultDependencies(codeableConceptMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("nested_narrative_statements.xml"); List documentReferences = documentReferenceMapper.mapResources(ehrExtract, createPatient(), @@ -189,6 +188,7 @@ void mapNestedNarrativeStatement() { @Test void mapNarrativeStatementToDocumentReferenceWithNullFlavors() { + registerDefaultDependencies(codeableConceptMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("narrative_statement_null_flavors.xml"); List documentReferences = documentReferenceMapper.mapResources(ehrExtract, createPatient(), getEncounterList(), AUTHOR_ORG, createAttachmentList()); @@ -228,6 +228,7 @@ void mapNarrativeStatementWithoutSnomedCode() { @Test void When_NarrativeStatement_With_ExternalDocumentAndNopatConfidentialityCode_Expect_MetaFromConfidentialityServiceWithSecurity() { + registerDefaultDependencies(codeableConceptMapper); final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("narrative_statement_has_referred_to_external_document_with_nopat.xml"); @@ -253,6 +254,7 @@ void When_NarrativeStatement_With_ExternalDocumentAndNopatConfidentialityCode_Ex @Test void When_NarrativeStatement_With_ExternalDocumentAndNoConfidentialityCode_Expect_MetaFromConfidentialityWithoutSecurity() { + registerDefaultDependencies(codeableConceptMapper); final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("narrative_statement_has_referred_to_external_document.xml"); @@ -384,18 +386,23 @@ private RCMRMT030101UKEhrExtract unmarshallEhrExtract(String fileName) { return unmarshallFile(file, RCMRMT030101UKEhrExtract.class); } - private void configureCommonStubs() { - final CodeableConcept concept = createCodeableConcept(null, SNOMED_SYSTEM, CODING_DISPLAY); - - Mockito.lenient().when(codeableConceptMapper.mapToCodeableConcept( - any(CD.class) - )).thenReturn(concept); - - Mockito.lenient().when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - eq(META_PROFILE), - ehrCompositionCaptor.capture(), - narrativeStatementCaptor.capture(), - externalDocumentCaptor.capture() - )).thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); + public void registerDefaultDependencies(Object... dependencies) { + for (Object dependency : dependencies) { + if (dependency == codeableConceptMapper) { + final CodeableConcept concept = createCodeableConcept(null, SNOMED_SYSTEM, CODING_DISPLAY); + + when(codeableConceptMapper.mapToCodeableConcept( + any(CD.class) + )).thenReturn(concept); + } + if (dependency == confidentialityService) { + when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( + eq(META_PROFILE), + ehrCompositionCaptor.capture(), + narrativeStatementCaptor.capture(), + externalDocumentCaptor.capture() + )).thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); + } + } } } \ No newline at end of file diff --git a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/EncounterMapperTest.java b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/EncounterMapperTest.java index e900836be..ca9483c64 100644 --- a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/EncounterMapperTest.java +++ b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/EncounterMapperTest.java @@ -9,7 +9,6 @@ import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -53,7 +52,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; @@ -138,11 +136,37 @@ public class EncounterMapperTest { private static final String SNOMED_SYSTEM = "http://snomed.info/sct"; + public void registerDefaultDependencies(Object... dependencies) { + for (Object dependency : dependencies) { + if (dependency == codeableConceptMapper) { + setUpCodeableConceptMock(); + } + if (dependency == confidentialityService) { + when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( + any(String.class), any(Optional.class) + )).thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); + } + if (dependency == consultationListMapper) { + when(consultationListMapper.mapToConsultation(any(RCMRMT030101UKEhrComposition.class), any(Encounter.class))) + .thenReturn(getList()); + when(consultationListMapper.mapToTopic(any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class))) + .thenReturn(getList()); + when(consultationListMapper.mapToCategory(any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class))) + .thenReturn(getList()); + } + if (dependency == immunizationChecker) { + when(immunizationChecker.isImmunization(any())).thenAnswer((Answer) invocation -> { + String code = invocation.getArgument(0); + return code.equals("1664081000000114"); + }); + } + } + } + @BeforeEach - public void setup() { + public void setUp() { patient = new Patient(); patient.setId(PATIENT_ID); - setUpCodeableConceptMock(); var location1 = new Location(); location1.setName("Branch Surgery"); @@ -157,21 +181,11 @@ public void setup() { location3.setId(LOCATION_ID); entryLocations = List.of(location1, location2, location3); - - Mockito.lenient() - .when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - any(String.class), any(Optional.class) - )).thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); } @Test public void testEncountersWithMultipleCompoundStatements() { - when(consultationListMapper.mapToConsultation(any(RCMRMT030101UKEhrComposition.class), any(Encounter.class))) - .thenReturn(getList()); - when(consultationListMapper.mapToTopic(any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class))) - .thenReturn(getList()); - when(consultationListMapper.mapToCategory(any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class))) - .thenReturn(getList()); + registerDefaultDependencies(codeableConceptMapper, confidentialityService, consultationListMapper); var ehrExtract = unmarshallEhrExtractElement(ENCOUNTER_WITH_MULTIPLE_COMPOUND_STATEMENTS_XML); @@ -190,12 +204,7 @@ public void testEncountersWithMultipleCompoundStatements() { @Test public void testMapValidEncounterWithSnomedCode() { - when(consultationListMapper.mapToConsultation(any(RCMRMT030101UKEhrComposition.class), any(Encounter.class))) - .thenReturn(getList()); - when(consultationListMapper.mapToTopic(any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class))) - .thenReturn(getList()); - when(consultationListMapper.mapToCategory(any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class))) - .thenReturn(getList()); + registerDefaultDependencies(codeableConceptMapper, consultationListMapper); var ehrExtract = unmarshallEhrExtractElement(FULL_VALID_STRUCTURED_ENCOUNTER_XML); @@ -217,17 +226,10 @@ public void testMapValidEncounterWithSnomedCode() { @Test public void testMapValidEncounterWithoutSnomedCode() { - + registerDefaultDependencies(confidentialityService, consultationListMapper); var codeableConcept = createCodeableConcept(null, "1.2.3.4.5", CODING_DISPLAY); when(codeableConceptMapper.mapToCodeableConcept(any())).thenReturn(codeableConcept); - when(consultationListMapper.mapToConsultation(any(RCMRMT030101UKEhrComposition.class), any(Encounter.class))) - .thenReturn(getList()); - when(consultationListMapper.mapToTopic(any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class))) - .thenReturn(getList()); - when(consultationListMapper.mapToCategory(any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class))) - .thenReturn(getList()); - var ehrExtract = unmarshallEhrExtractElement(FULL_VALID_STRUCTURED_ENCOUNTER_XML); Map> mappedResources = encounterMapper.mapEncounters( @@ -249,26 +251,16 @@ public void testMapValidEncounterWithoutSnomedCode() { @Test public void testMapValidEncounterWithNopatConfidentialityCodeWithinEhrCompositionExpectMetaSecurityAdded() { final Meta stubbedMeta = MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE); + registerDefaultDependencies(consultationListMapper); + final CodeableConcept codeableConcept = createCodeableConcept(null, "1.2.3.4.5", CODING_DISPLAY); when(codeableConceptMapper.mapToCodeableConcept( - any(CD.class)) + any(CD.class)) ).thenReturn(codeableConcept); - when(consultationListMapper.mapToConsultation( - any(RCMRMT030101UKEhrComposition.class), any(Encounter.class)) - ).thenReturn(getList()); - when(consultationListMapper.mapToTopic( - any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class)) - ).thenReturn(getList()); - when(consultationListMapper.mapToCategory( - any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class)) - ).thenReturn(getList()); - - Mockito - .lenient() - .when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( + when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( any(String.class), any(Optional.class) - )).thenReturn(stubbedMeta); + )).thenReturn(stubbedMeta); final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtractElement(ENCOUNTER_WITH_NOPAT_CONFIDENTIALITY_CODE_WITHIN_EHR_COMPOSITION); @@ -289,26 +281,13 @@ public void testMapValidEncounterWithNopatConfidentialityCodeWithinEhrCompositio @Test public void testMapValidEncounterWithNoscrubConfidentialityCodeWithinEhrCompositionExpectMetaSecurityNotAdded() { final Meta metaWithoutSecurity = MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE); + registerDefaultDependencies(confidentialityService, consultationListMapper); + final CodeableConcept codeableConcept = createCodeableConcept(null, "1.2.3.4.5", CODING_DISPLAY); when(codeableConceptMapper.mapToCodeableConcept( - any(CD.class)) + any(CD.class)) ).thenReturn(codeableConcept); - when(consultationListMapper.mapToConsultation( - any(RCMRMT030101UKEhrComposition.class), any(Encounter.class)) - ).thenReturn(getList()); - when(consultationListMapper.mapToTopic( - any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class)) - ).thenReturn(getList()); - when(consultationListMapper.mapToCategory( - any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class)) - ).thenReturn(getList()); - - Mockito - .lenient() - .when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - any(String.class), any(Optional.class) - )).thenReturn(metaWithoutSecurity); final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtractElement(ENCOUNTER_WITH_NOSCRUB_CONFIDENTIALITY_CODE_WITHIN_EHR_COMPOSITION); @@ -328,12 +307,7 @@ public void testMapValidEncounterWithNoscrubConfidentialityCodeWithinEhrComposit @Test public void testValidEncounterWithFullDataWithStructuredConsultation() { - when(consultationListMapper.mapToConsultation(any(RCMRMT030101UKEhrComposition.class), any(Encounter.class))) - .thenReturn(getList()); - when(consultationListMapper.mapToTopic(any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class))) - .thenReturn(getList()); - when(consultationListMapper.mapToCategory(any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class))) - .thenReturn(getList()); + registerDefaultDependencies(codeableConceptMapper, confidentialityService, consultationListMapper); var ehrExtract = unmarshallEhrExtractElement(FULL_VALID_STRUCTURED_ENCOUNTER_XML); @@ -368,12 +342,7 @@ public void testValidEncounterWithFullDataWithStructuredConsultation() { @Test public void testValidEncounterWithLinkSetWithStructuredConsultation() { - when(consultationListMapper.mapToConsultation(any(RCMRMT030101UKEhrComposition.class), any(Encounter.class))) - .thenReturn(getList()); - when(consultationListMapper.mapToTopic(any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class))) - .thenReturn(getList()); - when(consultationListMapper.mapToCategory(any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class))) - .thenReturn(getList()); + registerDefaultDependencies(codeableConceptMapper, confidentialityService, consultationListMapper); var ehrExtract = unmarshallEhrExtractElement(FULL_VALID_STRUCTURED_ENCOUNTER_WITH_LINKSET_XML); @@ -421,8 +390,10 @@ public void testValidEncounterWithLinkSetWithStructuredConsultation() { @Test public void testValidEncounterWithFlatConsultationWithLinkSet() { + registerDefaultDependencies(codeableConceptMapper, confidentialityService); + when(consultationListMapper.mapToConsultation(any(RCMRMT030101UKEhrComposition.class), any(Encounter.class))) - .thenReturn(getList()); + .thenReturn(getList()); when(consultationListMapper.mapToTopic(any(ListResource.class), isNull())).thenReturn(getList()); var ehrExtract = unmarshallEhrExtractElement(FULL_VALID_FLAT_ENCOUNTER_WITH_LINK_SET_XML); @@ -455,11 +426,11 @@ public void testValidEncounterWithFlatConsultationWithLinkSet() { @Test public void testValidEncounterWithFullDataWithFlatConsultation() { - when(consultationListMapper.mapToConsultation(any(RCMRMT030101UKEhrComposition.class), any(Encounter.class))) - .thenReturn(getList()); - when(consultationListMapper.mapToTopic(any(ListResource.class), isNull())) - .thenReturn(getList()); + registerDefaultDependencies(codeableConceptMapper, confidentialityService); + when(consultationListMapper.mapToConsultation(any(RCMRMT030101UKEhrComposition.class), any(Encounter.class))) + .thenReturn(getList()); + when(consultationListMapper.mapToTopic(any(ListResource.class), isNull())).thenReturn(getList()); var ehrExtract = unmarshallEhrExtractElement(FULL_VALID_FLAT_ENCOUNTER_XML); Map> mappedResources = encounterMapper.mapEncounters( @@ -487,10 +458,11 @@ public void testValidEncounterWithFullDataWithFlatConsultation() { @Test public void testValidEncounterWithNoOptionalDataWithFlatConsultation() { + registerDefaultDependencies(codeableConceptMapper, confidentialityService); + when(consultationListMapper.mapToConsultation(any(RCMRMT030101UKEhrComposition.class), any(Encounter.class))) - .thenReturn(getList()); - when(consultationListMapper.mapToTopic(any(ListResource.class), isNull())) - .thenReturn(getList()); + .thenReturn(getList()); + when(consultationListMapper.mapToTopic(any(ListResource.class), isNull())).thenReturn(getList()); var ehrExtract = unmarshallEhrExtractElement(NO_OPTIONAL_FLAT_ENCOUNTER_XML); @@ -518,12 +490,7 @@ public void testValidEncounterWithNoOptionalDataWithFlatConsultation() { @Test public void testEncounterWithMappedResourcesWithStructuredConsultation() { - when(consultationListMapper.mapToConsultation(any(RCMRMT030101UKEhrComposition.class), any(Encounter.class))) - .thenReturn(getList()); - when(consultationListMapper.mapToTopic(any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class))) - .thenReturn(getList()); - when(consultationListMapper.mapToCategory(any(ListResource.class), any(RCMRMT030101UKCompoundStatement.class))) - .thenReturn(getList()); + registerDefaultDependencies(codeableConceptMapper, confidentialityService, consultationListMapper); var ehrExtract = unmarshallEhrExtractElement(FULL_VALID_STRUCTURED_ENCOUNTER_WITH_RESOURCES_XML); @@ -561,6 +528,7 @@ public void testEncounterWithMappedResourcesWithStructuredConsultation() { @Test public void testEncounterWithMappedResourcesWithFlatConsultation() { + registerDefaultDependencies(codeableConceptMapper, confidentialityService); when(consultationListMapper.mapToConsultation(any(RCMRMT030101UKEhrComposition.class), any(Encounter.class))) .thenReturn(getList()); when(consultationListMapper.mapToTopic(any(ListResource.class), isNull())).thenReturn(getList()); @@ -595,9 +563,12 @@ public void testEncounterWithMappedResourcesWithFlatConsultation() { @Test public void testEncounterWithMappedResourcesWithFlatConsultationThatItReturnsRelatedProblemsForConditions() { + registerDefaultDependencies(codeableConceptMapper, confidentialityService); + when(consultationListMapper.mapToConsultation(any(RCMRMT030101UKEhrComposition.class), any(Encounter.class))) - .thenReturn(getList()); + .thenReturn(getList()); when(consultationListMapper.mapToTopic(any(ListResource.class), isNull())).thenReturn(getList()); + String conditionTopicListEntry = "Condition/4971E81E-693C-11EE-9D98-00155D78C707"; doAnswer(invocation -> { List list = invocation.getArgument(1); @@ -727,13 +698,8 @@ private void assertPeriod(Period period, String startDate, String endDate) { } private void setUpCodeableConceptMock() { - var codeableConcept = createCodeableConcept(null, SNOMED_SYSTEM, CODING_DISPLAY); - lenient().when(codeableConceptMapper.mapToCodeableConcept(any())).thenReturn(codeableConcept); - lenient().when(immunizationChecker.isImmunization(any())).thenAnswer((Answer) invocation -> { - String code = invocation.getArgument(0); - return code.equals("1664081000000114"); - }); + when(codeableConceptMapper.mapToCodeableConcept(any())).thenReturn(codeableConcept); } private ListResource getList() { diff --git a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ImmunizationMapperTest.java b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ImmunizationMapperTest.java index bf62b7156..7a4d0fb84 100644 --- a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ImmunizationMapperTest.java +++ b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ImmunizationMapperTest.java @@ -8,7 +8,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; import static org.springframework.util.ResourceUtils.getFile; @@ -26,7 +25,6 @@ import org.hl7.fhir.dstu3.model.Patient; import org.hl7.v3.CV; import org.hl7.v3.RCMRMT030101UKEhrExtract; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; @@ -76,13 +74,9 @@ public class ImmunizationMapperTest { @Captor private ArgumentCaptor> confidentialityCodeCaptor; - @BeforeEach - public void setup() { - configureDefaultStubs(); - } - @Test public void mapObservationToImmunizationWithValidData() { + registerDefaultDependencies(codeableConceptMapper, immunizationMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("full_valid_immunization.xml"); List immunizationList = immunizationMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); @@ -92,6 +86,7 @@ public void mapObservationToImmunizationWithValidData() { @Test public void mapObservationToImmunizationWithMissingValues() { + registerDefaultDependencies(codeableConceptMapper, immunizationMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("immunization_with_missing_optional_values.xml"); List immunizationList = immunizationMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); @@ -101,6 +96,7 @@ public void mapObservationToImmunizationWithMissingValues() { @Test public void mapObservationToImmunizationWhenEhrCompositionIdIsNotPresentOnEncounterList() { + registerDefaultDependencies(codeableConceptMapper, immunizationMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("immunization_with_ehr_composition_id_not_matching_encounter_id.xml"); List immunizationList = immunizationMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); @@ -110,6 +106,7 @@ public void mapObservationToImmunizationWhenEhrCompositionIdIsNotPresentOnEncoun @Test public void mapObservationToImmunizationWhenEhrCompositionWithParticipantAndAuthor() { + registerDefaultDependencies(codeableConceptMapper, immunizationMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("immunization_with_ehr_composition_with_author_and_participant.xml"); List immunizationList = immunizationMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); @@ -127,6 +124,7 @@ public void mapObservationToImmunizationWhenEhrCompositionWithParticipantAndAuth @Test public void mapObservationToImmunizationWhenEhrCompositionWithOneObservationParticipant() { + registerDefaultDependencies(codeableConceptMapper, immunizationMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("immunization_with_ehr_composition_with_one_observation_participant.xml"); List immunizationList = immunizationMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); @@ -139,6 +137,7 @@ public void mapObservationToImmunizationWhenEhrCompositionWithOneObservationPart @Test public void mapObservationToImmunizationWithMultipleObservationStatements() { + registerDefaultDependencies(codeableConceptMapper, immunizationMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("full_valid_immunization_with_multiple_observation_statements.xml"); List immunizationList = immunizationMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); @@ -151,6 +150,7 @@ public void mapObservationToImmunizationWithMultipleObservationStatements() { @Test public void mapObservationToImmunizationAndCheckCodingDisplayAndVaccineProcedureUrl() { + registerDefaultDependencies(codeableConceptMapper, immunizationMapper, confidentialityService); final String VACCINE_PROCEDURE_URL = "https://fhir.hl7.org.uk/STU3/StructureDefinition/Extension-CareConnect-VaccinationProcedure-1"; var ehrExtract = unmarshallEhrExtract("full_valid_immunization_with_multiple_observation_statements.xml"); List immunizationList = immunizationMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); @@ -163,6 +163,7 @@ public void mapObservationToImmunizationAndCheckCodingDisplayAndVaccineProcedure @Test public void mapObservationToImmunizationWithEffectiveTimeCenter() { + registerDefaultDependencies(codeableConceptMapper, immunizationMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("immunization_with_only_center_effective_time.xml"); List immunizationList = immunizationMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); @@ -172,6 +173,7 @@ public void mapObservationToImmunizationWithEffectiveTimeCenter() { @Test public void mapObservationToImmunizationWithEffectiveTimeLow() { + registerDefaultDependencies(codeableConceptMapper, immunizationMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("immunization_with_only_low_effective_time.xml"); List immunizationList = immunizationMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); @@ -181,6 +183,7 @@ public void mapObservationToImmunizationWithEffectiveTimeLow() { @Test public void mapObservationToImmunizationWithHighAndLowEffectiveTime() { + registerDefaultDependencies(codeableConceptMapper, immunizationMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("immunization_with_high_and_low_effective_time.xml"); List immunizationList = immunizationMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); @@ -190,6 +193,7 @@ public void mapObservationToImmunizationWithHighAndLowEffectiveTime() { @Test public void mapObservationToImmunizationWithHighEffectiveTime() { + registerDefaultDependencies(codeableConceptMapper, immunizationMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("immunization_with_only_high_effective_time.xml"); List immunizationList = immunizationMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); @@ -199,6 +203,7 @@ public void mapObservationToImmunizationWithHighEffectiveTime() { @Test public void mapObservationToImmunizationWithUNKVaccineCode() { + registerDefaultDependencies(codeableConceptMapper, immunizationMapper, confidentialityService); var ehrExtract = unmarshallEhrExtract("immunization_with_only_high_effective_time.xml"); List immunizationList = immunizationMapper.mapResources(ehrExtract, getPatient(), getEncounterList(), PRACTISE_CODE); @@ -208,6 +213,7 @@ public void mapObservationToImmunizationWithUNKVaccineCode() { @Test public void When_EhrCompositionWithNoPatConfidentialityCode_Expect_MetaFromConfidentialityServiceWithSecurity() { + registerDefaultDependencies(codeableConceptMapper, immunizationMapper); final var metaWithSecurity = MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE); when( confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( @@ -244,6 +250,7 @@ ehrExtract, getPatient(), @Test public void When_ObservationWithNoPatConfidentialityCode_Expect_MetaFromConfidentialityServiceWithSecurity() { + registerDefaultDependencies(codeableConceptMapper, immunizationMapper); final var metaWithSecurity = MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE); when( confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( @@ -341,18 +348,24 @@ private void assertThatIdentifierIsValid(Identifier identifier, String id) { assertEquals(id, identifier.getValue()); } - private void configureDefaultStubs() { - - when(codeableConceptMapper.mapToCodeableConcept(any())) - .thenReturn(createCodeableConcept(null, null, CODING_DISPLAY)); - when(immunizationChecker.isImmunization(any())).thenReturn(true); - lenient() - .when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - eq("Immunization-1"), - eq(Optional.empty()), - eq(Optional.empty()) - )) - .thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); + public void registerDefaultDependencies(Object... dependencies) { + for (Object dependency : dependencies) { + if (dependency == codeableConceptMapper) { + when(codeableConceptMapper.mapToCodeableConcept(any())) + .thenReturn(createCodeableConcept(null, null, CODING_DISPLAY)); + } + if (dependency == immunizationMapper) { + when(immunizationChecker.isImmunization(any())).thenReturn(true); + } + if (dependency == confidentialityService) { + when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( + eq("Immunization-1"), + eq(Optional.empty()), + eq(Optional.empty()) + )) + .thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); + } + } } private Patient getPatient() { diff --git a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ObservationMapperTest.java b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ObservationMapperTest.java index 808126446..cd31732a6 100644 --- a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ObservationMapperTest.java +++ b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ObservationMapperTest.java @@ -4,7 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; import static org.springframework.util.ResourceUtils.getFile; @@ -495,7 +494,7 @@ public void When_MapObservation_WithoutSnomedCodeInCode_Expect_DegradedCodeableC public void When_MapObservation_WithSnomedCodeInCode_Expect_MappedWithoutDegrading() { var codeableConcept = createCodeableConcept(null, SNOMED_SYSTEM, CODING_DISPLAY_MOCK); - lenient().when(codeableConceptMapper.mapToCodeableConcept(any())).thenReturn(codeableConcept); + when(codeableConceptMapper.mapToCodeableConcept(any())).thenReturn(codeableConcept); var ehrExtract = unmarshallEhrExtractElement("full_valid_data_observation_example.xml"); var observation = observationMapper.mapResources(ehrExtract, patient, ENCOUNTER_LIST, PRACTISE_CODE).getFirst(); diff --git a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ReferralRequestMapperTest.java b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ReferralRequestMapperTest.java index 262571eaa..f55571b47 100644 --- a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ReferralRequestMapperTest.java +++ b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/ReferralRequestMapperTest.java @@ -35,7 +35,6 @@ import org.hl7.v3.RCMRMT030101UKEhrComposition; import org.hl7.v3.RCMRMT030101UKEhrExtract; import org.hl7.v3.RCMRMT030101UKRequestStatement; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; @@ -45,7 +44,6 @@ import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import lombok.SneakyThrows; @@ -83,13 +81,9 @@ class ReferralRequestMapperTest { @Captor private ArgumentCaptor> confidentialityCodeCaptor; - @BeforeEach - void beforeEach() { - configureCommonStubs(); - } - @Test void mapReferralRequestWithReferralRequestAsOrganization() { + registerDefaultDependencies(confidentialityService); var codeableConcept = createCodeableConcept(REASON_CODE_1, SNOMED_SYSTEM, CODING_DISPLAY); when(codeableConceptMapper.mapToCodeableConcept(any())) @@ -120,7 +114,7 @@ void mapReferralRequestWithReferralRequestAsOrganization() { @Test void mapReferralRequestWithValidData() { - + registerDefaultDependencies(confidentialityService); var codeableConcept = createCodeableConcept(REASON_CODE_1, SNOMED_SYSTEM, CODING_DISPLAY); when(codeableConceptMapper.mapToCodeableConcept(any())) @@ -155,6 +149,7 @@ void mapReferralRequestWithValidData() { @Test void mapReferralRequestWithNoOptionalData() { + registerDefaultDependencies(confidentialityService); var inputXml = """ @@ -184,6 +179,7 @@ void mapReferralRequestWithNoOptionalData() { @Test void mapReferralRequestWithNoReferencedEncounter() { + registerDefaultDependencies(confidentialityService); var inputXml = """ @@ -206,6 +202,7 @@ void mapReferralRequestWithNoReferencedEncounter() { @Test void mapReferralRequestWithRequesterPrfParticipant() { + registerDefaultDependencies(confidentialityService); var inputXml = """ @@ -245,6 +242,7 @@ void mapReferralRequestWithRequesterPrfParticipant() { @Test void mapReferralRequestWithRequesterEhrCompositionParticipant2() { + registerDefaultDependencies(confidentialityService); var inputXml = """ @@ -284,6 +282,7 @@ void mapReferralRequestWithRequesterEhrCompositionParticipant2() { @Test void mapReferralRequestWithRecipientResponsiblePartyNoValidTypeCode() { + registerDefaultDependencies(confidentialityService); var inputXml = """ @@ -334,6 +333,7 @@ void mapReferralRequestWithRecipientResponsiblePartyNoValidTypeCode() { @Test void mapReferralRequestWithPriorityNoteWithUsingDisplayName() { + registerDefaultDependencies(confidentialityService); var inputXml = """ @@ -366,6 +366,7 @@ void mapReferralRequestWithPriorityNoteWithUsingDisplayName() { @Test void mapDegradedReferralRequest() { + registerDefaultDependencies(confidentialityService); when(codeableConceptMapper.mapToCodeableConcept(any())) .thenReturn(new CodeableConcept().addCoding(new Coding())); @@ -421,6 +422,7 @@ void mapReferralRequestPriority(String code, String display, String expectedDisp @Test void When_MapToReferralRequest_With_NestedRequestStatement_Expect_PriorityCodeMapped() { + registerDefaultDependencies(confidentialityService); var ehrComposition = unmarshallEhrCompositionElement("nested_request_statement.xml"); var referralRequest = mapReferralRequest(null, ehrComposition, this::getNestedRequestStatement); @@ -430,7 +432,7 @@ void When_MapToReferralRequest_With_NestedRequestStatement_Expect_PriorityCodeMa @Test void When_MapToReferralRequest_With_MissingPriorityCode_Expect_PriorityCodeNotMapped() { - + registerDefaultDependencies(confidentialityService); var ehrExtract = unmarshallEhrExtractElement("request_statement_missing_priority_code.xml"); var referralRequest = mapReferralRequest(ehrExtract, @@ -448,6 +450,7 @@ void When_MapToReferralRequest_With_MissingPriorityCode_Expect_PriorityCodeNotMa @Test void When_MapToReferralRequest_With_TwoNestedRequestStatements_Expect_CorrectPriorityCodeMapped() { + registerDefaultDependencies(confidentialityService); var ehrComposition = unmarshallEhrCompositionElement("two_nested_request_statements.xml"); var referralRequest = mapReferralRequest(null, ehrComposition, this::getNestedRequestStatement); @@ -457,7 +460,7 @@ void When_MapToReferralRequest_With_TwoNestedRequestStatements_Expect_CorrectPri @Test void When_MapToReferralRequest_With_UnexpectedPriorityCode_Expect_PriorityFieldNotPopulated() { - + registerDefaultDependencies(confidentialityService); var ehrExtract = unmarshallEhrExtractElement("request_statement_unexpected_priority_code.xml"); var referralRequest = mapReferralRequest(ehrExtract, @@ -475,7 +478,7 @@ void When_MapToReferralRequest_With_UnexpectedPriorityCode_Expect_PriorityFieldN @Test void When_MapToReferralRequest_With_UnexpectedPriorityCode_Expect_PriorityAddedToNotes() { - + registerDefaultDependencies(confidentialityService); var ehrExtract = unmarshallEhrExtractElement("request_statement_unexpected_priority_code.xml"); var referralRequest = mapReferralRequest(ehrExtract, @@ -556,6 +559,7 @@ void When_MapToReferralRequest_With_NopatConfidentialityCodeWithinEhrComposition @Test void When_MappingReferralRequestReferencedByReferralRequestToExternalDocumentLinkSet_Expect_SupportingInfoReferencesLinksetDocuments() { + registerDefaultDependencies(confidentialityService); final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtractElement( "ResourceFilter", "ehr_extract_with_referral_request_to_external_document_linkset.xml" @@ -579,6 +583,7 @@ void When_MappingReferralRequestReferencedByReferralRequestToExternalDocumentLin @Test void When_ReferralRequestReferencedByMultipleLinkSets_Expect_AllRelatedDocumentReferencesAddedAsSupportingInfo() { + registerDefaultDependencies(confidentialityService); final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtractElement( "ehr_extract_with_multiple_request_statement_to_external_document_linksets.xml" ); @@ -682,11 +687,15 @@ private RCMRMT030101UKEhrExtract unmarshallStringToEhrExtractElement(String inpu return unmarshallString(inputXml, RCMRMT030101UKEhrExtract.class); } - private void configureCommonStubs() { - Mockito.lenient().when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - eq(META_PROFILE), - confidentialityCodeCaptor.capture(), - confidentialityCodeCaptor.capture() - )).thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); + public void registerDefaultDependencies(Object... dependencies) { + for (Object dependency : dependencies) { + if (dependency == confidentialityService) { + when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( + eq(META_PROFILE), + confidentialityCodeCaptor.capture(), + confidentialityCodeCaptor.capture() + )).thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); + } + } } } \ No newline at end of file diff --git a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/medication/MedicationRequestMapperTest.java b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/medication/MedicationRequestMapperTest.java index 449d45ead..6d13d590f 100644 --- a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/medication/MedicationRequestMapperTest.java +++ b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/medication/MedicationRequestMapperTest.java @@ -27,7 +27,6 @@ import org.hl7.v3.RCMRMT030101UKPrescribe; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -46,7 +45,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -122,14 +120,10 @@ public class MedicationRequestMapperTest { @InjectMocks private MedicationRequestMapper medicationRequestMapper; - @BeforeEach - void beforeEach() { - setupCommonStubs(); - } - - @Test void When_MappingMedicationStatement_Expect_CorrectMappersToBeCalled() { + registerDependencies(medicationRequestPlanMapper, medicationStatementMapper, medicationRequestOrderMapper, medicationMapper); + final RCMRMT030101UKEhrExtract ehrExtract = unmarshallEhrExtract("ehrExtract1.xml"); final RCMRMT030101UKEhrComposition ehrComposition = ehrExtract.getComponent().getFirst().getEhrFolder().getComponent().getFirst().getEhrComposition(); @@ -175,6 +169,7 @@ void When_MappingMedicationStatement_Expect_CorrectMappersToBeCalled() { @Test public void When_MappingMedicationRequestWithAvailabilityTimeInMedicationStatement_Expect_UseThatAvailabilityTime() { + registerDependencies(medicationRequestPlanMapper, medicationStatementMapper, medicationRequestOrderMapper, medicationMapper); var ehrExtract = unmarshallEhrExtract("ehrExtract_AvailabilityTimeSetInMedicationStatement.xml"); var expectedAuthoredOn = DateFormatUtil.parseToDateTimeType("20100116"); @@ -195,6 +190,7 @@ public void When_MappingMedicationRequestWithAvailabilityTimeInMedicationStateme @Test public void When_MappingMedicationRequestWithAvailabilityTimeNotInMedicationStatement_Expect_AuthoredOnMapped() { + registerDependencies(medicationRequestPlanMapper, medicationStatementMapper, medicationRequestOrderMapper, medicationMapper); var ehrExtract = unmarshallEhrExtract("ehrExtract_AvailabilityTimeNotInMedicationStatement.xml"); var expectedAuthoredOn = DateFormatUtil.parseToDateTimeType("20100117"); @@ -216,6 +212,7 @@ public void When_MappingMedicationRequestWithAvailabilityTimeNotInMedicationStat @Test public void When_MappingMedicationRequestWithAvailabilityTimeInEhrCompositionAuthor_Expect_UseThatAvailabilityTime() { + registerDependencies(medicationRequestPlanMapper, medicationStatementMapper, medicationRequestOrderMapper, medicationMapper); final int expectedResourcesMapped = 6; final DateTimeType expectedAvailabilityTime = DateFormatUtil.parseToDateTimeType("20220101010101"); @@ -236,6 +233,7 @@ public void When_MappingMedicationRequestWithAvailabilityTimeInEhrCompositionAut @Test public void When_MappingMedicationRequestWithNoEhrCompositionAuthorTime_Expect_UseEhrExtractAvailabilityTime() { + registerDependencies(medicationRequestPlanMapper, medicationStatementMapper, medicationRequestOrderMapper, medicationMapper); final int expectedResourcesMapped = 6; final DateTimeType expectedAvailabilityTime = DateFormatUtil.parseToDateTimeType("20100115"); @@ -256,6 +254,7 @@ public void When_MappingMedicationRequestWithNoEhrCompositionAuthorTime_Expect_U @Test public void When_MappingMedicationRequestWithNoAuthoredOn_Expect_NullAuthoredOn() { + registerDependencies(medicationRequestPlanMapper, medicationRequestOrderMapper, medicationMapper); var ehrExtract = unmarshallEhrExtract("ehrExtract_AvailabilityTimeNotInMedicationStatementOrEhrComposition.xml"); when(medicationStatementMapper.mapToMedicationStatement( @@ -284,6 +283,7 @@ public void When_MappingMedicationRequestWithNoAuthoredOn_Expect_NullAuthoredOn( @Test public void When_MappingMedicationRequestWithAuthoredOnValidDate_Expect_AuthoredOnToUseMedicationAvailabilityTime() { + registerDependencies(medicationRequestPlanMapper, medicationStatementMapper, medicationRequestOrderMapper, medicationMapper); var ehrExtract = unmarshallEhrExtract("ehrExtract_hasAuthorTime.xml"); var expectedAuthoredOn = DateFormatUtil.parseToDateTimeType("20100115"); @@ -304,6 +304,7 @@ public void When_MappingMedicationRequestWithAuthoredOnValidDate_Expect_Authored @Test public void When_MappingMedicationRequestWithAuthoredOnInExtractAndComposition_Expect_AuthoredOnToUseAvailabilityTimeInStatement() { + registerDependencies(medicationRequestPlanMapper, medicationStatementMapper, medicationRequestOrderMapper, medicationMapper); var ehrExtract = unmarshallEhrExtract("ehrExtract_hasAuthorTimeInExtract.xml"); var expectedAuthoredOn = DateFormatUtil.parseToDateTimeType("20100115"); @@ -324,6 +325,7 @@ public void When_MappingMedicationRequestWithAuthoredOnInExtractAndComposition_E @Test public void When_MappingMedicationRequestWithAuthoredOnValidDateInExtractOnly_Expect_AuthoredOnToUseAvailabilityTimeInStatement() { + registerDependencies(medicationRequestPlanMapper, medicationStatementMapper, medicationRequestOrderMapper, medicationMapper); var ehrExtract = unmarshallEhrExtract("ehrExtract_hasAuthorTimeInExtractOnly.xml"); var expectedAuthoredOn = DateFormatUtil.parseToDateTimeType("20100115"); @@ -383,13 +385,13 @@ static void beforeAll() { ); } - @BeforeEach - void beforeEach() { + void setupMultipleOrders() { setupMultipleOrdersToOnePlanStubs(REPEAT_PRESCRIPTION_EXTENSION, MedicationStatementStatus.ACTIVE, true); } @Test void expectNoAdditionalPlanCreated() { + setupMultipleOrders(); var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE ); @@ -413,6 +415,7 @@ void expectNoAdditionalPlanCreated() { @Test void expectNoAdditionalMedicationStatementCreated() { + setupMultipleOrders(); var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE ); @@ -447,13 +450,14 @@ static void beforeAll() { "ehrExtract_MultipleSupplyPrescribeInFulfilmentOfSingleAcuteSupplyAuthorise.xml" ); } - @BeforeEach - void beforeEach() { + + void setupMultipleOrders() { setupMultipleOrdersToOnePlanStubs(ACUTE_PRESCRIPTION_EXTENSION, MedicationStatementStatus.ACTIVE, true); } @Test void expectAdditionalPlanCreated() { + setupMultipleOrders(); var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE ); @@ -477,6 +481,9 @@ void expectAdditionalPlanCreated() { @Test void expectTheGeneratedPlanHasIdAndIdentityUpdatedToGeneratedId() { + registerDependencies(idGeneratorService); + setupMultipleOrders(); + var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE ); @@ -493,6 +500,8 @@ void expectTheGeneratedPlanHasIdAndIdentityUpdatedToGeneratedId() { @Test void expectTheEarliestOrderBasedOnReferencesTheOriginalPlan() { + setupMultipleOrders(); + var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE ); @@ -509,6 +518,9 @@ void expectTheEarliestOrderBasedOnReferencesTheOriginalPlan() { @Test void expectTheLatestOrderBasedOnReferencesTheGeneratedPlan() { + registerDependencies(idGeneratorService); + setupMultipleOrders(); + var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE); @@ -525,6 +537,9 @@ void expectTheLatestOrderBasedOnReferencesTheGeneratedPlan() { @Test void expectTheLatestOrderPriorPrescriptionReferencesTheOriginalPlan() { + registerDependencies(idGeneratorService); + setupMultipleOrders(); + var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE); @@ -542,6 +557,9 @@ void expectTheLatestOrderPriorPrescriptionReferencesTheOriginalPlan() { @Test void expectGeneratedPlanDispenseRequestValidityPeriodIsCopiedFromTheLatestOrder() { + registerDependencies(idGeneratorService); + setupMultipleOrders(); + var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE); @@ -560,6 +578,8 @@ void expectGeneratedPlanDispenseRequestValidityPeriodIsCopiedFromTheLatestOrder( @Test void expectGeneratedPlanAuthoredOnIsSetFromTheValidityPeriodStartOfTheLatestOrder() { + registerDependencies(medicationMapper, idGeneratorService); + setupMultipleOrders(); var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE); @@ -576,6 +596,9 @@ void expectGeneratedPlanAuthoredOnIsSetFromTheValidityPeriodStartOfTheLatestOrde @Test void expectTheLatestOrderUnchangedPropertiesAreCopiedToGeneratedPlan() { + registerDependencies(idGeneratorService); + setupMultipleOrders(); + var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE); @@ -604,6 +627,8 @@ void expectTheLatestOrderUnchangedPropertiesAreCopiedToGeneratedPlan() { @Test void expectAdditionalMedicationStatementCreated() { + setupMultipleOrders(); + var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE ); @@ -626,6 +651,9 @@ void expectAdditionalMedicationStatementCreated() { @Test void expectGeneratedMedicationStatementHasIdAndIdentityUpdatedToGeneratedPlanWithSuffix() { + registerDependencies(idGeneratorService); + setupMultipleOrders(); + var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE ); @@ -642,6 +670,9 @@ void expectGeneratedMedicationStatementHasIdAndIdentityUpdatedToGeneratedPlanWit @Test void expectGeneratedMedicationStatementBasedOnReferencesTheGeneratedPlan() { + registerDependencies(idGeneratorService); + setupMultipleOrders(); + var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE ); @@ -658,6 +689,9 @@ void expectGeneratedMedicationStatementBasedOnReferencesTheGeneratedPlan() { @Test void When_Active_Expect_GeneratedMedicationStatementHasEffectivePeriodSetToOrderValidityPeriod() { + registerDependencies(idGeneratorService); + setupMultipleOrders(); + var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE ); @@ -674,7 +708,8 @@ void When_Active_Expect_GeneratedMedicationStatementHasEffectivePeriodSetToOrder @Test void When_NotActive_Expect_GeneratedStatementHasEffectiveTimeSetToOrderValidityPeriodWhenEndIsPresent() { - setupMultipleOrdersToOnePlanStubs(ACUTE_PRESCRIPTION_EXTENSION, MedicationStatementStatus.COMPLETED, true); + registerDependencies(idGeneratorService); + setupMultipleOrders(); var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE @@ -692,6 +727,8 @@ void When_NotActive_Expect_GeneratedStatementHasEffectiveTimeSetToOrderValidityP @Test void When_NotActive_Expect_GeneratedStatementHasEffectiveTimeEndSetToOrderValidityPeriodStartWhenEndIsNotPresent() { + registerDependencies(idGeneratorService); + setupMultipleOrdersToOnePlanStubs(ACUTE_PRESCRIPTION_EXTENSION, MedicationStatementStatus.COMPLETED, false); var resources = medicationRequestMapper @@ -712,6 +749,9 @@ void When_NotActive_Expect_GeneratedStatementHasEffectiveTimeEndSetToOrderValidi @Test void expectGeneratedMedicationStatementLastIssueDateExtensionSetToValidityPeriodStart() { + registerDependencies(idGeneratorService); + setupMultipleOrders(); + var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE ); @@ -725,6 +765,8 @@ void expectGeneratedMedicationStatementLastIssueDateExtensionSetToValidityPeriod @Test void expectOriginalMedicationStatementLastIssueDateExtensionSetToValidityPeriodStart() { + setupMultipleOrders(); + var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE ); @@ -738,6 +780,9 @@ void expectOriginalMedicationStatementLastIssueDateExtensionSetToValidityPeriodS @Test void expectOriginalMedicationStatementUnchangedPropertiesAreCopiedToGeneratedMedicationStatement() { + registerDependencies(idGeneratorService); + setupMultipleOrders(); + var resources = medicationRequestMapper .mapResources(ehrExtract, (Patient) new Patient().setId(PATIENT_ID), List.of(), PRACTISE_CODE ); @@ -892,7 +937,7 @@ private void setupMultipleOrdersToOnePlanStubs( MedicationStatementStatus medicationStatementStatus, boolean hasOrderValidityPeriodEnd ) { - lenient().when( + when( medicationRequestPlanMapper.mapToPlanMedicationRequest( any(RCMRMT030101UKEhrExtract.class), any(RCMRMT030101UKEhrComposition.class), @@ -906,7 +951,7 @@ private void setupMultipleOrdersToOnePlanStubs( ? "20240103" : null; - lenient().when( + when( medicationRequestOrderMapper.mapToOrderMedicationRequest( any(RCMRMT030101UKEhrExtract.class), any(RCMRMT030101UKEhrComposition.class), @@ -919,9 +964,7 @@ private void setupMultipleOrdersToOnePlanStubs( buildMedicationRequestOrder(EARLIEST_ORDER_ID, "20240101", orderValidityPeriodEnd) ); - lenient().when(idGeneratorService.generateUuid()).thenReturn(GENERATED_PLAN_ID); - - lenient().when( + when( medicationStatementMapper.mapToMedicationStatement( any(RCMRMT030101UKEhrExtract.class), any(RCMRMT030101UKEhrComposition.class), @@ -933,34 +976,45 @@ private void setupMultipleOrdersToOnePlanStubs( ).thenReturn(buildMedicationStatement(medicationStatementStatus)); } - private void setupCommonStubs() { - Mockito.lenient().when(medicationRequestPlanMapper.mapToPlanMedicationRequest( - any(RCMRMT030101UKEhrExtract.class), - any(RCMRMT030101UKEhrComposition.class), - any(RCMRMT030101UKMedicationStatement.class), - any(RCMRMT030101UKAuthorise.class), - any(String.class) - )).thenReturn(new MedicationRequest()); - - Mockito.lenient().when(medicationRequestOrderMapper.mapToOrderMedicationRequest( - any(RCMRMT030101UKEhrExtract.class), - any(RCMRMT030101UKEhrComposition.class), - any(RCMRMT030101UKMedicationStatement.class), - any(RCMRMT030101UKPrescribe.class), - any(String.class) - )).thenReturn(new MedicationRequest()); - - Mockito.lenient().when(medicationStatementMapper.mapToMedicationStatement( - any(RCMRMT030101UKEhrExtract.class), - any(RCMRMT030101UKEhrComposition.class), - any(RCMRMT030101UKMedicationStatement.class), - any(RCMRMT030101UKAuthorise.class), - any(String.class), - any(DateTimeType.class) - )).thenReturn(new MedicationStatement()); - - Mockito.lenient().when(medicationMapper.createMedication( - any(RCMRMT030101UKConsumable.class) - )).thenReturn(new Medication()); + private void registerDependencies(Object... dependencies) { + for (Object dependency : dependencies) { + if (dependency == medicationRequestPlanMapper) { + Mockito.when(medicationRequestPlanMapper.mapToPlanMedicationRequest( + any(RCMRMT030101UKEhrExtract.class), + any(RCMRMT030101UKEhrComposition.class), + any(RCMRMT030101UKMedicationStatement.class), + any(RCMRMT030101UKAuthorise.class), + any(String.class) + )).thenReturn(new MedicationRequest()); + } + if (dependency == medicationStatementMapper) { + Mockito.when(medicationStatementMapper.mapToMedicationStatement( + any(RCMRMT030101UKEhrExtract.class), + any(RCMRMT030101UKEhrComposition.class), + any(RCMRMT030101UKMedicationStatement.class), + any(RCMRMT030101UKAuthorise.class), + any(String.class), + any(DateTimeType.class) + )).thenReturn(new MedicationStatement()); + } + if (dependency == medicationRequestOrderMapper) { + Mockito.when(medicationRequestOrderMapper.mapToOrderMedicationRequest( + any(RCMRMT030101UKEhrExtract.class), + any(RCMRMT030101UKEhrComposition.class), + any(RCMRMT030101UKMedicationStatement.class), + any(RCMRMT030101UKPrescribe.class), + any(String.class) + )).thenReturn(new MedicationRequest()); + } + if (dependency == medicationMapper) { + Mockito.when(medicationMapper.createMedication( + any(RCMRMT030101UKConsumable.class) + )).thenReturn(new Medication()); + } + if (dependency == idGeneratorService) { + when(idGeneratorService.generateUuid()).thenReturn(GENERATED_PLAN_ID); + } + } } + } \ No newline at end of file diff --git a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/medication/MedicationRequestPlanMapperTest.java b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/medication/MedicationRequestPlanMapperTest.java index 4650eb596..3c9dd22d0 100644 --- a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/medication/MedicationRequestPlanMapperTest.java +++ b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/medication/MedicationRequestPlanMapperTest.java @@ -44,7 +44,6 @@ import org.hl7.v3.RCMRMT030101UKEhrFolder; import org.hl7.v3.RCMRMT030101UKMedicationStatement; import org.jetbrains.annotations.NotNull; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Named; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -55,7 +54,6 @@ import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import lombok.SneakyThrows; @@ -115,21 +113,26 @@ class MedicationRequestPlanMapperTest { @Captor private ArgumentCaptor> confidentialityCodeCaptor; - @BeforeEach - void setup() { - when(medicationMapper.extractMedicationReference( - any(RCMRMT030101UKMedicationStatement.class) - )).thenReturn(getReference()); - - Mockito.lenient().when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - eq(META_PROFILE), - confidentialityCodeCaptor.capture(), - confidentialityCodeCaptor.capture() - )).thenReturn(META_WITHOUT_SECURITY_ADDED); + public void registerDefaultDependencies(Object... dependencies) { + for (Object dependency : dependencies) { + if (dependency == medicationMapper) { + when(medicationMapper.extractMedicationReference( + any(RCMRMT030101UKMedicationStatement.class) + )).thenReturn(getReference()); + } + if (dependency == confidentialityService) { + when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( + eq(META_PROFILE), + confidentialityCodeCaptor.capture(), + confidentialityCodeCaptor.capture() + )).thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); + } + } } @Test void When_MappingAuthoriseResourceWithAllOptionals_Expect_AllFieldsToBeMappedCorrectly() { + registerDefaultDependencies(medicationMapper, confidentialityService); var medicationStatementXml = """ @@ -225,6 +228,7 @@ void When_MappingAuthoriseResourceWithAllOptionals_Expect_AllFieldsToBeMappedCor @Test void When_MappingAuthoriseResourceWithNoEffectiveTime_Expect_NoExpiryDateExtensionAdded() { + registerDefaultDependencies(medicationMapper, confidentialityService); var medicationStatementXml = """ @@ -247,6 +251,7 @@ void When_MappingAuthoriseResourceWithNoEffectiveTime_Expect_NoExpiryDateExtensi @Test void When_MappingAuthoriseResourceEffectiveTimeWithNullHighValue_Expect_NoExpiryDateExtensionAdded() { + registerDefaultDependencies(medicationMapper, confidentialityService); var medicationStatementXml = """ @@ -272,6 +277,7 @@ void When_MappingAuthoriseResourceEffectiveTimeWithNullHighValue_Expect_NoExpiry @Test void When_MappingDiscontinueWithPertinentInformation_Expect_StatusReasonAdded() { + registerDefaultDependencies(medicationMapper, confidentialityService); var ehrSupplyDiscontinue = """ @@ -298,6 +304,7 @@ void When_MappingDiscontinueWithPertinentInformation_Expect_StatusReasonAdded() @Test void When_MappingDiscontinueWithCodeDisplayAndMissingPertinentInformation_Expect_DefaultTextAddedAsReason() { + registerDefaultDependencies(medicationMapper, confidentialityService); var ehrSupplyDiscontinue = """ @@ -323,6 +330,7 @@ void When_MappingDiscontinueWithCodeDisplayAndMissingPertinentInformation_Expect @Test void When_MappingDiscontinue_With_NoPertinentInformationAndHasCodeOriginalText_Expect_OriginalTextAndDefaultText() { + registerDefaultDependencies(medicationMapper, confidentialityService); var ehrSupplyDiscontinue = """ @@ -347,6 +355,7 @@ void When_MappingDiscontinue_With_NoPertinentInformationAndHasCodeOriginalText_E @Test void When_MappingDiscontinue_With_MissingPertinentInformation_Expect_DefaultTextAddedAsReason() { + registerDefaultDependencies(medicationMapper, confidentialityService); var ehrSupplyDiscontinue = """ @@ -369,6 +378,7 @@ void When_MappingDiscontinue_With_MissingPertinentInformation_Expect_DefaultText @ParameterizedTest @MethodSource void When_MappingDiscontinue_WithPertinentInformationAndOriginalText_Expect_StatusReasonIs( String pertinentInformationText, String originalText, String expectedReason ) { + registerDefaultDependencies(medicationMapper, confidentialityService); var ehrSupplyDiscontinue = """ @@ -398,6 +408,7 @@ void When_MappingDiscontinue_With_MissingPertinentInformation_Expect_DefaultText @Test void When_MappingAuthoriseResource_WithActiveStatusAndNoDiscontinue_Expect_ActiveStatus() { + registerDefaultDependencies(medicationMapper, confidentialityService); var medicationStatementXml = """ @@ -419,6 +430,7 @@ void When_MappingAuthoriseResource_WithActiveStatusAndNoDiscontinue_Expect_Activ @Test void When_MappingAuthoriseResource_WithCompleteStatusAndNoDiscontinue_Expect_CompletedStatus() { + registerDefaultDependencies(medicationMapper, confidentialityService); var medicationStatementXml = """ @@ -440,6 +452,7 @@ void When_MappingAuthoriseResource_WithCompleteStatusAndNoDiscontinue_Expect_Com @Test void When_MappingAuthoriseResource_With_NoDiscontinue_Expect_NoStatusReasonExtension() { + registerDefaultDependencies(medicationMapper, confidentialityService); var medicationStatementXml = """ @@ -461,6 +474,7 @@ void When_MappingAuthoriseResource_With_NoDiscontinue_Expect_NoStatusReasonExten @Test void When_MappingDiscontinue_With_UnknownDate_Expect_DiscontinueIgnored() { + registerDefaultDependencies(medicationMapper, confidentialityService); var medicationStatementXml = """ @@ -521,6 +535,7 @@ void When_MappingAuthoriseResource_With_ConfidentialityCodeInEhrComposition_Expe @Test void When_MappingAuthoriseResource_Expect_MetaPopulatedFromConfidentialityServiceWithSecurity() { + registerDefaultDependencies(medicationMapper); final Meta meta = MetaUtil.getMetaFor(META_WITH_SECURITY, META_PROFILE); final String medicationStatement = """ @@ -557,6 +572,7 @@ void When_MappingAuthoriseResource_Expect_MetaPopulatedFromConfidentialityServic @Test void When_MappingAuthoriseResource_Expect_MetaPopulatedFromConfidentialityServiceWithNoSecurity() { + registerDefaultDependencies(medicationMapper, confidentialityService); final Meta meta = MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE); final String medicationStatement = """ diff --git a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/medication/MedicationStatementMapperTest.java b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/medication/MedicationStatementMapperTest.java index 0e1edb4bf..2666cc962 100644 --- a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/medication/MedicationStatementMapperTest.java +++ b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/mapper/medication/MedicationStatementMapperTest.java @@ -39,14 +39,12 @@ import org.hl7.v3.RCMRMT030101UKEhrExtract; import org.hl7.v3.RCMRMT030101UKEhrFolder; import org.hl7.v3.RCMRMT030101UKMedicationStatement; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import lombok.SneakyThrows; @@ -84,13 +82,16 @@ class MedicationStatementMapperTest { @Captor private ArgumentCaptor> confidentialityCodeCaptor; - @BeforeEach - void beforeEach() { - Mockito.lenient().when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( - eq(META_PROFILE), - confidentialityCodeCaptor.capture(), - confidentialityCodeCaptor.capture() - )).thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); + public void registerDefaultDependencies(Object... dependencies) { + for (Object dependency : dependencies) { + if (dependency == confidentialityService) { + when(confidentialityService.createMetaAndAddSecurityIfConfidentialityCodesPresent( + eq(META_PROFILE), + confidentialityCodeCaptor.capture(), + confidentialityCodeCaptor.capture() + )).thenReturn(MetaUtil.getMetaFor(META_WITHOUT_SECURITY, META_PROFILE)); + } + } } @Test @@ -238,6 +239,7 @@ void When_MappingPrescribeResourceWithOtcSale_Expect_AllFieldsToBeMappedCorrectl @Test void When_MappingPrescribeResourceWithNoOptionals_Expect_AllFieldsToBeMappedCorrectly() throws JAXBException { + registerDefaultDependencies(confidentialityService); final File file = FileFactory.getXmlFileFor("MedicationStatement", "ehrExtract3.xml"); final RCMRMT030101UKEhrExtract ehrExtract = unmarshallFile(file, RCMRMT030101UKEhrExtract.class); final RCMRMT030101UKEhrComposition ehrComposition = GET_EHR_COMPOSITION.apply(ehrExtract); @@ -283,6 +285,7 @@ void When_MappingPrescribeResourceWithNoOptionals_Expect_AllFieldsToBeMappedCorr @Test void When_MappingPrescribeResourceWithNoLastIssueDate_Expect_AllFieldsToBeMappedCorrectly() { + registerDefaultDependencies(confidentialityService); var medicationStatement = unmarshallMedicationStatement("medicationStatementAuthoriseNoOptionals_MedicationStatement.xml"); var authorise = medicationStatement.getComponent() .stream() @@ -323,6 +326,7 @@ void When_MappingPrescribeResourceWithNoLastIssueDate_Expect_AllFieldsToBeMapped @Test void When_MapToMedicationStatement_WithDiscontinue_WithAvailabilityTime_Expect_PeriodEndMappedAndStatusStopped() { + registerDefaultDependencies(confidentialityService); var expectedStartDate = "2010-01-14"; var expectedEndDate = "2010-04-26"; @@ -337,6 +341,7 @@ void When_MapToMedicationStatement_WithDiscontinue_WithAvailabilityTime_Expect_P @Test void When_MapToMedicationStatement_WithDiscontinue_WithMissingAvailabilityTime_Expect_PeriodEndMappedAndStatusCompleted() { + registerDefaultDependencies(confidentialityService); var expectedStartDate = "2010-01-14"; var result = @@ -350,6 +355,7 @@ void When_MapToMedicationStatement_WithDiscontinue_WithMissingAvailabilityTime_E @Test void When_MapToMedicationStatement_WithCompletedStatus_WithAuthoriseEffectiveTimeHigh_Expect_PeriodEndMapped() { + registerDefaultDependencies(confidentialityService); var expectedStartDate = "2010-04-27"; var expectedEndDate = "2010-06-27"; @@ -364,6 +370,7 @@ void When_MapToMedicationStatement_WithCompletedStatus_WithAuthoriseEffectiveTim @Test void When_MapToMedicationStatement_WithCompletedStatus_WithStatementEffectiveTimeHigh_Expect_PeriodEndMapped() { + registerDefaultDependencies(confidentialityService); var expectedStartDate = "2010-01-14"; var expectedEndDate = "2010-06-26"; @@ -377,6 +384,7 @@ void When_MapToMedicationStatement_WithCompletedStatus_WithStatementEffectiveTim @Test void When_MapToMedicationStatement_WithCompletedStatus_WithNoValidTimes_Expect_StartAndEndTimesEqualAuthoredOn() { + registerDefaultDependencies(confidentialityService); var authoredOn = new DateTimeType("2023-01-27"); var result = mapMedicationStatementFromEhrFile("ehrExtract_noValidTimes.xml", authoredOn); @@ -389,6 +397,7 @@ void When_MapToMedicationStatement_WithCompletedStatus_WithNoValidTimes_Expect_S @Test void When_MapToMedicationStatement_WithDiscontinue_WithNoValidTimes_Expect_StartAndEndTimesEqualAuthoredOn() { + registerDefaultDependencies(confidentialityService); var authoredOn = new DateTimeType("2023-01-27"); var result = @@ -402,6 +411,7 @@ void When_MapToMedicationStatement_WithDiscontinue_WithNoValidTimes_Expect_Start @Test void When_MapToMedicationStatement_WithActiveStatement_Expect_StartDateIsNotMappedToEndDate() { + registerDefaultDependencies(confidentialityService); var authoredOn = new DateTimeType("2023-01-27"); var expectedStartDate = "2010-01-14"; diff --git a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/task/COPCMessageHandlerTest.java b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/task/COPCMessageHandlerTest.java index 30b3192ee..47192d1ab 100644 --- a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/task/COPCMessageHandlerTest.java +++ b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/task/COPCMessageHandlerTest.java @@ -12,7 +12,6 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -169,6 +168,7 @@ public void When_CIDFragmentPartIsReceivedBeforeFragmentIndex_Expect_PartialLogT InboundMessage message = new InboundMessage(); prepareFragmentMocks(message); + prepareAttachmentLogs(); // ACT copcMessageHandler.handleMessage(message, CONVERSATION_ID); @@ -192,6 +192,7 @@ public void When_CIDFragmentPartIsReceivedBeforeFragmentIndex_Expect_StoreAttach InboundMessage message = new InboundMessage(); prepareFragmentMocks(message); + prepareAttachmentLogs(); when(patientAttachmentLogService.findAttachmentLog(MESSAGE_ID, CONVERSATION_ID)) .thenReturn(null) .thenReturn(buildPatientAttachmentLog("047C22B4-613F-47D3-9A72-44A1758464FB", null, true)); @@ -1379,16 +1380,6 @@ private void prepareFragmentMocks(InboundMessage inboundMessage) throws SAXExcep when(xPathService.getNodeValue(ebXmlDocument, "/Envelope/Header/MessageHeader/MessageData/MessageId")).thenReturn("CBBAE92D-C7E8" + "-4A9C-8887-F5AEBA1F8CE1").thenReturn("047C22B4-613F-47D3-9A72-44A1758464FB"); - var attachmentLog1 = buildPatientAttachmentLog("047C22B4-613F-47D3-9A72-44A1758464FB", - "CBBAE92D-C7E8-4A9C-8887-F5AEBA1F8CE1", 0, true, true); - - var attachmentLog2 = buildPatientAttachmentLog("057C22B4-613F-47D3-9A72-44A1758464FB", - "CBBAE92D-C7E8-4A9C-8887-F5AEBA1F8CE1", 1, false, true); - - var attachmentArray = Arrays.asList(attachmentLog1, attachmentLog2); - lenient().when(patientAttachmentLogService.findAttachmentLogs(CONVERSATION_ID)) - .thenReturn(attachmentArray); - when(idGeneratorService.generateUuid()).thenReturn(TEST_ID); } @@ -1404,12 +1395,26 @@ private void prepareMocks() { when(migrationRequestDao.getMigrationRequest(CONVERSATION_ID)).thenReturn(migrationRequest); } + private void prepareAttachmentLogMocks() { + } + + private void prepareAttachmentLogs() { var messageId = "CBBAE92D-C7E8-4A9C-8887-F5AEBA1F8CE1"; when(patientAttachmentLogService.findAttachmentLog(messageId, CONVERSATION_ID)).thenReturn(null) .thenReturn(buildPatientAttachmentLog("047C22B4-613F-47D3-9A72-44A1758464FB", null, true)); when(patientAttachmentLogService.findAttachmentLog("047C22B4-613F-47D3-9A72-44A1758464FB", CONVERSATION_ID)) .thenReturn(buildPatientAttachmentLog("047C22B4-613F-47D3-9A72-44A1758464FB", "CBBAE92D-C7E8-4A9C-8887-F5AEBA1F8CE1", true)); + + var attachmentLog1 = buildPatientAttachmentLog("047C22B4-613F-47D3-9A72-44A1758464FB", + "CBBAE92D-C7E8-4A9C-8887-F5AEBA1F8CE1", 0, true, true); + + var attachmentLog2 = buildPatientAttachmentLog("057C22B4-613F-47D3-9A72-44A1758464FB", + "CBBAE92D-C7E8-4A9C-8887-F5AEBA1F8CE1", 1, false, true); + + var attachmentArray = Arrays.asList(attachmentLog1, attachmentLog2); + when(patientAttachmentLogService.findAttachmentLogs(CONVERSATION_ID)) + .thenReturn(attachmentArray); } @SneakyThrows diff --git a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/util/ResourceReferenceUtilTest.java b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/util/ResourceReferenceUtilTest.java index 95d23c575..3368066b7 100644 --- a/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/util/ResourceReferenceUtilTest.java +++ b/gp2gp-translator/src/test/java/uk/nhs/adaptors/pss/translator/util/ResourceReferenceUtilTest.java @@ -2,7 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.when; import static org.springframework.util.ResourceUtils.getFile; import static uk.nhs.adaptors.pss.translator.util.XmlUnmarshallUtil.unmarshallFile; @@ -83,7 +83,20 @@ public void testTemplateChildResourcesReferencedAsQuestionnaireAnswers() { @MethodSource("ehrCompositionResourceFiles") public void testResourcesReferencedAtEhrCompositionLevel(String inputXML, String referenceString) { final RCMRMT030101UKEhrComposition ehrComposition = unmarshallEhrCompositionElement(inputXML); - lenient().when(immunizationChecker.isImmunization(any())).thenAnswer(new Answer() { + + List references = new ArrayList<>(); + resourceReferenceUtil.extractChildReferencesFromEhrComposition(ehrComposition, references); + + assertThat(references.size()).isOne(); + assertThat(references.getFirst().getReference()).isEqualTo(referenceString); + } + + @Test + public void testResourcesReferencedAtEhrCompositionLevelImmunization() { + String inputXML = "ehr_composition_immunization.xml"; + String referenceString = "Immunization/82A39454-299F-432E-993E-5A6232B4E099"; + + when(immunizationChecker.isImmunization(any())).thenAnswer(new Answer() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { RCMRMT030101UKObservationStatement statement = (RCMRMT030101UKObservationStatement) invocation.getArgument(0); @@ -91,6 +104,8 @@ public Boolean answer(InvocationOnMock invocation) throws Throwable { } }); + final RCMRMT030101UKEhrComposition ehrComposition = unmarshallEhrCompositionElement(inputXML); + List references = new ArrayList<>(); resourceReferenceUtil.extractChildReferencesFromEhrComposition(ehrComposition, references); @@ -102,7 +117,6 @@ private static Stream ehrCompositionResourceFiles() { return Stream.of( Arguments.of("ehr_composition_observation_comment.xml", "Observation/5E496953-065B-41F2-9577-BE8F2FBD0757"), Arguments.of("ehr_composition_document_reference.xml", "DocumentReference/5E496953-065B-41F2-9577-BE8F2FBD0757"), - Arguments.of("ehr_composition_immunization.xml", "Immunization/82A39454-299F-432E-993E-5A6232B4E099"), Arguments.of("ehr_composition_allergy_intolerance.xml", "AllergyIntolerance/6D35AFC6-464A-4432-88E0-0A7380E281C5"), Arguments.of("ehr_composition_observation_uncategorised.xml", "Observation/E9396E5B-B81A-4D69-BF0F-DFB1DFE80A33"), Arguments.of("ehr_composition_condition.xml", "Condition/5968B6B2-8E9A-4A78-8979-C8F14F4D274B"), @@ -111,11 +125,13 @@ private static Stream ehrCompositionResourceFiles() { ); } - @ParameterizedTest - @MethodSource("compoundStatementResourceFiles") - public void testResourcesReferencedAtCompoundStatementLevel(String inputXML, String referenceString) { + @Test + public void testResourcesReferencedAtCompoundStatementLevelImmunization() { + String inputXML = "compound_statement_immunization.xml"; + String referenceString = "Immunization/82A39454-299F-432E-993E-5A6232B4E099"; + final RCMRMT030101UKCompoundStatement compoundStatement = unmarshallCompoundStatementElement(inputXML); - lenient().when(immunizationChecker.isImmunization(any())).thenAnswer(new Answer() { + when(immunizationChecker.isImmunization(any())).thenAnswer(new Answer() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { RCMRMT030101UKObservationStatement statement = (RCMRMT030101UKObservationStatement) invocation.getArgument(0); @@ -130,11 +146,22 @@ public Boolean answer(InvocationOnMock invocation) throws Throwable { assertThat(references.getFirst().getReference()).isEqualTo(referenceString); } + @ParameterizedTest + @MethodSource("compoundStatementResourceFiles") + public void testResourcesReferencedAtCompoundStatementLevel(String inputXML, String referenceString) { + final RCMRMT030101UKCompoundStatement compoundStatement = unmarshallCompoundStatementElement(inputXML); + + List references = new ArrayList<>(); + resourceReferenceUtil.extractChildReferencesFromCompoundStatement(compoundStatement, references); + + assertThat(references.size()).isOne(); + assertThat(references.getFirst().getReference()).isEqualTo(referenceString); + } + private static Stream compoundStatementResourceFiles() { return Stream.of( Arguments.of("compound_statement_observation_comment.xml", "Observation/5E496953-065B-41F2-9577-BE8F2FBD0757"), Arguments.of("compound_statement_document_reference.xml", "DocumentReference/5E496953-065B-41F2-9577-BE8F2FBD0757"), - Arguments.of("compound_statement_immunization.xml", "Immunization/82A39454-299F-432E-993E-5A6232B4E099"), Arguments.of("compound_statement_allergy_intolerance.xml", "AllergyIntolerance/6D35AFC6-464A-4432-88E0-0A7380E281C5"), Arguments.of("compound_statement_observation_uncategorised.xml", "Observation/E9396E5B-B81A-4D69-BF0F-DFB1DFE80A33"), Arguments.of("compound_statement_condition.xml", "Condition/5968B6B2-8E9A-4A78-8979-C8F14F4D274B"),