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