run_test.cpp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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(
  23. llvm::SmallVector<std::string>& test_args,
  24. const llvm::StringMap<std::string>& replacements,
  25. const llvm::SmallVector<TestFile::Split>& split_files) -> 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. // Process arguments.
  83. if (test_file.test_args.empty()) {
  84. test_file.test_args = test_base.GetDefaultArgs();
  85. test_file.test_args.append(test_file.extra_args);
  86. }
  87. CARBON_RETURN_IF_ERROR(DoArgReplacements(test_file.test_args,
  88. test_base.GetArgReplacements(),
  89. test_file.file_splits));
  90. // stdin needs to exist on-disk for compatibility. We'll use a pointer for it.
  91. FILE* input_stream = nullptr;
  92. auto erase_input_on_exit = llvm::make_scope_exit([&input_stream]() {
  93. if (input_stream) {
  94. // fclose should delete the tmpfile.
  95. fclose(input_stream);
  96. input_stream = nullptr;
  97. }
  98. });
  99. // Create the files in-memory.
  100. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> fs =
  101. new llvm::vfs::InMemoryFileSystem;
  102. for (const auto& split : test_file.file_splits) {
  103. if (split.filename == StdinFilename) {
  104. input_stream = tmpfile();
  105. fwrite(split.content.c_str(), sizeof(char), split.content.size(),
  106. input_stream);
  107. rewind(input_stream);
  108. } else if (!fs->addFile(split.filename, /*ModificationTime=*/0,
  109. llvm::MemoryBuffer::getMemBuffer(
  110. split.content, split.filename,
  111. /*RequiresNullTerminator=*/false))) {
  112. return ErrorBuilder() << "File is repeated: " << split.filename;
  113. }
  114. }
  115. // Convert the arguments to StringRef and const char* to match the
  116. // expectations of PrettyStackTraceProgram and Run.
  117. llvm::SmallVector<llvm::StringRef> test_args_ref;
  118. llvm::SmallVector<const char*> test_argv_for_stack_trace;
  119. test_args_ref.reserve(test_file.test_args.size());
  120. test_argv_for_stack_trace.reserve(test_file.test_args.size() + 1);
  121. for (const auto& arg : test_file.test_args) {
  122. test_args_ref.push_back(arg);
  123. test_argv_for_stack_trace.push_back(arg.c_str());
  124. }
  125. // Add a trailing null so that this is a proper argv.
  126. test_argv_for_stack_trace.push_back(nullptr);
  127. // Add a stack trace entry for the test invocation.
  128. llvm::PrettyStackTraceProgram stack_trace_entry(
  129. test_argv_for_stack_trace.size() - 1, test_argv_for_stack_trace.data());
  130. // Conditionally capture console output. We use a scope exit to ensure the
  131. // captures terminate even on run failures.
  132. if (test_file.capture_console_output) {
  133. CaptureStderr();
  134. CaptureStdout();
  135. }
  136. // Prepare string streams to capture output. In order to address casting
  137. // constraints, we split calls to Run as a ternary based on whether we want to
  138. // capture output.
  139. llvm::raw_svector_ostream output_stream(test_file.actual_stdout);
  140. llvm::raw_svector_ostream error_stream(test_file.actual_stderr);
  141. ErrorOr<FileTestBase::RunResult> run_result =
  142. dump_output ? test_base.Run(test_args_ref, fs, input_stream, llvm::outs(),
  143. llvm::errs())
  144. : test_base.Run(test_args_ref, fs, input_stream,
  145. output_stream, error_stream);
  146. // Ensure stdout/stderr are always fetched, even when discarded on error.
  147. if (test_file.capture_console_output) {
  148. // No need to flush stderr.
  149. llvm::outs().flush();
  150. test_file.actual_stdout += GetCapturedStdout();
  151. test_file.actual_stderr += GetCapturedStderr();
  152. }
  153. if (!run_result.ok()) {
  154. return std::move(run_result).error();
  155. }
  156. test_file.run_result = std::move(*run_result);
  157. return Success();
  158. }
  159. } // namespace Carbon::Testing