1 // Copyright (c) 2013 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "testing/gtest/include/gtest/gtest.h" 6 #include "tools/gn/err.h" 7 #include "tools/gn/scope.h" 8 #include "tools/gn/settings.h" 9 #include "tools/gn/string_utils.h" 10 #include "tools/gn/token.h" 11 #include "tools/gn/value.h" 12 13 namespace { 14 15 bool CheckExpansionCase(const char* input, const char* expected, bool success) { 16 Scope scope(static_cast<const Settings*>(NULL)); 17 int64 one = 1; 18 scope.SetValue("one", Value(NULL, one), NULL); 19 scope.SetValue("onestring", Value(NULL, "one"), NULL); 20 21 // Construct the string token, which includes the quotes. 22 std::string literal_string; 23 literal_string.push_back('"'); 24 literal_string.append(input); 25 literal_string.push_back('"'); 26 Token literal(Location(), Token::STRING, literal_string); 27 28 Value result(NULL, Value::STRING); 29 Err err; 30 bool ret = ExpandStringLiteral(&scope, literal, &result, &err); 31 32 // Err and return value should agree. 33 EXPECT_NE(ret, err.has_error()); 34 35 if (ret != success) 36 return false; 37 38 if (!success) 39 return true; // Don't check result on failure. 40 return result.string_value() == expected; 41 } 42 43 } // namespace 44 45 TEST(StringUtils, ExpandStringLiteral) { 46 EXPECT_TRUE(CheckExpansionCase("", "", true)); 47 EXPECT_TRUE(CheckExpansionCase("hello", "hello", true)); 48 EXPECT_TRUE(CheckExpansionCase("hello #$one", "hello #1", true)); 49 EXPECT_TRUE(CheckExpansionCase("hello #$one/two", "hello #1/two", true)); 50 EXPECT_TRUE(CheckExpansionCase("hello #${one}", "hello #1", true)); 51 EXPECT_TRUE(CheckExpansionCase("hello #${one}one", "hello #1one", true)); 52 EXPECT_TRUE(CheckExpansionCase("hello #${one}$one", "hello #11", true)); 53 EXPECT_TRUE(CheckExpansionCase("$onestring${one}$one", "one11", true)); 54 55 // Errors 56 EXPECT_TRUE(CheckExpansionCase("hello #$", NULL, false)); 57 EXPECT_TRUE(CheckExpansionCase("hello #$%", NULL, false)); 58 EXPECT_TRUE(CheckExpansionCase("hello #${", NULL, false)); 59 EXPECT_TRUE(CheckExpansionCase("hello #${}", NULL, false)); 60 EXPECT_TRUE(CheckExpansionCase("hello #$nonexistant", NULL, false)); 61 EXPECT_TRUE(CheckExpansionCase("hello #${unterminated", NULL, false)); 62 63 // Unknown backslash values aren't special. 64 EXPECT_TRUE(CheckExpansionCase("\\", "\\", true)); 65 EXPECT_TRUE(CheckExpansionCase("\\b", "\\b", true)); 66 67 // Backslashes escape some special things. \"\$\\ -> "$\ Note that gtest 68 // doesn't like this escape sequence so we have to put it out-of-line. 69 const char* in = "\\\"\\$\\\\"; 70 const char* out = "\"$\\"; 71 EXPECT_TRUE(CheckExpansionCase(in, out, true)); 72 } 73