tfarina@chromium.org | 4cdd38e | 2011-06-29 07:56:33 +0900 | [diff] [blame^] | 1 | // Copyright (c) 2011 The Chromium Authors. All rights reserved. |
agl@chromium.org | 4300a31 | 2010-03-12 00:25:54 +0900 | [diff] [blame] | 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/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/logging.h" |
| 14 | #include "testing/gtest/include/gtest/gtest.h" |
| 15 | |
tfarina@chromium.org | 4cdd38e | 2011-06-29 07:56:33 +0900 | [diff] [blame^] | 16 | namespace base { |
agl@chromium.org | 4300a31 | 2010-03-12 00:25:54 +0900 | [diff] [blame] | 17 | |
| 18 | TEST(DirReaderPosixUnittest, Read) { |
| 19 | static const unsigned kNumFiles = 100; |
| 20 | |
| 21 | if (DirReaderPosix::IsFallback()) |
| 22 | return; |
| 23 | |
| 24 | char kDirTemplate[] = "/tmp/org.chromium.dir-reader-posix-XXXXXX"; |
| 25 | const char* dir = mkdtemp(kDirTemplate); |
| 26 | CHECK(dir); |
| 27 | |
| 28 | const int prev_wd = open(".", O_RDONLY | O_DIRECTORY); |
| 29 | CHECK_GE(prev_wd, 0); |
| 30 | |
| 31 | PCHECK(chdir(dir) == 0); |
| 32 | |
| 33 | for (unsigned i = 0; i < kNumFiles; i++) { |
| 34 | char buf[16]; |
| 35 | snprintf(buf, sizeof(buf), "%d", i); |
| 36 | const int fd = open(buf, O_CREAT | O_RDONLY | O_EXCL, 0600); |
| 37 | PCHECK(fd >= 0); |
| 38 | PCHECK(close(fd) == 0); |
| 39 | } |
| 40 | |
| 41 | std::set<unsigned> seen; |
| 42 | |
| 43 | DirReaderPosix reader(dir); |
| 44 | EXPECT_TRUE(reader.IsValid()); |
| 45 | |
| 46 | if (!reader.IsValid()) |
| 47 | return; |
| 48 | |
| 49 | bool seen_dot = false, seen_dotdot = false; |
| 50 | |
| 51 | for (; reader.Next(); ) { |
| 52 | if (strcmp(reader.name(), ".") == 0) { |
| 53 | seen_dot = true; |
| 54 | continue; |
| 55 | } |
| 56 | if (strcmp(reader.name(), "..") == 0) { |
| 57 | seen_dotdot = true; |
| 58 | continue; |
| 59 | } |
| 60 | |
| 61 | SCOPED_TRACE(testing::Message() << "reader.name(): " << reader.name()); |
| 62 | |
| 63 | char *endptr; |
| 64 | const unsigned long value = strtoul(reader.name(), &endptr, 10); |
| 65 | |
| 66 | EXPECT_FALSE(*endptr); |
| 67 | EXPECT_LT(value, kNumFiles); |
| 68 | EXPECT_EQ(0u, seen.count(value)); |
| 69 | seen.insert(value); |
| 70 | } |
| 71 | |
| 72 | for (unsigned i = 0; i < kNumFiles; i++) { |
| 73 | char buf[16]; |
| 74 | snprintf(buf, sizeof(buf), "%d", i); |
| 75 | PCHECK(unlink(buf) == 0); |
| 76 | } |
| 77 | |
| 78 | PCHECK(rmdir(dir) == 0); |
| 79 | |
| 80 | PCHECK(fchdir(prev_wd) == 0); |
| 81 | PCHECK(close(prev_wd) == 0); |
| 82 | |
| 83 | EXPECT_TRUE(seen_dot); |
| 84 | EXPECT_TRUE(seen_dotdot); |
| 85 | EXPECT_EQ(kNumFiles, seen.size()); |
| 86 | } |
| 87 | |
tfarina@chromium.org | 4cdd38e | 2011-06-29 07:56:33 +0900 | [diff] [blame^] | 88 | } // namespace base |