1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors
3 #include "utils/hex_utils.hpp"
4
5 #include <cctype>
6 #include <cstdint>
7 #include <limits>
8 #include <vector>
9
10 #include <gmock/gmock.h>
11 #include <gtest/gtest.h>
12
13 namespace
14 {
15
16 using ::testing::IsEmpty;
17
TEST(BytesToHexString,OnSuccess)18 TEST(BytesToHexString, OnSuccess)
19 {
20 EXPECT_EQ(bytesToHexString({{0x1a, 0x2b}}), "1A2B");
21 }
22
TEST(HexCharToNibble,ReturnsCorrectNibbleForEveryHexChar)23 TEST(HexCharToNibble, ReturnsCorrectNibbleForEveryHexChar)
24 {
25 for (char c = 0; c < std::numeric_limits<char>::max(); ++c)
26 {
27 uint8_t expected = 16;
28 if (isdigit(c) != 0)
29 {
30 expected = static_cast<uint8_t>(c) - '0';
31 }
32 else if (c >= 'A' && c <= 'F')
33 {
34 expected = static_cast<uint8_t>(c - 'A') + 10U;
35 }
36 else if (c >= 'a' && c <= 'f')
37 {
38 expected = static_cast<uint8_t>(c - 'a') + 10U;
39 }
40
41 EXPECT_EQ(hexCharToNibble(c), expected);
42 }
43 }
44
TEST(HexStringToBytes,Success)45 TEST(HexStringToBytes, Success)
46 {
47 std::vector<uint8_t> hexBytes = {0x01, 0x23, 0x45, 0x67,
48 0x89, 0xAB, 0xCD, 0xEF};
49 EXPECT_EQ(hexStringToBytes("0123456789ABCDEF"), hexBytes);
50 EXPECT_THAT(hexStringToBytes(""), IsEmpty());
51 }
52
TEST(HexStringToBytes,Failure)53 TEST(HexStringToBytes, Failure)
54 {
55 EXPECT_THAT(hexStringToBytes("Hello"), IsEmpty());
56 EXPECT_THAT(hexStringToBytes("`"), IsEmpty());
57 EXPECT_THAT(hexStringToBytes("012"), IsEmpty());
58 }
59
60 } // namespace
61