1 // Copyright 2022 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/test/test_file_util.h"
6
7 #include <windows.h>
8
9 #include <string>
10
11 #include "base/files/file_path.h"
12 #include "base/files/file_util.h"
13 #include "base/files/scoped_temp_dir.h"
14 #include "base/win/scoped_handle.h"
15 #include "testing/gmock/include/gmock/gmock.h"
16 #include "testing/gtest/include/gtest/gtest.h"
17
18 namespace base {
19
20 namespace {
21
22 class ScopedFileForTest {
23 public:
ScopedFileForTest(const FilePath & filename)24 ScopedFileForTest(const FilePath& filename)
25 : long_path_(L"\\\\?\\" + filename.value()) {
26 win::ScopedHandle handle(::CreateFile(long_path_.c_str(), GENERIC_WRITE, 0,
27 nullptr, CREATE_NEW,
28 FILE_ATTRIBUTE_NORMAL, nullptr));
29
30 valid_ = handle.is_valid();
31 }
32
33 ScopedFileForTest(ScopedFileForTest&&) = delete;
34 ScopedFileForTest& operator=(ScopedFileForTest&&) = delete;
35
IsValid() const36 bool IsValid() const { return valid_; }
37
~ScopedFileForTest()38 ~ScopedFileForTest() {
39 if (valid_)
40 ::DeleteFile(long_path_.c_str());
41 }
42
43 private:
44 FilePath::StringType long_path_;
45 bool valid_;
46 };
47
48 } // namespace
49
TEST(TestFileUtil,EvictNonExistingFile)50 TEST(TestFileUtil, EvictNonExistingFile) {
51 ScopedTempDir temp_dir;
52 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
53
54 FilePath path = temp_dir.GetPath().Append(FilePath(L"non_existing"));
55
56 ASSERT_FALSE(EvictFileFromSystemCache(path));
57 }
58
TEST(TestFileUtil,EvictFileWithShortName)59 TEST(TestFileUtil, EvictFileWithShortName) {
60 ScopedTempDir temp_dir;
61 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
62
63 FilePath temp_file = temp_dir.GetPath().Append(FilePath(L"file_for_evict"));
64 ASSERT_TRUE(temp_file.value().length() < MAX_PATH);
65 ScopedFileForTest file(temp_file);
66 ASSERT_TRUE(file.IsValid());
67
68 ASSERT_TRUE(EvictFileFromSystemCache(temp_file));
69 }
70
TEST(TestFileUtil,EvictFileWithLongName)71 TEST(TestFileUtil, EvictFileWithLongName) {
72 ScopedTempDir temp_dir;
73 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
74
75 // Create subdirectory with long name.
76 FilePath subdir =
77 temp_dir.GetPath().Append(FilePath(std::wstring(100, L'a')));
78 ASSERT_TRUE(subdir.value().length() < MAX_PATH);
79 ASSERT_TRUE(CreateDirectory(subdir));
80
81 // Create file with long name in subdirectory.
82 FilePath temp_file = subdir.Append(FilePath(std::wstring(200, L'b')));
83 ASSERT_TRUE(temp_file.value().length() > MAX_PATH);
84 ScopedFileForTest file(temp_file);
85 ASSERT_TRUE(file.IsValid());
86
87 ASSERT_TRUE(EvictFileFromSystemCache(temp_file));
88 }
89
TEST(TestFileUtil,GetTempDirForTesting)90 TEST(TestFileUtil, GetTempDirForTesting) {
91 ASSERT_FALSE(GetTempDirForTesting().value().empty());
92 }
93
94 } // namespace base
95