file_test_base.cpp 7.0 KB

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