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
- Whenever
kavach testneeds anEmail, it callssamplewith aGen, here 200 times fordomain. - A
Gen's choices are seeded like the rest of the run, so the run can be repeated. It is not theRandomcapability, sosampleneeds nouses. - A value from
samplethat breaks aninvariantis not used, andsampleis called again. sampleis tested like any function: itsensureis checked on every value it makes.
| Method | Gives |
|---|---|
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.