file_test_base.cpp 11 KB

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