xref: /aosp_15_r20/external/llvm-libc/test/src/unistd/readlink_test.cpp (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
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/errno/libc_errno.h"
11 #include "src/string/string_utils.h"
12 #include "src/unistd/readlink.h"
13 #include "src/unistd/symlink.h"
14 #include "src/unistd/unlink.h"
15 #include "test/UnitTest/ErrnoSetterMatcher.h"
16 #include "test/UnitTest/Test.h"
17 
18 namespace cpp = LIBC_NAMESPACE::cpp;
19 
TEST(LlvmLibcReadlinkTest,CreateAndUnlink)20 TEST(LlvmLibcReadlinkTest, CreateAndUnlink) {
21   using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
22   constexpr const char *FILENAME = "readlink_test_file";
23   auto LINK_VAL = libc_make_test_file_path(FILENAME);
24   constexpr const char *FILENAME2 = "readlink_test_file.link";
25   auto LINK = libc_make_test_file_path(FILENAME2);
26   LIBC_NAMESPACE::libc_errno = 0;
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 
TEST(LlvmLibcReadlinkTest,ReadlinkInNonExistentPath)43 TEST(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(ENOENT));
49 }
50