nesk / akkurate

The expressive validation library for Kotlin
https://akkurate.dev
Apache License 2.0
225 stars 9 forks source link

Expose a helper to test custom constraints #32

Open canatella opened 3 months ago

canatella commented 3 months ago

Describe the bug I'm defining custom constraints and there seems to be no easy way to test them. In the following example, I'd like to create a Validatable<String>, but without the helpers defined in the _test package, it's hard to do because the ConstraintRegistry class is internal.

fun Validatable<String>.isValidTimeZone() = constrain {
    kotlin.runCatching { TimeZone.of(it) }.isSuccess
} otherwise {
    "Should be a valid time zone"
}

Expected behavior Would it be possible to expose the helper functions, maybe in a test library so that it's possible to unit test the custom constraints?

fun "test_time_zone_constraint" {
  assertTrue(Validatable("America/New_York").isValidTimeZone().satisfied)
}

Thanks!

nesk commented 2 months ago

You're right, the helpers aren't currently available. The reason is they are not stable and currently only fit the internal use case. Do you think the current internal helpers would fit your use case?

Rest assured that this is something I have in mind, it was already in the roadmap. I will make sure to increase the priority of this feature, it seems reasonable :)

As a workaround, you can create a root Validatable with the following function:

/**
 * Creates a root [Validatable] with [the provided value][wrappedValue].
 */
fun <T> Validatable(wrappedValue: T): Validatable<T> {
    lateinit var validatable: Validatable<T>
    val validator = Validator<T> {
        validatable = this
    }
    validator(wrappedValue)
    return validatable
}
canatella commented 2 months ago

That does help thanks, thanks a lot!