Avi Drissman | e4622aa | 2022-09-08 20:36:06 | [diff] [blame] | 1 | // Copyright 2011 The Chromium Authors |
[email protected] | 05f9b68 | 2008-09-29 22:18:01 | [diff] [blame] | 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
danakj | 51d26a4 | 2024-04-25 14:23:56 | [diff] [blame] | 5 | #ifdef UNSAFE_BUFFERS_BUILD |
| 6 | // TODO(crbug.com/40284755): Remove this and spanify to fix the errors. |
| 7 | #pragma allow_unsafe_buffers |
| 8 | #endif |
| 9 | |
[email protected] | 05f9b68 | 2008-09-29 22:18:01 | [diff] [blame] | 10 | #include "base/rand_util.h" |
| 11 | |
avi | 9b6f4293 | 2015-12-26 22:15:14 | [diff] [blame] | 12 | #include <stddef.h> |
| 13 | #include <stdint.h> |
| 14 | |
[email protected] | 0173b96 | 2011-08-24 19:58:36 | [diff] [blame] | 15 | #include <algorithm> |
Benoit Lize | 73de21b | 2021-07-02 08:17:56 | [diff] [blame] | 16 | #include <cmath> |
[email protected] | 05f9b68 | 2008-09-29 22:18:01 | [diff] [blame] | 17 | #include <limits> |
dcheng | 093de9b | 2016-04-04 21:25:51 | [diff] [blame] | 18 | #include <memory> |
Benoit Lize | 73de21b | 2021-07-02 08:17:56 | [diff] [blame] | 19 | #include <vector> |
[email protected] | 05f9b68 | 2008-09-29 22:18:01 | [diff] [blame] | 20 | |
Austin Sullivan | a41f7f6 | 2024-01-09 20:11:50 | [diff] [blame] | 21 | #include "base/containers/span.h" |
[email protected] | c910c5a | 2014-01-23 02:14:28 | [diff] [blame] | 22 | #include "base/logging.h" |
[email protected] | c910c5a | 2014-01-23 02:14:28 | [diff] [blame] | 23 | #include "base/time/time.h" |
[email protected] | 05f9b68 | 2008-09-29 22:18:01 | [diff] [blame] | 24 | #include "testing/gtest/include/gtest/gtest.h" |
| 25 | |
Benoit Lize | 73de21b | 2021-07-02 08:17:56 | [diff] [blame] | 26 | namespace base { |
| 27 | |
[email protected] | 05f9b68 | 2008-09-29 22:18:01 | [diff] [blame] | 28 | namespace { |
| 29 | |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 30 | constexpr int kIntMin = std::numeric_limits<int>::min(); |
| 31 | constexpr int kIntMax = std::numeric_limits<int>::max(); |
[email protected] | 05f9b68 | 2008-09-29 22:18:01 | [diff] [blame] | 32 | |
| 33 | } // namespace |
| 34 | |
Nico Weber | 0a3852a7 | 2015-10-29 20:42:58 | [diff] [blame] | 35 | TEST(RandUtilTest, RandInt) { |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 36 | EXPECT_EQ(RandInt(0, 0), 0); |
| 37 | EXPECT_EQ(RandInt(kIntMin, kIntMin), kIntMin); |
| 38 | EXPECT_EQ(RandInt(kIntMax, kIntMax), kIntMax); |
Nico Weber | 0a3852a7 | 2015-10-29 20:42:58 | [diff] [blame] | 39 | |
| 40 | // Check that the DCHECKS in RandInt() don't fire due to internal overflow. |
| 41 | // There was a 50% chance of that happening, so calling it 40 times means |
| 42 | // the chances of this passing by accident are tiny (9e-13). |
Peter Kasting | 134ef9af | 2024-12-28 02:30:09 | [diff] [blame] | 43 | for (int i = 0; i < 40; ++i) { |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 44 | RandInt(kIntMin, kIntMax); |
Peter Kasting | 134ef9af | 2024-12-28 02:30:09 | [diff] [blame] | 45 | } |
[email protected] | 05f9b68 | 2008-09-29 22:18:01 | [diff] [blame] | 46 | } |
[email protected] | 94a0f31 | 2008-09-30 14:26:33 | [diff] [blame] | 47 | |
| 48 | TEST(RandUtilTest, RandDouble) { |
[email protected] | 29548d8 | 2011-04-29 21:03:54 | [diff] [blame] | 49 | // Force 64-bit precision, making sure we're not in a 80-bit FPU register. |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 50 | volatile double number = RandDouble(); |
| 51 | EXPECT_LT(number, 1.0); |
| 52 | EXPECT_GE(number, 0.0); |
[email protected] | 29548d8 | 2011-04-29 21:03:54 | [diff] [blame] | 53 | } |
| 54 | |
Avery Musbach | eff342b | 2022-10-06 18:36:07 | [diff] [blame] | 55 | TEST(RandUtilTest, RandFloat) { |
| 56 | // Force 32-bit precision, making sure we're not in an 80-bit FPU register. |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 57 | volatile float number = RandFloat(); |
| 58 | EXPECT_LT(number, 1.0f); |
| 59 | EXPECT_GE(number, 0.0f); |
Avery Musbach | eff342b | 2022-10-06 18:36:07 | [diff] [blame] | 60 | } |
| 61 | |
Peter Kasting | b2dc5504 | 2025-01-16 16:30:54 | [diff] [blame] | 62 | TEST(RandUtilTest, RandBool) { |
| 63 | // This test should finish extremely quickly unless `RandBool()` can only give |
| 64 | // one result value. |
| 65 | for (bool seen_false = false, seen_true = false; !seen_false || !seen_true;) { |
| 66 | (RandBool() ? seen_true : seen_false) = true; |
| 67 | } |
| 68 | } |
| 69 | |
Peter Kasting | f18c8ca | 2023-10-04 16:31:51 | [diff] [blame] | 70 | TEST(RandUtilTest, RandTimeDelta) { |
| 71 | { |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 72 | const auto delta = RandTimeDelta(-Seconds(2), -Seconds(1)); |
| 73 | EXPECT_GE(delta, -Seconds(2)); |
| 74 | EXPECT_LT(delta, -Seconds(1)); |
Peter Kasting | f18c8ca | 2023-10-04 16:31:51 | [diff] [blame] | 75 | } |
| 76 | |
| 77 | { |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 78 | const auto delta = RandTimeDelta(-Seconds(2), Seconds(2)); |
| 79 | EXPECT_GE(delta, -Seconds(2)); |
| 80 | EXPECT_LT(delta, Seconds(2)); |
Peter Kasting | f18c8ca | 2023-10-04 16:31:51 | [diff] [blame] | 81 | } |
| 82 | |
| 83 | { |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 84 | const auto delta = RandTimeDelta(Seconds(1), Seconds(2)); |
| 85 | EXPECT_GE(delta, Seconds(1)); |
| 86 | EXPECT_LT(delta, Seconds(2)); |
Peter Kasting | f18c8ca | 2023-10-04 16:31:51 | [diff] [blame] | 87 | } |
| 88 | } |
| 89 | |
| 90 | TEST(RandUtilTest, RandTimeDeltaUpTo) { |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 91 | const auto delta = RandTimeDeltaUpTo(Seconds(2)); |
Peter Kasting | f18c8ca | 2023-10-04 16:31:51 | [diff] [blame] | 92 | EXPECT_FALSE(delta.is_negative()); |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 93 | EXPECT_LT(delta, Seconds(2)); |
Peter Kasting | f18c8ca | 2023-10-04 16:31:51 | [diff] [blame] | 94 | } |
| 95 | |
Peter Kasting | b2dc5504 | 2025-01-16 16:30:54 | [diff] [blame] | 96 | TEST(RandUtilTest, RandomizeByPercentage) { |
| 97 | EXPECT_EQ(0, RandomizeByPercentage(0, 100)); |
| 98 | EXPECT_EQ(100, RandomizeByPercentage(100, 0)); |
| 99 | |
| 100 | // Check that 10 +/- 200% will eventually produce values in each range |
| 101 | // [-10, 0), [0, 10), [10, 20), [20, 30). |
| 102 | for (bool a = false, b = false, c = false, d = false; !a || !b || !c || !d;) { |
| 103 | const int r = RandomizeByPercentage(10, 200); |
| 104 | EXPECT_GE(r, -10); |
| 105 | EXPECT_LT(r, 30); |
| 106 | a |= (r < 0); |
| 107 | b |= (r >= 0 && r < 10); |
| 108 | c |= (r >= 10 && r < 20); |
| 109 | d |= (r >= 20); |
| 110 | } |
| 111 | } |
| 112 | |
Avery Musbach | 92a30e38 | 2022-09-08 23:30:41 | [diff] [blame] | 113 | TEST(RandUtilTest, BitsToOpenEndedUnitInterval) { |
| 114 | // Force 64-bit precision, making sure we're not in an 80-bit FPU register. |
| 115 | volatile double all_zeros = BitsToOpenEndedUnitInterval(0x0); |
| 116 | EXPECT_EQ(0.0, all_zeros); |
| 117 | |
| 118 | // Force 64-bit precision, making sure we're not in an 80-bit FPU register. |
| 119 | volatile double smallest_nonzero = BitsToOpenEndedUnitInterval(0x1); |
| 120 | EXPECT_LT(0.0, smallest_nonzero); |
| 121 | |
| 122 | for (uint64_t i = 0x2; i < 0x10; ++i) { |
| 123 | // Force 64-bit precision, making sure we're not in an 80-bit FPU register. |
| 124 | volatile double number = BitsToOpenEndedUnitInterval(i); |
| 125 | EXPECT_EQ(i * smallest_nonzero, number); |
| 126 | } |
| 127 | |
| 128 | // Force 64-bit precision, making sure we're not in an 80-bit FPU register. |
| 129 | volatile double all_ones = BitsToOpenEndedUnitInterval(UINT64_MAX); |
| 130 | EXPECT_GT(1.0, all_ones); |
| 131 | } |
| 132 | |
Avery Musbach | eff342b | 2022-10-06 18:36:07 | [diff] [blame] | 133 | TEST(RandUtilTest, BitsToOpenEndedUnitIntervalF) { |
| 134 | // Force 32-bit precision, making sure we're not in an 80-bit FPU register. |
| 135 | volatile float all_zeros = BitsToOpenEndedUnitIntervalF(0x0); |
| 136 | EXPECT_EQ(0.f, all_zeros); |
| 137 | |
| 138 | // Force 32-bit precision, making sure we're not in an 80-bit FPU register. |
| 139 | volatile float smallest_nonzero = BitsToOpenEndedUnitIntervalF(0x1); |
| 140 | EXPECT_LT(0.f, smallest_nonzero); |
| 141 | |
| 142 | for (uint64_t i = 0x2; i < 0x10; ++i) { |
| 143 | // Force 32-bit precision, making sure we're not in an 80-bit FPU register. |
| 144 | volatile float number = BitsToOpenEndedUnitIntervalF(i); |
| 145 | EXPECT_EQ(i * smallest_nonzero, number); |
| 146 | } |
| 147 | |
| 148 | // Force 32-bit precision, making sure we're not in an 80-bit FPU register. |
| 149 | volatile float all_ones = BitsToOpenEndedUnitIntervalF(UINT64_MAX); |
| 150 | EXPECT_GT(1.f, all_ones); |
| 151 | } |
| 152 | |
[email protected] | 51a0181 | 2011-05-05 08:46:11 | [diff] [blame] | 153 | TEST(RandUtilTest, RandBytes) { |
[email protected] | 0173b96 | 2011-08-24 19:58:36 | [diff] [blame] | 154 | const size_t buffer_size = 50; |
Austin Sullivan | a41f7f6 | 2024-01-09 20:11:50 | [diff] [blame] | 155 | uint8_t buffer[buffer_size]; |
[email protected] | 51a0181 | 2011-05-05 08:46:11 | [diff] [blame] | 156 | memset(buffer, 0, buffer_size); |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 157 | RandBytes(buffer); |
[email protected] | 0173b96 | 2011-08-24 19:58:36 | [diff] [blame] | 158 | std::sort(buffer, buffer + buffer_size); |
| 159 | // Probability of occurrence of less than 25 unique bytes in 50 random bytes |
| 160 | // is below 10^-25. |
| 161 | EXPECT_GT(std::unique(buffer, buffer + buffer_size) - buffer, 25); |
[email protected] | 51a0181 | 2011-05-05 08:46:11 | [diff] [blame] | 162 | } |
| 163 | |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 164 | // Verify that calling RandBytes with an empty buffer doesn't fail. |
Sergey Ulanov | fdc62f8e | 2017-08-01 19:51:00 | [diff] [blame] | 165 | TEST(RandUtilTest, RandBytes0) { |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 166 | RandBytes(span<uint8_t>()); |
Sergey Ulanov | fdc62f8e | 2017-08-01 19:51:00 | [diff] [blame] | 167 | } |
| 168 | |
Tom Sepez | 230a75c6 | 2023-11-13 23:27:16 | [diff] [blame] | 169 | TEST(RandUtilTest, RandBytesAsVector) { |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 170 | std::vector<uint8_t> random_vec = RandBytesAsVector(0); |
Tom Sepez | 230a75c6 | 2023-11-13 23:27:16 | [diff] [blame] | 171 | EXPECT_TRUE(random_vec.empty()); |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 172 | random_vec = RandBytesAsVector(1); |
Tom Sepez | 230a75c6 | 2023-11-13 23:27:16 | [diff] [blame] | 173 | EXPECT_EQ(1U, random_vec.size()); |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 174 | random_vec = RandBytesAsVector(145); |
Tom Sepez | 230a75c6 | 2023-11-13 23:27:16 | [diff] [blame] | 175 | EXPECT_EQ(145U, random_vec.size()); |
| 176 | char accumulator = 0; |
| 177 | for (auto i : random_vec) { |
| 178 | accumulator |= i; |
| 179 | } |
| 180 | // In theory this test can fail, but it won't before the universe dies of |
| 181 | // heat death. |
| 182 | EXPECT_NE(0, accumulator); |
| 183 | } |
| 184 | |
[email protected] | 29548d8 | 2011-04-29 21:03:54 | [diff] [blame] | 185 | TEST(RandUtilTest, RandBytesAsString) { |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 186 | std::string random_string = RandBytesAsString(1); |
[email protected] | fdce478 | 2011-11-29 20:06:18 | [diff] [blame] | 187 | EXPECT_EQ(1U, random_string.size()); |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 188 | random_string = RandBytesAsString(145); |
[email protected] | 29548d8 | 2011-04-29 21:03:54 | [diff] [blame] | 189 | EXPECT_EQ(145U, random_string.size()); |
| 190 | char accumulator = 0; |
Peter Kasting | 134ef9af | 2024-12-28 02:30:09 | [diff] [blame] | 191 | for (auto i : random_string) { |
jdoerrie | 6c622935 | 2018-10-22 15:55:43 | [diff] [blame] | 192 | accumulator |= i; |
Peter Kasting | 134ef9af | 2024-12-28 02:30:09 | [diff] [blame] | 193 | } |
[email protected] | 29548d8 | 2011-04-29 21:03:54 | [diff] [blame] | 194 | // In theory this test can fail, but it won't before the universe dies of |
| 195 | // heat death. |
| 196 | EXPECT_NE(0, accumulator); |
[email protected] | 94a0f31 | 2008-09-30 14:26:33 | [diff] [blame] | 197 | } |
[email protected] | a74dcae | 2010-08-30 21:07:05 | [diff] [blame] | 198 | |
| 199 | // Make sure that it is still appropriate to use RandGenerator in conjunction |
| 200 | // with std::random_shuffle(). |
| 201 | TEST(RandUtilTest, RandGeneratorForRandomShuffle) { |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 202 | EXPECT_EQ(RandGenerator(1), 0U); |
[email protected] | a74dcae | 2010-08-30 21:07:05 | [diff] [blame] | 203 | EXPECT_LE(std::numeric_limits<ptrdiff_t>::max(), |
avi | 9b6f4293 | 2015-12-26 22:15:14 | [diff] [blame] | 204 | std::numeric_limits<int64_t>::max()); |
[email protected] | a74dcae | 2010-08-30 21:07:05 | [diff] [blame] | 205 | } |
[email protected] | af2e192b | 2011-05-30 17:39:09 | [diff] [blame] | 206 | |
| 207 | TEST(RandUtilTest, RandGeneratorIsUniform) { |
| 208 | // Verify that RandGenerator has a uniform distribution. This is a |
| 209 | // regression test that consistently failed when RandGenerator was |
| 210 | // implemented this way: |
| 211 | // |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 212 | // return RandUint64() % max; |
[email protected] | af2e192b | 2011-05-30 17:39:09 | [diff] [blame] | 213 | // |
| 214 | // A degenerate case for such an implementation is e.g. a top of |
| 215 | // range that is 2/3rds of the way to MAX_UINT64, in which case the |
| 216 | // bottom half of the range would be twice as likely to occur as the |
| 217 | // top half. A bit of calculus care of jar@ shows that the largest |
| 218 | // measurable delta is when the top of the range is 3/4ths of the |
| 219 | // way, so that's what we use in the test. |
Peter Kasting | fbb9e56 | 2021-06-27 02:57:37 | [diff] [blame] | 220 | constexpr uint64_t kTopOfRange = |
avi | 9b6f4293 | 2015-12-26 22:15:14 | [diff] [blame] | 221 | (std::numeric_limits<uint64_t>::max() / 4ULL) * 3ULL; |
Peter Kasting | fbb9e56 | 2021-06-27 02:57:37 | [diff] [blame] | 222 | constexpr double kExpectedAverage = static_cast<double>(kTopOfRange / 2); |
| 223 | constexpr double kAllowedVariance = kExpectedAverage / 50.0; // +/- 2% |
| 224 | constexpr int kMinAttempts = 1000; |
| 225 | constexpr int kMaxAttempts = 1000000; |
[email protected] | af2e192b | 2011-05-30 17:39:09 | [diff] [blame] | 226 | |
| 227 | double cumulative_average = 0.0; |
| 228 | int count = 0; |
| 229 | while (count < kMaxAttempts) { |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 230 | uint64_t value = RandGenerator(kTopOfRange); |
[email protected] | af2e192b | 2011-05-30 17:39:09 | [diff] [blame] | 231 | cumulative_average = (count * cumulative_average + value) / (count + 1); |
| 232 | |
| 233 | // Don't quit too quickly for things to start converging, or we may have |
| 234 | // a false positive. |
| 235 | if (count > kMinAttempts && |
| 236 | kExpectedAverage - kAllowedVariance < cumulative_average && |
| 237 | cumulative_average < kExpectedAverage + kAllowedVariance) { |
| 238 | break; |
| 239 | } |
| 240 | |
| 241 | ++count; |
| 242 | } |
| 243 | |
Benoit Lize | 73de21b | 2021-07-02 08:17:56 | [diff] [blame] | 244 | ASSERT_LT(count, kMaxAttempts) << "Expected average was " << kExpectedAverage |
| 245 | << ", average ended at " << cumulative_average; |
[email protected] | af2e192b | 2011-05-30 17:39:09 | [diff] [blame] | 246 | } |
| 247 | |
| 248 | TEST(RandUtilTest, RandUint64ProducesBothValuesOfAllBits) { |
| 249 | // This tests to see that our underlying random generator is good |
| 250 | // enough, for some value of good enough. |
avi | 9b6f4293 | 2015-12-26 22:15:14 | [diff] [blame] | 251 | uint64_t kAllZeros = 0ULL; |
| 252 | uint64_t kAllOnes = ~kAllZeros; |
| 253 | uint64_t found_ones = kAllZeros; |
| 254 | uint64_t found_zeros = kAllOnes; |
[email protected] | af2e192b | 2011-05-30 17:39:09 | [diff] [blame] | 255 | |
| 256 | for (size_t i = 0; i < 1000; ++i) { |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 257 | uint64_t value = RandUint64(); |
[email protected] | af2e192b | 2011-05-30 17:39:09 | [diff] [blame] | 258 | found_ones |= value; |
| 259 | found_zeros &= value; |
| 260 | |
Peter Kasting | 134ef9af | 2024-12-28 02:30:09 | [diff] [blame] | 261 | if (found_zeros == kAllZeros && found_ones == kAllOnes) { |
[email protected] | af2e192b | 2011-05-30 17:39:09 | [diff] [blame] | 262 | return; |
Peter Kasting | 134ef9af | 2024-12-28 02:30:09 | [diff] [blame] | 263 | } |
[email protected] | af2e192b | 2011-05-30 17:39:09 | [diff] [blame] | 264 | } |
| 265 | |
| 266 | FAIL() << "Didn't achieve all bit values in maximum number of tries."; |
| 267 | } |
[email protected] | c910c5a | 2014-01-23 02:14:28 | [diff] [blame] | 268 | |
Scott Graham | 4ffd63b5 | 2017-06-01 18:03:33 | [diff] [blame] | 269 | TEST(RandUtilTest, RandBytesLonger) { |
| 270 | // Fuchsia can only retrieve 256 bytes of entropy at a time, so make sure we |
| 271 | // handle longer requests than that. |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 272 | std::string random_string0 = RandBytesAsString(255); |
Scott Graham | 4ffd63b5 | 2017-06-01 18:03:33 | [diff] [blame] | 273 | EXPECT_EQ(255u, random_string0.size()); |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 274 | std::string random_string1 = RandBytesAsString(1023); |
Scott Graham | 4ffd63b5 | 2017-06-01 18:03:33 | [diff] [blame] | 275 | EXPECT_EQ(1023u, random_string1.size()); |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 276 | std::string random_string2 = RandBytesAsString(4097); |
Scott Graham | 4ffd63b5 | 2017-06-01 18:03:33 | [diff] [blame] | 277 | EXPECT_EQ(4097u, random_string2.size()); |
| 278 | } |
| 279 | |
[email protected] | c910c5a | 2014-01-23 02:14:28 | [diff] [blame] | 280 | // Benchmark test for RandBytes(). Disabled since it's intentionally slow and |
| 281 | // does not test anything that isn't already tested by the existing RandBytes() |
| 282 | // tests. |
| 283 | TEST(RandUtilTest, DISABLED_RandBytesPerf) { |
| 284 | // Benchmark the performance of |kTestIterations| of RandBytes() using a |
| 285 | // buffer size of |kTestBufferSize|. |
| 286 | const int kTestIterations = 10; |
| 287 | const size_t kTestBufferSize = 1 * 1024 * 1024; |
| 288 | |
danakj | 95305d27 | 2024-05-09 20:38:44 | [diff] [blame] | 289 | std::array<uint8_t, kTestBufferSize> buffer; |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 290 | const TimeTicks now = TimeTicks::Now(); |
danakj | 95305d27 | 2024-05-09 20:38:44 | [diff] [blame] | 291 | for (int i = 0; i < kTestIterations; ++i) { |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 292 | RandBytes(buffer); |
danakj | 95305d27 | 2024-05-09 20:38:44 | [diff] [blame] | 293 | } |
Peter Kasting | a253f75 | 2025-01-31 18:57:26 | [diff] [blame] | 294 | const TimeTicks end = TimeTicks::Now(); |
[email protected] | c910c5a | 2014-01-23 02:14:28 | [diff] [blame] | 295 | |
Benoit Lize | 73de21b | 2021-07-02 08:17:56 | [diff] [blame] | 296 | LOG(INFO) << "RandBytes(" << kTestBufferSize |
| 297 | << ") took: " << (end - now).InMicroseconds() << "µs"; |
[email protected] | c910c5a | 2014-01-23 02:14:28 | [diff] [blame] | 298 | } |
Benoit Lize | 73de21b | 2021-07-02 08:17:56 | [diff] [blame] | 299 | |
| 300 | TEST(RandUtilTest, InsecureRandomGeneratorProducesBothValuesOfAllBits) { |
| 301 | // This tests to see that our underlying random generator is good |
| 302 | // enough, for some value of good enough. |
| 303 | uint64_t kAllZeros = 0ULL; |
| 304 | uint64_t kAllOnes = ~kAllZeros; |
| 305 | uint64_t found_ones = kAllZeros; |
| 306 | uint64_t found_zeros = kAllOnes; |
| 307 | |
| 308 | InsecureRandomGenerator generator; |
Benoit Lize | 73de21b | 2021-07-02 08:17:56 | [diff] [blame] | 309 | |
| 310 | for (size_t i = 0; i < 1000; ++i) { |
| 311 | uint64_t value = generator.RandUint64(); |
| 312 | found_ones |= value; |
| 313 | found_zeros &= value; |
| 314 | |
Peter Kasting | 134ef9af | 2024-12-28 02:30:09 | [diff] [blame] | 315 | if (found_zeros == kAllZeros && found_ones == kAllOnes) { |
Benoit Lize | 73de21b | 2021-07-02 08:17:56 | [diff] [blame] | 316 | return; |
Peter Kasting | 134ef9af | 2024-12-28 02:30:09 | [diff] [blame] | 317 | } |
Benoit Lize | 73de21b | 2021-07-02 08:17:56 | [diff] [blame] | 318 | } |
| 319 | |
| 320 | FAIL() << "Didn't achieve all bit values in maximum number of tries."; |
| 321 | } |
| 322 | |
| 323 | namespace { |
| 324 | |
| 325 | constexpr double kXp1Percent = -2.33; |
| 326 | constexpr double kXp99Percent = 2.33; |
| 327 | |
| 328 | double ChiSquaredCriticalValue(double nu, double x_p) { |
| 329 | // From "The Art Of Computer Programming" (TAOCP), Volume 2, Section 3.3.1, |
| 330 | // Table 1. This is the asymptotic value for nu > 30, up to O(1 / sqrt(nu)). |
| 331 | return nu + sqrt(2. * nu) * x_p + 2. / 3. * (x_p * x_p) - 2. / 3.; |
| 332 | } |
| 333 | |
| 334 | int ExtractBits(uint64_t value, int from_bit, int num_bits) { |
| 335 | return (value >> from_bit) & ((1 << num_bits) - 1); |
| 336 | } |
| 337 | |
| 338 | // Performs a Chi-Squared test on a subset of |num_bits| extracted starting from |
| 339 | // |from_bit| in the generated value. |
| 340 | // |
| 341 | // See TAOCP, Volume 2, Section 3.3.1, and |
| 342 | // https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test for details. |
| 343 | // |
| 344 | // This is only one of the many, many random number generator test we could do, |
| 345 | // but they are cumbersome, as they are typically very slow, and expected to |
| 346 | // fail from time to time, due to their probabilistic nature. |
| 347 | // |
| 348 | // The generator we use has however been vetted with the BigCrush test suite |
| 349 | // from Marsaglia, so this should suffice as a smoke test that our |
| 350 | // implementation is wrong. |
| 351 | bool ChiSquaredTest(InsecureRandomGenerator& gen, |
| 352 | size_t n, |
| 353 | int from_bit, |
| 354 | int num_bits) { |
| 355 | const int range = 1 << num_bits; |
| 356 | CHECK_EQ(static_cast<int>(n % range), 0) << "Makes computations simpler"; |
| 357 | std::vector<size_t> samples(range, 0); |
| 358 | |
| 359 | // Count how many samples pf each value are found. All buckets should be |
| 360 | // almost equal if the generator is suitably uniformly random. |
| 361 | for (size_t i = 0; i < n; i++) { |
| 362 | int sample = ExtractBits(gen.RandUint64(), from_bit, num_bits); |
| 363 | samples[sample] += 1; |
| 364 | } |
| 365 | |
| 366 | // Compute the Chi-Squared statistic, which is: |
| 367 | // \Sum_{k=0}^{range-1} \frac{(count - expected)^2}{expected} |
| 368 | double chi_squared = 0.; |
| 369 | double expected_count = n / range; |
| 370 | for (size_t sample_count : samples) { |
| 371 | double deviation = sample_count - expected_count; |
| 372 | chi_squared += (deviation * deviation) / expected_count; |
| 373 | } |
| 374 | |
| 375 | // The generator should produce numbers that are not too far of (chi_squared |
| 376 | // lower than a given quantile), but not too close to the ideal distribution |
| 377 | // either (chi_squared is too low). |
| 378 | // |
| 379 | // See The Art Of Computer Programming, Volume 2, Section 3.3.1 for details. |
| 380 | return chi_squared > ChiSquaredCriticalValue(range - 1, kXp1Percent) && |
| 381 | chi_squared < ChiSquaredCriticalValue(range - 1, kXp99Percent); |
| 382 | } |
| 383 | |
| 384 | } // namespace |
| 385 | |
| 386 | TEST(RandUtilTest, InsecureRandomGeneratorChiSquared) { |
| 387 | constexpr int kIterations = 50; |
| 388 | |
| 389 | // Specifically test the low bits, which are usually weaker in random number |
| 390 | // generators. We don't use them for the 32 bit number generation, but let's |
| 391 | // make sure they are still suitable. |
| 392 | for (int start_bit : {1, 2, 3, 8, 12, 20, 32, 48, 54}) { |
| 393 | int pass_count = 0; |
| 394 | for (int i = 0; i < kIterations; i++) { |
| 395 | size_t samples = 1 << 16; |
| 396 | InsecureRandomGenerator gen; |
| 397 | // Fix the seed to make the test non-flaky. |
Benoit Lize | 7532d4af | 2021-08-24 11:34:04 | [diff] [blame] | 398 | gen.ReseedForTesting(kIterations + 1); |
Benoit Lize | 73de21b | 2021-07-02 08:17:56 | [diff] [blame] | 399 | bool pass = ChiSquaredTest(gen, samples, start_bit, 8); |
| 400 | pass_count += pass; |
| 401 | } |
| 402 | |
| 403 | // We exclude 1% on each side, so we expect 98% of tests to pass, meaning 98 |
| 404 | // * kIterations / 100. However this is asymptotic, so add a bit of leeway. |
| 405 | int expected_pass_count = (kIterations * 98) / 100; |
| 406 | EXPECT_GE(pass_count, expected_pass_count - ((kIterations * 2) / 100)) |
| 407 | << "For start_bit = " << start_bit; |
| 408 | } |
| 409 | } |
| 410 | |
Benoit Lize | d637714 | 2021-07-05 10:17:16 | [diff] [blame] | 411 | TEST(RandUtilTest, InsecureRandomGeneratorRandDouble) { |
| 412 | InsecureRandomGenerator gen; |
Benoit Lize | d637714 | 2021-07-05 10:17:16 | [diff] [blame] | 413 | |
| 414 | for (int i = 0; i < 1000; i++) { |
| 415 | volatile double x = gen.RandDouble(); |
| 416 | EXPECT_GE(x, 0.); |
| 417 | EXPECT_LT(x, 1.); |
| 418 | } |
| 419 | } |
Olivier Li | ef2b23c | 2024-01-29 20:58:56 | [diff] [blame] | 420 | |
| 421 | TEST(RandUtilTest, MetricsSubSampler) { |
| 422 | MetricsSubSampler sub_sampler; |
| 423 | int true_count = 0; |
| 424 | int false_count = 0; |
| 425 | for (int i = 0; i < 1000; ++i) { |
| 426 | if (sub_sampler.ShouldSample(0.5)) { |
| 427 | ++true_count; |
| 428 | } else { |
| 429 | ++false_count; |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | // Validate that during normal operation MetricsSubSampler::ShouldSample() |
| 434 | // does not always give the same result. It's technically possible to fail |
| 435 | // this test during normal operation but if the sampling is realistic it |
| 436 | // should happen about once every 2^999 times (the likelihood of the [1,999] |
| 437 | // results being the same as [0], which can be either). This should not make |
| 438 | // this test flaky in the eyes of automated testing. |
| 439 | EXPECT_GT(true_count, 0); |
| 440 | EXPECT_GT(false_count, 0); |
| 441 | } |
| 442 | |
| 443 | TEST(RandUtilTest, MetricsSubSamplerTestingSupport) { |
| 444 | MetricsSubSampler sub_sampler; |
| 445 | |
| 446 | // ScopedAlwaysSampleForTesting makes ShouldSample() return true with |
| 447 | // any probability. |
| 448 | { |
| 449 | MetricsSubSampler::ScopedAlwaysSampleForTesting always_sample; |
| 450 | for (int i = 0; i < 100; ++i) { |
| 451 | EXPECT_TRUE(sub_sampler.ShouldSample(0)); |
| 452 | EXPECT_TRUE(sub_sampler.ShouldSample(0.5)); |
| 453 | EXPECT_TRUE(sub_sampler.ShouldSample(1)); |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | // ScopedNeverSampleForTesting makes ShouldSample() return true with |
| 458 | // any probability. |
| 459 | { |
| 460 | MetricsSubSampler::ScopedNeverSampleForTesting always_sample; |
| 461 | for (int i = 0; i < 100; ++i) { |
| 462 | EXPECT_FALSE(sub_sampler.ShouldSample(0)); |
| 463 | EXPECT_FALSE(sub_sampler.ShouldSample(0.5)); |
| 464 | EXPECT_FALSE(sub_sampler.ShouldSample(1)); |
| 465 | } |
| 466 | } |
| 467 | } |
| 468 | |
Benoit Lize | 73de21b | 2021-07-02 08:17:56 | [diff] [blame] | 469 | } // namespace base |