File: trash_auto_cleanup_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (288 lines) | stat: -rw-r--r-- 12,319 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/file_manager/trash_auto_cleanup.h"

#include <vector>

#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/i18n/time_formatting.h"
#include "base/rand_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/mock_callback.h"
#include "base/test/test_future.h"
#include "chrome/browser/ash/file_manager/path_util.h"
#include "chrome/browser/ash/file_manager/trash_io_task.h"
#include "chrome/browser/ash/file_manager/trash_unittest_base.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/test/browser_task_environment.h"
#include "storage/browser/file_system/external_mount_points.h"
#include "storage/browser/quota/quota_manager_proxy.h"
#include "storage/browser/test/test_file_system_context.h"
#include "testing/gmock/include/gmock/gmock.h"

namespace file_manager::trash {

inline constexpr size_t kTestFileSize = 32;

class TrashAutoCleanupTest : public file_manager::io_task::TrashBaseTest {
 public:
  TrashAutoCleanupTest() = default;

  TrashAutoCleanupTest(const TrashAutoCleanupTest&) = delete;
  TrashAutoCleanupTest& operator=(const TrashAutoCleanupTest&) = delete;

  void SetUp() override {
    file_manager::io_task::TrashBaseTest::SetUp();
    trash_auto_cleanup_ = base::WrapUnique(new TrashAutoCleanup(profile()));
  }

  void TearDown() override {
    trash_auto_cleanup_.reset();
    file_manager::io_task::TrashBaseTest::TearDown();
  }

  void SetupFileTrashedFromDownloads(const std::string& file_name) {
    // Create file in Downloads.
    const base::FilePath file_path = downloads_dir_.Append(file_name);
    ASSERT_TRUE(
        base::WriteFile(file_path, base::RandBytesAsString(kTestFileSize)));

    // Create the FileSystemURL for the file to trash.
    std::string relative_path = file_path.value();
    EXPECT_TRUE(file_manager::util::ReplacePrefix(
        &relative_path, temp_dir_.GetPath().AsEndingWithSeparator().value(),
        ""));
    std::vector<storage::FileSystemURL> source_urls = {
        file_system_context_->CreateCrackedFileSystemURL(
            kTestStorageKey, storage::kFileSystemTypeTest,
            base::FilePath::FromUTF8Unsafe(relative_path)),
    };

    // Trash the file.
    base::RunLoop run_loop;
    base::MockRepeatingCallback<void(const io_task::ProgressStatus&)>
        progress_callback;
    base::MockOnceCallback<void(io_task::ProgressStatus)> complete_callback;
    EXPECT_CALL(complete_callback,
                Run(::testing::Field(&io_task::ProgressStatus::state,
                                     io_task::State::kSuccess)))
        .WillOnce(base::test::RunClosure(run_loop.QuitClosure()));

    io_task::TrashIOTask task(source_urls, profile(), file_system_context_,
                              temp_dir_.GetPath());
    task.Execute(progress_callback.Get(), complete_callback.Get());
    run_loop.Run();

    // Check that the file has been trashed.
    const base::FilePath trashed_file_path = GetTrashedFilePath(file_name);
    const base::FilePath info_file_path = GetInfoFilePath(file_name);
    ASSERT_FALSE(base::PathExists(file_path));
    ASSERT_TRUE(base::PathExists(trashed_file_path));
    ASSERT_TRUE(base::PathExists(info_file_path));
    // Override last_modified time of the trashinfo file to match the task
    // environment's mocked clock.
    base::Time now = base::Time::Now();
    base::TouchFile(info_file_path, now, now);
  }

  void CheckFileExistsInTrash(const std::string& file_name, bool should_exist) {
    ASSERT_EQ(base::PathExists(GetInfoFilePath(file_name)), should_exist);
    ASSERT_EQ(base::PathExists(GetTrashedFilePath(file_name)), should_exist);
  }

  void SetCleanupDoneCallbackForTest(
      base::OnceCallback<void(AutoCleanupResult result)> callback) {
    trash_auto_cleanup_->SetCleanupDoneCallbackForTest(std::move(callback));
  }

  void StartCleanup() { trash_auto_cleanup_->StartCleanup(); }

  void InitAutoCleanup() { trash_auto_cleanup_->Init(); }

  std::string GenerateTrashInfoContents(const base::Time& deletion_time) {
    return base::StrCat(
        {"[Trash Info]\nPath=", "/Downloads/bar/", "original_file.txt",
         "\nDeletionDate=", base::TimeFormatAsIso8601(deletion_time)});
  }

