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