file_test_base.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 <filesystem>
  6. #include <fstream>
  7. #include "absl/flags/flag.h"
  8. #include "absl/flags/parse.h"
  9. #include "common/check.h"
  10. #include "llvm/ADT/StringExtras.h"
  11. #include "llvm/ADT/Twine.h"
  12. #include "llvm/Support/FormatVariadic.h"
  13. #include "llvm/Support/InitLLVM.h"
  14. #include "testing/util/test_raw_ostream.h"
  15. ABSL_FLAG(std::vector<std::string>, file_tests, {},
  16. "A comma-separated list of tests for file_test infrastructure.");
  17. namespace Carbon::Testing {
  18. // The length of the base directory.
  19. static int base_dir_len = 0;
  20. using ::testing::Eq;
  21. using ::testing::Matcher;
  22. using ::testing::MatchesRegex;
  23. using ::testing::StrEq;
  24. void FileTestBase::RegisterTests(
  25. const char* fixture_label,
  26. const llvm::SmallVector<std::filesystem::path>& paths,
  27. std::function<FileTestBase*(const std::filesystem::path&)> factory) {
  28. // Use RegisterTest instead of INSTANTIATE_TEST_CASE_P because of ordering
  29. // issues between container initialization and test instantiation by
  30. // InitGoogleTest.
  31. for (const auto& path : paths) {
  32. std::string test_name = path.string().substr(base_dir_len);
  33. testing::RegisterTest(fixture_label, test_name.c_str(), nullptr,
  34. test_name.c_str(), __FILE__, __LINE__,
  35. [=]() { return factory(path); });
  36. }
  37. }
  38. // Reads a file to string.
  39. static auto ReadFile(std::filesystem::path path) -> std::string {
  40. std::ifstream proto_file(path);
  41. std::stringstream buffer;
  42. buffer << proto_file.rdbuf();
  43. proto_file.close();
  44. return buffer.str();
  45. }
  46. // Splits outputs to string_view because gtest handles string_view by default.
  47. static auto SplitOutput(llvm::StringRef output)
  48. -> llvm::SmallVector<std::string_view> {
  49. if (output.empty()) {
  50. return {};
  51. }
  52. llvm::SmallVector<llvm::StringRef> lines;
  53. llvm::StringRef(output).split(lines, "\n");
  54. return llvm::SmallVector<std::string_view>(lines.begin(), lines.end());
  55. }
  56. // Runs a test and compares output. This keeps output split by line so that
  57. // issues are a little easier to identify by the different line.
  58. auto FileTestBase::TestBody() -> void {
  59. const char* src_dir = getenv("TEST_SRCDIR");
  60. CARBON_CHECK(src_dir);
  61. std::string test_file = path().lexically_relative(
  62. std::filesystem::path(src_dir).append("carbon"));
  63. const char* target = getenv("TEST_TARGET");
  64. CARBON_CHECK(target);
  65. // This advice overrides the --file_tests flag provided by the file_test rule.
  66. llvm::errs() << "\nTo test this file alone, run:\n bazel test " << target
  67. << " --test_arg=--file_tests=" << test_file << "\n\n";
  68. // Store the file so that test_files can use references to content.
  69. std::string test_content = ReadFile(path());
  70. // Load expected output.
  71. llvm::SmallVector<std::string> test_args;
  72. llvm::SmallVector<TestFile> test_files;
  73. llvm::SmallVector<Matcher<std::string>> expected_stdout;
  74. llvm::SmallVector<Matcher<std::string>> expected_stderr;
  75. bool check_subset = false;
  76. ProcessTestFile(test_content, test_args, test_files, expected_stdout,
  77. expected_stderr, check_subset);
  78. if (HasFailure()) {
  79. return;
  80. }
  81. // Process arguments.
  82. if (test_args.empty()) {
  83. test_args = GetDefaultArgs();
  84. }
  85. DoArgReplacements(test_args, test_files);
  86. if (HasFailure()) {
  87. return;
  88. }
  89. // Pass arguments as StringRef.
  90. llvm::SmallVector<llvm::StringRef> test_args_ref;
  91. test_args_ref.reserve(test_args.size());
  92. for (const auto& arg : test_args) {
  93. test_args_ref.push_back(arg);
  94. }
  95. // Capture trace streaming, but only when in debug mode.
  96. TestRawOstream stdout;
  97. TestRawOstream stderr;
  98. bool run_succeeded = RunWithFiles(test_args_ref, test_files, stdout, stderr);
  99. if (HasFailure()) {
  100. return;
  101. }
  102. EXPECT_THAT(!llvm::StringRef(path().filename()).starts_with("fail_"),
  103. Eq(run_succeeded))
  104. << "Tests should be prefixed with `fail_` if and only if running them "
  105. "is expected to fail.";
  106. // Check results.
  107. if (check_subset) {
  108. EXPECT_THAT(SplitOutput(stdout.TakeStr()), IsSupersetOf(expected_stdout));
  109. EXPECT_THAT(SplitOutput(stderr.TakeStr()), IsSupersetOf(expected_stderr));
  110. } else {
  111. EXPECT_THAT(SplitOutput(stdout.TakeStr()),
  112. ElementsAreArray(expected_stdout));
  113. EXPECT_THAT(SplitOutput(stderr.TakeStr()),
  114. ElementsAreArray(expected_stderr));
  115. }
  116. }
  117. auto FileTestBase::DoArgReplacements(
  118. llvm::SmallVector<std::string>& test_args,
  119. const llvm::SmallVector<TestFile>& test_files) -> void {
  120. for (auto* it = test_args.begin(); it != test_args.end(); ++it) {
  121. auto percent = it->find("%");
  122. if (percent == std::string::npos) {
  123. continue;
  124. }
  125. if (percent + 1 >= it->size()) {
  126. FAIL() << "% is not allowed on its own: " << *it;
  127. }
  128. char c = (*it)[percent + 1];
  129. switch (c) {
  130. case 's': {
  131. if (*it != "%s") {
  132. FAIL() << "%s must be the full argument: " << *it;
  133. }
  134. it = test_args.erase(it);
  135. for (const auto& file : test_files) {
  136. it = test_args.insert(it, file.filename);
  137. ++it;
  138. }
  139. // Back up once because the for loop will advance.
  140. --it;
  141. break;
  142. }
  143. case 't': {
  144. char* temp = getenv("TEST_TMPDIR");
  145. CARBON_CHECK(temp != nullptr);
  146. it->replace(percent, 2, llvm::formatv("{0}/temp_file", temp));
  147. break;
  148. }
  149. default:
  150. FAIL() << "%" << c << " is not supported: " << *it;
  151. }
  152. }
  153. }
  154. auto FileTestBase::ProcessTestFile(
  155. llvm::StringRef file_content, llvm::SmallVector<std::string>& test_args,
  156. llvm::SmallVector<TestFile>& test_files,
  157. llvm::SmallVector<Matcher<std::string>>& expected_stdout,
  158. llvm::SmallVector<Matcher<std::string>>& expected_stderr,
  159. bool& check_subset) -> void {
  160. llvm::StringRef cursor = file_content;
  161. bool found_content_pre_split = false;
  162. int line_index = 0;
  163. llvm::StringRef current_file_name;
  164. const char* current_file_start = nullptr;
  165. while (!cursor.empty()) {
  166. auto [line, next_cursor] = cursor.split("\n");
  167. cursor = next_cursor;
  168. static constexpr llvm::StringLiteral SplitPrefix = "// ---";
  169. if (line.consume_front(SplitPrefix)) {
  170. // On a file split, add the previous file, then start a new one.
  171. if (current_file_start) {
  172. test_files.push_back(TestFile(
  173. current_file_name.str(),
  174. llvm::StringRef(
  175. current_file_start,
  176. line.begin() - current_file_start - SplitPrefix.size())));
  177. } else {
  178. // For the first split, we make sure there was no content prior.
  179. ASSERT_FALSE(found_content_pre_split)
  180. << "When using split files, there must be no content before the "
  181. "first split file.";
  182. }
  183. current_file_name = line.trim();
  184. current_file_start = cursor.begin();
  185. line_index = 0;
  186. continue;
  187. } else if (!current_file_start && !line.starts_with("//") &&
  188. !line.trim().empty()) {
  189. found_content_pre_split = true;
  190. }
  191. ++line_index;
  192. // Process expectations when found.
  193. auto line_trimmed = line.ltrim();
  194. if (line_trimmed.consume_front("// ARGS: ")) {
  195. if (test_args.empty()) {
  196. // Split the line into arguments.
  197. std::pair<llvm::StringRef, llvm::StringRef> cursor =
  198. llvm::getToken(line_trimmed);
  199. while (!cursor.first.empty()) {
  200. test_args.push_back(std::string(cursor.first));
  201. cursor = llvm::getToken(cursor.second);
  202. }
  203. } else {
  204. FAIL() << "ARGS was specified multiple times: " << line.str();
  205. }
  206. } else if (line_trimmed == "// SET-CHECK-SUBSET") {
  207. if (!check_subset) {
  208. check_subset = true;
  209. } else {
  210. FAIL() << "SET-CHECK-SUBSET was specified multiple times";
  211. }
  212. } else if (line_trimmed.consume_front("// CHECK")) {
  213. if (line_trimmed.consume_front(":STDOUT:")) {
  214. expected_stdout.push_back(
  215. TransformExpectation(line_index, line_trimmed));
  216. } else if (line_trimmed.consume_front(":STDERR:")) {
  217. expected_stderr.push_back(
  218. TransformExpectation(line_index, line_trimmed));
  219. } else {
  220. FAIL() << "Unexpected CHECK in input: " << line.str();
  221. }
  222. }
  223. }
  224. if (current_file_start) {
  225. test_files.push_back(
  226. TestFile(current_file_name.str(),
  227. llvm::StringRef(current_file_start,
  228. file_content.end() - current_file_start)));
  229. } else {
  230. // If no file splitting happened, use the main file as the test file.
  231. test_files.push_back(TestFile(path().filename().string(), file_content));
  232. }
  233. // Assume there is always a suffix `\n` in output.
  234. if (!expected_stdout.empty()) {
  235. expected_stdout.push_back(StrEq(""));
  236. }
  237. if (!expected_stderr.empty()) {
  238. expected_stderr.push_back(StrEq(""));
  239. }
  240. }
  241. auto FileTestBase::TransformExpectation(int line_index, llvm::StringRef in)
  242. -> Matcher<std::string> {
  243. if (in.empty()) {
  244. return StrEq("");
  245. }
  246. CARBON_CHECK(in[0] == ' ') << "Malformated input: " << in;
  247. std::string str = in.substr(1).str();
  248. for (int pos = 0; pos < static_cast<int>(str.size());) {
  249. switch (str[pos]) {
  250. case '(':
  251. case ')':
  252. case ']':
  253. case '}':
  254. case '.':
  255. case '^':
  256. case '$':
  257. case '*':
  258. case '+':
  259. case '?':
  260. case '|':
  261. case '\\': {
  262. // Escape regex characters.
  263. str.insert(pos, "\\");
  264. pos += 2;
  265. break;
  266. }
  267. case '[': {
  268. llvm::StringRef line_keyword_cursor = llvm::StringRef(str).substr(pos);
  269. if (line_keyword_cursor.consume_front("[[")) {
  270. static constexpr llvm::StringLiteral LineKeyword = "@LINE";
  271. if (line_keyword_cursor.consume_front(LineKeyword)) {
  272. // Allow + or - here; consumeInteger handles -.
  273. line_keyword_cursor.consume_front("+");
  274. int offset;
  275. // consumeInteger returns true for errors, not false.
  276. CARBON_CHECK(!line_keyword_cursor.consumeInteger(10, offset) &&
  277. line_keyword_cursor.consume_front("]]"))
  278. << "Unexpected @LINE offset at `"
  279. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  280. std::string int_str = llvm::Twine(line_index + offset).str();
  281. int remove_len = (line_keyword_cursor.data() - str.data()) - pos;
  282. str.replace(pos, remove_len, int_str);
  283. pos += int_str.size();
  284. } else {
  285. CARBON_FATAL() << "Unexpected [[, should be {{\\[\\[}} at `"
  286. << line_keyword_cursor.substr(0, 5)
  287. << "` in: " << in;
  288. }
  289. } else {
  290. // Escape the `[`.
  291. str.insert(pos, "\\");
  292. pos += 2;
  293. }
  294. break;
  295. }
  296. case '{': {
  297. if (pos + 1 == static_cast<int>(str.size()) || str[pos + 1] != '{') {
  298. // Single `{`, escape it.
  299. str.insert(pos, "\\");
  300. pos += 2;
  301. } else {
  302. // Replace the `{{...}}` regex syntax with standard `(...)` syntax.
  303. str.replace(pos, 2, "(");
  304. for (++pos; pos < static_cast<int>(str.size() - 1); ++pos) {
  305. if (str[pos] == '}' && str[pos + 1] == '}') {
  306. str.replace(pos, 2, ")");
  307. ++pos;
  308. break;
  309. }
  310. }
  311. }
  312. break;
  313. }
  314. default: {
  315. ++pos;
  316. }
  317. }
  318. }
  319. return MatchesRegex(str);
  320. }
  321. } // namespace Carbon::Testing
  322. auto main(int argc, char** argv) -> int {
  323. absl::ParseCommandLine(argc, argv);
  324. testing::InitGoogleTest(&argc, argv);
  325. llvm::setBugReportMsg(
  326. "Please report issues to "
  327. "https://github.com/carbon-language/carbon-lang/issues and include the "
  328. "crash backtrace.\n");
  329. llvm::InitLLVM init_llvm(argc, argv);
  330. if (argc > 1) {
  331. llvm::errs() << "Unexpected arguments starting at: " << argv[1] << "\n";
  332. return EXIT_FAILURE;
  333. }
  334. // Configure the base directory for test names.
  335. const char* target = getenv("TEST_TARGET");
  336. CARBON_CHECK(target != nullptr);
  337. llvm::StringRef target_dir = target;
  338. std::error_code ec;
  339. std::filesystem::path working_dir = std::filesystem::current_path(ec);
  340. CARBON_CHECK(!ec) << ec.message();
  341. // Leaves one slash.
  342. CARBON_CHECK(target_dir.consume_front("/"));
  343. target_dir = target_dir.substr(0, target_dir.rfind(":"));
  344. std::string base_dir = working_dir.string() + target_dir.str() + "/";
  345. Carbon::Testing::base_dir_len = base_dir.size();
  346. // Register tests based on their absolute path.
  347. llvm::SmallVector<std::filesystem::path> paths;
  348. for (const auto& file_test : absl::GetFlag(FLAGS_file_tests)) {
  349. auto path = std::filesystem::absolute(file_test, ec);
  350. CARBON_CHECK(!ec) << file_test << ": " << ec.message();
  351. CARBON_CHECK(llvm::StringRef(path.string()).starts_with(base_dir))
  352. << "\n " << path << "\n should start with\n " << base_dir;
  353. paths.push_back(path);
  354. }
  355. Carbon::Testing::RegisterFileTests(paths);
  356. return RUN_ALL_TESTS();
  357. }