file_test_base.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "testing/file_test/file_test_base.h"
  5. #include <filesystem>
  6. #include <fstream>
  7. #include "common/check.h"
  8. #include "llvm/ADT/Twine.h"
  9. #include "llvm/Support/InitLLVM.h"
  10. namespace Carbon::Testing {
  11. // The length of the base directory.
  12. static int base_dir_len = 0;
  13. // The name of the `.subset` target.
  14. static std::string* subset_target = nullptr;
  15. using ::testing::Eq;
  16. void FileTestBase::RegisterTests(
  17. const char* fixture_label,
  18. const llvm::SmallVector<std::filesystem::path>& paths,
  19. std::function<FileTestBase*(const std::filesystem::path&)> factory) {
  20. // Use RegisterTest instead of INSTANTIATE_TEST_CASE_P because of ordering
  21. // issues between container initialization and test instantiation by
  22. // InitGoogleTest.
  23. for (const auto& path : paths) {
  24. std::string test_name = path.string().substr(base_dir_len);
  25. testing::RegisterTest(fixture_label, test_name.c_str(), nullptr,
  26. test_name.c_str(), __FILE__, __LINE__,
  27. [=]() { return factory(path); });
  28. }
  29. }
  30. // Reads a file to string.
  31. static auto ReadFile(std::filesystem::path path) -> std::string {
  32. std::ifstream proto_file(path);
  33. std::stringstream buffer;
  34. buffer << proto_file.rdbuf();
  35. proto_file.close();
  36. return buffer.str();
  37. }
  38. // Splits outputs to string_view because gtest handles string_view by default.
  39. static auto SplitOutput(llvm::StringRef output)
  40. -> llvm::SmallVector<std::string_view> {
  41. if (output.empty()) {
  42. return {};
  43. }
  44. llvm::SmallVector<llvm::StringRef> lines;
  45. llvm::StringRef(output).split(lines, "\n");
  46. return llvm::SmallVector<std::string_view>(lines.begin(), lines.end());
  47. }
  48. // Runs a test and compares output. This keeps output split by line so that
  49. // issues are a little easier to identify by the different line.
  50. auto FileTestBase::TestBody() -> void {
  51. const char* src_dir = getenv("TEST_SRCDIR");
  52. CARBON_CHECK(src_dir);
  53. std::string test_file = path().lexically_relative(
  54. std::filesystem::path(src_dir).append("carbon"));
  55. llvm::errs() << "\nTo test this file alone, run:\n bazel test "
  56. << *subset_target << " --test_arg=" << test_file << "\n\n";
  57. // Store the file so that test_files can use references to content.
  58. std::string test_content = ReadFile(path());
  59. // Load expected output.
  60. llvm::SmallVector<TestFile> test_files;
  61. llvm::SmallVector<testing::Matcher<std::string>> expected_stdout;
  62. llvm::SmallVector<testing::Matcher<std::string>> expected_stderr;
  63. ProcessTestFile(test_content, test_files, expected_stdout, expected_stderr);
  64. if (HasFailure()) {
  65. return;
  66. }
  67. // Capture trace streaming, but only when in debug mode.
  68. std::string stdout;
  69. std::string stderr;
  70. llvm::raw_string_ostream stdout_ostream(stdout);
  71. llvm::raw_string_ostream stderr_ostream(stderr);
  72. bool run_succeeded = RunWithFiles(test_files, stdout_ostream, stderr_ostream);
  73. if (HasFailure()) {
  74. return;
  75. }
  76. EXPECT_THAT(!llvm::StringRef(path().filename()).starts_with("fail_"),
  77. Eq(run_succeeded))
  78. << "Tests should be prefixed with `fail_` if and only if running them "
  79. "is expected to fail.";
  80. // Check results.
  81. EXPECT_THAT(SplitOutput(stdout), ElementsAreArray(expected_stdout));
  82. EXPECT_THAT(SplitOutput(stderr), ElementsAreArray(expected_stderr));
  83. }
  84. auto FileTestBase::ProcessTestFile(
  85. llvm::StringRef file_content, llvm::SmallVector<TestFile>& test_files,
  86. llvm::SmallVector<testing::Matcher<std::string>>& expected_stdout,
  87. llvm::SmallVector<testing::Matcher<std::string>>& expected_stderr) -> void {
  88. llvm::StringRef cursor = file_content;
  89. bool found_content_pre_split = false;
  90. int line_index = 0;
  91. llvm::StringRef current_file_name;
  92. const char* current_file_start = nullptr;
  93. while (!cursor.empty()) {
  94. auto [line, next_cursor] = cursor.split("\n");
  95. cursor = next_cursor;
  96. static constexpr llvm::StringLiteral SplitPrefix = "// ---";
  97. if (line.consume_front(SplitPrefix)) {
  98. // On a file split, add the previous file, then start a new one.
  99. if (current_file_start) {
  100. test_files.push_back(TestFile(
  101. current_file_name.str(),
  102. llvm::StringRef(
  103. current_file_start,
  104. line.begin() - current_file_start - SplitPrefix.size())));
  105. } else {
  106. // For the first split, we make sure there was no content prior.
  107. ASSERT_FALSE(found_content_pre_split)
  108. << "When using split files, there must be no content before the "
  109. "first split file.";
  110. }
  111. current_file_name = line.trim();
  112. current_file_start = cursor.begin();
  113. line_index = 0;
  114. continue;
  115. } else if (!current_file_start && !line.starts_with("//") &&
  116. !line.trim().empty()) {
  117. found_content_pre_split = true;
  118. }
  119. ++line_index;
  120. // Process expectations when found.
  121. auto line_trimmed = line.ltrim();
  122. if (!line_trimmed.consume_front("// CHECK")) {
  123. continue;
  124. }
  125. if (line_trimmed.consume_front(":STDOUT:")) {
  126. expected_stdout.push_back(TransformExpectation(line_index, line_trimmed));
  127. } else if (line_trimmed.consume_front(":STDERR:")) {
  128. expected_stderr.push_back(TransformExpectation(line_index, line_trimmed));
  129. } else {
  130. FAIL() << "Unexpected CHECK in input: " << line.str();
  131. }
  132. }
  133. if (current_file_start) {
  134. test_files.push_back(
  135. TestFile(current_file_name.str(),
  136. llvm::StringRef(current_file_start,
  137. file_content.end() - current_file_start)));
  138. } else {
  139. // If no file splitting happened, use the main file as the test file.
  140. test_files.push_back(TestFile(path().filename().string(), file_content));
  141. }
  142. // Assume there is always a suffix `\n` in output.
  143. if (!expected_stdout.empty()) {
  144. expected_stdout.push_back(testing::StrEq(""));
  145. }
  146. if (!expected_stderr.empty()) {
  147. expected_stderr.push_back(testing::StrEq(""));
  148. }
  149. }
  150. auto FileTestBase::TransformExpectation(int line_index, llvm::StringRef in)
  151. -> testing::Matcher<std::string> {
  152. if (in.empty()) {
  153. return testing::StrEq("");
  154. }
  155. CARBON_CHECK(in[0] == ' ') << "Malformated input: " << in;
  156. std::string str = in.substr(1).str();
  157. for (int pos = 0; pos < static_cast<int>(str.size());) {
  158. switch (str[pos]) {
  159. case '(':
  160. case ')':
  161. case ']':
  162. case '}':
  163. case '.':
  164. case '^':
  165. case '$':
  166. case '*':
  167. case '+':
  168. case '?':
  169. case '|':
  170. case '\\': {
  171. // Escape regex characters.
  172. str.insert(pos, "\\");
  173. pos += 2;
  174. break;
  175. }
  176. case '[': {
  177. llvm::StringRef line_keyword_cursor = llvm::StringRef(str).substr(pos);
  178. if (line_keyword_cursor.consume_front("[[")) {
  179. static constexpr llvm::StringLiteral LineKeyword = "@LINE";
  180. if (line_keyword_cursor.consume_front(LineKeyword)) {
  181. // Allow + or - here; consumeInteger handles -.
  182. line_keyword_cursor.consume_front("+");
  183. int offset;
  184. // consumeInteger returns true for errors, not false.
  185. CARBON_CHECK(!line_keyword_cursor.consumeInteger(10, offset) &&
  186. line_keyword_cursor.consume_front("]]"))
  187. << "Unexpected @LINE offset at `"
  188. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  189. std::string int_str = llvm::Twine(line_index + offset).str();
  190. int remove_len = (line_keyword_cursor.data() - str.data()) - pos;
  191. str.replace(pos, remove_len, int_str);
  192. pos += int_str.size();
  193. } else {
  194. CARBON_FATAL() << "Unexpected [[, should be {{\\[\\[}} at `"
  195. << line_keyword_cursor.substr(0, 5)
  196. << "` in: " << in;
  197. }
  198. } else {
  199. // Escape the `[`.
  200. str.insert(pos, "\\");
  201. pos += 2;
  202. }
  203. break;
  204. }
  205. case '{': {
  206. if (pos + 1 == static_cast<int>(str.size()) || str[pos + 1] != '{') {
  207. // Single `{`, escape it.
  208. str.insert(pos, "\\");
  209. pos += 2;
  210. } else {
  211. // Replace the `{{...}}` regex syntax with standard `(...)` syntax.
  212. str.replace(pos, 2, "(");
  213. for (++pos; pos < static_cast<int>(str.size() - 1); ++pos) {
  214. if (str[pos] == '}' && str[pos + 1] == '}') {
  215. str.replace(pos, 2, ")");
  216. ++pos;
  217. break;
  218. }
  219. }
  220. }
  221. break;
  222. }
  223. default: {
  224. ++pos;
  225. }
  226. }
  227. }
  228. return testing::MatchesRegex(str);
  229. }
  230. } // namespace Carbon::Testing
  231. auto main(int argc, char** argv) -> int {
  232. testing::InitGoogleTest(&argc, argv);
  233. llvm::setBugReportMsg(
  234. "Please report issues to "
  235. "https://github.com/carbon-language/carbon-lang/issues and include the "
  236. "crash backtrace.\n");
  237. llvm::InitLLVM init_llvm(argc, argv);
  238. if (argc < 2) {
  239. llvm::errs() << "At least one test file must be provided.\n";
  240. return EXIT_FAILURE;
  241. }
  242. const char* target = getenv("TEST_TARGET");
  243. CARBON_CHECK(target != nullptr);
  244. // Configure the name of the subset target.
  245. std::string subset_target_storage = target;
  246. static constexpr char SubsetSuffix[] = ".subset";
  247. if (!llvm::StringRef(subset_target_storage).ends_with(SubsetSuffix)) {
  248. subset_target_storage += SubsetSuffix;
  249. }
  250. Carbon::Testing::subset_target = &subset_target_storage;
  251. // Configure the base directory for test names.
  252. llvm::StringRef target_dir = target;
  253. std::error_code ec;
  254. std::filesystem::path working_dir = std::filesystem::current_path(ec);
  255. CARBON_CHECK(!ec) << ec.message();
  256. // Leaves one slash.
  257. CARBON_CHECK(target_dir.consume_front("/"));
  258. target_dir = target_dir.substr(0, target_dir.rfind(":"));
  259. std::string base_dir = working_dir.string() + target_dir.str() + "/";
  260. Carbon::Testing::base_dir_len = base_dir.size();
  261. // Register tests based on their absolute path.
  262. llvm::SmallVector<std::filesystem::path> paths;
  263. for (int i = 1; i < argc; ++i) {
  264. auto path = std::filesystem::absolute(argv[i], ec);
  265. CARBON_CHECK(!ec) << argv[i] << ": " << ec.message();
  266. CARBON_CHECK(llvm::StringRef(path.string()).starts_with(base_dir))
  267. << "\n " << path << "\n should start with\n " << base_dir;
  268. paths.push_back(path);
  269. }
  270. Carbon::Testing::RegisterFileTests(paths);
  271. return RUN_ALL_TESTS();
  272. }