Debian Codegraph @

src/test/test-random-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "hexdecoct.h"
4 #include "log.h"
5 #include "memory-util.h"
6 #include "random-util.h"
7 #include "terminal-util.h"
8 #include "tests.h"
9
10 TEST(random_bytes) {
11 uint8_t buf[16] = {};
12
13 for (size_t i = 1; i < sizeof buf; i++) {
14 random_bytes(buf, i);
15 if (i + 1 < sizeof buf)
16 ASSERT_EQ(buf[i], 0);
17
18 hexdump(stdout, buf, i);
19 }
20 }
21
22 TEST(crypto_random_bytes) {
23 uint8_t buf[16] = {};
24
25 for (size_t i = 1; i < sizeof buf; i++) {
26 ASSERT_OK(crypto_random_bytes(buf, i));
27 if (i + 1 < sizeof buf)
28 ASSERT_EQ(buf[i], 0);
29
30 hexdump(stdout, buf, i);
31 }
32 }
33
34 #define TOTAL 100000
35
36 static void test_random_u64_range_one(unsigned mod) {
37 log_info("/* %s(%u) */", __func__, mod);
38
39 unsigned max = 0, count[mod];
40 zero(count);
41
42 for (unsigned i = 0; i < TOTAL; i++) {
43 uint64_t x;
44
45 x = random_u64_range(mod);
46
47 count[x]++;
48 max = MAX(max, count[x]);
49 }
50
51 /* Print histogram: vertical axis — value, horizontal axis — count.
52 *
53 * The expected value is always TOTAL/mod, because the distribution should be flat. The expected
54 * variance is TOTAL×p×(1-p), where p==1/mod. Assert that the deviation from the expected value
55 * is less than 6 standard deviations by comparing squared values (diff² < 36·variance), which
56 * avoids a sqrt() call and the libm dependency that comes with it at -O0.
57 */
58 unsigned scale = 2 * max / (columns() < 20 ? 80 : columns() - 20);
59 double exp = (double) TOTAL / mod;
60 double variance = exp * (mod > 1 ? mod - 1 : 1) / mod;
61
62 for (size_t i = 0; i < mod; i++) {
63 double diff = count[i] - exp;
64 double dev_sq = diff * diff / variance;
65
66 log_debug("%02zu: %5u (z²=%.3f)%*s",
67 i, count[i], dev_sq,
68 (int) (count[i] / scale), "x");
69
70 ASSERT_TRUE(dev_sq < 36); /* 36 = 6²; 6 sigma is excessive, but this check should be
71 * enough to identify catastrophic failure while minimizing
72 * false positives. */
73 }
74 }
75
76 TEST(random_u64_range) {
77 for (unsigned mod = 1; mod < 29; mod++)
78 test_random_u64_range_one(mod);
79 }
80
81 DEFINE_TEST_MAIN(LOG_DEBUG);