xref: /aosp_15_r20/external/llvm-libc/test/src/stdio/rename_test.cpp (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===-- Unittests for rename ----------------------------------------------===//
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 "include/llvm-libc-macros/linux/sys-stat-macros.h"
10 #include "include/llvm-libc-macros/linux/unistd-macros.h"
11 #include "src/errno/libc_errno.h"
12 #include "src/fcntl/open.h"
13 #include "src/stdio/rename.h"
14 #include "src/unistd/access.h"
15 #include "src/unistd/close.h"
16 #include "test/UnitTest/ErrnoSetterMatcher.h"
17 #include "test/UnitTest/Test.h"
18 
TEST(LlvmLibcRenameTest,CreateAndRenameFile)19 TEST(LlvmLibcRenameTest, CreateAndRenameFile) {
20   // The test strategy is to create a file and rename it, and also verify that
21   // it was renamed.
22   LIBC_NAMESPACE::libc_errno = 0;
23   using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
24   using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
25 
26   constexpr const char *FILENAME0 = "rename.test.file0";
27   auto TEST_FILEPATH0 = libc_make_test_file_path(FILENAME0);
28 
29   int fd = LIBC_NAMESPACE::open(TEST_FILEPATH0, O_WRONLY | O_CREAT, S_IRWXU);
30   ASSERT_ERRNO_SUCCESS();
31   ASSERT_GT(fd, 0);
32   ASSERT_THAT(LIBC_NAMESPACE::close(fd), Succeeds(0));
33   ASSERT_THAT(LIBC_NAMESPACE::access(TEST_FILEPATH0, F_OK), Succeeds(0));
34 
35   constexpr const char *FILENAME1 = "rename.test.file1";
36   auto TEST_FILEPATH1 = libc_make_test_file_path(FILENAME1);
37   ASSERT_THAT(LIBC_NAMESPACE::rename(TEST_FILEPATH0, TEST_FILEPATH1),
38               Succeeds(0));
39   ASSERT_THAT(LIBC_NAMESPACE::access(TEST_FILEPATH1, F_OK), Succeeds(0));
40   ASSERT_THAT(LIBC_NAMESPACE::access(TEST_FILEPATH0, F_OK), Fails(ENOENT));
41 }
42 
TEST(LlvmLibcRenameTest,RenameNonExistent)43 TEST(LlvmLibcRenameTest, RenameNonExistent) {
44   using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
45 
46   constexpr const char *FILENAME1 = "rename.test.file1";
47   auto TEST_FILEPATH1 = libc_make_test_file_path(FILENAME1);
48 
49   ASSERT_THAT(LIBC_NAMESPACE::rename("non-existent", TEST_FILEPATH1),
50               Fails(ENOENT));
51 }
52