cheatah
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. Each
4// writes a tiny .purr that calls a single random function, compiles it with
5// 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 the
7// per-module system-level test (StdlibE2E.Random).
8//
9// RNG is non-deterministic until seeded, so every program seeds first and then
10// asserts a DETERMINISTIC property (degenerate range, in-bounds membership, or
11// 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.
15TEST(RandomCompileRun, Seed) {
16 e2e::expect_e2e("random_seed", R"PURR(import io
17import random
18random.seed(42)
19let a = random.random()
20random.seed(42)
21let b = random.random()
22io.print(a == b)
23)PURR", "True\n");
26// random: seeded value lies in the half-open unit interval [0, 1).
27TEST(RandomCompileRun, Random) {
28 e2e::expect_e2e("random_random", R"PURR(import io
29import random
30random.seed(42)
31let r = random.random()
32io.print(0.0 <= r and r < 1.0)
33)PURR", "True\n");
36// uniform: reproducible under a fixed seed and within the requested bounds.
37TEST(RandomCompileRun, Uniform) {
38 e2e::expect_e2e("random_uniform", R"PURR(import io
39import random
40random.seed(42)
41let a = random.uniform(-2.0, 3.0)
42random.seed(42)
43let b = random.uniform(-2.0, 3.0)
44io.print(a == b and -2.0 <= a and a <= 3.0)
45)PURR", "True\n");
48// randint: a degenerate range is fully deterministic — randint(5, 5) == 5.
49TEST(RandomCompileRun, Randint) {
50 e2e::expect_e2e("random_randint", R"PURR(import io
51import random
52random.seed(42)
53io.print(random.randint(5, 5))
54)PURR", "5\n");
57// gauss: reproducible under a fixed seed (same seed => same deviate).
58TEST(RandomCompileRun, Gauss) {
59 e2e::expect_e2e("random_gauss", R"PURR(import io
60import random
61random.seed(42)
62let a = random.gauss(0.0, 1.0)
63random.seed(42)
64let b = random.gauss(0.0, 1.0)
65io.print(a == b)
66)PURR", "True\n");
69// choice: picking from an all-equal sequence is deterministic (always 99).
70TEST(RandomCompileRun, Choice) {
71 e2e::expect_e2e("random_choice", R"PURR(import io
72import random
73random.seed(42)
74let xs = [99, 99, 99]
75io.print(random.choice(xs))
76)PURR", "99\n");