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