1 //===-- Unittests for functions from POSIX dirent.h -----------------------===//
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/StringView.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
15 #include "utils/UnitTest/Test.h"
16
17 #include <dirent.h>
18 #include <errno.h>
19
20 using StringView = __llvm_libc::cpp::StringView;
21
TEST(LlvmLibcDirentTest,SimpleOpenAndRead)22 TEST(LlvmLibcDirentTest, SimpleOpenAndRead) {
23 ::DIR *dir = __llvm_libc::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
27 // greater than 2.
28 ASSERT_GT(__llvm_libc::dirfd(dir), 2);
29
30 struct ::dirent *file1 = nullptr, *file2 = nullptr, *dir1 = nullptr,
31 *dir2 = nullptr;
32 while (true) {
33 struct ::dirent *d = __llvm_libc::readdir(dir);
34 if (d == nullptr)
35 break;
36 if (StringView(&d->d_name[0]).equals("file1.txt"))
37 file1 = d;
38 if (StringView(&d->d_name[0]).equals("file2.txt"))
39 file2 = d;
40 if (StringView(&d->d_name[0]).equals("dir1"))
41 dir1 = d;
42 if (StringView(&d->d_name[0]).equals("dir2"))
43 dir2 = d;
44 }
45
46 // Verify that we don't break out of the above loop in error.
47 ASSERT_EQ(errno, 0);
48
49 ASSERT_TRUE(file1 != nullptr);
50 ASSERT_TRUE(file2 != nullptr);
51 ASSERT_TRUE(dir1 != nullptr);
52 ASSERT_TRUE(dir2 != nullptr);
53
54 ASSERT_EQ(__llvm_libc::closedir(dir), 0);
55 }
56
TEST(LlvmLibcDirentTest,OpenNonExistentDir)57 TEST(LlvmLibcDirentTest, OpenNonExistentDir) {
58 errno = 0;
59 ::DIR *dir = __llvm_libc::opendir("___xyz123__.non_existent__");
60 ASSERT_TRUE(dir == nullptr);
61 ASSERT_EQ(errno, ENOENT);
62 errno = 0;
63 }
64
TEST(LlvmLibcDirentTest,OpenFile)65 TEST(LlvmLibcDirentTest, OpenFile) {
66 errno = 0;
67 ::DIR *dir = __llvm_libc::opendir("testdata/file1.txt");
68 ASSERT_TRUE(dir == nullptr);
69 ASSERT_EQ(errno, ENOTDIR);
70 errno = 0;
71 }
72