tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

uniform_int_distribution_test.cc (8903B)


      1 // Copyright 2017 The Abseil Authors.
      2 //
      3 // Licensed under the Apache License, Version 2.0 (the "License");
      4 // you may not use this file except in compliance with the License.
      5 // You may obtain a copy of the License at
      6 //
      7 //      https://www.apache.org/licenses/LICENSE-2.0
      8 //
      9 // Unless required by applicable law or agreed to in writing, software
     10 // distributed under the License is distributed on an "AS IS" BASIS,
     11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 // See the License for the specific language governing permissions and
     13 // limitations under the License.
     14 
     15 #include "absl/random/uniform_int_distribution.h"
     16 
     17 #include <cmath>
     18 #include <cstdint>
     19 #include <iterator>
     20 #include <random>
     21 #include <sstream>
     22 #include <string>
     23 #include <vector>
     24 
     25 #include "gmock/gmock.h"
     26 #include "gtest/gtest.h"
     27 #include "absl/log/log.h"
     28 #include "absl/random/internal/chi_square.h"
     29 #include "absl/random/internal/distribution_test_util.h"
     30 #include "absl/random/internal/pcg_engine.h"
     31 #include "absl/random/internal/sequence_urbg.h"
     32 #include "absl/random/random.h"
     33 #include "absl/strings/str_cat.h"
     34 
     35 namespace {
     36 
     37 template <typename IntType>
     38 class UniformIntDistributionTest : public ::testing::Test {};
     39 
     40 using IntTypes = ::testing::Types<int8_t, uint8_t, int16_t, uint16_t, int32_t,
     41                                  uint32_t, int64_t, uint64_t>;
     42 TYPED_TEST_SUITE(UniformIntDistributionTest, IntTypes);
     43 
     44 TYPED_TEST(UniformIntDistributionTest, ParamSerializeTest) {
     45  // This test essentially ensures that the parameters serialize,
     46  // not that the values generated cover the full range.
     47  using Limits = std::numeric_limits<TypeParam>;
     48  using param_type =
     49      typename absl::uniform_int_distribution<TypeParam>::param_type;
     50  const TypeParam kMin = std::is_unsigned<TypeParam>::value ? 37 : -105;
     51  const TypeParam kNegOneOrZero = std::is_unsigned<TypeParam>::value ? 0 : -1;
     52 
     53  constexpr int kCount = 1000;
     54  absl::InsecureBitGen gen;
     55  for (const auto& param : {
     56           param_type(),
     57           param_type(2, 2),  // Same
     58           param_type(9, 32),
     59           param_type(kMin, 115),
     60           param_type(kNegOneOrZero, Limits::max()),
     61           param_type(Limits::min(), Limits::max()),
     62           param_type(Limits::lowest(), Limits::max()),
     63           param_type(Limits::min() + 1, Limits::max() - 1),
     64       }) {
     65    const auto a = param.a();
     66    const auto b = param.b();
     67    absl::uniform_int_distribution<TypeParam> before(a, b);
     68    EXPECT_EQ(before.a(), param.a());
     69    EXPECT_EQ(before.b(), param.b());
     70 
     71    {
     72      // Initialize via param_type
     73      absl::uniform_int_distribution<TypeParam> via_param(param);
     74      EXPECT_EQ(via_param, before);
     75    }
     76 
     77    // Initialize via iostreams
     78    std::stringstream ss;
     79    ss << before;
     80 
     81    absl::uniform_int_distribution<TypeParam> after(Limits::min() + 3,
     82                                                    Limits::max() - 5);
     83 
     84    EXPECT_NE(before.a(), after.a());
     85    EXPECT_NE(before.b(), after.b());
     86    EXPECT_NE(before.param(), after.param());
     87    EXPECT_NE(before, after);
     88 
     89    ss >> after;
     90 
     91    EXPECT_EQ(before.a(), after.a());
     92    EXPECT_EQ(before.b(), after.b());
     93    EXPECT_EQ(before.param(), after.param());
     94    EXPECT_EQ(before, after);
     95 
     96    // Smoke test.
     97    auto sample_min = after.max();
     98    auto sample_max = after.min();
     99    for (int i = 0; i < kCount; i++) {
    100      auto sample = after(gen);
    101      EXPECT_GE(sample, after.min());
    102      EXPECT_LE(sample, after.max());
    103      if (sample > sample_max) {
    104        sample_max = sample;
    105      }
    106      if (sample < sample_min) {
    107        sample_min = sample;
    108      }
    109    }
    110    LOG(INFO) << "Range: " << sample_min << ", " << sample_max;
    111  }
    112 }
    113 
    114 TYPED_TEST(UniformIntDistributionTest, ViolatesPreconditionsDeathTest) {
    115 #if GTEST_HAS_DEATH_TEST
    116  // Hi < Lo
    117  EXPECT_DEBUG_DEATH(
    118      { absl::uniform_int_distribution<TypeParam> dist(10, 1); }, "");
    119 #endif  // GTEST_HAS_DEATH_TEST
    120 #if defined(NDEBUG)
    121  // opt-mode, for invalid parameters, will generate a garbage value,
    122  // but should not enter an infinite loop.
    123  absl::InsecureBitGen gen;
    124  absl::uniform_int_distribution<TypeParam> dist(10, 1);
    125  auto x = dist(gen);
    126 
    127  // Any value will generate a non-empty string.
    128  EXPECT_FALSE(absl::StrCat(+x).empty()) << x;
    129 #endif  // NDEBUG
    130 }
    131 
    132 TYPED_TEST(UniformIntDistributionTest, TestMoments) {
    133  constexpr int kSize = 100000;
    134  using Limits = std::numeric_limits<TypeParam>;
    135  using param_type =
    136      typename absl::uniform_int_distribution<TypeParam>::param_type;
    137 
    138  // We use a fixed bit generator for distribution accuracy tests.  This allows
    139  // these tests to be deterministic, while still testing the quality of the
    140  // implementation.
    141  absl::random_internal::pcg64_2018_engine rng{0x2B7E151628AED2A6};
    142 
    143  std::vector<double> values(kSize);
    144  for (const auto& param :
    145       {param_type(0, Limits::max()), param_type(13, 127)}) {
    146    absl::uniform_int_distribution<TypeParam> dist(param);
    147    for (int i = 0; i < kSize; i++) {
    148      const auto sample = dist(rng);
    149      ASSERT_LE(dist.param().a(), sample);
    150      ASSERT_GE(dist.param().b(), sample);
    151      values[i] = sample;
    152    }
    153 
    154    auto moments = absl::random_internal::ComputeDistributionMoments(values);
    155    const double a = dist.param().a();
    156    const double b = dist.param().b();
    157    const double n = (b - a + 1);
    158    const double mean = (a + b) / 2;
    159    const double var = ((b - a + 1) * (b - a + 1) - 1) / 12;
    160    const double kurtosis = 3 - 6 * (n * n + 1) / (5 * (n * n - 1));
    161 
    162    // TODO(ahh): this is not the right bound
    163    // empirically validated with --runs_per_test=10000.
    164    EXPECT_NEAR(mean, moments.mean, 0.01 * var);
    165    EXPECT_NEAR(var, moments.variance, 0.015 * var);
    166    EXPECT_NEAR(0.0, moments.skewness, 0.025);
    167    EXPECT_NEAR(kurtosis, moments.kurtosis, 0.02 * kurtosis);
    168  }
    169 }
    170 
    171 TYPED_TEST(UniformIntDistributionTest, ChiSquaredTest50) {
    172  using absl::random_internal::kChiSquared;
    173 
    174  constexpr size_t kTrials = 1000;
    175  constexpr int kBuckets = 50;  // inclusive, so actually +1
    176  constexpr double kExpected =
    177      static_cast<double>(kTrials) / static_cast<double>(kBuckets);
    178 
    179  // Empirically validated with --runs_per_test=10000.
    180  const int kThreshold =
    181      absl::random_internal::ChiSquareValue(kBuckets, 0.999999);
    182 
    183  const TypeParam min = std::is_unsigned<TypeParam>::value ? 37 : -37;
    184  const TypeParam max = min + kBuckets;
    185 
    186  // We use a fixed bit generator for distribution accuracy tests.  This allows
    187  // these tests to be deterministic, while still testing the quality of the
    188  // implementation.
    189  absl::random_internal::pcg64_2018_engine rng{0x2B7E151628AED2A6};
    190 
    191  absl::uniform_int_distribution<TypeParam> dist(min, max);
    192 
    193  std::vector<int32_t> counts(kBuckets + 1, 0);
    194  for (size_t i = 0; i < kTrials; i++) {
    195    auto x = dist(rng);
    196    counts[x - min]++;
    197  }
    198  double chi_square = absl::random_internal::ChiSquareWithExpected(
    199      std::begin(counts), std::end(counts), kExpected);
    200  if (chi_square > kThreshold) {
    201    double p_value =
    202        absl::random_internal::ChiSquarePValue(chi_square, kBuckets);
    203 
    204    // Chi-squared test failed. Output does not appear to be uniform.
    205    std::string msg;
    206    for (const auto& a : counts) {
    207      absl::StrAppend(&msg, a, "\n");
    208    }
    209    absl::StrAppend(&msg, kChiSquared, " p-value ", p_value, "\n");
    210    absl::StrAppend(&msg, "High ", kChiSquared, " value: ", chi_square, " > ",
    211                    kThreshold);
    212    LOG(INFO) << msg;
    213    FAIL() << msg;
    214  }
    215 }
    216 
    217 TEST(UniformIntDistributionTest, StabilityTest) {
    218  // absl::uniform_int_distribution stability relies only on integer operations.
    219  absl::random_internal::sequence_urbg urbg(
    220      {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull,
    221       0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull,
    222       0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull,
    223       0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull});
    224 
    225  std::vector<int> output(12);
    226 
    227  {
    228    absl::uniform_int_distribution<int32_t> dist(0, 4);
    229    for (auto& v : output) {
    230      v = dist(urbg);
    231    }
    232  }
    233  EXPECT_EQ(12, urbg.invocations());
    234  EXPECT_THAT(output, testing::ElementsAre(4, 4, 3, 2, 1, 0, 1, 4, 3, 1, 3, 1));
    235 
    236  {
    237    urbg.reset();
    238    absl::uniform_int_distribution<int32_t> dist(0, 100);
    239    for (auto& v : output) {
    240      v = dist(urbg);
    241    }
    242  }
    243  EXPECT_EQ(12, urbg.invocations());
    244  EXPECT_THAT(output, testing::ElementsAre(97, 86, 75, 41, 36, 16, 38, 92, 67,
    245                                           30, 80, 38));
    246 
    247  {
    248    urbg.reset();
    249    absl::uniform_int_distribution<int32_t> dist(0, 10000);
    250    for (auto& v : output) {
    251      v = dist(urbg);
    252    }
    253  }
    254  EXPECT_EQ(12, urbg.invocations());
    255  EXPECT_THAT(output, testing::ElementsAre(9648, 8562, 7439, 4089, 3571, 1602,
    256                                           3813, 9195, 6641, 2986, 7956, 3765));
    257 }
    258 
    259 }  // namespace