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 <sstream> 6 7 #include "testing/gtest/include/gtest/gtest.h" 8 #include "tools/gn/escape.h" 9 #include "tools/gn/file_template.h" 10 11 TEST(FileTemplate, Static) { 12 std::vector<std::string> templates; 13 templates.push_back("something_static"); 14 FileTemplate t(templates); 15 EXPECT_FALSE(t.has_substitutions()); 16 17 std::vector<std::string> result; 18 t.ApplyString("", &result); 19 ASSERT_EQ(1u, result.size()); 20 EXPECT_EQ("something_static", result[0]); 21 22 t.ApplyString("lalala", &result); 23 ASSERT_EQ(1u, result.size()); 24 EXPECT_EQ("something_static", result[0]); 25 } 26 27 TEST(FileTemplate, Typical) { 28 std::vector<std::string> templates; 29 templates.push_back("foo/{{source_name_part}}.cc"); 30 templates.push_back("foo/{{source_name_part}}.h"); 31 FileTemplate t(templates); 32 EXPECT_TRUE(t.has_substitutions()); 33 34 std::vector<std::string> result; 35 t.ApplyString("sources/ha.idl", &result); 36 ASSERT_EQ(2u, result.size()); 37 EXPECT_EQ("foo/ha.cc", result[0]); 38 EXPECT_EQ("foo/ha.h", result[1]); 39 } 40 41 TEST(FileTemplate, Weird) { 42 std::vector<std::string> templates; 43 templates.push_back("{{{source}}{{source}}{{"); 44 FileTemplate t(templates); 45 EXPECT_TRUE(t.has_substitutions()); 46 47 std::vector<std::string> result; 48 t.ApplyString("foo/lalala.c", &result); 49 ASSERT_EQ(1u, result.size()); 50 EXPECT_EQ("{foo/lalala.cfoo/lalala.c{{", result[0]); 51 } 52 53 TEST(FileTemplate, NinjaExpansions) { 54 std::vector<std::string> templates; 55 templates.push_back("-i"); 56 templates.push_back("{{source}}"); 57 templates.push_back("--out=foo bar\"{{source_name_part}}\".o"); 58 59 FileTemplate t(templates); 60 61 std::ostringstream out; 62 t.WriteWithNinjaExpansions(out); 63 64 // The third argument should get quoted since it contains a space, and the 65 // embedded quotes should get shell escaped. 66 EXPECT_EQ( 67 " -i ${source} \"--out=foo$ bar\\\"${source_name_part}\\\".o\"", 68 out.str()); 69 } 70 71 TEST(FileTemplate, NinjaVariables) { 72 std::vector<std::string> templates; 73 templates.push_back("-i"); 74 templates.push_back("{{source}}"); 75 templates.push_back("--out=foo bar\"{{source_name_part}}\".o"); 76 77 FileTemplate t(templates); 78 79 std::ostringstream out; 80 EscapeOptions options; 81 options.mode = ESCAPE_NINJA_SHELL; 82 t.WriteNinjaVariablesForSubstitution(out, "../../foo/bar.txt", options); 83 84 // Just the variables used above should be written. 85 EXPECT_EQ( 86 " source = ../../foo/bar.txt\n" 87 " source_name_part = bar\n", 88 out.str()); 89 } 90