1 | //===-- Unittests for fchdir ----------------------------------------------===// |
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/errno/libc_errno.h" |
10 | #include "src/fcntl/open.h" |
11 | #include "src/unistd/close.h" |
12 | #include "src/unistd/fchdir.h" |
13 | #include "test/UnitTest/ErrnoSetterMatcher.h" |
14 | #include "test/UnitTest/Test.h" |
15 | |
16 | #include <fcntl.h> |
17 | |
18 | TEST(LlvmLibcChdirTest, ChangeAndOpen) { |
19 | // The idea of this test is that we will first open an existing test file |
20 | // without changing the directory to make sure it exists. Next, we change |
21 | // directory and open the same file to make sure that the "fchdir" operation |
22 | // succeeded. |
23 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds; |
24 | constexpr const char *FILENAME = "testdata" ; |
25 | auto TEST_DIR = libc_make_test_file_path(FILENAME); |
26 | constexpr const char *FILENAME2 = "testdata/fchdir.test" ; |
27 | auto TEST_FILE = libc_make_test_file_path(FILENAME2); |
28 | constexpr const char *FILENAME3 = "fchdir.test" ; |
29 | auto TEST_FILE_BASE = libc_make_test_file_path(FILENAME3); |
30 | LIBC_NAMESPACE::libc_errno = 0; |
31 | |
32 | int dir_fd = LIBC_NAMESPACE::open(path: TEST_DIR, O_DIRECTORY); |
33 | ASSERT_GT(dir_fd, 0); |
34 | ASSERT_ERRNO_SUCCESS(); |
35 | int file_fd = LIBC_NAMESPACE::open(path: TEST_FILE, O_PATH); |
36 | ASSERT_GT(file_fd, 0); |
37 | ASSERT_ERRNO_SUCCESS(); |
38 | ASSERT_THAT(LIBC_NAMESPACE::close(file_fd), Succeeds(0)); |
39 | |
40 | ASSERT_THAT(LIBC_NAMESPACE::fchdir(dir_fd), Succeeds(0)); |
41 | file_fd = LIBC_NAMESPACE::open(path: TEST_FILE_BASE, O_PATH); |
42 | ASSERT_GT(file_fd, 0); |
43 | ASSERT_ERRNO_SUCCESS(); |
44 | ASSERT_THAT(LIBC_NAMESPACE::close(file_fd), Succeeds(0)); |
45 | ASSERT_THAT(LIBC_NAMESPACE::close(dir_fd), Succeeds(0)); |
46 | } |
47 | |
48 | TEST(LlvmLibcChdirTest, ChangeToNonExistentDir) { |
49 | using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails; |
50 | LIBC_NAMESPACE::libc_errno = 0; |
51 | ASSERT_EQ(LIBC_NAMESPACE::fchdir(0), -1); |
52 | ASSERT_ERRNO_FAILURE(); |
53 | LIBC_NAMESPACE::libc_errno = 0; |
54 | } |
55 | |