file_test_base.cpp 22 KB

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