diff options
author | Mathias Stearn <mathias@10gen.com> | 2015-08-25 17:17:39 -0400 |
---|---|---|
committer | Mathias Stearn <mathias@10gen.com> | 2015-08-28 15:23:54 -0400 |
commit | 1c5fdf89ee6fd377096b9369b94ee490792a22b8 (patch) | |
tree | 661e7a672e417375cc7685c0d11c98b7f1442c2d /src/mongo/platform/random_test.cpp | |
parent | 1eca10057d98aa46e9adf3b06edac74c437edfd3 (diff) | |
download | mongo-1c5fdf89ee6fd377096b9369b94ee490792a22b8.tar.gz |
SERVER-20121 Use unsigned arithmetic in PsuedoRandom
Diffstat (limited to 'src/mongo/platform/random_test.cpp')
-rw-r--r-- | src/mongo/platform/random_test.cpp | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/src/mongo/platform/random_test.cpp b/src/mongo/platform/random_test.cpp index c4e214f1af9..183ab03b3eb 100644 --- a/src/mongo/platform/random_test.cpp +++ b/src/mongo/platform/random_test.cpp @@ -29,6 +29,7 @@ */ #include <set> +#include <vector> #include "mongo/platform/random.h" @@ -145,6 +146,72 @@ TEST(RandomTest, NextCanonicalWithinRange) { } } +TEST(RandomTest, NextInt32SanityCheck) { + // Generate 1000 int32s and assert that each bit is set between 40% and 60% of the time. This is + // a bare minimum sanity check, not an attempt to ensure quality random numbers. + + PseudoRandom a(11); + std::vector<int32_t> nums; + for (int i = 0; i < 1000; i++) { + nums.push_back(a.nextInt32()); + } + + for (int bit = 0; bit < 32; bit++) { + int onesCount = 0; + for (auto&& num : nums) { + bool isSet = (num >> bit) & 1; + if (isSet) + onesCount++; + } + + if (onesCount < 400 || onesCount > 600) + FAIL(str::stream() << "bit " << bit << " was set " << (onesCount / 10.) + << "% of the time."); + } +} + +TEST(RandomTest, NextInt64SanityCheck) { + // Generate 1000 int64s and assert that each bit is set between 40% and 60% of the time. This is + // a bare minimum sanity check, not an attempt to ensure quality random numbers. + + PseudoRandom a(11); + std::vector<int64_t> nums; + for (int i = 0; i < 1000; i++) { + nums.push_back(a.nextInt64()); + } + + for (int bit = 0; bit < 64; bit++) { + int onesCount = 0; + for (auto&& num : nums) { + bool isSet = (num >> bit) & 1; + if (isSet) + onesCount++; + } + + if (onesCount < 400 || onesCount > 600) + FAIL(str::stream() << "bit " << bit << " was set " << (onesCount / 10.) + << "% of the time."); + } +} + +TEST(RandomTest, NextInt32InRange) { + PseudoRandom a(11); + for (int i = 0; i < 1000; i++) { + auto res = a.nextInt32(10); + ASSERT_GTE(res, 0); + ASSERT_LT(res, 10); + } +} + +TEST(RandomTest, NextInt64InRange) { + PseudoRandom a(11); + for (int i = 0; i < 1000; i++) { + auto res = a.nextInt64(10); + ASSERT_GTE(res, 0); + ASSERT_LT(res, 10); + } +} + TEST(RandomTest, Secure1) { SecureRandom* a = SecureRandom::create(); SecureRandom* b = SecureRandom::create(); |