File: backend_params_manager_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,122,156 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 (260 lines) | stat: -rw-r--r-- 9,228 bytes parent folder | download | duplicates (3)
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
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/persistent_cache/backend_params_manager.h"

#include <cstdint>
#include <memory>

#include "base/files/file.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/functional/callback_forward.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "base/threading/platform_thread.h"
#include "base/time/time.h"
#include "components/persistent_cache/backend_params.h"
#include "components/persistent_cache/persistent_cache.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace persistent_cache {

class BackendParamsManagerTest : public testing::Test {
  void SetUp() override { CHECK(temp_dir_.CreateUniqueTempDir()); }

 protected:
  int CountFiles() {
    base::FileEnumerator file_enumarator(temp_dir_.GetPath(),
                                         /*recursive=*/true,
                                         base::FileEnumerator::FILES);
    int file_count = 0;
    file_enumarator.ForEach(
        [&file_count](const base::FilePath& file_path) { ++file_count; });

    return file_count;
  }

  std::vector<base::Time> GetSortedModificationTimes() {
    std::vector<base::Time> modification_times;

    base::FileEnumerator file_enumarator(
        temp_dir_.GetPath(), /*recursive=*/true, base::FileEnumerator::FILES);
    file_enumarator.ForEach(
        [&modification_times](const base::FilePath& file_path) {
          base::File::Info info;
          base::GetFileInfo(file_path, &info);
          modification_times.push_back(info.last_accessed);
        });

    // Sort so that oldest entries are first.
    std::sort(modification_times.begin(), modification_times.end());

    return modification_times;
  }

  void Fill(persistent_cache::BackendParamsManager& params_manager,
            int64_t file_count,
            int64_t file_size) {
    for (int i = 0; i < file_count; ++i) {
      const std::string key = base::NumberToString(i);

      // Actual sleep is necessary to get timestamp variety since
      // BackendParamsManager relies on OS file timestamps which are not
      // affected by mock time.
      base::PlatformThread::Sleep(base::Milliseconds(5));

      BackendParams params = params_manager.GetOrCreateParamsSync(
          BackendType::kSqlite, key,
          BackendParamsManager::AccessRights::kReadWrite);
      params.db_file.SetLength(file_size);
    }
  }

  // Create enough file that are big enough to go over kTargetFootprint.
  void OverFill(persistent_cache::BackendParamsManager& params_manager) {
    static constexpr int64_t kFileCount = 10;
    // Just large enough to ensure the target footprint will be surpassed.
    static constexpr int64_t kFileSize = (kTargetFootprint / kFileCount) + 100;
    Fill(params_manager, kFileCount, kFileSize);
  }

  static constexpr int64_t kTargetFootprint = 20000;
  base::ScopedTempDir temp_dir_;
  base::test::TaskEnvironment task_environment_;
};

TEST_F(BackendParamsManagerTest,
       SynchronousCreationEqualsSubsequentSynchronousRetrieval) {
  BackendParamsManager params_manager(temp_dir_.GetPath());

  BackendParams params = params_manager.GetOrCreateParamsSync(
      BackendType::kSqlite, "key",
      BackendParamsManager::AccessRights::kReadWrite);
  EXPECT_TRUE(params.db_file.IsValid());
  EXPECT_TRUE(params.journal_file.IsValid());

  params.db_file.SetLength(42);

  BackendParams other_params = params_manager.GetOrCreateParamsSync(
      BackendType::kSqlite, "key",
      BackendParamsManager::AccessRights::kReadWrite);
  EXPECT_EQ(other_params.db_file.GetLength(), params.db_file.GetLength());
}

TEST_F(BackendParamsManagerTest, UnknownKeyTypePairQueryServedAsynchronously) {
  BackendParamsManager params_manager(temp_dir_.GetPath());

  base::RunLoop run_loop;

  BackendParams backend_params;
  params_manager.GetParamsSyncOrCreateAsync(
      BackendType::kSqlite, "key",
      BackendParamsManager::AccessRights::kReadWrite,
      base::BindLambdaForTesting(
          [&backend_params, &run_loop](const BackendParams& result) {
            backend_params = result.Copy();
            run_loop.Quit();
          }));

  // The callback was not invoked yet so files are not populated.
  EXPECT_FALSE(backend_params.db_file.IsValid());
  EXPECT_FALSE(backend_params.journal_file.IsValid());

  // Wait for the callback to be invoked. If never invoked the test will time
  // out.
  run_loop.Run();

  // Once received the params contain valid files.
  EXPECT_TRUE(backend_params.db_file.IsValid());
  EXPECT_TRUE(backend_params.journal_file.IsValid());
}

