file_test_base.cpp 10 KB

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