|
17 | 17 | */ |
18 | 18 |
|
19 | 19 | #include <set> |
| 20 | +#include <vector> |
20 | 21 |
|
21 | 22 | #include "mongo/platform/random.h" |
22 | 23 |
|
@@ -87,6 +88,73 @@ TEST(RandomTest, R2) { |
87 | 88 | } |
88 | 89 |
|
89 | 90 |
|
| 91 | +TEST(RandomTest, NextInt32SanityCheck) { |
| 92 | + // Generate 1000 int32s and assert that each bit is set between 40% and 60% of the time. This is |
| 93 | + // a bare minimum sanity check, not an attempt to ensure quality random numbers. |
| 94 | + |
| 95 | + PseudoRandom a(11); |
| 96 | + std::vector<int32_t> nums; |
| 97 | + for (int i = 0; i < 1000; i++) { |
| 98 | + nums.push_back(a.nextInt32()); |
| 99 | + } |
| 100 | + |
| 101 | + for (int bit = 0; bit < 32; bit++) { |
| 102 | + int onesCount = 0; |
| 103 | + for (size_t i = 0; i != nums.size(); ++i) { |
| 104 | + int32_t num = nums[i]; |
| 105 | + bool isSet = (num >> bit) & 1; |
| 106 | + if (isSet) |
| 107 | + onesCount++; |
| 108 | + } |
| 109 | + |
| 110 | + if (onesCount < 400 || onesCount > 600) |
| 111 | + FAIL() << "bit " << bit << " was set " << (onesCount / 10.) << "% of the time."; |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +TEST(RandomTest, NextInt64SanityCheck) { |
| 116 | + // Generate 1000 int64s and assert that each bit is set between 40% and 60% of the time. This is |
| 117 | + // a bare minimum sanity check, not an attempt to ensure quality random numbers. |
| 118 | + |
| 119 | + PseudoRandom a(11); |
| 120 | + std::vector<int64_t> nums; |
| 121 | + for (int i = 0; i < 1000; i++) { |
| 122 | + nums.push_back(a.nextInt64()); |
| 123 | + } |
| 124 | + |
| 125 | + for (int bit = 0; bit < 64; bit++) { |
| 126 | + int onesCount = 0; |
| 127 | + for (size_t i = 0; i != nums.size(); ++i) { |
| 128 | + int32_t num = nums[i]; |
| 129 | + |
| 130 | + bool isSet = (num >> bit) & 1; |
| 131 | + if (isSet) |
| 132 | + onesCount++; |
| 133 | + } |
| 134 | + |
| 135 | + if (onesCount < 400 || onesCount > 600) |
| 136 | + FAIL() << "bit " << bit << " was set " << (onesCount / 10.) << "% of the time."; |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +TEST(RandomTest, NextInt32InRange) { |
| 141 | + PseudoRandom a(11); |
| 142 | + for (int i = 0; i < 1000; i++) { |
| 143 | + int32_t res = a.nextInt32(10); |
| 144 | + ASSERT_GE(res, 0); |
| 145 | + ASSERT_LT(res, 10); |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +TEST(RandomTest, NextInt64InRange) { |
| 150 | + PseudoRandom a(11); |
| 151 | + for (int i = 0; i < 1000; i++) { |
| 152 | + int32_t res = a.nextInt64(10); |
| 153 | + ASSERT_GE(res, 0); |
| 154 | + ASSERT_LT(res, 10); |
| 155 | + } |
| 156 | +} |
| 157 | + |
90 | 158 | TEST(RandomTest, Secure1) { |
91 | 159 | SecureRandom* a = SecureRandom::create(); |
92 | 160 | SecureRandom* b = SecureRandom::create(); |
|
0 commit comments