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/utf_string_conversions.h"
34 #include "base/test/test_file_util.h"
35 #include "base/threading/platform_thread.h"
36 #include "testing/gtest/include/gtest/gtest.h"
37 #include "testing/platform_test.h"
40 #include "base/win/scoped_handle.h"
41 #include "base/win/windows_version.h"
44 #if defined(OS_ANDROID)
45 #include "base/android/content_uri_utils.h"
48 // This macro helps avoid wrapped lines in the test structs.
49 #define FPL(x) FILE_PATH_LITERAL(x)
55 // To test that NormalizeFilePath() deals with NTFS reparse points correctly,
56 // we need functions to create and delete reparse points.
58 typedef struct _REPARSE_DATA_BUFFER
{
60 USHORT ReparseDataLength
;
64 USHORT SubstituteNameOffset
;
65 USHORT SubstituteNameLength
;
66 USHORT PrintNameOffset
;
67 USHORT PrintNameLength
;
70 } SymbolicLinkReparseBuffer
;
72 USHORT SubstituteNameOffset
;
73 USHORT SubstituteNameLength
;
74 USHORT PrintNameOffset
;
75 USHORT PrintNameLength
;
77 } MountPointReparseBuffer
;
80 } GenericReparseBuffer
;
82 } REPARSE_DATA_BUFFER
, *PREPARSE_DATA_BUFFER
;
84 // Sets a reparse point. |source| will now point to |target|. Returns true if
85 // the call succeeds, false otherwise.
86 bool SetReparsePoint(HANDLE source
, const FilePath
& target_path
) {
87 std::wstring kPathPrefix
= L
"\\??\\";
88 std::wstring target_str
;
89 // The juction will not work if the target path does not start with \??\ .
90 if (kPathPrefix
!= target_path
.value().substr(0, kPathPrefix
.size()))
91 target_str
+= kPathPrefix
;
92 target_str
+= target_path
.value();
93 const wchar_t* target
= target_str
.c_str();
94 USHORT size_target
= static_cast<USHORT
>(wcslen(target
)) * sizeof(target
[0]);
95 char buffer
[2000] = {0};
98 REPARSE_DATA_BUFFER
* data
= reinterpret_cast<REPARSE_DATA_BUFFER
*>(buffer
);
100 data
->ReparseTag
= 0xa0000003;
101 memcpy(data
->MountPointReparseBuffer
.PathBuffer
, target
, size_target
+ 2);
103 data
->MountPointReparseBuffer
.SubstituteNameLength
= size_target
;
104 data
->MountPointReparseBuffer
.PrintNameOffset
= size_target
+ 2;
105 data
->ReparseDataLength
= size_target
+ 4 + 8;
107 int data_size
= data
->ReparseDataLength
+ 8;
109 if (!DeviceIoControl(source
, FSCTL_SET_REPARSE_POINT
, &buffer
, data_size
,
110 NULL
, 0, &returned
, NULL
)) {
116 // Delete the reparse point referenced by |source|. Returns true if the call
117 // succeeds, false otherwise.
118 bool DeleteReparsePoint(HANDLE source
) {
120 REPARSE_DATA_BUFFER data
= {0};
121 data
.ReparseTag
= 0xa0000003;
122 if (!DeviceIoControl(source
, FSCTL_DELETE_REPARSE_POINT
, &data
, 8, NULL
, 0,
129 // Manages a reparse point for a test.
132 // Creates a reparse point from |source| (an empty directory) to |target|.
133 ReparsePoint(const FilePath
& source
, const FilePath
& target
) {
135 ::CreateFile(source
.value().c_str(),
137 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
140 FILE_FLAG_BACKUP_SEMANTICS
, // Needed to open a directory.
142 created_
= dir_
.IsValid() && SetReparsePoint(dir_
.Get(), target
);
147 DeleteReparsePoint(dir_
.Get());
150 bool IsValid() { return created_
; }
153 win::ScopedHandle dir_
;
155 DISALLOW_COPY_AND_ASSIGN(ReparsePoint
);
160 #if defined(OS_POSIX)
161 // Provide a simple way to change the permissions bits on |path| in tests.
162 // ASSERT failures will return, but not stop the test. Caller should wrap
163 // calls to this function in ASSERT_NO_FATAL_FAILURE().
164 void ChangePosixFilePermissions(const FilePath
& path
,
165 int mode_bits_to_set
,
166 int mode_bits_to_clear
) {
167 ASSERT_FALSE(mode_bits_to_set
& mode_bits_to_clear
)
168 << "Can't set and clear the same bits.";
171 ASSERT_TRUE(GetPosixFilePermissions(path
, &mode
));
172 mode
|= mode_bits_to_set
;
173 mode
&= ~mode_bits_to_clear
;
174 ASSERT_TRUE(SetPosixFilePermissions(path
, mode
));
176 #endif // defined(OS_POSIX)
178 const wchar_t bogus_content
[] = L
"I'm cannon fodder.";
180 const int FILES_AND_DIRECTORIES
=
181 FileEnumerator::FILES
| FileEnumerator::DIRECTORIES
;
183 // file_util winds up using autoreleased objects on the Mac, so this needs
184 // to be a PlatformTest
185 class FileUtilTest
: public PlatformTest
{
187 void SetUp() override
{
188 PlatformTest::SetUp();
189 ASSERT_TRUE(temp_dir_
.CreateUniqueTempDir());
192 ScopedTempDir temp_dir_
;
195 // Collects all the results from the given file enumerator, and provides an
196 // interface to query whether a given file is present.
197 class FindResultCollector
{
199 explicit FindResultCollector(FileEnumerator
& enumerator
) {
201 while (!(cur_file
= enumerator
.Next()).value().empty()) {
202 FilePath::StringType path
= cur_file
.value();
203 // The file should not be returned twice.
204 EXPECT_TRUE(files_
.end() == files_
.find(path
))
205 << "Same file returned twice";
212 // Returns true if the enumerator found the file.
213 bool HasFile(const FilePath
& file
) const {
214 return files_
.find(file
.value()) != files_
.end();
218 return static_cast<int>(files_
.size());
222 std::set
<FilePath::StringType
> files_
;
225 // Simple function to dump some text into a new file.
226 void CreateTextFile(const FilePath
& filename
,
227 const std::wstring
& contents
) {
229 file
.open(filename
.value().c_str());
230 ASSERT_TRUE(file
.is_open());
235 // Simple function to take out some text from a file.
236 std::wstring
ReadTextFile(const FilePath
& filename
) {
237 wchar_t contents
[64];
239 file
.open(filename
.value().c_str());
240 EXPECT_TRUE(file
.is_open());
241 file
.getline(contents
, arraysize(contents
));
243 return std::wstring(contents
);
247 uint64
FileTimeAsUint64(const FILETIME
& ft
) {
249 u
.LowPart
= ft
.dwLowDateTime
;
250 u
.HighPart
= ft
.dwHighDateTime
;
255 TEST_F(FileUtilTest
, FileAndDirectorySize
) {
256 // Create three files of 20, 30 and 3 chars (utf8). ComputeDirectorySize
257 // should return 53 bytes.
258 FilePath file_01
= temp_dir_
.path().Append(FPL("The file 01.txt"));
259 CreateTextFile(file_01
, L
"12345678901234567890");
261 ASSERT_TRUE(GetFileSize(file_01
, &size_f1
));
262 EXPECT_EQ(20ll, size_f1
);
264 FilePath subdir_path
= temp_dir_
.path().Append(FPL("Level2"));
265 CreateDirectory(subdir_path
);
267 FilePath file_02
= subdir_path
.Append(FPL("The file 02.txt"));
268 CreateTextFile(file_02
, L
"123456789012345678901234567890");
270 ASSERT_TRUE(GetFileSize(file_02
, &size_f2
));
271 EXPECT_EQ(30ll, size_f2
);
273 FilePath subsubdir_path
= subdir_path
.Append(FPL("Level3"));
274 CreateDirectory(subsubdir_path
);
276 FilePath file_03
= subsubdir_path
.Append(FPL("The file 03.txt"));
277 CreateTextFile(file_03
, L
"123");
279 int64 computed_size
= ComputeDirectorySize(temp_dir_
.path());
280 EXPECT_EQ(size_f1
+ size_f2
+ 3, computed_size
);
283 TEST_F(FileUtilTest
, NormalizeFilePathBasic
) {
284 // Create a directory under the test dir. Because we create it,
285 // we know it is not a link.
286 FilePath file_a_path
= temp_dir_
.path().Append(FPL("file_a"));
287 FilePath dir_path
= temp_dir_
.path().Append(FPL("dir"));
288 FilePath file_b_path
= dir_path
.Append(FPL("file_b"));
289 CreateDirectory(dir_path
);
291 FilePath normalized_file_a_path
, normalized_file_b_path
;
292 ASSERT_FALSE(PathExists(file_a_path
));
293 ASSERT_FALSE(NormalizeFilePath(file_a_path
, &normalized_file_a_path
))
294 << "NormalizeFilePath() should fail on nonexistent paths.";
296 CreateTextFile(file_a_path
, bogus_content
);
297 ASSERT_TRUE(PathExists(file_a_path
));
298 ASSERT_TRUE(NormalizeFilePath(file_a_path
, &normalized_file_a_path
));
300 CreateTextFile(file_b_path
, bogus_content
);
301 ASSERT_TRUE(PathExists(file_b_path
));
302 ASSERT_TRUE(NormalizeFilePath(file_b_path
, &normalized_file_b_path
));
304 // Beacuse this test created |dir_path|, we know it is not a link
305 // or junction. So, the real path of the directory holding file a
306 // must be the parent of the path holding file b.
307 ASSERT_TRUE(normalized_file_a_path
.DirName()
308 .IsParent(normalized_file_b_path
.DirName()));
313 TEST_F(FileUtilTest
, NormalizeFilePathReparsePoints
) {
314 // Build the following directory structure:
320 // | |-> long_name___... (Very long name.)
324 // |-> to_sub_a (reparse point to temp_dir\base_a\sub_a)
325 // |-> to_base_b (reparse point to temp_dir\base_b)
326 // |-> to_sub_long (reparse point to temp_dir\sub_a\long_name_\sub_long)
328 FilePath base_a
= temp_dir_
.path().Append(FPL("base_a"));
329 ASSERT_TRUE(CreateDirectory(base_a
));
331 FilePath sub_a
= base_a
.Append(FPL("sub_a"));
332 ASSERT_TRUE(CreateDirectory(sub_a
));
334 FilePath file_txt
= sub_a
.Append(FPL("file.txt"));
335 CreateTextFile(file_txt
, bogus_content
);
337 // Want a directory whose name is long enough to make the path to the file
338 // inside just under MAX_PATH chars. This will be used to test that when
339 // a junction expands to a path over MAX_PATH chars in length,
340 // NormalizeFilePath() fails without crashing.
341 FilePath
sub_long_rel(FPL("sub_long"));
342 FilePath
deep_txt(FPL("deep.txt"));
344 int target_length
= MAX_PATH
;
345 target_length
-= (sub_a
.value().length() + 1); // +1 for the sepperator '\'.
346 target_length
-= (sub_long_rel
.Append(deep_txt
).value().length() + 1);
347 // Without making the path a bit shorter, CreateDirectory() fails.
348 // the resulting path is still long enough to hit the failing case in
350 const int kCreateDirLimit
= 4;
351 target_length
-= kCreateDirLimit
;
352 FilePath::StringType long_name_str
= FPL("long_name_");
353 long_name_str
.resize(target_length
, '_');
355 FilePath long_name
= sub_a
.Append(FilePath(long_name_str
));
356 FilePath deep_file
= long_name
.Append(sub_long_rel
).Append(deep_txt
);
357 ASSERT_EQ(MAX_PATH
- kCreateDirLimit
, deep_file
.value().length());
359 FilePath sub_long
= deep_file
.DirName();
360 ASSERT_TRUE(CreateDirectory(sub_long
));
361 CreateTextFile(deep_file
, bogus_content
);
363 FilePath base_b
= temp_dir_
.path().Append(FPL("base_b"));
364 ASSERT_TRUE(CreateDirectory(base_b
));
366 FilePath to_sub_a
= base_b
.Append(FPL("to_sub_a"));
367 ASSERT_TRUE(CreateDirectory(to_sub_a
));
368 FilePath normalized_path
;
370 ReparsePoint
reparse_to_sub_a(to_sub_a
, sub_a
);
371 ASSERT_TRUE(reparse_to_sub_a
.IsValid());
373 FilePath to_base_b
= base_b
.Append(FPL("to_base_b"));
374 ASSERT_TRUE(CreateDirectory(to_base_b
));
375 ReparsePoint
reparse_to_base_b(to_base_b
, base_b
);
376 ASSERT_TRUE(reparse_to_base_b
.IsValid());
378 FilePath to_sub_long
= base_b
.Append(FPL("to_sub_long"));
379 ASSERT_TRUE(CreateDirectory(to_sub_long
));
380 ReparsePoint
reparse_to_sub_long(to_sub_long
, sub_long
);
381 ASSERT_TRUE(reparse_to_sub_long
.IsValid());
383 // Normalize a junction free path: base_a\sub_a\file.txt .
384 ASSERT_TRUE(NormalizeFilePath(file_txt
, &normalized_path
));
385 ASSERT_STREQ(file_txt
.value().c_str(), normalized_path
.value().c_str());
387 // Check that the path base_b\to_sub_a\file.txt can be normalized to exclude
388 // the junction to_sub_a.
389 ASSERT_TRUE(NormalizeFilePath(to_sub_a
.Append(FPL("file.txt")),
391 ASSERT_STREQ(file_txt
.value().c_str(), normalized_path
.value().c_str());
393 // Check that the path base_b\to_base_b\to_base_b\to_sub_a\file.txt can be
394 // normalized to exclude junctions to_base_b and to_sub_a .
395 ASSERT_TRUE(NormalizeFilePath(base_b
.Append(FPL("to_base_b"))
396 .Append(FPL("to_base_b"))
397 .Append(FPL("to_sub_a"))
398 .Append(FPL("file.txt")),
400 ASSERT_STREQ(file_txt
.value().c_str(), normalized_path
.value().c_str());
402 // A long enough path will cause NormalizeFilePath() to fail. Make a long
403 // path using to_base_b many times, and check that paths long enough to fail
404 // do not cause a crash.
405 FilePath long_path
= base_b
;
406 const int kLengthLimit
= MAX_PATH
+ 200;
407 while (long_path
.value().length() <= kLengthLimit
) {
408 long_path
= long_path
.Append(FPL("to_base_b"));
410 long_path
= long_path
.Append(FPL("to_sub_a"))
411 .Append(FPL("file.txt"));
413 ASSERT_FALSE(NormalizeFilePath(long_path
, &normalized_path
));
415 // Normalizing the junction to deep.txt should fail, because the expanded
416 // path to deep.txt is longer than MAX_PATH.
417 ASSERT_FALSE(NormalizeFilePath(to_sub_long
.Append(deep_txt
),
420 // Delete the reparse points, and see that NormalizeFilePath() fails
424 ASSERT_FALSE(NormalizeFilePath(to_sub_a
.Append(FPL("file.txt")),
428 TEST_F(FileUtilTest
, DevicePathToDriveLetter
) {
429 // Get a drive letter.
430 std::wstring real_drive_letter
= 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.";
436 // Get the NT style path to that drive.
437 wchar_t device_path
[MAX_PATH
] = {'\0'};
439 ::QueryDosDevice(real_drive_letter
.c_str(), device_path
, MAX_PATH
));
440 FilePath
actual_device_path(device_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
450 FilePath
kRelativePath(FPL("dir1\\dir2\\file.txt"));
451 ASSERT_TRUE(DevicePathToDriveLetterPath(
452 actual_device_path
.Append(kRelativePath
),
454 EXPECT_EQ(FilePath(real_drive_letter
+ L
"\\").Append(kRelativePath
).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
,
472 ASSERT_FALSE(DevicePathToDriveLetterPath(
473 prefix_of_real_device_path
.Append(kRelativePath
),
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
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
,
491 ASSERT_FALSE(DevicePathToDriveLetterPath(
492 real_device_path_plus_numbers
.Append(kRelativePath
),
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());
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 base::FilePermissionRestorer
long_test_dir_restorer(long_test_dir
);
532 ASSERT_TRUE(base::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
560 std::wstring contents
= ReadTextFile(link_from
);
561 EXPECT_EQ(bogus_content
, contents
);
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.";
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.";
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
) {
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
) {
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
];
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.
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
));
743 EXPECT_TRUE(DeleteFile(file_name
, false));
744 EXPECT_FALSE(PathExists(file_name
));
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");
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.
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
));
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.
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());
834 EXPECT_TRUE(DeleteFile(subdir_path
, true));
835 EXPECT_FALSE(PathExists(subdir_path
));
838 #endif // defined(OS_POSIX)
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
));
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
) {
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
));
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
) {
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
) {
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
) {
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
) {
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
) {
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
));
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.
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///"));
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
) {
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
)));
1391 // Files in the temporary directory should not be indexed ever. If this
1392 // assumption change, fix this unit test accordingly.
1393 // FILE_ATTRIBUTE_NOT_CONTENT_INDEXED doesn't exist on XP.
1394 DWORD expected
= read_only
?
1395 ((attrs
& (FILE_ATTRIBUTE_ARCHIVE
| FILE_ATTRIBUTE_DIRECTORY
)) |
1396 FILE_ATTRIBUTE_READONLY
) :
1397 (attrs
& (FILE_ATTRIBUTE_ARCHIVE
| FILE_ATTRIBUTE_DIRECTORY
));
1398 // TODO(ripp@yandex-team.ru): this seems out of place here. If we really think
1399 // it is important to verify that temp files are not indexed there should be
1400 // a dedicated test for that (create a file, inspect the attributes)
1401 if (win::GetVersion() >= win::VERSION_VISTA
)
1402 expected
|= FILE_ATTRIBUTE_NOT_CONTENT_INDEXED
;
1403 attrs
= GetFileAttributes(path
.value().c_str());
1404 ASSERT_EQ(expected
, attrs
);
1406 // On all other platforms, it involves removing/setting the write bit.
1407 mode_t mode
= read_only
? S_IRUSR
: (S_IRUSR
| S_IWUSR
);
1408 EXPECT_TRUE(SetPosixFilePermissions(
1409 path
, DirectoryExists(path
) ? (mode
| S_IXUSR
) : mode
));
1413 bool IsReadOnly(const FilePath
& path
) {
1415 DWORD attrs
= GetFileAttributes(path
.value().c_str());
1416 EXPECT_NE(INVALID_FILE_ATTRIBUTES
, attrs
);
1417 return attrs
& FILE_ATTRIBUTE_READONLY
;
1420 EXPECT_TRUE(GetPosixFilePermissions(path
, &mode
));
1421 return !(mode
& S_IWUSR
);
1425 TEST_F(FileUtilTest
, CopyDirectoryACL
) {
1426 // Create source directories.
1427 FilePath src
= temp_dir_
.path().Append(FILE_PATH_LITERAL("src"));
1428 FilePath src_subdir
= src
.Append(FILE_PATH_LITERAL("subdir"));
1429 CreateDirectory(src_subdir
);
1430 ASSERT_TRUE(PathExists(src_subdir
));
1432 // Create a file under the directory.
1433 FilePath src_file
= src
.Append(FILE_PATH_LITERAL("src.txt"));
1434 CreateTextFile(src_file
, L
"Gooooooooooooooooooooogle");
1435 SetReadOnly(src_file
, true);
1436 ASSERT_TRUE(IsReadOnly(src_file
));
1438 // Make directory read-only.
1439 SetReadOnly(src_subdir
, true);
1440 ASSERT_TRUE(IsReadOnly(src_subdir
));
1442 // Copy the directory recursively.
1443 FilePath dst
= temp_dir_
.path().Append(FILE_PATH_LITERAL("dst"));
1444 FilePath dst_file
= dst
.Append(FILE_PATH_LITERAL("src.txt"));
1445 EXPECT_TRUE(CopyDirectory(src
, dst
, true));
1447 FilePath dst_subdir
= dst
.Append(FILE_PATH_LITERAL("subdir"));
1448 ASSERT_FALSE(IsReadOnly(dst_subdir
));
1449 ASSERT_FALSE(IsReadOnly(dst_file
));
1451 // Give write permissions to allow deletion.
1452 SetReadOnly(src_subdir
, false);
1453 ASSERT_FALSE(IsReadOnly(src_subdir
));
1456 TEST_F(FileUtilTest
, CopyFile
) {
1457 // Create a directory
1458 FilePath dir_name_from
=
1459 temp_dir_
.path().Append(FILE_PATH_LITERAL("Copy_From_Subdir"));
1460 CreateDirectory(dir_name_from
);
1461 ASSERT_TRUE(PathExists(dir_name_from
));
1463 // Create a file under the directory
1464 FilePath file_name_from
=
1465 dir_name_from
.Append(FILE_PATH_LITERAL("Copy_Test_File.txt"));
1466 const std::wstring
file_contents(L
"Gooooooooooooooooooooogle");
1467 CreateTextFile(file_name_from
, file_contents
);
1468 ASSERT_TRUE(PathExists(file_name_from
));
1471 FilePath dest_file
= dir_name_from
.Append(FILE_PATH_LITERAL("DestFile.txt"));
1472 ASSERT_TRUE(CopyFile(file_name_from
, dest_file
));
1474 // Try to copy the file to another location using '..' in the path.
1475 FilePath
dest_file2(dir_name_from
);
1476 dest_file2
= dest_file2
.AppendASCII("..");
1477 dest_file2
= dest_file2
.AppendASCII("DestFile.txt");
1478 ASSERT_FALSE(CopyFile(file_name_from
, dest_file2
));
1480 FilePath
dest_file2_test(dir_name_from
);
1481 dest_file2_test
= dest_file2_test
.DirName();
1482 dest_file2_test
= dest_file2_test
.AppendASCII("DestFile.txt");
1484 // Check expected copy results.
1485 EXPECT_TRUE(PathExists(file_name_from
));
1486 EXPECT_TRUE(PathExists(dest_file
));
1487 const std::wstring read_contents
= ReadTextFile(dest_file
);
1488 EXPECT_EQ(file_contents
, read_contents
);
1489 EXPECT_FALSE(PathExists(dest_file2_test
));
1490 EXPECT_FALSE(PathExists(dest_file2
));
1493 TEST_F(FileUtilTest
, CopyFileACL
) {
1494 // While FileUtilTest.CopyFile asserts the content is correctly copied over,
1495 // this test case asserts the access control bits are meeting expectations in
1497 FilePath src
= temp_dir_
.path().Append(FILE_PATH_LITERAL("src.txt"));
1498 const std::wstring
file_contents(L
"Gooooooooooooooooooooogle");
1499 CreateTextFile(src
, file_contents
);
1501 // Set the source file to read-only.
1502 ASSERT_FALSE(IsReadOnly(src
));
1503 SetReadOnly(src
, true);
1504 ASSERT_TRUE(IsReadOnly(src
));
1507 FilePath dst
= temp_dir_
.path().Append(FILE_PATH_LITERAL("dst.txt"));
1508 ASSERT_TRUE(CopyFile(src
, dst
));
1509 EXPECT_EQ(file_contents
, ReadTextFile(dst
));
1511 ASSERT_FALSE(IsReadOnly(dst
));
1514 // file_util winds up using autoreleased objects on the Mac, so this needs
1515 // to be a PlatformTest.
1516 typedef PlatformTest ReadOnlyFileUtilTest
;
1518 TEST_F(ReadOnlyFileUtilTest
, ContentsEqual
) {
1520 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA
, &data_dir
));
1521 data_dir
= data_dir
.AppendASCII("file_util");
1522 ASSERT_TRUE(PathExists(data_dir
));
1524 FilePath original_file
=
1525 data_dir
.Append(FILE_PATH_LITERAL("original.txt"));
1526 FilePath same_file
=
1527 data_dir
.Append(FILE_PATH_LITERAL("same.txt"));
1528 FilePath same_length_file
=
1529 data_dir
.Append(FILE_PATH_LITERAL("same_length.txt"));
1530 FilePath different_file
=
1531 data_dir
.Append(FILE_PATH_LITERAL("different.txt"));
1532 FilePath different_first_file
=
1533 data_dir
.Append(FILE_PATH_LITERAL("different_first.txt"));
1534 FilePath different_last_file
=
1535 data_dir
.Append(FILE_PATH_LITERAL("different_last.txt"));
1536 FilePath empty1_file
=
1537 data_dir
.Append(FILE_PATH_LITERAL("empty1.txt"));
1538 FilePath empty2_file
=
1539 data_dir
.Append(FILE_PATH_LITERAL("empty2.txt"));
1540 FilePath shortened_file
=
1541 data_dir
.Append(FILE_PATH_LITERAL("shortened.txt"));
1542 FilePath binary_file
=
1543 data_dir
.Append(FILE_PATH_LITERAL("binary_file.bin"));
1544 FilePath binary_file_same
=
1545 data_dir
.Append(FILE_PATH_LITERAL("binary_file_same.bin"));
1546 FilePath binary_file_diff
=
1547 data_dir
.Append(FILE_PATH_LITERAL("binary_file_diff.bin"));
1549 EXPECT_TRUE(ContentsEqual(original_file
, original_file
));
1550 EXPECT_TRUE(ContentsEqual(original_file
, same_file
));
1551 EXPECT_FALSE(ContentsEqual(original_file
, same_length_file
));
1552 EXPECT_FALSE(ContentsEqual(original_file
, different_file
));
1553 EXPECT_FALSE(ContentsEqual(FilePath(FILE_PATH_LITERAL("bogusname")),
1554 FilePath(FILE_PATH_LITERAL("bogusname"))));
1555 EXPECT_FALSE(ContentsEqual(original_file
, different_first_file
));
1556 EXPECT_FALSE(ContentsEqual(original_file
, different_last_file
));
1557 EXPECT_TRUE(ContentsEqual(empty1_file
, empty2_file
));
1558 EXPECT_FALSE(ContentsEqual(original_file
, shortened_file
));
1559 EXPECT_FALSE(ContentsEqual(shortened_file
, original_file
));
1560 EXPECT_TRUE(ContentsEqual(binary_file
, binary_file_same
));
1561 EXPECT_FALSE(ContentsEqual(binary_file
, binary_file_diff
));
1564 TEST_F(ReadOnlyFileUtilTest
, TextContentsEqual
) {
1566 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA
, &data_dir
));
1567 data_dir
= data_dir
.AppendASCII("file_util");
1568 ASSERT_TRUE(PathExists(data_dir
));
1570 FilePath original_file
=
1571 data_dir
.Append(FILE_PATH_LITERAL("original.txt"));
1572 FilePath same_file
=
1573 data_dir
.Append(FILE_PATH_LITERAL("same.txt"));
1574 FilePath crlf_file
=
1575 data_dir
.Append(FILE_PATH_LITERAL("crlf.txt"));
1576 FilePath shortened_file
=
1577 data_dir
.Append(FILE_PATH_LITERAL("shortened.txt"));
1578 FilePath different_file
=
1579 data_dir
.Append(FILE_PATH_LITERAL("different.txt"));
1580 FilePath different_first_file
=
1581 data_dir
.Append(FILE_PATH_LITERAL("different_first.txt"));
1582 FilePath different_last_file
=
1583 data_dir
.Append(FILE_PATH_LITERAL("different_last.txt"));
1584 FilePath first1_file
=
1585 data_dir
.Append(FILE_PATH_LITERAL("first1.txt"));
1586 FilePath first2_file
=
1587 data_dir
.Append(FILE_PATH_LITERAL("first2.txt"));
1588 FilePath empty1_file
=
1589 data_dir
.Append(FILE_PATH_LITERAL("empty1.txt"));
1590 FilePath empty2_file
=
1591 data_dir
.Append(FILE_PATH_LITERAL("empty2.txt"));
1592 FilePath blank_line_file
=
1593 data_dir
.Append(FILE_PATH_LITERAL("blank_line.txt"));
1594 FilePath blank_line_crlf_file
=
1595 data_dir
.Append(FILE_PATH_LITERAL("blank_line_crlf.txt"));
1597 EXPECT_TRUE(TextContentsEqual(original_file
, same_file
));
1598 EXPECT_TRUE(TextContentsEqual(original_file
, crlf_file
));
1599 EXPECT_FALSE(TextContentsEqual(original_file
, shortened_file
));
1600 EXPECT_FALSE(TextContentsEqual(original_file
, different_file
));
1601 EXPECT_FALSE(TextContentsEqual(original_file
, different_first_file
));
1602 EXPECT_FALSE(TextContentsEqual(original_file
, different_last_file
));
1603 EXPECT_FALSE(TextContentsEqual(first1_file
, first2_file
));
1604 EXPECT_TRUE(TextContentsEqual(empty1_file
, empty2_file
));
1605 EXPECT_FALSE(TextContentsEqual(original_file
, empty1_file
));
1606 EXPECT_TRUE(TextContentsEqual(blank_line_file
, blank_line_crlf_file
));
1609 // We don't need equivalent functionality outside of Windows.
1611 TEST_F(FileUtilTest
, CopyAndDeleteDirectoryTest
) {
1612 // Create a directory
1613 FilePath dir_name_from
=
1614 temp_dir_
.path().Append(FILE_PATH_LITERAL("CopyAndDelete_From_Subdir"));
1615 CreateDirectory(dir_name_from
);
1616 ASSERT_TRUE(PathExists(dir_name_from
));
1618 // Create a file under the directory
1619 FilePath file_name_from
=
1620 dir_name_from
.Append(FILE_PATH_LITERAL("CopyAndDelete_Test_File.txt"));
1621 CreateTextFile(file_name_from
, L
"Gooooooooooooooooooooogle");
1622 ASSERT_TRUE(PathExists(file_name_from
));
1624 // Move the directory by using CopyAndDeleteDirectory
1625 FilePath dir_name_to
= temp_dir_
.path().Append(
1626 FILE_PATH_LITERAL("CopyAndDelete_To_Subdir"));
1627 FilePath file_name_to
=
1628 dir_name_to
.Append(FILE_PATH_LITERAL("CopyAndDelete_Test_File.txt"));
1630 ASSERT_FALSE(PathExists(dir_name_to
));
1632 EXPECT_TRUE(internal::CopyAndDeleteDirectory(dir_name_from
,
1635 // Check everything has been moved.
1636 EXPECT_FALSE(PathExists(dir_name_from
));
1637 EXPECT_FALSE(PathExists(file_name_from
));
1638 EXPECT_TRUE(PathExists(dir_name_to
));
1639 EXPECT_TRUE(PathExists(file_name_to
));
1642 TEST_F(FileUtilTest
, GetTempDirTest
) {
1643 static const TCHAR
* kTmpKey
= _T("TMP");
1644 static const TCHAR
* kTmpValues
[] = {
1645 _T(""), _T("C:"), _T("C:\\"), _T("C:\\tmp"), _T("C:\\tmp\\")
1647 // Save the original $TMP.
1648 size_t original_tmp_size
;
1649 TCHAR
* original_tmp
;
1650 ASSERT_EQ(0, ::_tdupenv_s(&original_tmp
, &original_tmp_size
, kTmpKey
));
1651 // original_tmp may be NULL.
1653 for (unsigned int i
= 0; i
< arraysize(kTmpValues
); ++i
) {
1655 ::_tputenv_s(kTmpKey
, kTmpValues
[i
]);
1657 EXPECT_TRUE(path
.IsAbsolute()) << "$TMP=" << kTmpValues
[i
] <<
1658 " result=" << path
.value();
1661 // Restore the original $TMP.
1663 ::_tputenv_s(kTmpKey
, original_tmp
);
1666 ::_tputenv_s(kTmpKey
, _T(""));
1671 TEST_F(FileUtilTest
, CreateTemporaryFileTest
) {
1672 FilePath temp_files
[3];
1673 for (int i
= 0; i
< 3; i
++) {
1674 ASSERT_TRUE(CreateTemporaryFile(&(temp_files
[i
])));
1675 EXPECT_TRUE(PathExists(temp_files
[i
]));
1676 EXPECT_FALSE(DirectoryExists(temp_files
[i
]));
1678 for (int i
= 0; i
< 3; i
++)
1679 EXPECT_FALSE(temp_files
[i
] == temp_files
[(i
+1)%3]);
1680 for (int i
= 0; i
< 3; i
++)
1681 EXPECT_TRUE(DeleteFile(temp_files
[i
], false));
1684 TEST_F(FileUtilTest
, CreateAndOpenTemporaryFileTest
) {
1689 // Create; make sure they are open and exist.
1690 for (i
= 0; i
< 3; ++i
) {
1691 fps
[i
] = CreateAndOpenTemporaryFile(&(names
[i
]));
1692 ASSERT_TRUE(fps
[i
]);
1693 EXPECT_TRUE(PathExists(names
[i
]));
1696 // Make sure all names are unique.
1697 for (i
= 0; i
< 3; ++i
) {
1698 EXPECT_FALSE(names
[i
] == names
[(i
+1)%3]);
1701 // Close and delete.
1702 for (i
= 0; i
< 3; ++i
) {
1703 EXPECT_TRUE(CloseFile(fps
[i
]));
1704 EXPECT_TRUE(DeleteFile(names
[i
], false));
1708 TEST_F(FileUtilTest
, FileToFILE
) {
1710 FILE* stream
= FileToFILE(file
.Pass(), "w");
1711 EXPECT_FALSE(stream
);
1713 FilePath file_name
= temp_dir_
.path().Append(FPL("The file.txt"));
1714 file
= File(file_name
, File::FLAG_CREATE
| File::FLAG_WRITE
);
1715 EXPECT_TRUE(file
.IsValid());
1717 stream
= FileToFILE(file
.Pass(), "w");
1718 EXPECT_TRUE(stream
);
1719 EXPECT_FALSE(file
.IsValid());
1720 EXPECT_TRUE(CloseFile(stream
));
1723 TEST_F(FileUtilTest
, CreateNewTempDirectoryTest
) {
1725 ASSERT_TRUE(CreateNewTempDirectory(FilePath::StringType(), &temp_dir
));
1726 EXPECT_TRUE(PathExists(temp_dir
));
1727 EXPECT_TRUE(DeleteFile(temp_dir
, false));
1730 TEST_F(FileUtilTest
, CreateNewTemporaryDirInDirTest
) {
1732 ASSERT_TRUE(CreateTemporaryDirInDir(
1734 FILE_PATH_LITERAL("CreateNewTemporaryDirInDirTest"),
1736 EXPECT_TRUE(PathExists(new_dir
));
1737 EXPECT_TRUE(temp_dir_
.path().IsParent(new_dir
));
1738 EXPECT_TRUE(DeleteFile(new_dir
, false));
1741 #if defined(OS_POSIX)
1742 TEST_F(FileUtilTest
, GetShmemTempDirTest
) {
1744 EXPECT_TRUE(GetShmemTempDir(false, &dir
));
1745 EXPECT_TRUE(DirectoryExists(dir
));
1749 TEST_F(FileUtilTest
, GetHomeDirTest
) {
1750 #if !defined(OS_ANDROID) // Not implemented on Android.
1751 // We don't actually know what the home directory is supposed to be without
1752 // calling some OS functions which would just duplicate the implementation.
1753 // So here we just test that it returns something "reasonable".
1754 FilePath home
= GetHomeDir();
1755 ASSERT_FALSE(home
.empty());
1756 ASSERT_TRUE(home
.IsAbsolute());
1760 TEST_F(FileUtilTest
, CreateDirectoryTest
) {
1761 FilePath test_root
=
1762 temp_dir_
.path().Append(FILE_PATH_LITERAL("create_directory_test"));
1764 FilePath test_path
=
1765 test_root
.Append(FILE_PATH_LITERAL("dir\\tree\\likely\\doesnt\\exist\\"));
1766 #elif defined(OS_POSIX)
1767 FilePath test_path
=
1768 test_root
.Append(FILE_PATH_LITERAL("dir/tree/likely/doesnt/exist/"));
1771 EXPECT_FALSE(PathExists(test_path
));
1772 EXPECT_TRUE(CreateDirectory(test_path
));
1773 EXPECT_TRUE(PathExists(test_path
));
1774 // CreateDirectory returns true if the DirectoryExists returns true.
1775 EXPECT_TRUE(CreateDirectory(test_path
));
1777 // Doesn't work to create it on top of a non-dir
1778 test_path
= test_path
.Append(FILE_PATH_LITERAL("foobar.txt"));
1779 EXPECT_FALSE(PathExists(test_path
));
1780 CreateTextFile(test_path
, L
"test file");
1781 EXPECT_TRUE(PathExists(test_path
));
1782 EXPECT_FALSE(CreateDirectory(test_path
));
1784 EXPECT_TRUE(DeleteFile(test_root
, true));
1785 EXPECT_FALSE(PathExists(test_root
));
1786 EXPECT_FALSE(PathExists(test_path
));
1788 // Verify assumptions made by the Windows implementation:
1789 // 1. The current directory always exists.
1790 // 2. The root directory always exists.
1791 ASSERT_TRUE(DirectoryExists(FilePath(FilePath::kCurrentDirectory
)));
1792 FilePath top_level
= test_root
;
1793 while (top_level
!= top_level
.DirName()) {
1794 top_level
= top_level
.DirName();
1796 ASSERT_TRUE(DirectoryExists(top_level
));
1798 // Given these assumptions hold, it should be safe to
1799 // test that "creating" these directories succeeds.
1800 EXPECT_TRUE(CreateDirectory(
1801 FilePath(FilePath::kCurrentDirectory
)));
1802 EXPECT_TRUE(CreateDirectory(top_level
));
1805 FilePath
invalid_drive(FILE_PATH_LITERAL("o:\\"));
1806 FilePath invalid_path
=
1807 invalid_drive
.Append(FILE_PATH_LITERAL("some\\inaccessible\\dir"));
1808 if (!PathExists(invalid_drive
)) {
1809 EXPECT_FALSE(CreateDirectory(invalid_path
));
1814 TEST_F(FileUtilTest
, DetectDirectoryTest
) {
1815 // Check a directory
1816 FilePath test_root
=
1817 temp_dir_
.path().Append(FILE_PATH_LITERAL("detect_directory_test"));
1818 EXPECT_FALSE(PathExists(test_root
));
1819 EXPECT_TRUE(CreateDirectory(test_root
));
1820 EXPECT_TRUE(PathExists(test_root
));
1821 EXPECT_TRUE(DirectoryExists(test_root
));
1823 FilePath test_path
=
1824 test_root
.Append(FILE_PATH_LITERAL("foobar.txt"));
1825 EXPECT_FALSE(PathExists(test_path
));
1826 CreateTextFile(test_path
, L
"test file");
1827 EXPECT_TRUE(PathExists(test_path
));
1828 EXPECT_FALSE(DirectoryExists(test_path
));
1829 EXPECT_TRUE(DeleteFile(test_path
, false));
1831 EXPECT_TRUE(DeleteFile(test_root
, true));
1834 TEST_F(FileUtilTest
, FileEnumeratorTest
) {
1835 // Test an empty directory.
1836 FileEnumerator
f0(temp_dir_
.path(), true, FILES_AND_DIRECTORIES
);
1837 EXPECT_EQ(FPL(""), f0
.Next().value());
1838 EXPECT_EQ(FPL(""), f0
.Next().value());
1840 // Test an empty directory, non-recursively, including "..".
1841 FileEnumerator
f0_dotdot(temp_dir_
.path(), false,
1842 FILES_AND_DIRECTORIES
| FileEnumerator::INCLUDE_DOT_DOT
);
1843 EXPECT_EQ(temp_dir_
.path().Append(FPL("..")).value(),
1844 f0_dotdot
.Next().value());
1845 EXPECT_EQ(FPL(""), f0_dotdot
.Next().value());
1847 // create the directories
1848 FilePath dir1
= temp_dir_
.path().Append(FPL("dir1"));
1849 EXPECT_TRUE(CreateDirectory(dir1
));
1850 FilePath dir2
= temp_dir_
.path().Append(FPL("dir2"));
1851 EXPECT_TRUE(CreateDirectory(dir2
));
1852 FilePath dir2inner
= dir2
.Append(FPL("inner"));
1853 EXPECT_TRUE(CreateDirectory(dir2inner
));
1856 FilePath dir2file
= dir2
.Append(FPL("dir2file.txt"));
1857 CreateTextFile(dir2file
, std::wstring());
1858 FilePath dir2innerfile
= dir2inner
.Append(FPL("innerfile.txt"));
1859 CreateTextFile(dir2innerfile
, std::wstring());
1860 FilePath file1
= temp_dir_
.path().Append(FPL("file1.txt"));
1861 CreateTextFile(file1
, std::wstring());
1862 FilePath file2_rel
= dir2
.Append(FilePath::kParentDirectory
)
1863 .Append(FPL("file2.txt"));
1864 CreateTextFile(file2_rel
, std::wstring());
1865 FilePath file2_abs
= temp_dir_
.path().Append(FPL("file2.txt"));
1867 // Only enumerate files.
1868 FileEnumerator
f1(temp_dir_
.path(), true, FileEnumerator::FILES
);
1869 FindResultCollector
c1(f1
);
1870 EXPECT_TRUE(c1
.HasFile(file1
));
1871 EXPECT_TRUE(c1
.HasFile(file2_abs
));
1872 EXPECT_TRUE(c1
.HasFile(dir2file
));
1873 EXPECT_TRUE(c1
.HasFile(dir2innerfile
));
1874 EXPECT_EQ(4, c1
.size());
1876 // Only enumerate directories.
1877 FileEnumerator
f2(temp_dir_
.path(), true, FileEnumerator::DIRECTORIES
);
1878 FindResultCollector
c2(f2
);
1879 EXPECT_TRUE(c2
.HasFile(dir1
));
1880 EXPECT_TRUE(c2
.HasFile(dir2
));
1881 EXPECT_TRUE(c2
.HasFile(dir2inner
));
1882 EXPECT_EQ(3, c2
.size());
1884 // Only enumerate directories non-recursively.
1885 FileEnumerator
f2_non_recursive(
1886 temp_dir_
.path(), false, FileEnumerator::DIRECTORIES
);
1887 FindResultCollector
c2_non_recursive(f2_non_recursive
);
1888 EXPECT_TRUE(c2_non_recursive
.HasFile(dir1
));
1889 EXPECT_TRUE(c2_non_recursive
.HasFile(dir2
));
1890 EXPECT_EQ(2, c2_non_recursive
.size());
1892 // Only enumerate directories, non-recursively, including "..".
1893 FileEnumerator
f2_dotdot(temp_dir_
.path(), false,
1894 FileEnumerator::DIRECTORIES
|
1895 FileEnumerator::INCLUDE_DOT_DOT
);
1896 FindResultCollector
c2_dotdot(f2_dotdot
);
1897 EXPECT_TRUE(c2_dotdot
.HasFile(dir1
));
1898 EXPECT_TRUE(c2_dotdot
.HasFile(dir2
));
1899 EXPECT_TRUE(c2_dotdot
.HasFile(temp_dir_
.path().Append(FPL(".."))));
1900 EXPECT_EQ(3, c2_dotdot
.size());
1902 // Enumerate files and directories.
1903 FileEnumerator
f3(temp_dir_
.path(), true, FILES_AND_DIRECTORIES
);
1904 FindResultCollector
c3(f3
);
1905 EXPECT_TRUE(c3
.HasFile(dir1
));
1906 EXPECT_TRUE(c3
.HasFile(dir2
));
1907 EXPECT_TRUE(c3
.HasFile(file1
));
1908 EXPECT_TRUE(c3
.HasFile(file2_abs
));
1909 EXPECT_TRUE(c3
.HasFile(dir2file
));
1910 EXPECT_TRUE(c3
.HasFile(dir2inner
));
1911 EXPECT_TRUE(c3
.HasFile(dir2innerfile
));
1912 EXPECT_EQ(7, c3
.size());
1914 // Non-recursive operation.
1915 FileEnumerator
f4(temp_dir_
.path(), false, FILES_AND_DIRECTORIES
);
1916 FindResultCollector
c4(f4
);
1917 EXPECT_TRUE(c4
.HasFile(dir2
));
1918 EXPECT_TRUE(c4
.HasFile(dir2
));
1919 EXPECT_TRUE(c4
.HasFile(file1
));
1920 EXPECT_TRUE(c4
.HasFile(file2_abs
));
1921 EXPECT_EQ(4, c4
.size());
1923 // Enumerate with a pattern.
1924 FileEnumerator
f5(temp_dir_
.path(), true, FILES_AND_DIRECTORIES
, FPL("dir*"));
1925 FindResultCollector
c5(f5
);
1926 EXPECT_TRUE(c5
.HasFile(dir1
));
1927 EXPECT_TRUE(c5
.HasFile(dir2
));
1928 EXPECT_TRUE(c5
.HasFile(dir2file
));
1929 EXPECT_TRUE(c5
.HasFile(dir2inner
));
1930 EXPECT_TRUE(c5
.HasFile(dir2innerfile
));
1931 EXPECT_EQ(5, c5
.size());
1935 // Make dir1 point to dir2.
1936 ReparsePoint
reparse_point(dir1
, dir2
);
1937 EXPECT_TRUE(reparse_point
.IsValid());
1939 if ((win::GetVersion() >= win::VERSION_VISTA
)) {
1940 // There can be a delay for the enumeration code to see the change on
1941 // the file system so skip this test for XP.
1942 // Enumerate the reparse point.
1943 FileEnumerator
f6(dir1
, true, FILES_AND_DIRECTORIES
);
1944 FindResultCollector
c6(f6
);
1945 FilePath inner2
= dir1
.Append(FPL("inner"));
1946 EXPECT_TRUE(c6
.HasFile(inner2
));
1947 EXPECT_TRUE(c6
.HasFile(inner2
.Append(FPL("innerfile.txt"))));
1948 EXPECT_TRUE(c6
.HasFile(dir1
.Append(FPL("dir2file.txt"))));
1949 EXPECT_EQ(3, c6
.size());
1952 // No changes for non recursive operation.
1953 FileEnumerator
f7(temp_dir_
.path(), false, FILES_AND_DIRECTORIES
);
1954 FindResultCollector
c7(f7
);
1955 EXPECT_TRUE(c7
.HasFile(dir2
));
1956 EXPECT_TRUE(c7
.HasFile(dir2
));
1957 EXPECT_TRUE(c7
.HasFile(file1
));
1958 EXPECT_TRUE(c7
.HasFile(file2_abs
));
1959 EXPECT_EQ(4, c7
.size());
1961 // Should not enumerate inside dir1 when using recursion.
1962 FileEnumerator
f8(temp_dir_
.path(), true, FILES_AND_DIRECTORIES
);
1963 FindResultCollector
c8(f8
);
1964 EXPECT_TRUE(c8
.HasFile(dir1
));
1965 EXPECT_TRUE(c8
.HasFile(dir2
));
1966 EXPECT_TRUE(c8
.HasFile(file1
));
1967 EXPECT_TRUE(c8
.HasFile(file2_abs
));
1968 EXPECT_TRUE(c8
.HasFile(dir2file
));
1969 EXPECT_TRUE(c8
.HasFile(dir2inner
));
1970 EXPECT_TRUE(c8
.HasFile(dir2innerfile
));
1971 EXPECT_EQ(7, c8
.size());
1975 // Make sure the destructor closes the find handle while in the middle of a
1976 // query to allow TearDown to delete the directory.
1977 FileEnumerator
f9(temp_dir_
.path(), true, FILES_AND_DIRECTORIES
);
1978 EXPECT_FALSE(f9
.Next().value().empty()); // Should have found something
1979 // (we don't care what).
1982 TEST_F(FileUtilTest
, AppendToFile
) {
1984 temp_dir_
.path().Append(FILE_PATH_LITERAL("FilePathTest"));
1986 // Create a fresh, empty copy of this directory.
1987 if (PathExists(data_dir
)) {
1988 ASSERT_TRUE(DeleteFile(data_dir
, true));
1990 ASSERT_TRUE(CreateDirectory(data_dir
));
1992 // Create a fresh, empty copy of this directory.
1993 if (PathExists(data_dir
)) {
1994 ASSERT_TRUE(DeleteFile(data_dir
, true));
1996 ASSERT_TRUE(CreateDirectory(data_dir
));
1997 FilePath
foobar(data_dir
.Append(FILE_PATH_LITERAL("foobar.txt")));
1999 std::string
data("hello");
2000 EXPECT_FALSE(AppendToFile(foobar
, data
.c_str(), data
.size()));
2001 EXPECT_EQ(static_cast<int>(data
.length()),
2002 WriteFile(foobar
, data
.c_str(), data
.length()));
2003 EXPECT_TRUE(AppendToFile(foobar
, data
.c_str(), data
.size()));
2005 const std::wstring read_content
= ReadTextFile(foobar
);
2006 EXPECT_EQ(L
"hellohello", read_content
);
2009 TEST_F(FileUtilTest
, ReadFile
) {
2010 // Create a test file to be read.
2011 const std::string
kTestData("The quick brown fox jumps over the lazy dog.");
2012 FilePath file_path
=
2013 temp_dir_
.path().Append(FILE_PATH_LITERAL("ReadFileTest"));
2015 ASSERT_EQ(static_cast<int>(kTestData
.size()),
2016 WriteFile(file_path
, kTestData
.data(), kTestData
.size()));
2018 // Make buffers with various size.
2019 std::vector
<char> small_buffer(kTestData
.size() / 2);
2020 std::vector
<char> exact_buffer(kTestData
.size());
2021 std::vector
<char> large_buffer(kTestData
.size() * 2);
2023 // Read the file with smaller buffer.
2024 int bytes_read_small
= ReadFile(
2025 file_path
, &small_buffer
[0], static_cast<int>(small_buffer
.size()));
2026 EXPECT_EQ(static_cast<int>(small_buffer
.size()), bytes_read_small
);
2028 std::string(kTestData
.begin(), kTestData
.begin() + small_buffer
.size()),
2029 std::string(small_buffer
.begin(), small_buffer
.end()));
2031 // Read the file with buffer which have exactly same size.
2032 int bytes_read_exact
= ReadFile(
2033 file_path
, &exact_buffer
[0], static_cast<int>(exact_buffer
.size()));
2034 EXPECT_EQ(static_cast<int>(kTestData
.size()), bytes_read_exact
);
2035 EXPECT_EQ(kTestData
, std::string(exact_buffer
.begin(), exact_buffer
.end()));
2037 // Read the file with larger buffer.
2038 int bytes_read_large
= ReadFile(
2039 file_path
, &large_buffer
[0], static_cast<int>(large_buffer
.size()));
2040 EXPECT_EQ(static_cast<int>(kTestData
.size()), bytes_read_large
);
2041 EXPECT_EQ(kTestData
, std::string(large_buffer
.begin(),
2042 large_buffer
.begin() + kTestData
.size()));
2044 // Make sure the return value is -1 if the file doesn't exist.
2045 FilePath file_path_not_exist
=
2046 temp_dir_
.path().Append(FILE_PATH_LITERAL("ReadFileNotExistTest"));
2048 ReadFile(file_path_not_exist
,
2050 static_cast<int>(exact_buffer
.size())));
2053 TEST_F(FileUtilTest
, ReadFileToString
) {
2054 const char kTestData
[] = "0123";
2057 FilePath file_path
=
2058 temp_dir_
.path().Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
2059 FilePath file_path_dangerous
=
2060 temp_dir_
.path().Append(FILE_PATH_LITERAL("..")).
2061 Append(temp_dir_
.path().BaseName()).
2062 Append(FILE_PATH_LITERAL("ReadFileToStringTest"));
2064 // Create test file.
2065 ASSERT_EQ(4, WriteFile(file_path
, kTestData
, 4));
2067 EXPECT_TRUE(ReadFileToString(file_path
, &data
));
2068 EXPECT_EQ(kTestData
, data
);
2071 EXPECT_FALSE(ReadFileToString(file_path
, &data
, 0));
2072 EXPECT_EQ(0u, data
.length());
2075 EXPECT_FALSE(ReadFileToString(file_path
, &data
, 2));
2076 EXPECT_EQ("01", data
);
2079 EXPECT_FALSE(ReadFileToString(file_path
, &data
, 3));
2080 EXPECT_EQ("012", data
);
2083 EXPECT_TRUE(ReadFileToString(file_path
, &data
, 4));
2084 EXPECT_EQ("0123", data
);
2087 EXPECT_TRUE(ReadFileToString(file_path
, &data
, 6));
2088 EXPECT_EQ("0123", data
);
2090 EXPECT_TRUE(ReadFileToString(file_path
, NULL
, 6));
2092 EXPECT_TRUE(ReadFileToString(file_path
, NULL
));
2095 EXPECT_FALSE(ReadFileToString(file_path_dangerous
, &data
));
2096 EXPECT_EQ(0u, data
.length());
2098 // Delete test file.
2099 EXPECT_TRUE(base::DeleteFile(file_path
, false));
2102 EXPECT_FALSE(ReadFileToString(file_path
, &data
));
2103 EXPECT_EQ(0u, data
.length());
2106 EXPECT_FALSE(ReadFileToString(file_path
, &data
, 6));
2107 EXPECT_EQ(0u, data
.length());
2110 TEST_F(FileUtilTest
, TouchFile
) {
2112 temp_dir_
.path().Append(FILE_PATH_LITERAL("FilePathTest"));
2114 // Create a fresh, empty copy of this directory.
2115 if (PathExists(data_dir
)) {
2116 ASSERT_TRUE(DeleteFile(data_dir
, true));
2118 ASSERT_TRUE(CreateDirectory(data_dir
));
2120 FilePath
foobar(data_dir
.Append(FILE_PATH_LITERAL("foobar.txt")));
2121 std::string
data("hello");
2122 ASSERT_TRUE(WriteFile(foobar
, data
.c_str(), data
.length()));
2125 // This timestamp is divisible by one day (in local timezone),
2126 // to make it work on FAT too.
2127 ASSERT_TRUE(Time::FromString("Wed, 16 Nov 1994, 00:00:00",
2130 Time modification_time
;
2131 // Note that this timestamp is divisible by two (seconds) - FAT stores
2132 // modification times with 2s resolution.
2133 ASSERT_TRUE(Time::FromString("Tue, 15 Nov 1994, 12:45:26 GMT",
2134 &modification_time
));
2136 ASSERT_TRUE(TouchFile(foobar
, access_time
, modification_time
));
2137 File::Info file_info
;
2138 ASSERT_TRUE(GetFileInfo(foobar
, &file_info
));
2139 EXPECT_EQ(access_time
.ToInternalValue(),
2140 file_info
.last_accessed
.ToInternalValue());
2141 EXPECT_EQ(modification_time
.ToInternalValue(),
2142 file_info
.last_modified
.ToInternalValue());
2145 TEST_F(FileUtilTest
, IsDirectoryEmpty
) {
2146 FilePath empty_dir
= temp_dir_
.path().Append(FILE_PATH_LITERAL("EmptyDir"));
2148 ASSERT_FALSE(PathExists(empty_dir
));
2150 ASSERT_TRUE(CreateDirectory(empty_dir
));
2152 EXPECT_TRUE(IsDirectoryEmpty(empty_dir
));
2154 FilePath
foo(empty_dir
.Append(FILE_PATH_LITERAL("foo.txt")));
2155 std::string
bar("baz");
2156 ASSERT_TRUE(WriteFile(foo
, bar
.c_str(), bar
.length()));
2158 EXPECT_FALSE(IsDirectoryEmpty(empty_dir
));
2161 #if defined(OS_POSIX)
2163 // Testing VerifyPathControlledByAdmin() is hard, because there is no
2164 // way a test can make a file owned by root, or change file paths
2165 // at the root of the file system. VerifyPathControlledByAdmin()
2166 // is implemented as a call to VerifyPathControlledByUser, which gives
2167 // us the ability to test with paths under the test's temp directory,
2168 // using a user id we control.
2169 // Pull tests of VerifyPathControlledByUserTest() into a separate test class
2170 // with a common SetUp() method.
2171 class VerifyPathControlledByUserTest
: public FileUtilTest
{
2173 void SetUp() override
{
2174 FileUtilTest::SetUp();
2176 // Create a basic structure used by each test.
2181 base_dir_
= temp_dir_
.path().AppendASCII("base_dir");
2182 ASSERT_TRUE(CreateDirectory(base_dir_
));
2184 sub_dir_
= base_dir_
.AppendASCII("sub_dir");
2185 ASSERT_TRUE(CreateDirectory(sub_dir_
));
2187 text_file_
= sub_dir_
.AppendASCII("file.txt");
2188 CreateTextFile(text_file_
, L
"This text file has some text in it.");
2190 // Get the user and group files are created with from |base_dir_|.
2191 struct stat stat_buf
;
2192 ASSERT_EQ(0, stat(base_dir_
.value().c_str(), &stat_buf
));
2193 uid_
= stat_buf
.st_uid
;
2194 ok_gids_
.insert(stat_buf
.st_gid
);
2195 bad_gids_
.insert(stat_buf
.st_gid
+ 1);
2197 ASSERT_EQ(uid_
, getuid()); // This process should be the owner.
2199 // To ensure that umask settings do not cause the initial state
2200 // of permissions to be different from what we expect, explicitly
2201 // set permissions on the directories we create.
2202 // Make all files and directories non-world-writable.
2204 // Users and group can read, write, traverse
2205 int enabled_permissions
=
2206 FILE_PERMISSION_USER_MASK
| FILE_PERMISSION_GROUP_MASK
;
2207 // Other users can't read, write, traverse
2208 int disabled_permissions
= FILE_PERMISSION_OTHERS_MASK
;
2210 ASSERT_NO_FATAL_FAILURE(
2211 ChangePosixFilePermissions(
2212 base_dir_
, enabled_permissions
, disabled_permissions
));
2213 ASSERT_NO_FATAL_FAILURE(
2214 ChangePosixFilePermissions(
2215 sub_dir_
, enabled_permissions
, disabled_permissions
));
2220 FilePath text_file_
;
2223 std::set
<gid_t
> ok_gids_
;
2224 std::set
<gid_t
> bad_gids_
;
2227 TEST_F(VerifyPathControlledByUserTest
, BadPaths
) {
2228 // File does not exist.
2229 FilePath does_not_exist
= base_dir_
.AppendASCII("does")
2231 .AppendASCII("exist");
2233 base::VerifyPathControlledByUser(
2234 base_dir_
, does_not_exist
, uid_
, ok_gids_
));
2236 // |base| not a subpath of |path|.
2238 base::VerifyPathControlledByUser(
2239 sub_dir_
, base_dir_
, uid_
, ok_gids_
));
2241 // An empty base path will fail to be a prefix for any path.
2244 base::VerifyPathControlledByUser(
2245 empty
, base_dir_
, uid_
, ok_gids_
));
2247 // Finding that a bad call fails proves nothing unless a good call succeeds.
2249 base::VerifyPathControlledByUser(
2250 base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2253 TEST_F(VerifyPathControlledByUserTest
, Symlinks
) {
2254 // Symlinks in the path should cause failure.
2256 // Symlink to the file at the end of the path.
2257 FilePath file_link
= base_dir_
.AppendASCII("file_link");
2258 ASSERT_TRUE(CreateSymbolicLink(text_file_
, file_link
))
2259 << "Failed to create symlink.";
2262 base::VerifyPathControlledByUser(
2263 base_dir_
, file_link
, uid_
, ok_gids_
));
2265 base::VerifyPathControlledByUser(
2266 file_link
, file_link
, uid_
, ok_gids_
));
2268 // Symlink from one directory to another within the path.
2269 FilePath link_to_sub_dir
= base_dir_
.AppendASCII("link_to_sub_dir");
2270 ASSERT_TRUE(CreateSymbolicLink(sub_dir_
, link_to_sub_dir
))
2271 << "Failed to create symlink.";
2273 FilePath file_path_with_link
= link_to_sub_dir
.AppendASCII("file.txt");
2274 ASSERT_TRUE(PathExists(file_path_with_link
));
2277 base::VerifyPathControlledByUser(
2278 base_dir_
, file_path_with_link
, uid_
, ok_gids_
));
2281 base::VerifyPathControlledByUser(
2282 link_to_sub_dir
, file_path_with_link
, uid_
, ok_gids_
));
2284 // Symlinks in parents of base path are allowed.
2286 base::VerifyPathControlledByUser(
2287 file_path_with_link
, file_path_with_link
, uid_
, ok_gids_
));
2290 TEST_F(VerifyPathControlledByUserTest
, OwnershipChecks
) {
2291 // Get a uid that is not the uid of files we create.
2292 uid_t bad_uid
= uid_
+ 1;
2294 // Make all files and directories non-world-writable.
2295 ASSERT_NO_FATAL_FAILURE(
2296 ChangePosixFilePermissions(base_dir_
, 0u, S_IWOTH
));
2297 ASSERT_NO_FATAL_FAILURE(
2298 ChangePosixFilePermissions(sub_dir_
, 0u, S_IWOTH
));
2299 ASSERT_NO_FATAL_FAILURE(
2300 ChangePosixFilePermissions(text_file_
, 0u, S_IWOTH
));
2302 // We control these paths.
2304 base::VerifyPathControlledByUser(
2305 base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2307 base::VerifyPathControlledByUser(
2308 base_dir_
, text_file_
, uid_
, ok_gids_
));
2310 base::VerifyPathControlledByUser(
2311 sub_dir_
, text_file_
, uid_
, ok_gids_
));
2313 // Another user does not control these paths.
2315 base::VerifyPathControlledByUser(
2316 base_dir_
, sub_dir_
, bad_uid
, ok_gids_
));
2318 base::VerifyPathControlledByUser(
2319 base_dir_
, text_file_
, bad_uid
, ok_gids_
));
2321 base::VerifyPathControlledByUser(
2322 sub_dir_
, text_file_
, bad_uid
, ok_gids_
));
2324 // Another group does not control the paths.
2326 base::VerifyPathControlledByUser(
2327 base_dir_
, sub_dir_
, uid_
, bad_gids_
));
2329 base::VerifyPathControlledByUser(
2330 base_dir_
, text_file_
, uid_
, bad_gids_
));
2332 base::VerifyPathControlledByUser(
2333 sub_dir_
, text_file_
, uid_
, bad_gids_
));
2336 TEST_F(VerifyPathControlledByUserTest
, GroupWriteTest
) {
2337 // Make all files and directories writable only by their owner.
2338 ASSERT_NO_FATAL_FAILURE(
2339 ChangePosixFilePermissions(base_dir_
, 0u, S_IWOTH
|S_IWGRP
));
2340 ASSERT_NO_FATAL_FAILURE(
2341 ChangePosixFilePermissions(sub_dir_
, 0u, S_IWOTH
|S_IWGRP
));
2342 ASSERT_NO_FATAL_FAILURE(
2343 ChangePosixFilePermissions(text_file_
, 0u, S_IWOTH
|S_IWGRP
));
2345 // Any group is okay because the path is not group-writable.
2347 base::VerifyPathControlledByUser(
2348 base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2350 base::VerifyPathControlledByUser(
2351 base_dir_
, text_file_
, uid_
, ok_gids_
));
2353 base::VerifyPathControlledByUser(
2354 sub_dir_
, text_file_
, uid_
, ok_gids_
));
2357 base::VerifyPathControlledByUser(
2358 base_dir_
, sub_dir_
, uid_
, bad_gids_
));
2360 base::VerifyPathControlledByUser(
2361 base_dir_
, text_file_
, uid_
, bad_gids_
));
2363 base::VerifyPathControlledByUser(
2364 sub_dir_
, text_file_
, uid_
, bad_gids_
));
2366 // No group is okay, because we don't check the group
2367 // if no group can write.
2368 std::set
<gid_t
> no_gids
; // Empty set of gids.
2370 base::VerifyPathControlledByUser(
2371 base_dir_
, sub_dir_
, uid_
, no_gids
));
2373 base::VerifyPathControlledByUser(
2374 base_dir_
, text_file_
, uid_
, no_gids
));
2376 base::VerifyPathControlledByUser(
2377 sub_dir_
, text_file_
, uid_
, no_gids
));
2380 // Make all files and directories writable by their group.
2381 ASSERT_NO_FATAL_FAILURE(
2382 ChangePosixFilePermissions(base_dir_
, S_IWGRP
, 0u));
2383 ASSERT_NO_FATAL_FAILURE(
2384 ChangePosixFilePermissions(sub_dir_
, S_IWGRP
, 0u));
2385 ASSERT_NO_FATAL_FAILURE(
2386 ChangePosixFilePermissions(text_file_
, S_IWGRP
, 0u));
2388 // Now |ok_gids_| works, but |bad_gids_| fails.
2390 base::VerifyPathControlledByUser(
2391 base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2393 base::VerifyPathControlledByUser(
2394 base_dir_
, text_file_
, uid_
, ok_gids_
));
2396 base::VerifyPathControlledByUser(
2397 sub_dir_
, text_file_
, uid_
, ok_gids_
));
2400 base::VerifyPathControlledByUser(
2401 base_dir_
, sub_dir_
, uid_
, bad_gids_
));
2403 base::VerifyPathControlledByUser(
2404 base_dir_
, text_file_
, uid_
, bad_gids_
));
2406 base::VerifyPathControlledByUser(
2407 sub_dir_
, text_file_
, uid_
, bad_gids_
));
2409 // Because any group in the group set is allowed,
2410 // the union of good and bad gids passes.
2412 std::set
<gid_t
> multiple_gids
;
2414 ok_gids_
.begin(), ok_gids_
.end(),
2415 bad_gids_
.begin(), bad_gids_
.end(),
2416 std::inserter(multiple_gids
, multiple_gids
.begin()));
2419 base::VerifyPathControlledByUser(
2420 base_dir_
, sub_dir_
, uid_
, multiple_gids
));
2422 base::VerifyPathControlledByUser(
2423 base_dir_
, text_file_
, uid_
, multiple_gids
));
2425 base::VerifyPathControlledByUser(
2426 sub_dir_
, text_file_
, uid_
, multiple_gids
));
2429 TEST_F(VerifyPathControlledByUserTest
, WriteBitChecks
) {
2430 // Make all files and directories non-world-writable.
2431 ASSERT_NO_FATAL_FAILURE(
2432 ChangePosixFilePermissions(base_dir_
, 0u, S_IWOTH
));
2433 ASSERT_NO_FATAL_FAILURE(
2434 ChangePosixFilePermissions(sub_dir_
, 0u, S_IWOTH
));
2435 ASSERT_NO_FATAL_FAILURE(
2436 ChangePosixFilePermissions(text_file_
, 0u, S_IWOTH
));
2438 // Initialy, we control all parts of the path.
2440 base::VerifyPathControlledByUser(
2441 base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2443 base::VerifyPathControlledByUser(
2444 base_dir_
, text_file_
, uid_
, ok_gids_
));
2446 base::VerifyPathControlledByUser(
2447 sub_dir_
, text_file_
, uid_
, ok_gids_
));
2449 // Make base_dir_ world-writable.
2450 ASSERT_NO_FATAL_FAILURE(
2451 ChangePosixFilePermissions(base_dir_
, S_IWOTH
, 0u));
2453 base::VerifyPathControlledByUser(
2454 base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2456 base::VerifyPathControlledByUser(
2457 base_dir_
, text_file_
, uid_
, ok_gids_
));
2459 base::VerifyPathControlledByUser(
2460 sub_dir_
, text_file_
, uid_
, ok_gids_
));
2462 // Make sub_dir_ world writable.
2463 ASSERT_NO_FATAL_FAILURE(
2464 ChangePosixFilePermissions(sub_dir_
, S_IWOTH
, 0u));
2466 base::VerifyPathControlledByUser(
2467 base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2469 base::VerifyPathControlledByUser(
2470 base_dir_
, text_file_
, uid_
, ok_gids_
));
2472 base::VerifyPathControlledByUser(
2473 sub_dir_
, text_file_
, uid_
, ok_gids_
));
2475 // Make text_file_ world writable.
2476 ASSERT_NO_FATAL_FAILURE(
2477 ChangePosixFilePermissions(text_file_
, S_IWOTH
, 0u));
2479 base::VerifyPathControlledByUser(
2480 base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2482 base::VerifyPathControlledByUser(
2483 base_dir_
, text_file_
, uid_
, ok_gids_
));
2485 base::VerifyPathControlledByUser(
2486 sub_dir_
, text_file_
, uid_
, ok_gids_
));
2488 // Make sub_dir_ non-world writable.
2489 ASSERT_NO_FATAL_FAILURE(
2490 ChangePosixFilePermissions(sub_dir_
, 0u, S_IWOTH
));
2492 base::VerifyPathControlledByUser(
2493 base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2495 base::VerifyPathControlledByUser(
2496 base_dir_
, text_file_
, uid_
, ok_gids_
));
2498 base::VerifyPathControlledByUser(
2499 sub_dir_
, text_file_
, uid_
, ok_gids_
));
2501 // Make base_dir_ non-world-writable.
2502 ASSERT_NO_FATAL_FAILURE(
2503 ChangePosixFilePermissions(base_dir_
, 0u, S_IWOTH
));
2505 base::VerifyPathControlledByUser(
2506 base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2508 base::VerifyPathControlledByUser(
2509 base_dir_
, text_file_
, uid_
, ok_gids_
));
2511 base::VerifyPathControlledByUser(
2512 sub_dir_
, text_file_
, uid_
, ok_gids_
));
2514 // Back to the initial state: Nothing is writable, so every path
2516 ASSERT_NO_FATAL_FAILURE(
2517 ChangePosixFilePermissions(text_file_
, 0u, S_IWOTH
));
2519 base::VerifyPathControlledByUser(
2520 base_dir_
, sub_dir_
, uid_
, ok_gids_
));
2522 base::VerifyPathControlledByUser(
2523 base_dir_
, text_file_
, uid_
, ok_gids_
));
2525 base::VerifyPathControlledByUser(
2526 sub_dir_
, text_file_
, uid_
, ok_gids_
));
2529 #if defined(OS_ANDROID)
2530 TEST_F(FileUtilTest
, ValidContentUriTest
) {
2531 // Get the test image path.
2533 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA
, &data_dir
));
2534 data_dir
= data_dir
.AppendASCII("file_util");
2535 ASSERT_TRUE(PathExists(data_dir
));
2536 FilePath image_file
= data_dir
.Append(FILE_PATH_LITERAL("red.png"));
2538 GetFileSize(image_file
, &image_size
);
2539 EXPECT_LT(0, image_size
);
2541 // Insert the image into MediaStore. MediaStore will do some conversions, and
2542 // return the content URI.
2543 FilePath path
= base::InsertImageIntoMediaStore(image_file
);
2544 EXPECT_TRUE(path
.IsContentUri());
2545 EXPECT_TRUE(PathExists(path
));
2546 // The file size may not equal to the input image as MediaStore may convert
2548 int64 content_uri_size
;
2549 GetFileSize(path
, &content_uri_size
);
2550 EXPECT_EQ(image_size
, content_uri_size
);
2552 // We should be able to read the file.
2553 char* buffer
= new char[image_size
];
2554 File file
= OpenContentUriForRead(path
);
2555 EXPECT_TRUE(file
.IsValid());
2556 EXPECT_TRUE(file
.ReadAtCurrentPos(buffer
, image_size
));
2560 TEST_F(FileUtilTest
, NonExistentContentUriTest
) {
2561 FilePath
path("content://foo.bar");
2562 EXPECT_TRUE(path
.IsContentUri());
2563 EXPECT_FALSE(PathExists(path
));
2564 // Size should be smaller than 0.
2566 EXPECT_FALSE(GetFileSize(path
, &size
));
2568 // We should not be able to read the file.
2569 File file
= OpenContentUriForRead(path
);
2570 EXPECT_FALSE(file
.IsValid());
2574 TEST(ScopedFD
, ScopedFDDoesClose
) {
2577 ASSERT_EQ(0, pipe(fds
));
2578 const int write_end
= fds
[1];
2579 base::ScopedFD
read_end_closer(fds
[0]);
2581 base::ScopedFD
write_end_closer(fds
[1]);
2583 // This is the only thread. This file descriptor should no longer be valid.
2584 int ret
= close(write_end
);
2586 EXPECT_EQ(EBADF
, errno
);
2587 // Make sure read(2) won't block.
2588 ASSERT_EQ(0, fcntl(fds
[0], F_SETFL
, O_NONBLOCK
));
2589 // Reading the pipe should EOF.
2590 EXPECT_EQ(0, read(fds
[0], &c
, 1));
2593 #if defined(GTEST_HAS_DEATH_TEST)
2594 void CloseWithScopedFD(int fd
) {
2595 base::ScopedFD
fd_closer(fd
);
2599 TEST(ScopedFD
, ScopedFDCrashesOnCloseFailure
) {
2601 ASSERT_EQ(0, pipe(fds
));
2602 base::ScopedFD
read_end_closer(fds
[0]);
2603 EXPECT_EQ(0, IGNORE_EINTR(close(fds
[1])));
2604 #if defined(GTEST_HAS_DEATH_TEST)
2605 // This is the only thread. This file descriptor should no longer be valid.
2606 // Trying to close it should crash. This is important for security.
2607 EXPECT_DEATH(CloseWithScopedFD(fds
[1]), "");
2611 #endif // defined(OS_POSIX)