file_test_base.cpp 17 KB

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