Search in sources :

Example 41 with ValidationResult

use of org.hl7.fhir.r5.context.IWorkerContext.ValidationResult in project dpc-app by CMSgov.

the class OrganizationValidationTest method testAddress.

@Test
void testAddress() {
    final Organization organization = generateFakeOrganization();
    organization.addIdentifier().setSystem(DPCIdentifierSystem.NPPES.getSystem()).setValue("test-value");
    final ValidationResult result = fhirValidator.validateWithResult(organization, new ValidationOptions().addProfile(OrganizationProfile.PROFILE_URI));
    assertAll(() -> assertFalse(result.isSuccessful(), "Should have failed validation"), () -> assertEquals(1, result.getMessages().size(), "Should have a single failure"));
    // Add a text based Address
    organization.addAddress().setText("7500 Security Blvd").setType(Address.AddressType.PHYSICAL).setUse(Address.AddressUse.HOME);
    final ValidationResult r2 = fhirValidator.validateWithResult(organization, new ValidationOptions().addProfile(OrganizationProfile.PROFILE_URI));
    assertAll(() -> assertFalse(r2.isSuccessful(), "Should have failed validation"), () -> assertEquals(6, r2.getMessages().size(), "Should have multiple address failures"));
    // Add valid address
    organization.setAddress(Collections.singletonList(generateFakeAddress()));
    final ValidationResult r3 = fhirValidator.validateWithResult(organization, new ValidationOptions().addProfile(OrganizationProfile.PROFILE_URI));
    assertTrue(r3.isSuccessful(), "Should have passed");
}
Also used : OrganizationFactory.generateFakeOrganization(gov.cms.dpc.testing.factories.OrganizationFactory.generateFakeOrganization) Organization(org.hl7.fhir.dstu3.model.Organization) ValidationResult(ca.uhn.fhir.validation.ValidationResult) ValidationOptions(ca.uhn.fhir.validation.ValidationOptions) Test(org.junit.jupiter.api.Test)

Example 42 with ValidationResult

use of org.hl7.fhir.r5.context.IWorkerContext.ValidationResult in project dpc-app by CMSgov.

the class PractitionerValidationTest method testHasName.

@Test
void testHasName() {
    final Practitioner practitioner = generateFakePractitioner();
    practitioner.addName().setFamily("Patient").addGiven("Test");
    practitioner.addIdentifier().setSystem(DPCIdentifierSystem.NPPES.getSystem()).setValue("test-mpi");
    final ValidationResult result = fhirValidator.validateWithResult(practitioner);
    assertTrue(result.isSuccessful(), "Should have passed");
    // Add a bad name
    practitioner.addName().setFamily("Missing");
    final ValidationResult r2 = fhirValidator.validateWithResult(practitioner);
    assertAll(() -> assertFalse(r2.isSuccessful(), "Should have failed validation"), () -> assertEquals(1, r2.getMessages().size(), "Should have a single failure"));
}
Also used : Practitioner(org.hl7.fhir.dstu3.model.Practitioner) ValidationResult(ca.uhn.fhir.validation.ValidationResult) Test(org.junit.jupiter.api.Test)

Example 43 with ValidationResult

use of org.hl7.fhir.r5.context.IWorkerContext.ValidationResult in project synthea by synthetichealth.

the class FHIRDSTU2ExporterTest method testFHIRDSTU2Export.