  base::FilePath GetInfoFilePath(const std::string& file_name) {
    return downloads_dir_.Append(trash::kTrashFolderName)
        .Append(trash::kInfoFolderName)
        .Append(base::StrCat({file_name, ".trashinfo"}));
  }

  base::FilePath GetTrashedFilePath(const std::string& file_name) {
    return downloads_dir_.Append(trash::kTrashFolderName)
        .Append(trash::kFilesFolderName)
        .Append(file_name);
  }

  Profile* profile() const { return profile_.get(); }

  content::BrowserTaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};
  std::unique_ptr<TrashAutoCleanup> trash_auto_cleanup_;
};

TEST_F(TrashAutoCleanupTest, CleanupIteration) {
  EnsureTrashDirectorySetup(downloads_dir_);

  // Setup files in trash directory.
  const std::string first_file_name = "first_file.txt";
  const std::string second_file_name = "second_file.txt";

  // Setup trashed files. The first file is trashed at T = 0, the second file is
  // trashed at T = 1 day.
  SetupFileTrashedFromDownloads(first_file_name);
  task_environment_.FastForwardBy(base::Days(1));
  SetupFileTrashedFromDownloads(second_file_name);

  // At T = 29 days, no file should be removed.
  task_environment_.FastForwardBy(base::Days(28));
  // Start auto cleanup.
  base::test::TestFuture<AutoCleanupResult> future;
  SetCleanupDoneCallbackForTest(future.GetCallback<AutoCleanupResult>());
  StartCleanup();
  ASSERT_TRUE(future.Wait());
  // Check that no file has been removed.
  ASSERT_EQ(future.Take(), AutoCleanupResult::kNoOldFilesToCleanup);
  CheckFileExistsInTrash(first_file_name, /*should_exist=*/true);
  CheckFileExistsInTrash(second_file_name, /*should_exist=*/true);

  // At T = 30 days, only the first file should be removed.
  task_environment_.FastForwardBy(base::Days(1));
  // Start auto cleanup.
  SetCleanupDoneCallbackForTest(future.GetCallback<AutoCleanupResult>());
  StartCleanup();
  ASSERT_TRUE(future.Wait());
  // Check that the first file has been removed.
  ASSERT_EQ(future.Take(), AutoCleanupResult::kCleanupSuccessful);
  CheckFileExistsInTrash(first_file_name, /*should_exist=*/false);
  CheckFileExistsInTrash(second_file_name, /*should_exist=*/true);

  // At T = 31 days, the second file should also be removed.
  task_environment_.FastForwardBy(base::Days(1));
  // Start auto cleanup.
  SetCleanupDoneCallbackForTest(future.GetCallback<AutoCleanupResult>());
  StartCleanup();
  ASSERT_TRUE(future.Wait());
  // Check that the second file has been removed.
  ASSERT_EQ(future.Take(), AutoCleanupResult::kCleanupSuccessful);
  CheckFileExistsInTrash(first_file_name, /*should_exist=*/false);
  CheckFileExistsInTrash(second_file_name, /*should_exist=*/false);
}

TEST_F(TrashAutoCleanupTest, PeriodicCleanup) {
  // Setup files in trash directory.
  const std::string first_file_name = "first_file.txt";
  const std::string second_file_name = "second_file.txt";

  // Setup trashed files. The first file is trashed at T = 0, the second file is
  // trashed a bit later at T = 10 minutes.
  SetupFileTrashedFromDownloads(first_file_name);
  task_environment_.FastForwardBy(base::Minutes(10));
  SetupFileTrashedFromDownloads(second_file_name);

  // Init the autocleanup process at T = 30 days (minus kCleanupCheckInterval,
  // the delay before the initial cleanup iteration). Only the first file should
  // be removed.
  task_environment_.FastForwardBy(base::Minutes(50) + base::Hours(23) +
                                  base::Days(29) - kCleanupCheckInterval);
  // Init periodic cleanup.
  base::test::TestFuture<AutoCleanupResult> future;
  SetCleanupDoneCallbackForTest(future.GetCallback<AutoCleanupResult>());
  InitAutoCleanup();
  ASSERT_TRUE(future.Wait());
  // Check that the first file has been removed.
  ASSERT_EQ(future.Take(), AutoCleanupResult::kCleanupSuccessful);
  CheckFileExistsInTrash(first_file_name, /*should_exist=*/false);
  CheckFileExistsInTrash(second_file_name, /*should_exist=*/true);

  // The second file should persist while we are within `kCleanupInterval` of
  // the last cleanup iteration.
  // Note: the mocked time stays constant until `future.Wait()` is called, so
  // `last_cleanup_iteration` is accurate.
  const base::Time last_cleanup_iteration = base::Time::Now();
  task_environment_.FastForwardBy(kCleanupInterval - kCleanupCheckInterval);
  CheckFileExistsInTrash(second_file_name, /*should_exist=*/true);
  // The next cleanup check should happen `kCleanupInterval` after the last
  // iteration. Check that the second file has now been removed.
  SetCleanupDoneCallbackForTest(future.GetCallback<AutoCleanupResult>());
  ASSERT_TRUE(future.Wait());
  ASSERT_EQ(base::Time::Now() - last_cleanup_iteration, kCleanupInterval);
  ASSERT_EQ(future.Take(), AutoCleanupResult::kCleanupSuccessful);
  CheckFileExistsInTrash(second_file_name, /*should_exist=*/false);
}

