| 1 | //===-- Unittests for readlink --------------------------------------------===// |
| 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/readlink.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 | namespace cpp = LIBC_NAMESPACE::cpp; |
| 19 | using LlvmLibcReadlinkTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest; |
| 20 | |
| 21 | TEST_F(LlvmLibcReadlinkTest, CreateAndUnlink) { |
| 22 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds; |
| 23 | constexpr const char *FILENAME = "readlink_test_file" ; |
| 24 | auto LINK_VAL = libc_make_test_file_path(FILENAME); |
| 25 | constexpr const char *FILENAME2 = "readlink_test_file.link" ; |
| 26 | auto LINK = libc_make_test_file_path(FILENAME2); |
| 27 | |
| 28 | // The test strategy is as follows: |
| 29 | // 1. Create a symlink with value LINK_VAL. |
| 30 | // 2. Read the symlink with readlink. The link value read should be LINK_VAL |
| 31 | // 3. Cleanup the symlink created in step #1. |
| 32 | ASSERT_THAT(LIBC_NAMESPACE::symlink(LINK_VAL, LINK), Succeeds(0)); |
| 33 | |
| 34 | char buf[256]; |
| 35 | ssize_t len = LIBC_NAMESPACE::readlink( |
| 36 | LINK, buf, LIBC_NAMESPACE::internal::string_length(FILENAME)); |
| 37 | ASSERT_ERRNO_SUCCESS(); |
| 38 | ASSERT_EQ(cpp::string_view(buf, len), cpp::string_view(LINK_VAL)); |
| 39 | |
| 40 | ASSERT_THAT(LIBC_NAMESPACE::unlink(LINK), Succeeds(0)); |
| 41 | } |
| 42 | |
| 43 | TEST_F(LlvmLibcReadlinkTest, ReadlinkInNonExistentPath) { |
| 44 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails; |
| 45 | constexpr auto LEN = 8; |
| 46 | char buf[LEN]; |
| 47 | ASSERT_THAT(LIBC_NAMESPACE::readlink("non-existent-link" , buf, LEN), |
| 48 | Fails<ssize_t>(ENOENT)); |
| 49 | } |
| 50 | |