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 <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <unistd.h>
12 
13 #include "base/files/scoped_temp_dir.h"
14 #include "base/logging.h"
15 #include "build/build_config.h"
16 #include "testing/gtest/include/gtest/gtest.h"
17 
18 #if defined(OS_ANDROID)
19 #include "base/os_compat_android.h"
20 #endif
21 
22 namespace base {
23 
TEST(DirReaderPosixUnittest,Read)24 TEST(DirReaderPosixUnittest, Read) {
25   static const unsigned kNumFiles = 100;
26 
27   if (DirReaderPosix::IsFallback())
28     return;
29 
30   base::ScopedTempDir temp_dir;
31   ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
32   const char* dir = temp_dir.path().value().c_str();
33   ASSERT_TRUE(dir);
34 
35   const int prev_wd = open(".", O_RDONLY | O_DIRECTORY);
36   DCHECK_GE(prev_wd, 0);
37 
38   PCHECK(chdir(dir) == 0);
39 
40   for (unsigned i = 0; i < kNumFiles; i++) {
41     char buf[16];
42     snprintf(buf, sizeof(buf), "%d", i);
43     const int fd = open(buf, O_CREAT | O_RDONLY | O_EXCL, 0600);
44     PCHECK(fd >= 0);
45     PCHECK(close(fd) == 0);
46   }
47 
48   std::set<unsigned> seen;
49 
50   DirReaderPosix reader(dir);
51   EXPECT_TRUE(reader.IsValid());
52 
53   if (!reader.IsValid())
54     return;
55 
56   bool seen_dot = false, seen_dotdot = false;
57 
58   for (; reader.Next(); ) {
59     if (strcmp(reader.name(), ".") == 0) {
60       seen_dot = true;
61       continue;
62     }
63     if (strcmp(reader.name(), "..") == 0) {
64       seen_dotdot = true;
65       continue;
66     }
67 
68     SCOPED_TRACE(testing::Message() << "reader.name(): " << reader.name());
69 
70     char *endptr;
71     const unsigned long value = strtoul(reader.name(), &endptr, 10);
72 
73     EXPECT_FALSE(*endptr);
74     EXPECT_LT(value, kNumFiles);
75     EXPECT_EQ(0u, seen.count(value));
76     seen.insert(value);
77   }
78 
79   for (unsigned i = 0; i < kNumFiles; i++) {
80     char buf[16];
81     snprintf(buf, sizeof(buf), "%d", i);
82     PCHECK(unlink(buf) == 0);
83   }
84 
85   PCHECK(rmdir(dir) == 0);
86 
87   PCHECK(fchdir(prev_wd) == 0);
88   PCHECK(close(prev_wd) == 0);
89 
90   EXPECT_TRUE(seen_dot);
91   EXPECT_TRUE(seen_dotdot);
92   EXPECT_EQ(kNumFiles, seen.size());
93 }
94 
95 }  // namespace base
96