abarth@chromium.org | 29548d8 | 2011-04-29 21:03:54 | [diff] [blame] | 1 | // Copyright (c) 2011 The Chromium Authors. All rights reserved. |
mark@chromium.org | 05f9b68 | 2008-09-29 22:18:01 | [diff] [blame] | 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "base/rand_util.h" |
| 6 | |
| 7 | #include <limits> |
| 8 | |
| 9 | #include "testing/gtest/include/gtest/gtest.h" |
| 10 | |
| 11 | namespace { |
| 12 | |
| 13 | const int kIntMin = std::numeric_limits<int>::min(); |
| 14 | const int kIntMax = std::numeric_limits<int>::max(); |
| 15 | |
| 16 | } // namespace |
| 17 | |
| 18 | TEST(RandUtilTest, SameMinAndMax) { |
| 19 | EXPECT_EQ(base::RandInt(0, 0), 0); |
| 20 | EXPECT_EQ(base::RandInt(kIntMin, kIntMin), kIntMin); |
| 21 | EXPECT_EQ(base::RandInt(kIntMax, kIntMax), kIntMax); |
| 22 | } |
mark@chromium.org | 94a0f31 | 2008-09-30 14:26:33 | [diff] [blame] | 23 | |
| 24 | TEST(RandUtilTest, RandDouble) { |
abarth@chromium.org | 29548d8 | 2011-04-29 21:03:54 | [diff] [blame] | 25 | // Force 64-bit precision, making sure we're not in a 80-bit FPU register. |
| 26 | volatile double number = base::RandDouble(); |
| 27 | EXPECT_GT(1.0, number); |
| 28 | EXPECT_LE(0.0, number); |
| 29 | } |
| 30 | |
qsr@google.com | 51a0181 | 2011-05-05 08:46:11 | [diff] [blame^] | 31 | TEST(RandUtilTest, RandBytes) { |
| 32 | const size_t buffer_size = 145; |
| 33 | char buffer[buffer_size]; |
| 34 | memset(buffer, 0, buffer_size); |
| 35 | base::RandBytes(buffer, buffer_size); |
| 36 | char accumulator = 0; |
| 37 | for(size_t i = 0; i < buffer_size; ++i) |
| 38 | accumulator |= buffer[i]; |
| 39 | // In theory this test can fail, but it won't before the universe dies of |
| 40 | // heat death. |
| 41 | EXPECT_NE(0, accumulator); |
| 42 | } |
| 43 | |
abarth@chromium.org | 29548d8 | 2011-04-29 21:03:54 | [diff] [blame] | 44 | TEST(RandUtilTest, RandBytesAsString) { |
| 45 | std::string random_string = base::RandBytesAsString(0); |
| 46 | EXPECT_EQ(0U, random_string.size()); |
| 47 | random_string = base::RandBytesAsString(145); |
| 48 | EXPECT_EQ(145U, random_string.size()); |
| 49 | char accumulator = 0; |
| 50 | for (size_t i = 0; i < random_string.size(); ++i) |
| 51 | accumulator |= random_string[i]; |
| 52 | // In theory this test can fail, but it won't before the universe dies of |
| 53 | // heat death. |
| 54 | EXPECT_NE(0, accumulator); |
mark@chromium.org | 94a0f31 | 2008-09-30 14:26:33 | [diff] [blame] | 55 | } |
isherman@chromium.org | a74dcae | 2010-08-30 21:07:05 | [diff] [blame] | 56 | |
| 57 | // Make sure that it is still appropriate to use RandGenerator in conjunction |
| 58 | // with std::random_shuffle(). |
| 59 | TEST(RandUtilTest, RandGeneratorForRandomShuffle) { |
| 60 | EXPECT_EQ(base::RandGenerator(1), 0U); |
| 61 | EXPECT_LE(std::numeric_limits<ptrdiff_t>::max(), |
| 62 | std::numeric_limits<int64>::max()); |
| 63 | } |