Skip to content
Kavachकवच

Testing: Your own values

● Intermediate3 minBefore this: Testing: Tests from types

When the values kavach test makes up don't suit a type, the type makes its own: it implements Sample, and builds a value from a Gen.

type Email: Sample {
    value: String
    invariant value.contains("@")

    fn sample(gen: Gen) -> Email
        ensure result.value.ends_with(".com") or result.value.ends_with(".in")
    {
        Email(value: "{gen.word()}@{gen.pick(["example.com", "test.in"])}")
    }
}

fn domain(email: Email) -> String
    ensure result.contains(".")
    example domain(Email(value: "asha@example.com")) == "example.com"
{
    email.value.slice((email.value.index_of("@") ?? 0) + 1, email.value.len())
}

The program ran and printed:

kavach run own-sample.kav

✓ domain: example domain(Email(value: "asha@example.com")) == "example.com"1 passed, 0 failedseed 7✓ domain  200 cases✓ Email.sample  200 cases2 functions   2 ✓   0 ✗   0 weakly tested
own-sample.kav: Kavach code, then what running it prints
  • Whenever kavach test needs an Email, it calls sample with a Gen, here 200 times for domain.
  • A Gen's choices are seeded like the rest of the run, so the run can be repeated. It is not the Random capability, so sample needs no uses.
  • A value from sample that breaks an invariant is not used, and sample is called again.
  • sample is tested like any function: its ensure is checked on every value it makes.
MethodGives
gen.int(from, to)An Int from from to to, both included
gen.bool()true or false
gen.pick(items)One of the items; the list must not be empty
gen.word()A word of 1 to 8 lowercase letters

Sample and Gen, like every standard type, need no use.