1 /*
2 * Copyright 2019 Google LLC
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "fcp/base/random_token.h"
18
19 #include <string>
20 #include <vector>
21
22 #include "gmock/gmock.h"
23 #include "gtest/gtest.h"
24 #include "absl/container/flat_hash_set.h"
25 #include "absl/hash/hash_testing.h"
26
27 namespace fcp {
28
29 using ::testing::Eq;
30
TEST(RandomTokenTest,Equality)31 TEST(RandomTokenTest, Equality) {
32 RandomToken a1 = RandomToken::Generate();
33 RandomToken a2 = a1;
34 RandomToken b = RandomToken::Generate();
35
36 EXPECT_TRUE(a1 == a2);
37 EXPECT_FALSE(a1 != a2);
38
39 EXPECT_TRUE(b != a1);
40 EXPECT_FALSE(b == a1);
41 }
42
TEST(RandomTokenTest,Hashing)43 TEST(RandomTokenTest, Hashing) {
44 std::vector<RandomToken> distinct;
45 for (int i = 0; i < 128; i++) {
46 distinct.push_back(RandomToken::Generate());
47 }
48
49 EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(distinct));
50 }
51
TEST(RandomTokenTest,Collisions)52 TEST(RandomTokenTest, Collisions) {
53 // If this test ever fails, then we've tragically over-estimated the quality
54 // of our random source.
55 absl::flat_hash_set<RandomToken> tokens;
56 for (int i = 0; i < 1024; i++) {
57 RandomToken t = RandomToken::Generate();
58 bool inserted = tokens.insert(t).second;
59 EXPECT_TRUE(inserted);
60 }
61 }
62
TEST(RandomTokenTest,Serialization)63 TEST(RandomTokenTest, Serialization) {
64 RandomToken original = RandomToken::Generate();
65 auto bytes = original.ToBytes();
66 RandomToken deserialized = RandomToken::FromBytes(bytes);
67 EXPECT_THAT(deserialized, Eq(original));
68 }
69
TEST(RandomTokenTest,SerializationToString)70 TEST(RandomTokenTest, SerializationToString) {
71 RandomToken original = RandomToken::Generate();
72 std::string str = original.ToString();
73 RandomToken deserialized = RandomToken::FromBytes(str);
74 EXPECT_THAT(deserialized, Eq(original));
75 }
76
TEST(RandomTokenTest,ToPrintableString)77 TEST(RandomTokenTest, ToPrintableString) {
78 constexpr char const* kHex = "000102030405060708090a0b0c0d0e0f";
79 std::array<char, kRandomTokenSizeInBytes> kBytes{
80 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
81 EXPECT_THAT(RandomToken::FromBytes(kBytes).ToPrintableString(), Eq(kHex));
82 }
83
84 } // namespace fcp
85