TEST_F(TrashAutoCleanupTest, MultipleBatchesCleanup) {
  // Setup a number of files in trash directory that equals more than twice the
  // batch size.
  std::vector<std::string> file_names;
  const int n_files = 2.5 * kMaxBatchSize;
  for (int i = 0; i < n_files; ++i) {
    const std::string file_name = "file" + base::NumberToString(i);
    file_names.emplace_back(file_name);
    SetupFileTrashedFromDownloads(file_name);
  }

  task_environment_.FastForwardBy(base::Days(30));
  base::test::TestFuture<AutoCleanupResult> future;
  SetCleanupDoneCallbackForTest(future.GetCallback<AutoCleanupResult>());
  InitAutoCleanup();
  ASSERT_TRUE(future.Wait());
  base::Time last_cleanup_iteration = base::Time::Now();
  // Check that the first batch of files has been removed.
  ASSERT_EQ(future.Take(), AutoCleanupResult::kCleanupSuccessful);
  // Check that `kMaxBatchSize` files have been removed.
  int n_remaining_files = 0;
  for (int i = 0; i < n_files; ++i) {
    const std::string file_name = "file" + base::NumberToString(i);
    if (!base::PathExists(GetTrashedFilePath(file_name))) {
      ASSERT_FALSE(base::PathExists(GetInfoFilePath(file_name)));
    } else {
      ASSERT_TRUE(base::PathExists(GetInfoFilePath(file_name)));
      ++n_remaining_files;
    }
  }
  ASSERT_EQ(n_remaining_files, n_files - kMaxBatchSize);

  // After this iteration, the next batch of files should be processed.
  SetCleanupDoneCallbackForTest(future.GetCallback<AutoCleanupResult>());
  ASSERT_TRUE(future.Wait());
  // This iteration should happen `kCleanupCheckInterval` after the preview one,
  // instead of the next day, since not all the batches have been processed
  // yet.
  ASSERT_EQ(base::Time::Now() - last_cleanup_iteration, kCleanupCheckInterval);
  last_cleanup_iteration = base::Time::Now();
  // Check that the second batch of files has been removed.
  ASSERT_EQ(future.Take(), AutoCleanupResult::kCleanupSuccessful);
  // Check that `2 * kMaxBatchSize` files have been removed.
  n_remaining_files = 0;
  for (int i = 0; i < n_files; ++i) {
    const std::string file_name = "file" + base::NumberToString(i);
    if (!base::PathExists(GetTrashedFilePath(file_name))) {
      ASSERT_FALSE(base::PathExists(GetInfoFilePath(file_name)));
    } else {
      ASSERT_TRUE(base::PathExists(GetInfoFilePath(file_name)));
      ++n_remaining_files;
    }
  }
  ASSERT_EQ(n_remaining_files, n_files - 2 * kMaxBatchSize);

  // After the last iteration, no file should be remaining.
  SetCleanupDoneCallbackForTest(future.GetCallback<AutoCleanupResult>());
  ASSERT_TRUE(future.Wait());
  ASSERT_EQ(base::Time::Now() - last_cleanup_iteration, kCleanupCheckInterval);
  // Check that all files have been removed.
  ASSERT_EQ(future.Take(), AutoCleanupResult::kCleanupSuccessful);
  for (int i = 0; i < n_files; ++i) {
    const std::string file_name = "file" + base::NumberToString(i);
    CheckFileExistsInTrash(file_name, /*should_exist=*/false);
  }
}

}  // namespace file_manager::trash