Source
tests/purrc/random_cr_test.cpp
1
// Copyright (c) 2026 BigBrain LLC. MIT-licensed (see LICENSE).2
// Original work; see ACKNOWLEDGMENTS.md for the open-source ideas we build upon.3
// Compile-run unit tests for the `random` module: one test per function. Each4
// writes a tiny .purr that calls a single random function, compiles it with5
// purrc, runs it under the cheatah runtime, and asserts the exact stdout.6
// Complements the in-process unit tests (stdlib/tests/random_test.cpp) and the7
// per-module system-level test (StdlibE2E.Random).8
//9
// RNG is non-deterministic until seeded, so every program seeds first and then10
// asserts a DETERMINISTIC property (degenerate range, in-bounds membership, or11
// same-seed reproducibility) — never a raw random value.12
#include "e2e_harness.hpp"14
// seed: same seed => same stream, proven by drawing twice and comparing.15
TEST(RandomCompileRun, Seed) {16
e2e::expect_e2e("random_seed", R"PURR(import io17
import random18
random.seed(42)19
let a = random.random()20
random.seed(42)21
let b = random.random()22
io.print(a == b)23
)PURR", "True\n");24
}26
// random: seeded value lies in the half-open unit interval [0, 1).27
TEST(RandomCompileRun, Random) {28
e2e::expect_e2e("random_random", R"PURR(import io29
import random30
random.seed(42)31
let r = random.random()32
io.print(0.0 <= r and r < 1.0)33
)PURR", "True\n");34
}36
// uniform: reproducible under a fixed seed and within the requested bounds.37
TEST(RandomCompileRun, Uniform) {38
e2e::expect_e2e("random_uniform", R"PURR(import io39
import random40
random.seed(42)41
let a = random.uniform(-2.0, 3.0)42
random.seed(42)43
let b = random.uniform(-2.0, 3.0)44
io.print(a == b and -2.0 <= a and a <= 3.0)45
)PURR", "True\n");46
}48
// randint: a degenerate range is fully deterministic — randint(5, 5) == 5.49
TEST(RandomCompileRun, Randint) {50
e2e::expect_e2e("random_randint", R"PURR(import io51
import random52
random.seed(42)53
io.print(random.randint(5, 5))54
)PURR", "5\n");55
}57
// gauss: reproducible under a fixed seed (same seed => same deviate).58
TEST(RandomCompileRun, Gauss) {59
e2e::expect_e2e("random_gauss", R"PURR(import io60
import random61
random.seed(42)62
let a = random.gauss(0.0, 1.0)63
random.seed(42)64
let b = random.gauss(0.0, 1.0)65
io.print(a == b)66
)PURR", "True\n");67
}69
// choice: picking from an all-equal sequence is deterministic (always 99).70
TEST(RandomCompileRun, Choice) {71
e2e::expect_e2e("random_choice", R"PURR(import io72
import random73
random.seed(42)74
let xs = [99, 99, 99]75
io.print(random.choice(xs))76
)PURR", "99\n");77
}