file_test_base.cpp 19 KB

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