Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validate extracted fhir resources while in debug #2874

Merged
merged 17 commits into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions android/engine/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ dependencies {
implementation(Dependencies.HapiFhir.structuresR4) { exclude(module = "junit") }
implementation(Dependencies.HapiFhir.guavaCaching)
implementation(Dependencies.HapiFhir.validationR4)
implementation(Dependencies.HapiFhir.validationR5)
implementation(Dependencies.HapiFhir.validation) {
exclude(module = "commons-logging")
exclude(module = "httpclient")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright 2021-2024 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.smartregister.fhircore.engine.di

import ca.uhn.fhir.context.FhirContext
import ca.uhn.fhir.context.support.DefaultProfileValidationSupport
import ca.uhn.fhir.context.support.IValidationSupport
import ca.uhn.fhir.validation.FhirValidator
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
import org.hl7.fhir.common.hapi.validation.support.CommonCodeSystemsTerminologyService
import org.hl7.fhir.common.hapi.validation.support.InMemoryTerminologyServerValidationSupport
import org.hl7.fhir.common.hapi.validation.support.UnknownCodeSystemWarningValidationSupport
import org.hl7.fhir.common.hapi.validation.support.ValidationSupportChain
import org.hl7.fhir.common.hapi.validation.validator.FhirInstanceValidator

@Module
@InstallIn(SingletonComponent::class)
class FhirValidatorModule {

@Provides
@Singleton
fun provideFhirValidator(fhirContext: FhirContext): FhirValidator {
val validationSupportChain =
ValidationSupportChain(
DefaultProfileValidationSupport(fhirContext),
InMemoryTerminologyServerValidationSupport(fhirContext),
CommonCodeSystemsTerminologyService(fhirContext),
UnknownCodeSystemWarningValidationSupport(fhirContext).apply {
setNonExistentCodeSystemSeverity(IValidationSupport.IssueSeverity.WARNING)
},
)
val instanceValidator = FhirInstanceValidator(validationSupportChain)
instanceValidator.isAssumeValidRestReferences = true
instanceValidator.invalidateCaches()
return fhirContext.newValidator().apply { registerValidatorModule(instanceValidator) }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright 2021-2024 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.smartregister.fhircore.engine.util.extension

import ca.uhn.fhir.validation.FhirValidator
import ca.uhn.fhir.validation.ResultSeverityEnum
import ca.uhn.fhir.validation.ValidationResult
import kotlin.coroutines.coroutineContext
import kotlinx.coroutines.withContext
import org.hl7.fhir.r4.model.Resource
import org.smartregister.fhircore.engine.BuildConfig
import timber.log.Timber

data class ResourceValidationResult(
val resource: Resource,
val validationResult: ValidationResult,
) {
val errorMessages
get() = buildString {
val messages =
validationResult.messages.filter {
it.severity.ordinal >= ResultSeverityEnum.WARNING.ordinal
}

for (validationMsg in messages) {
appendLine(
"${validationMsg.message} - ${validationMsg.locationString} -- (${validationMsg.severity})",
)
}
}
}

data class FhirValidatorResultsWrapper(val results: List<ResourceValidationResult> = emptyList()) {
val errorMessages = results.map { it.errorMessages }
}

suspend fun FhirValidator.checkResourceValid(
vararg resource: Resource,
isDebug: Boolean = BuildConfig.DEBUG,
): FhirValidatorResultsWrapper {
if (!isDebug) return FhirValidatorResultsWrapper()

return withContext(coroutineContext) {
FhirValidatorResultsWrapper(
results =
resource.map {
val result = [email protected](it)
ResourceValidationResult(it, result)
},
)
}
}

fun FhirValidatorResultsWrapper.logErrorMessages() {
results.forEach {

Check warning on line 69 in android/engine/src/main/java/org/smartregister/fhircore/engine/util/extension/FhirValidatorExtension.kt

View check run for this annotation

Codecov / codecov/patch

android/engine/src/main/java/org/smartregister/fhircore/engine/util/extension/FhirValidatorExtension.kt#L69

Added line #L69 was not covered by tests
if (it.errorMessages.isNotBlank()) {
Timber.tag("$TAG (${it.resource.referenceValue()})").e(it.errorMessages)

Check warning on line 71 in android/engine/src/main/java/org/smartregister/fhircore/engine/util/extension/FhirValidatorExtension.kt

View check run for this annotation

Codecov / codecov/patch

android/engine/src/main/java/org/smartregister/fhircore/engine/util/extension/FhirValidatorExtension.kt#L71

Added line #L71 was not covered by tests
}
}
}

private const val TAG = "FhirValidator"
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,8 @@ class FhirCarePlanGeneratorTest : RobolectricTest() {
fhirCarePlanGenerator =
FhirCarePlanGenerator(
fhirEngine = fhirEngine,
transformSupportServices = transformSupportServices,
fhirPathEngine = fhirPathEngine,
transformSupportServices = transformSupportServices,
defaultRepository = defaultRepository,
fhirResourceUtil = fhirResourceUtil,
workflowCarePlanGenerator = workflowCarePlanGenerator,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* Copyright 2021-2024 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.smartregister.fhircore.engine.util.extension

import ca.uhn.fhir.validation.FhirValidator
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import io.mockk.spyk
import io.mockk.verify
import javax.inject.Inject
import kotlinx.coroutines.test.runTest
import org.hl7.fhir.instance.model.api.IBaseResource
import org.hl7.fhir.r4.model.CarePlan
import org.hl7.fhir.r4.model.Patient
import org.hl7.fhir.r4.model.Reference
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.smartregister.fhircore.engine.robolectric.RobolectricTest

@HiltAndroidTest
class FhirValidatorExtensionTest : RobolectricTest() {

@get:Rule var hiltRule = HiltAndroidRule(this)

@Inject lateinit var validator: FhirValidator

@Before
fun setUp() {
hiltRule.inject()
}

@Test
fun testCheckResourceValidRunsNoValidationWhenBuildTypeIsNotDebug() = runTest {
val basicResource = CarePlan()
val fhirValidatorSpy = spyk(validator)
val resultsWrapper = fhirValidatorSpy.checkResourceValid(basicResource, isDebug = false)
Assert.assertTrue(resultsWrapper.results.isEmpty())
verify(exactly = 0) { fhirValidatorSpy.validateWithResult(any<IBaseResource>()) }
verify(exactly = 0) { fhirValidatorSpy.validateWithResult(any<String>()) }
}

@Test
fun testCheckResourceValidValidatesResourceStructureWhenCarePlanResourceInvalid() = runTest {
val basicCarePlan = CarePlan()
val resultsWrapper = validator.checkResourceValid(basicCarePlan)
Assert.assertTrue(
resultsWrapper.errorMessages.any {
it.contains(
"CarePlan.status: minimum required = 1, but only found 0",
ignoreCase = true,
)
},
)
Assert.assertTrue(
resultsWrapper.errorMessages.any {
it.contains(
"CarePlan.intent: minimum required = 1, but only found 0",
ignoreCase = true,
)
},
)
}

@Test
fun testCheckResourceValidValidatesReferenceType() = runTest {
val carePlan =
CarePlan().apply {
status = CarePlan.CarePlanStatus.ACTIVE
intent = CarePlan.CarePlanIntent.PLAN
subject = Reference("Task/unknown")
}
val resultsWrapper = validator.checkResourceValid(carePlan)
Assert.assertEquals(1, resultsWrapper.errorMessages.size)
Assert.assertTrue(
resultsWrapper.errorMessages
.first()
.contains(
"The type 'Task' implied by the reference URL Task/unknown is not a valid Target for this element (must be one of [Group, Patient]) - CarePlan.subject",
ignoreCase = true,
),
)
}

@Test
fun testCheckResourceValidValidatesReferenceWithNoType() = runTest {
val carePlan =
CarePlan().apply {
status = CarePlan.CarePlanStatus.ACTIVE
intent = CarePlan.CarePlanIntent.PLAN
subject = Reference("unknown")
}
val resultsWrapper = validator.checkResourceValid(carePlan)
Assert.assertEquals(1, resultsWrapper.errorMessages.size)
Assert.assertTrue(
resultsWrapper.errorMessages
.first()
.contains(
"The syntax of the reference 'unknown' looks incorrect, and it should be checked - CarePlan.subject",
ignoreCase = true,
),
)
}

@Test
fun testCheckResourceValidValidatesResourceCorrectly() = runTest {
val patient = Patient()
val carePlan =
CarePlan().apply {
status = CarePlan.CarePlanStatus.ACTIVE
intent = CarePlan.CarePlanIntent.PLAN
subject = Reference(patient)
}
val resultsWrapper = validator.checkResourceValid(carePlan)
Assert.assertEquals(1, resultsWrapper.errorMessages.size)
Assert.assertTrue(resultsWrapper.errorMessages.first().isBlank())
}
}
Loading
Loading