1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/files/dir_reader_posix.h"
6
7 #include <fcntl.h>
8 #include <limits.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <unistd.h>
13
14 #include "base/files/scoped_temp_dir.h"
15 #include "base/logging.h"
16 #include "build/build_config.h"
17 #include "testing/gtest/include/gtest/gtest.h"
18
19 #if defined(OS_ANDROID)
20 #include "base/os_compat_android.h"
21 #endif
22
23 namespace base {
24
TEST(DirReaderPosixUnittest,Read)25 TEST(DirReaderPosixUnittest, Read) {
26 static const unsigned kNumFiles = 100;
27
28 if (DirReaderPosix::IsFallback())
29 return;
30
31 base::ScopedTempDir temp_dir;
32 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
33 const char* dir = temp_dir.GetPath().value().c_str();
34 ASSERT_TRUE(dir);
35
36 char wdbuf[PATH_MAX];
37 PCHECK(getcwd(wdbuf, PATH_MAX));
38
39 PCHECK(chdir(dir) == 0);
40
41 for (unsigned i = 0; i < kNumFiles; i++) {
42 char buf[16];
43 snprintf(buf, sizeof(buf), "%d", i);
44 const int fd = open(buf, O_CREAT | O_RDONLY | O_EXCL, 0600);
45 PCHECK(fd >= 0);
46 PCHECK(close(fd) == 0);
47 }
48
49 std::set<unsigned> seen;
50
51 DirReaderPosix reader(dir);
52 EXPECT_TRUE(reader.IsValid());
53
54 if (!reader.IsValid())
55 return;
56
57 bool seen_dot = false, seen_dotdot = false;
58
59 for (; reader.Next(); ) {
60 if (strcmp(reader.name(), ".") == 0) {
61 seen_dot = true;
62 continue;
63 }
64 if (strcmp(reader.name(), "..") == 0) {
65 seen_dotdot = true;
66 continue;
67 }
68
69 SCOPED_TRACE(testing::Message() << "reader.name(): " << reader.name());
70
71 char *endptr;
72 const unsigned long value = strtoul(reader.name(), &endptr, 10);
73
74 EXPECT_FALSE(*endptr);
75 EXPECT_LT(value, kNumFiles);
76 EXPECT_EQ(0u, seen.count(value));
77 seen.insert(value);
78 }
79
80 for (unsigned i = 0; i < kNumFiles; i++) {
81 char buf[16];
82 snprintf(buf, sizeof(buf), "%d", i);
83 PCHECK(unlink(buf) == 0);
84 }
85
86 PCHECK(rmdir(dir) == 0);
87
88 PCHECK(chdir(wdbuf) == 0);
89
90 EXPECT_TRUE(seen_dot);
91 EXPECT_TRUE(seen_dotdot);
92 EXPECT_EQ(kNumFiles, seen.size());
93 }
94
95 } // namespace base
96