akkurate icon indicating copy to clipboard operation
akkurate copied to clipboard

Expose a helper to test custom constraints

Open canatella opened this issue 1 year ago • 2 comments

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!

canatella avatar Mar 22 '24 15:03 canatella

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
}

nesk avatar Apr 04 '24 14:04 nesk

That does help thanks, thanks a lot!

canatella avatar Apr 04 '24 16:04 canatella

Hi @canatella! This helper is now available since release 0.10.0. It's in the dedicated akkurate-test artifact, see documentation here: https://akkurate.dev/docs/extend.html#test-your-code

nesk avatar Sep 29 '24 12:09 nesk

Closed by commit 36962a76b6e59218c92b207c6e33280e30bdb563

nesk avatar Sep 29 '24 12:09 nesk