file_test_base.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. // The original working directory for restoration after each test.
  16. static std::filesystem::path* orig_working_dir = nullptr;
  17. using ::testing::Eq;
  18. FileTestBase::FileTestBase(const std::filesystem::path& path) : path_(&path) {
  19. // Run from the file's parent directory.
  20. std::error_code ec;
  21. std::filesystem::current_path(path.parent_path(), ec);
  22. CARBON_CHECK(!ec) << ec.message();
  23. }
  24. FileTestBase::~FileTestBase() {
  25. // Restore the original working directory.
  26. std::error_code ec;
  27. std::filesystem::current_path(*orig_working_dir, ec);
  28. CARBON_CHECK(!ec) << ec.message();
  29. }
  30. void FileTestBase::RegisterTests(
  31. const char* fixture_label, const std::vector<std::filesystem::path>& paths,
  32. std::function<FileTestBase*(const std::filesystem::path&)> factory) {
  33. // Use RegisterTest instead of INSTANTIATE_TEST_CASE_P because of ordering
  34. // issues between container initialization and test instantiation by
  35. // InitGoogleTest.
  36. for (const auto& path : paths) {
  37. std::string test_name = path.string().substr(base_dir_len);
  38. testing::RegisterTest(fixture_label, test_name.c_str(), nullptr,
  39. test_name.c_str(), __FILE__, __LINE__,
  40. [=]() { return factory(path); });
  41. }
  42. }
  43. // Splits outputs to string_view because gtest handles string_view by default.
  44. static auto SplitOutput(llvm::StringRef output)
  45. -> std::vector<std::string_view> {
  46. if (output.empty()) {
  47. return {};
  48. }
  49. llvm::SmallVector<llvm::StringRef> lines;
  50. llvm::StringRef(output).split(lines, "\n");
  51. return std::vector<std::string_view>(lines.begin(), lines.end());
  52. }
  53. // Runs a test and compares output. This keeps output split by line so that
  54. // issues are a little easier to identify by the different line.
  55. auto FileTestBase::TestBody() -> void {
  56. llvm::errs() << "\nTo test this file alone, run:\n bazel test "
  57. << *subset_target << " --test_arg=" << path() << "\n\n";
  58. // Load expected output.
  59. std::vector<testing::Matcher<std::string>> expected_stdout;
  60. std::vector<testing::Matcher<std::string>> expected_stderr;
  61. std::ifstream file_content(path());
  62. int line_index = 0;
  63. std::string line_str;
  64. while (std::getline(file_content, line_str)) {
  65. ++line_index;
  66. llvm::StringRef line = line_str;
  67. line = line.ltrim();
  68. if (!line.consume_front("// CHECK")) {
  69. continue;
  70. }
  71. if (line.consume_front(":STDOUT:")) {
  72. expected_stdout.push_back(TransformExpectation(line_index, line));
  73. } else if (line.consume_front(":STDERR:")) {
  74. expected_stderr.push_back(TransformExpectation(line_index, line));
  75. } else {
  76. FAIL() << "Unexpected CHECK in input: " << line_str;
  77. }
  78. }
  79. // Assume there is always a suffix `\n` in output.
  80. if (!expected_stdout.empty()) {
  81. expected_stdout.push_back(testing::StrEq(""));
  82. }
  83. if (!expected_stderr.empty()) {
  84. expected_stderr.push_back(testing::StrEq(""));
  85. }
  86. // Capture trace streaming, but only when in debug mode.
  87. std::string stdout;
  88. std::string stderr;
  89. llvm::raw_string_ostream stdout_ostream(stdout);
  90. llvm::raw_string_ostream stderr_ostream(stderr);
  91. bool run_succeeded = RunOverFile(stdout_ostream, stderr_ostream);
  92. if (HasFailure()) {
  93. return;
  94. }
  95. EXPECT_THAT(!llvm::StringRef(path().filename()).starts_with("fail_"),
  96. Eq(run_succeeded))
  97. << "Tests should be prefixed with `fail_` if and only if running them "
  98. "is expected to fail.";
  99. // Check results.
  100. EXPECT_THAT(SplitOutput(stdout), ElementsAreArray(expected_stdout));
  101. EXPECT_THAT(SplitOutput(stderr), ElementsAreArray(expected_stderr));
  102. }
  103. auto FileTestBase::TransformExpectation(int line_index, llvm::StringRef in)
  104. -> testing::Matcher<std::string> {
  105. if (in.empty()) {
  106. return testing::StrEq("");
  107. }
  108. CARBON_CHECK(in[0] == ' ') << "Malformated input: " << in;
  109. std::string str = in.substr(1).str();
  110. for (int pos = 0; pos < static_cast<int>(str.size());) {
  111. switch (str[pos]) {
  112. case '(':
  113. case ')':
  114. case ']':
  115. case '}':
  116. case '.':
  117. case '^':
  118. case '$':
  119. case '*':
  120. case '+':
  121. case '?':
  122. case '|':
  123. case '\\': {
  124. // Escape regex characters.
  125. str.insert(pos, "\\");
  126. pos += 2;
  127. break;
  128. }
  129. case '[': {
  130. llvm::StringRef line_keyword_cursor = llvm::StringRef(str).substr(pos);
  131. if (line_keyword_cursor.consume_front("[[")) {
  132. static constexpr llvm::StringLiteral LineKeyword = "@LINE";
  133. if (line_keyword_cursor.consume_front(LineKeyword)) {
  134. // Allow + or - here; consumeInteger handles -.
  135. line_keyword_cursor.consume_front("+");
  136. int offset;
  137. // consumeInteger returns true for errors, not false.
  138. CARBON_CHECK(!line_keyword_cursor.consumeInteger(10, offset) &&
  139. line_keyword_cursor.consume_front("]]"))
  140. << "Unexpected @LINE offset at `"
  141. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  142. std::string int_str = llvm::Twine(line_index + offset).str();
  143. int remove_len = (line_keyword_cursor.data() - str.data()) - pos;
  144. str.replace(pos, remove_len, int_str);
  145. pos += int_str.size();
  146. } else {
  147. CARBON_FATAL() << "Unexpected [[, should be {{\\[\\[}} at `"
  148. << line_keyword_cursor.substr(0, 5)
  149. << "` in: " << in;
  150. }
  151. } else {
  152. // Escape the `[`.
  153. str.insert(pos, "\\");
  154. pos += 2;
  155. }
  156. break;
  157. }
  158. case '{': {
  159. if (pos + 1 == static_cast<int>(str.size()) || str[pos + 1] != '{') {
  160. // Single `{`, escape it.
  161. str.insert(pos, "\\");
  162. pos += 2;
  163. } else {
  164. // Replace the `{{...}}` regex syntax with standard `(...)` syntax.
  165. str.replace(pos, 2, "(");
  166. for (++pos; pos < static_cast<int>(str.size() - 1); ++pos) {
  167. if (str[pos] == '}' && str[pos + 1] == '}') {
  168. str.replace(pos, 2, ")");
  169. ++pos;
  170. break;
  171. }
  172. }
  173. }
  174. break;
  175. }
  176. default: {
  177. ++pos;
  178. }
  179. }
  180. }
  181. return testing::MatchesRegex(str);
  182. }
  183. } // namespace Carbon::Testing
  184. auto main(int argc, char** argv) -> int {
  185. testing::InitGoogleTest(&argc, argv);
  186. llvm::setBugReportMsg(
  187. "Please report issues to "
  188. "https://github.com/carbon-language/carbon-lang/issues and include the "
  189. "crash backtrace.\n");
  190. llvm::InitLLVM init_llvm(argc, argv);
  191. if (argc < 2) {
  192. llvm::errs() << "At least one test file must be provided.\n";
  193. return EXIT_FAILURE;
  194. }
  195. const char* target = getenv("TEST_TARGET");
  196. CARBON_CHECK(target != nullptr);
  197. // Configure the name of the subset target.
  198. std::string subset_target_storage = target;
  199. static constexpr char SubsetSuffix[] = ".subset";
  200. if (!llvm::StringRef(subset_target_storage).ends_with(SubsetSuffix)) {
  201. subset_target_storage += SubsetSuffix;
  202. }
  203. Carbon::Testing::subset_target = &subset_target_storage;
  204. // Save the working directory for later restoration.
  205. std::error_code ec;
  206. std::filesystem::path orig_working_dir_storage =
  207. std::filesystem::current_path(ec);
  208. CARBON_CHECK(!ec) << ec.message();
  209. Carbon::Testing::orig_working_dir = &orig_working_dir_storage;
  210. // Configure the base directory for test names.
  211. llvm::StringRef target_dir = target;
  212. // Leaves one slash.
  213. CARBON_CHECK(target_dir.consume_front("/"));
  214. target_dir = target_dir.substr(0, target_dir.rfind(":"));
  215. std::string base_dir =
  216. orig_working_dir_storage.string() + target_dir.str() + "/";
  217. Carbon::Testing::base_dir_len = base_dir.size();
  218. // Register tests based on their absolute path.
  219. std::vector<std::filesystem::path> paths;
  220. for (int i = 1; i < argc; ++i) {
  221. auto path = std::filesystem::absolute(argv[i], ec);
  222. CARBON_CHECK(!ec) << argv[i] << ": " << ec.message();
  223. CARBON_CHECK(llvm::StringRef(path.string()).starts_with(base_dir))
  224. << "\n " << path << "\n should start with\n " << base_dir;
  225. paths.push_back(path);
  226. }
  227. Carbon::Testing::RegisterFileTests(paths);
  228. return RUN_ALL_TESTS();
  229. }