file_test_base.cpp 16 KB

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