file_test_base.cpp 18 KB

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