TEST_F(BackendParamsManagerTest, ExistingKeyTypePairQueryServedSynchronously) {
  BackendParamsManager params_manager(temp_dir_.GetPath());

  {
    BackendParams backend_params;
    base::RunLoop run_loop;
    params_manager.GetParamsSyncOrCreateAsync(
        BackendType::kSqlite, "key",
        BackendParamsManager::AccessRights::kReadWrite,
        base::BindLambdaForTesting(
            [&backend_params, &run_loop](const BackendParams& result) {
              backend_params = result.Copy();
              run_loop.Quit();
            }));

    // The callback was not invoked yet so files are not populated.
    EXPECT_FALSE(backend_params.db_file.IsValid());
    EXPECT_FALSE(backend_params.journal_file.IsValid());

    // Makes sure the callback runs on the ThreadPool.
    run_loop.Run();

    // Once received the params contain valid files.
    EXPECT_TRUE(backend_params.db_file.IsValid());
    EXPECT_TRUE(backend_params.journal_file.IsValid());
  }

  {
    BackendParams backend_params;
    base::RunLoop run_loop;
    params_manager.GetParamsSyncOrCreateAsync(
        BackendType::kSqlite, "key",
        BackendParamsManager::AccessRights::kReadWrite,
        base::BindLambdaForTesting(
            [&backend_params, &run_loop](const BackendParams& result) {
              backend_params = result.Copy();
              run_loop.Quit();
            }));

    // No need to run `run_loop` since the callback was invoked synchronously.

    // Once received the params contain valid files.
    EXPECT_TRUE(backend_params.db_file.IsValid());
    EXPECT_TRUE(backend_params.journal_file.IsValid());
  }
}

TEST_F(BackendParamsManagerTest, DeleteAllFiles) {
  BackendParamsManager params_manager(temp_dir_.GetPath());

  {
    BackendParams params = params_manager.GetOrCreateParamsSync(
        BackendType::kSqlite, "key",
        BackendParamsManager::AccessRights::kReadWrite);
    EXPECT_TRUE(params.db_file.IsValid());

    // Inserting an entry should have created at least one file.
    EXPECT_GE(CountFiles(), 1);
  }

  params_manager.DeleteAllFiles();
  EXPECT_EQ(CountFiles(), 0);
}

TEST_F(BackendParamsManagerTest, NoFileReductionIfNotNeeded) {
  const int64_t file_count = 1;
  const int64_t file_size = 100;

  BackendParamsManager params_manager(temp_dir_.GetPath());
  Fill(params_manager, file_count, file_size);
  EXPECT_LE(base::ComputeDirectorySize(temp_dir_.GetPath()), kTargetFootprint);

  // The footprint of the files do not approach the requested target size so
  // nothing is done.
  EXPECT_EQ(params_manager.BringDownTotalFootprintOfFiles(file_count *
                                                          file_size * 10),
            0);
}

TEST_F(BackendParamsManagerTest, BringDownTotalFootPrint) {
  BackendParamsManager params_manager(temp_dir_.GetPath());

  OverFill(params_manager);
  EXPECT_GE(base::ComputeDirectorySize(temp_dir_.GetPath()), kTargetFootprint);

  EXPECT_GT(params_manager.BringDownTotalFootprintOfFiles(kTargetFootprint), 0);

  EXPECT_LE(base::ComputeDirectorySize(temp_dir_.GetPath()), kTargetFootprint);
}

TEST_F(BackendParamsManagerTest, OldestEntriesAreRemovedFirst) {
  BackendParamsManager params_manager(temp_dir_.GetPath());

  OverFill(params_manager);

  std::vector<base::Time> modification_times = GetSortedModificationTimes();

  params_manager.BringDownTotalFootprintOfFiles(kTargetFootprint);

  std::vector<base::Time> modification_times_after_reduction =
      GetSortedModificationTimes();

  // Verify that the size of the files in the directory actually went down.
  ASSERT_GT(modification_times.size(),
            modification_times_after_reduction.size());

  auto original_timestamps_it = modification_times.rbegin();
  auto timestamps_after_reduction_it =
      modification_times_after_reduction.rbegin();

  // Verify that the entries removed were the oldest ones or tied for oldest.
  // The missing timestamps have to be the smallest since the data is sorted.
  // This test is tolerant of timestamps all being equal for whatever reason.
  while (timestamps_after_reduction_it !=
         modification_times_after_reduction.rend()) {
    EXPECT_EQ(*original_timestamps_it, *timestamps_after_reduction_it);

    ++original_timestamps_it;
    ++timestamps_after_reduction_it;
  }
}

}  // namespace persistent_cache