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.
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"
15 bool CheckExpansionCase(const char* input
, const char* expected
, bool success
) {
16 Scope
scope(static_cast<const Settings
*>(nullptr));
18 scope
.SetValue("one", Value(nullptr, one
), nullptr);
19 scope
.SetValue("onestring", Value(nullptr, "one"), nullptr);
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
);
28 Value
result(nullptr, Value::STRING
);
30 bool ret
= ExpandStringLiteral(&scope
, literal
, &result
, &err
);
32 // Err and return value should agree.
33 EXPECT_NE(ret
, err
.has_error());
39 return true; // Don't check result on failure.
40 return result
.string_value() == expected
;
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));
56 EXPECT_TRUE(CheckExpansionCase("hello #$", nullptr, false));
57 EXPECT_TRUE(CheckExpansionCase("hello #$%", nullptr, false));
58 EXPECT_TRUE(CheckExpansionCase("hello #${", nullptr, false));
59 EXPECT_TRUE(CheckExpansionCase("hello #${}", nullptr, false));
60 EXPECT_TRUE(CheckExpansionCase("hello #$nonexistant", nullptr, false));
61 EXPECT_TRUE(CheckExpansionCase("hello #${unterminated", nullptr, false));
63 // Unknown backslash values aren't special.
64 EXPECT_TRUE(CheckExpansionCase("\\", "\\", true));
65 EXPECT_TRUE(CheckExpansionCase("\\b", "\\b", true));
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));