1 // Copyright (C) 2019 The Android Open Source Project 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 "utils/config_file.h" 16 17 #include <sstream> 18 19 #include <gtest/gtest.h> 20 21 22 namespace header_checker { 23 namespace utils { 24 25 26 TEST(ConfigParserTest, Parse) { 27 std::stringstream stream(R"( 28 # Comment line starts with hash symbol 29 ; Comment line starts with semicolon 30 31 [section1] 32 key1 = value1 33 key2 = value2 34 35 [section2] 36 key1 = true 37 key2 = false 38 )"); 39 40 auto &&cfg = ConfigParser::ParseFile(stream); 41 EXPECT_TRUE(cfg.HasSection("section1")); 42 EXPECT_TRUE(cfg.HasSection("section2")); 43 EXPECT_FALSE(cfg.HasSection("section3")); 44 45 auto &§ion1 = cfg.GetSection("section1"); 46 EXPECT_TRUE(section1.HasProperty("key1")); 47 EXPECT_EQ("value1", section1.GetProperty("key1")); 48 EXPECT_TRUE(section1.HasProperty("key2")); 49 EXPECT_EQ("value2", section1.GetProperty("key2")); 50 51 EXPECT_FALSE(section1.HasProperty("key3")); 52 EXPECT_EQ("", section1.GetProperty("key3")); 53 54 auto &§ion2 = cfg.GetSection("section2"); 55 EXPECT_TRUE(section2.HasProperty("key1")); 56 EXPECT_EQ("true", section2.GetProperty("key1")); 57 EXPECT_TRUE(section2.HasProperty("key2")); 58 EXPECT_EQ("false", section2.GetProperty("key2")); 59 60 EXPECT_EQ("value1", cfg.GetProperty("section1", "key1")); 61 EXPECT_EQ("value2", cfg.GetProperty("section1", "key2")); 62 63 EXPECT_EQ("value1", cfg["section1"]["key1"]); 64 EXPECT_EQ("value2", cfg["section1"]["key2"]); 65 } 66 67 68 TEST(ConfigParserTest, BadSectionNameLine) { 69 std::stringstream stream(R"( 70 [section1 71 key1 = value1 72 )"); 73 74 size_t num_errors = 0; 75 76 ConfigParser parser(stream); 77 parser.SetErrorListener( 78 [&num_errors](size_t line_no, const char *cause) { 79 ++num_errors; 80 EXPECT_EQ(2, line_no); 81 EXPECT_STREQ("bad section name line", cause); 82 }); 83 parser.ParseFile(); 84 85 EXPECT_EQ(1, num_errors); 86 } 87 88 89 TEST(ConfigParserTest, BadKeyValueLine) { 90 std::stringstream stream(R"( 91 [section1] 92 key1 93 )"); 94 95 size_t num_errors = 0; 96 97 ConfigParser parser(stream); 98 parser.SetErrorListener( 99 [&num_errors](size_t line_no, const char *cause) { 100 ++num_errors; 101 EXPECT_EQ(3, line_no); 102 EXPECT_STREQ("bad key-value line", cause); 103 }); 104 parser.ParseFile(); 105 106 EXPECT_EQ(1, num_errors); 107 } 108 109 110 } // namespace utils 111 } // namespace header_checker 112