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"
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"
41 #include "base/win/scoped_handle.h"
42 #include "base/win/windows_version.h"
45 #if defined(OS_ANDROID)
46 #include "base/android/content_uri_utils.h"
49 // This macro helps avoid wrapped lines in the test structs.
50 #define FPL(x) FILE_PATH_LITERAL(x)
56 // To test that NormalizeFilePath() deals with NTFS reparse points correctly,
57 // we need functions to create and delete reparse points.
59 typedef struct _REPARSE_DATA_BUFFER
{
61 USHORT ReparseDataLength
;
65 USHORT SubstituteNameOffset
;
66 USHORT SubstituteNameLength
;
67 USHORT PrintNameOffset
;
68 USHORT PrintNameLength
;
71 } SymbolicLinkReparseBuffer
;
73 USHORT SubstituteNameOffset
;
74 USHORT SubstituteNameLength
;
75 USHORT PrintNameOffset
;
76 USHORT PrintNameLength
;
78 } MountPointReparseBuffer
;
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};
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
)) {
117 // Delete the reparse point referenced by |source|. Returns true if the call
118 // succeeds, false otherwise.
119 bool DeleteReparsePoint(HANDLE source
) {
121 REPARSE_DATA_BUFFER data
= {0};
122 data
.ReparseTag
= 0xa0000003;
123 if (!DeviceIoControl(source
, FSCTL_DELETE_REPARSE_POINT
, &data
, 8, NULL
, 0,
130 // Manages a reparse point for a test.
133 // Creates a reparse point from |source| (an empty directory) to |target|.
134 ReparsePoint(const FilePath
& source
, const FilePath
& target
) {
136 ::CreateFile(source
.value().c_str(),
138 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
141 FILE_FLAG_BACKUP_SEMANTICS
, // Needed to open a directory.
143 created_
= dir_
.IsValid() && SetReparsePoint(dir_
.Get(), target
);
148 DeleteReparsePoint(dir_
.Get());
151 bool IsValid() { return created_
; }
154 win::ScopedHandle dir_
;
156 DISALLOW_COPY_AND_ASSIGN(ReparsePoint
);
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.";
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
{
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
{
200 explicit FindResultCollector(FileEnumerator
* enumerator
) {
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";
213 // Returns true if the enumerator found the file.
214 bool HasFile(const FilePath
& file
) const {
215 return files_
.find(file
.value()) != files_
.end();
219 return static_cast<int>(files_
.size());
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
) {
230 file
.open(filename
.value().c_str());
231 ASSERT_TRUE(file
.is_open());
236 // Simple function to take out some text from a file.
237 std::wstring
ReadTextFile(const FilePath
& filename
) {
238 wchar_t contents
[64];
240 file
.open(filename
.value().c_str());
241 EXPECT_TRUE(file
.is_open());
242 file
.getline(contents
, arraysize(contents
));
244 return std::wstring(contents
);
248 uint64
FileTimeAsUint64(const FILETIME
& ft
) {
250 u
.LowPart
= ft
.dwLowDateTime
;
251 u
.HighPart
= ft
.dwHighDateTime
;
256 TEST_F(FileUtilTest
, FileAndDirectorySize
) {
257 // Create three files of 20, 30 and 3 chars (utf8). ComputeDirectorySize
258 // should return 53 bytes.
259 FilePath file_01
= temp_dir_
.path().Append(FPL("The file 01.txt"));
260 CreateTextFile(file_01
, L
"12345678901234567890");
262 ASSERT_TRUE(GetFileSize(file_01
, &size_f1
));
263 EXPECT_EQ(20ll, size_f1
);
265 FilePath subdir_path
= temp_dir_
.path().Append(FPL("Level2"));
266 CreateDirectory(subdir_path
);
268 FilePath file_02
= subdir_path
.Append(FPL("The file 02.txt"));
269 CreateTextFile(file_02
, L
"123456789012345678901234567890");
271 ASSERT_TRUE(GetFileSize(file_02
, &size_f2
));
272 EXPECT_EQ(30ll, size_f2
);
274 FilePath subsubdir_path
= subdir_path
.Append(FPL("Level3"));
275 CreateDirectory(subsubdir_path
);
277 FilePath file_03
= subsubdir_path
.Append(FPL("The file 03.txt"));
278 CreateTextFile(file_03
, L
"123");
280 int64 computed_size
= ComputeDirectorySize(temp_dir_
.path());
281 EXPECT_EQ(size_f1
+ size_f2
+ 3, computed_size
);
284 TEST_F(FileUtilTest
, NormalizeFilePathBasic
) {
285 // Create a directory under the test dir. Because we create it,
286 // we know it is not a link.
287 FilePath file_a_path
= temp_dir_
.path().Append(FPL("file_a"));
288 FilePath dir_path
= temp_dir_
.path().Append(FPL("dir"));
289 FilePath file_b_path
= dir_path
.Append(FPL("file_b"));
290 CreateDirectory(dir_path
);
292 FilePath normalized_file_a_path
, normalized_file_b_path
;
293 ASSERT_FALSE(PathExists(file_a_path
));
294 ASSERT_FALSE(NormalizeFilePath(file_a_path
, &normalized_file_a_path
))
295 << "NormalizeFilePath() should fail on nonexistent paths.";
297 CreateTextFile(file_a_path
, bogus_content
);
298 ASSERT_TRUE(PathExists(file_a_path
));
299 ASSERT_TRUE(NormalizeFilePath(file_a_path
, &normalized_file_a_path
));
301 CreateTextFile(file_b_path
, bogus_content
);
302 ASSERT_TRUE(PathExists(file_b_path
));
303 ASSERT_TRUE(NormalizeFilePath(file_b_path
, &normalized_file_b_path
));
305 // Beacuse this test created |dir_path|, we know it is not a link
306 // or junction. So, the real path of the directory holding file a
307 // must be the parent of the path holding file b.
308 ASSERT_TRUE(normalized_file_a_path
.DirName()
309 .IsParent(normalized_file_b_path
.DirName()));
314 TEST_F(FileUtilTest
, NormalizeFilePathReparsePoints
) {
315 // Build the following directory structure:
321 // | |-> long_name___... (Very long name.)
325 // |-> to_sub_a (reparse point to temp_dir\base_a\sub_a)
326 // |-> to_base_b (reparse point to temp_dir\base_b)
327 // |-> to_sub_long (reparse point to temp_dir\sub_a\long_name_\sub_long)
329 FilePath base_a
= temp_dir_
.path().Append(FPL("base_a"));
331 // TEMP can have a lower case drive letter.
332 string16 temp_base_a
= base_a
.value();
333 ASSERT_FALSE(temp_base_a
.empty());
334 *temp_base_a
.begin() = ToUpperASCII(*temp_base_a
.begin());
335 base_a
= FilePath(temp_base_a
);
337 ASSERT_TRUE(CreateDirectory(base_a
));
339 FilePath sub_a
= base_a
.Append(FPL("sub_a"));
340 ASSERT_TRUE(CreateDirectory(sub_a
));
342 FilePath file_txt
= sub_a
.Append(FPL("file.txt"));
343 CreateTextFile(file_txt
, bogus_content
);
345 // Want a directory whose name is long enough to make the path to the file
346 // inside just under MAX_PATH chars. This will be used to test that when
347 // a junction expands to a path over MAX_PATH chars in length,
348 // NormalizeFilePath() fails without crashing.
349 FilePath
sub_long_rel(FPL("sub_long"));
350 FilePath
deep_txt(FPL("deep.txt"));
352 int target_length
= MAX_PATH
;
353 target_length
-= (sub_a
.value().length() + 1); // +1 for the sepperator '\'.
354 target_length
-= (sub_long_rel
.Append(deep_txt
).value().length() + 1);
355 // Without making the path a bit shorter, CreateDirectory() fails.
356 // the resulting path is still long enough to hit the failing case in
358 const int kCreateDirLimit
= 4;
359 target_length
-= kCreateDirLimit
;
360 FilePath::StringType long_name_str
= FPL("long_name_");
361 long_name_str
.resize(target_length
, '_');
363 FilePath long_name
= sub_a
.Append(FilePath(long_name_str
));
364 FilePath deep_file
= long_name
.Append(sub_long_rel
).Append(deep_txt
);
365 ASSERT_EQ(MAX_PATH
- kCreateDirLimit
, deep_file
.value().length());
367 FilePath sub_long
= deep_file
.DirName();
368 ASSERT_TRUE(CreateDirectory(sub_long
));
369 CreateTextFile(deep_file
, bogus_content
);
371 FilePath base_b
= temp_dir_
.path().Append(FPL("base_b"));
372 ASSERT_TRUE(CreateDirectory(base_b
));
374 FilePath to_sub_a
= base_b
.Append(FPL("to_sub_a"));
375 ASSERT_TRUE(CreateDirectory(to_sub_a
));
376 FilePath normalized_path
;
378 ReparsePoint
reparse_to_sub_a(to_sub_a
, sub_a
);
379 ASSERT_TRUE(reparse_to_sub_a
.IsValid());
381 FilePath to_base_b
= base_b
.Append(FPL("to_base_b"));
382 ASSERT_TRUE(CreateDirectory(to_base_b
));
383 ReparsePoint
reparse_to_base_b(to_base_b
, base_b
);
384 ASSERT_TRUE(reparse_to_base_b
.IsValid());
386 FilePath to_sub_long
= base_b
.Append(FPL("to_sub_long"));
387 ASSERT_TRUE(CreateDirectory(to_sub_long
));
388 ReparsePoint
reparse_to_sub_long(to_sub_long
, sub_long
);
389 ASSERT_TRUE(reparse_to_sub_long
.IsValid());
391 // Normalize a junction free path: base_a\sub_a\file.txt .
392 ASSERT_TRUE(NormalizeFilePath(file_txt
, &normalized_path
));
393 ASSERT_STREQ(file_txt
.value().c_str(), normalized_path
.value().c_str());
395 // Check that the path base_b\to_sub_a\file.txt can be normalized to exclude
396 // the junction to_sub_a.
397 ASSERT_TRUE(NormalizeFilePath(to_sub_a
.Append(FPL("file.txt")),
399 ASSERT_STREQ(file_txt
.value().c_str(), normalized_path
.value().c_str());
401 // Check that the path base_b\to_base_b\to_base_b\to_sub_a\file.txt can be
402 // normalized to exclude junctions to_base_b and to_sub_a .
403 ASSERT_TRUE(NormalizeFilePath(base_b
.Append(FPL("to_base_b"))
404 .Append(FPL("to_base_b"))
405 .Append(FPL("to_sub_a"))
406 .Append(FPL("file.txt")),
408 ASSERT_STREQ(file_txt
.value().c_str(), normalized_path
.value().c_str());
410 // A long enough path will cause NormalizeFilePath() to fail. Make a long
411 // path using to_base_b many times, and check that paths long enough to fail
412 // do not cause a crash.
413 FilePath long_path
= base_b
;
414 const int kLengthLimit
= MAX_PATH
+ 200;
415 while (long_path
.value().length() <= kLengthLimit
) {
416 long_path
= long_path
.Append(FPL("to_base_b"));
418 long_path
= long_path
.Append(FPL("to_sub_a"))
419 .Append(FPL("file.txt"));
421 ASSERT_FALSE(NormalizeFilePath(long_path
, &normalized_path
));
423 // Normalizing the junction to deep.txt should fail, because the expanded
424 // path to deep.txt is longer than MAX_PATH.
425 ASSERT_FALSE(NormalizeFilePath(to_sub_long
.Append(deep_txt
),
428 // Delete the reparse points, and see that NormalizeFilePath() fails
432 ASSERT_FALSE(NormalizeFilePath(to_sub_a
.Append(FPL("file.txt")),
436 TEST_F(FileUtilTest
, DevicePathToDriveLetter
) {
437 // Get a drive letter.
438 std::wstring real_drive_letter
= temp_dir_
.path().value().substr(0, 2);
439 StringToUpperASCII(&real_drive_letter
);
440 if (!isalpha(real_drive_letter
[0]) || ':' != real_drive_letter
[1]) {
441 LOG(ERROR
) << "Can't get a drive letter to test with.";
445 // Get the NT style path to that drive.
446 wchar_t device_path
[MAX_PATH
] = {'\0'};
448 ::QueryDosDevice(real_drive_letter
.c_str(), device_path
, MAX_PATH
));
449 FilePath
actual_device_path(device_path
);
452 // Run DevicePathToDriveLetterPath() on the NT style path we got from
453 // QueryDosDevice(). Expect the drive letter we started with.
454 ASSERT_TRUE(DevicePathToDriveLetterPath(actual_device_path
, &win32_path
));
455 ASSERT_EQ(real_drive_letter
, win32_path
.value());
457 // Add some directories to the path. Expect those extra path componenets
459 FilePath
kRelativePath(FPL("dir1\\dir2\\file.txt"));
460 ASSERT_TRUE(DevicePathToDriveLetterPath(
461 actual_device_path
.Append(kRelativePath
),
463 EXPECT_EQ(FilePath(real_drive_letter
+ L
"\\").Append(kRelativePath
).value(),
466 // Deform the real path so that it is invalid by removing the last four
467 // characters. The way windows names devices that are hard disks
468 // (\Device\HardDiskVolume${NUMBER}) guarantees that the string is longer
469 // than three characters. The only way the truncated string could be a
470 // real drive is if more than 10^3 disks are mounted:
471 // \Device\HardDiskVolume10000 would be truncated to \Device\HardDiskVolume1
472 // Check that DevicePathToDriveLetterPath fails.
473 int path_length
= actual_device_path
.value().length();
474 int new_length
= path_length
- 4;
475 ASSERT_LT(0, new_length
);
476 FilePath
prefix_of_real_device_path(
477 actual_device_path
.value().substr(0, new_length
));
478 ASSERT_FALSE(DevicePathToDriveLetterPath(prefix_of_real_device_path
,
481 ASSERT_FALSE(DevicePathToDriveLetterPath(
482 prefix_of_real_device_path
.Append(kRelativePath
),
485 // Deform the real path so that it is invalid by adding some characters. For
486 // example, if C: maps to \Device\HardDiskVolume8, then we simulate a
487 // request for the drive letter whose native path is
488 // \Device\HardDiskVolume812345 . We assume such a device does not exist,
489 // because drives are numbered in order and mounting 112345 hard disks will
491 const FilePath::StringType kExtraChars
= FPL("12345");
493 FilePath
real_device_path_plus_numbers(
494 actual_device_path
.value() + kExtraChars
);
496 ASSERT_FALSE(DevicePathToDriveLetterPath(
497 real_device_path_plus_numbers
,
500 ASSERT_FALSE(DevicePathToDriveLetterPath(
501 real_device_path_plus_numbers
.Append(kRelativePath
),
505 TEST_F(FileUtilTest
, CreateTemporaryFileInDirLongPathTest
) {
506 // Test that CreateTemporaryFileInDir() creates a path and returns a long path
507 // if it is available. This test requires that:
508 // - the filesystem at |temp_dir_| supports long filenames.
509 // - the account has FILE_LIST_DIRECTORY permission for all ancestor
510 // directories of |temp_dir_|.
511 const FilePath::CharType kLongDirName
[] = FPL("A long path");
512 const FilePath::CharType kTestSubDirName
[] = FPL("test");
513 FilePath long_test_dir
= temp_dir_
.path().Append(kLongDirName
);
514 ASSERT_TRUE(CreateDirectory(long_test_dir
));
516 // kLongDirName is not a 8.3 component. So GetShortName() should give us a
517 // different short name.
518 WCHAR path_buffer
[MAX_PATH
];
519 DWORD path_buffer_length
= GetShortPathName(long_test_dir
.value().c_str(),
520 path_buffer
, MAX_PATH
);
521 ASSERT_LT(path_buffer_length
, DWORD(MAX_PATH
));
522 ASSERT_NE(DWORD(0), path_buffer_length
);
523 FilePath
short_test_dir(path_buffer
);
524 ASSERT_STRNE(kLongDirName
, short_test_dir
.BaseName().value().c_str());
527 ASSERT_TRUE(CreateTemporaryFileInDir(short_test_dir
, &temp_file
));
528 EXPECT_STREQ(kLongDirName
, temp_file
.DirName().BaseName().value().c_str());
529 EXPECT_TRUE(PathExists(temp_file
));
531 // Create a subdirectory of |long_test_dir| and make |long_test_dir|
532 // unreadable. We should still be able to create a temp file in the
533 // subdirectory, but we won't be able to determine the long path for it. This
534 // mimics the environment that some users run where their user profiles reside
535 // in a location where the don't have full access to the higher level
536 // directories. (Note that this assumption is true for NTFS, but not for some
537 // network file systems. E.g. AFS).
538 FilePath access_test_dir
= long_test_dir
.Append(kTestSubDirName
);
539 ASSERT_TRUE(CreateDirectory(access_test_dir
));
540 FilePermissionRestorer
long_test_dir_restorer(long_test_dir
);
541 ASSERT_TRUE(MakeFileUnreadable(long_test_dir
));
543 // Use the short form of the directory to create a temporary filename.
544 ASSERT_TRUE(CreateTemporaryFileInDir(
545 short_test_dir
.Append(kTestSubDirName
), &temp_file
));
546 EXPECT_TRUE(PathExists(temp_file
));
547 EXPECT_TRUE(short_test_dir
.IsParent(temp_file
.DirName()));
549 // Check that the long path can't be determined for |temp_file|.
550 path_buffer_length
= GetLongPathName(temp_file
.value().c_str(),
551 path_buffer
, MAX_PATH
);
552 EXPECT_EQ(DWORD(0), path_buffer_length
);
555 #endif // defined(OS_WIN)
557 #if defined(OS_POSIX)
559 TEST_F(FileUtilTest
, CreateAndReadSymlinks
) {
560 FilePath link_from
= temp_dir_
.path().Append(FPL("from_file"));
561 FilePath link_to
= temp_dir_
.path().Append(FPL("to_file"));
562 CreateTextFile(link_to
, bogus_content
);
564 ASSERT_TRUE(CreateSymbolicLink(link_to
, link_from
))
565 << "Failed to create file symlink.";
567 // If we created the link properly, we should be able to read the contents
569 std::wstring contents
= ReadTextFile(link_from
);
570 EXPECT_EQ(bogus_content
, contents
);
573 ASSERT_TRUE(ReadSymbolicLink(link_from
, &result
));
574 EXPECT_EQ(link_to
.value(), result
.value());
576 // Link to a directory.
577 link_from
= temp_dir_
.path().Append(FPL("from_dir"));
578 link_to
= temp_dir_
.path().Append(FPL("to_dir"));
579 ASSERT_TRUE(CreateDirectory(link_to
));
580 ASSERT_TRUE(CreateSymbolicLink(link_to
, link_from
))
581 << "Failed to create directory symlink.";
584 EXPECT_FALSE(CreateSymbolicLink(link_to
, link_to
));
585 EXPECT_FALSE(ReadSymbolicLink(link_to
, &result
));
586 FilePath missing
= temp_dir_
.path().Append(FPL("missing"));
587 EXPECT_FALSE(ReadSymbolicLink(missing
, &result
));
590 // The following test of NormalizeFilePath() require that we create a symlink.
591 // This can not be done on Windows before Vista. On Vista, creating a symlink
592 // requires privilege "SeCreateSymbolicLinkPrivilege".
593 // TODO(skerner): Investigate the possibility of giving base_unittests the
594 // privileges required to create a symlink.
595 TEST_F(FileUtilTest
, NormalizeFilePathSymlinks
) {
596 // Link one file to another.
597 FilePath link_from
= temp_dir_
.path().Append(FPL("from_file"));
598 FilePath link_to
= temp_dir_
.path().Append(FPL("to_file"));
599 CreateTextFile(link_to
, bogus_content
);
601 ASSERT_TRUE(CreateSymbolicLink(link_to
, link_from
))
602 << "Failed to create file symlink.";
604 // Check that NormalizeFilePath sees the link.
605 FilePath normalized_path
;
606 ASSERT_TRUE(NormalizeFilePath(link_from
, &normalized_path
));
607 EXPECT_NE(link_from
, link_to
);
608 EXPECT_EQ(link_to
.BaseName().value(), normalized_path
.BaseName().value());
609 EXPECT_EQ(link_to
.BaseName().value(), normalized_path
.BaseName().value());
611 // Link to a directory.
612 link_from
= temp_dir_
.path().Append(FPL("from_dir"));
613 link_to
= temp_dir_
.path().Append(FPL("to_dir"));
614 ASSERT_TRUE(CreateDirectory(link_to
));
615 ASSERT_TRUE(CreateSymbolicLink(link_to
, link_from
))
616 << "Failed to create directory symlink.";
618 EXPECT_FALSE(NormalizeFilePath(link_from
, &normalized_path
))
619 << "Links to directories should return false.";
621 // Test that a loop in the links causes NormalizeFilePath() to return false.
622 link_from
= temp_dir_
.path().Append(FPL("link_a"));
623 link_to
= temp_dir_
.path().Append(FPL("link_b"));
624 ASSERT_TRUE(CreateSymbolicLink(link_to
, link_from
))
625 << "Failed to create loop symlink a.";
626 ASSERT_TRUE(CreateSymbolicLink(link_from
, link_to
))
627 << "Failed to create loop symlink b.";
630 EXPECT_FALSE(NormalizeFilePath(link_from
, &normalized_path
));
632 #endif // defined(OS_POSIX)
634 TEST_F(FileUtilTest
, DeleteNonExistent
) {
635 FilePath non_existent
= temp_dir_
.path().AppendASCII("bogus_file_dne.foobar");
636 ASSERT_FALSE(PathExists(non_existent
));
638 EXPECT_TRUE(DeleteFile(non_existent
, false));
639 ASSERT_FALSE(PathExists(non_existent
));
640 EXPECT_TRUE(DeleteFile(non_existent
, true));
641 ASSERT_FALSE(PathExists(non_existent
));
644 TEST_F(FileUtilTest
, DeleteNonExistentWithNonExistentParent
) {
645 FilePath non_existent
= temp_dir_
.path().AppendASCII("bogus_topdir");
646 non_existent
= non_existent
.AppendASCII("bogus_subdir");
647 ASSERT_FALSE(PathExists(non_existent
));
649 EXPECT_TRUE(DeleteFile(non_existent
, false));
650 ASSERT_FALSE(PathExists(non_existent
));
651 EXPECT_TRUE(DeleteFile(non_existent
, true));
652 ASSERT_FALSE(PathExists(non_existent
));
655 TEST_F(FileUtilTest
, DeleteFile
) {
657 FilePath file_name
= temp_dir_
.path().Append(FPL("Test DeleteFile 1.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
, false));
663 EXPECT_FALSE(PathExists(file_name
));
665 // Test recursive case, create a new file
666 file_name
= temp_dir_
.path().Append(FPL("Test DeleteFile 2.txt"));
667 CreateTextFile(file_name
, bogus_content
);
668 ASSERT_TRUE(PathExists(file_name
));
670 // Make sure it's deleted
671 EXPECT_TRUE(DeleteFile(file_name
, true));
672 EXPECT_FALSE(PathExists(file_name
));
675 #if defined(OS_POSIX)
676 TEST_F(FileUtilTest
, DeleteSymlinkToExistentFile
) {
678 FilePath file_name
= temp_dir_
.path().Append(FPL("Test DeleteFile 2.txt"));
679 CreateTextFile(file_name
, bogus_content
);
680 ASSERT_TRUE(PathExists(file_name
));
682 // Create a symlink to the file.
683 FilePath file_link
= temp_dir_
.path().Append("file_link_2");
684 ASSERT_TRUE(CreateSymbolicLink(file_name
, file_link
))
685 << "Failed to create symlink.";
687 // Delete the symbolic link.
688 EXPECT_TRUE(DeleteFile(file_link
, false));
690 // Make sure original file is not deleted.
691 EXPECT_FALSE(PathExists(file_link
));
692 EXPECT_TRUE(PathExists(file_name
));
695 TEST_F(FileUtilTest
, DeleteSymlinkToNonExistentFile
) {
696 // Create a non-existent file path.
697 FilePath non_existent
= temp_dir_
.path().Append(FPL("Test DeleteFile 3.txt"));
698 EXPECT_FALSE(PathExists(non_existent
));
700 // Create a symlink to the non-existent file.
701 FilePath file_link
= temp_dir_
.path().Append("file_link_3");
702 ASSERT_TRUE(CreateSymbolicLink(non_existent
, file_link
))
703 << "Failed to create symlink.";
705 // Make sure the symbolic link is exist.
706 EXPECT_TRUE(IsLink(file_link
));
707 EXPECT_FALSE(PathExists(file_link
));
709 // Delete the symbolic link.
710 EXPECT_TRUE(DeleteFile(file_link
, false));
712 // Make sure the symbolic link is deleted.
713 EXPECT_FALSE(IsLink(file_link
));
716 TEST_F(FileUtilTest
, ChangeFilePermissionsAndRead
) {
717 // Create a file path.
718 FilePath file_name
= temp_dir_
.path().Append(FPL("Test Readable File.txt"));
719 EXPECT_FALSE(PathExists(file_name
));
721 const std::string
kData("hello");
723 int buffer_size
= kData
.length();
724 char* buffer
= new char[buffer_size
];
727 EXPECT_EQ(static_cast<int>(kData
.length()),
728 WriteFile(file_name
, kData
.data(), kData
.length()));
729 EXPECT_TRUE(PathExists(file_name
));
731 // Make sure the file is readable.
733 EXPECT_TRUE(GetPosixFilePermissions(file_name
, &mode
));
734 EXPECT_TRUE(mode
& FILE_PERMISSION_READ_BY_USER
);
736 // Get rid of the read permission.
737 EXPECT_TRUE(SetPosixFilePermissions(file_name
, 0u));
738 EXPECT_TRUE(GetPosixFilePermissions(file_name
, &mode
));
739 EXPECT_FALSE(mode
& FILE_PERMISSION_READ_BY_USER
);
740 // Make sure the file can't be read.
741 EXPECT_EQ(-1, ReadFile(file_name
, buffer
, buffer_size
));
743 // Give the read permission.
744 EXPECT_TRUE(SetPosixFilePermissions(file_name
, FILE_PERMISSION_READ_BY_USER
));
745 EXPECT_TRUE(GetPosixFilePermissions(file_name
, &mode
));
746 EXPECT_TRUE(mode
& FILE_PERMISSION_READ_BY_USER
);
747 // Make sure the file can be read.
748 EXPECT_EQ(static_cast<int>(kData
.length()),
749 ReadFile(file_name
, buffer
, buffer_size
));
752 EXPECT_TRUE(DeleteFile(file_name
, false));
753 EXPECT_FALSE(PathExists(file_name
));
758 TEST_F(FileUtilTest
, ChangeFilePermissionsAndWrite
) {
759 // Create a file path.
760 FilePath file_name
= temp_dir_
.path().Append(FPL("Test Readable File.txt"));
761 EXPECT_FALSE(PathExists(file_name
));
763 const std::string
kData("hello");
766 EXPECT_EQ(static_cast<int>(kData
.length()),
767 WriteFile(file_name
, kData
.data(), kData
.length()));
768 EXPECT_TRUE(PathExists(file_name
));
770 // Make sure the file is writable.
772 EXPECT_TRUE(GetPosixFilePermissions(file_name
, &mode
));
773 EXPECT_TRUE(mode
& FILE_PERMISSION_WRITE_BY_USER
);
774 EXPECT_TRUE(PathIsWritable(file_name
));
776 // Get rid of the write permission.
777 EXPECT_TRUE(SetPosixFilePermissions(file_name
, 0u));
778 EXPECT_TRUE(GetPosixFilePermissions(file_name
, &mode
));
779 EXPECT_FALSE(mode
& FILE_PERMISSION_WRITE_BY_USER
);
780 // Make sure the file can't be write.
781 EXPECT_EQ(-1, WriteFile(file_name
, kData
.data(), kData
.length()));
782 EXPECT_FALSE(PathIsWritable(file_name
));
784 // Give read permission.
785 EXPECT_TRUE(SetPosixFilePermissions(file_name
,
786 FILE_PERMISSION_WRITE_BY_USER
));
787 EXPECT_TRUE(GetPosixFilePermissions(file_name
, &mode
));
788 EXPECT_TRUE(mode
& FILE_PERMISSION_WRITE_BY_USER
);
789 // Make sure the file can be write.
790 EXPECT_EQ(static_cast<int>(kData
.length()),
791 WriteFile(file_name
, kData
.data(), kData
.length()));
792 EXPECT_TRUE(PathIsWritable(file_name
));
795 EXPECT_TRUE(DeleteFile(file_name
, false));
796 EXPECT_FALSE(PathExists(file_name
));
799 TEST_F(FileUtilTest
, ChangeDirectoryPermissionsAndEnumerate
) {
800 // Create a directory path.
801 FilePath subdir_path
=
802 temp_dir_
.path().Append(FPL("PermissionTest1"));
803 CreateDirectory(subdir_path
);
804 ASSERT_TRUE(PathExists(subdir_path
));
806 // Create a dummy file to enumerate.
807 FilePath file_name
= subdir_path
.Append(FPL("Test Readable File.txt"));
808 EXPECT_FALSE(PathExists(file_name
));
809 const std::string
kData("hello");
810 EXPECT_EQ(static_cast<int>(kData
.length()),
811 WriteFile(file_name
, kData
.data(), kData
.length()));
812 EXPECT_TRUE(PathExists(file_name
));
814 // Make sure the directory has the all permissions.
816 EXPECT_TRUE(GetPosixFilePermissions(subdir_path
, &mode
));
817 EXPECT_EQ(FILE_PERMISSION_USER_MASK
, mode
& FILE_PERMISSION_USER_MASK
);
819 // Get rid of the permissions from the directory.
820 EXPECT_TRUE(SetPosixFilePermissions(subdir_path
, 0u));
821 EXPECT_TRUE(GetPosixFilePermissions(subdir_path
, &mode
));
822 EXPECT_FALSE(mode
& FILE_PERMISSION_USER_MASK
);
824 // Make sure the file in the directory can't be enumerated.
825 FileEnumerator
f1(subdir_path
, true, FileEnumerator::FILES
);
826 EXPECT_TRUE(PathExists(subdir_path
));
827 FindResultCollector
c1(&f1
);
828 EXPECT_EQ(0, c1
.size());
829 EXPECT_FALSE(GetPosixFilePermissions(file_name
, &mode
));
831 // Give the permissions to the directory.
832 EXPECT_TRUE(SetPosixFilePermissions(subdir_path
, FILE_PERMISSION_USER_MASK
));
833 EXPECT_TRUE(GetPosixFilePermissions(subdir_path
, &mode
));
834 EXPECT_EQ(FILE_PERMISSION_USER_MASK
, mode
& FILE_PERMISSION_USER_MASK
);
836 // Make sure the file in the directory can be enumerated.
837 FileEnumerator
f2(subdir_path
, true, FileEnumerator::FILES
);
838 FindResultCollector
c2(&f2
);
839 EXPECT_TRUE(c2
.HasFile(file_name
));
840 EXPECT_EQ(1, c2
.size());
843 EXPECT_TRUE(DeleteFile(subdir_path
, true));
844 EXPECT_FALSE(PathExists(subdir_path
));
847 #endif // defined(OS_POSIX)
850 // Tests that the Delete function works for wild cards, especially
851 // with the recursion flag. Also coincidentally tests PathExists.
852 // TODO(erikkay): see if anyone's actually using this feature of the API
853 TEST_F(FileUtilTest
, DeleteWildCard
) {
854 // Create a file and a directory
855 FilePath file_name
= temp_dir_
.path().Append(FPL("Test DeleteWildCard.txt"));
856 CreateTextFile(file_name
, bogus_content
);
857 ASSERT_TRUE(PathExists(file_name
));
859 FilePath subdir_path
= temp_dir_
.path().Append(FPL("DeleteWildCardDir"));
860 CreateDirectory(subdir_path
);
861 ASSERT_TRUE(PathExists(subdir_path
));
863 // Create the wildcard path
864 FilePath directory_contents
= temp_dir_
.path();
865 directory_contents
= directory_contents
.Append(FPL("*"));
867 // Delete non-recursively and check that only the file is deleted
868 EXPECT_TRUE(DeleteFile(directory_contents
, false));
869 EXPECT_FALSE(PathExists(file_name
));
870 EXPECT_TRUE(PathExists(subdir_path
));
872 // Delete recursively and make sure all contents are deleted
873 EXPECT_TRUE(DeleteFile(directory_contents
, true));
874 EXPECT_FALSE(PathExists(file_name
));
875 EXPECT_FALSE(PathExists(subdir_path
));
878 // TODO(erikkay): see if anyone's actually using this feature of the API
879 TEST_F(FileUtilTest
, DeleteNonExistantWildCard
) {
880 // Create a file and a directory
881 FilePath subdir_path
=
882 temp_dir_
.path().Append(FPL("DeleteNonExistantWildCard"));
883 CreateDirectory(subdir_path
);
884 ASSERT_TRUE(PathExists(subdir_path
));
886 // Create the wildcard path
887 FilePath directory_contents
= subdir_path
;
888 directory_contents
= directory_contents
.Append(FPL("*"));
890 // Delete non-recursively and check nothing got deleted
891 EXPECT_TRUE(DeleteFile(directory_contents
, false));
892 EXPECT_TRUE(PathExists(subdir_path
));
894 // Delete recursively and check nothing got deleted
895 EXPECT_TRUE(DeleteFile(directory_contents
, true));
896 EXPECT_TRUE(PathExists(subdir_path
));
900 // Tests non-recursive Delete() for a directory.
901 TEST_F(FileUtilTest
, DeleteDirNonRecursive
) {
902 // Create a subdirectory and put a file and two directories inside.
903 FilePath test_subdir
= temp_dir_
.path().Append(FPL("DeleteDirNonRecursive"));
904 CreateDirectory(test_subdir
);
905 ASSERT_TRUE(PathExists(test_subdir
));
907 FilePath file_name
= test_subdir
.Append(FPL("Test DeleteDir.txt"));
908 CreateTextFile(file_name
, bogus_content
);
909 ASSERT_TRUE(PathExists(file_name
));
911 FilePath subdir_path1
= test_subdir
.Append(FPL("TestSubDir1"));
912 CreateDirectory(subdir_path1
);
913 ASSERT_TRUE(PathExists(subdir_path1
));
915 FilePath subdir_path2
= test_subdir
.Append(FPL("TestSubDir2"));
916 CreateDirectory(subdir_path2
);
917 ASSERT_TRUE(PathExists(subdir_path2
));
919 // Delete non-recursively and check that the empty dir got deleted
920 EXPECT_TRUE(DeleteFile(subdir_path2
, false));
921 EXPECT_FALSE(PathExists(subdir_path2
));
923 // Delete non-recursively and check that nothing got deleted
924 EXPECT_FALSE(DeleteFile(test_subdir
, false));
925 EXPECT_TRUE(PathExists(test_subdir
));
926 EXPECT_TRUE(PathExists(file_name
));
927 EXPECT_TRUE(PathExists(subdir_path1
));
930 // Tests recursive Delete() for a directory.
931 TEST_F(FileUtilTest
, DeleteDirRecursive
) {
932 // Create a subdirectory and put a file and two directories inside.
933 FilePath test_subdir
= temp_dir_
.path().Append(FPL("DeleteDirRecursive"));
934 CreateDirectory(test_subdir
);
935 ASSERT_TRUE(PathExists(test_subdir
));
937 FilePath file_name
= test_subdir
.Append(FPL("Test DeleteDirRecursive.txt"));
938 CreateTextFile(file_name
, bogus_content
);
939 ASSERT_TRUE(PathExists(file_name
));
941 FilePath subdir_path1
= test_subdir
.Append(FPL("TestSubDir1"));
942 CreateDirectory(subdir_path1
);
943 ASSERT_TRUE(PathExists(subdir_path1
));
945 FilePath subdir_path2
= test_subdir
.Append(FPL("TestSubDir2"));
946 CreateDirectory(subdir_path2
);
947 ASSERT_TRUE(PathExists(subdir_path2
));
949 // Delete recursively and check that the empty dir got deleted
950 EXPECT_TRUE(DeleteFile(subdir_path2
, true));
951 EXPECT_FALSE(PathExists(subdir_path2
));
953 // Delete recursively and check that everything got deleted
954 EXPECT_TRUE(DeleteFile(test_subdir
, true));
955 EXPECT_FALSE(PathExists(file_name
));
956 EXPECT_FALSE(PathExists(subdir_path1
));
957 EXPECT_FALSE(PathExists(test_subdir
));
960 TEST_F(FileUtilTest
, MoveFileNew
) {
962 FilePath file_name_from
=
963 temp_dir_
.path().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
964 CreateTextFile(file_name_from
, L
"Gooooooooooooooooooooogle");
965 ASSERT_TRUE(PathExists(file_name_from
));
968 FilePath file_name_to
= temp_dir_
.path().Append(
969 FILE_PATH_LITERAL("Move_Test_File_Destination.txt"));
970 ASSERT_FALSE(PathExists(file_name_to
));
972 EXPECT_TRUE(Move(file_name_from
, file_name_to
));
974 // Check everything has been moved.
975 EXPECT_FALSE(PathExists(file_name_from
));
976 EXPECT_TRUE(PathExists(file_name_to
));
979 TEST_F(FileUtilTest
, MoveFileExists
) {
981 FilePath file_name_from
=
982 temp_dir_
.path().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
983 CreateTextFile(file_name_from
, L
"Gooooooooooooooooooooogle");
984 ASSERT_TRUE(PathExists(file_name_from
));
986 // The destination name.
987 FilePath file_name_to
= temp_dir_
.path().Append(
988 FILE_PATH_LITERAL("Move_Test_File_Destination.txt"));
989 CreateTextFile(file_name_to
, L
"Old file content");
990 ASSERT_TRUE(PathExists(file_name_to
));
992 EXPECT_TRUE(Move(file_name_from
, file_name_to
));
994 // Check everything has been moved.
995 EXPECT_FALSE(PathExists(file_name_from
));
996 EXPECT_TRUE(PathExists(file_name_to
));
997 EXPECT_TRUE(L
"Gooooooooooooooooooooogle" == ReadTextFile(file_name_to
));
1000 TEST_F(FileUtilTest
, MoveFileDirExists
) {
1002 FilePath file_name_from
=
1003 temp_dir_
.path().Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
1004 CreateTextFile(file_name_from
, L
"Gooooooooooooooooooooogle");
1005 ASSERT_TRUE(PathExists(file_name_from
));
1007 // The destination directory
1008 FilePath dir_name_to
=
1009 temp_dir_
.path().Append(FILE_PATH_LITERAL("Destination"));
1010 CreateDirectory(dir_name_to
);
1011 ASSERT_TRUE(PathExists(dir_name_to
));
1013 EXPECT_FALSE(Move(file_name_from
, dir_name_to
));
1017 TEST_F(FileUtilTest
, MoveNew
) {
1018 // Create a directory
1019 FilePath dir_name_from
=
1020 temp_dir_
.path().Append(FILE_PATH_LITERAL("Move_From_Subdir"));
1021 CreateDirectory(dir_name_from
);
1022 ASSERT_TRUE(PathExists(dir_name_from
));
1024 // Create a file under the directory
1025 FilePath
txt_file_name(FILE_PATH_LITERAL("Move_Test_File.txt"));
1026 FilePath file_name_from
= dir_name_from
.Append(txt_file_name
);
1027 CreateTextFile(file_name_from
, L
"Gooooooooooooooooooooogle");
1028 ASSERT_TRUE(PathExists(file_name_from
));
1030 // Move the directory.
1031 FilePath dir_name_to
=
1032 temp_dir_
.path().Append(FILE_PATH_LITERAL("Move_To_Subdir"));
1033 FilePath file_name_to
=
1034 dir_name_to
.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
1036 ASSERT_FALSE(PathExists(dir_name_to
));
1038 EXPECT_TRUE(Move(dir_name_from
, dir_name_to
));
1040 // Check everything has been moved.
1041 EXPECT_FALSE(PathExists(dir_name_from
));
1042 EXPECT_FALSE(PathExists(file_name_from
));
1043 EXPECT_TRUE(PathExists(dir_name_to
));
1044 EXPECT_TRUE(PathExists(file_name_to
));
1046 // Test path traversal.
1047 file_name_from
= dir_name_to
.Append(txt_file_name
);
1048 file_name_to
= dir_name_to
.Append(FILE_PATH_LITERAL(".."));
1049 file_name_to
= file_name_to
.Append(txt_file_name
);
1050 EXPECT_FALSE(Move(file_name_from
, file_name_to
));
1051 EXPECT_TRUE(PathExists(file_name_from
));
1052 EXPECT_FALSE(PathExists(file_name_to
));
1053 EXPECT_TRUE(internal::MoveUnsafe(file_name_from
, file_name_to
));
1054 EXPECT_FALSE(PathExists(file_name_from
));
1055 EXPECT_TRUE(PathExists(file_name_to
));
1058 TEST_F(FileUtilTest
, MoveExist
) {
1059 // Create a directory
1060 FilePath dir_name_from
=
1061 temp_dir_
.path().Append(FILE_PATH_LITERAL("Move_From_Subdir"));
1062 CreateDirectory(dir_name_from
);
1063 ASSERT_TRUE(PathExists(dir_name_from
));
1065 // Create a file under the directory
1066 FilePath file_name_from
=
1067 dir_name_from
.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
1068 CreateTextFile(file_name_from
, L
"Gooooooooooooooooooooogle");
1069 ASSERT_TRUE(PathExists(file_name_from
));
1071 // Move the directory
1072 FilePath dir_name_exists
=
1073 temp_dir_
.path().Append(FILE_PATH_LITERAL("Destination"));
1075 FilePath dir_name_to
=
1076 dir_name_exists
.Append(FILE_PATH_LITERAL("Move_To_Subdir"));
1077 FilePath file_name_to
=
1078 dir_name_to
.Append(FILE_PATH_LITERAL("Move_Test_File.txt"));
1080 // Create the destination directory.
1081 CreateDirectory(dir_name_exists
);
1082 ASSERT_TRUE(PathExists(dir_name_exists
));
1084 EXPECT_TRUE(Move(dir_name_from
, dir_name_to
));
1086 // Check everything has been moved.
1087 EXPECT_FALSE(PathExists(dir_name_from
));
1088 EXPECT_FALSE(PathExists(file_name_from
));
1089 EXPECT_TRUE(PathExists(dir_name_to
));
1090 EXPECT_TRUE(PathExists(file_name_to
));
1093 TEST_F(FileUtilTest
, CopyDirectoryRecursivelyNew
) {
1094 // Create a directory.
1095 FilePath dir_name_from
=
1096 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1097 CreateDirectory(dir_name_from
);
1098 ASSERT_TRUE(PathExists(dir_name_from
));
1100 // Create a file under the directory.
1101 FilePath file_name_from
=
1102 dir_name_from
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1103 CreateTextFile(file_name_from
, L
"Gooooooooooooooooooooogle");
1104 ASSERT_TRUE(PathExists(file_name_from
));
1106 // Create a subdirectory.
1107 FilePath subdir_name_from
=
1108 dir_name_from
.Append(FILE_PATH_LITERAL("Subdir"));
1109 CreateDirectory(subdir_name_from
);
1110 ASSERT_TRUE(PathExists(subdir_name_from
));
1112 // Create a file under the subdirectory.
1113 FilePath file_name2_from
=
1114 subdir_name_from
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1115 CreateTextFile(file_name2_from
, L
"Gooooooooooooooooooooogle");
1116 ASSERT_TRUE(PathExists(file_name2_from
));
1118 // Copy the directory recursively.
1119 FilePath dir_name_to
=
1120 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1121 FilePath file_name_to
=
1122 dir_name_to
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1123 FilePath subdir_name_to
=
1124 dir_name_to
.Append(FILE_PATH_LITERAL("Subdir"));
1125 FilePath file_name2_to
=
1126 subdir_name_to
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1128 ASSERT_FALSE(PathExists(dir_name_to
));
1130 EXPECT_TRUE(CopyDirectory(dir_name_from
, dir_name_to
, true));
1132 // Check everything has been copied.
1133 EXPECT_TRUE(PathExists(dir_name_from
));
1134 EXPECT_TRUE(PathExists(file_name_from
));
1135 EXPECT_TRUE(PathExists(subdir_name_from
));
1136 EXPECT_TRUE(PathExists(file_name2_from
));
1137 EXPECT_TRUE(PathExists(dir_name_to
));
1138 EXPECT_TRUE(PathExists(file_name_to
));
1139 EXPECT_TRUE(PathExists(subdir_name_to
));
1140 EXPECT_TRUE(PathExists(file_name2_to
));
1143 TEST_F(FileUtilTest
, CopyDirectoryRecursivelyExists
) {
1144 // Create a directory.
1145 FilePath dir_name_from
=
1146 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1147 CreateDirectory(dir_name_from
);
1148 ASSERT_TRUE(PathExists(dir_name_from
));
1150 // Create a file under the directory.
1151 FilePath file_name_from
=
1152 dir_name_from
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1153 CreateTextFile(file_name_from
, L
"Gooooooooooooooooooooogle");
1154 ASSERT_TRUE(PathExists(file_name_from
));
1156 // Create a subdirectory.
1157 FilePath subdir_name_from
=
1158 dir_name_from
.Append(FILE_PATH_LITERAL("Subdir"));
1159 CreateDirectory(subdir_name_from
);
1160 ASSERT_TRUE(PathExists(subdir_name_from
));
1162 // Create a file under the subdirectory.
1163 FilePath file_name2_from
=
1164 subdir_name_from
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1165 CreateTextFile(file_name2_from
, L
"Gooooooooooooooooooooogle");
1166 ASSERT_TRUE(PathExists(file_name2_from
));
1168 // Copy the directory recursively.
1169 FilePath dir_name_exists
=
1170 temp_dir_
.path().Append(FILE_PATH_LITERAL("Destination"));
1172 FilePath dir_name_to
=
1173 dir_name_exists
.Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1174 FilePath file_name_to
=
1175 dir_name_to
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1176 FilePath subdir_name_to
=
1177 dir_name_to
.Append(FILE_PATH_LITERAL("Subdir"));
1178 FilePath file_name2_to
=
1179 subdir_name_to
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1181 // Create the destination directory.
1182 CreateDirectory(dir_name_exists
);
1183 ASSERT_TRUE(PathExists(dir_name_exists
));
1185 EXPECT_TRUE(CopyDirectory(dir_name_from
, dir_name_exists
, true));
1187 // Check everything has been copied.
1188 EXPECT_TRUE(PathExists(dir_name_from
));
1189 EXPECT_TRUE(PathExists(file_name_from
));
1190 EXPECT_TRUE(PathExists(subdir_name_from
));
1191 EXPECT_TRUE(PathExists(file_name2_from
));
1192 EXPECT_TRUE(PathExists(dir_name_to
));
1193 EXPECT_TRUE(PathExists(file_name_to
));
1194 EXPECT_TRUE(PathExists(subdir_name_to
));
1195 EXPECT_TRUE(PathExists(file_name2_to
));
1198 TEST_F(FileUtilTest
, CopyDirectoryNew
) {
1199 // Create a directory.
1200 FilePath dir_name_from
=
1201 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1202 CreateDirectory(dir_name_from
);
1203 ASSERT_TRUE(PathExists(dir_name_from
));
1205 // Create a file under the directory.
1206 FilePath file_name_from
=
1207 dir_name_from
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1208 CreateTextFile(file_name_from
, L
"Gooooooooooooooooooooogle");
1209 ASSERT_TRUE(PathExists(file_name_from
));
1211 // Create a subdirectory.
1212 FilePath subdir_name_from
=
1213 dir_name_from
.Append(FILE_PATH_LITERAL("Subdir"));
1214 CreateDirectory(subdir_name_from
);
1215 ASSERT_TRUE(PathExists(subdir_name_from
));
1217 // Create a file under the subdirectory.
1218 FilePath file_name2_from
=
1219 subdir_name_from
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1220 CreateTextFile(file_name2_from
, L
"Gooooooooooooooooooooogle");
1221 ASSERT_TRUE(PathExists(file_name2_from
));
1223 // Copy the directory not recursively.
1224 FilePath dir_name_to
=
1225 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1226 FilePath file_name_to
=
1227 dir_name_to
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1228 FilePath subdir_name_to
=
1229 dir_name_to
.Append(FILE_PATH_LITERAL("Subdir"));
1231 ASSERT_FALSE(PathExists(dir_name_to
));
1233 EXPECT_TRUE(CopyDirectory(dir_name_from
, dir_name_to
, false));
1235 // Check everything has been copied.
1236 EXPECT_TRUE(PathExists(dir_name_from
));
1237 EXPECT_TRUE(PathExists(file_name_from
));
1238 EXPECT_TRUE(PathExists(subdir_name_from
));
1239 EXPECT_TRUE(PathExists(file_name2_from
));
1240 EXPECT_TRUE(PathExists(dir_name_to
));
1241 EXPECT_TRUE(PathExists(file_name_to
));
1242 EXPECT_FALSE(PathExists(subdir_name_to
));
1245 TEST_F(FileUtilTest
, CopyDirectoryExists
) {
1246 // Create a directory.
1247 FilePath dir_name_from
=
1248 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1249 CreateDirectory(dir_name_from
);
1250 ASSERT_TRUE(PathExists(dir_name_from
));
1252 // Create a file under the directory.
1253 FilePath file_name_from
=
1254 dir_name_from
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1255 CreateTextFile(file_name_from
, L
"Gooooooooooooooooooooogle");
1256 ASSERT_TRUE(PathExists(file_name_from
));
1258 // Create a subdirectory.
1259 FilePath subdir_name_from
=
1260 dir_name_from
.Append(FILE_PATH_LITERAL("Subdir"));
1261 CreateDirectory(subdir_name_from
);
1262 ASSERT_TRUE(PathExists(subdir_name_from
));
1264 // Create a file under the subdirectory.
1265 FilePath file_name2_from
=
1266 subdir_name_from
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1267 CreateTextFile(file_name2_from
, L
"Gooooooooooooooooooooogle");
1268 ASSERT_TRUE(PathExists(file_name2_from
));
1270 // Copy the directory not recursively.
1271 FilePath dir_name_to
=
1272 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1273 FilePath file_name_to
=
1274 dir_name_to
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1275 FilePath subdir_name_to
=
1276 dir_name_to
.Append(FILE_PATH_LITERAL("Subdir"));
1278 // Create the destination directory.
1279 CreateDirectory(dir_name_to
);
1280 ASSERT_TRUE(PathExists(dir_name_to
));
1282 EXPECT_TRUE(CopyDirectory(dir_name_from
, dir_name_to
, false));
1284 // Check everything has been copied.
1285 EXPECT_TRUE(PathExists(dir_name_from
));
1286 EXPECT_TRUE(PathExists(file_name_from
));
1287 EXPECT_TRUE(PathExists(subdir_name_from
));
1288 EXPECT_TRUE(PathExists(file_name2_from
));
1289 EXPECT_TRUE(PathExists(dir_name_to
));
1290 EXPECT_TRUE(PathExists(file_name_to
));
1291 EXPECT_FALSE(PathExists(subdir_name_to
));
1294 TEST_F(FileUtilTest
, CopyFileWithCopyDirectoryRecursiveToNew
) {
1296 FilePath file_name_from
=
1297 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1298 CreateTextFile(file_name_from
, L
"Gooooooooooooooooooooogle");
1299 ASSERT_TRUE(PathExists(file_name_from
));
1301 // The destination name
1302 FilePath file_name_to
= temp_dir_
.path().Append(
1303 FILE_PATH_LITERAL("Copy_Test_File_Destination.txt"));
1304 ASSERT_FALSE(PathExists(file_name_to
));
1306 EXPECT_TRUE(CopyDirectory(file_name_from
, file_name_to
, true));
1308 // Check the has been copied
1309 EXPECT_TRUE(PathExists(file_name_to
));
1312 TEST_F(FileUtilTest
, CopyFileWithCopyDirectoryRecursiveToExisting
) {
1314 FilePath file_name_from
=
1315 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1316 CreateTextFile(file_name_from
, L
"Gooooooooooooooooooooogle");
1317 ASSERT_TRUE(PathExists(file_name_from
));
1319 // The destination name
1320 FilePath file_name_to
= temp_dir_
.path().Append(
1321 FILE_PATH_LITERAL("Copy_Test_File_Destination.txt"));
1322 CreateTextFile(file_name_to
, L
"Old file content");
1323 ASSERT_TRUE(PathExists(file_name_to
));
1325 EXPECT_TRUE(CopyDirectory(file_name_from
, file_name_to
, true));
1327 // Check the has been copied
1328 EXPECT_TRUE(PathExists(file_name_to
));
1329 EXPECT_TRUE(L
"Gooooooooooooooooooooogle" == ReadTextFile(file_name_to
));
1332 TEST_F(FileUtilTest
, CopyFileWithCopyDirectoryRecursiveToExistingDirectory
) {
1334 FilePath file_name_from
=
1335 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1336 CreateTextFile(file_name_from
, L
"Gooooooooooooooooooooogle");
1337 ASSERT_TRUE(PathExists(file_name_from
));
1340 FilePath dir_name_to
=
1341 temp_dir_
.path().Append(FILE_PATH_LITERAL("Destination"));
1342 CreateDirectory(dir_name_to
);
1343 ASSERT_TRUE(PathExists(dir_name_to
));
1344 FilePath file_name_to
=
1345 dir_name_to
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1347 EXPECT_TRUE(CopyDirectory(file_name_from
, dir_name_to
, true));
1349 // Check the has been copied
1350 EXPECT_TRUE(PathExists(file_name_to
));
1353 TEST_F(FileUtilTest
, CopyDirectoryWithTrailingSeparators
) {
1354 // Create a directory.
1355 FilePath dir_name_from
=
1356 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1357 CreateDirectory(dir_name_from
);
1358 ASSERT_TRUE(PathExists(dir_name_from
));
1360 // Create a file under the directory.
1361 FilePath file_name_from
=
1362 dir_name_from
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1363 CreateTextFile(file_name_from
, L
"Gooooooooooooooooooooogle");
1364 ASSERT_TRUE(PathExists(file_name_from
));
1366 // Copy the directory recursively.
1367 FilePath dir_name_to
=
1368 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_To_Subdir"));
1369 FilePath file_name_to
=
1370 dir_name_to
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1372 // Create from path with trailing separators.
1374 FilePath from_path
=
1375 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir\\\\\\"));
1376 #elif defined (OS_POSIX)
1377 FilePath from_path
=
1378 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir///"));
1381 EXPECT_TRUE(CopyDirectory(from_path
, dir_name_to
, true));
1383 // Check everything has been copied.
1384 EXPECT_TRUE(PathExists(dir_name_from
));
1385 EXPECT_TRUE(PathExists(file_name_from
));
1386 EXPECT_TRUE(PathExists(dir_name_to
));
1387 EXPECT_TRUE(PathExists(file_name_to
));
1390 // Sets the source file to read-only.
1391 void SetReadOnly(const FilePath
& path
, bool read_only
) {
1393 // On Windows, it involves setting/removing the 'readonly' bit.
1394 DWORD attrs
= GetFileAttributes(path
.value().c_str());
1395 ASSERT_NE(INVALID_FILE_ATTRIBUTES
, attrs
);
1396 ASSERT_TRUE(SetFileAttributes(
1397 path
.value().c_str(),
1398 read_only
? (attrs
| FILE_ATTRIBUTE_READONLY
) :
1399 (attrs
& ~FILE_ATTRIBUTE_READONLY
)));
1401 DWORD expected
= read_only
?
1402 ((attrs
& (FILE_ATTRIBUTE_ARCHIVE
| FILE_ATTRIBUTE_DIRECTORY
)) |
1403 FILE_ATTRIBUTE_READONLY
) :
1404 (attrs
& (FILE_ATTRIBUTE_ARCHIVE
| FILE_ATTRIBUTE_DIRECTORY
));
1406 // Ignore FILE_ATTRIBUTE_NOT_CONTENT_INDEXED if present.
1407 attrs
= GetFileAttributes(path
.value().c_str()) &
1408 ~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED
;
1409 ASSERT_EQ(expected
, attrs
);
1411 // On all other platforms, it involves removing/setting the write bit.
1412 mode_t mode
= read_only
? S_IRUSR
: (S_IRUSR
| S_IWUSR
);
1413 EXPECT_TRUE(SetPosixFilePermissions(
1414 path
, DirectoryExists(path
) ? (mode
| S_IXUSR
) : mode
));
1418 bool IsReadOnly(const FilePath
& path
) {
1420 DWORD attrs
= GetFileAttributes(path
.value().c_str());
1421 EXPECT_NE(INVALID_FILE_ATTRIBUTES
, attrs
);
1422 return attrs
& FILE_ATTRIBUTE_READONLY
;
1425 EXPECT_TRUE(GetPosixFilePermissions(path
, &mode
));
1426 return !(mode
& S_IWUSR
);
1430 TEST_F(FileUtilTest
, CopyDirectoryACL
) {
1431 // Create source directories.
1432 FilePath src
= temp_dir_
.path().Append(FILE_PATH_LITERAL("src"));
1433 FilePath src_subdir
= src
.Append(FILE_PATH_LITERAL("subdir"));
1434 CreateDirectory(src_subdir
);
1435 ASSERT_TRUE(PathExists(src_subdir
));
1437 // Create a file under the directory.
1438 FilePath src_file
= src
.Append(FILE_PATH_LITERAL("src.txt"));
1439 CreateTextFile(src_file
, L
"Gooooooooooooooooooooogle");
1440 SetReadOnly(src_file
, true);
1441 ASSERT_TRUE(IsReadOnly(src_file
));
1443 // Make directory read-only.
1444 SetReadOnly(src_subdir
, true);
1445 ASSERT_TRUE(IsReadOnly(src_subdir
));
1447 // Copy the directory recursively.
1448 FilePath dst
= temp_dir_
.path().Append(FILE_PATH_LITERAL("dst"));
1449 FilePath dst_file
= dst
.Append(FILE_PATH_LITERAL("src.txt"));
1450 EXPECT_TRUE(CopyDirectory(src
, dst
, true));
1452 FilePath dst_subdir
= dst
.Append(FILE_PATH_LITERAL("subdir"));
1453 ASSERT_FALSE(IsReadOnly(dst_subdir
));
1454 ASSERT_FALSE(IsReadOnly(dst_file
));
1456 // Give write permissions to allow deletion.
1457 SetReadOnly(src_subdir
, false);
1458 ASSERT_FALSE(IsReadOnly(src_subdir
));
1461 TEST_F(FileUtilTest
, CopyFile
) {
1462 // Create a directory
1463 FilePath dir_name_from
=
1464 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1465 CreateDirectory(dir_name_from
);
1466 ASSERT_TRUE(PathExists(dir_name_from
));
1468 // Create a file under the directory
1469 FilePath file_name_from
=
1470 dir_name_from
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1471 const std::wstring
file_contents(L
"Gooooooooooooooooooooogle");
1472 CreateTextFile(file_name_from
, file_contents
);
1473 ASSERT_TRUE(PathExists(file_name_from
));
1476 FilePath dest_file
= dir_name_from
.Append(FILE_PATH_LITERAL("DestFile.txt"));
1477 ASSERT_TRUE(CopyFile(file_name_from
, dest_file
));
1479 // Try to copy the file to another location using '..' in the path.
1480 FilePath
dest_file2(dir_name_from
);
1481 dest_file2
= dest_file2
.AppendASCII("..");
1482 dest_file2
= dest_file2
.AppendASCII("DestFile.txt");
1483 ASSERT_FALSE(CopyFile(file_name_from
, dest_file2
));
1485 FilePath
dest_file2_test(dir_name_from
);
1486 dest_file2_test
= dest_file2_test
.DirName();
1487 dest_file2_test
= dest_file2_test
.AppendASCII("DestFile.txt");
1489 // Check expected copy results.
1490 EXPECT_TRUE(PathExists(file_name_from
));
1491 EXPECT_TRUE(PathExists(dest_file
));
1492 const std::wstring read_contents
= ReadTextFile(dest_file
);
1493 EXPECT_EQ(file_contents
, read_contents
);
1494 EXPECT_FALSE(PathExists(dest_file2_test
));
1495 EXPECT_FALSE(PathExists(dest_file2
));
1498 TEST_F(FileUtilTest
, CopyFileACL
) {
1499 // While FileUtilTest.CopyFile asserts the content is correctly copied over,
1500 // this test case asserts the access control bits are meeting expectations in
1502 FilePath src
= temp_dir_
.path().Append(FILE_PATH_LITERAL("src.txt"));
1503 const std::wstring
file_contents(L
"Gooooooooooooooooooooogle");
1504 CreateTextFile(src
, file_contents
);
1506 // Set the source file to read-only.
1507 ASSERT_FALSE(IsReadOnly(src
));
1508 SetReadOnly(src
, true);
1509 ASSERT_TRUE(IsReadOnly(src
));
1512 FilePath dst
= temp_dir_
.path().Append(FILE_PATH_LITERAL("dst.txt"));
1513 ASSERT_TRUE(CopyFile(src
, dst
));
1514 EXPECT_EQ(file_contents
, ReadTextFile(dst
));
1516 ASSERT_FALSE(IsReadOnly(dst
));
1519 // file_util winds up using autoreleased objects on the Mac, so this needs
1520 // to be a PlatformTest.
1521 typedef PlatformTest ReadOnlyFileUtilTest
;
1523 TEST_F(ReadOnlyFileUtilTest
, ContentsEqual
) {
1525 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA
, &data_dir
));
1526 data_dir
= data_dir
.AppendASCII("file_util");
1527 ASSERT_TRUE(PathExists(data_dir
));
1529 FilePath original_file
=
1530 data_dir
.Append(FILE_PATH_LITERAL("original.txt"));
1531 FilePath same_file
=
1532 data_dir
.Append(FILE_PATH_LITERAL("same.txt"));
1533 FilePath same_length_file
=
1534 data_dir
.Append(FILE_PATH_LITERAL("same_length.txt"));
1535 FilePath different_file
=
1536 data_dir
.Append(FILE_PATH_LITERAL("different.txt"));
1537 FilePath different_first_file
=
1538 data_dir
.Append(FILE_PATH_LITERAL("different_first.txt"));
1539 FilePath different_last_file
=
1540 data_dir
.Append(FILE_PATH_LITERAL("different_last.txt"));
1541 FilePath empty1_file
=
1542 data_dir
.Append(FILE_PATH_LITERAL("empty1.txt"));
1543 FilePath empty2_file
=
1544 data_dir
.Append(FILE_PATH_LITERAL("empty2.txt"));
1545 FilePath shortened_file
=
1546 data_dir
.Append(FILE_PATH_LITERAL("shortened.txt"));
1547 FilePath binary_file
=
1548 data_dir
.Append(FILE_PATH_LITERAL("binary_file.bin"));
1549 FilePath binary_file_same
=
1550 data_dir
.Append(FILE_PATH_LITERAL("binary_file_same.bin"));
1551 FilePath binary_file_diff
=
1552 data_dir
.Append(FILE_PATH_LITERAL("binary_file_diff.bin"));
1554 EXPECT_TRUE(ContentsEqual(original_file
, original_file
));
1555 EXPECT_TRUE(ContentsEqual(original_file
, same_file
));
1556 EXPECT_FALSE(ContentsEqual(original_file
, same_length_file
));
1557 EXPECT_FALSE(ContentsEqual(original_file
, different_file
));
1558 EXPECT_FALSE(ContentsEqual(FilePath(FILE_PATH_LITERAL("bogusname")),
1559 FilePath(FILE_PATH_LITERAL("bogusname"))));
1560 EXPECT_FALSE(ContentsEqual(original_file
, different_first_file
));
1561 EXPECT_FALSE(ContentsEqual(original_file
, different_last_file
));
1562 EXPECT_TRUE(ContentsEqual(empty1_file
, empty2_file
));
1563 EXPECT_FALSE(ContentsEqual(original_file
, shortened_file
));
1564 EXPECT_FALSE(ContentsEqual(shortened_file
, original_file
));
1565 EXPECT_TRUE(ContentsEqual(binary_file
, binary_file_same
));
1566 EXPECT_FALSE(ContentsEqual(binary_file
, binary_file_diff
));
1569 TEST_F(ReadOnlyFileUtilTest
, TextContentsEqual
) {
1571 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA
, &data_dir
));
1572 data_dir
= data_dir
.AppendASCII("file_util");
1573 ASSERT_TRUE(PathExists(data_dir
));
1575 FilePath original_file
=
1576 data_dir
.Append(FILE_PATH_LITERAL("original.txt"));
1577 FilePath same_file
=
1578 data_dir
.Append(FILE_PATH_LITERAL("same.txt"));
1579 FilePath crlf_file
=
1580 data_dir
.Append(FILE_PATH_LITERAL("crlf.txt"));
1581 FilePath shortened_file
=
1582 data_dir
.Append(FILE_PATH_LITERAL("shortened.txt"));
1583 FilePath different_file
=
1584 data_dir
.Append(FILE_PATH_LITERAL("different.txt"));
1585 FilePath different_first_file
=
1586 data_dir
.Append(FILE_PATH_LITERAL("different_first.txt"));
1587 FilePath different_last_file
=
1588 data_dir
.Append(FILE_PATH_LITERAL("different_last.txt"));
1589 FilePath first1_file
=
1590 data_dir
.Append(FILE_PATH_LITERAL("first1.txt"));
1591 FilePath first2_file
=
1592 data_dir
.Append(FILE_PATH_LITERAL("first2.txt"));
1593 FilePath empty1_file
=
1594 data_dir
.Append(FILE_PATH_LITERAL("empty1.txt"));
1595 FilePath empty2_file
=
1596 data_dir
.Append(FILE_PATH_LITERAL("empty2.txt"));
1597 FilePath blank_line_file
=
1598 data_dir
.Append(FILE_PATH_LITERAL("blank_line.txt"));
1599 FilePath blank_line_crlf_file
=
1600 data_dir
.Append(FILE_PATH_LITERAL("blank_line_crlf.txt"));
1602 EXPECT_TRUE(TextContentsEqual(original_file
, same_file
));
1603 EXPECT_TRUE(TextContentsEqual(original_file
, crlf_file
));
1604 EXPECT_FALSE(TextContentsEqual(original_file
, shortened_file
));
1605 EXPECT_FALSE(TextContentsEqual(original_file
, different_file
));
1606 EXPECT_FALSE(TextContentsEqual(original_file
, different_first_file
));
1607 EXPECT_FALSE(TextContentsEqual(original_file
, different_last_file
));
1608 EXPECT_FALSE(TextContentsEqual(first1_file
, first2_file
));
1609 EXPECT_TRUE(TextContentsEqual(empty1_file
, empty2_file
));
1610 EXPECT_FALSE(TextContentsEqual(original_file
, empty1_file
));
1611 EXPECT_TRUE(TextContentsEqual(blank_line_file
, blank_line_crlf_file
));
1614 // We don't need equivalent functionality outside of Windows.
1616 TEST_F(FileUtilTest
, CopyAndDeleteDirectoryTest
) {
1617 // Create a directory
1618 FilePath dir_name_from
=
1619 temp_dir_
.path().Append(FILE_PATH_LITERAL("CopyAndDelete_From_Subdir"));
1620 CreateDirectory(dir_name_from
);
1621 ASSERT_TRUE(PathExists(dir_name_from
));
1623 // Create a file under the directory
1624 FilePath file_name_from
=
1625 dir_name_from
.Append(FILE_PATH_LITERAL("CopyAndDelete_Test_File.txt"));
1626 CreateTextFile(file_name_from
, L
"Gooooooooooooooooooooogle");
1627 ASSERT_TRUE(PathExists(file_name_from
));
1629 // Move the directory by using CopyAndDeleteDirectory
1630 FilePath dir_name_to
= temp_dir_
.path().Append(
1631 FILE_PATH_LITERAL("CopyAndDelete_To_Subdir"));
1632 FilePath file_name_to
=
1633 dir_name_to
.Append(FILE_PATH_LITERAL("CopyAndDelete_Test_File.txt"));
1635 ASSERT_FALSE(PathExists(dir_name_to
));
1637 EXPECT_TRUE(internal::CopyAndDeleteDirectory(dir_name_from
,
1640 // Check everything has been moved.
1641 EXPECT_FALSE(PathExists(dir_name_from
));
1642 EXPECT_FALSE(PathExists(file_name_from
));
1643 EXPECT_TRUE(PathExists(dir_name_to
));
1644 EXPECT_TRUE(PathExists(file_name_to
));
1647 TEST_F(FileUtilTest
, GetTempDirTest
) {
1648 static const TCHAR
* kTmpKey
= _T("TMP");
1649 static const TCHAR
* kTmpValues
[] = {
1650 _T(""), _T("C:"), _T("C:\\"), _T("C:\\tmp"), _T("C:\\tmp\\")
1652 // Save the original $TMP.
1653 size_t original_tmp_size
;
1654 TCHAR
* original_tmp
;
1655 ASSERT_EQ(0, ::_tdupenv_s(&original_tmp
, &original_tmp_size
, kTmpKey
));
1656 // original_tmp may be NULL.
1658 for (unsigned int i
= 0; i
< arraysize(kTmpValues
); ++i
) {
1660 ::_tputenv_s(kTmpKey
, kTmpValues
[i
]);
1662 EXPECT_TRUE(path
.IsAbsolute()) << "$TMP=" << kTmpValues
[i
] <<
1663 " result=" << path
.value();
1666 // Restore the original $TMP.
1668 ::_tputenv_s(kTmpKey
, original_tmp
);
1671 ::_tputenv_s(kTmpKey
, _T(""));
1676 TEST_F(FileUtilTest
, CreateTemporaryFileTest
) {
1677 FilePath temp_files
[3];
1678 for (int i
= 0; i
< 3; i
++) {
1679 ASSERT_TRUE(CreateTemporaryFile(&(temp_files
[i
])));
1680 EXPECT_TRUE(PathExists(temp_files
[i
]));
1681 EXPECT_FALSE(DirectoryExists(temp_files
[i
]));
1683 for (int i
= 0; i
< 3; i
++)
1684 EXPECT_FALSE(temp_files
[i
] == temp_files
[(i
+1)%3]);
1685 for (int i
= 0; i
< 3; i
++)
1686 EXPECT_TRUE(DeleteFile(temp_files
[i
], false));
1689 TEST_F(FileUtilTest
, CreateAndOpenTemporaryFileTest
) {
1694 // Create; make sure they are open and exist.
1695 for (i
= 0; i
< 3; ++i
) {
1696 fps
[i
] = CreateAndOpenTemporaryFile(&(names
[i
]));
1697 ASSERT_TRUE(fps
[i
]);
1698 EXPECT_TRUE(PathExists(names
[i
]));
1701 // Make sure all names are unique.
1702 for (i
= 0; i
< 3; ++i
) {
1703 EXPECT_FALSE(names
[i
] == names
[(i
+1)%3]);
1706 // Close and delete.
1707 for (i
= 0; i
< 3; ++i
) {
1708 EXPECT_TRUE(CloseFile(fps
[i
]));
1709 EXPECT_TRUE(DeleteFile(names
[i
], false));
1713 TEST_F(FileUtilTest
, FileToFILE
) {
1715 FILE* stream
= FileToFILE(file
.Pass(), "w");
1716 EXPECT_FALSE(stream
);
1718 FilePath file_name
= temp_dir_
.path().Append(FPL("The file.txt"));
1719 file
= File(file_name
, File::FLAG_CREATE
| File::FLAG_WRITE
);
1720 EXPECT_TRUE(file
.IsValid());
1722 stream
= FileToFILE(file
.Pass(), "w");
1723 EXPECT_TRUE(stream
);
1724 EXPECT_FALSE(file
.IsValid());
1725 EXPECT_TRUE(CloseFile(stream
));
1728 TEST_F(FileUtilTest
, CreateNewTempDirectoryTest
) {
1730 ASSERT_TRUE(CreateNewTempDirectory(FilePath::StringType(), &temp_dir
));
1731 EXPECT_TRUE(PathExists(temp_dir
));
1732 EXPECT_TRUE(DeleteFile(temp_dir
, false));
1735 TEST_F(FileUtilTest
, CreateNewTemporaryDirInDirTest
) {
1737 ASSERT_TRUE(CreateTemporaryDirInDir(
1739 FILE_PATH_LITERAL("CreateNewTemporaryDirInDirTest"),
1741 EXPECT_TRUE(PathExists(new_dir
));
1742 EXPECT_TRUE(temp_dir_
.path().IsParent(new_dir
));
1743 EXPECT_TRUE(DeleteFile(new_dir
, false));
1746 #if defined(OS_POSIX)
1747 TEST_F(FileUtilTest
, GetShmemTempDirTest
) {
1749 EXPECT_TRUE(GetShmemTempDir(false, &dir
));
1750 EXPECT_TRUE(DirectoryExists(dir
));
1754 TEST_F(FileUtilTest
, GetHomeDirTest
) {
1755 #if !defined(OS_ANDROID) // Not implemented on Android.
1756 // We don't actually know what the home directory is supposed to be without
1757 // calling some OS functions which would just duplicate the implementation.
1758 // So here we just test that it returns something "reasonable".
1759 FilePath home
= GetHomeDir();
1760 ASSERT_FALSE(home
.empty());
1761 ASSERT_TRUE(home
.IsAbsolute());
1765 TEST_F(FileUtilTest
, CreateDirectoryTest
) {
1766 FilePath test_root
=
1767 temp_dir_
.path().Append(FILE_PATH_LITERAL("create_directory_test"));
1769 FilePath test_path
=
1770 test_root
.Append(FILE_PATH_LITERAL("dir\\tree\\likely\\doesnt\\exist\\"));
1771 #elif defined(OS_POSIX)
1772 FilePath test_path
=
1773 test_root
.Append(FILE_PATH_LITERAL("dir/tree/likely/doesnt/exist/"));
1776 EXPECT_FALSE(PathExists(test_path
));
1777 EXPECT_TRUE(CreateDirectory(test_path
));
1778 EXPECT_TRUE(PathExists(test_path
));
1779 // CreateDirectory returns true if the DirectoryExists returns true.
1780 EXPECT_TRUE(CreateDirectory(test_path
));
1782 // Doesn't work to create it on top of a non-dir
1783 test_path
= test_path
.Append(FILE_PATH_LITERAL("foobar.txt"));
1784 EXPECT_FALSE(PathExists(test_path
));
1785 CreateTextFile(test_path
, L
"test file");
1786 EXPECT_TRUE(PathExists(test_path
));
1787 EXPECT_FALSE(CreateDirectory(test_path
));
1789 EXPECT_TRUE(DeleteFile(test_root
, true));
1790 EXPECT_FALSE(PathExists(test_root
));
1791 EXPECT_FALSE(PathExists(test_path
));
1793 // Verify assumptions made by the Windows implementation:
1794 // 1. The current directory always exists.
1795 // 2. The root directory always exists.
1796 ASSERT_TRUE(DirectoryExists(FilePath(FilePath::kCurrentDirectory
)));
1797 FilePath top_level
= test_root
;
1798 while (top_level
!= top_level
.DirName()) {
1799 top_level
= top_level
.DirName();
1801 ASSERT_TRUE(DirectoryExists(top_level
));
1803 // Given these assumptions hold, it should be safe to
1804 // test that "creating" these directories succeeds.
1805 EXPECT_TRUE(CreateDirectory(
1806 FilePath(FilePath::kCurrentDirectory
)));
1807 EXPECT_TRUE(CreateDirectory(top_level
));
1810 FilePath
invalid_drive(FILE_PATH_LITERAL("o:\\"));
1811 FilePath invalid_path
=
1812 invalid_drive
.Append(FILE_PATH_LITERAL("some\\inaccessible\\dir"));
1813 if (!PathExists(invalid_drive
)) {
1814 EXPECT_FALSE(CreateDirectory(invalid_path
));
1819 TEST_F(FileUtilTest
, DetectDirectoryTest
) {
1820 // Check a directory
1821 FilePath test_root
=
1822 temp_dir_
.path().Append(FILE_PATH_LITERAL("detect_directory_test"));
1823 EXPECT_FALSE(PathExists(test_root
));
1824 EXPECT_TRUE(CreateDirectory(test_root
));
1825 EXPECT_TRUE(PathExists(test_root
));
1826 EXPECT_TRUE(DirectoryExists(test_root
));
1828 FilePath test_path
=
1829 test_root
.Append(FILE_PATH_LITERAL("foobar.txt"));
1830 EXPECT_FALSE(PathExists(test_path
));
1831 CreateTextFile(test_path
, L
"test file");
1832 EXPECT_TRUE(PathExists(test_path
));
1833 EXPECT_FALSE(DirectoryExists(test_path
));
1834 EXPECT_TRUE(DeleteFile(test_path
, false));
1836 EXPECT_TRUE(DeleteFile(test_root
, true));
1839 TEST_F(FileUtilTest
, FileEnumeratorTest
) {
1840 // Test an empty directory.
1841 FileEnumerator
f0(temp_dir_
.path(), true, FILES_AND_DIRECTORIES
);
1842 EXPECT_EQ(FPL(""), f0
.Next().value());
1843 EXPECT_EQ(FPL(""), f0
.Next().value());
1845 // Test an empty directory, non-recursively, including "..".
1846 FileEnumerator
f0_dotdot(temp_dir_
.path(), false,
1847 FILES_AND_DIRECTORIES
| FileEnumerator::INCLUDE_DOT_DOT
);
1848 EXPECT_EQ(temp_dir_
.path().Append(FPL("..")).value(),
1849 f0_dotdot
.Next().value());
1850 EXPECT_EQ(FPL(""), f0_dotdot
.Next().value());
1852 // create the directories
1853 FilePath dir1
= temp_dir_
.path().Append(FPL("dir1"));
1854 EXPECT_TRUE(CreateDirectory(dir1
));
1855 FilePath dir2
= temp_dir_
.path().Append(FPL("dir2"));
1856 EXPECT_TRUE(CreateDirectory(dir2
));
1857 FilePath dir2inner
= dir2
.Append(FPL("inner"));
1858 EXPECT_TRUE(CreateDirectory(dir2inner
));
1861 FilePath dir2file
= dir2
.Append(FPL("dir2file.txt"));
1862 CreateTextFile(dir2file
, std::wstring());
1863 FilePath dir2innerfile
= dir2inner
.Append(FPL("innerfile.txt"));
1864 CreateTextFile(dir2innerfile
, std::wstring());
1865 FilePath file1
= temp_dir_
.path().Append(FPL("file1.txt"));
1866 CreateTextFile(file1
, std::wstring());
1867 FilePath file2_rel
= dir2
.Append(FilePath::kParentDirectory
)
1868 .Append(FPL("file2.txt"));
1869 CreateTextFile(file2_rel
, std::wstring());
1870 FilePath file2_abs
= temp_dir_
.path().Append(FPL("file2.txt"));
1872 // Only enumerate files.
1873 FileEnumerator
f1(temp_dir_
.path(), true, FileEnumerator::FILES
);
1874 FindResultCollector
c1(&f1
);
1875 EXPECT_TRUE(c1
.HasFile(file1
));
1876 EXPECT_TRUE(c1
.HasFile(file2_abs
));
1877 EXPECT_TRUE(c1
.HasFile(dir2file
));
1878 EXPECT_TRUE(c1
.HasFile(dir2innerfile
));
1879 EXPECT_EQ(4, c1
.size());
1881 // Only enumerate directories.
1882 FileEnumerator
f2(temp_dir_
.path(), true, FileEnumerator::DIRECTORIES
);
1883 FindResultCollector
c2(&f2
);
1884 EXPECT_TRUE(c2
.HasFile(dir1
));
1885 EXPECT_TRUE(c2
.HasFile(dir2
));
1886 EXPECT_TRUE(c2
.HasFile(dir2inner
));
1887 EXPECT_EQ(3, c2
.size());
1889 // Only enumerate directories non-recursively.
1890 FileEnumerator
f2_non_recursive(
1891 temp_dir_
.path(), false, FileEnumerator::DIRECTORIES
);
1892 FindResultCollector
c2_non_recursive(&f2_non_recursive
);
1893 EXPECT_TRUE(c2_non_recursive
.HasFile(dir1
));
1894 EXPECT_TRUE(c2_non_recursive
.HasFile(dir2
));
1895 EXPECT_EQ(2, c2_non_recursive
.size());
1897 // Only enumerate directories, non-recursively, including "..".
1898 FileEnumerator
f2_dotdot(temp_dir_
.path(), false,
1899 FileEnumerator::DIRECTORIES
|
1900 FileEnumerator::INCLUDE_DOT_DOT
);
1901 FindResultCollector
c2_dotdot(&f2_dotdot
);
1902 EXPECT_TRUE(c2_dotdot
.HasFile(dir1
));
1903 EXPECT_TRUE(c2_dotdot
.HasFile(dir2
));
1904 EXPECT_TRUE(c2_dotdot
.HasFile(temp_dir_
.path().Append(FPL(".."))));
1905 EXPECT_EQ(3, c2_dotdot
.size());
1907 // Enumerate files and directories.
1908 FileEnumerator
f3(temp_dir_
.path(), true, FILES_AND_DIRECTORIES
);
1909 FindResultCollector
c3(&f3
);
1910 EXPECT_TRUE(c3
.HasFile(dir1
));
1911 EXPECT_TRUE(c3
.HasFile(dir2
));
1912 EXPECT_TRUE(c3
.HasFile(file1
));
1913 EXPECT_TRUE(c3
.HasFile(file2_abs
));
1914 EXPECT_TRUE(c3
.HasFile(dir2file
));
1915 EXPECT_TRUE(c3
.HasFile(dir2inner
));
1916 EXPECT_TRUE(c3
.HasFile(dir2innerfile
));
1917 EXPECT_EQ(7, c3
.size());
1919 // Non-recursive operation.
1920 FileEnumerator
f4(temp_dir_
.path(), false, FILES_AND_DIRECTORIES
);
1921 FindResultCollector
c4(&f4
);
1922 EXPECT_TRUE(c4
.HasFile(dir2
));
1923 EXPECT_TRUE(c4
.HasFile(dir2
));
1924 EXPECT_TRUE(c4
.HasFile(file1
));
1925 EXPECT_TRUE(c4
.HasFile(file2_abs
));
1926 EXPECT_EQ(4, c4
.size());
1928 // Enumerate with a pattern.
1929 FileEnumerator
f5(temp_dir_
.path(), true, FILES_AND_DIRECTORIES
, FPL("dir*"));
1930 FindResultCollector
c5(&f5
);
1931 EXPECT_TRUE(c5
.HasFile(dir1
));
1932 EXPECT_TRUE(c5
.HasFile(dir2
));
1933 EXPECT_TRUE(c5
.HasFile(dir2file
));
1934 EXPECT_TRUE(c5
.HasFile(dir2inner
));
1935 EXPECT_TRUE(c5
.HasFile(dir2innerfile
));
1936 EXPECT_EQ(5, c5
.size());
1940 // Make dir1 point to dir2.
1941 ReparsePoint
reparse_point(dir1
, dir2
);
1942 EXPECT_TRUE(reparse_point
.IsValid());
1944 if ((win::GetVersion() >= win::VERSION_VISTA
)) {
1945 // There can be a delay for the enumeration code to see the change on
1946 // the file system so skip this test for XP.
1947 // Enumerate the reparse point.
1948 FileEnumerator
f6(dir1
, true, FILES_AND_DIRECTORIES
);
1949 FindResultCollector
c6(&f6
);
1950 FilePath inner2
= dir1
.Append(FPL("inner"));
1951 EXPECT_TRUE(c6
.HasFile(inner2
));
1952 EXPECT_TRUE(c6
.HasFile(inner2
.Append(FPL("innerfile.txt"))));
1953 EXPECT_TRUE(c6
.HasFile(dir1
.Append(FPL("dir2file.txt"))));
1954 EXPECT_EQ(3, c6
.size());
1957 // No changes for non recursive operation.
1958 FileEnumerator
f7(temp_dir_
.path(), false, FILES_AND_DIRECTORIES
);
1959 FindResultCollector
c7(&f7
);
1960 EXPECT_TRUE(c7
.HasFile(dir2
));
1961 EXPECT_TRUE(c7
.HasFile(dir2
));
1962 EXPECT_TRUE(c7
.HasFile(file1
));
1963 EXPECT_TRUE(c7
.HasFile(file2_abs
));
1964 EXPECT_EQ(4, c7
.size());
1966 // Should not enumerate inside dir1 when using recursion.
1967 FileEnumerator
f8(temp_dir_
.path(), true, FILES_AND_DIRECTORIES
);
1968 FindResultCollector
c8(&f8
);
1969 EXPECT_TRUE(c8
.HasFile(dir1
));
1970 EXPECT_TRUE(c8
.HasFile(dir2
));
1971 EXPECT_TRUE(c8
.HasFile(file1
));
1972 EXPECT_TRUE(c8
.HasFile(file2_abs
));
1973 EXPECT_TRUE(c8
.HasFile(dir2file
));
1974 EXPECT_TRUE(c8
.HasFile(dir2inner
));
1975 EXPECT_TRUE(c8
.HasFile(dir2innerfile
));
1976 EXPECT_EQ(7, c8
.size());
1980 // Make sure the destructor closes the find handle while in the middle of a
1981 // query to allow TearDown to delete the directory.
1982 FileEnumerator
f9(temp_dir_
.path(), true, FILES_AND_DIRECTORIES
);
1983 EXPECT_FALSE(f9
.Next().value().empty()); // Should have found something
1984 // (we don't care what).
1987 TEST_F(FileUtilTest
, AppendToFile
) {
1989 temp_dir_
.path().Append(FILE_PATH_LITERAL("FilePathTest"));
1991 // Create a fresh, empty copy of this directory.
1992 if (PathExists(data_dir
)) {
1993 ASSERT_TRUE(DeleteFile(data_dir
, true));
1995 ASSERT_TRUE(CreateDirectory(data_dir
));
1997 // Create a fresh, empty copy of this directory.
1998 if (PathExists(data_dir
)) {
1999 ASSERT_TRUE(DeleteFile(data_dir
, true));
2001 ASSERT_TRUE(CreateDirectory(data_dir
));
2002 FilePath
foobar(data_dir
.Append(FILE_PATH_LITERAL("foobar.txt")));
2004 std::string
data("hello");
2005 EXPECT_FALSE(AppendToFile(foobar
, data
.c_str(), data
.size()));
2006 EXPECT_EQ(static_cast<int>(data
.length()),
2007 WriteFile(foobar
, data
.c_str(), data
.length()));
2008 EXPECT_TRUE(AppendToFile(foobar
, data
.c_str(), data
.size()));
2010 const std::wstring read_content
= ReadTextFile(foobar
);
2011 EXPECT_EQ(L
"hellohello", read_content
);
2014 TEST_F(FileUtilTest
, ReadFile
) {
2015 // Create a test file to be read.
2016 const std::string
kTestData("The quick brown fox jumps over the lazy dog.");
2017 FilePath file_path
=
2018 temp_dir_
.path().Append(FILE_PATH_LITERAL("ReadFileTest"));
2020 ASSERT_EQ(static_cast<int>(kTestData
.size()),
2021 WriteFile(file_path
, kTestData
.data(), kTestData
.size()));
2023 // Make buffers with various size.
2024 std::vector
<char> small_buffer(kTestData
.size() / 2);
2025 std::vector
<char> exact_buffer(kTestData
.size());
2026 std::vector
<char> large_buffer(kTestData
.size() * 2);
2028 // Read the file with smaller buffer.
2029 int bytes_read_small
= ReadFile(
2030 file_path
, &small_buffer
[0], static_cast<int>(small_buffer
.size()));
2031 EXPECT_EQ(static_cast<int>(small_buffer
.size()), bytes_read_small
);
2033 std::string(kTestData
.begin(), kTestData
.begin() + small_buffer
.size()),
2034 std::string(small_buffer
.begin(), small_buffer
.end()));
2036 // Read the file with buffer which have exactly same size.
2037 int bytes_read_exact
= ReadFile(
2038 file_path
, &exact_buffer
[0], static_cast<int>(exact_buffer
.size()));
2039 EXPECT_EQ(static_cast<int>(kTestData
.size()), bytes_read_exact
);
2040 EXPECT_EQ(kTestData
, std::string(exact_buffer
.begin(), exact_buffer
.end()));
2042 // Read the file with larger buffer.
2043 int bytes_read_large
= ReadFile(
2044 file_path
, &large_buffer
[0], static_cast<int>(large_buffer
.size()));
2045 EXPECT_EQ(static_cast<int>(kTestData
.size()), bytes_read_large
);
2046 EXPECT_EQ(kTestData
, std::string(large_buffer
.begin(),
2047 large_buffer
.begin() + kTestData
.size()));
2049 // Make sure the return value is -1 if the file doesn't exist.
2050 FilePath file_path_not_exist
=
2051 temp_dir_
.path().Append(FILE_PATH_LITERAL("ReadFileNotExistTest"));
2053 ReadFile(file_path_not_exist
,
2055 static_cast<int>(exact_buffer
.size())));
2058 TEST_F(FileUtilTest
, ReadFileToString
) {
2059 const char kTestData
[] = "0123";
2062 FilePath file_path
=
2063 temp_dir_
.path().Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
2064 FilePath file_path_dangerous
=
2065 temp_dir_
.path().Append(FILE_PATH_LITERAL("..")).
2066 Append(temp_dir_
.path().BaseName()).
2067 Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
2069 // Create test file.
2070 ASSERT_EQ(4, WriteFile(file_path
, kTestData
, 4));
2072 EXPECT_TRUE(ReadFileToString(file_path
, &data
));
2073 EXPECT_EQ(kTestData
, data
);
2076 EXPECT_FALSE(ReadFileToString(file_path
, &data
, 0));
2077 EXPECT_EQ(0u, data
.length());
2080 EXPECT_FALSE(ReadFileToString(file_path
, &data
, 2));
2081 EXPECT_EQ("01", data
);
2084 EXPECT_FALSE(ReadFileToString(file_path
, &data
, 3));
2085 EXPECT_EQ("012", data
);
2088 EXPECT_TRUE(ReadFileToString(file_path
, &data
, 4));
2089 EXPECT_EQ("0123", data
);
2092 EXPECT_TRUE(ReadFileToString(file_path
, &data
, 6));
2093 EXPECT_EQ("0123", data
);
2095 EXPECT_TRUE(ReadFileToString(file_path
, NULL
, 6));
2097 EXPECT_TRUE(ReadFileToString(file_path
, NULL
));
2100 EXPECT_FALSE(ReadFileToString(file_path_dangerous
, &data
));
2101 EXPECT_EQ(0u, data
.length());
2103 // Delete test file.
2104 EXPECT_TRUE(DeleteFile(file_path
, false));
2107 EXPECT_FALSE(ReadFileToString(file_path
, &data
));
2108 EXPECT_EQ(0u, data
.length());
2111 EXPECT_FALSE(ReadFileToString(file_path
, &data
, 6));
2112 EXPECT_EQ(0u, data
.length());
2115 TEST_F(FileUtilTest
, TouchFile
) {
2117 temp_dir_
.path().Append(FILE_PATH_LITERAL("FilePathTest"));
2119 // Create a fresh, empty copy of this directory.
2120 if (PathExists(data_dir
)) {
2121 ASSERT_TRUE(DeleteFile(data_dir
, true));
2123 ASSERT_TRUE(CreateDirectory(data_dir
));
2125 FilePath
foobar(data_dir
.Append(FILE_PATH_LITERAL("foobar.txt")));
2126 std::string
data("hello");
2127 ASSERT_TRUE(WriteFile(foobar
, data
.c_str(), data
.length()));
2130 // This timestamp is divisible by one day (in local timezone),
2131 // to make it work on FAT too.
2132 ASSERT_TRUE(Time::FromString("Wed, 16 Nov 1994, 00:00:00",
2135 Time modification_time
;
2136 // Note that this timestamp is divisible by two (seconds) - FAT stores
2137 // modification times with 2s resolution.
2138 ASSERT_TRUE(Time::FromString("Tue, 15 Nov 1994, 12:45:26 GMT",
2139 &modification_time
));
2141 ASSERT_TRUE(TouchFile(foobar
, access_time
, modification_time
));
2142 File::Info file_info
;
2143 ASSERT_TRUE(GetFileInfo(foobar
, &file_info
));
2144 EXPECT_EQ(access_time
.ToInternalValue(),
2145 file_info
.last_accessed
.ToInternalValue());
2146 EXPECT_EQ(modification_time
.ToInternalValue(),
2147 file_info
.last_modified
.ToInternalValue());
2150 TEST_F(FileUtilTest
, IsDirectoryEmpty
) {
2151 FilePath empty_dir
= temp_dir_
.path().Append(FILE_PATH_LITERAL("EmptyDir"));
2153 ASSERT_FALSE(PathExists(empty_dir
));
2155 ASSERT_TRUE(CreateDirectory(empty_dir
));
2157 EXPECT_TRUE(IsDirectoryEmpty(empty_dir
));
2159 FilePath
foo(empty_dir
.Append(FILE_PATH_LITERAL("foo.txt")));
2160 std::string
bar("baz");
2161 ASSERT_TRUE(WriteFile(foo
, bar
.c_str(), bar
.length()));
2163 EXPECT_FALSE(IsDirectoryEmpty(empty_dir
));
2166 #if defined(OS_POSIX)
2168 // Testing VerifyPathControlledByAdmin() is hard, because there is no
2169 // way a test can make a file owned by root, or change file paths
2170 // at the root of the file system. VerifyPathControlledByAdmin()
2171 // is implemented as a call to VerifyPathControlledByUser, which gives
2172 // us the ability to test with paths under the test's temp directory,
2173 // using a user id we control.
2174 // Pull tests of VerifyPathControlledByUserTest() into a separate test class
2175 // with a common SetUp() method.
2176 class VerifyPathControlledByUserTest
: public FileUtilTest
{
2178 void SetUp() override
{
2179 FileUtilTest::SetUp();
2181 // Create a basic structure used by each test.
2186 base_dir_
= temp_dir_
.path().AppendASCII("base_dir");
2187 ASSERT_TRUE(CreateDirectory(base_dir_
));
2189 sub_dir_
= base_dir_
.AppendASCII("sub_dir");
2190 ASSERT_TRUE(CreateDirectory(sub_dir_
));
2192 text_file_
= sub_dir_
.AppendASCII("file.txt");
2193 CreateTextFile(text_file_
, L
"This text file has some text in it.");
2195 // Get the user and group files are created with from |base_dir_|.
2196 struct stat stat_buf
;
2197 ASSERT_EQ(0, stat(base_dir_
.value().c_str(), &stat_buf
));
2198 uid_
= stat_buf
.st_uid
;
2199 ok_gids_
.insert(stat_buf
.st_gid
);
2200 bad_gids_
.insert(stat_buf
.st_gid
+ 1);
2202 ASSERT_EQ(uid_
, getuid()); // This process should be the owner.
2204 // To ensure that umask settings do not cause the initial state
2205 // of permissions to be different from what we expect, explicitly
2206 // set permissions on the directories we create.
2207 // Make all files and directories non-world-writable.
2209 // Users and group can read, write, traverse
2210 int enabled_permissions
=
2211 FILE_PERMISSION_USER_MASK
| FILE_PERMISSION_GROUP_MASK
;
2212 // Other users can't read, write, traverse
2213 int disabled_permissions
= FILE_PERMISSION_OTHERS_MASK
;
2215 ASSERT_NO_FATAL_FAILURE(
2216 ChangePosixFilePermissions(
2217 base_dir_
, enabled_permissions
, disabled_permissions
));
2218 ASSERT_NO_FATAL_FAILURE(
2219 ChangePosixFilePermissions(
2220 sub_dir_
, enabled_permissions
, disabled_permissions
));
2225 FilePath text_file_
;
2228 std::set
<gid_t
> ok_gids_
;
2229 std::set
<gid_t
> bad_gids_
;
2232 TEST_F(VerifyPathControlledByUserTest
, BadPaths
) {
2233 // File does not exist.
2234 FilePath does_not_exist
= base_dir_
.AppendASCII("does")
2236 .AppendASCII("exist");
2238 VerifyPathControlledByUser(base_dir_
, does_not_exist
, uid_
, ok_gids_
));
2240 // |base| not a subpath of |path|.
2241 EXPECT_FALSE(VerifyPathControlledByUser(sub_dir_
, base_dir_
, uid_
, ok_gids_
));
2243 // An empty base path will fail to be a prefix for any path.
2245 EXPECT_FALSE(VerifyPathControlledByUser(empty
, base_dir_
, uid_
, ok_gids_
));
2247 // Finding that a bad call fails proves nothing unless a good call succeeds.
2248 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2251 TEST_F(VerifyPathControlledByUserTest
, Symlinks
) {
2252 // Symlinks in the path should cause failure.
2254 // Symlink to the file at the end of the path.
2255 FilePath file_link
= base_dir_
.AppendASCII("file_link");
2256 ASSERT_TRUE(CreateSymbolicLink(text_file_
, file_link
))
2257 << "Failed to create symlink.";
2260 VerifyPathControlledByUser(base_dir_
, file_link
, uid_
, ok_gids_
));
2262 VerifyPathControlledByUser(file_link
, file_link
, uid_
, ok_gids_
));
2264 // Symlink from one directory to another within the path.
2265 FilePath link_to_sub_dir
= base_dir_
.AppendASCII("link_to_sub_dir");
2266 ASSERT_TRUE(CreateSymbolicLink(sub_dir_
, link_to_sub_dir
))
2267 << "Failed to create symlink.";
2269 FilePath file_path_with_link
= link_to_sub_dir
.AppendASCII("file.txt");
2270 ASSERT_TRUE(PathExists(file_path_with_link
));
2272 EXPECT_FALSE(VerifyPathControlledByUser(base_dir_
, file_path_with_link
, uid_
,
2275 EXPECT_FALSE(VerifyPathControlledByUser(link_to_sub_dir
, file_path_with_link
,
2278 // Symlinks in parents of base path are allowed.
2279 EXPECT_TRUE(VerifyPathControlledByUser(file_path_with_link
,
2280 file_path_with_link
, uid_
, ok_gids_
));
2283 TEST_F(VerifyPathControlledByUserTest
, OwnershipChecks
) {
2284 // Get a uid that is not the uid of files we create.
2285 uid_t bad_uid
= uid_
+ 1;
2287 // Make all files and directories non-world-writable.
2288 ASSERT_NO_FATAL_FAILURE(
2289 ChangePosixFilePermissions(base_dir_
, 0u, S_IWOTH
));
2290 ASSERT_NO_FATAL_FAILURE(
2291 ChangePosixFilePermissions(sub_dir_
, 0u, S_IWOTH
));
2292 ASSERT_NO_FATAL_FAILURE(
2293 ChangePosixFilePermissions(text_file_
, 0u, S_IWOTH
));
2295 // We control these paths.
2296 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2298 VerifyPathControlledByUser(base_dir_
, text_file_
, uid_
, ok_gids_
));
2299 EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_
, text_file_
, uid_
, ok_gids_
));
2301 // Another user does not control these paths.
2303 VerifyPathControlledByUser(base_dir_
, sub_dir_
, bad_uid
, ok_gids_
));
2305 VerifyPathControlledByUser(base_dir_
, text_file_
, bad_uid
, ok_gids_
));
2307 VerifyPathControlledByUser(sub_dir_
, text_file_
, bad_uid
, ok_gids_
));
2309 // Another group does not control the paths.
2311 VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, bad_gids_
));
2313 VerifyPathControlledByUser(base_dir_
, text_file_
, uid_
, bad_gids_
));
2315 VerifyPathControlledByUser(sub_dir_
, text_file_
, uid_
, bad_gids_
));
2318 TEST_F(VerifyPathControlledByUserTest
, GroupWriteTest
) {
2319 // Make all files and directories writable only by their owner.
2320 ASSERT_NO_FATAL_FAILURE(
2321 ChangePosixFilePermissions(base_dir_
, 0u, S_IWOTH
|S_IWGRP
));
2322 ASSERT_NO_FATAL_FAILURE(
2323 ChangePosixFilePermissions(sub_dir_
, 0u, S_IWOTH
|S_IWGRP
));
2324 ASSERT_NO_FATAL_FAILURE(
2325 ChangePosixFilePermissions(text_file_
, 0u, S_IWOTH
|S_IWGRP
));
2327 // Any group is okay because the path is not group-writable.
2328 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2330 VerifyPathControlledByUser(base_dir_
, text_file_
, uid_
, ok_gids_
));
2331 EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_
, text_file_
, uid_
, ok_gids_
));
2333 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, bad_gids_
));
2335 VerifyPathControlledByUser(base_dir_
, text_file_
, uid_
, bad_gids_
));
2337 VerifyPathControlledByUser(sub_dir_
, text_file_
, uid_
, bad_gids_
));
2339 // No group is okay, because we don't check the group
2340 // if no group can write.
2341 std::set
<gid_t
> no_gids
; // Empty set of gids.
2342 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, no_gids
));
2343 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_
, text_file_
, uid_
, no_gids
));
2344 EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_
, text_file_
, uid_
, no_gids
));
2346 // Make all files and directories writable by their group.
2347 ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(base_dir_
, S_IWGRP
, 0u));
2348 ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(sub_dir_
, S_IWGRP
, 0u));
2349 ASSERT_NO_FATAL_FAILURE(ChangePosixFilePermissions(text_file_
, S_IWGRP
, 0u));
2351 // Now |ok_gids_| works, but |bad_gids_| fails.
2352 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2354 VerifyPathControlledByUser(base_dir_
, text_file_
, uid_
, ok_gids_
));
2355 EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_
, text_file_
, uid_
, ok_gids_
));
2358 VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, bad_gids_
));
2360 VerifyPathControlledByUser(base_dir_
, text_file_
, uid_
, bad_gids_
));
2362 VerifyPathControlledByUser(sub_dir_
, text_file_
, uid_
, bad_gids_
));
2364 // Because any group in the group set is allowed,
2365 // the union of good and bad gids passes.
2367 std::set
<gid_t
> multiple_gids
;
2369 ok_gids_
.begin(), ok_gids_
.end(),
2370 bad_gids_
.begin(), bad_gids_
.end(),
2371 std::inserter(multiple_gids
, multiple_gids
.begin()));
2374 VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, multiple_gids
));
2376 VerifyPathControlledByUser(base_dir_
, text_file_
, uid_
, multiple_gids
));
2378 VerifyPathControlledByUser(sub_dir_
, text_file_
, uid_
, multiple_gids
));
2381 TEST_F(VerifyPathControlledByUserTest
, WriteBitChecks
) {
2382 // Make all files and directories non-world-writable.
2383 ASSERT_NO_FATAL_FAILURE(
2384 ChangePosixFilePermissions(base_dir_
, 0u, S_IWOTH
));
2385 ASSERT_NO_FATAL_FAILURE(
2386 ChangePosixFilePermissions(sub_dir_
, 0u, S_IWOTH
));
2387 ASSERT_NO_FATAL_FAILURE(
2388 ChangePosixFilePermissions(text_file_
, 0u, S_IWOTH
));
2390 // Initialy, we control all parts of the path.
2391 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2393 VerifyPathControlledByUser(base_dir_
, text_file_
, uid_
, ok_gids_
));
2394 EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_
, text_file_
, uid_
, ok_gids_
));
2396 // Make base_dir_ world-writable.
2397 ASSERT_NO_FATAL_FAILURE(
2398 ChangePosixFilePermissions(base_dir_
, S_IWOTH
, 0u));
2399 EXPECT_FALSE(VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2401 VerifyPathControlledByUser(base_dir_
, text_file_
, uid_
, ok_gids_
));
2402 EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_
, text_file_
, uid_
, ok_gids_
));
2404 // Make sub_dir_ world writable.
2405 ASSERT_NO_FATAL_FAILURE(
2406 ChangePosixFilePermissions(sub_dir_
, S_IWOTH
, 0u));
2407 EXPECT_FALSE(VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2409 VerifyPathControlledByUser(base_dir_
, text_file_
, uid_
, ok_gids_
));
2411 VerifyPathControlledByUser(sub_dir_
, text_file_
, uid_
, ok_gids_
));
2413 // Make text_file_ world writable.
2414 ASSERT_NO_FATAL_FAILURE(
2415 ChangePosixFilePermissions(text_file_
, S_IWOTH
, 0u));
2416 EXPECT_FALSE(VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2418 VerifyPathControlledByUser(base_dir_
, text_file_
, uid_
, ok_gids_
));
2420 VerifyPathControlledByUser(sub_dir_
, text_file_
, uid_
, ok_gids_
));
2422 // Make sub_dir_ non-world writable.
2423 ASSERT_NO_FATAL_FAILURE(
2424 ChangePosixFilePermissions(sub_dir_
, 0u, S_IWOTH
));
2425 EXPECT_FALSE(VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2427 VerifyPathControlledByUser(base_dir_
, text_file_
, uid_
, ok_gids_
));
2429 VerifyPathControlledByUser(sub_dir_
, text_file_
, uid_
, ok_gids_
));
2431 // Make base_dir_ non-world-writable.
2432 ASSERT_NO_FATAL_FAILURE(
2433 ChangePosixFilePermissions(base_dir_
, 0u, S_IWOTH
));
2434 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2436 VerifyPathControlledByUser(base_dir_
, text_file_
, uid_
, ok_gids_
));
2438 VerifyPathControlledByUser(sub_dir_
, text_file_
, uid_
, ok_gids_
));
2440 // Back to the initial state: Nothing is writable, so every path
2442 ASSERT_NO_FATAL_FAILURE(
2443 ChangePosixFilePermissions(text_file_
, 0u, S_IWOTH
));
2444 EXPECT_TRUE(VerifyPathControlledByUser(base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2446 VerifyPathControlledByUser(base_dir_
, text_file_
, uid_
, ok_gids_
));
2447 EXPECT_TRUE(VerifyPathControlledByUser(sub_dir_
, text_file_
, uid_
, ok_gids_
));
2450 #if defined(OS_ANDROID)
2451 TEST_F(FileUtilTest
, ValidContentUriTest
) {
2452 // Get the test image path.
2454 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA
, &data_dir
));
2455 data_dir
= data_dir
.AppendASCII("file_util");
2456 ASSERT_TRUE(PathExists(data_dir
));
2457 FilePath image_file
= data_dir
.Append(FILE_PATH_LITERAL("red.png"));
2459 GetFileSize(image_file
, &image_size
);
2460 EXPECT_LT(0, image_size
);
2462 // Insert the image into MediaStore. MediaStore will do some conversions, and
2463 // return the content URI.
2464 FilePath path
= InsertImageIntoMediaStore(image_file
);
2465 EXPECT_TRUE(path
.IsContentUri());
2466 EXPECT_TRUE(PathExists(path
));
2467 // The file size may not equal to the input image as MediaStore may convert
2469 int64 content_uri_size
;
2470 GetFileSize(path
, &content_uri_size
);
2471 EXPECT_EQ(image_size
, content_uri_size
);
2473 // We should be able to read the file.
2474 char* buffer
= new char[image_size
];
2475 File file
= OpenContentUriForRead(path
);
2476 EXPECT_TRUE(file
.IsValid());
2477 EXPECT_TRUE(file
.ReadAtCurrentPos(buffer
, image_size
));
2481 TEST_F(FileUtilTest
, NonExistentContentUriTest
) {
2482 FilePath
path("content://foo.bar");
2483 EXPECT_TRUE(path
.IsContentUri());
2484 EXPECT_FALSE(PathExists(path
));
2485 // Size should be smaller than 0.
2487 EXPECT_FALSE(GetFileSize(path
, &size
));
2489 // We should not be able to read the file.
2490 File file
= OpenContentUriForRead(path
);
2491 EXPECT_FALSE(file
.IsValid());
2495 TEST(ScopedFD
, ScopedFDDoesClose
) {
2498 ASSERT_EQ(0, pipe(fds
));
2499 const int write_end
= fds
[1];
2500 ScopedFD
read_end_closer(fds
[0]);
2502 ScopedFD
write_end_closer(fds
[1]);
2504 // This is the only thread. This file descriptor should no longer be valid.
2505 int ret
= close(write_end
);
2507 EXPECT_EQ(EBADF
, errno
);
2508 // Make sure read(2) won't block.
2509 ASSERT_EQ(0, fcntl(fds
[0], F_SETFL
, O_NONBLOCK
));
2510 // Reading the pipe should EOF.
2511 EXPECT_EQ(0, read(fds
[0], &c
, 1));
2514 #if defined(GTEST_HAS_DEATH_TEST)
2515 void CloseWithScopedFD(int fd
) {
2516 ScopedFD
fd_closer(fd
);
2520 TEST(ScopedFD
, ScopedFDCrashesOnCloseFailure
) {
2522 ASSERT_EQ(0, pipe(fds
));
2523 ScopedFD
read_end_closer(fds
[0]);
2524 EXPECT_EQ(0, IGNORE_EINTR(close(fds
[1])));
2525 #if defined(GTEST_HAS_DEATH_TEST)
2526 // This is the only thread. This file descriptor should no longer be valid.
2527 // Trying to close it should crash. This is important for security.
2528 EXPECT_DEATH(CloseWithScopedFD(fds
[1]), "");
2532 #endif // defined(OS_POSIX)