run_test.cpp 6.7 KB

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