run_test.cpp 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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/run_test.h"
  5. #include <gtest/gtest.h>
  6. #include <string>
  7. #include <utility>
  8. #include "llvm/ADT/ScopeExit.h"
  9. #include "llvm/ADT/SmallVector.h"
  10. #include "llvm/ADT/StringMap.h"
  11. #include "llvm/ADT/StringRef.h"
  12. #include "llvm/Support/PrettyStackTrace.h"
  13. #include "testing/base/file_helpers.h"
  14. #include "testing/file_test/file_test_base.h"
  15. #include "testing/file_test/test_file.h"
  16. namespace Carbon::Testing {
  17. // While these are marked as "internal" APIs, they seem to work and be pretty
  18. // widely used for their exact documented behavior.
  19. using ::testing::internal::CaptureStderr;
  20. using ::testing::internal::CaptureStdout;
  21. using ::testing::internal::GetCapturedStderr;
  22. using ::testing::internal::GetCapturedStdout;
  23. static constexpr llvm::StringLiteral StdinFilename = "STDIN";
  24. // Does replacements in ARGS for %s and %t.
  25. static auto DoArgReplacements(llvm::SmallVector<std::string>& test_args,
  26. const llvm::StringMap<std::string>& replacements,
  27. llvm::ArrayRef<TestFile::Split*> split_files)
  28. -> ErrorOr<Success> {
  29. for (auto* it = test_args.begin(); it != test_args.end(); ++it) {
  30. auto percent = it->find("%");
  31. if (percent == std::string::npos) {
  32. continue;
  33. }
  34. if (percent + 1 >= it->size()) {
  35. return ErrorBuilder() << "% is not allowed on its own: " << *it;
  36. }
  37. char c = (*it)[percent + 1];
  38. switch (c) {
  39. case 's': {
  40. if (*it != "%s") {
  41. return ErrorBuilder() << "%s must be the full argument: " << *it;
  42. }
  43. it = test_args.erase(it);
  44. for (const auto& split : split_files) {
  45. const std::string& filename = split->filename;
  46. if (filename == StdinFilename || filename.ends_with(".h")) {
  47. continue;
  48. }
  49. it = test_args.insert(it, filename);
  50. ++it;
  51. }
  52. // Back up once because the for loop will advance.
  53. --it;
  54. break;
  55. }
  56. case 't': {
  57. std::filesystem::path tmpdir = GetTempDirectory();
  58. it->replace(percent, 2, llvm::formatv("{0}/temp_file", tmpdir));
  59. break;
  60. }
  61. case '{': {
  62. auto end_brace = it->find('}', percent);
  63. if (end_brace == std::string::npos) {
  64. return ErrorBuilder() << "%{ without closing }: " << *it;
  65. }
  66. llvm::StringRef substr(&*(it->begin() + percent + 2),
  67. end_brace - percent - 2);
  68. auto replacement = replacements.find(substr);
  69. if (replacement == replacements.end()) {
  70. return ErrorBuilder()
  71. << "unknown substitution: %{" << substr << "}: " << *it;
  72. }
  73. it->replace(percent, end_brace - percent + 1, replacement->second);
  74. break;
  75. }
  76. default:
  77. return ErrorBuilder() << "%" << c << " is not supported: " << *it;
  78. }
  79. }
  80. return Success();
  81. }
  82. auto RunTestFile(const FileTestBase& test_base, bool dump_output,
  83. TestFile& test_file) -> ErrorOr<Success> {
  84. llvm::SmallVector<TestFile::Split*> all_splits;
  85. for (auto& split : test_file.file_splits) {
  86. all_splits.push_back(&split);
  87. }
  88. for (auto& split : test_file.include_file_splits) {
  89. all_splits.push_back(&split);
  90. }
  91. // Process arguments.
  92. if (test_file.test_args.empty()) {
  93. test_file.test_args = test_base.GetDefaultArgs();
  94. }
  95. test_file.test_args.append(test_file.extra_args);
  96. CARBON_RETURN_IF_ERROR(DoArgReplacements(
  97. test_file.test_args, test_base.GetArgReplacements(), all_splits));
  98. // stdin needs to exist on-disk for compatibility. We'll use a pointer for it.
  99. FILE* input_stream = nullptr;
  100. auto erase_input_on_exit = llvm::make_scope_exit([&input_stream]() {
  101. if (input_stream) {
  102. // fclose should delete the tmpfile.
  103. fclose(input_stream);
  104. input_stream = nullptr;
  105. }
  106. });
  107. // Create the files in-memory.
  108. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> fs =
  109. new llvm::vfs::InMemoryFileSystem;
  110. for (const auto& split : all_splits) {
  111. if (split->filename == StdinFilename) {
  112. input_stream = tmpfile();
  113. fwrite(split->content.c_str(), sizeof(char), split->content.size(),
  114. input_stream);
  115. CARBON_CHECK(!fseek(input_stream, 0, SEEK_SET));
  116. } else if (!fs->addFile(split->filename, /*ModificationTime=*/0,
  117. llvm::MemoryBuffer::getMemBuffer(
  118. split->content, split->filename,
  119. /*RequiresNullTerminator=*/false))) {
  120. return ErrorBuilder() << "File is repeated: " << split->filename;
  121. }
  122. }
  123. // Convert the arguments to StringRef and const char* to match the
  124. // expectations of PrettyStackTraceProgram and Run.
  125. llvm::SmallVector<llvm::StringRef> test_args_ref;
  126. llvm::SmallVector<const char*> test_argv_for_stack_trace;
  127. test_args_ref.reserve(test_file.test_args.size());
  128. test_argv_for_stack_trace.reserve(test_file.test_args.size() + 1);
  129. for (const auto& arg : test_file.test_args) {
  130. test_args_ref.push_back(arg);
  131. test_argv_for_stack_trace.push_back(arg.c_str());
  132. }
  133. // Add a trailing null so that this is a proper argv.
  134. test_argv_for_stack_trace.push_back(nullptr);
  135. // Add a stack trace entry for the test invocation.
  136. llvm::PrettyStackTraceProgram stack_trace_entry(
  137. test_argv_for_stack_trace.size() - 1, test_argv_for_stack_trace.data());
  138. // Conditionally capture console output. We use a scope exit to ensure the
  139. // captures terminate even on run failures.
  140. if (test_file.capture_console_output) {
  141. CaptureStderr();
  142. CaptureStdout();
  143. }
  144. // Prepare string streams to capture output. In order to address casting
  145. // constraints, we split calls to Run as a ternary based on whether we want to
  146. // capture output.
  147. llvm::raw_svector_ostream output_stream(test_file.actual_stdout);
  148. llvm::raw_svector_ostream error_stream(test_file.actual_stderr);
  149. Timer timer;
  150. ErrorOr<FileTestBase::RunResult> run_result =
  151. dump_output ? test_base.Run(test_args_ref, fs, input_stream, llvm::outs(),
  152. llvm::errs())
  153. : test_base.Run(test_args_ref, fs, input_stream,
  154. output_stream, error_stream);
  155. test_file.run_elapsed_ms = timer.elapsed_ms();
  156. // Ensure stdout/stderr are always fetched, even when discarded on error.
  157. if (test_file.capture_console_output) {
  158. // No need to flush stderr.
  159. llvm::outs().flush();
  160. test_file.actual_stdout += GetCapturedStdout();
  161. test_file.actual_stderr += GetCapturedStderr();
  162. }
  163. if (!run_result.ok()) {
  164. return std::move(run_result).error();
  165. }
  166. test_file.run_result = std::move(*run_result);
  167. return Success();
  168. }
  169. } // namespace Carbon::Testing