1// Copyright 2012 Google Inc. All Rights Reserved.
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//     http://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 <gtest/gtest.h>
16#include <polo/util/poloutil.h>
17
18namespace polo {
19namespace util {
20
21TEST(PoloUtilTest, BytesToHexString) {
22  uint8_t bytes[4] = {0xAA, 0xBB, 0xCC, 0xDD};
23  std::string result = PoloUtil::BytesToHexString(bytes, 4);
24  ASSERT_EQ(std::string("AABBCCDD"), result);
25}
26
27TEST(PoloUtilTest, BytesToHexStringLeadingNull) {
28  uint8_t bytes[4] = {0x00, 0xBB, 0xCC, 0xDD};
29  std::string result = PoloUtil::BytesToHexString(bytes, 4);
30  ASSERT_EQ(std::string("BBCCDD"), result);
31}
32
33TEST(PoloUtilTest, HexStringToBytes) {
34  uint8_t* bytes;
35  size_t length = PoloUtil::HexStringToBytes(std::string("AABBCCDD"), bytes);
36  ASSERT_EQ(4, length);
37  ASSERT_EQ(0xAA, bytes[0]);
38  ASSERT_EQ(0xBB, bytes[1]);
39  ASSERT_EQ(0xCC, bytes[2]);
40  ASSERT_EQ(0xDD, bytes[3]);
41  delete[] bytes;
42}
43
44TEST(PoloUtilTest, IntToBigEndianBytes) {
45  uint8_t* bytes;
46  PoloUtil::IntToBigEndianBytes(0xAABBCCDD, bytes);
47  ASSERT_EQ(0xAA, bytes[0]);
48  ASSERT_EQ(0xBB, bytes[1]);
49  ASSERT_EQ(0xCC, bytes[2]);
50  ASSERT_EQ(0xDD, bytes[3]);
51  delete[] bytes;
52}
53
54TEST(PoloUtilTest, IntToBigEndianBytes_NullBytes) {
55  uint8_t* bytes;
56  PoloUtil::IntToBigEndianBytes(0x00AABB00, bytes);
57  ASSERT_EQ(0x00, bytes[0]);
58  ASSERT_EQ(0xAA, bytes[1]);
59  ASSERT_EQ(0xBB, bytes[2]);
60  ASSERT_EQ(0x00, bytes[3]);
61  delete[] bytes;
62}
63
64TEST(PoloUtilTest, BigEndianBytesToInt) {
65  uint8_t bytes[4] = {0xAA, 0xBB, 0xCC, 0xDD};
66  const uint32_t value = PoloUtil::BigEndianBytesToInt(bytes);
67  ASSERT_EQ(0xAABBCCDD, value);
68}
69
70TEST(PoloUtilTest, BigEndianBytesToInt_NullBytes) {
71  uint8_t bytes[4] = {0x00, 0xAA, 0xBB, 0x00};
72  const uint32_t value = PoloUtil::BigEndianBytesToInt(bytes);
73  ASSERT_EQ(0x00AABB00, value);
74}
75
76TEST(PoloUtilTest, GenerateRandomBytes) {
77  uint8_t* random1 = PoloUtil::GenerateRandomBytes(16);
78  ASSERT_TRUE(random1);
79  const std::string value1 = PoloUtil::BytesToHexString(random1, 16);
80  delete[] random1;
81
82  uint8_t* random2 = PoloUtil::GenerateRandomBytes(16);
83  ASSERT_TRUE(random2);
84  const std::string value2 = PoloUtil::BytesToHexString(random2, 16);
85  delete[] random2;
86
87  ASSERT_NE(value1, value2);
88}
89
90}  // namespace util
91}  // namespace polo
92