| 1 | //===-- Unittests for readlinkat ------------------------------------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "src/__support/CPP/string_view.h" |
| 10 | #include "src/string/string_utils.h" |
| 11 | #include "src/unistd/readlinkat.h" |
| 12 | #include "src/unistd/symlink.h" |
| 13 | #include "src/unistd/unlink.h" |
| 14 | #include "test/UnitTest/ErrnoCheckingTest.h" |
| 15 | #include "test/UnitTest/ErrnoSetterMatcher.h" |
| 16 | #include "test/UnitTest/Test.h" |
| 17 | |
| 18 | #include "hdr/fcntl_macros.h" |
| 19 | |
| 20 | namespace cpp = LIBC_NAMESPACE::cpp; |
| 21 | using LlvmLibcReadlinkatTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest; |
| 22 | |
| 23 | TEST_F(LlvmLibcReadlinkatTest, CreateAndUnlink) { |
| 24 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds; |
| 25 | constexpr const char *FILENAME = "readlinkat_test_file" ; |
| 26 | auto LINK_VAL = libc_make_test_file_path(FILENAME); |
| 27 | constexpr const char *FILENAME2 = "readlinkat_test_file.link" ; |
| 28 | auto LINK = libc_make_test_file_path(FILENAME2); |
| 29 | |
| 30 | // The test strategy is as follows: |
| 31 | // 1. Create a symlink with value LINK_VAL. |
| 32 | // 2. Read the symlink with readlink. The link value read should be LINK_VAL |
| 33 | // 3. Cleanup the symlink created in step #1. |
| 34 | ASSERT_THAT(LIBC_NAMESPACE::symlink(LINK_VAL, LINK), Succeeds(0)); |
| 35 | |
| 36 | char buf[256]; |
| 37 | ssize_t len = LIBC_NAMESPACE::readlinkat( |
| 38 | AT_FDCWD, LINK, buf, LIBC_NAMESPACE::internal::string_length(FILENAME)); |
| 39 | ASSERT_ERRNO_SUCCESS(); |
| 40 | ASSERT_EQ(cpp::string_view(buf, len), cpp::string_view(LINK_VAL)); |
| 41 | |
| 42 | ASSERT_THAT(LIBC_NAMESPACE::unlink(LINK), Succeeds(0)); |
| 43 | } |
| 44 | |
| 45 | TEST_F(LlvmLibcReadlinkatTest, ReadlinkInNonExistentPath) { |
| 46 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails; |
| 47 | constexpr auto LEN = 8; |
| 48 | char buf[LEN]; |
| 49 | ASSERT_THAT( |
| 50 | LIBC_NAMESPACE::readlinkat(AT_FDCWD, "non-existent-link" , buf, LEN), |
| 51 | Fails<ssize_t>(ENOENT)); |
| 52 | } |
| 53 | |