1 //===-- Unittests for functions from POSIX dirent.h -----------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "src/__support/CPP/string_view.h"
10 #include "src/dirent/closedir.h"
11 #include "src/dirent/dirfd.h"
12 #include "src/dirent/opendir.h"
13 #include "src/dirent/readdir.h"
14 #include "src/errno/libc_errno.h"
16 #include "test/UnitTest/Test.h"
20 using string_view
= LIBC_NAMESPACE::cpp::string_view
;
22 TEST(LlvmLibcDirentTest
, SimpleOpenAndRead
) {
23 ::DIR *dir
= LIBC_NAMESPACE::opendir("testdata");
24 ASSERT_TRUE(dir
!= nullptr);
25 // The file descriptors 0, 1 and 2 are reserved for standard streams.
26 // So, the file descriptor for the newly opened directory should be
28 ASSERT_GT(LIBC_NAMESPACE::dirfd(dir
), 2);
30 struct ::dirent
*file1
= nullptr, *file2
= nullptr, *dir1
= nullptr,
33 struct ::dirent
*d
= LIBC_NAMESPACE::readdir(dir
);
36 if (string_view(&d
->d_name
[0]) == "file1.txt")
38 if (string_view(&d
->d_name
[0]) == "file2.txt")
40 if (string_view(&d
->d_name
[0]) == "dir1")
42 if (string_view(&d
->d_name
[0]) == "dir2")
46 // Verify that we don't break out of the above loop in error.
47 ASSERT_ERRNO_SUCCESS();
49 ASSERT_TRUE(file1
!= nullptr);
50 ASSERT_TRUE(file2
!= nullptr);
51 ASSERT_TRUE(dir1
!= nullptr);
52 ASSERT_TRUE(dir2
!= nullptr);
54 ASSERT_EQ(LIBC_NAMESPACE::closedir(dir
), 0);
57 TEST(LlvmLibcDirentTest
, OpenNonExistentDir
) {
58 LIBC_NAMESPACE::libc_errno
= 0;
59 ::DIR *dir
= LIBC_NAMESPACE::opendir("___xyz123__.non_existent__");
60 ASSERT_TRUE(dir
== nullptr);
61 ASSERT_ERRNO_EQ(ENOENT
);
62 LIBC_NAMESPACE::libc_errno
= 0;
65 TEST(LlvmLibcDirentTest
, OpenFile
) {
66 LIBC_NAMESPACE::libc_errno
= 0;
67 ::DIR *dir
= LIBC_NAMESPACE::opendir("testdata/file1.txt");
68 ASSERT_TRUE(dir
== nullptr);
69 ASSERT_ERRNO_EQ(ENOTDIR
);
70 LIBC_NAMESPACE::libc_errno
= 0;