file_test_base.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 <optional>
  8. #include <string>
  9. #include <utility>
  10. #include "absl/flags/flag.h"
  11. #include "absl/flags/parse.h"
  12. #include "common/check.h"
  13. #include "llvm/ADT/StringExtras.h"
  14. #include "llvm/ADT/Twine.h"
  15. #include "llvm/Support/FormatVariadic.h"
  16. #include "llvm/Support/InitLLVM.h"
  17. #include "llvm/Support/MemoryBuffer.h"
  18. #include "llvm/Support/PrettyStackTrace.h"
  19. ABSL_FLAG(std::vector<std::string>, file_tests, {},
  20. "A comma-separated list of repo-relative names of test files. "
  21. "Overrides test_targets_file.");
  22. ABSL_FLAG(std::string, test_targets_file, "",
  23. "A path to a file containing repo-relative names of test files.");
  24. ABSL_FLAG(bool, autoupdate, false,
  25. "Instead of verifying files match test output, autoupdate files "
  26. "based on test output.");
  27. namespace Carbon::Testing {
  28. using ::testing::Eq;
  29. using ::testing::Matcher;
  30. using ::testing::MatchesRegex;
  31. using ::testing::StrEq;
  32. // Reads a file to string.
  33. static auto ReadFile(std::string_view path) -> std::string {
  34. std::ifstream proto_file(path);
  35. std::stringstream buffer;
  36. buffer << proto_file.rdbuf();
  37. proto_file.close();
  38. return buffer.str();
  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* target = getenv("TEST_TARGET");
  54. CARBON_CHECK(target);
  55. // This advice overrides the --file_tests flag provided by the file_test rule.
  56. llvm::errs() << "\nTo test this file alone, run:\n bazel test " << target
  57. << " --test_arg=--file_tests=" << test_name_ << "\n\n";
  58. // Add a crash trace entry with a command that runs this test in isolation.
  59. llvm::PrettyStackTraceFormat stack_trace_entry(
  60. "bazel test %s --test_arg=--file_tests=%s", target, test_name_);
  61. TestContext context;
  62. auto run_result = ProcessTestFileAndRun(context);
  63. ASSERT_TRUE(run_result.ok()) << run_result.error();
  64. ValidateRun();
  65. auto test_filename = std::filesystem::path(test_name_.str()).filename();
  66. EXPECT_THAT(!llvm::StringRef(test_filename).starts_with("fail_"),
  67. Eq(context.exit_with_success))
  68. << "Tests should be prefixed with `fail_` if and only if running them "
  69. "is expected to fail.";
  70. // Check results.
  71. if (context.check_subset) {
  72. EXPECT_THAT(SplitOutput(context.stdout),
  73. IsSupersetOf(context.expected_stdout));
  74. EXPECT_THAT(SplitOutput(context.stderr),
  75. IsSupersetOf(context.expected_stderr));
  76. } else {
  77. EXPECT_THAT(SplitOutput(context.stdout),
  78. ElementsAreArray(context.expected_stdout));
  79. EXPECT_THAT(SplitOutput(context.stderr),
  80. ElementsAreArray(context.expected_stderr));
  81. }
  82. }
  83. auto FileTestBase::Autoupdate() -> ErrorOr<bool> {
  84. // Add a crash trace entry mentioning which file we're updating.
  85. llvm::PrettyStackTraceFormat stack_trace_entry("performing autoupdate for %s",
  86. test_name_);
  87. TestContext context;
  88. auto run_result = ProcessTestFileAndRun(context);
  89. if (!run_result.ok()) {
  90. return ErrorBuilder() << "Error updating " << test_name_ << ": "
  91. << run_result.error();
  92. }
  93. if (!context.autoupdate_line_number) {
  94. return false;
  95. }
  96. llvm::SmallVector<llvm::StringRef> filenames;
  97. filenames.reserve(context.non_check_lines.size());
  98. if (context.non_check_lines.size() > 1) {
  99. // There are splits, so we provide an empty name for the first file.
  100. filenames.push_back({});
  101. }
  102. for (const auto& file : context.test_files) {
  103. filenames.push_back(file.filename);
  104. }
  105. llvm::ArrayRef expected_filenames = filenames;
  106. if (filenames.size() > 1) {
  107. expected_filenames = expected_filenames.drop_front();
  108. }
  109. return AutoupdateFileTest(
  110. std::filesystem::absolute(test_name_.str()), context.input_content,
  111. filenames, *context.autoupdate_line_number, context.non_check_lines,
  112. context.stdout, context.stderr, GetDefaultFileRE(expected_filenames),
  113. GetLineNumberReplacements(expected_filenames),
  114. [&](std::string& line) { DoExtraCheckReplacements(line); });
  115. }
  116. auto FileTestBase::GetLineNumberReplacements(
  117. llvm::ArrayRef<llvm::StringRef> filenames)
  118. -> llvm::SmallVector<LineNumberReplacement> {
  119. return {{.has_file = true,
  120. .re = std::make_shared<RE2>(
  121. llvm::formatv(R"(({0}):(\d+))", llvm::join(filenames, "|"))),
  122. .line_formatv = R"({0})"}};
  123. }
  124. auto FileTestBase::ProcessTestFileAndRun(TestContext& context)
  125. -> ErrorOr<Success> {
  126. // Store the file so that test_files can use references to content.
  127. context.input_content = ReadFile(test_name_);
  128. // Load expected output.
  129. CARBON_RETURN_IF_ERROR(ProcessTestFile(context));
  130. // Process arguments.
  131. if (context.test_args.empty()) {
  132. context.test_args = GetDefaultArgs();
  133. }
  134. CARBON_RETURN_IF_ERROR(
  135. DoArgReplacements(context.test_args, context.test_files));
  136. // Create the files in-memory.
  137. llvm::vfs::InMemoryFileSystem fs;
  138. for (const auto& test_file : context.test_files) {
  139. if (!fs.addFile(test_file.filename, /*ModificationTime=*/0,
  140. llvm::MemoryBuffer::getMemBuffer(
  141. test_file.content, test_file.filename,
  142. /*RequiresNullTerminator=*/false))) {
  143. return ErrorBuilder() << "File is repeated: " << test_file.filename;
  144. }
  145. }
  146. // Convert the arguments to StringRef and const char* to match the
  147. // expectations of PrettyStackTraceProgram and Run.
  148. llvm::SmallVector<llvm::StringRef> test_args_ref;
  149. llvm::SmallVector<const char*> test_argv_for_stack_trace;
  150. test_args_ref.reserve(context.test_args.size());
  151. test_argv_for_stack_trace.reserve(context.test_args.size() + 1);
  152. for (const auto& arg : context.test_args) {
  153. test_args_ref.push_back(arg);
  154. test_argv_for_stack_trace.push_back(arg.c_str());
  155. }
  156. // Add a trailing null so that this is a proper argv.
  157. test_argv_for_stack_trace.push_back(nullptr);
  158. // Add a stack trace entry for the test invocation.
  159. llvm::PrettyStackTraceProgram stack_trace_entry(
  160. test_argv_for_stack_trace.size(), test_argv_for_stack_trace.data());
  161. // Capture trace streaming, but only when in debug mode.
  162. llvm::raw_svector_ostream stdout(context.stdout);
  163. llvm::raw_svector_ostream stderr(context.stderr);
  164. CARBON_ASSIGN_OR_RETURN(context.exit_with_success,
  165. Run(test_args_ref, fs, stdout, stderr));
  166. return Success();
  167. }
  168. auto FileTestBase::DoArgReplacements(
  169. llvm::SmallVector<std::string>& test_args,
  170. const llvm::SmallVector<TestFile>& test_files) -> ErrorOr<Success> {
  171. for (auto* it = test_args.begin(); it != test_args.end(); ++it) {
  172. auto percent = it->find("%");
  173. if (percent == std::string::npos) {
  174. continue;
  175. }
  176. if (percent + 1 >= it->size()) {
  177. return ErrorBuilder() << "% is not allowed on its own: " << *it;
  178. }
  179. char c = (*it)[percent + 1];
  180. switch (c) {
  181. case 's': {
  182. if (*it != "%s") {
  183. return ErrorBuilder() << "%s must be the full argument: " << *it;
  184. }
  185. it = test_args.erase(it);
  186. for (const auto& file : test_files) {
  187. it = test_args.insert(it, file.filename);
  188. ++it;
  189. }
  190. // Back up once because the for loop will advance.
  191. --it;
  192. break;
  193. }
  194. case 't': {
  195. char* tmpdir = getenv("TEST_TMPDIR");
  196. CARBON_CHECK(tmpdir != nullptr);
  197. it->replace(percent, 2, llvm::formatv("{0}/temp_file", tmpdir));
  198. break;
  199. }
  200. default:
  201. return ErrorBuilder() << "%" << c << " is not supported: " << *it;
  202. }
  203. }
  204. return Success();
  205. }
  206. auto FileTestBase::ProcessTestFile(TestContext& context) -> ErrorOr<Success> {
  207. // Original file content, and a cursor for walking through it.
  208. llvm::StringRef file_content = context.input_content;
  209. llvm::StringRef cursor = file_content;
  210. // Whether content has been found, only updated before a file split is found
  211. // (which may be never).
  212. bool found_content_pre_split = false;
  213. // Whether either AUTOUDPATE or NOAUTOUPDATE was found.
  214. bool found_autoupdate = false;
  215. // The index in the current test file. Will be reset on splits.
  216. int line_index = 0;
  217. // The current file name, considering splits. Not set for the default file.
  218. llvm::StringRef current_file_name;
  219. // The current file's start.
  220. const char* current_file_start = nullptr;
  221. context.non_check_lines.resize(1);
  222. while (!cursor.empty()) {
  223. auto [line, next_cursor] = cursor.split("\n");
  224. cursor = next_cursor;
  225. auto line_trimmed = line.ltrim();
  226. static constexpr llvm::StringLiteral SplitPrefix = "// ---";
  227. if (line_trimmed.consume_front(SplitPrefix)) {
  228. if (!found_autoupdate) {
  229. // If there's a split, all output is appended at the end of each file
  230. // before AUTOUPDATE. We may want to change that, but it's not necessary
  231. // to handle right now.
  232. return ErrorBuilder()
  233. << "AUTOUPDATE/NOAUTOUPDATE setting must be in the first file.";
  234. }
  235. context.non_check_lines.push_back({FileTestLine(0, line)});
  236. // On a file split, add the previous file, then start a new one.
  237. if (current_file_start) {
  238. context.test_files.push_back(TestFile(
  239. current_file_name.str(),
  240. llvm::StringRef(current_file_start, line_trimmed.begin() -
  241. current_file_start -
  242. SplitPrefix.size())));
  243. } else if (found_content_pre_split) {
  244. // For the first split, we make sure there was no content prior.
  245. return ErrorBuilder()
  246. << "When using split files, there must be no content before the "
  247. "first split file.";
  248. }
  249. current_file_name = line_trimmed.trim();
  250. current_file_start = cursor.begin();
  251. line_index = 0;
  252. continue;
  253. } else if (!current_file_start && !line_trimmed.starts_with("//") &&
  254. !line_trimmed.empty()) {
  255. found_content_pre_split = true;
  256. }
  257. ++line_index;
  258. // Process expectations when found.
  259. if (line_trimmed.consume_front("// CHECK")) {
  260. // Don't build expectations when doing an autoupdate. We don't want to
  261. // break the autoupdate on an invalid CHECK line.
  262. if (!absl::GetFlag(FLAGS_autoupdate)) {
  263. llvm::SmallVector<Matcher<std::string>>* expected = nullptr;
  264. if (line_trimmed.consume_front(":STDOUT:")) {
  265. expected = &context.expected_stdout;
  266. } else if (line_trimmed.consume_front(":STDERR:")) {
  267. expected = &context.expected_stderr;
  268. } else {
  269. return ErrorBuilder() << "Unexpected CHECK in input: " << line.str();
  270. }
  271. CARBON_ASSIGN_OR_RETURN(Matcher<std::string> check_matcher,
  272. TransformExpectation(line_index, line_trimmed));
  273. expected->push_back(check_matcher);
  274. }
  275. } else {
  276. context.non_check_lines.back().push_back(FileTestLine(line_index, line));
  277. if (line_trimmed.consume_front("// ARGS: ")) {
  278. if (context.test_args.empty()) {
  279. // Split the line into arguments.
  280. std::pair<llvm::StringRef, llvm::StringRef> cursor =
  281. llvm::getToken(line_trimmed);
  282. while (!cursor.first.empty()) {
  283. context.test_args.push_back(std::string(cursor.first));
  284. cursor = llvm::getToken(cursor.second);
  285. }
  286. } else {
  287. return ErrorBuilder()
  288. << "ARGS was specified multiple times: " << line.str();
  289. }
  290. } else if (line_trimmed == "// AUTOUPDATE" ||
  291. line_trimmed == "// NOAUTOUPDATE") {
  292. if (found_autoupdate) {
  293. return ErrorBuilder()
  294. << "Multiple AUTOUPDATE/NOAUTOUPDATE settings found";
  295. }
  296. found_autoupdate = true;
  297. if (line_trimmed == "// AUTOUPDATE") {
  298. context.autoupdate_line_number = line_index;
  299. }
  300. } else if (line_trimmed == "// SET-CHECK-SUBSET") {
  301. if (!context.check_subset) {
  302. context.check_subset = true;
  303. } else {
  304. return ErrorBuilder()
  305. << "SET-CHECK-SUBSET was specified multiple times";
  306. }
  307. }
  308. }
  309. }
  310. if (!found_autoupdate) {
  311. return ErrorBuilder() << "Missing AUTOUPDATE/NOAUTOUPDATE setting";
  312. }
  313. if (current_file_start) {
  314. context.test_files.push_back(
  315. TestFile(current_file_name.str(),
  316. llvm::StringRef(current_file_start,
  317. file_content.end() - current_file_start)));
  318. } else {
  319. // If no file splitting happened, use the main file as the test file.
  320. // There will always be a `/` unless tests are in the repo root.
  321. context.test_files.push_back(TestFile(
  322. test_name_.drop_front(test_name_.rfind("/") + 1).str(), file_content));
  323. }
  324. // Assume there is always a suffix `\n` in output.
  325. if (!context.expected_stdout.empty()) {
  326. context.expected_stdout.push_back(StrEq(""));
  327. }
  328. if (!context.expected_stderr.empty()) {
  329. context.expected_stderr.push_back(StrEq(""));
  330. }
  331. return Success();
  332. }
  333. auto FileTestBase::TransformExpectation(int line_index, llvm::StringRef in)
  334. -> ErrorOr<Matcher<std::string>> {
  335. if (in.empty()) {
  336. return Matcher<std::string>{StrEq("")};
  337. }
  338. if (in[0] != ' ') {
  339. return ErrorBuilder() << "Malformated CHECK line: " << in;
  340. }
  341. std::string str = in.substr(1).str();
  342. for (int pos = 0; pos < static_cast<int>(str.size());) {
  343. switch (str[pos]) {
  344. case '(':
  345. case ')':
  346. case ']':
  347. case '}':
  348. case '.':
  349. case '^':
  350. case '$':
  351. case '*':
  352. case '+':
  353. case '?':
  354. case '|':
  355. case '\\': {
  356. // Escape regex characters.
  357. str.insert(pos, "\\");
  358. pos += 2;
  359. break;
  360. }
  361. case '[': {
  362. llvm::StringRef line_keyword_cursor = llvm::StringRef(str).substr(pos);
  363. if (line_keyword_cursor.consume_front("[[")) {
  364. static constexpr llvm::StringLiteral LineKeyword = "@LINE";
  365. if (line_keyword_cursor.consume_front(LineKeyword)) {
  366. // Allow + or - here; consumeInteger handles -.
  367. line_keyword_cursor.consume_front("+");
  368. int offset;
  369. // consumeInteger returns true for errors, not false.
  370. if (line_keyword_cursor.consumeInteger(10, offset) ||
  371. !line_keyword_cursor.consume_front("]]")) {
  372. return ErrorBuilder()
  373. << "Unexpected @LINE offset at `"
  374. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  375. }
  376. std::string int_str = llvm::Twine(line_index + offset).str();
  377. int remove_len = (line_keyword_cursor.data() - str.data()) - pos;
  378. str.replace(pos, remove_len, int_str);
  379. pos += int_str.size();
  380. } else {
  381. return ErrorBuilder()
  382. << "Unexpected [[, should be {{\\[\\[}} at `"
  383. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  384. }
  385. } else {
  386. // Escape the `[`.
  387. str.insert(pos, "\\");
  388. pos += 2;
  389. }
  390. break;
  391. }
  392. case '{': {
  393. if (pos + 1 == static_cast<int>(str.size()) || str[pos + 1] != '{') {
  394. // Single `{`, escape it.
  395. str.insert(pos, "\\");
  396. pos += 2;
  397. } else {
  398. // Replace the `{{...}}` regex syntax with standard `(...)` syntax.
  399. str.replace(pos, 2, "(");
  400. for (++pos; pos < static_cast<int>(str.size() - 1); ++pos) {
  401. if (str[pos] == '}' && str[pos + 1] == '}') {
  402. str.replace(pos, 2, ")");
  403. ++pos;
  404. break;
  405. }
  406. }
  407. }
  408. break;
  409. }
  410. default: {
  411. ++pos;
  412. }
  413. }
  414. }
  415. return Matcher<std::string>{MatchesRegex(str)};
  416. }
  417. // Returns the tests to run.
  418. static auto GetTests() -> llvm::SmallVector<std::string> {
  419. // Prefer a user-specified list if present.
  420. auto specific_tests = absl::GetFlag(FLAGS_file_tests);
  421. if (!specific_tests.empty()) {
  422. return llvm::SmallVector<std::string>(specific_tests.begin(),
  423. specific_tests.end());
  424. }
  425. // Extracts tests from the target file.
  426. CARBON_CHECK(!absl::GetFlag(FLAGS_test_targets_file).empty())
  427. << "Missing --test_targets_file.";
  428. auto content = ReadFile(absl::GetFlag(FLAGS_test_targets_file));
  429. llvm::SmallVector<std::string> all_tests;
  430. for (llvm::StringRef file_ref : llvm::split(content, "\n")) {
  431. if (file_ref.empty()) {
  432. continue;
  433. }
  434. all_tests.push_back(file_ref.str());
  435. }
  436. return all_tests;
  437. }
  438. // Implements main() within the Carbon::Testing namespace for convenience.
  439. static auto Main(int argc, char** argv) -> int {
  440. absl::ParseCommandLine(argc, argv);
  441. testing::InitGoogleTest(&argc, argv);
  442. llvm::setBugReportMsg(
  443. "Please report issues to "
  444. "https://github.com/carbon-language/carbon-lang/issues and include the "
  445. "crash backtrace.\n");
  446. llvm::InitLLVM init_llvm(argc, argv);
  447. if (argc > 1) {
  448. llvm::errs() << "Unexpected arguments starting at: " << argv[1] << "\n";
  449. return EXIT_FAILURE;
  450. }
  451. llvm::SmallVector<std::string> tests = GetTests();
  452. auto test_factory = GetFileTestFactory();
  453. if (absl::GetFlag(FLAGS_autoupdate)) {
  454. for (const auto& test_name : tests) {
  455. std::unique_ptr<FileTestBase> test(test_factory.factory_fn(test_name));
  456. auto result = test->Autoupdate();
  457. llvm::errs() << (result.ok() ? (*result ? "!" : ".")
  458. : result.error().message());
  459. }
  460. llvm::errs() << "\nDone!\n";
  461. return EXIT_SUCCESS;
  462. } else {
  463. for (llvm::StringRef test_name : tests) {
  464. testing::RegisterTest(test_factory.name, test_name.data(), nullptr,
  465. test_name.data(), __FILE__, __LINE__,
  466. [&test_factory, test_name = test_name]() {
  467. return test_factory.factory_fn(test_name);
  468. });
  469. }
  470. return RUN_ALL_TESTS();
  471. }
  472. }
  473. } // namespace Carbon::Testing
  474. auto main(int argc, char** argv) -> int {
  475. return Carbon::Testing::Main(argc, argv);
  476. }