file_test_base.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. // Implementation-wise, this:
  5. //
  6. // - Uses the registered `FileTestFactory` to construct `FileTestBase`
  7. // instances.
  8. // - Constructs a `FileTestCase` that wraps each `FileTestBase` instance to
  9. // register with googletest, and to provide the actual `TestBody`.
  10. // - Using `FileTestEventListener`, runs tests in parallel prior to normal
  11. // googletest execution.
  12. // - This is required to support `--gtest_filter` and access `should_run`.
  13. // - Runs each `FileTestBase` instance to cache the `TestFile` on
  14. // `FileTestInfo`.
  15. // - Determines whether autoupdate would make changes, autoupdating if
  16. // requested.
  17. // - When googletest would normally execute the test, `FileTestCase::TestBody`
  18. // instead uses the cached state on `FileTestInfo`.
  19. // - This only occurs when neither autoupdating nor dumping output.
  20. #include "testing/file_test/file_test_base.h"
  21. #include <filesystem>
  22. #include <optional>
  23. #include <string>
  24. #include <utility>
  25. #include "absl/flags/flag.h"
  26. #include "absl/flags/parse.h"
  27. #include "absl/strings/str_join.h"
  28. #include "absl/strings/str_split.h"
  29. #include "common/check.h"
  30. #include "common/error.h"
  31. #include "common/exe_path.h"
  32. #include "common/init_llvm.h"
  33. #include "common/raw_string_ostream.h"
  34. #include "llvm/ADT/StringExtras.h"
  35. #include "llvm/Support/CrashRecoveryContext.h"
  36. #include "llvm/Support/FormatVariadic.h"
  37. #include "llvm/Support/MemoryBuffer.h"
  38. #include "llvm/Support/PrettyStackTrace.h"
  39. #include "llvm/Support/Process.h"
  40. #include "llvm/Support/ThreadPool.h"
  41. #include "testing/base/file_helpers.h"
  42. #include "testing/file_test/autoupdate.h"
  43. #include "testing/file_test/run_test.h"
  44. #include "testing/file_test/test_file.h"
  45. ABSL_FLAG(std::vector<std::string>, file_tests, {},
  46. "A comma-separated list of repo-relative names of test files. "
  47. "Similar to and overrides `--gtest_filter`, but doesn't require the "
  48. "test class name to be known.");
  49. ABSL_FLAG(bool, autoupdate, false,
  50. "Instead of verifying files match test output, autoupdate files "
  51. "based on test output.");
  52. ABSL_FLAG(unsigned int, threads, 0,
  53. "Number of threads to use when autoupdating tests, or 0 to "
  54. "automatically determine a thread count.");
  55. ABSL_FLAG(bool, dump_output, false,
  56. "Instead of verifying files match test output, directly dump output "
  57. "to stderr.");
  58. namespace Carbon::Testing {
  59. // Information for a test case.
  60. struct FileTestInfo {
  61. // The name.
  62. std::string test_name;
  63. // A factory function for creating the test object.
  64. std::function<auto()->FileTestBase*> factory_fn;
  65. // gtest's information about the test.
  66. ::testing::TestInfo* registered_test;
  67. // The test result, set after running.
  68. std::optional<ErrorOr<TestFile>> test_result;
  69. // Whether running autoupdate would change (or when autoupdating, already
  70. // changed) the test file. This may be true even if output passes test
  71. // expectations.
  72. bool autoupdate_differs = false;
  73. };
  74. // Adapts a `FileTestBase` instance to gtest for outputting results.
  75. class FileTestCase : public testing::Test {
  76. public:
  77. explicit FileTestCase(FileTestInfo* test_info) : test_info_(test_info) {}
  78. // Runs a test and compares output. This keeps output split by line so that
  79. // issues are a little easier to identify by the different line.
  80. auto TestBody() -> void final;
  81. private:
  82. FileTestInfo* test_info_;
  83. };
  84. // Splits outputs to string_view because gtest handles string_view by default.
  85. static auto SplitOutput(llvm::StringRef output)
  86. -> llvm::SmallVector<std::string_view> {
  87. if (output.empty()) {
  88. return {};
  89. }
  90. llvm::SmallVector<llvm::StringRef> lines;
  91. llvm::StringRef(output).split(lines, "\n");
  92. return llvm::SmallVector<std::string_view>(lines.begin(), lines.end());
  93. }
  94. // Verify that the success and `fail_` prefix use correspond. Separately handle
  95. // both cases for clearer test failures.
  96. static auto CompareFailPrefix(llvm::StringRef filename, bool success) -> void {
  97. if (success) {
  98. EXPECT_FALSE(filename.starts_with("fail_"))
  99. << "`" << filename
  100. << "` succeeded; if success is expected, remove the `fail_` "
  101. "prefix.";
  102. } else {
  103. EXPECT_TRUE(filename.starts_with("fail_"))
  104. << "`" << filename
  105. << "` failed; if failure is expected, add the `fail_` prefix.";
  106. }
  107. }
  108. // Modes for GetBazelCommand.
  109. enum class BazelMode : uint8_t {
  110. Autoupdate,
  111. Dump,
  112. Test,
  113. };
  114. // Returns the requested bazel command string for the given execution mode.
  115. static auto GetBazelCommand(BazelMode mode, llvm::StringRef test_name)
  116. -> std::string {
  117. RawStringOstream args;
  118. const char* target = getenv("TEST_TARGET");
  119. args << "bazel " << ((mode == BazelMode::Test) ? "test" : "run") << " "
  120. << (target ? target : "<target>") << " ";
  121. switch (mode) {
  122. case BazelMode::Autoupdate:
  123. args << "-- --autoupdate ";
  124. break;
  125. case BazelMode::Dump:
  126. args << "-- --dump_output ";
  127. break;
  128. case BazelMode::Test:
  129. args << "--test_arg=";
  130. break;
  131. }
  132. args << "--file_tests=";
  133. args << test_name;
  134. return args.TakeStr();
  135. }
  136. // Runs the FileTestAutoupdater, returning the result.
  137. static auto RunAutoupdater(FileTestBase* test_base, const TestFile& test_file,
  138. bool dry_run) -> bool {
  139. if (!test_file.autoupdate_line_number) {
  140. return false;
  141. }
  142. llvm::SmallVector<llvm::StringRef> filenames;
  143. filenames.reserve(test_file.non_check_lines.size());
  144. if (test_file.has_splits) {
  145. // There are splits, so we provide an empty name for the first file.
  146. filenames.push_back({});
  147. }
  148. for (const auto& file : test_file.file_splits) {
  149. filenames.push_back(file.filename);
  150. }
  151. llvm::ArrayRef expected_filenames = filenames;
  152. if (filenames.size() > 1) {
  153. expected_filenames = expected_filenames.drop_front();
  154. }
  155. return FileTestAutoupdater(
  156. std::filesystem::absolute(test_base->test_name().str()),
  157. GetBazelCommand(BazelMode::Test, test_base->test_name()),
  158. GetBazelCommand(BazelMode::Dump, test_base->test_name()),
  159. test_file.input_content, filenames,
  160. *test_file.autoupdate_line_number, test_file.autoupdate_split,
  161. test_file.non_check_lines, test_file.actual_stdout,
  162. test_file.actual_stderr,
  163. test_base->GetDefaultFileRE(expected_filenames),
  164. test_base->GetLineNumberReplacements(expected_filenames),
  165. [&](std::string& line) {
  166. test_base->DoExtraCheckReplacements(line);
  167. })
  168. .Run(dry_run);
  169. }
  170. auto FileTestCase::TestBody() -> void {
  171. if (absl::GetFlag(FLAGS_autoupdate) || absl::GetFlag(FLAGS_dump_output)) {
  172. return;
  173. }
  174. CARBON_CHECK(test_info_->test_result,
  175. "Expected test to be run prior to TestBody: {0}",
  176. test_info_->test_name);
  177. ASSERT_TRUE(test_info_->test_result->ok())
  178. << test_info_->test_result->error();
  179. auto test_filename = std::filesystem::path(test_info_->test_name).filename();
  180. // Check success/failure against `fail_` prefixes.
  181. TestFile& test_file = **(test_info_->test_result);
  182. if (test_file.run_result.per_file_success.empty()) {
  183. CompareFailPrefix(test_filename.string(), test_file.run_result.success);
  184. } else {
  185. bool require_overall_failure = false;
  186. for (const auto& [filename, success] :
  187. test_file.run_result.per_file_success) {
  188. CompareFailPrefix(filename, success);
  189. if (!success) {
  190. require_overall_failure = true;
  191. }
  192. }
  193. if (require_overall_failure) {
  194. EXPECT_FALSE(test_file.run_result.success)
  195. << "There is a per-file failure expectation, so the overall result "
  196. "should have been a failure.";
  197. } else {
  198. // Individual files all succeeded, so the prefix is enforced on the main
  199. // test file.
  200. CompareFailPrefix(test_filename.string(), test_file.run_result.success);
  201. }
  202. }
  203. // Check results. Include a reminder for NOAUTOUPDATE tests.
  204. std::unique_ptr<testing::ScopedTrace> scoped_trace;
  205. if (!test_file.autoupdate_line_number) {
  206. scoped_trace = std::make_unique<testing::ScopedTrace>(
  207. __FILE__, __LINE__,
  208. "This file is NOAUTOUPDATE, so expected differences require manual "
  209. "updates.");
  210. }
  211. if (test_file.check_subset) {
  212. EXPECT_THAT(SplitOutput(test_file.actual_stdout),
  213. IsSupersetOf(test_file.expected_stdout));
  214. EXPECT_THAT(SplitOutput(test_file.actual_stderr),
  215. IsSupersetOf(test_file.expected_stderr));
  216. } else {
  217. EXPECT_THAT(SplitOutput(test_file.actual_stdout),
  218. ElementsAreArray(test_file.expected_stdout));
  219. EXPECT_THAT(SplitOutput(test_file.actual_stderr),
  220. ElementsAreArray(test_file.expected_stderr));
  221. }
  222. if (HasFailure()) {
  223. llvm::errs() << "\nTo test this file alone, run:\n "
  224. << GetBazelCommand(BazelMode::Test, test_info_->test_name)
  225. << "\n\n";
  226. if (test_file.autoupdate_line_number) {
  227. llvm::errs() << "\nThis test is NOAUTOUPDATE.\n\n";
  228. }
  229. }
  230. if (test_info_->autoupdate_differs) {
  231. ADD_FAILURE() << "Autoupdate would make changes to the file content. Run:\n"
  232. << GetBazelCommand(BazelMode::Autoupdate,
  233. test_info_->test_name);
  234. }
  235. }
  236. auto FileTestBase::GetLineNumberReplacements(
  237. llvm::ArrayRef<llvm::StringRef> filenames)
  238. -> llvm::SmallVector<LineNumberReplacement> {
  239. return {{.has_file = true,
  240. .re = std::make_shared<RE2>(
  241. llvm::formatv(R"(({0}):(\d+)?)", llvm::join(filenames, "|"))),
  242. .line_formatv = R"({0})"}};
  243. }
  244. // If `--file_tests` is set, transform it into a `--gtest_filter`.
  245. static auto MaybeApplyFileTestsFlag(llvm::StringRef factory_name) -> void {
  246. if (absl::GetFlag(FLAGS_file_tests).empty()) {
  247. return;
  248. }
  249. RawStringOstream filter;
  250. llvm::ListSeparator sep(":");
  251. for (const auto& file : absl::GetFlag(FLAGS_file_tests)) {
  252. filter << sep << factory_name << "." << file;
  253. }
  254. absl::SetFlag(&FLAGS_gtest_filter, filter.TakeStr());
  255. }
  256. // Loads tests from the manifest file, and registers them for execution. The
  257. // vector is taken as an output parameter so that the address of entries is
  258. // stable for the factory.
  259. static auto RegisterTests(FileTestFactory* test_factory,
  260. llvm::StringRef exe_path,
  261. llvm::SmallVectorImpl<FileTestInfo>& tests)
  262. -> ErrorOr<Success> {
  263. GetFileTestManifestPath();
  264. CARBON_ASSIGN_OR_RETURN(auto test_manifest,
  265. ReadFile(GetFileTestManifestPath()));
  266. // Prepare the vector first, so that the location of entries won't change.
  267. for (const auto& test_name :
  268. absl::StrSplit(test_manifest, "\n", absl::SkipEmpty())) {
  269. tests.push_back({.test_name = std::string(test_name)});
  270. }
  271. // Amend entries with factory functions.
  272. for (auto& test : tests) {
  273. llvm::StringRef test_name = test.test_name;
  274. test.factory_fn = [test_factory, exe_path, test_name]() {
  275. return test_factory->factory_fn(exe_path, test_name);
  276. };
  277. test.registered_test = testing::RegisterTest(
  278. test_factory->name, test_name.data(), nullptr, test_name.data(),
  279. __FILE__, __LINE__, [&test]() { return new FileTestCase(&test); });
  280. }
  281. return Success();
  282. }
  283. // Implements the parallel test execution through gtest's listener support.
  284. class FileTestEventListener : public testing::EmptyTestEventListener {
  285. public:
  286. explicit FileTestEventListener(llvm::MutableArrayRef<FileTestInfo> tests)
  287. : tests_(tests) {}
  288. // Runs test during start, after `should_run` is initialized. This is
  289. // multi-threaded to get extra speed.
  290. auto OnTestProgramStart(const testing::UnitTest& /*unit_test*/)
  291. -> void override;
  292. private:
  293. llvm::MutableArrayRef<FileTestInfo> tests_;
  294. };
  295. auto FileTestEventListener::OnTestProgramStart(
  296. const testing::UnitTest& /*unit_test*/) -> void {
  297. llvm::CrashRecoveryContext::Enable();
  298. llvm::DefaultThreadPool pool(
  299. {.ThreadsRequested = absl::GetFlag(FLAGS_dump_output)
  300. ? 1
  301. : absl::GetFlag(FLAGS_threads)});
  302. if (!absl::GetFlag(FLAGS_dump_output)) {
  303. llvm::errs() << "Running tests with " << pool.getMaxConcurrency()
  304. << " thread(s)\n";
  305. }
  306. // Guard access to both `llvm::errs` and `crashed`.
  307. bool crashed = false;
  308. std::mutex output_mutex;
  309. for (auto& test : tests_) {
  310. if (!test.registered_test->should_run()) {
  311. continue;
  312. }
  313. pool.async([&output_mutex, &crashed, &test] {
  314. // If any thread crashed, don't try running more.
  315. {
  316. std::unique_lock<std::mutex> lock(output_mutex);
  317. if (crashed) {
  318. return;
  319. }
  320. }
  321. // Use a crash recovery context to try to get a stack trace when
  322. // multiple threads may crash in parallel, which otherwise leads to the
  323. // program aborting without printing a stack trace.
  324. llvm::CrashRecoveryContext crc;
  325. crc.DumpStackAndCleanupOnFailure = true;
  326. bool thread_crashed = !crc.RunSafely([&] {
  327. std::unique_ptr<FileTestBase> test_instance(test.factory_fn());
  328. // Add a crash trace entry with the single-file test command.
  329. std::string test_command =
  330. GetBazelCommand(BazelMode::Test, test.test_name);
  331. llvm::PrettyStackTraceString stack_trace_entry(test_command.c_str());
  332. if (absl::GetFlag(FLAGS_dump_output)) {
  333. std::unique_lock<std::mutex> lock(output_mutex);
  334. llvm::errs() << "\n--- Dumping: " << test.test_name << "\n\n";
  335. }
  336. test.test_result = ProcessTestFileAndRun(
  337. test_instance.get(), &output_mutex,
  338. absl::GetFlag(FLAGS_dump_output), absl::GetFlag(FLAGS_autoupdate));
  339. if (!test.test_result->ok()) {
  340. std::unique_lock<std::mutex> lock(output_mutex);
  341. llvm::errs() << "\n" << test.test_result->error().message() << "\n";
  342. return;
  343. }
  344. test.autoupdate_differs =
  345. RunAutoupdater(test_instance.get(), **test.test_result,
  346. /*dry_run=*/!absl::GetFlag(FLAGS_autoupdate));
  347. std::unique_lock<std::mutex> lock(output_mutex);
  348. if (absl::GetFlag(FLAGS_dump_output)) {
  349. llvm::outs().flush();
  350. const TestFile& test_file = **test.test_result;
  351. llvm::errs() << "\n--- Exit with success: "
  352. << (test_file.run_result.success ? "true" : "false")
  353. << "\n--- Autoupdate differs: "
  354. << (test.autoupdate_differs ? "true" : "false") << "\n";
  355. } else {
  356. llvm::errs() << (test.autoupdate_differs ? "!" : ".");
  357. }
  358. });
  359. if (thread_crashed) {
  360. std::unique_lock<std::mutex> lock(output_mutex);
  361. crashed = true;
  362. }
  363. });
  364. }
  365. pool.wait();
  366. if (crashed) {
  367. // Abort rather than returning so that we don't get a LeakSanitizer report.
  368. // We expect to have leaked memory if one or more of our tests crashed.
  369. std::abort();
  370. }
  371. llvm::errs() << "\nDone!\n";
  372. }
  373. // Implements main() within the Carbon::Testing namespace for convenience.
  374. static auto Main(int argc, char** argv) -> ErrorOr<int> {
  375. Carbon::InitLLVM init_llvm(argc, argv);
  376. testing::InitGoogleTest(&argc, argv);
  377. auto args = absl::ParseCommandLine(argc, argv);
  378. if (args.size() > 1) {
  379. ErrorBuilder b;
  380. b << "Unexpected arguments:";
  381. for (char* arg : llvm::ArrayRef(args).drop_front()) {
  382. b << " " << FormatEscaped(arg);
  383. }
  384. return b;
  385. }
  386. std::string exe_path = FindExecutablePath(argv[0]);
  387. // Tests might try to read from stdin. Ensure those reads fail by closing
  388. // stdin and reopening it as /dev/null. Note that STDIN_FILENO doesn't exist
  389. // on Windows, but POSIX requires it to be 0.
  390. if (std::error_code error =
  391. llvm::sys::Process::SafelyCloseFileDescriptor(0)) {
  392. return Error("Unable to close standard input: " + error.message());
  393. }
  394. if (std::error_code error =
  395. llvm::sys::Process::FixupStandardFileDescriptors()) {
  396. return Error("Unable to correct standard file descriptors: " +
  397. error.message());
  398. }
  399. if (absl::GetFlag(FLAGS_autoupdate) && absl::GetFlag(FLAGS_dump_output)) {
  400. return Error("--autoupdate and --dump_output are mutually exclusive.");
  401. }
  402. auto test_factory = GetFileTestFactory();
  403. MaybeApplyFileTestsFlag(test_factory.name);
  404. // Inline 0 entries because it will always be too large to store on the stack.
  405. llvm::SmallVector<FileTestInfo, 0> tests;
  406. CARBON_RETURN_IF_ERROR(RegisterTests(&test_factory, exe_path, tests));
  407. testing::TestEventListeners& listeners =
  408. testing::UnitTest::GetInstance()->listeners();
  409. if (absl::GetFlag(FLAGS_autoupdate) || absl::GetFlag(FLAGS_dump_output)) {
  410. // Suppress all of the default output.
  411. delete listeners.Release(listeners.default_result_printer());
  412. }
  413. // Use a listener to run tests in parallel.
  414. listeners.Append(new FileTestEventListener(tests));
  415. return RUN_ALL_TESTS();
  416. }
  417. } // namespace Carbon::Testing
  418. auto main(int argc, char** argv) -> int {
  419. if (auto result = Carbon::Testing::Main(argc, argv); result.ok()) {
  420. return *result;
  421. } else {
  422. llvm::errs() << result.error() << "\n";
  423. return EXIT_FAILURE;
  424. }
  425. }