Roll src/third_party/WebKit d9c6159:8139f33 (svn 201974:201975)
[chromium-blink-merge.git] / base / files / file_util_unittest.cc
blob4b95dbb4bdf7455aeac3abde84b168fcee0b5c95
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.
5 #include "build/build_config.h"
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #include <shellapi.h>
10 #include <shlobj.h>
11 #include <tchar.h>
12 #include <winioctl.h>
13 #endif
15 #if defined(OS_POSIX)
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <unistd.h>
19 #endif
21 #include <algorithm>
22 #include <fstream>
23 #include <set>
24 #include <vector>
26 #include "base/base_paths.h"
27 #include "base/files/file_enumerator.h"
28 #include "base/files/file_path.h"
29 #include "base/files/file_util.h"
30 #include "base/files/scoped_file.h"
31 #include "base/files/scoped_temp_dir.h"
32 #include "base/path_service.h"
33 #include "base/strings/string_util.h"
34 #include "base/strings/utf_string_conversions.h"
35 #include "base/test/test_file_util.h"
36 #include "base/threading/platform_thread.h"
37 #include "testing/gtest/include/gtest/gtest.h"
38 #include "testing/platform_test.h"
40 #if defined(OS_WIN)
41 #include "base/win/scoped_handle.h"
42 #include "base/win/windows_version.h"
43 #endif
45 #if defined(OS_ANDROID)
46 #include "base/android/content_uri_utils.h"
47 #endif
49 // This macro helps avoid wrapped lines in the test structs.
50 #define FPL(x) FILE_PATH_LITERAL(x)
52 namespace base {
54 namespace {
56 // To test that NormalizeFilePath() deals with NTFS reparse points correctly,
57 // we need functions to create and delete reparse points.
58 #if defined(OS_WIN)
59 typedef struct _REPARSE_DATA_BUFFER {
60 ULONG ReparseTag;
61 USHORT ReparseDataLength;
62 USHORT Reserved;
63 union {
64 struct {
65 USHORT SubstituteNameOffset;
66 USHORT SubstituteNameLength;
67 USHORT PrintNameOffset;
68 USHORT PrintNameLength;
69 ULONG Flags;
70 WCHAR PathBuffer[1];
71 } SymbolicLinkReparseBuffer;
72 struct {
73 USHORT SubstituteNameOffset;
74 USHORT SubstituteNameLength;
75 USHORT PrintNameOffset;
76 USHORT PrintNameLength;
77 WCHAR PathBuffer[1];
78 } MountPointReparseBuffer;
79 struct {
80 UCHAR DataBuffer[1];
81 } GenericReparseBuffer;
83 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
85 // Sets a reparse point. |source| will now point to |target|. Returns true if
86 // the call succeeds, false otherwise.
87 bool SetReparsePoint(HANDLE source, const FilePath& target_path) {
88 std::wstring kPathPrefix = L"\\??\\";
89 std::wstring target_str;
90 // The juction will not work if the target path does not start with \??\ .
91 if (kPathPrefix != target_path.value().substr(0, kPathPrefix.size()))
92 target_str += kPathPrefix;
93 target_str += target_path.value();
94 const wchar_t* target = target_str.c_str();
95 USHORT size_target = static_cast<USHORT>(wcslen(target)) * sizeof(target[0]);
96 char buffer[2000] = {0};
97 DWORD returned;
99 REPARSE_DATA_BUFFER* data = reinterpret_cast<REPARSE_DATA_BUFFER*>(buffer);
101 data->ReparseTag = 0xa0000003;
102 memcpy(data->MountPointReparseBuffer.PathBuffer, target, size_target + 2);
104 data->MountPointReparseBuffer.SubstituteNameLength = size_target;
105 data->MountPointReparseBuffer.PrintNameOffset = size_target + 2;
106 data->ReparseDataLength = size_target + 4 + 8;
108 int data_size = data->ReparseDataLength + 8;
110 if (!DeviceIoControl(source, FSCTL_SET_REPARSE_POINT, &buffer, data_size,
111 NULL, 0, &returned, NULL)) {
112 return false;
114 return true;
117 // Delete the reparse point referenced by |source|. Returns true if the call
118 // succeeds, false otherwise.
119 bool DeleteReparsePoint(HANDLE source) {
120 DWORD returned;
121 REPARSE_DATA_BUFFER data = {0};
122 data.ReparseTag = 0xa0000003;
123 if (!DeviceIoControl(source, FSCTL_DELETE_REPARSE_POINT, &data, 8, NULL, 0,
124 &returned, NULL)) {
125 return false;
127 return true;
130 // Manages a reparse point for a test.
131 class ReparsePoint {
132 public:
133 // Creates a reparse point from |source| (an empty directory) to |target|.
134 ReparsePoint(const FilePath& source, const FilePath& target) {
135 dir_.Set(
136 ::CreateFile(source.value().c_str(),
137 FILE_ALL_ACCESS,
138 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
139 NULL,
140 OPEN_EXISTING,
141 FILE_FLAG_BACKUP_SEMANTICS, // Needed to open a directory.
142 NULL));
143 created_ = dir_.IsValid() && SetReparsePoint(dir_.Get(), target);
146 ~ReparsePoint() {
147 if (created_)
148 DeleteReparsePoint(dir_.Get());
151 bool IsValid() { return created_; }
153 private:
154 win::ScopedHandle dir_;
155 bool created_;
156 DISALLOW_COPY_AND_ASSIGN(ReparsePoint);
159 #endif
161 #if defined(OS_POSIX)
162 // Provide a simple way to change the permissions bits on |path| in tests.
163 // ASSERT failures will return, but not stop the test. Caller should wrap
164 // calls to this function in ASSERT_NO_FATAL_FAILURE().
165 void ChangePosixFilePermissions(const FilePath& path,
166 int mode_bits_to_set,
167 int mode_bits_to_clear) {
168 ASSERT_FALSE(mode_bits_to_set & mode_bits_to_clear)
169 << "Can't set and clear the same bits.";
171 int mode = 0;
172 ASSERT_TRUE(GetPosixFilePermissions(path, &mode));
173 mode |= mode_bits_to_set;
174 mode &= ~mode_bits_to_clear;
175 ASSERT_TRUE(SetPosixFilePermissions(path, mode));
177 #endif // defined(OS_POSIX)
179 const wchar_t bogus_content[] = L"I'm cannon fodder.";
181 const int FILES_AND_DIRECTORIES =
182 FileEnumerator::FILES | FileEnumerator::DIRECTORIES;
184 // file_util winds up using autoreleased objects on the Mac, so this needs
185 // to be a PlatformTest
186 class FileUtilTest : public PlatformTest {
187 protected:
188 void SetUp() override {
189 PlatformTest::SetUp();
190 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
193 ScopedTempDir temp_dir_;
196 // Collects all the results from the given file enumerator, and provides an
197 // interface to query whether a given file is present.
198 class FindResultCollector {
199 public:
200 explicit FindResultCollector(FileEnumerator* enumerator) {
201 FilePath cur_file;
202 while (!(cur_file = enumerator->Next()).value().empty()) {
203 FilePath::StringType path = cur_file.value();
204 // The file should not be returned twice.
205 EXPECT_TRUE(files_.end() == files_.find(path))
206 << "Same file returned twice";
208 // Save for later.
209 files_.insert(path);
213 // Returns true if the enumerator found the file.
214 bool HasFile(const FilePath& file) const {
215 return files_.find(file.value()) != files_.end();
218 int size() {
219 return static_cast<int>(files_.size());
222 private:
223 std::set<FilePath::StringType> files_;
226 // Simple function to dump some text into a new file.
227 void CreateTextFile(const FilePath& filename,
228 const std::wstring& contents) {
229 std::wofstream file;
230 file.open(filename.value().c_str());
231 ASSERT_TRUE(file.is_open());
232 file << contents;
233 file.close();
236 // Simple function to take out some text from a file.
237 std::wstring ReadTextFile(const FilePath& filename) {
238 wchar_t contents[64];
239 std::wifstream file;
240 file.open(filename.value().c_str());
241 EXPECT_TRUE(file.is_open());
242 file.getline(contents, arraysize(contents));
243 file.close();
244 return std::wstring(contents);
247 TEST_F(FileUtilTest, FileAndDirectorySize) {
248 // Create three files of 20, 30 and 3 chars (utf8). ComputeDirectorySize
249 // should return 53 bytes.
250 FilePath file_01 = temp_dir_.path().Append(FPL("The file 01.txt"));
251 CreateTextFile(file_01, L"12345678901234567890");
252 int64 size_f1 = 0;
253 ASSERT_TRUE(GetFileSize(file_01, &size_f1));
254 EXPECT_EQ(20ll, size_f1);
256 FilePath subdir_path = temp_dir_.path().Append(FPL("Level2"));
257 CreateDirectory(subdir_path);
259 FilePath file_02 = subdir_path.Append(FPL("The file 02.txt"));
260 CreateTextFile(file_02, L"123456789012345678901234567890");
261 int64 size_f2 = 0;
262 ASSERT_TRUE(GetFileSize(file_02, &size_f2));
263 EXPECT_EQ(30ll, size_f2);
265 FilePath subsubdir_path = subdir_path.Append(FPL("Level3"));
266 CreateDirectory(subsubdir_path);
268 FilePath file_03 = subsubdir_path.Append(FPL("The file 03.txt"));
269 CreateTextFile(file_03, L"123");
271 int64 computed_size = ComputeDirectorySize(temp_dir_.path());
272 EXPECT_EQ(size_f1 + size_f2 + 3, computed_size);
275 TEST_F(FileUtilTest, NormalizeFilePathBasic) {
276 // Create a directory under the test dir. Because we create it,
277 // we know it is not a link.
278 FilePath file_a_path = temp_dir_.path().Append(FPL("file_a"));
279 FilePath dir_path = temp_dir_.path().Append(FPL("dir"));
280 FilePath file_b_path = dir_path.Append(FPL("file_b"));
281 CreateDirectory(dir_path);
283 FilePath normalized_file_a_path, normalized_file_b_path;
284 ASSERT_FALSE(PathExists(file_a_path));
285 ASSERT_FALSE(NormalizeFilePath(file_a_path, &normalized_file_a_path))
286 << "NormalizeFilePath() should fail on nonexistent paths.";
288 CreateTextFile(file_a_path, bogus_content);
289 ASSERT_TRUE(PathExists(file_a_path));
290 ASSERT_TRUE(NormalizeFilePath(file_a_path, &normalized_file_a_path));
292 CreateTextFile(file_b_path, bogus_content);
293 ASSERT_TRUE(PathExists(file_b_path));
294 ASSERT_TRUE(NormalizeFilePath(file_b_path, &normalized_file_b_path));
296 // Beacuse this test created |dir_path|, we know it is not a link
297 // or junction. So, the real path of the directory holding file a
298 // must be the parent of the path holding file b.
299 ASSERT_TRUE(normalized_file_a_path.DirName()
300 .IsParent(normalized_file_b_path.DirName()));
303 #if defined(OS_WIN)
305 TEST_F(FileUtilTest, NormalizeFilePathReparsePoints) {
306 // Build the following directory structure:
308 // temp_dir
309 // |-> base_a
310 // | |-> sub_a
311 // | |-> file.txt
312 // | |-> long_name___... (Very long name.)
313 // | |-> sub_long
314 // | |-> deep.txt
315 // |-> base_b
316 // |-> to_sub_a (reparse point to temp_dir\base_a\sub_a)
317 // |-> to_base_b (reparse point to temp_dir\base_b)
318 // |-> to_sub_long (reparse point to temp_dir\sub_a\long_name_\sub_long)
320 FilePath base_a = temp_dir_.path().Append(FPL("base_a"));
321 #if defined(OS_WIN)
322 // TEMP can have a lower case drive letter.
323 string16 temp_base_a = base_a.value();
324 ASSERT_FALSE(temp_base_a.empty());
325 *temp_base_a.begin() = ToUpperASCII(*temp_base_a.begin());
326 base_a = FilePath(temp_base_a);
327 #endif
328 ASSERT_TRUE(CreateDirectory(base_a));
330 FilePath sub_a = base_a.Append(FPL("sub_a"));
331 ASSERT_TRUE(CreateDirectory(sub_a));
333 FilePath file_txt = sub_a.Append(FPL("file.txt"));
334 CreateTextFile(file_txt, bogus_content);
336 // Want a directory whose name is long enough to make the path to the file
337 // inside just under MAX_PATH chars. This will be used to test that when
338 // a junction expands to a path over MAX_PATH chars in length,
339 // NormalizeFilePath() fails without crashing.
340 FilePath sub_long_rel(FPL("sub_long"));
341 FilePath deep_txt(FPL("deep.txt"));
343 int target_length = MAX_PATH;
344 target_length -= (sub_a.value().length() + 1); // +1 for the sepperator '\'.
345 target_length -= (sub_long_rel.Append(deep_txt).value().length() + 1);
346 // Without making the path a bit shorter, CreateDirectory() fails.
347 // the resulting path is still long enough to hit the failing case in
348 // NormalizePath().
349 const int kCreateDirLimit = 4;
350 target_length -= kCreateDirLimit;
351 FilePath::StringType long_name_str = FPL("long_name_");
352 long_name_str.resize(target_length, '_');
354 FilePath long_name = sub_a.Append(FilePath(long_name_str));
355 FilePath deep_file = long_name.Append(sub_long_rel).Append(deep_txt);
356 ASSERT_EQ(MAX_PATH - kCreateDirLimit, deep_file.value().length());
358 FilePath sub_long = deep_file.DirName();
359 ASSERT_TRUE(CreateDirectory(sub_long));
360 CreateTextFile(deep_file, bogus_content);
362 FilePath base_b = temp_dir_.path().Append(FPL("base_b"));
363 ASSERT_TRUE(CreateDirectory(base_b));
365 FilePath to_sub_a = base_b.Append(FPL("to_sub_a"));
366 ASSERT_TRUE(CreateDirectory(to_sub_a));
367 FilePath normalized_path;
369 ReparsePoint reparse_to_sub_a(to_sub_a, sub_a);
370 ASSERT_TRUE(reparse_to_sub_a.IsValid());
372 FilePath to_base_b = base_b.Append(FPL("to_base_b"));
373 ASSERT_TRUE(CreateDirectory(to_base_b));
374 ReparsePoint reparse_to_base_b(to_base_b, base_b);
375 ASSERT_TRUE(reparse_to_base_b.IsValid());
377 FilePath to_sub_long = base_b.Append(FPL("to_sub_long"));
378 ASSERT_TRUE(CreateDirectory(to_sub_long));
379 ReparsePoint reparse_to_sub_long(to_sub_long, sub_long);
380 ASSERT_TRUE(reparse_to_sub_long.IsValid());
382 // Normalize a junction free path: base_a\sub_a\file.txt .
383 ASSERT_TRUE(NormalizeFilePath(file_txt, &normalized_path));
384 ASSERT_STREQ(file_txt.value().c_str(), normalized_path.value().c_str());
386 // Check that the path base_b\to_sub_a\file.txt can be normalized to exclude
387 // the junction to_sub_a.
388 ASSERT_TRUE(NormalizeFilePath(to_sub_a.Append(FPL("file.txt")),
389 &normalized_path));
390 ASSERT_STREQ(file_txt.value().c_str(), normalized_path.value().c_str());
392 // Check that the path base_b\to_base_b\to_base_b\to_sub_a\file.txt can be
393 // normalized to exclude junctions to_base_b and to_sub_a .
394 ASSERT_TRUE(NormalizeFilePath(base_b.Append(FPL("to_base_b"))
395 .Append(FPL("to_base_b"))
396 .Append(FPL("to_sub_a"))
397 .Append(FPL("file.txt")),
398 &normalized_path));
399 ASSERT_STREQ(file_txt.value().c_str(), normalized_path.value().c_str());
401 // A long enough path will cause NormalizeFilePath() to fail. Make a long
402 // path using to_base_b many times, and check that paths long enough to fail
403 // do not cause a crash.
404 FilePath long_path = base_b;
405 const int kLengthLimit = MAX_PATH + 200;
406 while (long_path.value().length() <= kLengthLimit) {
407 long_path = long_path.Append(FPL("to_base_b"));
409 long_path = long_path.Append(FPL("to_sub_a"))
410 .Append(FPL("file.txt"));
412 ASSERT_FALSE(NormalizeFilePath(long_path, &normalized_path));
414 // Normalizing the junction to deep.txt should fail, because the expanded
415 // path to deep.txt is longer than MAX_PATH.
416 ASSERT_FALSE(NormalizeFilePath(to_sub_long.Append(deep_txt),
417 &normalized_path));
419 // Delete the reparse points, and see that NormalizeFilePath() fails
420 // to traverse them.
423 ASSERT_FALSE(NormalizeFilePath(to_sub_a.Append(FPL("file.txt")),
424 &normalized_path));
427 TEST_F(FileUtilTest, DevicePathToDriveLetter) {
428 // Get a drive letter.
429 string16 real_drive_letter =
430 ToUpperASCII(temp_dir_.path().value().substr(0, 2));
431 if (!isalpha(real_drive_letter[0]) || ':' != real_drive_letter[1]) {
432 LOG(ERROR) << "Can't get a drive letter to test with.";
433 return;
436 // Get the NT style path to that drive.
437 wchar_t device_path[MAX_PATH] = {'\0'};
438 ASSERT_TRUE(
439 ::QueryDosDevice(real_drive_letter.c_str(), device_path, MAX_PATH));
440 FilePath actual_device_path(device_path);
441 FilePath win32_path;
443 // Run DevicePathToDriveLetterPath() on the NT style path we got from
444 // QueryDosDevice(). Expect the drive letter we started with.
445 ASSERT_TRUE(DevicePathToDriveLetterPath(actual_device_path, &win32_path));
446 ASSERT_EQ(real_drive_letter, win32_path.value());
448 // Add some directories to the path. Expect those extra path componenets
449 // to be preserved.
450 FilePath kRelativePath(FPL("dir1\\dir2\\file.txt"));
451 ASSERT_TRUE(DevicePathToDriveLetterPath(
452 actual_device_path.Append(kRelativePath),
453 &win32_path));
454 EXPECT_EQ(FilePath(real_drive_letter + L"\\").Append(kRelativePath).value(),
455 win32_path.value());
457 // Deform the real path so that it is invalid by removing the last four
458 // characters. The way windows names devices that are hard disks
459 // (\Device\HardDiskVolume${NUMBER}) guarantees that the string is longer
460 // than three characters. The only way the truncated string could be a
461 // real drive is if more than 10^3 disks are mounted:
462 // \Device\HardDiskVolume10000 would be truncated to \Device\HardDiskVolume1
463 // Check that DevicePathToDriveLetterPath fails.
464 int path_length = actual_device_path.value().length();
465 int new_length = path_length - 4;
466 ASSERT_LT(0, new_length);
467 FilePath prefix_of_real_device_path(
468 actual_device_path.value().substr(0, new_length));
469 ASSERT_FALSE(DevicePathToDriveLetterPath(prefix_of_real_device_path,
470 &win32_path));
472 ASSERT_FALSE(DevicePathToDriveLetterPath(
473 prefix_of_real_device_path.Append(kRelativePath),
474 &win32_path));
476 // Deform the real path so that it is invalid by adding some characters. For
477 // example, if C: maps to \Device\HardDiskVolume8, then we simulate a
478 // request for the drive letter whose native path is
479 // \Device\HardDiskVolume812345 . We assume such a device does not exist,
480 // because drives are numbered in order and mounting 112345 hard disks will
481 // never happen.
482 const FilePath::StringType kExtraChars = FPL("12345");
484 FilePath real_device_path_plus_numbers(
485 actual_device_path.value() + kExtraChars);
487 ASSERT_FALSE(DevicePathToDriveLetterPath(
488 real_device_path_plus_numbers,
489 &win32_path));
491 ASSERT_FALSE(DevicePathToDriveLetterPath(
492 real_device_path_plus_numbers.Append(kRelativePath),
493 &win32_path));
496 TEST_F(FileUtilTest, CreateTemporaryFileInDirLongPathTest) {
497 // Test that CreateTemporaryFileInDir() creates a path and returns a long path
498 // if it is available. This test requires that:
499 // - the filesystem at |temp_dir_| supports long filenames.
500 // - the account has FILE_LIST_DIRECTORY permission for all ancestor
501 // directories of |temp_dir_|.
502 const FilePath::CharType kLongDirName[] = FPL("A long path");
503 const FilePath::CharType kTestSubDirName[] = FPL("test");
504 FilePath long_test_dir = temp_dir_.path().Append(kLongDirName);
505 ASSERT_TRUE(CreateDirectory(long_test_dir));
507 // kLongDirName is not a 8.3 component. So GetShortName() should give us a
508 // different short name.
509 WCHAR path_buffer[MAX_PATH];
510 DWORD path_buffer_length = GetShortPathName(long_test_dir.value().c_str(),
511 path_buffer, MAX_PATH);
512 ASSERT_LT(path_buffer_length, DWORD(MAX_PATH));
513 ASSERT_NE(DWORD(0), path_buffer_length);
514 FilePath short_test_dir(path_buffer);
515 ASSERT_STRNE(kLongDirName, short_test_dir.BaseName().value().c_str());
517 FilePath temp_file;
518 ASSERT_TRUE(CreateTemporaryFileInDir(short_test_dir, &temp_file));
519 EXPECT_STREQ(kLongDirName, temp_file.DirName().BaseName().value().c_str());
520 EXPECT_TRUE(PathExists(temp_file));
522 // Create a subdirectory of |long_test_dir| and make |long_test_dir|
523 // unreadable. We should still be able to create a temp file in the
524 // subdirectory, but we won't be able to determine the long path for it. This
525 // mimics the environment that some users run where their user profiles reside
526 // in a location where the don't have full access to the higher level
527 // directories. (Note that this assumption is true for NTFS, but not for some
528 // network file systems. E.g. AFS).
529 FilePath access_test_dir = long_test_dir.Append(kTestSubDirName);
530 ASSERT_TRUE(CreateDirectory(access_test_dir));
531 FilePermissionRestorer long_test_dir_restorer(long_test_dir);
532 ASSERT_TRUE(MakeFileUnreadable(long_test_dir));
534 // Use the short form of the directory to create a temporary filename.
535 ASSERT_TRUE(CreateTemporaryFileInDir(
536 short_test_dir.Append(kTestSubDirName), &temp_file));
537 EXPECT_TRUE(PathExists(temp_file));
538 EXPECT_TRUE(short_test_dir.IsParent(temp_file.DirName()));
540 // Check that the long path can't be determined for |temp_file|.
541 path_buffer_length = GetLongPathName(temp_file.value().c_str(),
542 path_buffer, MAX_PATH);
543 EXPECT_EQ(DWORD(0), path_buffer_length);
546 #endif // defined(OS_WIN)
548 #if defined(OS_POSIX)
550 TEST_F(FileUtilTest, CreateAndReadSymlinks) {
551 FilePath link_from = temp_dir_.path().Append(FPL("from_file"));
552 FilePath link_to = temp_dir_.path().Append(FPL("to_file"));
553 CreateTextFile(link_to, bogus_content);
555 ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
556 << "Failed to create file symlink.";
558 // If we created the link properly, we should be able to read the contents
559 // through it.
560 std::wstring contents = ReadTextFile(link_from);
561 EXPECT_EQ(bogus_content, contents);
563 FilePath result;
564 ASSERT_TRUE(ReadSymbolicLink(link_from, &result));
565 EXPECT_EQ(link_to.value(), result.value());
567 // Link to a directory.
568 link_from = temp_dir_.path().Append(FPL("from_dir"));
569 link_to = temp_dir_.path().Append(FPL("to_dir"));
570 ASSERT_TRUE(CreateDirectory(link_to));
571 ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
572 << "Failed to create directory symlink.";
574 // Test failures.
575 EXPECT_FALSE(CreateSymbolicLink(link_to, link_to));
576 EXPECT_FALSE(ReadSymbolicLink(link_to, &result));
577 FilePath missing = temp_dir_.path().Append(FPL("missing"));
578 EXPECT_FALSE(ReadSymbolicLink(missing, &result));
581 // The following test of NormalizeFilePath() require that we create a symlink.
582 // This can not be done on Windows before Vista. On Vista, creating a symlink
583 // requires privilege "SeCreateSymbolicLinkPrivilege".
584 // TODO(skerner): Investigate the possibility of giving base_unittests the
585 // privileges required to create a symlink.
586 TEST_F(FileUtilTest, NormalizeFilePathSymlinks) {
587 // Link one file to another.
588 FilePath link_from = temp_dir_.path().Append(FPL("from_file"));
589 FilePath link_to = temp_dir_.path().Append(FPL("to_file"));
590 CreateTextFile(link_to, bogus_content);
592 ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
593 << "Failed to create file symlink.";
595 // Check that NormalizeFilePath sees the link.
596 FilePath normalized_path;
597 ASSERT_TRUE(NormalizeFilePath(link_from, &normalized_path));
598 EXPECT_NE(link_from, link_to);
599 EXPECT_EQ(link_to.BaseName().value(), normalized_path.BaseName().value());
600 EXPECT_EQ(link_to.BaseName().value(), normalized_path.BaseName().value());
602 // Link to a directory.
603 link_from = temp_dir_.path().Append(FPL("from_dir"));
604 link_to = temp_dir_.path().Append(FPL("to_dir"));
605 ASSERT_TRUE(CreateDirectory(link_to));
606 ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
607 << "Failed to create directory symlink.";
609 EXPECT_FALSE(NormalizeFilePath(link_from, &normalized_path))
610 << "Links to directories should return false.";
612 // Test that a loop in the links causes NormalizeFilePath() to return false.
613 link_from = temp_dir_.path().Append(FPL("link_a"));
614 link_to = temp_dir_.path().Append(FPL("link_b"));
615 ASSERT_TRUE(CreateSymbolicLink(link_to, link_from))
616 << "Failed to create loop symlink a.";
617 ASSERT_TRUE(CreateSymbolicLink(link_from, link_to))
618 << "Failed to create loop symlink b.";
620 // Infinite loop!
621 EXPECT_FALSE(NormalizeFilePath(link_from, &normalized_path));
623 #endif // defined(OS_POSIX)
625 TEST_F(FileUtilTest, DeleteNonExistent) {
626 FilePath non_existent = temp_dir_.path().AppendASCII("bogus_file_dne.foobar");
627 ASSERT_FALSE(PathExists(non_existent));
629 EXPECT_TRUE(DeleteFile(non_existent, false));
630 ASSERT_FALSE(PathExists(non_existent));
631 EXPECT_TRUE(DeleteFile(non_existent, true));
632 ASSERT_FALSE(PathExists(non_existent));
635 TEST_F(FileUtilTest, DeleteNonExistentWithNonExistentParent) {
636 FilePath non_existent = temp_dir_.path().AppendASCII("bogus_topdir");
637 non_existent = non_existent.AppendASCII("bogus_subdir");
638 ASSERT_FALSE(PathExists(non_existent));
640 EXPECT_TRUE(DeleteFile(non_existent, false));
641 ASSERT_FALSE(PathExists(non_existent));
642 EXPECT_TRUE(DeleteFile(non_existent, true));
643 ASSERT_FALSE(PathExists(non_existent));
646 TEST_F(FileUtilTest, DeleteFile) {
647 // Create a file
648 FilePath file_name = temp_dir_.path().Append(FPL("Test DeleteFile 1.txt"));
649 CreateTextFile(file_name, bogus_content);
650 ASSERT_TRUE(PathExists(file_name));
652 // Make sure it's deleted
653 EXPECT_TRUE(DeleteFile(file_name, false));
654 EXPECT_FALSE(PathExists(file_name));
656 // Test recursive case, create a new file
657 file_name = temp_dir_.path().Append(FPL("Test DeleteFile 2.txt"));
658 CreateTextFile(file_name, bogus_content);
659 ASSERT_TRUE(PathExists(file_name));
661 // Make sure it's deleted
662 EXPECT_TRUE(DeleteFile(file_name, true));
663 EXPECT_FALSE(PathExists(file_name));
666 #if defined(OS_POSIX)
667 TEST_F(FileUtilTest, DeleteSymlinkToExistentFile) {
668 // Create a file.
669 FilePath file_name = temp_dir_.path().Append(FPL("Test DeleteFile 2.txt"));
670 CreateTextFile(file_name, bogus_content);
671 ASSERT_TRUE(PathExists(file_name));
673 // Create a symlink to the file.
674 FilePath file_link = temp_dir_.path().Append("file_link_2");
675 ASSERT_TRUE(CreateSymbolicLink(file_name, file_link))
676 << "Failed to create symlink.";
678 // Delete the symbolic link.
679 EXPECT_TRUE(DeleteFile(file_link, false));
681 // Make sure original file is not deleted.
682 EXPECT_FALSE(PathExists(file_link));
683 EXPECT_TRUE(PathExists(file_name));
686 TEST_F(FileUtilTest, DeleteSymlinkToNonExistentFile) {
687 // Create a non-existent file path.
688 FilePath non_existent = temp_dir_.path().Append(FPL("Test DeleteFile 3.txt"));
689 EXPECT_FALSE(PathExists(non_existent));
691 // Create a symlink to the non-existent file.
692 FilePath file_link = temp_dir_.path().Append("file_link_3");
693 ASSERT_TRUE(CreateSymbolicLink(non_existent, file_link))
694 << "Failed to create symlink.";
696 // Make sure the symbolic link is exist.
697 EXPECT_TRUE(IsLink(file_link));
698 EXPECT_FALSE(PathExists(file_link));
700 // Delete the symbolic link.
701 EXPECT_TRUE(DeleteFile(file_link, false));
703 // Make sure the symbolic link is deleted.
704 EXPECT_FALSE(IsLink(file_link));
707 TEST_F(FileUtilTest, ChangeFilePermissionsAndRead) {
708 // Create a file path.
709 FilePath file_name = temp_dir_.path().Append(FPL("Test Readable File.txt"));
710 EXPECT_FALSE(PathExists(file_name));
712 const std::string kData("hello");
714 int buffer_size = kData.length();
715 char* buffer = new char[buffer_size];
717 // Write file.
718 EXPECT_EQ(static_cast<int>(kData.length()),
719 WriteFile(file_name, kData.data(), kData.length()));
720 EXPECT_TRUE(PathExists(file_name));
722 // Make sure the file is readable.
723 int32 mode = 0;
724 EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
725 EXPECT_TRUE(mode & FILE_PERMISSION_READ_BY_USER);
727 // Get rid of the read permission.
728 EXPECT_TRUE(SetPosixFilePermissions(file_name, 0u));
729 EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
730 EXPECT_FALSE(mode & FILE_PERMISSION_READ_BY_USER);
731 // Make sure the file can't be read.
732 EXPECT_EQ(-1, ReadFile(file_name, buffer, buffer_size));
734 // Give the read permission.
735 EXPECT_TRUE(SetPosixFilePermissions(file_name, FILE_PERMISSION_READ_BY_USER));
736 EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
737 EXPECT_TRUE(mode & FILE_PERMISSION_READ_BY_USER);
738 // Make sure the file can be read.
739 EXPECT_EQ(static_cast<int>(kData.length()),
740 ReadFile(file_name, buffer, buffer_size));
742 // Delete the file.
743 EXPECT_TRUE(DeleteFile(file_name, false));
744 EXPECT_FALSE(PathExists(file_name));
746 delete[] buffer;
749 TEST_F(FileUtilTest, ChangeFilePermissionsAndWrite) {
750 // Create a file path.
751 FilePath file_name = temp_dir_.path().Append(FPL("Test Readable File.txt"));
752 EXPECT_FALSE(PathExists(file_name));
754 const std::string kData("hello");
756 // Write file.
757 EXPECT_EQ(static_cast<int>(kData.length()),
758 WriteFile(file_name, kData.data(), kData.length()));
759 EXPECT_TRUE(PathExists(file_name));
761 // Make sure the file is writable.
762 int mode = 0;
763 EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
764 EXPECT_TRUE(mode & FILE_PERMISSION_WRITE_BY_USER);
765 EXPECT_TRUE(PathIsWritable(file_name));
767 // Get rid of the write permission.
768 EXPECT_TRUE(SetPosixFilePermissions(file_name, 0u));
769 EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
770 EXPECT_FALSE(mode & FILE_PERMISSION_WRITE_BY_USER);
771 // Make sure the file can't be write.
772 EXPECT_EQ(-1, WriteFile(file_name, kData.data(), kData.length()));
773 EXPECT_FALSE(PathIsWritable(file_name));
775 // Give read permission.
776 EXPECT_TRUE(SetPosixFilePermissions(file_name,
777 FILE_PERMISSION_WRITE_BY_USER));
778 EXPECT_TRUE(GetPosixFilePermissions(file_name, &mode));
779 EXPECT_TRUE(mode & FILE_PERMISSION_WRITE_BY_USER);
780 // Make sure the file can be write.
781 EXPECT_EQ(static_cast<int>(kData.length()),
782 WriteFile(file_name, kData.data(), kData.length()));
783 EXPECT_TRUE(PathIsWritable(file_name));
785 // Delete the file.
786 EXPECT_TRUE(DeleteFile(file_name, false));
787 EXPECT_FALSE(PathExists(file_name));
790 TEST_F(FileUtilTest, ChangeDirectoryPermissionsAndEnumerate) {
791 // Create a directory path.
792 FilePath subdir_path =
793 temp_dir_.path().Append(FPL("PermissionTest1"));
794 CreateDirectory(subdir_path);
795 ASSERT_TRUE(PathExists(subdir_path));
797 // Create a dummy file to enumerate.
798 FilePath file_name = subdir_path.Append(FPL("Test Readable File.txt"));
799 EXPECT_FALSE(PathExists(file_name));
800 const std::string kData("hello");
801 EXPECT_EQ(static_cast<int>(kData.length()),
802 WriteFile(file_name, kData.data(), kData.length()));
803 EXPECT_TRUE(PathExists(file_name));
805 // Make sure the directory has the all permissions.
806 int mode = 0;
807 EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
808 EXPECT_EQ(FILE_PERMISSION_USER_MASK, mode & FILE_PERMISSION_USER_MASK);
810 // Get rid of the permissions from the directory.
811 EXPECT_TRUE(SetPosixFilePermissions(subdir_path, 0u));
812 EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
813 EXPECT_FALSE(mode & FILE_PERMISSION_USER_MASK);
815 // Make sure the file in the directory can't be enumerated.
816 FileEnumerator f1(subdir_path, true, FileEnumerator::FILES);
817 EXPECT_TRUE(PathExists(subdir_path));
818 FindResultCollector c1(&f1);
819 EXPECT_EQ(0, c1.size());
820 EXPECT_FALSE(GetPosixFilePermissions(file_name, &mode));
822 // Give the permissions to the directory.
823 EXPECT_TRUE(SetPosixFilePermissions(subdir_path, FILE_PERMISSION_USER_MASK));
824 EXPECT_TRUE(GetPosixFilePermissions(subdir_path, &mode));
825 EXPECT_EQ(FILE_PERMISSION_USER_MASK, mode & FILE_PERMISSION_USER_MASK);
827 // Make sure the file in the directory can be enumerated.
828 FileEnumerator f2(subdir_path, true, FileEnumerator::FILES);
829 FindResultCollector c2(&f2);
830 EXPECT_TRUE(c2.HasFile(file_name));
831 EXPECT_EQ(1, c2.size());
833 // Delete the file.
834 EXPECT_TRUE(DeleteFile(subdir_path, true));
835 EXPECT_FALSE(PathExists(subdir_path));
838 #endif // defined(OS_POSIX)
840 #if defined(OS_WIN)
841 // Tests that the Delete function works for wild cards, especially
842 // with the recursion flag. Also coincidentally tests PathExists.
843 // TODO(erikkay): see if anyone's actually using this feature of the API
844 TEST_F(FileUtilTest, DeleteWildCard) {
845 // Create a file and a directory
846 FilePath file_name = temp_dir_.path().Append(FPL("Test DeleteWildCard.txt"));
847 CreateTextFile(file_name, bogus_content);
848 ASSERT_TRUE(PathExists(file_name));
850 FilePath subdir_path = temp_dir_.path().Append(FPL("DeleteWildCardDir"));
851 CreateDirectory(subdir_path);
852 ASSERT_TRUE(PathExists(subdir_path));
854 // Create the wildcard path
855 FilePath directory_contents = temp_dir_.path();
856 directory_contents = directory_contents.Append(FPL("*"));
858 // Delete non-recursively and check that only the file is deleted
859 EXPECT_TRUE(DeleteFile(directory_contents, false));
860 EXPECT_FALSE(PathExists(file_name));
861 EXPECT_TRUE(PathExists(subdir_path));
863 // Delete recursively and make sure all contents are deleted
864 EXPECT_TRUE(DeleteFile(directory_contents, true));
865 EXPECT_FALSE(PathExists(file_name));
866 EXPECT_FALSE(PathExists(subdir_path));
869 // TODO(erikkay): see if anyone's actually using this feature of the API
870 TEST_F(FileUtilTest, DeleteNonExistantWildCard) {
871 // Create a file and a directory
872 FilePath subdir_path =
873 temp_dir_.path().Append(FPL("DeleteNonExistantWildCard"));
874 CreateDirectory(subdir_path);
875 ASSERT_TRUE(PathExists(subdir_path));
877 // Create the wildcard path
878 FilePath directory_contents = subdir_path;
879 directory_contents = directory_contents.Append(FPL("*"));
881 // Delete non-recursively and check nothing got deleted
882 EXPECT_TRUE(DeleteFile(directory_contents, false));
883 EXPECT_TRUE(PathExists(subdir_path));
885 // Delete recursively and check nothing got deleted
886 EXPECT_TRUE(DeleteFile(directory_contents, true));
887 EXPECT_TRUE(PathExists(subdir_path));
889 #endif
891 // Tests non-recursive Delete() for a directory.
892 TEST_F(FileUtilTest, DeleteDirNonRecursive) {
893 // Create a subdirectory and put a file and two directories inside.
894 FilePath test_subdir = temp_dir_.path().Append(FPL("DeleteDirNonRecursive"));
895 CreateDirectory(test_subdir);
896 ASSERT_TRUE(PathExists(test_subdir));
898 FilePath file_name = test_subdir.Append(FPL("Test DeleteDir.txt"));
899 CreateTextFile(file_name, bogus_content);
900 ASSERT_TRUE(PathExists(file_name));
902 FilePath subdir_path1 = test_subdir.Append(FPL("TestSubDir1"));
903 CreateDirectory(subdir_path1);
904 ASSERT_TRUE(PathExists(subdir_path1));
906 FilePath subdir_path2 = test_subdir.Append(FPL("TestSubDir2"));
907 CreateDirectory(subdir_path2);
908 ASSERT_TRUE(PathExists(subdir_path2));
910 // Delete non-recursively and check that the empty dir got deleted
911 EXPECT_TRUE(DeleteFile(subdir_path2, false));
912 EXPECT_FALSE(PathExists(subdir_path2));
914 // Delete non-recursively and check that nothing got deleted
915 EXPECT_FALSE(DeleteFile(test_subdir, false));
916 EXPECT_TRUE(PathExists(test_subdir));
917 EXPECT_TRUE(PathExists(file_name));
918 EXPECT_TRUE(PathExists(subdir_path1));
921 // Tests recursive Delete() for a directory.
922 TEST_F(FileUtilTest, DeleteDirRecursive) {
923 // Create a subdirectory and put a file and two directories inside.
924 FilePath test_subdir = temp_dir_.path().Append(FPL("DeleteDirRecursive"));
925 CreateDirectory(test_subdir);
926 ASSERT_TRUE(PathExists(test_subdir));
928 FilePath file_name = test_subdir.Append(FPL("Test DeleteDirRecursive.txt"));
929 CreateTextFile(file_name, bogus_content);
930 ASSERT_TRUE(PathExists(file_name));
932 FilePath subdir_path1 = test_subdir.Append(FPL("TestSubDir1"));
933 CreateDirectory(subdir_path1);
934 ASSERT_TRUE(PathExists(subdir_path1));
936 FilePath subdir_path2 = test_subdir.Append(FPL("TestSubDir2"));
937 CreateDirectory(subdir_path2);
938 ASSERT_TRUE(PathExists(subdir_path2));
940 // Delete recursively and check that the empty dir got deleted
941 EXPECT_TRUE(DeleteFile(subdir_path2, true));
942 EXPECT_FALSE(PathExists(subdir_path2));
944 // Delete recursively and check that everything got deleted
945 EXPECT_TRUE(DeleteFile(test_subdir, true));
946 EXPECT_FALSE(PathExists(file_name));
947 EXPECT_FALSE(PathExists(subdir_path1));
948 EXPECT_FALSE(PathExists(test_subdir));
951 TEST_F(FileUtilTest, MoveFileNew) {
952 // Create a file
953 FilePath file_name_from =
954 temp_dir_.path().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
955 CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
956 ASSERT_TRUE(PathExists(file_name_from));
958 // The destination.
959 FilePath file_name_to = temp_dir_.path().Append(
960 FILE_PATH_LITERAL("Move_Test_File_Destination.txt"));
961 ASSERT_FALSE(PathExists(file_name_to));
963 EXPECT_TRUE(Move(file_name_from, file_name_to));
965 // Check everything has been moved.
966 EXPECT_FALSE(PathExists(file_name_from));
967 EXPECT_TRUE(PathExists(file_name_to));
970 TEST_F(FileUtilTest, MoveFileExists) {
971 // Create a file
972 FilePath file_name_from =
973 temp_dir_.path().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
974 CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
975 ASSERT_TRUE(PathExists(file_name_from));
977 // The destination name.
978 FilePath file_name_to = temp_dir_.path().Append(
979 FILE_PATH_LITERAL("Move_Test_File_Destination.txt"));
980 CreateTextFile(file_name_to, L"Old file content");
981 ASSERT_TRUE(PathExists(file_name_to));
983 EXPECT_TRUE(Move(file_name_from, file_name_to));
985 // Check everything has been moved.
986 EXPECT_FALSE(PathExists(file_name_from));
987 EXPECT_TRUE(PathExists(file_name_to));
988 EXPECT_TRUE(L"Gooooooooooooooooooooogle" == ReadTextFile(file_name_to));
991 TEST_F(FileUtilTest, MoveFileDirExists) {
992 // Create a file
993 FilePath file_name_from =
994 temp_dir_.path().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
995 CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
996 ASSERT_TRUE(PathExists(file_name_from));
998 // The destination directory
999 FilePath dir_name_to =
1000 temp_dir_.path().Append(FILE_PATH_LITERAL("Destination"));
1001 CreateDirectory(dir_name_to);
1002 ASSERT_TRUE(PathExists(dir_name_to));
1004 EXPECT_FALSE(Move(file_name_from, dir_name_to));
1008 TEST_F(FileUtilTest, MoveNew) {
1009 // Create a directory
1010 FilePath dir_name_from =
1011 temp_dir_.path().Append(FILE_PATH_LITERAL("Move_From_Subdir"));
1012 CreateDirectory(dir_name_from);
1013 ASSERT_TRUE(PathExists(dir_name_from));
1015 // Create a file under the directory
1016 FilePath txt_file_name(FILE_PATH_LITERAL("Move_Test_File.txt"));
1017 FilePath file_name_from = dir_name_from.Append(txt_file_name);
1018 CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1019 ASSERT_TRUE(PathExists(file_name_from));
1021 // Move the directory.
1022 FilePath dir_name_to =
1023 temp_dir_.path().Append(FILE_PATH_LITERAL("Move_To_Subdir"));
1024 FilePath file_name_to =
1025 dir_name_to.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
1027 ASSERT_FALSE(PathExists(dir_name_to));
1029 EXPECT_TRUE(Move(dir_name_from, dir_name_to));
1031 // Check everything has been moved.
1032 EXPECT_FALSE(PathExists(dir_name_from));
1033 EXPECT_FALSE(PathExists(file_name_from));
1034 EXPECT_TRUE(PathExists(dir_name_to));
1035 EXPECT_TRUE(PathExists(file_name_to));
1037 // Test path traversal.
1038 file_name_from = dir_name_to.Append(txt_file_name);
1039 file_name_to = dir_name_to.Append(FILE_PATH_LITERAL(".."));
1040 file_name_to = file_name_to.Append(txt_file_name);
1041 EXPECT_FALSE(Move(file_name_from, file_name_to));
1042 EXPECT_TRUE(PathExists(file_name_from));
1043 EXPECT_FALSE(PathExists(file_name_to));
1044 EXPECT_TRUE(internal::MoveUnsafe(file_name_from, file_name_to));
1045 EXPECT_FALSE(PathExists(file_name_from));
1046 EXPECT_TRUE(PathExists(file_name_to));
1049 TEST_F(FileUtilTest, MoveExist) {
1050 // Create a directory
1051 FilePath dir_name_from =
1052 temp_dir_.path().Append(FILE_PATH_LITERAL("Move_From_Subdir"));
1053 CreateDirectory(dir_name_from);
1054 ASSERT_TRUE(PathExists(dir_name_from));
1056 // Create a file under the directory
1057 FilePath file_name_from =
1058 dir_name_from.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
1059 CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1060 ASSERT_TRUE(PathExists(file_name_from));
1062 // Move the directory
1063 FilePath dir_name_exists =
1064 temp_dir_.path().Append(FILE_PATH_LITERAL("Destination"));
1066 FilePath dir_name_to =
1067 dir_name_exists.Append(FILE_PATH_LITERAL("Move_To_Subdir"));
1068 FilePath file_name_to =
1069 dir_name_to.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
1071 // Create the destination directory.
1072 CreateDirectory(dir_name_exists);
1073 ASSERT_TRUE(PathExists(dir_name_exists));
1075 EXPECT_TRUE(Move(dir_name_from, dir_name_to));
1077 // Check everything has been moved.
1078 EXPECT_FALSE(PathExists(dir_name_from));
1079 EXPECT_FALSE(PathExists(file_name_from));
1080 EXPECT_TRUE(PathExists(dir_name_to));
1081 EXPECT_TRUE(PathExists(file_name_to));
1084 TEST_F(FileUtilTest, CopyDirectoryRecursivelyNew) {
1085 // Create a directory.
1086 FilePath dir_name_from =
1087 temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1088 CreateDirectory(dir_name_from);
1089 ASSERT_TRUE(PathExists(dir_name_from));
1091 // Create a file under the directory.
1092 FilePath file_name_from =
1093 dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1094 CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1095 ASSERT_TRUE(PathExists(file_name_from));
1097 // Create a subdirectory.
1098 FilePath subdir_name_from =
1099 dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
1100 CreateDirectory(subdir_name_from);
1101 ASSERT_TRUE(PathExists(subdir_name_from));
1103 // Create a file under the subdirectory.
1104 FilePath file_name2_from =
1105 subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1106 CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
1107 ASSERT_TRUE(PathExists(file_name2_from));
1109 // Copy the directory recursively.
1110 FilePath dir_name_to =
1111 temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1112 FilePath file_name_to =
1113 dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1114 FilePath subdir_name_to =
1115 dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
1116 FilePath file_name2_to =
1117 subdir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1119 ASSERT_FALSE(PathExists(dir_name_to));
1121 EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, true));
1123 // Check everything has been copied.
1124 EXPECT_TRUE(PathExists(dir_name_from));
1125 EXPECT_TRUE(PathExists(file_name_from));
1126 EXPECT_TRUE(PathExists(subdir_name_from));
1127 EXPECT_TRUE(PathExists(file_name2_from));
1128 EXPECT_TRUE(PathExists(dir_name_to));
1129 EXPECT_TRUE(PathExists(file_name_to));
1130 EXPECT_TRUE(PathExists(subdir_name_to));
1131 EXPECT_TRUE(PathExists(file_name2_to));
1134 TEST_F(FileUtilTest, CopyDirectoryRecursivelyExists) {
1135 // Create a directory.
1136 FilePath dir_name_from =
1137 temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1138 CreateDirectory(dir_name_from);
1139 ASSERT_TRUE(PathExists(dir_name_from));
1141 // Create a file under the directory.
1142 FilePath file_name_from =
1143 dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1144 CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1145 ASSERT_TRUE(PathExists(file_name_from));
1147 // Create a subdirectory.
1148 FilePath subdir_name_from =
1149 dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
1150 CreateDirectory(subdir_name_from);
1151 ASSERT_TRUE(PathExists(subdir_name_from));
1153 // Create a file under the subdirectory.
1154 FilePath file_name2_from =
1155 subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1156 CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
1157 ASSERT_TRUE(PathExists(file_name2_from));
1159 // Copy the directory recursively.
1160 FilePath dir_name_exists =
1161 temp_dir_.path().Append(FILE_PATH_LITERAL("Destination"));
1163 FilePath dir_name_to =
1164 dir_name_exists.Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1165 FilePath file_name_to =
1166 dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1167 FilePath subdir_name_to =
1168 dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
1169 FilePath file_name2_to =
1170 subdir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1172 // Create the destination directory.
1173 CreateDirectory(dir_name_exists);
1174 ASSERT_TRUE(PathExists(dir_name_exists));
1176 EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_exists, true));
1178 // Check everything has been copied.
1179 EXPECT_TRUE(PathExists(dir_name_from));
1180 EXPECT_TRUE(PathExists(file_name_from));
1181 EXPECT_TRUE(PathExists(subdir_name_from));
1182 EXPECT_TRUE(PathExists(file_name2_from));
1183 EXPECT_TRUE(PathExists(dir_name_to));
1184 EXPECT_TRUE(PathExists(file_name_to));
1185 EXPECT_TRUE(PathExists(subdir_name_to));
1186 EXPECT_TRUE(PathExists(file_name2_to));
1189 TEST_F(FileUtilTest, CopyDirectoryNew) {
1190 // Create a directory.
1191 FilePath dir_name_from =
1192 temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1193 CreateDirectory(dir_name_from);
1194 ASSERT_TRUE(PathExists(dir_name_from));
1196 // Create a file under the directory.
1197 FilePath file_name_from =
1198 dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1199 CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1200 ASSERT_TRUE(PathExists(file_name_from));
1202 // Create a subdirectory.
1203 FilePath subdir_name_from =
1204 dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
1205 CreateDirectory(subdir_name_from);
1206 ASSERT_TRUE(PathExists(subdir_name_from));
1208 // Create a file under the subdirectory.
1209 FilePath file_name2_from =
1210 subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1211 CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
1212 ASSERT_TRUE(PathExists(file_name2_from));
1214 // Copy the directory not recursively.
1215 FilePath dir_name_to =
1216 temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1217 FilePath file_name_to =
1218 dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1219 FilePath subdir_name_to =
1220 dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
1222 ASSERT_FALSE(PathExists(dir_name_to));
1224 EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
1226 // Check everything has been copied.
1227 EXPECT_TRUE(PathExists(dir_name_from));
1228 EXPECT_TRUE(PathExists(file_name_from));
1229 EXPECT_TRUE(PathExists(subdir_name_from));
1230 EXPECT_TRUE(PathExists(file_name2_from));
1231 EXPECT_TRUE(PathExists(dir_name_to));
1232 EXPECT_TRUE(PathExists(file_name_to));
1233 EXPECT_FALSE(PathExists(subdir_name_to));
1236 TEST_F(FileUtilTest, CopyDirectoryExists) {
1237 // Create a directory.
1238 FilePath dir_name_from =
1239 temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1240 CreateDirectory(dir_name_from);
1241 ASSERT_TRUE(PathExists(dir_name_from));
1243 // Create a file under the directory.
1244 FilePath file_name_from =
1245 dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1246 CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1247 ASSERT_TRUE(PathExists(file_name_from));
1249 // Create a subdirectory.
1250 FilePath subdir_name_from =
1251 dir_name_from.Append(FILE_PATH_LITERAL("Subdir"));
1252 CreateDirectory(subdir_name_from);
1253 ASSERT_TRUE(PathExists(subdir_name_from));
1255 // Create a file under the subdirectory.
1256 FilePath file_name2_from =
1257 subdir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1258 CreateTextFile(file_name2_from, L"Gooooooooooooooooooooogle");
1259 ASSERT_TRUE(PathExists(file_name2_from));
1261 // Copy the directory not recursively.
1262 FilePath dir_name_to =
1263 temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1264 FilePath file_name_to =
1265 dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1266 FilePath subdir_name_to =
1267 dir_name_to.Append(FILE_PATH_LITERAL("Subdir"));
1269 // Create the destination directory.
1270 CreateDirectory(dir_name_to);
1271 ASSERT_TRUE(PathExists(dir_name_to));
1273 EXPECT_TRUE(CopyDirectory(dir_name_from, dir_name_to, false));
1275 // Check everything has been copied.
1276 EXPECT_TRUE(PathExists(dir_name_from));
1277 EXPECT_TRUE(PathExists(file_name_from));
1278 EXPECT_TRUE(PathExists(subdir_name_from));
1279 EXPECT_TRUE(PathExists(file_name2_from));
1280 EXPECT_TRUE(PathExists(dir_name_to));
1281 EXPECT_TRUE(PathExists(file_name_to));
1282 EXPECT_FALSE(PathExists(subdir_name_to));
1285 TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToNew) {
1286 // Create a file
1287 FilePath file_name_from =
1288 temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1289 CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1290 ASSERT_TRUE(PathExists(file_name_from));
1292 // The destination name
1293 FilePath file_name_to = temp_dir_.path().Append(
1294 FILE_PATH_LITERAL("Copy_Test_File_Destination.txt"));
1295 ASSERT_FALSE(PathExists(file_name_to));
1297 EXPECT_TRUE(CopyDirectory(file_name_from, file_name_to, true));
1299 // Check the has been copied
1300 EXPECT_TRUE(PathExists(file_name_to));
1303 TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToExisting) {
1304 // Create a file
1305 FilePath file_name_from =
1306 temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1307 CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1308 ASSERT_TRUE(PathExists(file_name_from));
1310 // The destination name
1311 FilePath file_name_to = temp_dir_.path().Append(
1312 FILE_PATH_LITERAL("Copy_Test_File_Destination.txt"));
1313 CreateTextFile(file_name_to, L"Old file content");
1314 ASSERT_TRUE(PathExists(file_name_to));
1316 EXPECT_TRUE(CopyDirectory(file_name_from, file_name_to, true));
1318 // Check the has been copied
1319 EXPECT_TRUE(PathExists(file_name_to));
1320 EXPECT_TRUE(L"Gooooooooooooooooooooogle" == ReadTextFile(file_name_to));
1323 TEST_F(FileUtilTest, CopyFileWithCopyDirectoryRecursiveToExistingDirectory) {
1324 // Create a file
1325 FilePath file_name_from =
1326 temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1327 CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1328 ASSERT_TRUE(PathExists(file_name_from));
1330 // The destination
1331 FilePath dir_name_to =
1332 temp_dir_.path().Append(FILE_PATH_LITERAL("Destination"));
1333 CreateDirectory(dir_name_to);
1334 ASSERT_TRUE(PathExists(dir_name_to));
1335 FilePath file_name_to =
1336 dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1338 EXPECT_TRUE(CopyDirectory(file_name_from, dir_name_to, true));
1340 // Check the has been copied
1341 EXPECT_TRUE(PathExists(file_name_to));
1344 TEST_F(FileUtilTest, CopyDirectoryWithTrailingSeparators) {
1345 // Create a directory.
1346 FilePath dir_name_from =
1347 temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1348 CreateDirectory(dir_name_from);
1349 ASSERT_TRUE(PathExists(dir_name_from));
1351 // Create a file under the directory.
1352 FilePath file_name_from =
1353 dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1354 CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1355 ASSERT_TRUE(PathExists(file_name_from));
1357 // Copy the directory recursively.
1358 FilePath dir_name_to =
1359 temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1360 FilePath file_name_to =
1361 dir_name_to.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1363 // Create from path with trailing separators.
1364 #if defined(OS_WIN)
1365 FilePath from_path =
1366 temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir\\\\\\"));
1367 #elif defined (OS_POSIX)
1368 FilePath from_path =
1369 temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir///"));
1370 #endif
1372 EXPECT_TRUE(CopyDirectory(from_path, dir_name_to, true));
1374 // Check everything has been copied.
1375 EXPECT_TRUE(PathExists(dir_name_from));
1376 EXPECT_TRUE(PathExists(file_name_from));
1377 EXPECT_TRUE(PathExists(dir_name_to));
1378 EXPECT_TRUE(PathExists(file_name_to));
1381 // Sets the source file to read-only.
1382 void SetReadOnly(const FilePath& path, bool read_only) {
1383 #if defined(OS_WIN)
1384 // On Windows, it involves setting/removing the 'readonly' bit.
1385 DWORD attrs = GetFileAttributes(path.value().c_str());
1386 ASSERT_NE(INVALID_FILE_ATTRIBUTES, attrs);
1387 ASSERT_TRUE(SetFileAttributes(
1388 path.value().c_str(),
1389 read_only ? (attrs | FILE_ATTRIBUTE_READONLY) :
1390 (attrs & ~FILE_ATTRIBUTE_READONLY)));
1392 DWORD expected = read_only ?
1393 ((attrs & (FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_DIRECTORY)) |
1394 FILE_ATTRIBUTE_READONLY) :
1395 (attrs & (FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_DIRECTORY));
1397 // Ignore FILE_ATTRIBUTE_NOT_CONTENT_INDEXED if present.
1398 attrs = GetFileAttributes(path.value().c_str()) &
1399 ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
1400 ASSERT_EQ(expected, attrs);
1401 #else
1402 // On all other platforms, it involves removing/setting the write bit.
1403 mode_t mode = read_only ? S_IRUSR : (S_IRUSR | S_IWUSR);
1404 EXPECT_TRUE(SetPosixFilePermissions(
1405 path, DirectoryExists(path) ? (mode | S_IXUSR) : mode));
1406 #endif
1409 bool IsReadOnly(const FilePath& path) {
1410 #if defined(OS_WIN)
1411 DWORD attrs = GetFileAttributes(path.value().c_str());
1412 EXPECT_NE(INVALID_FILE_ATTRIBUTES, attrs);
1413 return attrs & FILE_ATTRIBUTE_READONLY;
1414 #else
1415 int mode = 0;
1416 EXPECT_TRUE(GetPosixFilePermissions(path, &mode));
1417 return !(mode & S_IWUSR);
1418 #endif
1421 TEST_F(FileUtilTest, CopyDirectoryACL) {
1422 // Create source directories.
1423 FilePath src = temp_dir_.path().Append(FILE_PATH_LITERAL("src"));
1424 FilePath src_subdir = src.Append(FILE_PATH_LITERAL("subdir"));
1425 CreateDirectory(src_subdir);
1426 ASSERT_TRUE(PathExists(src_subdir));
1428 // Create a file under the directory.
1429 FilePath src_file = src.Append(FILE_PATH_LITERAL("src.txt"));
1430 CreateTextFile(src_file, L"Gooooooooooooooooooooogle");
1431 SetReadOnly(src_file, true);
1432 ASSERT_TRUE(IsReadOnly(src_file));
1434 // Make directory read-only.
1435 SetReadOnly(src_subdir, true);
1436 ASSERT_TRUE(IsReadOnly(src_subdir));
1438 // Copy the directory recursively.
1439 FilePath dst = temp_dir_.path().Append(FILE_PATH_LITERAL("dst"));
1440 FilePath dst_file = dst.Append(FILE_PATH_LITERAL("src.txt"));
1441 EXPECT_TRUE(CopyDirectory(src, dst, true));
1443 FilePath dst_subdir = dst.Append(FILE_PATH_LITERAL("subdir"));
1444 ASSERT_FALSE(IsReadOnly(dst_subdir));
1445 ASSERT_FALSE(IsReadOnly(dst_file));
1447 // Give write permissions to allow deletion.
1448 SetReadOnly(src_subdir, false);
1449 ASSERT_FALSE(IsReadOnly(src_subdir));
1452 TEST_F(FileUtilTest, CopyFile) {
1453 // Create a directory
1454 FilePath dir_name_from =
1455 temp_dir_.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1456 CreateDirectory(dir_name_from);
1457 ASSERT_TRUE(PathExists(dir_name_from));
1459 // Create a file under the directory
1460 FilePath file_name_from =
1461 dir_name_from.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1462 const std::wstring file_contents(L"Gooooooooooooooooooooogle");
1463 CreateTextFile(file_name_from, file_contents);
1464 ASSERT_TRUE(PathExists(file_name_from));
1466 // Copy the file.
1467 FilePath dest_file = dir_name_from.Append(FILE_PATH_LITERAL("DestFile.txt"));
1468 ASSERT_TRUE(CopyFile(file_name_from, dest_file));
1470 // Try to copy the file to another location using '..' in the path.
1471 FilePath dest_file2(dir_name_from);
1472 dest_file2 = dest_file2.AppendASCII("..");
1473 dest_file2 = dest_file2.AppendASCII("DestFile.txt");
1474 ASSERT_FALSE(CopyFile(file_name_from, dest_file2));
1476 FilePath dest_file2_test(dir_name_from);
1477 dest_file2_test = dest_file2_test.DirName();
1478 dest_file2_test = dest_file2_test.AppendASCII("DestFile.txt");
1480 // Check expected copy results.
1481 EXPECT_TRUE(PathExists(file_name_from));
1482 EXPECT_TRUE(PathExists(dest_file));
1483 const std::wstring read_contents = ReadTextFile(dest_file);
1484 EXPECT_EQ(file_contents, read_contents);
1485 EXPECT_FALSE(PathExists(dest_file2_test));
1486 EXPECT_FALSE(PathExists(dest_file2));
1489 TEST_F(FileUtilTest, CopyFileACL) {
1490 // While FileUtilTest.CopyFile asserts the content is correctly copied over,
1491 // this test case asserts the access control bits are meeting expectations in
1492 // CopyFile().
1493 FilePath src = temp_dir_.path().Append(FILE_PATH_LITERAL("src.txt"));
1494 const std::wstring file_contents(L"Gooooooooooooooooooooogle");
1495 CreateTextFile(src, file_contents);
1497 // Set the source file to read-only.
1498 ASSERT_FALSE(IsReadOnly(src));
1499 SetReadOnly(src, true);
1500 ASSERT_TRUE(IsReadOnly(src));
1502 // Copy the file.
1503 FilePath dst = temp_dir_.path().Append(FILE_PATH_LITERAL("dst.txt"));
1504 ASSERT_TRUE(CopyFile(src, dst));
1505 EXPECT_EQ(file_contents, ReadTextFile(dst));
1507 ASSERT_FALSE(IsReadOnly(dst));
1510 // file_util winds up using autoreleased objects on the Mac, so this needs
1511 // to be a PlatformTest.
1512 typedef PlatformTest ReadOnlyFileUtilTest;
1514 TEST_F(ReadOnlyFileUtilTest, ContentsEqual) {
1515 FilePath data_dir;
1516 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
1517 data_dir = data_dir.AppendASCII("file_util");
1518 ASSERT_TRUE(PathExists(data_dir));
1520 FilePath original_file =
1521 data_dir.Append(FILE_PATH_LITERAL("original.txt"));
1522 FilePath same_file =
1523 data_dir.Append(FILE_PATH_LITERAL("same.txt"));
1524 FilePath same_length_file =
1525 data_dir.Append(FILE_PATH_LITERAL("same_length.txt"));
1526 FilePath different_file =
1527 data_dir.Append(FILE_PATH_LITERAL("different.txt"));
1528 FilePath different_first_file =
1529 data_dir.Append(FILE_PATH_LITERAL("different_first.txt"));
1530 FilePath different_last_file =
1531 data_dir.Append(FILE_PATH_LITERAL("different_last.txt"));
1532 FilePath empty1_file =
1533 data_dir.Append(FILE_PATH_LITERAL("empty1.txt"));
1534 FilePath empty2_file =
1535 data_dir.Append(FILE_PATH_LITERAL("empty2.txt"));
1536 FilePath shortened_file =
1537 data_dir.Append(FILE_PATH_LITERAL("shortened.txt"));
1538 FilePath binary_file =
1539 data_dir.Append(FILE_PATH_LITERAL("binary_file.bin"));
1540 FilePath binary_file_same =
1541 data_dir.Append(FILE_PATH_LITERAL("binary_file_same.bin"));
1542 FilePath binary_file_diff =
1543 data_dir.Append(FILE_PATH_LITERAL("binary_file_diff.bin"));
1545 EXPECT_TRUE(ContentsEqual(original_file, original_file));
1546 EXPECT_TRUE(ContentsEqual(original_file, same_file));
1547 EXPECT_FALSE(ContentsEqual(original_file, same_length_file));
1548 EXPECT_FALSE(ContentsEqual(original_file, different_file));
1549 EXPECT_FALSE(ContentsEqual(FilePath(FILE_PATH_LITERAL("bogusname")),
1550 FilePath(FILE_PATH_LITERAL("bogusname"))));
1551 EXPECT_FALSE(ContentsEqual(original_file, different_first_file));
1552 EXPECT_FALSE(ContentsEqual(original_file, different_last_file));
1553 EXPECT_TRUE(ContentsEqual(empty1_file, empty2_file));
1554 EXPECT_FALSE(ContentsEqual(original_file, shortened_file));
1555 EXPECT_FALSE(ContentsEqual(shortened_file, original_file));
1556 EXPECT_TRUE(ContentsEqual(binary_file, binary_file_same));
1557 EXPECT_FALSE(ContentsEqual(binary_file, binary_file_diff));
1560 TEST_F(ReadOnlyFileUtilTest, TextContentsEqual) {
1561 FilePath data_dir;
1562 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
1563 data_dir = data_dir.AppendASCII("file_util");
1564 ASSERT_TRUE(PathExists(data_dir));
1566 FilePath original_file =
1567 data_dir.Append(FILE_PATH_LITERAL("original.txt"));
1568 FilePath same_file =
1569 data_dir.Append(FILE_PATH_LITERAL("same.txt"));
1570 FilePath crlf_file =
1571 data_dir.Append(FILE_PATH_LITERAL("crlf.txt"));
1572 FilePath shortened_file =
1573 data_dir.Append(FILE_PATH_LITERAL("shortened.txt"));
1574 FilePath different_file =
1575 data_dir.Append(FILE_PATH_LITERAL("different.txt"));
1576 FilePath different_first_file =
1577 data_dir.Append(FILE_PATH_LITERAL("different_first.txt"));
1578 FilePath different_last_file =
1579 data_dir.Append(FILE_PATH_LITERAL("different_last.txt"));
1580 FilePath first1_file =
1581 data_dir.Append(FILE_PATH_LITERAL("first1.txt"));
1582 FilePath first2_file =
1583 data_dir.Append(FILE_PATH_LITERAL("first2.txt"));
1584 FilePath empty1_file =
1585 data_dir.Append(FILE_PATH_LITERAL("empty1.txt"));
1586 FilePath empty2_file =
1587 data_dir.Append(FILE_PATH_LITERAL("empty2.txt"));
1588 FilePath blank_line_file =
1589 data_dir.Append(FILE_PATH_LITERAL("blank_line.txt"));
1590 FilePath blank_line_crlf_file =
1591 data_dir.Append(FILE_PATH_LITERAL("blank_line_crlf.txt"));
1593 EXPECT_TRUE(TextContentsEqual(original_file, same_file));
1594 EXPECT_TRUE(TextContentsEqual(original_file, crlf_file));
1595 EXPECT_FALSE(TextContentsEqual(original_file, shortened_file));
1596 EXPECT_FALSE(TextContentsEqual(original_file, different_file));
1597 EXPECT_FALSE(TextContentsEqual(original_file, different_first_file));
1598 EXPECT_FALSE(TextContentsEqual(original_file, different_last_file));
1599 EXPECT_FALSE(TextContentsEqual(first1_file, first2_file));
1600 EXPECT_TRUE(TextContentsEqual(empty1_file, empty2_file));
1601 EXPECT_FALSE(TextContentsEqual(original_file, empty1_file));
1602 EXPECT_TRUE(TextContentsEqual(blank_line_file, blank_line_crlf_file));
1605 // We don't need equivalent functionality outside of Windows.
1606 #if defined(OS_WIN)
1607 TEST_F(FileUtilTest, CopyAndDeleteDirectoryTest) {
1608 // Create a directory
1609 FilePath dir_name_from =
1610 temp_dir_.path().Append(FILE_PATH_LITERAL("CopyAndDelete_From_Subdir"));
1611 CreateDirectory(dir_name_from);
1612 ASSERT_TRUE(PathExists(dir_name_from));
1614 // Create a file under the directory
1615 FilePath file_name_from =
1616 dir_name_from.Append(FILE_PATH_LITERAL("CopyAndDelete_Test_File.txt"));
1617 CreateTextFile(file_name_from, L"Gooooooooooooooooooooogle");
1618 ASSERT_TRUE(PathExists(file_name_from));
1620 // Move the directory by using CopyAndDeleteDirectory
1621 FilePath dir_name_to = temp_dir_.path().Append(
1622 FILE_PATH_LITERAL("CopyAndDelete_To_Subdir"));
1623 FilePath file_name_to =
1624 dir_name_to.Append(FILE_PATH_LITERAL("CopyAndDelete_Test_File.txt"));
1626 ASSERT_FALSE(PathExists(dir_name_to));
1628 EXPECT_TRUE(internal::CopyAndDeleteDirectory(dir_name_from,
1629 dir_name_to));
1631 // Check everything has been moved.
1632 EXPECT_FALSE(PathExists(dir_name_from));
1633 EXPECT_FALSE(PathExists(file_name_from));
1634 EXPECT_TRUE(PathExists(dir_name_to));
1635 EXPECT_TRUE(PathExists(file_name_to));
1638 TEST_F(FileUtilTest, GetTempDirTest) {
1639 static const TCHAR* kTmpKey = _T("TMP");
1640 static const TCHAR* kTmpValues[] = {
1641 _T(""), _T("C:"), _T("C:\\"), _T("C:\\tmp"), _T("C:\\tmp\\")
1643 // Save the original $TMP.
1644 size_t original_tmp_size;
1645 TCHAR* original_tmp;
1646 ASSERT_EQ(0, ::_tdupenv_s(&original_tmp, &original_tmp_size, kTmpKey));
1647 // original_tmp may be NULL.
1649 for (unsigned int i = 0; i < arraysize(kTmpValues); ++i) {
1650 FilePath path;
1651 ::_tputenv_s(kTmpKey, kTmpValues[i]);
1652 GetTempDir(&path);
1653 EXPECT_TRUE(path.IsAbsolute()) << "$TMP=" << kTmpValues[i] <<
1654 " result=" << path.value();
1657 // Restore the original $TMP.
1658 if (original_tmp) {
1659 ::_tputenv_s(kTmpKey, original_tmp);
1660 free(original_tmp);
1661 } else {
1662 ::_tputenv_s(kTmpKey, _T(""));
1665 #endif // OS_WIN
1667 TEST_F(FileUtilTest, CreateTemporaryFileTest) {
1668 FilePath temp_files[3];
1669 for (int i = 0; i < 3; i++) {
1670 ASSERT_TRUE(CreateTemporaryFile(&(temp_files[i])));
1671 EXPECT_TRUE(PathExists(temp_files[i]));
1672 EXPECT_FALSE(DirectoryExists(temp_files[i]));
1674 for (int i = 0; i < 3; i++)
1675 EXPECT_FALSE(temp_files[i] == temp_files[(i+1)%3]);
1676 for (int i = 0; i < 3; i++)
1677 EXPECT_TRUE(DeleteFile(temp_files[i], false));
1680 TEST_F(FileUtilTest, CreateAndOpenTemporaryFileTest) {
1681 FilePath names[3];
1682 FILE* fps[3];
1683 int i;
1685 // Create; make sure they are open and exist.
1686 for (i = 0; i < 3; ++i) {
1687 fps[i] = CreateAndOpenTemporaryFile(&(names[i]));
1688 ASSERT_TRUE(fps[i]);
1689 EXPECT_TRUE(PathExists(names[i]));
1692 // Make sure all names are unique.
1693 for (i = 0; i < 3; ++i) {
1694 EXPECT_FALSE(names[i] == names[(i+1)%3]);
1697 // Close and delete.
1698 for (i = 0; i < 3; ++i) {
1699 EXPECT_TRUE(CloseFile(fps[i]));
1700 EXPECT_TRUE(DeleteFile(names[i], false));
1704 TEST_F(FileUtilTest, FileToFILE) {
1705 File file;
1706 FILE* stream = FileToFILE(file.Pass(), "w");
1707 EXPECT_FALSE(stream);
1709 FilePath file_name = temp_dir_.path().Append(FPL("The file.txt"));
1710 file = File(file_name, File::FLAG_CREATE | File::FLAG_WRITE);
1711 EXPECT_TRUE(file.IsValid());
1713 stream = FileToFILE(file.Pass(), "w");
1714 EXPECT_TRUE(stream);
1715 EXPECT_FALSE(file.IsValid());
1716 EXPECT_TRUE(CloseFile(stream));
1719 TEST_F(FileUtilTest, CreateNewTempDirectoryTest) {
1720 FilePath temp_dir;
1721 ASSERT_TRUE(CreateNewTempDirectory(FilePath::StringType(), &temp_dir));
1722 EXPECT_TRUE(PathExists(temp_dir));
1723 EXPECT_TRUE(DeleteFile(temp_dir, false));
1726 TEST_F(FileUtilTest, CreateNewTemporaryDirInDirTest) {
1727 FilePath new_dir;
1728 ASSERT_TRUE(CreateTemporaryDirInDir(
1729 temp_dir_.path(),
1730 FILE_PATH_LITERAL("CreateNewTemporaryDirInDirTest"),
1731 &new_dir));
1732 EXPECT_TRUE(PathExists(new_dir));
1733 EXPECT_TRUE(temp_dir_.path().IsParent(new_dir));
1734 EXPECT_TRUE(DeleteFile(new_dir, false));
1737 #if defined(OS_POSIX)
1738 TEST_F(FileUtilTest, GetShmemTempDirTest) {
1739 FilePath dir;
1740 EXPECT_TRUE(GetShmemTempDir(false, &dir));
1741 EXPECT_TRUE(DirectoryExists(dir));
1743 #endif
1745 TEST_F(FileUtilTest, GetHomeDirTest) {
1746 #if !defined(OS_ANDROID) // Not implemented on Android.
1747 // We don't actually know what the home directory is supposed to be without
1748 // calling some OS functions which would just duplicate the implementation.
1749 // So here we just test that it returns something "reasonable".
1750 FilePath home = GetHomeDir();
1751 ASSERT_FALSE(home.empty());
1752 ASSERT_TRUE(home.IsAbsolute());
1753 #endif
1756 TEST_F(FileUtilTest, CreateDirectoryTest) {
1757 FilePath test_root =
1758 temp_dir_.path().Append(FILE_PATH_LITERAL("create_directory_test"));
1759 #if defined(OS_WIN)
1760 FilePath test_path =
1761 test_root.Append(FILE_PATH_LITERAL("dir\\tree\\likely\\doesnt\\exist\\"));
1762 #elif defined(OS_POSIX)
1763 FilePath test_path =
1764 test_root.Append(FILE_PATH_LITERAL("dir/tree/likely/doesnt/exist/"));
1765 #endif
1767 EXPECT_FALSE(PathExists(test_path));
1768 EXPECT_TRUE(CreateDirectory(test_path));
1769 EXPECT_TRUE(PathExists(test_path));
1770 // CreateDirectory returns true if the DirectoryExists returns true.
1771 EXPECT_TRUE(CreateDirectory(test_path));
1773 // Doesn't work to create it on top of a non-dir
1774 test_path = test_path.Append(FILE_PATH_LITERAL("foobar.txt"));
1775 EXPECT_FALSE(PathExists(test_path));
1776 CreateTextFile(test_path, L"test file");
1777 EXPECT_TRUE(PathExists(test_path));
1778 EXPECT_FALSE(CreateDirectory(test_path));
1780 EXPECT_TRUE(DeleteFile(test_root, true));
1781 EXPECT_FALSE(PathExists(test_root));
1782 EXPECT_FALSE(PathExists(test_path));
1784 // Verify assumptions made by the Windows implementation:
1785 // 1. The current directory always exists.
1786 // 2. The root directory always exists.
1787 ASSERT_TRUE(DirectoryExists(FilePath(FilePath::kCurrentDirectory)));
1788 FilePath top_level = test_root;
1789 while (top_level != top_level.DirName()) {
1790 top_level = top_level.DirName();
1792 ASSERT_TRUE(DirectoryExists(top_level));
1794 // Given these assumptions hold, it should be safe to
1795 // test that "creating" these directories succeeds.
1796 EXPECT_TRUE(CreateDirectory(
1797 FilePath(FilePath::kCurrentDirectory)));
1798 EXPECT_TRUE(CreateDirectory(top_level));
1800 #if defined(OS_WIN)
1801 FilePath invalid_drive(FILE_PATH_LITERAL("o:\\"));
1802 FilePath invalid_path =
1803 invalid_drive.Append(FILE_PATH_LITERAL("some\\inaccessible\\dir"));
1804 if (!PathExists(invalid_drive)) {
1805 EXPECT_FALSE(CreateDirectory(invalid_path));
1807 #endif
1810 TEST_F(FileUtilTest, DetectDirectoryTest) {
1811 // Check a directory
1812 FilePath test_root =
1813 temp_dir_.path().Append(FILE_PATH_LITERAL("detect_directory_test"));
1814 EXPECT_FALSE(PathExists(test_root));
1815 EXPECT_TRUE(CreateDirectory(test_root));
1816 EXPECT_TRUE(PathExists(test_root));
1817 EXPECT_TRUE(DirectoryExists(test_root));
1818 // Check a file
1819 FilePath test_path =
1820 test_root.Append(FILE_PATH_LITERAL("foobar.txt"));
1821 EXPECT_FALSE(PathExists(test_path));
1822 CreateTextFile(test_path, L"test file");
1823 EXPECT_TRUE(PathExists(test_path));
1824 EXPECT_FALSE(DirectoryExists(test_path));
1825 EXPECT_TRUE(DeleteFile(test_path, false));
1827 EXPECT_TRUE(DeleteFile(test_root, true));
1830 TEST_F(FileUtilTest, FileEnumeratorTest) {
1831 // Test an empty directory.
1832 FileEnumerator f0(temp_dir_.path(), true, FILES_AND_DIRECTORIES);
1833 EXPECT_EQ(FPL(""), f0.Next().value());
1834 EXPECT_EQ(FPL(""), f0.Next().value());
1836 // Test an empty directory, non-recursively, including "..".
1837 FileEnumerator f0_dotdot(temp_dir_.path(), false,
1838 FILES_AND_DIRECTORIES | FileEnumerator::INCLUDE_DOT_DOT);
1839 EXPECT_EQ(temp_dir_.path().Append(FPL("..")).value(),
1840 f0_dotdot.Next().value());
1841 EXPECT_EQ(FPL(""), f0_dotdot.Next().value());
1843 // create the directories
1844 FilePath dir1 = temp_dir_.path().Append(FPL("dir1"));
1845 EXPECT_TRUE(CreateDirectory(dir1));
1846 FilePath dir2 = temp_dir_.path().Append(FPL("dir2"));
1847 EXPECT_TRUE(CreateDirectory(dir2));
1848 FilePath dir2inner = dir2.Append(FPL("inner"));
1849 EXPECT_TRUE(CreateDirectory(dir2inner));
1851 // create the files
1852 FilePath dir2file = dir2.Append(FPL("dir2file.txt"));
1853 CreateTextFile(dir2file, std::wstring());
1854 FilePath dir2innerfile = dir2inner.Append(FPL("innerfile.txt"));
1855 CreateTextFile(dir2innerfile, std::wstring());
1856 FilePath file1 = temp_dir_.path().Append(FPL("file1.txt"));
1857 CreateTextFile(file1, std::wstring());
1858 FilePath file2_rel = dir2.Append(FilePath::kParentDirectory)
1859 .Append(FPL("file2.txt"));
1860 CreateTextFile(file2_rel, std::wstring());
1861 FilePath file2_abs = temp_dir_.path().Append(FPL("file2.txt"));
1863 // Only enumerate files.
1864 FileEnumerator f1(temp_dir_.path(), true, FileEnumerator::FILES);
1865 FindResultCollector c1(&f1);
1866 EXPECT_TRUE(c1.HasFile(file1));
1867 EXPECT_TRUE(c1.HasFile(file2_abs));
1868 EXPECT_TRUE(c1.HasFile(dir2file));
1869 EXPECT_TRUE(c1.HasFile(dir2innerfile));
1870 EXPECT_EQ(4, c1.size());
1872 // Only enumerate directories.
1873 FileEnumerator f2(temp_dir_.path(), true, FileEnumerator::DIRECTORIES);
1874 FindResultCollector c2(&f2);
1875 EXPECT_TRUE(c2.HasFile(dir1));
1876 EXPECT_TRUE(c2.HasFile(dir2));
1877 EXPECT_TRUE(c2.HasFile(dir2inner));
1878 EXPECT_EQ(3, c2.size());
1880 // Only enumerate directories non-recursively.
1881 FileEnumerator f2_non_recursive(
1882 temp_dir_.path(), false, FileEnumerator::DIRECTORIES);
1883 FindResultCollector c2_non_recursive(&f2_non_recursive);
1884 EXPECT_TRUE(c2_non_recursive.HasFile(dir1));
1885 EXPECT_TRUE(c2_non_recursive.HasFile(dir2));
1886 EXPECT_EQ(2, c2_non_recursive.size());
1888 // Only enumerate directories, non-recursively, including "..".
1889 FileEnumerator f2_dotdot(temp_dir_.path(), false,
1890 FileEnumerator::DIRECTORIES |
1891 FileEnumerator::INCLUDE_DOT_DOT);
1892 FindResultCollector c2_dotdot(&f2_dotdot);
1893 EXPECT_TRUE(c2_dotdot.HasFile(dir1));
1894 EXPECT_TRUE(c2_dotdot.HasFile(dir2));
1895 EXPECT_TRUE(c2_dotdot.HasFile(temp_dir_.path().Append(FPL(".."))));
1896 EXPECT_EQ(3, c2_dotdot.size());
1898 // Enumerate files and directories.
1899 FileEnumerator f3(temp_dir_.path(), true, FILES_AND_DIRECTORIES);
1900 FindResultCollector c3(&f3);
1901 EXPECT_TRUE(c3.HasFile(dir1));
1902 EXPECT_TRUE(c3.HasFile(dir2));
1903 EXPECT_TRUE(c3.HasFile(file1));
1904 EXPECT_TRUE(c3.HasFile(file2_abs));
1905 EXPECT_TRUE(c3.HasFile(dir2file));
1906 EXPECT_TRUE(c3.HasFile(dir2inner));
1907 EXPECT_TRUE(c3.HasFile(dir2innerfile));
1908 EXPECT_EQ(7, c3.size());
1910 // Non-recursive operation.
1911 FileEnumerator f4(temp_dir_.path(), false, FILES_AND_DIRECTORIES);
1912 FindResultCollector c4(&f4);
1913 EXPECT_TRUE(c4.HasFile(dir2));
1914 EXPECT_TRUE(c4.HasFile(dir2));
1915 EXPECT_TRUE(c4.HasFile(file1));
1916 EXPECT_TRUE(c4.HasFile(file2_abs));
1917 EXPECT_EQ(4, c4.size());
1919 // Enumerate with a pattern.
1920 FileEnumerator f5(temp_dir_.path(), true, FILES_AND_DIRECTORIES, FPL("dir*"));
1921 FindResultCollector c5(&f5);
1922 EXPECT_TRUE(c5.HasFile(dir1));
1923 EXPECT_TRUE(c5.HasFile(dir2));
1924 EXPECT_TRUE(c5.HasFile(dir2file));
1925 EXPECT_TRUE(c5.HasFile(dir2inner));
1926 EXPECT_TRUE(c5.HasFile(dir2innerfile));
1927 EXPECT_EQ(5, c5.size());
1929 #if defined(OS_WIN)
1931 // Make dir1 point to dir2.
1932 ReparsePoint reparse_point(dir1, dir2);
1933 EXPECT_TRUE(reparse_point.IsValid());
1935 if ((win::GetVersion() >= win::VERSION_VISTA)) {
1936 // There can be a delay for the enumeration code to see the change on
1937 // the file system so skip this test for XP.
1938 // Enumerate the reparse point.
1939 FileEnumerator f6(dir1, true, FILES_AND_DIRECTORIES);
1940 FindResultCollector c6(&f6);
1941 FilePath inner2 = dir1.Append(FPL("inner"));
1942 EXPECT_TRUE(c6.HasFile(inner2));
1943 EXPECT_TRUE(c6.HasFile(inner2.Append(FPL("innerfile.txt"))));
1944 EXPECT_TRUE(c6.HasFile(dir1.Append(FPL("dir2file.txt"))));
1945 EXPECT_EQ(3, c6.size());
1948 // No changes for non recursive operation.
1949 FileEnumerator f7(temp_dir_.path(), false, FILES_AND_DIRECTORIES);
1950 FindResultCollector c7(&f7);
1951 EXPECT_TRUE(c7.HasFile(dir2));
1952 EXPECT_TRUE(c7.HasFile(dir2));
1953 EXPECT_TRUE(c7.HasFile(file1));
1954 EXPECT_TRUE(c7.HasFile(file2_abs));
1955 EXPECT_EQ(4, c7.size());
1957 // Should not enumerate inside dir1 when using recursion.
1958 FileEnumerator f8(temp_dir_.path(), true, FILES_AND_DIRECTORIES);
1959 FindResultCollector c8(&f8);
1960 EXPECT_TRUE(c8.HasFile(dir1));
1961 EXPECT_TRUE(c8.HasFile(dir2));
1962 EXPECT_TRUE(c8.HasFile(file1));
1963 EXPECT_TRUE(c8.HasFile(file2_abs));
1964 EXPECT_TRUE(c8.HasFile(dir2file));
1965 EXPECT_TRUE(c8.HasFile(dir2inner));
1966 EXPECT_TRUE(c8.HasFile(dir2innerfile));
1967 EXPECT_EQ(7, c8.size());
1969 #endif
1971 // Make sure the destructor closes the find handle while in the middle of a
1972 // query to allow TearDown to delete the directory.
1973 FileEnumerator f9(temp_dir_.path(), true, FILES_AND_DIRECTORIES);
1974 EXPECT_FALSE(f9.Next().value().empty()); // Should have found something
1975 // (we don't care what).
1978 TEST_F(FileUtilTest, AppendToFile) {
1979 FilePath data_dir =
1980 temp_dir_.path().Append(FILE_PATH_LITERAL("FilePathTest"));
1982 // Create a fresh, empty copy of this directory.
1983 if (PathExists(data_dir)) {
1984 ASSERT_TRUE(DeleteFile(data_dir, true));
1986 ASSERT_TRUE(CreateDirectory(data_dir));
1988 // Create a fresh, empty copy of this directory.
1989 if (PathExists(data_dir)) {
1990 ASSERT_TRUE(DeleteFile(data_dir, true));
1992 ASSERT_TRUE(CreateDirectory(data_dir));
1993 FilePath foobar(data_dir.Append(FILE_PATH_LITERAL("foobar.txt")));
1995 std::string data("hello");
1996 EXPECT_FALSE(AppendToFile(foobar, data.c_str(), data.size()));
1997 EXPECT_EQ(static_cast<int>(data.length()),
1998 WriteFile(foobar, data.c_str(), data.length()));
1999 EXPECT_TRUE(AppendToFile(foobar, data.c_str(), data.size()));
2001 const std::wstring read_content = ReadTextFile(foobar);
2002 EXPECT_EQ(L"hellohello", read_content);
2005 TEST_F(FileUtilTest, ReadFile) {
2006 // Create a test file to be read.
2007 const std::string kTestData("The quick brown fox jumps over the lazy dog.");
2008 FilePath file_path =
2009 temp_dir_.path().Append(FILE_PATH_LITERAL("ReadFileTest"));
2011 ASSERT_EQ(static_cast<int>(kTestData.size()),
2012 WriteFile(file_path, kTestData.data(), kTestData.size()));
2014 // Make buffers with various size.
2015 std::vector<char> small_buffer(kTestData.size() / 2);
2016 std::vector<char> exact_buffer(kTestData.size());
2017 std::vector<char> large_buffer(kTestData.size() * 2);
2019 // Read the file with smaller buffer.
2020 int bytes_read_small = ReadFile(
2021 file_path, &small_buffer[0], static_cast<int>(small_buffer.size()));
2022 EXPECT_EQ(static_cast<int>(small_buffer.size()), bytes_read_small);
2023 EXPECT_EQ(
2024 std::string(kTestData.begin(), kTestData.begin() + small_buffer.size()),
2025 std::string(small_buffer.begin(), small_buffer.end()));
2027 // Read the file with buffer which have exactly same size.
2028 int bytes_read_exact = ReadFile(
2029 file_path, &exact_buffer[0], static_cast<int>(exact_buffer.size()));
2030 EXPECT_EQ(static_cast<int>(kTestData.size()), bytes_read_exact);
2031 EXPECT_EQ(kTestData, std::string(exact_buffer.begin(), exact_buffer.end()));
2033 // Read the file with larger buffer.
2034 int bytes_read_large = ReadFile(
2035 file_path, &large_buffer[0], static_cast<int>(large_buffer.size()));
2036 EXPECT_EQ(static_cast<int>(kTestData.size()), bytes_read_large);
2037 EXPECT_EQ(kTestData, std::string(large_buffer.begin(),
2038 large_buffer.begin() + kTestData.size()));
2040 // Make sure the return value is -1 if the file doesn't exist.
2041 FilePath file_path_not_exist =
2042 temp_dir_.path().Append(FILE_PATH_LITERAL("ReadFileNotExistTest"));
2043 EXPECT_EQ(-1,
2044 ReadFile(file_path_not_exist,
2045 &exact_buffer[0],
2046 static_cast<int>(exact_buffer.size())));
2049 TEST_F(FileUtilTest, ReadFileToString) {
2050 const char kTestData[] = "0123";
2051 std::string data;
2053 FilePath file_path =
2054 temp_dir_.path().Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
2055 FilePath file_path_dangerous =
2056 temp_dir_.path().Append(FILE_PATH_LITERAL("..")).
2057 Append(temp_dir_.path().BaseName()).
2058 Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
2060 // Create test file.
2061 ASSERT_EQ(4, WriteFile(file_path, kTestData, 4));
2063 EXPECT_TRUE(ReadFileToString(file_path, &data));
2064 EXPECT_EQ(kTestData, data);
2066 data = "temp";
2067 EXPECT_FALSE(ReadFileToString(file_path, &data, 0));
2068 EXPECT_EQ(0u, data.length());
2070 data = "temp";
2071 EXPECT_FALSE(ReadFileToString(file_path, &data, 2));
2072 EXPECT_EQ("01", data);
2074 data.clear();
2075 EXPECT_FALSE(ReadFileToString(file_path, &data, 3));
2076 EXPECT_EQ("012", data);
2078 data.clear();
2079 EXPECT_TRUE(ReadFileToString(file_path, &data, 4));
2080 EXPECT_EQ("0123", data);
2082 data.clear();
2083 EXPECT_TRUE(ReadFileToString(file_path, &data, 6));
2084 EXPECT_EQ("0123", data);
2086 EXPECT_TRUE(ReadFileToString(file_path, NULL, 6));
2088 EXPECT_TRUE(ReadFileToString(file_path, NULL));
2090 data = "temp";
2091 EXPECT_FALSE(ReadFileToString(file_path_dangerous, &data));
2092 EXPECT_EQ(0u, data.length());
2094 // Delete test file.
2095 EXPECT_TRUE(DeleteFile(file_path, false));
2097 data = "temp";
2098 EXPECT_FALSE(ReadFileToString(file_path, &data));
2099 EXPECT_EQ(0u, data.length());
2101 data = "temp";
2102 EXPECT_FALSE(ReadFileToString(file_path, &data, 6));
2103 EXPECT_EQ(0u, data.length());
2106 TEST_F(FileUtilTest, TouchFile) {
2107 FilePath data_dir =
2108 temp_dir_.path().Append(FILE_PATH_LITERAL("FilePathTest"));
2110 // Create a fresh, empty copy of this directory.
2111 if (PathExists(data_dir)) {
2112 ASSERT_TRUE(DeleteFile(data_dir, true));
2114 ASSERT_TRUE(CreateDirectory(data_dir));
2116 FilePath foobar(data_dir.Append(FILE_PATH_LITERAL("foobar.txt")));
2117 std::string data("hello");
2118 ASSERT_TRUE(WriteFile(foobar, data.c_str(), data.length()));
2120 Time access_time;
2121 // This timestamp is divisible by one day (in local timezone),
2122 // to make it work on FAT too.
2123 ASSERT_TRUE(Time::FromString("Wed, 16 Nov 1994, 00:00:00",
2124 &access_time));
2126 Time modification_time;
2127 // Note that this timestamp is divisible by two (seconds) - FAT stores
2128 // modification times with 2s resolution.
2129 ASSERT_TRUE(Time::FromString("Tue, 15 Nov 1994, 12:45:26 GMT",
2130 &modification_time));
2132 ASSERT_TRUE(TouchFile(foobar, access_time, modification_time));
2133 File::Info file_info;
2134 ASSERT_TRUE(GetFileInfo(foobar, &file_info));
2135 EXPECT_EQ(access_time.ToInternalValue(),
2136 file_info.last_accessed.ToInternalValue());
2137 EXPECT_EQ(modification_time.ToInternalValue(),
2138 file_info.last_modified.ToInternalValue());
2141 TEST_F(FileUtilTest, IsDirectoryEmpty) {
2142 FilePath empty_dir = temp_dir_.path().Append(FILE_PATH_LITERAL("EmptyDir"));
2144 ASSERT_FALSE(PathExists(empty_dir));
2146 ASSERT_TRUE(CreateDirectory(empty_dir));
2148 EXPECT_TRUE(IsDirectoryEmpty(empty_dir));
2150 FilePath foo(empty_dir.Append(FILE_PATH_LITERAL("foo.txt")));
2151 std::string bar("baz");
2152 ASSERT_TRUE(WriteFile(foo, bar.c_str(), bar.length()));
2154 EXPECT_FALSE(IsDirectoryEmpty(empty_dir));
2157 #if defined(OS_POSIX)
2159 // Testing VerifyPathControlledByAdmin() is hard, because there is no
2160 // way a test can make a file owned by root, or change file paths
2161 // at the root of the file system. VerifyPathControlledByAdmin()
2162 // is implemented as a call to VerifyPathControlledByUser, which gives
2163 // us the ability to test with paths under the test's temp directory,
2164 // using a user id we control.
2165 // Pull tests of VerifyPathControlledByUserTest() into a separate test class
2166 // with a common SetUp() method.
2167 class VerifyPathControlledByUserTest : public FileUtilTest {
2168 protected:
2169 void SetUp() override {
2170 FileUtilTest::SetUp();
2172 // Create a basic structure used by each test.
2173 // base_dir_
2174 // |-> sub_dir_
2175 // |-> text_file_
2177 base_dir_ = temp_dir_.path().AppendASCII("base_dir");
2178 ASSERT_TRUE(CreateDirectory(base_dir_));
2180 sub_dir_ = base_dir_.AppendASCII("sub_dir");
2181 ASSERT_TRUE(CreateDirectory(sub_dir_));
2183 text_file_ = sub_dir_.AppendASCII("file.txt");
2184 CreateTextFile(text_file_, L"This text file has some text in it.");
2186 // Get the user and group files are created with from |base_dir_|.
2187 struct stat stat_buf;
2188 ASSERT_EQ(0, stat(base_dir_.value().c_str(), &stat_buf));
2189 uid_ = stat_buf.st_uid;
2190 ok_gids_.insert(stat_buf.st_gid);
2191 bad_gids_.insert(stat_buf.st_gid + 1);
2193 ASSERT_EQ(uid_, getuid()); // This process should be the owner.
2195 // To ensure that umask settings do not cause the initial state
2196 // of permissions to be different from what we expect, explicitly
2197 // set permissions on the directories we create.
2198 // Make all files and directories non-world-writable.
2200 // Users and group can read, write, traverse
2201 int enabled_permissions =
2202 FILE_PERMISSION_USER_MASK | FILE_PERMISSION_GROUP_MASK;
2203 // Other users can't read, write, traverse
2204 int disabled_permissions = FILE_PERMISSION_OTHERS_MASK;
2206 ASSERT_NO_FATAL_FAILURE(
2207 ChangePosixFilePermissions(
2208 base_dir_, enabled_permissions, disabled_permissions));
2209 ASSERT_NO_FATAL_FAILURE(
2210 ChangePosixFilePermissions(
2211 sub_dir_, enabled_permissions, disabled_permissions));
2214 FilePath base_dir_;
2215 FilePath sub_dir_;
2216 FilePath text_file_;
2217 uid_t uid_;
2219 std::set<gid_t> ok_gids_;
2220 std::set<gid_t> bad_gids_;
2223 TEST_F(VerifyPathControlledByUserTest, BadPaths) {
2224 // File does not exist.
2225 FilePath does_not_exist = base_dir_.AppendASCII("does")
2226 .AppendASCII("not")
2227 .AppendASCII("exist");
2228 EXPECT_FALSE(
2229 VerifyPathControlledByUser(base_dir_, does_not_exist, uid_, ok_gids_));
2231 // |base| not a subpath of |path|.
2232 EXPECT_FALSE(VerifyPathControlledByUser(sub_dir_, base_dir_, uid_, ok_gids_));
2234 // An empty base path will fail to be a prefix for any path.
2235 FilePath empty;
2236 EXPECT_FALSE(VerifyPathControlledByUser(empty, base_dir_, uid_, ok_gids_));
2238 // Finding that a bad call fails proves nothing unless a good call succeeds.
2239 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
2242 TEST_F(VerifyPathControlledByUserTest, Symlinks) {
2243 // Symlinks in the path should cause failure.
2245 // Symlink to the file at the end of the path.
2246 FilePath file_link = base_dir_.AppendASCII("file_link");
2247 ASSERT_TRUE(CreateSymbolicLink(text_file_, file_link))
2248 << "Failed to create symlink.";
2250 EXPECT_FALSE(
2251 VerifyPathControlledByUser(base_dir_, file_link, uid_, ok_gids_));
2252 EXPECT_FALSE(
2253 VerifyPathControlledByUser(file_link, file_link, uid_, ok_gids_));
2255 // Symlink from one directory to another within the path.
2256 FilePath link_to_sub_dir = base_dir_.AppendASCII("link_to_sub_dir");
2257 ASSERT_TRUE(CreateSymbolicLink(sub_dir_, link_to_sub_dir))
2258 << "Failed to create symlink.";
2260 FilePath file_path_with_link = link_to_sub_dir.AppendASCII("file.txt");
2261 ASSERT_TRUE(PathExists(file_path_with_link));
2263 EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, file_path_with_link, uid_,
2264 ok_gids_));
2266 EXPECT_FALSE(VerifyPathControlledByUser(link_to_sub_dir, file_path_with_link,
2267 uid_, ok_gids_));
2269 // Symlinks in parents of base path are allowed.
2270 EXPECT_TRUE(VerifyPathControlledByUser(file_path_with_link,
2271 file_path_with_link, uid_, ok_gids_));
2274 TEST_F(VerifyPathControlledByUserTest, OwnershipChecks) {
2275 // Get a uid that is not the uid of files we create.
2276 uid_t bad_uid = uid_ + 1;
2278 // Make all files and directories non-world-writable.
2279 ASSERT_NO_FATAL_FAILURE(
2280 ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
2281 ASSERT_NO_FATAL_FAILURE(
2282 ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
2283 ASSERT_NO_FATAL_FAILURE(
2284 ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
2286 // We control these paths.
2287 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
2288 EXPECT_TRUE(
2289 VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
2290 EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
2292 // Another user does not control these paths.
2293 EXPECT_FALSE(
2294 VerifyPathControlledByUser(base_dir_, sub_dir_, bad_uid, ok_gids_));
2295 EXPECT_FALSE(
2296 VerifyPathControlledByUser(base_dir_, text_file_, bad_uid, ok_gids_));
2297 EXPECT_FALSE(
2298 VerifyPathControlledByUser(sub_dir_, text_file_, bad_uid, ok_gids_));
2300 // Another group does not control the paths.
2301 EXPECT_FALSE(
2302 VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, bad_gids_));
2303 EXPECT_FALSE(
2304 VerifyPathControlledByUser(base_dir_, text_file_, uid_, bad_gids_));
2305 EXPECT_FALSE(
2306 VerifyPathControlledByUser(sub_dir_, text_file_, uid_, bad_gids_));
2309 TEST_F(VerifyPathControlledByUserTest, GroupWriteTest) {
2310 // Make all files and directories writable only by their owner.
2311 ASSERT_NO_FATAL_FAILURE(
2312 ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH|S_IWGRP));
2313 ASSERT_NO_FATAL_FAILURE(
2314 ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH|S_IWGRP));
2315 ASSERT_NO_FATAL_FAILURE(
2316 ChangePosixFilePermissions(text_file_, 0u, S_IWOTH|S_IWGRP));
2318 // Any group is okay because the path is not group-writable.
2319 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
2320 EXPECT_TRUE(
2321 VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
2322 EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
2324 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, bad_gids_));
2325 EXPECT_TRUE(
2326 VerifyPathControlledByUser(base_dir_, text_file_, uid_, bad_gids_));
2327 EXPECT_TRUE(
2328 VerifyPathControlledByUser(sub_dir_, text_file_, uid_, bad_gids_));
2330 // No group is okay, because we don't check the group
2331 // if no group can write.
2332 std::set<gid_t> no_gids; // Empty set of gids.
2333 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, no_gids));
2334 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, text_file_, uid_, no_gids));
2335 EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, no_gids));
2337 // Make all files and directories writable by their group.
2338 ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(base_dir_, S_IWGRP, 0u));
2339 ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(sub_dir_, S_IWGRP, 0u));
2340 ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(text_file_, S_IWGRP, 0u));
2342 // Now |ok_gids_| works, but |bad_gids_| fails.
2343 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
2344 EXPECT_TRUE(
2345 VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
2346 EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
2348 EXPECT_FALSE(
2349 VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, bad_gids_));
2350 EXPECT_FALSE(
2351 VerifyPathControlledByUser(base_dir_, text_file_, uid_, bad_gids_));
2352 EXPECT_FALSE(
2353 VerifyPathControlledByUser(sub_dir_, text_file_, uid_, bad_gids_));
2355 // Because any group in the group set is allowed,
2356 // the union of good and bad gids passes.
2358 std::set<gid_t> multiple_gids;
2359 std::set_union(
2360 ok_gids_.begin(), ok_gids_.end(),
2361 bad_gids_.begin(), bad_gids_.end(),
2362 std::inserter(multiple_gids, multiple_gids.begin()));
2364 EXPECT_TRUE(
2365 VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, multiple_gids));
2366 EXPECT_TRUE(
2367 VerifyPathControlledByUser(base_dir_, text_file_, uid_, multiple_gids));
2368 EXPECT_TRUE(
2369 VerifyPathControlledByUser(sub_dir_, text_file_, uid_, multiple_gids));
2372 TEST_F(VerifyPathControlledByUserTest, WriteBitChecks) {
2373 // Make all files and directories non-world-writable.
2374 ASSERT_NO_FATAL_FAILURE(
2375 ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
2376 ASSERT_NO_FATAL_FAILURE(
2377 ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
2378 ASSERT_NO_FATAL_FAILURE(
2379 ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
2381 // Initialy, we control all parts of the path.
2382 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
2383 EXPECT_TRUE(
2384 VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
2385 EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
2387 // Make base_dir_ world-writable.
2388 ASSERT_NO_FATAL_FAILURE(
2389 ChangePosixFilePermissions(base_dir_, S_IWOTH, 0u));
2390 EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
2391 EXPECT_FALSE(
2392 VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
2393 EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
2395 // Make sub_dir_ world writable.
2396 ASSERT_NO_FATAL_FAILURE(
2397 ChangePosixFilePermissions(sub_dir_, S_IWOTH, 0u));
2398 EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
2399 EXPECT_FALSE(
2400 VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
2401 EXPECT_FALSE(
2402 VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
2404 // Make text_file_ world writable.
2405 ASSERT_NO_FATAL_FAILURE(
2406 ChangePosixFilePermissions(text_file_, S_IWOTH, 0u));
2407 EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
2408 EXPECT_FALSE(
2409 VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
2410 EXPECT_FALSE(
2411 VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
2413 // Make sub_dir_ non-world writable.
2414 ASSERT_NO_FATAL_FAILURE(
2415 ChangePosixFilePermissions(sub_dir_, 0u, S_IWOTH));
2416 EXPECT_FALSE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
2417 EXPECT_FALSE(
2418 VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
2419 EXPECT_FALSE(
2420 VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
2422 // Make base_dir_ non-world-writable.
2423 ASSERT_NO_FATAL_FAILURE(
2424 ChangePosixFilePermissions(base_dir_, 0u, S_IWOTH));
2425 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
2426 EXPECT_FALSE(
2427 VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
2428 EXPECT_FALSE(
2429 VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
2431 // Back to the initial state: Nothing is writable, so every path
2432 // should pass.
2433 ASSERT_NO_FATAL_FAILURE(
2434 ChangePosixFilePermissions(text_file_, 0u, S_IWOTH));
2435 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_, sub_dir_, uid_, ok_gids_));
2436 EXPECT_TRUE(
2437 VerifyPathControlledByUser(base_dir_, text_file_, uid_, ok_gids_));
2438 EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_, text_file_, uid_, ok_gids_));
2441 #if defined(OS_ANDROID)
2442 TEST_F(FileUtilTest, ValidContentUriTest) {
2443 // Get the test image path.
2444 FilePath data_dir;
2445 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
2446 data_dir = data_dir.AppendASCII("file_util");
2447 ASSERT_TRUE(PathExists(data_dir));
2448 FilePath image_file = data_dir.Append(FILE_PATH_LITERAL("red.png"));
2449 int64 image_size;
2450 GetFileSize(image_file, &image_size);
2451 EXPECT_LT(0, image_size);
2453 // Insert the image into MediaStore. MediaStore will do some conversions, and
2454 // return the content URI.
2455 FilePath path = InsertImageIntoMediaStore(image_file);
2456 EXPECT_TRUE(path.IsContentUri());
2457 EXPECT_TRUE(PathExists(path));
2458 // The file size may not equal to the input image as MediaStore may convert
2459 // the image.
2460 int64 content_uri_size;
2461 GetFileSize(path, &content_uri_size);
2462 EXPECT_EQ(image_size, content_uri_size);
2464 // We should be able to read the file.
2465 char* buffer = new char[image_size];
2466 File file = OpenContentUriForRead(path);
2467 EXPECT_TRUE(file.IsValid());
2468 EXPECT_TRUE(file.ReadAtCurrentPos(buffer, image_size));
2469 delete[] buffer;
2472 TEST_F(FileUtilTest, NonExistentContentUriTest) {
2473 FilePath path("content://foo.bar");
2474 EXPECT_TRUE(path.IsContentUri());
2475 EXPECT_FALSE(PathExists(path));
2476 // Size should be smaller than 0.
2477 int64 size;
2478 EXPECT_FALSE(GetFileSize(path, &size));
2480 // We should not be able to read the file.
2481 File file = OpenContentUriForRead(path);
2482 EXPECT_FALSE(file.IsValid());
2484 #endif
2486 TEST(ScopedFD, ScopedFDDoesClose) {
2487 int fds[2];
2488 char c = 0;
2489 ASSERT_EQ(0, pipe(fds));
2490 const int write_end = fds[1];
2491 ScopedFD read_end_closer(fds[0]);
2493 ScopedFD write_end_closer(fds[1]);
2495 // This is the only thread. This file descriptor should no longer be valid.
2496 int ret = close(write_end);
2497 EXPECT_EQ(-1, ret);
2498 EXPECT_EQ(EBADF, errno);
2499 // Make sure read(2) won't block.
2500 ASSERT_EQ(0, fcntl(fds[0], F_SETFL, O_NONBLOCK));
2501 // Reading the pipe should EOF.
2502 EXPECT_EQ(0, read(fds[0], &c, 1));
2505 #if defined(GTEST_HAS_DEATH_TEST)
2506 void CloseWithScopedFD(int fd) {
2507 ScopedFD fd_closer(fd);
2509 #endif
2511 TEST(ScopedFD, ScopedFDCrashesOnCloseFailure) {
2512 int fds[2];
2513 ASSERT_EQ(0, pipe(fds));
2514 ScopedFD read_end_closer(fds[0]);
2515 EXPECT_EQ(0, IGNORE_EINTR(close(fds[1])));
2516 #if defined(GTEST_HAS_DEATH_TEST)
2517 // This is the only thread. This file descriptor should no longer be valid.
2518 // Trying to close it should crash. This is important for security.
2519 EXPECT_DEATH(CloseWithScopedFD(fds[1]), "");
2520 #endif
2523 #endif // defined(OS_POSIX)
2525 } // namespace
2527 } // namespace base