1 // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
2 // This source code is licensed under both the GPLv2 (found in the
3 // COPYING file in the root directory) and Apache 2.0 License
4 // (found in the LICENSE.Apache file in the root directory).
5 //
6 // Copyright (c) 2012 The LevelDB Authors. All rights reserved.
7 // Use of this source code is governed by a BSD-style license that can be
8 // found in the LICENSE file. See the AUTHORS file for names of contributors.
9
10 #include <cstring>
11 #include <vector>
12
13 #include "test_util/testharness.h"
14 #include "util/random.h"
15
16 using ROCKSDB_NAMESPACE::Random;
17
TEST(RandomTest,Uniform)18 TEST(RandomTest, Uniform) {
19 const int average = 20;
20 for (uint32_t seed : {0, 1, 2, 37, 4096}) {
21 Random r(seed);
22 for (int range : {1, 2, 8, 12, 100}) {
23 std::vector<int> counts(range, 0);
24
25 for (int i = 0; i < range * average; ++i) {
26 ++counts.at(r.Uniform(range));
27 }
28 int max_variance = static_cast<int>(std::sqrt(range) * 2 + 4);
29 for (int i = 0; i < range; ++i) {
30 EXPECT_GE(counts[i], std::max(1, average - max_variance));
31 EXPECT_LE(counts[i], average + max_variance + 1);
32 }
33 }
34 }
35 }
36
TEST(RandomTest,OneIn)37 TEST(RandomTest, OneIn) {
38 Random r(42);
39 for (int range : {1, 2, 8, 12, 100, 1234}) {
40 const int average = 100;
41 int count = 0;
42 for (int i = 0; i < average * range; ++i) {
43 if (r.OneIn(range)) {
44 ++count;
45 }
46 }
47 if (range == 1) {
48 EXPECT_EQ(count, average);
49 } else {
50 int max_variance = static_cast<int>(std::sqrt(average) * 1.5);
51 EXPECT_GE(count, average - max_variance);
52 EXPECT_LE(count, average + max_variance);
53 }
54 }
55 }
56
TEST(RandomTest,OneInOpt)57 TEST(RandomTest, OneInOpt) {
58 Random r(42);
59 for (int range : {-12, 0, 1, 2, 8, 12, 100, 1234}) {
60 const int average = 100;
61 int count = 0;
62 for (int i = 0; i < average * range; ++i) {
63 if (r.OneInOpt(range)) {
64 ++count;
65 }
66 }
67 if (range < 1) {
68 EXPECT_EQ(count, 0);
69 } else if (range == 1) {
70 EXPECT_EQ(count, average);
71 } else {
72 int max_variance = static_cast<int>(std::sqrt(average) * 1.5);
73 EXPECT_GE(count, average - max_variance);
74 EXPECT_LE(count, average + max_variance);
75 }
76 }
77 }
78
TEST(RandomTest,PercentTrue)79 TEST(RandomTest, PercentTrue) {
80 Random r(42);
81 for (int pct : {-12, 0, 1, 2, 10, 50, 90, 98, 99, 100, 1234}) {
82 const int samples = 10000;
83
84 int count = 0;
85 for (int i = 0; i < samples; ++i) {
86 if (r.PercentTrue(pct)) {
87 ++count;
88 }
89 }
90 if (pct <= 0) {
91 EXPECT_EQ(count, 0);
92 } else if (pct >= 100) {
93 EXPECT_EQ(count, samples);
94 } else {
95 int est = (count * 100 + (samples / 2)) / samples;
96 EXPECT_EQ(est, pct);
97 }
98 }
99 }
100
main(int argc,char ** argv)101 int main(int argc, char** argv) {
102 ::testing::InitGoogleTest(&argc, argv);
103
104 return RUN_ALL_TESTS();
105 }
106