@Test
public void testFHIRDSTU2Export() throws Exception {
    TestHelper.loadTestProperties();
    Generator.DEFAULT_STATE = Config.get("test_state.default", "Massachusetts");
    Config.set("exporter.baseDirectory", tempFolder.newFolder().toString());
    FhirContext ctx = FhirDstu2.getContext();
    IParser parser = ctx.newJsonParser().setPrettyPrint(true);
    FhirValidator validator = ctx.newValidator();
    validator.setValidateAgainstStandardSchema(true);
    validator.setValidateAgainstStandardSchematron(true);
    List<String> errors = ParallelTestingService.runInParallel((person) -> {
        List<String> validationErrors = new ArrayList<String>();
        Config.set("exporter.fhir_dstu2.export", "true");
        FhirDstu2.TRANSACTION_BUNDLE = person.randBoolean();
        String fhirJson = FhirDstu2.convertToFHIRJson(person, System.currentTimeMillis());
        // (these should have been converted into URIs)
        if (fhirJson.contains("SNOMED-CT")) {
            validationErrors.add("JSON contains unconverted references to 'SNOMED-CT' (should be URIs)");
        }
        // let's crack open the Bundle and validate
        // each individual entry.resource to get context-sensitive error
        // messages...
        Bundle bundle = parser.parseResource(Bundle.class, fhirJson);
        for (Entry entry : bundle.getEntry()) {
            ValidationResult eresult = validator.validateWithResult(entry.getResource());
            if (!eresult.isSuccessful()) {
                for (SingleValidationMessage emessage : eresult.getMessages()) {
                    if (emessage.getMessage().contains("start SHALL have a lower value than end")) {
                        continue;
                    }
                    System.out.println(parser.encodeResourceToString(entry.getResource()));
                    System.out.println("ERROR: " + emessage.getMessage());
                    validationErrors.add(emessage.getMessage());
                }
            }
            if (entry.getResource() instanceof DiagnosticReport) {
                DiagnosticReport report = (DiagnosticReport) entry.getResource();
                if (report.getPerformer().isEmpty()) {
                    validationErrors.add("Performer is a required field on DiagnosticReport!");
                }
            }
        }
        if (!validationErrors.isEmpty()) {
            Exporter.export(person, System.currentTimeMillis());
        }
        return validationErrors;
    });
    assertTrue("Validation of exported FHIR bundle failed: " + String.join("|", errors), errors.size() == 0);
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) Entry(ca.uhn.fhir.model.dstu2.resource.Bundle.Entry) SingleValidationMessage(ca.uhn.fhir.validation.SingleValidationMessage) Bundle(ca.uhn.fhir.model.dstu2.resource.Bundle) ArrayList(java.util.ArrayList) DiagnosticReport(org.hl7.fhir.dstu3.model.DiagnosticReport) FhirValidator(ca.uhn.fhir.validation.FhirValidator) ValidationResult(ca.uhn.fhir.validation.ValidationResult) IParser(ca.uhn.fhir.parser.IParser) Test(org.junit.Test)

Example 44 with ValidationResult

use of org.hl7.fhir.r5.context.IWorkerContext.ValidationResult in project synthea by synthetichealth.

the class FHIRR4ExporterTest method testFHIRR4Export.

@Test
public void testFHIRR4Export() throws Exception {
    TestHelper.loadTestProperties();
    Generator.DEFAULT_STATE = Config.get("test_state.default", "Massachusetts");
    Config.set("exporter.baseDirectory", tempFolder.newFolder().toString());
    FhirContext ctx = FhirR4.getContext();
    IParser parser = ctx.newJsonParser().setPrettyPrint(true);
    ValidationResources validator = new ValidationResources();
    List<String> errors = ParallelTestingService.runInParallel((person) -> {
        List<String> validationErrors = new ArrayList<String>();
        TestHelper.exportOff();
        FhirR4.TRANSACTION_BUNDLE = person.randBoolean();
        FhirR4.USE_US_CORE_IG = person.randBoolean();
        FhirR4.USE_SHR_EXTENSIONS = false;
        String fhirJson = FhirR4.convertToFHIRJson(person, System.currentTimeMillis());
        // (these should have been converted into URIs)
        if (fhirJson.contains("SNOMED-CT")) {
            validationErrors.add("JSON contains unconverted references to 'SNOMED-CT' (should be URIs)");
        }
        // Let's crack open the Bundle and validate
        // each individual entry.resource to get context-sensitive error
        // messages...
        // IMPORTANT: this approach significantly reduces memory usage when compared to
        // validating the entire bundle at a time, but means that validating references
        // is impossible.
        // As of 2021-01-05, validating the bundle didn't validate references anyway,
        // but at some point we may want to do that.
        Bundle bundle = parser.parseResource(Bundle.class, fhirJson);
        for (Bundle.BundleEntryComponent entry : bundle.getEntry()) {
            ValidationResult eresult = validator.validateR4(entry.getResource());
            if (!eresult.isSuccessful()) {
                for (SingleValidationMessage emessage : eresult.getMessages()) {
                    boolean valid = false;
                    if (emessage.getSeverity() == ResultSeverityEnum.INFORMATION || emessage.getSeverity() == ResultSeverityEnum.WARNING) {
                        /*
               * Ignore warnings.
               */
                        valid = true;
                    }
                    if (!valid) {
                        System.out.println(parser.encodeResourceToString(entry.getResource()));
                        System.out.println("ERROR: " + emessage.getMessage());
                        validationErrors.add(emessage.getMessage());
                    }
                }
            }
        }
        if (!validationErrors.isEmpty()) {
            FailedExportHelper.dumpInfo("FHIRR4", fhirJson, validationErrors, person);
        }
        return validationErrors;
    });
    assertTrue("Validation of exported FHIR bundle failed: " + String.join("|", errors), errors.size() == 0);
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) SingleValidationMessage(ca.uhn.fhir.validation.SingleValidationMessage) Bundle(org.hl7.fhir.r4.model.Bundle) ArrayList(java.util.ArrayList) BundleEntryComponent(org.hl7.fhir.r4.model.Bundle.BundleEntryComponent) ValidationResult(ca.uhn.fhir.validation.ValidationResult) IParser(ca.uhn.fhir.parser.IParser) Test(org.junit.Test)

