file_test_base_test.cpp 9.8 KB

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