dir_reader_posix_unittest.cc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. #include "base/files/dir_reader_posix.h"
  5. #include <fcntl.h>
  6. #include <limits.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <unistd.h>
  11. #include "base/check.h"
  12. #include "base/files/scoped_temp_dir.h"
  13. #include "build/build_config.h"
  14. #include "testing/gtest/include/gtest/gtest.h"
  15. #if BUILDFLAG(IS_ANDROID)
  16. #include "base/os_compat_android.h"
  17. #endif
  18. namespace base {
  19. TEST(DirReaderPosixUnittest, Read) {
  20. static const unsigned kNumFiles = 100;
  21. if (DirReaderPosix::IsFallback())
  22. return;
  23. base::ScopedTempDir temp_dir;
  24. ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  25. const char* dir = temp_dir.GetPath().value().c_str();
  26. ASSERT_TRUE(dir);
  27. char wdbuf[PATH_MAX];
  28. PCHECK(getcwd(wdbuf, PATH_MAX));
  29. PCHECK(chdir(dir) == 0);
  30. for (unsigned i = 0; i < kNumFiles; i++) {
  31. char buf[16];
  32. snprintf(buf, sizeof(buf), "%d", i);
  33. const int fd = open(buf, O_CREAT | O_RDONLY | O_EXCL, 0600);
  34. PCHECK(fd >= 0);
  35. PCHECK(close(fd) == 0);
  36. }
  37. std::set<unsigned> seen;
  38. DirReaderPosix reader(dir);
  39. EXPECT_TRUE(reader.IsValid());
  40. if (!reader.IsValid())
  41. return;
  42. bool seen_dot = false, seen_dotdot = false;
  43. for (; reader.Next(); ) {
  44. if (strcmp(reader.name(), ".") == 0) {
  45. seen_dot = true;
  46. continue;
  47. }
  48. if (strcmp(reader.name(), "..") == 0) {
  49. seen_dotdot = true;
  50. continue;
  51. }
  52. SCOPED_TRACE(testing::Message() << "reader.name(): " << reader.name());
  53. char *endptr;
  54. const unsigned long value = strtoul(reader.name(), &endptr, 10);
  55. EXPECT_FALSE(*endptr);
  56. EXPECT_LT(value, kNumFiles);
  57. EXPECT_EQ(0u, seen.count(value));
  58. seen.insert(value);
  59. }
  60. for (unsigned i = 0; i < kNumFiles; i++) {
  61. char buf[16];
  62. snprintf(buf, sizeof(buf), "%d", i);
  63. PCHECK(unlink(buf) == 0);
  64. }
  65. PCHECK(rmdir(dir) == 0);
  66. PCHECK(chdir(wdbuf) == 0);
  67. EXPECT_TRUE(seen_dot);
  68. EXPECT_TRUE(seen_dotdot);
  69. EXPECT_EQ(kNumFiles, seen.size());
  70. }
  71. } // namespace base