1 #include "helpers.hpp"
2 #include "utils/conversion.hpp"
3 
4 #include <gmock/gmock.h>
5 
6 using namespace testing;
7 
8 class TestConversion : public Test
9 {
10   public:
11     enum class Enum
12     {
13         zero = 0,
14         one,
15         two
16     };
17 
18     Enum toEnum(int x)
19     {
20         return utils::toEnum<Enum, utils::minEnumValue(convDataEnum),
21                              utils::maxEnumValue(convDataEnum)>(x);
22     }
23 
24     Enum toEnum(const std::string& value)
25     {
26         return utils::toEnum(convDataEnum, value);
27     }
28 
29     std::string enumToString(Enum value)
30     {
31         return std::string(utils::enumToString(convDataEnum, value));
32     }
33 
34     static constexpr std::array<std::pair<std::string_view, Enum>, 3>
35         convDataEnum = {
36             {std::make_pair<std::string_view, Enum>("zero", Enum::zero),
37              std::make_pair<std::string_view, Enum>("one", Enum::one),
38              std::make_pair<std::string_view, Enum>("two", Enum::two)}};
39 };
40 
41 namespace utils
42 {
43 
44 template <>
45 struct EnumTraits<TestConversion::Enum>
46 {
47     static constexpr auto propertyName = ConstexprString{"Enum"};
48 };
49 
50 } // namespace utils
51 
52 TEST_F(TestConversion, passValueInRangeExpectToGetValidOutput)
53 {
54     EXPECT_EQ(toEnum(0), Enum::zero);
55     EXPECT_EQ(toEnum(2), Enum::two);
56 }
57 
58 TEST_F(TestConversion, passInvalidValueExpectToThrowException)
59 {
60     EXPECT_THROW(toEnum(-1), errors::InvalidArgument);
61     EXPECT_THROW(toEnum(3), errors::InvalidArgument);
62 }
63 
64 TEST_F(TestConversion, convertsToUnderlyingType)
65 {
66     EXPECT_THAT(utils::toUnderlying(Enum::one), Eq(1));
67     EXPECT_THAT(utils::toUnderlying(Enum::two), Eq(2));
68     EXPECT_THAT(utils::toUnderlying(Enum::zero), Eq(0));
69 }
70 
71 TEST_F(TestConversion, convertsEnumToString)
72 {
73     EXPECT_THAT(enumToString(Enum::one), Eq("one"));
74     EXPECT_THAT(enumToString(Enum::two), Eq("two"));
75     EXPECT_THAT(enumToString(Enum::zero), Eq("zero"));
76 }
77 
78 TEST_F(TestConversion, convertsStringToEnum)
79 {
80     EXPECT_THAT(toEnum("one"), Eq(Enum::one));
81     EXPECT_THAT(toEnum("two"), Eq(Enum::two));
82     EXPECT_THAT(toEnum("zero"), Eq(Enum::zero));
83 }
84 
85 TEST_F(TestConversion, enumToStringThrowsWhenUknownEnumPassed)
86 {
87     EXPECT_THROW(enumToString(static_cast<Enum>(77)), errors::InvalidArgument);
88 }
89 
90 TEST_F(TestConversion, toEnumThrowsWhenUknownStringPassed)
91 {
92     EXPECT_THROW(toEnum("four"), errors::InvalidArgument);
93 }
94