file_test_base.cpp 17 KB

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