gen
Random values for tests, fake data, and property checks that shrink what
they find. Pure Louise, on std/random.
import gen
import gen/check
import gen/fake
@test
fn a_title_survives_its_round_trip ::
{
check.property ~runs: 200 fake.sentence fn title { decode (encode title) == Ok(title) }
}
Most packages take it as a dev-dependency, for their tests only (ADR 0064):
[dev-dependencies]
gen = { git = "https://toboggan.cloud/louise-lang/packages.git", subdir = "gen", version = "~> 0.21.0" }
Generators (gen)
A generator is any fn() -> a / <random>: there is no generator type, and
they compose as ordinary code. random.with_seed gives the same values on
every run.
int ~low ~high | an Int in low..=high |
bool | |
pick xs | one of xs |
weighted [(weight, x), …] | one of the values, in proportion to its weight |
list ~min ~max item | min to max items |
string ~alphabet ~min ~max | with lower (), digits (), alnum () or printable () |
option item | None or Some |
from_bytes choices generate | generate's value from given bytes (then zeros) |
To choose between generators, choose a value and match on it: a generator
kept in a list would not get its caller's random, since handlers are
lexical (ADR 0010).
Fake data (gen/fake)
word, words ~min ~max, sentence, paragraph, first_name,
last_name, full_name, email (ada.lovelace7@example.com), slug, and
url (https://example.com/<slug>).
Property checks (gen/check)
property ~runs generate holdschecksholdsonrunscases. Its seed comes fromrandom, so in a test each run tries new cases.seeded ~seed ~runs generate holdsdoes the same with a given seed: that is how a failure is replayed.counterexample ~seed ~runs generate holdsreturns the shrunk failing case, if there is one.
A failure panics with the seed, the shrunk case and the case it came from:
property does not hold (seed 812733406, case 4 of 200):
[11]
shrunk from:
[3, 61, 0, 98, 12]
replay: check.seeded ~seed: 812733406 ~runs: 200
Shrinking works on the bytes a case drew, as Hypothesis does: the bytes are made shorter and smaller while the generator, replaying them, still makes a failing case. Every generator here gives smaller values from smaller bytes (zero bytes give the lowest Int, the shortest list, the first choice), so no type needs a shrinker of its own. A shrink stops after 2,000 tries.