Delete | operator for Subprocess::Options
[folly.git] / folly / test / RandomTest.cpp
index 2f3c97d5cc03180e185f986886fb69c5354d91de..a51baffe5977898d7c486069b1ba1a9cafa31581 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2016 Facebook, Inc.
+ * Copyright 2017 Facebook, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 #include <folly/Random.h>
 
 #include <glog/logging.h>
-#include <gtest/gtest.h>
 
 #include <algorithm>
 #include <thread>
 #include <vector>
 #include <random>
+#include <unordered_set>
+
+#include <folly/portability/GTest.h>
 
 using namespace folly;
 
@@ -47,6 +49,35 @@ TEST(Random, Simple) {
   }
 }
 
+TEST(Random, FixedSeed) {
+  // clang-format off
+  struct ConstantRNG {
+    typedef uint32_t result_type;
+    result_type operator()() {
+      return 4; // chosen by fair dice roll.
+                // guaranteed to be random.
+    }
+    static constexpr result_type min() {
+      return std::numeric_limits<result_type>::min();
+    }
+    static constexpr result_type max() {
+      return std::numeric_limits<result_type>::max();
+    }
+  };
+  // clang-format on
+
+  ConstantRNG gen;
+
+  // Pick a constant random number...
+  auto value = Random::rand32(10, gen);
+
+  // Loop to make sure it really is constant.
+  for (int i = 0; i < 1024; ++i) {
+    auto result = Random::rand32(10, gen);
+    EXPECT_EQ(value, result);
+  }
+}
+
 TEST(Random, MultiThreaded) {
   const int n = 100;
   std::vector<uint32_t> seeds(n);
@@ -64,3 +95,46 @@ TEST(Random, MultiThreaded) {
     EXPECT_LT(seeds[i], seeds[i+1]);
   }
 }
+
+TEST(Random, sanity) {
+  // edge cases
+  EXPECT_EQ(folly::Random::rand32(0), 0);
+  EXPECT_EQ(folly::Random::rand32(12, 12), 0);
+  EXPECT_EQ(folly::Random::rand64(0), 0);
+  EXPECT_EQ(folly::Random::rand64(12, 12), 0);
+
+  // 32-bit repeatability, uniqueness
+  constexpr int kTestSize = 1000;
+  {
+    std::vector<uint32_t> vals;
+    folly::Random::DefaultGenerator rng;
+    rng.seed(0xdeadbeef);
+    for (int i = 0; i < kTestSize; ++i) {
+      vals.push_back(folly::Random::rand32(rng));
+    }
+    rng.seed(0xdeadbeef);
+    for (int i = 0; i < kTestSize; ++i) {
+      EXPECT_EQ(vals[i], folly::Random::rand32(rng));
+    }
+    EXPECT_EQ(
+        vals.size(),
+        std::unordered_set<uint32_t>(vals.begin(), vals.end()).size());
+  }
+
+  // 64-bit repeatability, uniqueness
+  {
+    std::vector<uint64_t> vals;
+    folly::Random::DefaultGenerator rng;
+    rng.seed(0xdeadbeef);
+    for (int i = 0; i < kTestSize; ++i) {
+      vals.push_back(folly::Random::rand64(rng));
+    }
+    rng.seed(0xdeadbeef);
+    for (int i = 0; i < kTestSize; ++i) {
+      EXPECT_EQ(vals[i], folly::Random::rand64(rng));
+    }
+    EXPECT_EQ(
+        vals.size(),
+        std::unordered_set<uint32_t>(vals.begin(), vals.end()).size());
+  }
+}