Example 45 with ValidationResult

use of org.hl7.fhir.r5.context.IWorkerContext.ValidationResult in project synthea by synthetichealth.

the class FHIRSTU3ExporterTest method testFHIRSTU3Export.

@Test
public void testFHIRSTU3Export() throws Exception {
    TestHelper.loadTestProperties();
    Generator.DEFAULT_STATE = Config.get("test_state.default", "Massachusetts");
    Config.set("exporter.baseDirectory", tempFolder.newFolder().toString());
    FhirContext ctx = FhirStu3.getContext();
    IParser parser = ctx.newJsonParser().setPrettyPrint(true);
    FhirValidator validator = ctx.newValidator();
    validator.setValidateAgainstStandardSchema(true);
    validator.setValidateAgainstStandardSchematron(true);
    ValidationResources validationResources = new ValidationResources();
    List<String> errors = ParallelTestingService.runInParallel((person) -> {
        List<String> validationErrors = new ArrayList<String>();
        TestHelper.exportOff();
        Config.set("exporter.fhir_stu3.export", "true");
        Config.set("exporter.fhir.use_shr_extensions", "true");
        FhirStu3.TRANSACTION_BUNDLE = person.randBoolean();
        String fhirJson = FhirStu3.convertToFHIRJson(person, System.currentTimeMillis());
        // (these should have been converted into URIs)
        if (fhirJson.contains("SNOMED-CT")) {
            validationErrors.add("JSON contains unconverted references to 'SNOMED-CT' (should be URIs)");
        }
        // let's crack open the Bundle and validate
        // each individual entry.resource to get context-sensitive error
        // messages...
        Bundle bundle = parser.parseResource(Bundle.class, fhirJson);
        for (BundleEntryComponent entry : bundle.getEntry()) {
            ValidationResult eresult = validator.validateWithResult(entry.getResource());
            if (!eresult.isSuccessful()) {
                for (SingleValidationMessage emessage : eresult.getMessages()) {
                    boolean valid = false;
                    if (emessage.getMessage().contains("@ Observation obs-7")) {
                        /*
               * The obs-7 invariant basically says that Observations should have values, unless
               * they are made of components. This test replaces an invalid XPath expression
               * that was causing correct instances to fail validation.
               */
                        valid = validateObs7((Observation) entry.getResource());
                    } else if (emessage.getMessage().contains("@ Condition con-4")) {
                        /*
               * The con-4 invariant says "If condition is abated, then clinicalStatus must be
               * either inactive, resolved, or remission" which is very clear and sensical.
               * However, the XPath expression does not evaluate correctly for valid instances,
               * so we must manually validate.
               */
                        valid = validateCon4((Condition) entry.getResource());
                    } else if (emessage.getMessage().contains("@ MedicationRequest mps-1")) {
                        /*
               * The mps-1 invariant says MedicationRequest.requester.onBehalfOf can only be
               * specified if MedicationRequest.requester.agent is practitioner or device.
               * But the invariant is poorly written and does not correctly handle references
               * starting with "urn:uuid"
               */
                        // ignore this error
                        valid = true;
                    } else if (emessage.getMessage().contains("per-1: If present, start SHALL have a lower value than end")) {
                        /*
               * The per-1 invariant does not account for daylight savings time... so, if the
               * daylight savings switch happens between the start and end, the validation
               * fails, even if it is valid.
               */
                        // ignore this error
                        valid = true;
                    }
                    if (!valid) {
                        System.out.println(parser.encodeResourceToString(entry.getResource()));
                        System.out.println("ERROR: " + emessage.getMessage());
                        validationErrors.add(emessage.getMessage());
                    }
                }
            }
            // Check ExplanationOfBenefit Resources against BlueButton
            if (entry.getResource().fhirType().equals("ExplanationOfBenefit")) {
                ValidationResult bbResult = validationResources.validateSTU3(entry.getResource());
                for (SingleValidationMessage message : bbResult.getMessages()) {
                    if (message.getMessage().contains("extension https://bluebutton.cms.gov/assets")) {
                        /*
               * The instance validator complains about the BlueButton extensions, ignore
               */
                        continue;
                    } else if (message.getSeverity() == ResultSeverityEnum.ERROR) {
                        if (!(message.getMessage().contains("Element 'ExplanationOfBenefit.id': minimum required = 1, but only found 0") || message.getMessage().contains("Could not verify slice for profile"))) {
                            // For some reason the validator is not detecting the IDs on the resources,
                            // even though they appear to be present while debugging and during normal
                            // operations.
                            System.out.println(message.getSeverity() + ": " + message.getMessage());
                            Assert.fail(message.getSeverity() + ": " + message.getMessage());
                        }
                    }
                }
            }
        }
        if (!validationErrors.isEmpty()) {
            FailedExportHelper.dumpInfo("FHIRSTU3", fhirJson, validationErrors, person);
        }
        return validationErrors;
    });
    assertTrue("Validation of exported FHIR bundle failed: " + String.join("|", errors), errors.size() == 0);
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) SingleValidationMessage(ca.uhn.fhir.validation.SingleValidationMessage) Bundle(org.hl7.fhir.dstu3.model.Bundle) ArrayList(java.util.ArrayList) FhirValidator(ca.uhn.fhir.validation.FhirValidator) ValidationResult(ca.uhn.fhir.validation.ValidationResult) BundleEntryComponent(org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent) Observation(org.hl7.fhir.dstu3.model.Observation) IParser(ca.uhn.fhir.parser.IParser) Test(org.junit.Test)

