file_test_base.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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 <atomic>
  22. #include <chrono>
  23. #include <cstdlib>
  24. #include <filesystem>
  25. #include <functional>
  26. #include <memory>
  27. #include <mutex>
  28. #include <optional>
  29. #include <string>
  30. #include <string_view>
  31. #include <system_error>
  32. #include <utility>
  33. #include "absl/flags/flag.h"
  34. #include "absl/flags/parse.h"
  35. #include "absl/strings/str_join.h"
  36. #include "common/check.h"
  37. #include "common/error.h"
  38. #include "common/exe_path.h"
  39. #include "common/init_llvm.h"
  40. #include "common/raw_string_ostream.h"
  41. #include "llvm/ADT/StringExtras.h"
  42. #include "llvm/Support/CrashRecoveryContext.h"
  43. #include "llvm/Support/FormatVariadic.h"
  44. #include "llvm/Support/MemoryBuffer.h"
  45. #include "llvm/Support/PrettyStackTrace.h"
  46. #include "llvm/Support/Process.h"
  47. #include "llvm/Support/ThreadPool.h"
  48. #include "testing/file_test/autoupdate.h"
  49. #include "testing/file_test/run_test.h"
  50. #include "testing/file_test/test_file.h"
  51. ABSL_FLAG(std::vector<std::string>, file_tests, {},
  52. "A comma-separated list of repo-relative names of test files. "
  53. "Similar to and overrides `--gtest_filter`, but doesn't require the "
  54. "test class name to be known.");
  55. ABSL_FLAG(bool, autoupdate, false,
  56. "Instead of verifying files match test output, autoupdate files "
  57. "based on test output.");
  58. ABSL_FLAG(unsigned int, threads, 0,
  59. "Number of threads to use when autoupdating tests, or 0 to "
  60. "automatically determine a thread count.");
  61. ABSL_FLAG(bool, dump_output, false,
  62. "Instead of verifying files match test output, directly dump output "
  63. "to stderr.");
  64. ABSL_FLAG(int, print_slowest_tests, 5,
  65. "The number of tests to print when showing slowest tests. Set to 0 "
  66. "to disabling printing. Set to -1 to print all tests.");
  67. namespace Carbon::Testing {
  68. // Information for a test case.
  69. struct FileTestInfo {
  70. // The name.
  71. std::string test_name;
  72. // A factory function for creating the test object.
  73. std::function<auto()->std::unique_ptr<FileTestBase>> factory_fn;
  74. // gtest's information about the test.
  75. ::testing::TestInfo* registered_test;
  76. // The test result, set after running.
  77. std::optional<ErrorOr<TestFile>> test_result;
  78. // Whether running autoupdate would change (or when autoupdating, already
  79. // changed) the test file. This may be true even if output passes test
  80. // expectations.
  81. bool autoupdate_differs = false;
  82. // Time spent in the test total, including processing and autoupdate.
  83. std::chrono::milliseconds elapsed_ms = std::chrono::milliseconds(0);
  84. };
  85. // Adapts a `FileTestBase` instance to gtest for outputting results.
  86. class FileTestCase : public testing::Test {
  87. public:
  88. explicit FileTestCase(FileTestInfo* test_info) : test_info_(test_info) {}
  89. // Runs a test and compares output. This keeps output split by line so that
  90. // issues are a little easier to identify by the different line.
  91. auto TestBody() -> void final;
  92. private:
  93. FileTestInfo* test_info_;
  94. };
  95. // Splits outputs to string_view because gtest handles string_view by default.
  96. static auto SplitOutput(llvm::StringRef output)
  97. -> llvm::SmallVector<std::string_view> {
  98. if (output.empty()) {
  99. return {};
  100. }
  101. llvm::SmallVector<llvm::StringRef> lines;
  102. llvm::StringRef(output).split(lines, "\n");
  103. return llvm::SmallVector<std::string_view>(lines.begin(), lines.end());
  104. }
  105. // Verify that the success and `fail_` prefix use correspond. Separately handle
  106. // both cases for clearer test failures.
  107. static auto CompareFailPrefix(llvm::StringRef filename, bool success) -> void {
  108. if (success) {
  109. EXPECT_FALSE(filename.starts_with("fail_"))
  110. << "`" << filename
  111. << "` succeeded; if success is expected, remove the `fail_` "
  112. "prefix.";
  113. } else {
  114. EXPECT_TRUE(filename.starts_with("fail_"))
  115. << "`" << filename
  116. << "` failed; if failure is expected, add the `fail_` prefix.";
  117. }
  118. }
  119. // Returns the requested bazel command string for the given execution mode.
  120. auto FileTestBase::GetBazelCommand(BazelMode mode) -> std::string {
  121. RawStringOstream args;
  122. args << "bazel " << ((mode == BazelMode::Test) ? "test" : "run") << " "
  123. << GetBazelLabel() << " ";
  124. switch (mode) {
  125. case BazelMode::Autoupdate:
  126. args << "-- --autoupdate ";
  127. break;
  128. case BazelMode::Dump:
  129. args << "-- --dump_output ";
  130. break;
  131. case BazelMode::Test:
  132. args << "--test_arg=";
  133. break;
  134. }
  135. args << "--file_tests=";
  136. args << test_name();
  137. return args.TakeStr();
  138. }
  139. auto FileTestBase::GetBazelLabel() -> std::string {
  140. const char* target = getenv("TEST_TARGET");
  141. return target ? target : "<target>";
  142. }
  143. // Runs the FileTestAutoupdater, returning the result.
  144. static auto RunAutoupdater(FileTestBase* test_base, const TestFile& test_file,
  145. bool dry_run) -> bool {
  146. if (!test_file.autoupdate_line_number) {
  147. return false;
  148. }
  149. llvm::SmallVector<llvm::StringRef> filenames;
  150. filenames.reserve(test_file.non_check_lines.size());
  151. if (test_file.has_splits) {
  152. // There are splits, so we provide an empty name for the first file.
  153. filenames.push_back({});
  154. }
  155. for (const auto& file : test_file.file_splits) {
  156. filenames.push_back(file.filename);
  157. }
  158. llvm::ArrayRef expected_filenames = filenames;
  159. if (filenames.size() > 1) {
  160. expected_filenames = expected_filenames.drop_front();
  161. }
  162. return FileTestAutoupdater(
  163. std::filesystem::absolute(test_base->test_name().str()),
  164. test_base->GetBazelCommand(FileTestBase::BazelMode::Test),
  165. test_base->GetBazelCommand(FileTestBase::BazelMode::Dump),
  166. test_file.input_content, filenames,
  167. *test_file.autoupdate_line_number, test_file.autoupdate_split,
  168. test_file.non_check_lines, test_file.actual_stdout,
  169. test_file.actual_stderr,
  170. test_base->GetDefaultFileRE(expected_filenames),
  171. test_base->GetLineNumberReplacements(expected_filenames),
  172. [&](std::string& line) {
  173. test_base->DoExtraCheckReplacements(line);
  174. })
  175. .Run(dry_run);
  176. }
  177. auto FileTestCase::TestBody() -> void {
  178. if (absl::GetFlag(FLAGS_autoupdate) || absl::GetFlag(FLAGS_dump_output)) {
  179. return;
  180. }
  181. CARBON_CHECK(test_info_->test_result,
  182. "Expected test to be run prior to TestBody: {0}",
  183. test_info_->test_name);
  184. ASSERT_TRUE(test_info_->test_result->ok())
  185. << test_info_->test_result->error();
  186. auto test_filename = std::filesystem::path(test_info_->test_name).filename();
  187. // Check success/failure against `fail_` prefixes.
  188. TestFile& test_file = **(test_info_->test_result);
  189. if (test_file.run_result.per_file_success.empty()) {
  190. CompareFailPrefix(test_filename.string(), test_file.run_result.success);
  191. } else {
  192. bool require_overall_failure = false;
  193. for (const auto& [filename, success] :
  194. test_file.run_result.per_file_success) {
  195. CompareFailPrefix(filename, success);
  196. if (!success) {
  197. require_overall_failure = true;
  198. }
  199. }
  200. if (require_overall_failure) {
  201. EXPECT_FALSE(test_file.run_result.success)
  202. << "There is a per-file failure expectation, so the overall result "
  203. "should have been a failure.";
  204. } else {
  205. // Individual files all succeeded, so the prefix is enforced on the main
  206. // test file.
  207. CompareFailPrefix(test_filename.string(), test_file.run_result.success);
  208. }
  209. }
  210. // Check results. Include a reminder for NOAUTOUPDATE tests.
  211. std::unique_ptr<testing::ScopedTrace> scoped_trace;
  212. if (!test_file.autoupdate_line_number) {
  213. scoped_trace = std::make_unique<testing::ScopedTrace>(
  214. __FILE__, __LINE__,
  215. "This file is NOAUTOUPDATE, so expected differences require manual "
  216. "updates.");
  217. }
  218. if (test_file.check_subset) {
  219. EXPECT_THAT(SplitOutput(test_file.actual_stdout),
  220. IsSupersetOf(test_file.expected_stdout));
  221. EXPECT_THAT(SplitOutput(test_file.actual_stderr),
  222. IsSupersetOf(test_file.expected_stderr));
  223. } else {
  224. EXPECT_THAT(SplitOutput(test_file.actual_stdout),
  225. ElementsAreArray(test_file.expected_stdout));
  226. EXPECT_THAT(SplitOutput(test_file.actual_stderr),
  227. ElementsAreArray(test_file.expected_stderr));
  228. }
  229. if (HasFailure()) {
  230. llvm::errs() << "\nTo test this file alone, run:\n "
  231. << test_info_->factory_fn()->GetBazelCommand(
  232. FileTestBase::BazelMode::Test)
  233. << "\n\n";
  234. if (!test_file.autoupdate_line_number) {
  235. llvm::errs() << "\nThis test is NOAUTOUPDATE.\n\n";
  236. }
  237. }
  238. if (test_info_->autoupdate_differs) {
  239. ADD_FAILURE() << "Autoupdate would make changes to the file content. Run:\n"
  240. << test_info_->factory_fn()->GetBazelCommand(
  241. FileTestBase::BazelMode::Autoupdate);
  242. }
  243. }
  244. auto FileTestBase::GetLineNumberReplacements(
  245. llvm::ArrayRef<llvm::StringRef> filenames) const
  246. -> llvm::SmallVector<LineNumberReplacement> {
  247. return {{.has_file = true,
  248. .re = std::make_shared<RE2>(
  249. llvm::formatv(R"(({0}):(\d+)?)", llvm::join(filenames, "|"))),
  250. .line_formatv = R"({0})"}};
  251. }
  252. // If `--file_tests` is set, transform it into a `--gtest_filter`.
  253. static auto MaybeApplyFileTestsFlag(llvm::StringRef factory_name) -> void {
  254. if (absl::GetFlag(FLAGS_file_tests).empty()) {
  255. return;
  256. }
  257. RawStringOstream filter;
  258. llvm::ListSeparator sep(":");
  259. for (const auto& file : absl::GetFlag(FLAGS_file_tests)) {
  260. filter << sep << factory_name << "." << file;
  261. }
  262. absl::SetFlag(&FLAGS_gtest_filter, filter.TakeStr());
  263. }
  264. // Loads tests from the manifest file, and registers them for execution. The
  265. // vector is taken as an output parameter so that the address of entries is
  266. // stable for the factory.
  267. static auto RegisterTests(FileTestFactory* test_factory,
  268. llvm::StringRef exe_path,
  269. llvm::SmallVectorImpl<FileTestInfo>& tests)
  270. -> ErrorOr<Success> {
  271. // Prepare the vector first, so that the location of entries won't change.
  272. for (auto& test_name : GetFileTestManifest()) {
  273. tests.push_back({.test_name = test_name});
  274. }
  275. // Amend entries with factory functions.
  276. for (auto& test : tests) {
  277. const std::string& test_name = test.test_name;
  278. test.factory_fn = [test_factory, exe_path, &test_name]() {
  279. return test_factory->factory_fn(exe_path, test_name);
  280. };
  281. test.registered_test = testing::RegisterTest(
  282. test_factory->name, test_name.c_str(), nullptr, test_name.c_str(),
  283. __FILE__, __LINE__, [&test]() { return new FileTestCase(&test); });
  284. }
  285. return Success();
  286. }
  287. // Implements the parallel test execution through gtest's listener support.
  288. class FileTestEventListener : public testing::EmptyTestEventListener {
  289. public:
  290. explicit FileTestEventListener(llvm::MutableArrayRef<FileTestInfo> tests)
  291. : tests_(tests) {}
  292. // Runs test during start, after `should_run` is initialized. This is
  293. // multi-threaded to get extra speed.
  294. auto OnTestProgramStart(const testing::UnitTest& /*unit_test*/)
  295. -> void override;
  296. private:
  297. llvm::MutableArrayRef<FileTestInfo> tests_;
  298. };
  299. // Returns true if the main thread should be used to run tests. This is if
  300. // either --dump_output is specified, or only 1 thread is needed to run tests.
  301. static auto SingleThreaded(llvm::ArrayRef<FileTestInfo> tests) -> bool {
  302. if (absl::GetFlag(FLAGS_dump_output) || absl::GetFlag(FLAGS_threads) == 1) {
  303. return true;
  304. }
  305. bool found_test_to_run = false;
  306. for (const auto& test : tests) {
  307. if (!test.registered_test->should_run()) {
  308. continue;
  309. }
  310. if (found_test_to_run) {
  311. // At least two tests will run, so multi-threaded.
  312. return false;
  313. }
  314. // Found the first test to run.
  315. found_test_to_run = true;
  316. }
  317. // 0 or 1 test will be run, so single-threaded.
  318. return true;
  319. }
  320. // Runs the test in the section that would be inside a lock, possibly inside a
  321. // CrashRecoveryContext.
  322. static auto RunSingleTestHelper(FileTestInfo& test, FileTestBase& test_instance)
  323. -> void {
  324. Timer timer;
  325. // Add a crash trace entry with the single-file test command.
  326. std::string test_command =
  327. test_instance.GetBazelCommand(FileTestBase::BazelMode::Test);
  328. llvm::PrettyStackTraceString stack_trace_entry(test_command.c_str());
  329. if (auto err = RunTestFile(test_instance, absl::GetFlag(FLAGS_dump_output),
  330. **test.test_result);
  331. !err.ok()) {
  332. test.test_result = std::move(err).error();
  333. }
  334. test.elapsed_ms += timer.elapsed_ms();
  335. }
  336. // Runs a single test. Uses a CrashRecoveryContext, and returns false on a
  337. // crash. For test_elapsed_ms, try to exclude time spent waiting on
  338. // output_mutex.
  339. static auto RunSingleTest(FileTestInfo& test, bool single_threaded,
  340. std::mutex& output_mutex) -> bool {
  341. std::unique_ptr<FileTestBase> test_instance(test.factory_fn());
  342. if (absl::GetFlag(FLAGS_dump_output)) {
  343. std::unique_lock<std::mutex> lock(output_mutex);
  344. llvm::errs() << "\n--- Dumping: " << test.test_name << "\n\n";
  345. }
  346. // Load expected output.
  347. Timer process_timer;
  348. test.test_result = ProcessTestFile(test_instance->test_name(),
  349. absl::GetFlag(FLAGS_autoupdate));
  350. test.elapsed_ms = process_timer.elapsed_ms();
  351. if (test.test_result->ok()) {
  352. // Execution must be serialized for either serial tests or console
  353. // output.
  354. std::unique_lock<std::mutex> output_lock;
  355. if ((*test.test_result)->capture_console_output ||
  356. !test_instance->AllowParallelRun()) {
  357. output_lock = std::unique_lock<std::mutex>(output_mutex);
  358. }
  359. if (single_threaded) {
  360. RunSingleTestHelper(test, *test_instance);
  361. } else {
  362. // Use a crash recovery context to try to get a stack trace when
  363. // multiple threads may crash in parallel, which otherwise leads to the
  364. // program aborting without printing a stack trace.
  365. llvm::CrashRecoveryContext crc;
  366. crc.DumpStackAndCleanupOnFailure = true;
  367. if (!crc.RunSafely([&] { RunSingleTestHelper(test, *test_instance); })) {
  368. return false;
  369. }
  370. }
  371. }
  372. if (!test.test_result->ok()) {
  373. std::unique_lock<std::mutex> lock(output_mutex);
  374. llvm::errs() << "\n" << test.test_result->error().message() << "\n";
  375. return true;
  376. }
  377. Timer autoupdate_timer;
  378. test.autoupdate_differs =
  379. RunAutoupdater(test_instance.get(), **test.test_result,
  380. /*dry_run=*/!absl::GetFlag(FLAGS_autoupdate));
  381. test.elapsed_ms += autoupdate_timer.elapsed_ms();
  382. std::unique_lock<std::mutex> lock(output_mutex);
  383. if (absl::GetFlag(FLAGS_dump_output)) {
  384. llvm::outs().flush();
  385. const TestFile& test_file = **test.test_result;
  386. llvm::errs() << "\n--- Exit with success: "
  387. << (test_file.run_result.success ? "true" : "false")
  388. << "\n--- Autoupdate differs: "
  389. << (test.autoupdate_differs ? "true" : "false") << "\n";
  390. } else {
  391. llvm::errs() << (test.autoupdate_differs ? "!" : ".");
  392. }
  393. return true;
  394. }
  395. auto FileTestEventListener::OnTestProgramStart(
  396. const testing::UnitTest& /*unit_test*/) -> void {
  397. bool single_threaded = SingleThreaded(tests_);
  398. std::unique_ptr<llvm::ThreadPoolInterface> pool;
  399. if (single_threaded) {
  400. pool = std::make_unique<llvm::SingleThreadExecutor>();
  401. } else {
  402. // Enable the CRC for use in `RunSingleTest`.
  403. llvm::CrashRecoveryContext::Enable();
  404. llvm::ThreadPoolStrategy thread_strategy = {
  405. .ThreadsRequested = absl::GetFlag(FLAGS_threads),
  406. // Disable hyper threads to reduce contention.
  407. .UseHyperThreads = false};
  408. pool = std::make_unique<llvm::DefaultThreadPool>(thread_strategy);
  409. }
  410. if (!absl::GetFlag(FLAGS_dump_output)) {
  411. llvm::errs() << "Running tests with " << pool->getMaxConcurrency()
  412. << " thread(s)\n";
  413. }
  414. // Guard access to output (stdout and stderr).
  415. std::mutex output_mutex;
  416. std::atomic<bool> crashed = false;
  417. Timer all_timer;
  418. int run_count = 0;
  419. for (auto& test : tests_) {
  420. if (!test.registered_test->should_run()) {
  421. continue;
  422. }
  423. ++run_count;
  424. pool->async([&] {
  425. // If any thread crashed, don't try running more.
  426. if (crashed) {
  427. return;
  428. }
  429. if (!RunSingleTest(test, single_threaded, output_mutex)) {
  430. crashed = true;
  431. }
  432. });
  433. }
  434. pool->wait();
  435. if (crashed) {
  436. // Abort rather than returning so that we don't get a LeakSanitizer report.
  437. // We expect to have leaked memory if one or more of our tests crashed.
  438. std::abort();
  439. }
  440. // Calculate the total test time.
  441. auto all_elapsed_ms = all_timer.elapsed_ms();
  442. auto total_elapsed_ms = std::chrono::milliseconds(0);
  443. for (auto& test : tests_) {
  444. total_elapsed_ms += test.elapsed_ms;
  445. }
  446. llvm::errs() << "\nRan " << run_count << " tests in "
  447. << all_elapsed_ms.count() << " ms wall time, "
  448. << total_elapsed_ms.count() << " ms across threads\n";
  449. // When there are multiple tests, give additional timing details, particularly
  450. // slowest tests.
  451. auto print_slowest_tests = absl::GetFlag(FLAGS_print_slowest_tests);
  452. if (run_count > 1 && print_slowest_tests != 0) {
  453. // Sort in a copy so that `FileTestCase` pointers to the original tests
  454. // remain stable.
  455. llvm::SmallVector<const FileTestInfo*> sorted_tests(
  456. llvm::make_pointer_range(tests_));
  457. llvm::sort(sorted_tests,
  458. [](const FileTestInfo* lhs, const FileTestInfo* rhs) {
  459. return lhs->elapsed_ms > rhs->elapsed_ms;
  460. });
  461. llvm::errs() << " Slowest tests:\n";
  462. int count = print_slowest_tests > 0 ? print_slowest_tests : run_count;
  463. for (const auto* test : llvm::ArrayRef(sorted_tests).take_front(count)) {
  464. std::chrono::milliseconds run_ms(0);
  465. if (test->test_result && test->test_result->ok()) {
  466. run_ms = test->test_result.value()->run_elapsed_ms;
  467. }
  468. llvm::errs() << " - " << test->test_name << ": "
  469. << test->elapsed_ms.count() << " ms, " << run_ms.count()
  470. << " ms in Run\n";
  471. }
  472. }
  473. }
  474. // Implements main() within the Carbon::Testing namespace for convenience.
  475. static auto Main(int argc, char** argv) -> ErrorOr<int> {
  476. // Default to brief because we expect lots of tests, and `FileTestBase`
  477. // provides some summaries. Note `--test_arg=--gtest_brief=0` works to restore
  478. // output.
  479. absl::SetFlag(&FLAGS_gtest_brief, 1);
  480. Carbon::InitLLVM init_llvm(argc, argv);
  481. testing::InitGoogleTest(&argc, argv);
  482. auto args = absl::ParseCommandLine(argc, argv);
  483. if (args.size() > 1) {
  484. ErrorBuilder b;
  485. b << "Unexpected arguments:";
  486. for (char* arg : llvm::ArrayRef(args).drop_front()) {
  487. b << " " << FormatEscaped(arg);
  488. }
  489. return b;
  490. }
  491. std::string exe_path = FindExecutablePath(argv[0]);
  492. // Tests might try to read from stdin. Ensure those reads fail by closing
  493. // stdin and reopening it as /dev/null. Note that STDIN_FILENO doesn't exist
  494. // on Windows, but POSIX requires it to be 0.
  495. if (std::error_code error =
  496. llvm::sys::Process::SafelyCloseFileDescriptor(0)) {
  497. return Error("Unable to close standard input: " + error.message());
  498. }
  499. if (std::error_code error =
  500. llvm::sys::Process::FixupStandardFileDescriptors()) {
  501. return Error("Unable to correct standard file descriptors: " +
  502. error.message());
  503. }
  504. if (absl::GetFlag(FLAGS_autoupdate) && absl::GetFlag(FLAGS_dump_output)) {
  505. return Error("--autoupdate and --dump_output are mutually exclusive.");
  506. }
  507. auto test_factory = GetFileTestFactory();
  508. MaybeApplyFileTestsFlag(test_factory.name);
  509. // Inline 0 entries because it will always be too large to store on the stack.
  510. llvm::SmallVector<FileTestInfo, 0> tests;
  511. CARBON_RETURN_IF_ERROR(RegisterTests(&test_factory, exe_path, tests));
  512. testing::TestEventListeners& listeners =
  513. testing::UnitTest::GetInstance()->listeners();
  514. if (absl::GetFlag(FLAGS_autoupdate) || absl::GetFlag(FLAGS_dump_output)) {
  515. // Suppress all of the default output.
  516. delete listeners.Release(listeners.default_result_printer());
  517. }
  518. // Use a listener to run tests in parallel.
  519. listeners.Append(new FileTestEventListener(tests));
  520. return RUN_ALL_TESTS();
  521. }
  522. } // namespace Carbon::Testing
  523. auto main(int argc, char** argv) -> int {
  524. if (auto result = Carbon::Testing::Main(argc, argv); result.ok()) {
  525. return *result;
  526. } else {
  527. llvm::errs() << result.error() << "\n";
  528. return EXIT_FAILURE;
  529. }
  530. }