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/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"
15
16#include "test/UnitTest/Test.h"
17
18#include <dirent.h>
19
20using string_view = LIBC_NAMESPACE::cpp::string_view;
21
22TEST(LlvmLibcDirentTest, SimpleOpenAndRead) {
23 ::DIR *dir = LIBC_NAMESPACE::opendir(name: "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(LIBC_NAMESPACE::dirfd(dir), 2);
29
30 struct ::dirent *file1 = nullptr, *file2 = nullptr, *dir1 = nullptr,
31 *dir2 = nullptr;
32 while (true) {
33 struct ::dirent *d = LIBC_NAMESPACE::readdir(dir);
34 if (d == nullptr)
35 break;
36 if (string_view(&d->d_name[0]) == "file1.txt")
37 file1 = d;
38 if (string_view(&d->d_name[0]) == "file2.txt")
39 file2 = d;
40 if (string_view(&d->d_name[0]) == "dir1")
41 dir1 = d;
42 if (string_view(&d->d_name[0]) == "dir2")
43 dir2 = d;
44 }
45
46 // Verify that we don't break out of the above loop in error.
47 ASSERT_ERRNO_SUCCESS();
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(LIBC_NAMESPACE::closedir(dir), 0);
55}
56
57TEST(LlvmLibcDirentTest, OpenNonExistentDir) {
58 LIBC_NAMESPACE::libc_errno = 0;
59 ::DIR *dir = LIBC_NAMESPACE::opendir(name: "___xyz123__.non_existent__");
60 ASSERT_TRUE(dir == nullptr);
61 ASSERT_ERRNO_EQ(ENOENT);
62 LIBC_NAMESPACE::libc_errno = 0;
63}
64
65TEST(LlvmLibcDirentTest, OpenFile) {
66 LIBC_NAMESPACE::libc_errno = 0;
67 ::DIR *dir = LIBC_NAMESPACE::opendir(name: "testdata/file1.txt");
68 ASSERT_TRUE(dir == nullptr);
69 ASSERT_ERRNO_EQ(ENOTDIR);
70 LIBC_NAMESPACE::libc_errno = 0;
71}
72

source code of libc/test/src/dirent/dirent_test.cpp