xref: /llvm-project/libc/test/src/unistd/chdir_test.cpp (revision 67de5381a3ebe1cacbef4f0f7b382b6a40841608)
1 //===-- Unittests for chdir -----------------------------------------------===//
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/chdir.h"
12 #include "src/unistd/close.h"
13 #include "test/ErrnoSetterMatcher.h"
14 #include "test/UnitTest/Test.h"
15 #include "utils/testutils/FDReader.h"
16 
17 #include <fcntl.h>
18 
19 TEST(LlvmLibcChdirTest, ChangeAndOpen) {
20   // The idea of this test is that we will first open an existing test file
21   // without changing the directory to make sure it exists. Next, we change
22   // directory and open the same file to make sure that the "chdir" operation
23   // succeeded.
24   using __llvm_libc::testing::ErrnoSetterMatcher::Succeeds;
25   constexpr const char *TEST_DIR = "testdata";
26   constexpr const char *TEST_FILE = "testdata/chdir.test";
27   constexpr const char *TEST_FILE_BASE = "chdir.test";
28   libc_errno = 0;
29 
30   int fd = __llvm_libc::open(TEST_FILE, O_PATH);
31   ASSERT_GT(fd, 0);
32   ASSERT_EQ(libc_errno, 0);
33   ASSERT_THAT(__llvm_libc::close(fd), Succeeds(0));
34 
35   ASSERT_THAT(__llvm_libc::chdir(TEST_DIR), Succeeds(0));
36   fd = __llvm_libc::open(TEST_FILE_BASE, O_PATH);
37   ASSERT_GT(fd, 0);
38   ASSERT_EQ(libc_errno, 0);
39   ASSERT_THAT(__llvm_libc::close(fd), Succeeds(0));
40 }
41 
42 TEST(LlvmLibcChdirTest, ChangeToNonExistentDir) {
43   libc_errno = 0;
44   using __llvm_libc::testing::ErrnoSetterMatcher::Fails;
45   ASSERT_THAT(__llvm_libc::chdir("non-existent-dir"), Fails(ENOENT));
46   libc_errno = 0;
47 }
48