file_test_base_test.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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/file_test_base.h"
  5. #include <gmock/gmock.h>
  6. #include <gtest/gtest.h>
  7. #include "common/ostream.h"
  8. #include "llvm/ADT/StringExtras.h"
  9. #include "llvm/ADT/StringSwitch.h"
  10. #include "llvm/Support/FormatVariadic.h"
  11. namespace Carbon::Testing {
  12. namespace {
  13. class FileTestBaseTest : public FileTestBase {
  14. public:
  15. FileTestBaseTest(llvm::StringRef /*exe_path*/, std::mutex* output_mutex,
  16. llvm::StringRef test_name)
  17. : FileTestBase(output_mutex, test_name) {}
  18. auto Run(const llvm::SmallVector<llvm::StringRef>& test_args,
  19. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>& fs,
  20. llvm::raw_pwrite_stream& stdout, llvm::raw_pwrite_stream& stderr)
  21. -> ErrorOr<RunResult> override;
  22. auto GetArgReplacements() -> llvm::StringMap<std::string> override {
  23. return {{"replacement", "replaced"}};
  24. }
  25. auto GetDefaultArgs() -> llvm::SmallVector<std::string> override {
  26. return {"default_args", "%s"};
  27. }
  28. auto GetDefaultFileRE(llvm::ArrayRef<llvm::StringRef> filenames)
  29. -> std::optional<RE2> override {
  30. return std::make_optional<RE2>(
  31. llvm::formatv(R"(file: ({0}))", llvm::join(filenames, "|")));
  32. }
  33. auto GetLineNumberReplacements(llvm::ArrayRef<llvm::StringRef> filenames)
  34. -> llvm::SmallVector<LineNumberReplacement> override {
  35. auto replacements = FileTestBase::GetLineNumberReplacements(filenames);
  36. auto filename = std::filesystem::path(test_name().str()).filename();
  37. if (llvm::StringRef(filename).starts_with("file_only_re_")) {
  38. replacements.push_back({.has_file = false,
  39. .re = std::make_shared<RE2>(R"(line: (\d+))"),
  40. .line_formatv = "{0}"});
  41. }
  42. return replacements;
  43. }
  44. };
  45. // Prints arguments so that they can be validated in tests.
  46. static auto PrintArgs(llvm::ArrayRef<llvm::StringRef> args,
  47. llvm::raw_pwrite_stream& stdout) -> void {
  48. llvm::ListSeparator sep;
  49. stdout << args.size() << " args: ";
  50. for (auto arg : args) {
  51. stdout << sep << "`" << arg << "`";
  52. }
  53. stdout << "\n";
  54. }
  55. // Verifies arguments are well-structured, and returns the files in them.
  56. static auto GetFilesFromArgs(llvm::ArrayRef<llvm::StringRef> args,
  57. llvm::vfs::InMemoryFileSystem& fs)
  58. -> ErrorOr<llvm::ArrayRef<llvm::StringRef>> {
  59. if (args.empty() || args.front() != "default_args") {
  60. return ErrorBuilder() << "missing `default_args` argument";
  61. }
  62. args = args.drop_front();
  63. for (auto arg : args) {
  64. if (!fs.exists(arg)) {
  65. return ErrorBuilder() << "Missing file: " << arg;
  66. }
  67. }
  68. return args;
  69. }
  70. // Parameters used to by individual test handlers, for easy value forwarding.
  71. struct TestParams {
  72. // These are the arguments to `Run()`.
  73. llvm::vfs::InMemoryFileSystem& fs;
  74. llvm::raw_pwrite_stream& stdout;
  75. llvm::raw_pwrite_stream& stderr;
  76. // This is assigned after construction.
  77. llvm::ArrayRef<llvm::StringRef> files;
  78. };
  79. // Does printing and returns expected results for alternating_files.carbon.
  80. static auto TestAlternatingFiles(TestParams& params)
  81. -> ErrorOr<FileTestBaseTest::RunResult> {
  82. params.stdout << "unattached message 1\n"
  83. << "a.carbon:2: message 2\n"
  84. << "b.carbon:5: message 3\n"
  85. << "a.carbon:2: message 4\n"
  86. << "b.carbon:5: message 5\n"
  87. << "unattached message 6\n";
  88. params.stderr << "unattached message 1\n"
  89. << "a.carbon:2: message 2\n"
  90. << "b.carbon:5: message 3\n"
  91. << "a.carbon:2: message 4\n"
  92. << "b.carbon:5: message 5\n"
  93. << "unattached message 6\n";
  94. return {{.success = true}};
  95. }
  96. // Does printing and returns expected results for capture_console_output.carbon.
  97. static auto TestCaptureConsoleOutput(TestParams& params)
  98. -> ErrorOr<FileTestBaseTest::RunResult> {
  99. llvm::errs() << "llvm::errs\n";
  100. params.stderr << "params.stderr\n";
  101. llvm::outs() << "llvm::outs\n";
  102. params.stdout << "params.stdout\n";
  103. return {{.success = true}};
  104. }
  105. // Does printing and returns expected results for example.carbon.
  106. static auto TestExample(TestParams& params)
  107. -> ErrorOr<FileTestBaseTest::RunResult> {
  108. int delta_line = 10;
  109. params.stdout << "something\n"
  110. << "\n"
  111. << "example.carbon:" << delta_line + 1 << ": Line delta\n"
  112. << "example.carbon:" << delta_line << ": Negative line delta\n"
  113. << "+*[]{}\n"
  114. << "Foo baz\n";
  115. return {{.success = true}};
  116. }
  117. // Does printing and returns expected results for fail_example.carbon.
  118. static auto TestFailExample(TestParams& params)
  119. -> ErrorOr<FileTestBaseTest::RunResult> {
  120. params.stderr << "Oops\n";
  121. return {{.success = false}};
  122. }
  123. // Does printing and returns expected results for
  124. // file_only_re_multi_file.carbon.
  125. static auto TestFileOnlyREMultiFile(TestParams& params)
  126. -> ErrorOr<FileTestBaseTest::RunResult> {
  127. int msg_count = 0;
  128. params.stdout << "unattached message " << ++msg_count << "\n"
  129. << "file: a.carbon\n"
  130. << "unattached message " << ++msg_count << "\n"
  131. << "line: 3: attached message " << ++msg_count << "\n"
  132. << "unattached message " << ++msg_count << "\n"
  133. << "line: 8: late message " << ++msg_count << "\n"
  134. << "unattached message " << ++msg_count << "\n"
  135. << "file: b.carbon\n"
  136. << "line: 2: attached message " << ++msg_count << "\n"
  137. << "unattached message " << ++msg_count << "\n"
  138. << "line: 7: late message " << ++msg_count << "\n"
  139. << "unattached message " << ++msg_count << "\n";
  140. return {{.success = true}};
  141. }
  142. // Does printing and returns expected results for file_only_re_one_file.carbon.
  143. static auto TestFileOnlyREOneFile(TestParams& params)
  144. -> ErrorOr<FileTestBaseTest::RunResult> {
  145. params.stdout << "unattached message 1\n"
  146. << "file: file_only_re_one_file.carbon\n"
  147. << "line: 1\n"
  148. << "unattached message 2\n";
  149. return {{.success = true}};
  150. }
  151. // Does printing and returns expected results for unattached_multi_file.carbon.
  152. static auto TestUnattachedMultiFile(TestParams& params)
  153. -> ErrorOr<FileTestBaseTest::RunResult> {
  154. params.stdout << "unattached message 1\n"
  155. << "unattached message 2\n";
  156. params.stderr << "unattached message 3\n"
  157. << "unattached message 4\n";
  158. return {{.success = true}};
  159. }
  160. // Does printing and returns expected results for:
  161. // - fail_multi_success_overall_fail.carbon
  162. // - multi_success.carbon
  163. // - multi_success_and_fail.carbon
  164. //
  165. // Parameters indicate overall and per-file success.
  166. static auto HandleMultiSuccessTests(bool overall, bool a, bool b)
  167. -> ErrorOr<FileTestBaseTest::RunResult> {
  168. FileTestBaseTest::RunResult result = {.success = overall};
  169. result.per_file_success.push_back({a ? "a.carbon" : "fail_a.carbon", a});
  170. result.per_file_success.push_back({b ? "b.carbon" : "fail_b.carbon", b});
  171. return result;
  172. }
  173. // Echoes back non-comment file content. Used for default file handling.
  174. static auto EchoFileContent(TestParams& params)
  175. -> ErrorOr<FileTestBaseTest::RunResult> {
  176. // By default, echo non-comment content of files back.
  177. for (auto test_file : params.files) {
  178. // Describe file contents to stdout to validate splitting.
  179. auto file = params.fs.getBufferForFile(test_file, /*FileSize=*/-1,
  180. /*RequiresNullTerminator=*/false);
  181. if (file.getError()) {
  182. return Error(file.getError().message());
  183. }
  184. llvm::StringRef buffer = file.get()->getBuffer();
  185. for (int line_number = 1; !buffer.empty(); ++line_number) {
  186. auto [line, remainder] = buffer.split('\n');
  187. if (!line.empty() && !line.starts_with("//")) {
  188. params.stdout << test_file << ":" << line_number << ": " << line
  189. << "\n";
  190. }
  191. buffer = remainder;
  192. }
  193. }
  194. return {{.success = true}};
  195. }
  196. auto FileTestBaseTest::Run(
  197. const llvm::SmallVector<llvm::StringRef>& test_args,
  198. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>& fs,
  199. llvm::raw_pwrite_stream& stdout, llvm::raw_pwrite_stream& stderr)
  200. -> ErrorOr<RunResult> {
  201. PrintArgs(test_args, stdout);
  202. auto filename = std::filesystem::path(test_name().str()).filename();
  203. if (filename == "args.carbon") {
  204. // 'args.carbon' has custom arguments, so don't do regular argument
  205. // validation for it.
  206. return {{.success = true}};
  207. }
  208. // Choose the test function based on filename.
  209. auto test_fn =
  210. llvm::StringSwitch<std::function<ErrorOr<RunResult>(TestParams&)>>(
  211. filename.string())
  212. .Case("alternating_files.carbon", &TestAlternatingFiles)
  213. .Case("capture_console_output.carbon", &TestCaptureConsoleOutput)
  214. .Case("example.carbon", &TestExample)
  215. .Case("fail_example.carbon", &TestFailExample)
  216. .Case("file_only_re_one_file.carbon", &TestFileOnlyREOneFile)
  217. .Case("file_only_re_multi_file.carbon", &TestFileOnlyREMultiFile)
  218. .Case("unattached_multi_file.carbon", &TestUnattachedMultiFile)
  219. .Case("fail_multi_success_overall_fail.carbon",
  220. [&](TestParams&) {
  221. return HandleMultiSuccessTests(/*overall=*/false, /*a=*/true,
  222. /*b=*/true);
  223. })
  224. .Case("multi_success.carbon",
  225. [&](TestParams&) {
  226. return HandleMultiSuccessTests(/*overall=*/true, /*a=*/true,
  227. /*b=*/true);
  228. })
  229. .Case("multi_success_and_fail.carbon",
  230. [&](TestParams&) {
  231. return HandleMultiSuccessTests(/*overall=*/false, /*a=*/true,
  232. /*b=*/false);
  233. })
  234. .Default(&EchoFileContent);
  235. // Call the appropriate test function for the file.
  236. TestParams params = {.fs = *fs, .stdout = stdout, .stderr = stderr};
  237. CARBON_ASSIGN_OR_RETURN(params.files, GetFilesFromArgs(test_args, *fs));
  238. return test_fn(params);
  239. }
  240. } // namespace
  241. CARBON_FILE_TEST_FACTORY(FileTestBaseTest)
  242. } // namespace Carbon::Testing