file_test_base_test.cpp 12 KB

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