Skip to content

Commit

Permalink
Validate extracted fhir resources while in debug
Browse files Browse the repository at this point in the history
  • Loading branch information
LZRS committed Jan 25, 2024
1 parent feaa214 commit 1cf49f6
Show file tree
Hide file tree
Showing 10 changed files with 436 additions and 16 deletions.
4 changes: 4 additions & 0 deletions android/engine/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,10 @@ dependencies {
exclude(group = "ca.uhn.hapi.fhir")
}

implementation(libs.hapi.fhir.validation) { exclude(module = "commons-logging") }
implementation(libs.hapi.fhir.validation.resources.r4)
implementation(libs.hapi.fhir.validation.resources.r5)

// Shared dependencies
api(libs.bundles.datastore.kt)
api(libs.glide)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* 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(): FhirValidator {
val fhirContext = FhirContext.forR4()

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
Expand Up @@ -19,12 +19,14 @@ package org.smartregister.fhircore.engine.task
import androidx.annotation.VisibleForTesting
import ca.uhn.fhir.context.FhirContext
import ca.uhn.fhir.util.TerserUtil
import ca.uhn.fhir.validation.FhirValidator
import com.google.android.fhir.FhirEngine
import com.google.android.fhir.get
import com.google.android.fhir.logicalId
import com.google.android.fhir.search.search
import java.util.Date
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
import org.hl7.fhir.r4.model.ActivityDefinition
import org.hl7.fhir.r4.model.Base
Expand Down Expand Up @@ -56,7 +58,9 @@ import org.smartregister.fhircore.engine.configuration.event.EventType
import org.smartregister.fhircore.engine.data.local.DefaultRepository
import org.smartregister.fhircore.engine.util.extension.addResourceParameter
import org.smartregister.fhircore.engine.util.extension.asReference
import org.smartregister.fhircore.engine.util.extension.checkResourceValid
import org.smartregister.fhircore.engine.util.extension.encodeResourceToString
import org.smartregister.fhircore.engine.util.extension.errorMessages
import org.smartregister.fhircore.engine.util.extension.extractFhirpathDuration
import org.smartregister.fhircore.engine.util.extension.extractFhirpathPeriod
import org.smartregister.fhircore.engine.util.extension.extractId
Expand All @@ -75,6 +79,7 @@ constructor(
val transformSupportServices: TransformSupportServices,
val defaultRepository: DefaultRepository,
val fhirResourceUtil: FhirResourceUtil,
val fhirValidatorProvider: Provider<FhirValidator>,
val workflowCarePlanGenerator: WorkflowCarePlanGenerator,
) {
private val structureMapUtilities by lazy {
Expand Down Expand Up @@ -193,7 +198,22 @@ constructor(

val carePlanTasks = output.contained.filterIsInstance<Task>()

if (carePlanModified) saveCarePlan(output)
if (carePlanModified) {
fhirValidatorProvider
.get()
.checkResourceValid(output)
.filterNot { it.errorMessages.isBlank() }
.takeIf { it.isNotEmpty() }
?.let {
val errors = buildString {
it.forEach { validationResult -> appendLine(validationResult.errorMessages) }
}

throw IllegalStateException(errors)
}

saveCarePlan(output)

Check warning on line 215 in android/engine/src/main/java/org/smartregister/fhircore/engine/task/FhirCarePlanGenerator.kt

View check run for this annotation

Codecov / codecov/patch

android/engine/src/main/java/org/smartregister/fhircore/engine/task/FhirCarePlanGenerator.kt#L215

Added line #L215 was not covered by tests
}

if (carePlanTasks.isNotEmpty()) {
fhirResourceUtil.updateUpcomingTasksToDue(
Expand All @@ -215,7 +235,9 @@ constructor(
carePlan.contained.clear()

// Save CarePlan only if it has activity, otherwise just save contained/dependent resources
if (output.hasActivity()) defaultRepository.create(true, carePlan)
if (output.hasActivity()) {
defaultRepository.create(true, carePlan)

Check warning on line 239 in android/engine/src/main/java/org/smartregister/fhircore/engine/task/FhirCarePlanGenerator.kt

View check run for this annotation

Codecov / codecov/patch

android/engine/src/main/java/org/smartregister/fhircore/engine/task/FhirCarePlanGenerator.kt#L239

Added line #L239 was not covered by tests
}

dependents.forEach { defaultRepository.create(true, it) }

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* 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

suspend fun FhirValidator.checkResourceValid(
vararg resource: Resource,
isDebug: Boolean = BuildConfig.BUILD_TYPE.contains("debug", ignoreCase = true),
): List<ValidationResult> {
if (!isDebug) return emptyList()

return withContext(coroutineContext) {
resource.map { this@checkResourceValid.validateWithResult(it) }
}
}

val ValidationResult.errorMessages
get() = buildString {
for (validationMsg in
messages.filter { it.severity.ordinal >= ResultSeverityEnum.WARNING.ordinal }) {
appendLine("${validationMsg.message} - ${validationMsg.locationString}")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import ca.uhn.fhir.context.FhirContext
import ca.uhn.fhir.context.FhirVersionEnum
import ca.uhn.fhir.parser.IParser
import ca.uhn.fhir.rest.gclient.ReferenceClientParam
import ca.uhn.fhir.validation.FhirValidator
import com.google.android.fhir.FhirEngine
import com.google.android.fhir.SearchResult
import com.google.android.fhir.get
Expand All @@ -45,6 +46,7 @@ import java.util.Calendar
import java.util.Date
import java.util.UUID
import javax.inject.Inject
import javax.inject.Provider
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
Expand Down Expand Up @@ -129,6 +131,8 @@ class FhirCarePlanGeneratorTest : RobolectricTest() {

@Inject lateinit var workflowCarePlanGenerator: WorkflowCarePlanGenerator

@Inject lateinit var fhirValidatorProvider: Provider<FhirValidator>

@Inject lateinit var fhirPathEngine: FHIRPathEngine

@Inject lateinit var fhirEngine: FhirEngine
Expand Down Expand Up @@ -169,6 +173,7 @@ class FhirCarePlanGeneratorTest : RobolectricTest() {
fhirPathEngine = fhirPathEngine,
defaultRepository = defaultRepository,
fhirResourceUtil = fhirResourceUtil,
fhirValidatorProvider = fhirValidatorProvider,
workflowCarePlanGenerator = workflowCarePlanGenerator,
)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/*
* 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 results = fhirValidatorSpy.checkResourceValid(basicResource, isDebug = false)
Assert.assertTrue(results.isEmpty())
verify(exactly = 0) { fhirValidatorSpy.validateWithResult(any<IBaseResource>()) }
verify(exactly = 0) { fhirValidatorSpy.validateWithResult(any<String>()) }
}

@Test
fun testCheckResourceValidValidatesResourceStructureWhenCarePlanResourceInvalid() = runTest {
val basicCarePlan = CarePlan()
val results = validator.checkResourceValid(basicCarePlan)
Assert.assertFalse(results.isEmpty())
Assert.assertTrue(
results.any {
it.errorMessages.contains(
"CarePlan.status: minimum required = 1, but only found 0",
ignoreCase = true,
)
},
)
Assert.assertTrue(
results.any {
it.errorMessages.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 results = validator.checkResourceValid(carePlan)
Assert.assertFalse(results.isEmpty())
Assert.assertEquals(1, results.size)
Assert.assertTrue(
results
.first()
.errorMessages
.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 results = validator.checkResourceValid(carePlan)
Assert.assertFalse(results.isEmpty())
Assert.assertEquals(1, results.size)
Assert.assertTrue(
results
.first()
.errorMessages
.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 results = validator.checkResourceValid(carePlan)
Assert.assertFalse(results.isEmpty())
Assert.assertEquals(1, results.size)
Assert.assertTrue(results.first().errorMessages.isBlank())
}
}
5 changes: 4 additions & 1 deletion android/gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ dagger-hilt = "2.45"
jetbrains-dokka = "1.8.20"
navigation-safeargs = "2.4.2"
diffplug-spotless = "6.19.0"

hapi-fhir = "6.0.1"

[libraries]
accompanist-flowlayout = { group = "com.google.accompanist", name = "accompanist-flowlayout", version.ref = "accompanist-flowlayout" }
Expand Down Expand Up @@ -222,6 +222,9 @@ work-runtime-ktx = { group = "androidx.work", name = "work-runtime-ktx", version
work-testing = { group = "androidx.work", name = "work-testing", version.ref = "work-testing" }
workflow = { group = "org.smartregister", name = "workflow", version.ref = "workflow" }
xercesImpl = { group = "xerces", name = "xercesImpl", version.ref = "xercesImpl" }
hapi-fhir-validation = {group = "ca.uhn.hapi.fhir", name="hapi-fhir-validation", version.ref = "hapi-fhir"}
hapi-fhir-validation-resources-r4 = {group = "ca.uhn.hapi.fhir", name="hapi-fhir-validation-resources-r4", version.ref = "hapi-fhir"}
hapi-fhir-validation-resources-r5 = {group = "ca.uhn.hapi.fhir", name="hapi-fhir-validation-resources-r5", version.ref = "hapi-fhir"}

[plugins]
org-jetbrains-kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "org-jetbrains-kotlin-android" }
Expand Down
Loading

0 comments on commit 1cf49f6

Please sign in to comment.