Aggregations

FHIRException (org.hl7.fhir.exceptions.FHIRException)32 IOException (java.io.IOException)22 ValidationResult (org.hl7.fhir.r5.context.IWorkerContext.ValidationResult)20 TerminologyServiceException (org.hl7.fhir.exceptions.TerminologyServiceException)17 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)15 FileNotFoundException (java.io.FileNotFoundException)14 ValidationResult (ca.uhn.fhir.validation.ValidationResult)12 CodeSystem (org.hl7.fhir.r5.model.CodeSystem)12 ConceptDefinitionComponent (org.hl7.fhir.r5.model.CodeSystem.ConceptDefinitionComponent)11 ValueSet (org.hl7.fhir.r5.model.ValueSet)11 CommaSeparatedStringBuilder (org.hl7.fhir.utilities.CommaSeparatedStringBuilder)11 NoTerminologyServiceException (org.hl7.fhir.exceptions.NoTerminologyServiceException)10 ValidationResult (org.hl7.fhir.r4b.context.IWorkerContext.ValidationResult)10 ArrayList (java.util.ArrayList)9 Coding (org.hl7.fhir.r5.model.Coding)9 NotImplementedException (org.apache.commons.lang3.NotImplementedException)7 PathEngineException (org.hl7.fhir.exceptions.PathEngineException)7 ValidationResult (org.hl7.fhir.r4.context.IWorkerContext.ValidationResult)7 ConceptDefinitionComponent (org.hl7.fhir.r4b.model.CodeSystem.ConceptDefinitionComponent)7 FHIRLexerException (org.hl7.fhir.r5.utils.FHIRLexer.FHIRLexerException)7