blob: 4d165b396521cd2c47bbf67a7f834068c9e809ac [file] [log] [blame]
Alex Deymoedfa1d42014-04-28 16:53:51 -07001// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Alex Deymo63784a52014-05-28 10:46:14 -07005#include "update_engine/update_manager/prng.h"
Alex Deymoedfa1d42014-04-28 16:53:51 -07006
7#include <vector>
8
9#include <gtest/gtest.h>
10
11using std::vector;
12
Alex Deymo63784a52014-05-28 10:46:14 -070013namespace chromeos_update_manager {
Alex Deymoedfa1d42014-04-28 16:53:51 -070014
Alex Deymo63784a52014-05-28 10:46:14 -070015TEST(UmPRNGTest, ShouldBeDeterministic) {
Alex Deymoedfa1d42014-04-28 16:53:51 -070016 PRNG a(42);
17 PRNG b(42);
18
19 for (int i = 0; i < 1000; ++i) {
Gilad Arnolde1218812014-05-07 12:21:36 -070020 EXPECT_EQ(a.Rand(), b.Rand()) << "Iteration i=" << i;
Alex Deymoedfa1d42014-04-28 16:53:51 -070021 }
22}
23
Alex Deymo63784a52014-05-28 10:46:14 -070024TEST(UmPRNGTest, SeedChangesGeneratedSequence) {
Alex Deymoedfa1d42014-04-28 16:53:51 -070025 PRNG a(42);
26 PRNG b(5);
27
Gilad Arnolde1218812014-05-07 12:21:36 -070028 vector<uint32_t> values_a;
29 vector<uint32_t> values_b;
Alex Deymoedfa1d42014-04-28 16:53:51 -070030
31 for (int i = 0; i < 100; ++i) {
Gilad Arnolde1218812014-05-07 12:21:36 -070032 values_a.push_back(a.Rand());
33 values_b.push_back(b.Rand());
Alex Deymoedfa1d42014-04-28 16:53:51 -070034 }
35 EXPECT_NE(values_a, values_b);
36}
37
Alex Deymo63784a52014-05-28 10:46:14 -070038TEST(UmPRNGTest, IsNotConstant) {
Alex Deymoedfa1d42014-04-28 16:53:51 -070039 PRNG prng(5);
40
Gilad Arnolde1218812014-05-07 12:21:36 -070041 uint32_t initial_value = prng.Rand();
Alex Deymoedfa1d42014-04-28 16:53:51 -070042 bool prng_is_constant = true;
43 for (int i = 0; i < 100; ++i) {
Gilad Arnolde1218812014-05-07 12:21:36 -070044 if (prng.Rand() != initial_value) {
Alex Deymoedfa1d42014-04-28 16:53:51 -070045 prng_is_constant = false;
46 break;
47 }
48 }
49 EXPECT_FALSE(prng_is_constant) << "After 100 iterations.";
50}
51
Alex Deymo63784a52014-05-28 10:46:14 -070052TEST(UmPRNGTest, RandCoversRange) {
Gilad Arnolde1218812014-05-07 12:21:36 -070053 PRNG a(42);
54 int hits[11] = { 0 };
55
56 for (int i = 0; i < 1000; i++) {
57 int r = a.RandMinMax(0, 10);
58 ASSERT_LE(0, r);
59 ASSERT_GE(10, r);
60 hits[r]++;
61 }
62
63 for (auto& hit : hits)
64 EXPECT_LT(0, hit);
65}
66
Alex Deymo63784a52014-05-28 10:46:14 -070067} // namespace chromeos_update_manager