file_test_base.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. const char* src_dir = getenv("TEST_SRCDIR");
  57. CARBON_CHECK(src_dir);
  58. std::string test_file = path().lexically_relative(
  59. std::filesystem::path(src_dir).append("carbon"));
  60. llvm::errs() << "\nTo test this file alone, run:\n bazel test "
  61. << *subset_target << " --test_arg=" << test_file << "\n\n";
  62. // Load expected output.
  63. std::vector<testing::Matcher<std::string>> expected_stdout;
  64. std::vector<testing::Matcher<std::string>> expected_stderr;
  65. std::ifstream file_content(path());
  66. int line_index = 0;
  67. std::string line_str;
  68. while (std::getline(file_content, line_str)) {
  69. ++line_index;
  70. llvm::StringRef line = line_str;
  71. line = line.ltrim();
  72. if (!line.consume_front("// CHECK")) {
  73. continue;
  74. }
  75. if (line.consume_front(":STDOUT:")) {
  76. expected_stdout.push_back(TransformExpectation(line_index, line));
  77. } else if (line.consume_front(":STDERR:")) {
  78. expected_stderr.push_back(TransformExpectation(line_index, line));
  79. } else {
  80. FAIL() << "Unexpected CHECK in input: " << line_str;
  81. }
  82. }
  83. // Assume there is always a suffix `\n` in output.
  84. if (!expected_stdout.empty()) {
  85. expected_stdout.push_back(testing::StrEq(""));
  86. }
  87. if (!expected_stderr.empty()) {
  88. expected_stderr.push_back(testing::StrEq(""));
  89. }
  90. // Capture trace streaming, but only when in debug mode.
  91. std::string stdout;
  92. std::string stderr;
  93. llvm::raw_string_ostream stdout_ostream(stdout);
  94. llvm::raw_string_ostream stderr_ostream(stderr);
  95. bool run_succeeded = RunOverFile(stdout_ostream, stderr_ostream);
  96. if (HasFailure()) {
  97. return;
  98. }
  99. EXPECT_THAT(!llvm::StringRef(path().filename()).starts_with("fail_"),
  100. Eq(run_succeeded))
  101. << "Tests should be prefixed with `fail_` if and only if running them "
  102. "is expected to fail.";
  103. // Check results.
  104. EXPECT_THAT(SplitOutput(stdout), ElementsAreArray(expected_stdout));
  105. EXPECT_THAT(SplitOutput(stderr), ElementsAreArray(expected_stderr));
  106. }
  107. auto FileTestBase::TransformExpectation(int line_index, llvm::StringRef in)
  108. -> testing::Matcher<std::string> {
  109. if (in.empty()) {
  110. return testing::StrEq("");
  111. }
  112. CARBON_CHECK(in[0] == ' ') << "Malformated input: " << in;
  113. std::string str = in.substr(1).str();
  114. for (int pos = 0; pos < static_cast<int>(str.size());) {
  115. switch (str[pos]) {
  116. case '(':
  117. case ')':
  118. case ']':
  119. case '}':
  120. case '.':
  121. case '^':
  122. case '$':
  123. case '*':
  124. case '+':
  125. case '?':
  126. case '|':
  127. case '\\': {
  128. // Escape regex characters.
  129. str.insert(pos, "\\");
  130. pos += 2;
  131. break;
  132. }
  133. case '[': {
  134. llvm::StringRef line_keyword_cursor = llvm::StringRef(str).substr(pos);
  135. if (line_keyword_cursor.consume_front("[[")) {
  136. static constexpr llvm::StringLiteral LineKeyword = "@LINE";
  137. if (line_keyword_cursor.consume_front(LineKeyword)) {
  138. // Allow + or - here; consumeInteger handles -.
  139. line_keyword_cursor.consume_front("+");
  140. int offset;
  141. // consumeInteger returns true for errors, not false.
  142. CARBON_CHECK(!line_keyword_cursor.consumeInteger(10, offset) &&
  143. line_keyword_cursor.consume_front("]]"))
  144. << "Unexpected @LINE offset at `"
  145. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  146. std::string int_str = llvm::Twine(line_index + offset).str();
  147. int remove_len = (line_keyword_cursor.data() - str.data()) - pos;
  148. str.replace(pos, remove_len, int_str);
  149. pos += int_str.size();
  150. } else {
  151. CARBON_FATAL() << "Unexpected [[, should be {{\\[\\[}} at `"
  152. << line_keyword_cursor.substr(0, 5)
  153. << "` in: " << in;
  154. }
  155. } else {
  156. // Escape the `[`.
  157. str.insert(pos, "\\");
  158. pos += 2;
  159. }
  160. break;
  161. }
  162. case '{': {
  163. if (pos + 1 == static_cast<int>(str.size()) || str[pos + 1] != '{') {
  164. // Single `{`, escape it.
  165. str.insert(pos, "\\");
  166. pos += 2;
  167. } else {
  168. // Replace the `{{...}}` regex syntax with standard `(...)` syntax.
  169. str.replace(pos, 2, "(");
  170. for (++pos; pos < static_cast<int>(str.size() - 1); ++pos) {
  171. if (str[pos] == '}' && str[pos + 1] == '}') {
  172. str.replace(pos, 2, ")");
  173. ++pos;
  174. break;
  175. }
  176. }
  177. }
  178. break;
  179. }
  180. default: {
  181. ++pos;
  182. }
  183. }
  184. }
  185. return testing::MatchesRegex(str);
  186. }
  187. } // namespace Carbon::Testing
  188. auto main(int argc, char** argv) -> int {
  189. testing::InitGoogleTest(&argc, argv);
  190. llvm::setBugReportMsg(
  191. "Please report issues to "
  192. "https://github.com/carbon-language/carbon-lang/issues and include the "
  193. "crash backtrace.\n");
  194. llvm::InitLLVM init_llvm(argc, argv);
  195. if (argc < 2) {
  196. llvm::errs() << "At least one test file must be provided.\n";
  197. return EXIT_FAILURE;
  198. }
  199. const char* target = getenv("TEST_TARGET");
  200. CARBON_CHECK(target != nullptr);
  201. // Configure the name of the subset target.
  202. std::string subset_target_storage = target;
  203. static constexpr char SubsetSuffix[] = ".subset";
  204. if (!llvm::StringRef(subset_target_storage).ends_with(SubsetSuffix)) {
  205. subset_target_storage += SubsetSuffix;
  206. }
  207. Carbon::Testing::subset_target = &subset_target_storage;
  208. // Save the working directory for later restoration.
  209. std::error_code ec;
  210. std::filesystem::path orig_working_dir_storage =
  211. std::filesystem::current_path(ec);
  212. CARBON_CHECK(!ec) << ec.message();
  213. Carbon::Testing::orig_working_dir = &orig_working_dir_storage;
  214. // Configure the base directory for test names.
  215. llvm::StringRef target_dir = target;
  216. // Leaves one slash.
  217. CARBON_CHECK(target_dir.consume_front("/"));
  218. target_dir = target_dir.substr(0, target_dir.rfind(":"));
  219. std::string base_dir =
  220. orig_working_dir_storage.string() + target_dir.str() + "/";
  221. Carbon::Testing::base_dir_len = base_dir.size();
  222. // Register tests based on their absolute path.
  223. std::vector<std::filesystem::path> paths;
  224. for (int i = 1; i < argc; ++i) {
  225. auto path = std::filesystem::absolute(argv[i], ec);
  226. CARBON_CHECK(!ec) << argv[i] << ": " << ec.message();
  227. CARBON_CHECK(llvm::StringRef(path.string()).starts_with(base_dir))
  228. << "\n " << path << "\n should start with\n " << base_dir;
  229. paths.push_back(path);
  230. }
  231. Carbon::Testing::RegisterFileTests(paths);
  232. return RUN_ALL_TESTS();
  233. }