file_test_base_test.cpp 12 KB

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