blob: 689b8ad3967eacb7a3bf6b1d5497cf73137aa6a3 [file] [log] [blame]
abarth@chromium.orgc19cb312011-04-30 06:03:54 +09001// Copyright (c) 2011 The Chromium Authors. All rights reserved.
mark@chromium.orgb93c0542008-09-30 07:18:01 +09002// 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
dilmah@chromium.orgbd365732011-08-25 04:58:36 +09007#include <algorithm>
mark@chromium.orgb93c0542008-09-30 07:18:01 +09008#include <limits>
9
dalecurtis@chromium.org4f4a8772014-01-23 11:14:28 +090010#include "base/logging.h"
11#include "base/memory/scoped_ptr.h"
12#include "base/time/time.h"
mark@chromium.orgb93c0542008-09-30 07:18:01 +090013#include "testing/gtest/include/gtest/gtest.h"
14
15namespace {
16
17const int kIntMin = std::numeric_limits<int>::min();
18const int kIntMax = std::numeric_limits<int>::max();
19
20} // namespace
21
Nico Weber1796efe2015-10-30 05:42:58 +090022TEST(RandUtilTest, RandInt) {
mark@chromium.orgb93c0542008-09-30 07:18:01 +090023 EXPECT_EQ(base::RandInt(0, 0), 0);
24 EXPECT_EQ(base::RandInt(kIntMin, kIntMin), kIntMin);
25 EXPECT_EQ(base::RandInt(kIntMax, kIntMax), kIntMax);
Nico Weber1796efe2015-10-30 05:42:58 +090026
27 // Check that the DCHECKS in RandInt() don't fire due to internal overflow.
28 // There was a 50% chance of that happening, so calling it 40 times means
29 // the chances of this passing by accident are tiny (9e-13).
30 for (int i = 0; i < 40; ++i)
31 base::RandInt(kIntMin, kIntMax);
mark@chromium.orgb93c0542008-09-30 07:18:01 +090032}
mark@chromium.orgc22c62b2008-09-30 23:26:33 +090033
34TEST(RandUtilTest, RandDouble) {
abarth@chromium.orgc19cb312011-04-30 06:03:54 +090035 // Force 64-bit precision, making sure we're not in a 80-bit FPU register.
36 volatile double number = base::RandDouble();
37 EXPECT_GT(1.0, number);
38 EXPECT_LE(0.0, number);
39}
40
qsr@google.comfbda4d52011-05-05 17:46:11 +090041TEST(RandUtilTest, RandBytes) {
dilmah@chromium.orgbd365732011-08-25 04:58:36 +090042 const size_t buffer_size = 50;
qsr@google.comfbda4d52011-05-05 17:46:11 +090043 char buffer[buffer_size];
44 memset(buffer, 0, buffer_size);
45 base::RandBytes(buffer, buffer_size);
dilmah@chromium.orgbd365732011-08-25 04:58:36 +090046 std::sort(buffer, buffer + buffer_size);
47 // Probability of occurrence of less than 25 unique bytes in 50 random bytes
48 // is below 10^-25.
49 EXPECT_GT(std::unique(buffer, buffer + buffer_size) - buffer, 25);
qsr@google.comfbda4d52011-05-05 17:46:11 +090050}
51
abarth@chromium.orgc19cb312011-04-30 06:03:54 +090052TEST(RandUtilTest, RandBytesAsString) {
pkasting@chromium.orgd3479372011-11-30 05:06:18 +090053 std::string random_string = base::RandBytesAsString(1);
54 EXPECT_EQ(1U, random_string.size());
abarth@chromium.orgc19cb312011-04-30 06:03:54 +090055 random_string = base::RandBytesAsString(145);
56 EXPECT_EQ(145U, random_string.size());
57 char accumulator = 0;
58 for (size_t i = 0; i < random_string.size(); ++i)
59 accumulator |= random_string[i];
60 // In theory this test can fail, but it won't before the universe dies of
61 // heat death.
62 EXPECT_NE(0, accumulator);
mark@chromium.orgc22c62b2008-09-30 23:26:33 +090063}
isherman@chromium.org01eaa0b2010-08-31 06:07:05 +090064
65// Make sure that it is still appropriate to use RandGenerator in conjunction
66// with std::random_shuffle().
67TEST(RandUtilTest, RandGeneratorForRandomShuffle) {
68 EXPECT_EQ(base::RandGenerator(1), 0U);
69 EXPECT_LE(std::numeric_limits<ptrdiff_t>::max(),
70 std::numeric_limits<int64>::max());
71}
joi@chromium.orgedf24fc2011-05-31 02:39:09 +090072
73TEST(RandUtilTest, RandGeneratorIsUniform) {
74 // Verify that RandGenerator has a uniform distribution. This is a
75 // regression test that consistently failed when RandGenerator was
76 // implemented this way:
77 //
78 // return base::RandUint64() % max;
79 //
80 // A degenerate case for such an implementation is e.g. a top of
81 // range that is 2/3rds of the way to MAX_UINT64, in which case the
82 // bottom half of the range would be twice as likely to occur as the
83 // top half. A bit of calculus care of jar@ shows that the largest
84 // measurable delta is when the top of the range is 3/4ths of the
85 // way, so that's what we use in the test.
86 const uint64 kTopOfRange = (std::numeric_limits<uint64>::max() / 4ULL) * 3ULL;
87 const uint64 kExpectedAverage = kTopOfRange / 2ULL;
88 const uint64 kAllowedVariance = kExpectedAverage / 50ULL; // +/- 2%
89 const int kMinAttempts = 1000;
90 const int kMaxAttempts = 1000000;
91
92 double cumulative_average = 0.0;
93 int count = 0;
94 while (count < kMaxAttempts) {
95 uint64 value = base::RandGenerator(kTopOfRange);
96 cumulative_average = (count * cumulative_average + value) / (count + 1);
97
98 // Don't quit too quickly for things to start converging, or we may have
99 // a false positive.
100 if (count > kMinAttempts &&
101 kExpectedAverage - kAllowedVariance < cumulative_average &&
102 cumulative_average < kExpectedAverage + kAllowedVariance) {
103 break;
104 }
105
106 ++count;
107 }
108
109 ASSERT_LT(count, kMaxAttempts) << "Expected average was " <<
110 kExpectedAverage << ", average ended at " << cumulative_average;
111}
112
113TEST(RandUtilTest, RandUint64ProducesBothValuesOfAllBits) {
114 // This tests to see that our underlying random generator is good
115 // enough, for some value of good enough.
116 uint64 kAllZeros = 0ULL;
117 uint64 kAllOnes = ~kAllZeros;
118 uint64 found_ones = kAllZeros;
119 uint64 found_zeros = kAllOnes;
120
121 for (size_t i = 0; i < 1000; ++i) {
122 uint64 value = base::RandUint64();
123 found_ones |= value;
124 found_zeros &= value;
125
126 if (found_zeros == kAllZeros && found_ones == kAllOnes)
127 return;
128 }
129
130 FAIL() << "Didn't achieve all bit values in maximum number of tries.";
131}
dalecurtis@chromium.org4f4a8772014-01-23 11:14:28 +0900132
133// Benchmark test for RandBytes(). Disabled since it's intentionally slow and
134// does not test anything that isn't already tested by the existing RandBytes()
135// tests.
136TEST(RandUtilTest, DISABLED_RandBytesPerf) {
137 // Benchmark the performance of |kTestIterations| of RandBytes() using a
138 // buffer size of |kTestBufferSize|.
139 const int kTestIterations = 10;
140 const size_t kTestBufferSize = 1 * 1024 * 1024;
141
142 scoped_ptr<uint8[]> buffer(new uint8[kTestBufferSize]);
charlieaddf2b792015-01-27 02:35:41 +0900143 const base::TimeTicks now = base::TimeTicks::Now();
dalecurtis@chromium.org4f4a8772014-01-23 11:14:28 +0900144 for (int i = 0; i < kTestIterations; ++i)
145 base::RandBytes(buffer.get(), kTestBufferSize);
charlieaddf2b792015-01-27 02:35:41 +0900146 const base::TimeTicks end = base::TimeTicks::Now();
dalecurtis@chromium.org4f4a8772014-01-23 11:14:28 +0900147
148 LOG(INFO) << "RandBytes(" << kTestBufferSize << ") took: "
149 << (end - now).InMicroseconds() << "µs";
150}