Skip to content

expose random seed to the test runner #17609

@andrewrk

Description

@andrewrk

In #14940, the Zig compiler passes a 32-bit integer --seed parameter to the build runner for shuffling dependency traversal order. If something goes wrong, the user can repeat the same operation with the same seed because the seed will be printed on the command line.

This same concept can be useful for unit tests which want to use randomness but also need reproducibility.

This proposal is to expose the seed to std.testing so that unit tests can obtain it and use it.

This would also provide a way to resolve one area of confusion for users which is the fact that unit tests get cached. Some users are confused why unit tests would be cached. Explicitly having this seed would make everything make sense. If you give the same seed, then the test runs are considered cached. If you give a different seed, it's a new run.

Example code:

test "example" {
    var rng = std.DefaultPrng.init(std.testing.random_seed);
    // use rng to influence the unit test
}

If this is implemented then it will be important for the seed to be displayed if the tests fail. This is already the case, as shown here:

[nix-shell:~/dev/zig/build-release]$ stage3/bin/zig test test3.zig 
Test [1/1] test.example... FAIL (TestUnexpectedResult)
/home/andy/dev/zig/lib/std/testing.zig:527:14: 0x22383f in expect (test)
    if (!ok) return error.TestUnexpectedResult;
             ^
/home/andy/dev/zig/lib/test3.zig:5:5: 0x223955 in test.example (test)
0 passed; 0 skipped; 1 failed.
error: the following test command failed with exit code 1:
/home/andy/dev/zig/zig-cache/o/1a7789de4ed95c05d2d1ac588f0e29ca/test

This proposal would mean that last line would include, for example, --seed 0xdeadbeef .

Metadata

Metadata

Assignees

No one assigned

    Labels

    acceptedThis proposal is planned.enhancementSolving this issue will likely involve adding new logic or components to the codebase.proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.standard libraryThis issue involves writing Zig code for the standard library.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions