file_test_base.cpp 13 KB

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