diff --git a/test/stdlib/rand.c b/test/stdlib/rand.c index eaac447..e48558b 100644 --- a/test/stdlib/rand.c +++ b/test/stdlib/rand.c @@ -5,6 +5,9 @@ #include "stdlib_tests.h" #include +#include +#include +#include // Cmocka needs these // clang-format off @@ -18,7 +21,41 @@ static void rand_test(void** state) { - // TODO: rand tests not implemented + const unsigned int test_seed = 12345; + + /* test if rand_r affects the seed */ + srand(test_seed); + int rand_out = rand(); + + srand(test_seed); + unsigned int rand_r_ctx = 5732; + rand_r(&rand_r_ctx); + int rand_r_out = rand(); /* should be the same as before if rand_r is correct */ + + assert_true(rand_out == rand_r_out); + + /* test how random `rand` really is */ + srand(time(NULL)); + + const unsigned int amount = 65536; /* must be power of 2 because of mean algo */ + int values[amount]; + for(unsigned int i = 0; i < amount; i++) + { + values[i] = rand(); + } + + /* mean algo with O(nlog n) */ + for(unsigned int j = 2; j <= amount; j *= 2) + { + for(unsigned int i = 0; i < amount; i += j) + { + values[i] = ((long)values[i] + (long)values[i + j / 2]) / 2; + } + } + + /* 1.554 435 122 * 10^−26% chance of failing even if rand is sufficient */ + assert_true(values[0] - INT_MAX / 2 < 1048576); + assert_true(values[0] - INT_MAX / 2 > -1048576); } #pragma mark - Public Functions -