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

Expose a helper to test custom constraints #32

Open
canatella opened this issue Mar 22, 2024 · 2 comments
Open

Expose a helper to test custom constraints #32

canatella opened this issue Mar 22, 2024 · 2 comments
Labels
enhancement New feature or request

Comments

@canatella
Copy link

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 canatella added the bug Something isn't working label Mar 22, 2024
@nesk
Copy link
Owner

nesk commented Apr 4, 2024

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 nesk added enhancement New feature or request and removed bug Something isn't working labels Apr 4, 2024
@canatella
Copy link
Author

That does help thanks, thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants