filesystem_test_helper.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. #ifndef FILESYSTEM_TEST_HELPER_H
  2. #define FILESYSTEM_TEST_HELPER_H
  3. #include "filesystem_include.h"
  4. #include <unistd.h> // for ftruncate
  5. #include <cassert>
  6. #include <cstdio> // for printf
  7. #include <string>
  8. #include <fstream>
  9. #include <random>
  10. #include <chrono>
  11. #include <vector>
  12. #include <regex>
  13. #include "test_macros.h"
  14. #include "rapid-cxx-test.h"
  15. #include "format_string.h"
  16. // static test helpers
  17. #ifndef LIBCXX_FILESYSTEM_STATIC_TEST_ROOT
  18. #warning "STATIC TESTS DISABLED"
  19. #else // LIBCXX_FILESYSTEM_STATIC_TEST_ROOT
  20. namespace StaticEnv {
  21. inline fs::path makePath(fs::path const& p) {
  22. // env_path is expected not to contain symlinks.
  23. static const fs::path env_path = LIBCXX_FILESYSTEM_STATIC_TEST_ROOT;
  24. return env_path / p;
  25. }
  26. static const fs::path Root = LIBCXX_FILESYSTEM_STATIC_TEST_ROOT;
  27. static const fs::path TestFileList[] = {
  28. makePath("empty_file"),
  29. makePath("non_empty_file"),
  30. makePath("dir1/file1"),
  31. makePath("dir1/file2")
  32. };
  33. const std::size_t TestFileListSize = sizeof(TestFileList) / sizeof(fs::path);
  34. static const fs::path TestDirList[] = {
  35. makePath("dir1"),
  36. makePath("dir1/dir2"),
  37. makePath("dir1/dir2/dir3")
  38. };
  39. const std::size_t TestDirListSize = sizeof(TestDirList) / sizeof(fs::path);
  40. static const fs::path File = TestFileList[0];
  41. static const fs::path Dir = TestDirList[0];
  42. static const fs::path Dir2 = TestDirList[1];
  43. static const fs::path Dir3 = TestDirList[2];
  44. static const fs::path SymlinkToFile = makePath("symlink_to_empty_file");
  45. static const fs::path SymlinkToDir = makePath("symlink_to_dir");
  46. static const fs::path BadSymlink = makePath("bad_symlink");
  47. static const fs::path DNE = makePath("DNE");
  48. static const fs::path EmptyFile = TestFileList[0];
  49. static const fs::path NonEmptyFile = TestFileList[1];
  50. static const fs::path CharFile = "/dev/null"; // Hopefully this exists
  51. static const fs::path DirIterationList[] = {
  52. makePath("dir1/dir2"),
  53. makePath("dir1/file1"),
  54. makePath("dir1/file2")
  55. };
  56. const std::size_t DirIterationListSize = sizeof(DirIterationList)
  57. / sizeof(fs::path);
  58. static const fs::path DirIterationListDepth1[] = {
  59. makePath("dir1/dir2/afile3"),
  60. makePath("dir1/dir2/dir3"),
  61. makePath("dir1/dir2/symlink_to_dir3"),
  62. makePath("dir1/dir2/file4"),
  63. };
  64. static const fs::path RecDirIterationList[] = {
  65. makePath("dir1/dir2"),
  66. makePath("dir1/file1"),
  67. makePath("dir1/file2"),
  68. makePath("dir1/dir2/afile3"),
  69. makePath("dir1/dir2/dir3"),
  70. makePath("dir1/dir2/symlink_to_dir3"),
  71. makePath("dir1/dir2/file4"),
  72. makePath("dir1/dir2/dir3/file5")
  73. };
  74. static const fs::path RecDirFollowSymlinksIterationList[] = {
  75. makePath("dir1/dir2"),
  76. makePath("dir1/file1"),
  77. makePath("dir1/file2"),
  78. makePath("dir1/dir2/afile3"),
  79. makePath("dir1/dir2/dir3"),
  80. makePath("dir1/dir2/file4"),
  81. makePath("dir1/dir2/dir3/file5"),
  82. makePath("dir1/dir2/symlink_to_dir3"),
  83. makePath("dir1/dir2/symlink_to_dir3/file5"),
  84. };
  85. } // namespace StaticEnv
  86. #endif // LIBCXX_FILESYSTEM_STATIC_TEST_ROOT
  87. #ifndef LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT
  88. #warning LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT must be defined
  89. #else // LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT
  90. #ifndef LIBCXX_FILESYSTEM_DYNAMIC_TEST_HELPER
  91. #error LIBCXX_FILESYSTEM_DYNAMIC_TEST_HELPER must be defined
  92. #endif
  93. namespace random_utils {
  94. inline char to_hex(int ch) {
  95. return ch < 10 ? static_cast<char>('0' + ch)
  96. : static_cast<char>('a' + (ch - 10));
  97. }
  98. inline char random_hex_char() {
  99. static std::mt19937 rd{std::random_device{}()};
  100. static std::uniform_int_distribution<int> mrand{0, 15};
  101. return to_hex(mrand(rd));
  102. }
  103. } // namespace random_utils
  104. struct scoped_test_env
  105. {
  106. scoped_test_env() : test_root(random_env_path())
  107. { fs_helper_run(fs_make_cmd("init_test_directory", test_root)); }
  108. ~scoped_test_env()
  109. { fs_helper_run(fs_make_cmd("destroy_test_directory", test_root)); }
  110. scoped_test_env(scoped_test_env const &) = delete;
  111. scoped_test_env & operator=(scoped_test_env const &) = delete;
  112. fs::path make_env_path(std::string p) { return sanitize_path(p); }
  113. std::string sanitize_path(std::string raw) {
  114. assert(raw.find("..") == std::string::npos);
  115. std::string const& root = test_root.native();
  116. if (root.compare(0, root.size(), raw, 0, root.size()) != 0) {
  117. assert(raw.front() != '\\');
  118. fs::path tmp(test_root);
  119. tmp /= raw;
  120. return std::move(const_cast<std::string&>(tmp.native()));
  121. }
  122. return raw;
  123. }
  124. // Purposefully using a size potentially larger than off_t here so we can
  125. // test the behavior of libc++fs when it is built with _FILE_OFFSET_BITS=64
  126. // but the caller is not (std::filesystem also uses uintmax_t rather than
  127. // off_t). On a 32-bit system this allows us to create a file larger than
  128. // 2GB.
  129. std::string create_file(std::string filename, uintmax_t size = 0) {
  130. #if defined(__LP64__)
  131. auto large_file_fopen = fopen;
  132. auto large_file_ftruncate = ftruncate;
  133. using large_file_offset_t = off_t;
  134. #else
  135. auto large_file_fopen = fopen64;
  136. auto large_file_ftruncate = ftruncate64;
  137. using large_file_offset_t = off64_t;
  138. #endif
  139. filename = sanitize_path(std::move(filename));
  140. if (size > std::numeric_limits<large_file_offset_t>::max()) {
  141. fprintf(stderr, "create_file(%s, %ju) too large\n",
  142. filename.c_str(), size);
  143. abort();
  144. }
  145. FILE* file = large_file_fopen(filename.c_str(), "we");
  146. if (file == nullptr) {
  147. fprintf(stderr, "fopen %s failed: %s\n", filename.c_str(),
  148. strerror(errno));
  149. abort();
  150. }
  151. if (large_file_ftruncate(
  152. fileno(file), static_cast<large_file_offset_t>(size)) == -1) {
  153. fprintf(stderr, "ftruncate %s %ju failed: %s\n", filename.c_str(),
  154. size, strerror(errno));
  155. fclose(file);
  156. abort();
  157. }
  158. fclose(file);
  159. return filename;
  160. }
  161. std::string create_dir(std::string filename) {
  162. filename = sanitize_path(std::move(filename));
  163. fs_helper_run(fs_make_cmd("create_dir", filename));
  164. return filename;
  165. }
  166. std::string create_symlink(std::string source, std::string to) {
  167. source = sanitize_path(std::move(source));
  168. to = sanitize_path(std::move(to));
  169. fs_helper_run(fs_make_cmd("create_symlink", source, to));
  170. return to;
  171. }
  172. std::string create_hardlink(std::string source, std::string to) {
  173. source = sanitize_path(std::move(source));
  174. to = sanitize_path(std::move(to));
  175. fs_helper_run(fs_make_cmd("create_hardlink", source, to));
  176. return to;
  177. }
  178. std::string create_fifo(std::string file) {
  179. file = sanitize_path(std::move(file));
  180. fs_helper_run(fs_make_cmd("create_fifo", file));
  181. return file;
  182. }
  183. // OS X and FreeBSD doesn't support socket files so we shouldn't even
  184. // allow tests to call this unguarded.
  185. #if !defined(__FreeBSD__) && !defined(__APPLE__)
  186. std::string create_socket(std::string file) {
  187. file = sanitize_path(std::move(file));
  188. fs_helper_run(fs_make_cmd("create_socket", file));
  189. return file;
  190. }
  191. #endif
  192. fs::path const test_root;
  193. private:
  194. static std::string unique_path_suffix() {
  195. std::string model = "test.%%%%%%";
  196. for (auto & ch : model) {
  197. if (ch == '%')
  198. ch = random_utils::random_hex_char();
  199. }
  200. return model;
  201. }
  202. // This could potentially introduce a filesystem race with other tests
  203. // running at the same time, but oh well, it's just test code.
  204. static inline fs::path random_env_path() {
  205. static const char* env_path = LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT;
  206. fs::path p = fs::path(env_path) / unique_path_suffix();
  207. assert(p.parent_path() == env_path);
  208. return p;
  209. }
  210. static inline std::string make_arg(std::string const& arg) {
  211. return "'" + arg + "'";
  212. }
  213. static inline std::string make_arg(std::size_t arg) {
  214. return std::to_string(arg);
  215. }
  216. template <class T>
  217. static inline std::string
  218. fs_make_cmd(std::string const& cmd_name, T const& arg) {
  219. return cmd_name + "(" + make_arg(arg) + ")";
  220. }
  221. template <class T, class U>
  222. static inline std::string
  223. fs_make_cmd(std::string const& cmd_name, T const& arg1, U const& arg2) {
  224. return cmd_name + "(" + make_arg(arg1) + ", " + make_arg(arg2) + ")";
  225. }
  226. static inline void fs_helper_run(std::string const& raw_cmd) {
  227. // check that the fs test root in the environment matches what we were
  228. // compiled with.
  229. static bool checked = checkDynamicTestRoot();
  230. ((void)checked);
  231. std::string cmd = LIBCXX_FILESYSTEM_DYNAMIC_TEST_HELPER;
  232. cmd += " \"" + raw_cmd + "\"";
  233. int ret = std::system(cmd.c_str());
  234. assert(ret == 0);
  235. }
  236. static bool checkDynamicTestRoot() {
  237. // LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT is expected not to contain symlinks.
  238. char* fs_root = std::getenv("LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT");
  239. if (!fs_root) {
  240. std::printf("ERROR: LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT must be a defined "
  241. "environment variable when running the test.\n");
  242. std::abort();
  243. }
  244. if (std::string(fs_root) != LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT) {
  245. std::printf("ERROR: LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT environment variable"
  246. " must have the same value as when the test was compiled.\n");
  247. std::printf(" Current Value: '%s'\n", fs_root);
  248. std::printf(" Expected Value: '%s'\n", LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT);
  249. std::abort();
  250. }
  251. return true;
  252. }
  253. };
  254. #endif // LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT
  255. // Misc test types
  256. #define CONCAT2(LHS, RHS) LHS##RHS
  257. #define CONCAT(LHS, RHS) CONCAT2(LHS, RHS)
  258. #define MKSTR(Str) {Str, CONCAT(L, Str), CONCAT(u, Str), CONCAT(U, Str)}
  259. struct MultiStringType {
  260. const char* s;
  261. const wchar_t* w;
  262. const char16_t* u16;
  263. const char32_t* u32;
  264. operator const char* () const { return s; }
  265. operator const wchar_t* () const { return w; }
  266. operator const char16_t* () const { return u16; }
  267. operator const char32_t* () const { return u32; }
  268. };
  269. const MultiStringType PathList[] = {
  270. MKSTR(""),
  271. MKSTR(" "),
  272. MKSTR("//"),
  273. MKSTR("."),
  274. MKSTR(".."),
  275. MKSTR("foo"),
  276. MKSTR("/"),
  277. MKSTR("/foo"),
  278. MKSTR("foo/"),
  279. MKSTR("/foo/"),
  280. MKSTR("foo/bar"),
  281. MKSTR("/foo/bar"),
  282. MKSTR("//net"),
  283. MKSTR("//net/foo"),
  284. MKSTR("///foo///"),
  285. MKSTR("///foo///bar"),
  286. MKSTR("/."),
  287. MKSTR("./"),
  288. MKSTR("/.."),
  289. MKSTR("../"),
  290. MKSTR("foo/."),
  291. MKSTR("foo/.."),
  292. MKSTR("foo/./"),
  293. MKSTR("foo/./bar"),
  294. MKSTR("foo/../"),
  295. MKSTR("foo/../bar"),
  296. MKSTR("c:"),
  297. MKSTR("c:/"),
  298. MKSTR("c:foo"),
  299. MKSTR("c:/foo"),
  300. MKSTR("c:foo/"),
  301. MKSTR("c:/foo/"),
  302. MKSTR("c:/foo/bar"),
  303. MKSTR("prn:"),
  304. MKSTR("c:\\"),
  305. MKSTR("c:\\foo"),
  306. MKSTR("c:foo\\"),
  307. MKSTR("c:\\foo\\"),
  308. MKSTR("c:\\foo/"),
  309. MKSTR("c:/foo\\bar"),
  310. MKSTR("//"),
  311. MKSTR("/finally/we/need/one/really/really/really/really/really/really/really/long/string")
  312. };
  313. const unsigned PathListSize = sizeof(PathList) / sizeof(MultiStringType);
  314. template <class Iter>
  315. Iter IterEnd(Iter B) {
  316. using VT = typename std::iterator_traits<Iter>::value_type;
  317. for (; *B != VT{}; ++B)
  318. ;
  319. return B;
  320. }
  321. template <class CharT>
  322. const CharT* StrEnd(CharT const* P) {
  323. return IterEnd(P);
  324. }
  325. template <class CharT>
  326. std::size_t StrLen(CharT const* P) {
  327. return StrEnd(P) - P;
  328. }
  329. // Testing the allocation behavior of the code_cvt functions requires
  330. // *knowing* that the allocation was not done by "path::__str_".
  331. // This hack forces path to allocate enough memory.
  332. inline void PathReserve(fs::path& p, std::size_t N) {
  333. auto const& native_ref = p.native();
  334. const_cast<std::string&>(native_ref).reserve(N);
  335. }
  336. template <class Iter1, class Iter2>
  337. bool checkCollectionsEqual(
  338. Iter1 start1, Iter1 const end1
  339. , Iter2 start2, Iter2 const end2
  340. )
  341. {
  342. while (start1 != end1 && start2 != end2) {
  343. if (*start1 != *start2) {
  344. return false;
  345. }
  346. ++start1; ++start2;
  347. }
  348. return (start1 == end1 && start2 == end2);
  349. }
  350. template <class Iter1, class Iter2>
  351. bool checkCollectionsEqualBackwards(
  352. Iter1 const start1, Iter1 end1
  353. , Iter2 const start2, Iter2 end2
  354. )
  355. {
  356. while (start1 != end1 && start2 != end2) {
  357. --end1; --end2;
  358. if (*end1 != *end2) {
  359. return false;
  360. }
  361. }
  362. return (start1 == end1 && start2 == end2);
  363. }
  364. // We often need to test that the error_code was cleared if no error occurs
  365. // this function returns an error_code which is set to an error that will
  366. // never be returned by the filesystem functions.
  367. inline std::error_code GetTestEC(unsigned Idx = 0) {
  368. using std::errc;
  369. auto GetErrc = [&]() {
  370. switch (Idx) {
  371. case 0:
  372. return errc::address_family_not_supported;
  373. case 1:
  374. return errc::address_not_available;
  375. case 2:
  376. return errc::address_in_use;
  377. case 3:
  378. return errc::argument_list_too_long;
  379. default:
  380. assert(false && "Idx out of range");
  381. std::abort();
  382. }
  383. };
  384. return std::make_error_code(GetErrc());
  385. }
  386. inline bool ErrorIsImp(const std::error_code& ec,
  387. std::vector<std::errc> const& errors) {
  388. for (auto errc : errors) {
  389. if (ec == std::make_error_code(errc))
  390. return true;
  391. }
  392. return false;
  393. }
  394. template <class... ErrcT>
  395. inline bool ErrorIs(const std::error_code& ec, std::errc First, ErrcT... Rest) {
  396. std::vector<std::errc> errors = {First, Rest...};
  397. return ErrorIsImp(ec, errors);
  398. }
  399. // Provide our own Sleep routine since std::this_thread::sleep_for is not
  400. // available in single-threaded mode.
  401. void SleepFor(std::chrono::seconds dur) {
  402. using namespace std::chrono;
  403. #if defined(_LIBCPP_HAS_NO_MONOTONIC_CLOCK)
  404. using Clock = system_clock;
  405. #else
  406. using Clock = steady_clock;
  407. #endif
  408. const auto wake_time = Clock::now() + dur;
  409. while (Clock::now() < wake_time)
  410. ;
  411. }
  412. inline bool PathEq(fs::path const& LHS, fs::path const& RHS) {
  413. return LHS.native() == RHS.native();
  414. }
  415. struct ExceptionChecker {
  416. std::errc expected_err;
  417. fs::path expected_path1;
  418. fs::path expected_path2;
  419. unsigned num_paths;
  420. const char* func_name;
  421. std::string opt_message;
  422. explicit ExceptionChecker(std::errc first_err, const char* func_name,
  423. std::string opt_msg = {})
  424. : expected_err{first_err}, num_paths(0), func_name(func_name),
  425. opt_message(opt_msg) {}
  426. explicit ExceptionChecker(fs::path p, std::errc first_err,
  427. const char* func_name, std::string opt_msg = {})
  428. : expected_err(first_err), expected_path1(p), num_paths(1),
  429. func_name(func_name), opt_message(opt_msg) {}
  430. explicit ExceptionChecker(fs::path p1, fs::path p2, std::errc first_err,
  431. const char* func_name, std::string opt_msg = {})
  432. : expected_err(first_err), expected_path1(p1), expected_path2(p2),
  433. num_paths(2), func_name(func_name), opt_message(opt_msg) {}
  434. void operator()(fs::filesystem_error const& Err) {
  435. TEST_CHECK(ErrorIsImp(Err.code(), {expected_err}));
  436. TEST_CHECK(Err.path1() == expected_path1);
  437. TEST_CHECK(Err.path2() == expected_path2);
  438. LIBCPP_ONLY(check_libcxx_string(Err));
  439. }
  440. void check_libcxx_string(fs::filesystem_error const& Err) {
  441. std::string message = std::make_error_code(expected_err).message();
  442. std::string additional_msg = "";
  443. if (!opt_message.empty()) {
  444. additional_msg = opt_message + ": ";
  445. }
  446. auto transform_path = [](const fs::path& p) {
  447. if (p.native().empty())
  448. return "\"\"";
  449. return p.c_str();
  450. };
  451. std::string format = [&]() -> std::string {
  452. switch (num_paths) {
  453. case 0:
  454. return format_string("filesystem error: in %s: %s%s", func_name,
  455. additional_msg, message);
  456. case 1:
  457. return format_string("filesystem error: in %s: %s%s [%s]", func_name,
  458. additional_msg, message,
  459. transform_path(expected_path1));
  460. case 2:
  461. return format_string("filesystem error: in %s: %s%s [%s] [%s]",
  462. func_name, additional_msg, message,
  463. transform_path(expected_path1),
  464. transform_path(expected_path2));
  465. default:
  466. TEST_CHECK(false && "unexpected case");
  467. return "";
  468. }
  469. }();
  470. TEST_CHECK(format == Err.what());
  471. if (format != Err.what()) {
  472. fprintf(stderr,
  473. "filesystem_error::what() does not match expected output:\n");
  474. fprintf(stderr, " expected: \"%s\"\n", format.c_str());
  475. fprintf(stderr, " actual: \"%s\"\n\n", Err.what());
  476. }
  477. }
  478. ExceptionChecker(ExceptionChecker const&) = delete;
  479. ExceptionChecker& operator=(ExceptionChecker const&) = delete;
  480. };
  481. #endif /* FILESYSTEM_TEST_HELPER_HPP */