blob: 8b922cf799eb2ac73cd3529811821a8685114a0b [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2011 The Chromium Authors
[email protected]05f9b682008-09-29 22:18:012// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
danakj51d26a42024-04-25 14:23:565#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]05f9b682008-09-29 22:18:0110#include "base/rand_util.h"
11
avi9b6f42932015-12-26 22:15:1412#include <stddef.h>
13#include <stdint.h>
14
[email protected]0173b962011-08-24 19:58:3615#include <algorithm>
Benoit Lize73de21b2021-07-02 08:17:5616#include <cmath>
[email protected]05f9b682008-09-29 22:18:0117#include <limits>
dcheng093de9b2016-04-04 21:25:5118#include <memory>
Benoit Lize73de21b2021-07-02 08:17:5619#include <vector>
[email protected]05f9b682008-09-29 22:18:0120
Austin Sullivana41f7f62024-01-09 20:11:5021#include "base/containers/span.h"
[email protected]c910c5a2014-01-23 02:14:2822#include "base/logging.h"
[email protected]c910c5a2014-01-23 02:14:2823#include "base/time/time.h"
[email protected]05f9b682008-09-29 22:18:0124#include "testing/gtest/include/gtest/gtest.h"
25
Benoit Lize73de21b2021-07-02 08:17:5626namespace base {
27
[email protected]05f9b682008-09-29 22:18:0128namespace {
29
Peter Kastinga253f752025-01-31 18:57:2630constexpr int kIntMin = std::numeric_limits<int>::min();
31constexpr int kIntMax = std::numeric_limits<int>::max();
[email protected]05f9b682008-09-29 22:18:0132
33} // namespace
34
Nico Weber0a3852a72015-10-29 20:42:5835TEST(RandUtilTest, RandInt) {
Peter Kastinga253f752025-01-31 18:57:2636 EXPECT_EQ(RandInt(0, 0), 0);
37 EXPECT_EQ(RandInt(kIntMin, kIntMin), kIntMin);
38 EXPECT_EQ(RandInt(kIntMax, kIntMax), kIntMax);
Nico Weber0a3852a72015-10-29 20:42:5839
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 Kasting134ef9af2024-12-28 02:30:0943 for (int i = 0; i < 40; ++i) {
Peter Kastinga253f752025-01-31 18:57:2644 RandInt(kIntMin, kIntMax);
Peter Kasting134ef9af2024-12-28 02:30:0945 }
[email protected]05f9b682008-09-29 22:18:0146}
[email protected]94a0f312008-09-30 14:26:3347
48TEST(RandUtilTest, RandDouble) {
[email protected]29548d82011-04-29 21:03:5449 // Force 64-bit precision, making sure we're not in a 80-bit FPU register.
Peter Kastinga253f752025-01-31 18:57:2650 volatile double number = RandDouble();
51 EXPECT_LT(number, 1.0);
52 EXPECT_GE(number, 0.0);
[email protected]29548d82011-04-29 21:03:5453}
54
Avery Musbacheff342b2022-10-06 18:36:0755TEST(RandUtilTest, RandFloat) {
56 // Force 32-bit precision, making sure we're not in an 80-bit FPU register.
Peter Kastinga253f752025-01-31 18:57:2657 volatile float number = RandFloat();
58 EXPECT_LT(number, 1.0f);
59 EXPECT_GE(number, 0.0f);
Avery Musbacheff342b2022-10-06 18:36:0760}
61
Peter Kastingb2dc55042025-01-16 16:30:5462TEST(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 Kastingf18c8ca2023-10-04 16:31:5170TEST(RandUtilTest, RandTimeDelta) {
71 {
Peter Kastinga253f752025-01-31 18:57:2672 const auto delta = RandTimeDelta(-Seconds(2), -Seconds(1));
73 EXPECT_GE(delta, -Seconds(2));
74 EXPECT_LT(delta, -Seconds(1));
Peter Kastingf18c8ca2023-10-04 16:31:5175 }
76
77 {
Peter Kastinga253f752025-01-31 18:57:2678 const auto delta = RandTimeDelta(-Seconds(2), Seconds(2));
79 EXPECT_GE(delta, -Seconds(2));
80 EXPECT_LT(delta, Seconds(2));
Peter Kastingf18c8ca2023-10-04 16:31:5181 }
82
83 {
Peter Kastinga253f752025-01-31 18:57:2684 const auto delta = RandTimeDelta(Seconds(1), Seconds(2));
85 EXPECT_GE(delta, Seconds(1));
86 EXPECT_LT(delta, Seconds(2));
Peter Kastingf18c8ca2023-10-04 16:31:5187 }
88}
89
90TEST(RandUtilTest, RandTimeDeltaUpTo) {
Peter Kastinga253f752025-01-31 18:57:2691 const auto delta = RandTimeDeltaUpTo(Seconds(2));
Peter Kastingf18c8ca2023-10-04 16:31:5192 EXPECT_FALSE(delta.is_negative());
Peter Kastinga253f752025-01-31 18:57:2693 EXPECT_LT(delta, Seconds(2));
Peter Kastingf18c8ca2023-10-04 16:31:5194}
95
Peter Kastingb2dc55042025-01-16 16:30:5496TEST(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 Musbach92a30e382022-09-08 23:30:41113TEST(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 Musbacheff342b2022-10-06 18:36:07133TEST(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]51a01812011-05-05 08:46:11153TEST(RandUtilTest, RandBytes) {
[email protected]0173b962011-08-24 19:58:36154 const size_t buffer_size = 50;
Austin Sullivana41f7f62024-01-09 20:11:50155 uint8_t buffer[buffer_size];
[email protected]51a01812011-05-05 08:46:11156 memset(buffer, 0, buffer_size);
Peter Kastinga253f752025-01-31 18:57:26157 RandBytes(buffer);
[email protected]0173b962011-08-24 19:58:36158 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]51a01812011-05-05 08:46:11162}
163
Peter Kastinga253f752025-01-31 18:57:26164// Verify that calling RandBytes with an empty buffer doesn't fail.
Sergey Ulanovfdc62f8e2017-08-01 19:51:00165TEST(RandUtilTest, RandBytes0) {
Peter Kastinga253f752025-01-31 18:57:26166 RandBytes(span<uint8_t>());
Sergey Ulanovfdc62f8e2017-08-01 19:51:00167}
168
Tom Sepez230a75c62023-11-13 23:27:16169TEST(RandUtilTest, RandBytesAsVector) {
Peter Kastinga253f752025-01-31 18:57:26170 std::vector<uint8_t> random_vec = RandBytesAsVector(0);
Tom Sepez230a75c62023-11-13 23:27:16171 EXPECT_TRUE(random_vec.empty());
Peter Kastinga253f752025-01-31 18:57:26172 random_vec = RandBytesAsVector(1);
Tom Sepez230a75c62023-11-13 23:27:16173 EXPECT_EQ(1U, random_vec.size());
Peter Kastinga253f752025-01-31 18:57:26174 random_vec = RandBytesAsVector(145);
Tom Sepez230a75c62023-11-13 23:27:16175 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]29548d82011-04-29 21:03:54185TEST(RandUtilTest, RandBytesAsString) {
Peter Kastinga253f752025-01-31 18:57:26186 std::string random_string = RandBytesAsString(1);
[email protected]fdce4782011-11-29 20:06:18187 EXPECT_EQ(1U, random_string.size());
Peter Kastinga253f752025-01-31 18:57:26188 random_string = RandBytesAsString(145);
[email protected]29548d82011-04-29 21:03:54189 EXPECT_EQ(145U, random_string.size());
190 char accumulator = 0;
Peter Kasting134ef9af2024-12-28 02:30:09191 for (auto i : random_string) {
jdoerrie6c6229352018-10-22 15:55:43192 accumulator |= i;
Peter Kasting134ef9af2024-12-28 02:30:09193 }
[email protected]29548d82011-04-29 21:03:54194 // 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]94a0f312008-09-30 14:26:33197}
[email protected]a74dcae2010-08-30 21:07:05198
199// Make sure that it is still appropriate to use RandGenerator in conjunction
200// with std::random_shuffle().
201TEST(RandUtilTest, RandGeneratorForRandomShuffle) {
Peter Kastinga253f752025-01-31 18:57:26202 EXPECT_EQ(RandGenerator(1), 0U);
[email protected]a74dcae2010-08-30 21:07:05203 EXPECT_LE(std::numeric_limits<ptrdiff_t>::max(),
avi9b6f42932015-12-26 22:15:14204 std::numeric_limits<int64_t>::max());
[email protected]a74dcae2010-08-30 21:07:05205}
[email protected]af2e192b2011-05-30 17:39:09206
207TEST(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 Kastinga253f752025-01-31 18:57:26212 // return RandUint64() % max;
[email protected]af2e192b2011-05-30 17:39:09213 //
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 Kastingfbb9e562021-06-27 02:57:37220 constexpr uint64_t kTopOfRange =
avi9b6f42932015-12-26 22:15:14221 (std::numeric_limits<uint64_t>::max() / 4ULL) * 3ULL;
Peter Kastingfbb9e562021-06-27 02:57:37222 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]af2e192b2011-05-30 17:39:09226
227 double cumulative_average = 0.0;
228 int count = 0;
229 while (count < kMaxAttempts) {
Peter Kastinga253f752025-01-31 18:57:26230 uint64_t value = RandGenerator(kTopOfRange);
[email protected]af2e192b2011-05-30 17:39:09231 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 Lize73de21b2021-07-02 08:17:56244 ASSERT_LT(count, kMaxAttempts) << "Expected average was " << kExpectedAverage
245 << ", average ended at " << cumulative_average;
[email protected]af2e192b2011-05-30 17:39:09246}
247
248TEST(RandUtilTest, RandUint64ProducesBothValuesOfAllBits) {
249 // This tests to see that our underlying random generator is good
250 // enough, for some value of good enough.
avi9b6f42932015-12-26 22:15:14251 uint64_t kAllZeros = 0ULL;
252 uint64_t kAllOnes = ~kAllZeros;
253 uint64_t found_ones = kAllZeros;
254 uint64_t found_zeros = kAllOnes;
[email protected]af2e192b2011-05-30 17:39:09255
256 for (size_t i = 0; i < 1000; ++i) {
Peter Kastinga253f752025-01-31 18:57:26257 uint64_t value = RandUint64();
[email protected]af2e192b2011-05-30 17:39:09258 found_ones |= value;
259 found_zeros &= value;
260
Peter Kasting134ef9af2024-12-28 02:30:09261 if (found_zeros == kAllZeros && found_ones == kAllOnes) {
[email protected]af2e192b2011-05-30 17:39:09262 return;
Peter Kasting134ef9af2024-12-28 02:30:09263 }
[email protected]af2e192b2011-05-30 17:39:09264 }
265
266 FAIL() << "Didn't achieve all bit values in maximum number of tries.";
267}
[email protected]c910c5a2014-01-23 02:14:28268
Scott Graham4ffd63b52017-06-01 18:03:33269TEST(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 Kastinga253f752025-01-31 18:57:26272 std::string random_string0 = RandBytesAsString(255);
Scott Graham4ffd63b52017-06-01 18:03:33273 EXPECT_EQ(255u, random_string0.size());
Peter Kastinga253f752025-01-31 18:57:26274 std::string random_string1 = RandBytesAsString(1023);
Scott Graham4ffd63b52017-06-01 18:03:33275 EXPECT_EQ(1023u, random_string1.size());
Peter Kastinga253f752025-01-31 18:57:26276 std::string random_string2 = RandBytesAsString(4097);
Scott Graham4ffd63b52017-06-01 18:03:33277 EXPECT_EQ(4097u, random_string2.size());
278}
279
[email protected]c910c5a2014-01-23 02:14:28280// 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.
283TEST(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
danakj95305d272024-05-09 20:38:44289 std::array<uint8_t, kTestBufferSize> buffer;
Peter Kastinga253f752025-01-31 18:57:26290 const TimeTicks now = TimeTicks::Now();
danakj95305d272024-05-09 20:38:44291 for (int i = 0; i < kTestIterations; ++i) {
Peter Kastinga253f752025-01-31 18:57:26292 RandBytes(buffer);
danakj95305d272024-05-09 20:38:44293 }
Peter Kastinga253f752025-01-31 18:57:26294 const TimeTicks end = TimeTicks::Now();
[email protected]c910c5a2014-01-23 02:14:28295
Benoit Lize73de21b2021-07-02 08:17:56296 LOG(INFO) << "RandBytes(" << kTestBufferSize
297 << ") took: " << (end - now).InMicroseconds() << "µs";
[email protected]c910c5a2014-01-23 02:14:28298}
Benoit Lize73de21b2021-07-02 08:17:56299
300TEST(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 Lize73de21b2021-07-02 08:17:56309
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 Kasting134ef9af2024-12-28 02:30:09315 if (found_zeros == kAllZeros && found_ones == kAllOnes) {
Benoit Lize73de21b2021-07-02 08:17:56316 return;
Peter Kasting134ef9af2024-12-28 02:30:09317 }
Benoit Lize73de21b2021-07-02 08:17:56318 }
319
320 FAIL() << "Didn't achieve all bit values in maximum number of tries.";
321}
322
323namespace {
324
325constexpr double kXp1Percent = -2.33;
326constexpr double kXp99Percent = 2.33;
327
328double 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
334int 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.
351bool 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
386TEST(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 Lize7532d4af2021-08-24 11:34:04398 gen.ReseedForTesting(kIterations + 1);
Benoit Lize73de21b2021-07-02 08:17:56399 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 Lized6377142021-07-05 10:17:16411TEST(RandUtilTest, InsecureRandomGeneratorRandDouble) {
412 InsecureRandomGenerator gen;
Benoit Lized6377142021-07-05 10:17:16413
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 Lief2b23c2024-01-29 20:58:56420
421TEST(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
443TEST(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 Lize73de21b2021-07-02 08:17:56469} // namespace base