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
  289
  290
  291
  292
  293
  294
  295
  296
  297
  298
  299
  300
  301
  302
  303
  304
  305
  306
  307
  308
  309
  310
  311

base / files / important_file_writer_cleaner_unittest.cc [blame]

// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/files/important_file_writer_cleaner.h"

#include <optional>

#include "base/check.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/task/thread_pool.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "base/test/test_waitable_event.h"
#include "base/time/time.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::testing::ElementsAre;

namespace base {

class ImportantFileWriterCleanerTest : public ::testing::Test {
 public:
  ImportantFileWriterCleanerTest()
      : old_file_time_(ImportantFileWriterCleaner::GetInstance()
                           .GetUpperBoundTimeForTest() -
                       Milliseconds(1)) {}

 protected:
  // Initializes and Starts the global cleaner at construction and Stops it
  // at destruction. ("Lifetime" refers to its activity rather than existence.)
  class ScopedCleanerLifetime {
   public:
    ScopedCleanerLifetime() {
      auto& instance = ImportantFileWriterCleaner::GetInstance();
      instance.Initialize();
      instance.Start();
    }
    ScopedCleanerLifetime(const ScopedCleanerLifetime&) = delete;
    ScopedCleanerLifetime& operator=(const ScopedCleanerLifetime&) = delete;
    ~ScopedCleanerLifetime() {
      ImportantFileWriterCleaner::GetInstance().Stop();
    }
  };

  void SetUp() override;
  void TearDown() override;

  const FilePath& dir_1() const { return dir_1_; }
  const FilePath& dir_1_file_new() const { return dir_1_file_new_; }
  const FilePath& dir_1_file_old() const { return dir_1_file_old_; }
  const FilePath& dir_1_file_other() const { return dir_1_file_other_; }
  const FilePath& dir_2() const { return dir_2_; }
  const FilePath& dir_2_file_new() const { return dir_2_file_new_; }
  const FilePath& dir_2_file_old() const { return dir_2_file_old_; }
  const FilePath& dir_2_file_other() const { return dir_2_file_other_; }

  void StartCleaner() {
    DCHECK(!cleaner_lifetime_.has_value());
    cleaner_lifetime_.emplace();
  }

  void StopCleaner() {
    DCHECK(cleaner_lifetime_.has_value());
    cleaner_lifetime_.reset();
  }

  void CreateNewFileInDir(const FilePath& dir, FilePath& path) {
    File file = CreateAndOpenTemporaryFileInDir(dir, &path);
    ASSERT_TRUE(file.IsValid());
  }

  void CreateOldFileInDir(const FilePath& dir, FilePath& path) {
    File file = CreateAndOpenTemporaryFileInDir(dir, &path);
    ASSERT_TRUE(file.IsValid());
    ASSERT_TRUE(file.SetTimes(Time::Now(), old_file_time_));
  }

  void CreateOldFile(const FilePath& path) {
    File file(path, File::FLAG_CREATE | File::FLAG_WRITE);
    ASSERT_TRUE(file.IsValid());
    ASSERT_TRUE(file.SetTimes(Time::Now(), old_file_time_));
  }

  ScopedTempDir temp_dir_;
  test::TaskEnvironment task_environment_;

 private:
  const Time old_file_time_;
  FilePath dir_1_;
  FilePath dir_2_;
  FilePath dir_1_file_new_;
  FilePath dir_1_file_old_;
  FilePath dir_1_file_other_;
  FilePath dir_2_file_new_;
  FilePath dir_2_file_old_;
  FilePath dir_2_file_other_;
  std::optional<ScopedCleanerLifetime> cleaner_lifetime_;
};

void ImportantFileWriterCleanerTest::SetUp() {
  ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());

  // Create two directories that will hold files to be cleaned.
  dir_1_ = temp_dir_.GetPath().Append(FILE_PATH_LITERAL("dir_1"));
  ASSERT_TRUE(CreateDirectory(dir_1_));
  dir_2_ = temp_dir_.GetPath().Append(FILE_PATH_LITERAL("dir_2"));
  ASSERT_TRUE(CreateDirectory(dir_2_));

  // Create some old and new files in each dir.
  ASSERT_NO_FATAL_FAILURE(CreateNewFileInDir(dir_1_, dir_1_file_new_));

  ASSERT_NO_FATAL_FAILURE(CreateOldFileInDir(dir_1_, dir_1_file_old_));

  dir_1_file_other_ = dir_1_.Append(FILE_PATH_LITERAL("other.nottmp"));
  ASSERT_NO_FATAL_FAILURE(CreateOldFile(dir_1_file_other_));

  ASSERT_NO_FATAL_FAILURE(CreateNewFileInDir(dir_2_, dir_2_file_new_));

  ASSERT_NO_FATAL_FAILURE(CreateOldFileInDir(dir_2_, dir_2_file_old_));

  dir_2_file_other_ = dir_2_.Append(FILE_PATH_LITERAL("other.nottmp"));
  ASSERT_NO_FATAL_FAILURE(CreateOldFile(dir_2_file_other_));
}

void ImportantFileWriterCleanerTest::TearDown() {
  cleaner_lifetime_.reset();
  task_environment_.RunUntilIdle();
  ImportantFileWriterCleaner::GetInstance().UninitializeForTesting();
  EXPECT_TRUE(temp_dir_.Delete());
}

// Tests that adding a directory without initializing the cleaner does nothing.
TEST_F(ImportantFileWriterCleanerTest, NotInitializedNoOpAdd) {
  ImportantFileWriterCleaner::AddDirectory(dir_1());
  task_environment_.RunUntilIdle();
  EXPECT_TRUE(PathExists(dir_1_file_new()));
  EXPECT_TRUE(PathExists(dir_1_file_old()));
  EXPECT_TRUE(PathExists(dir_1_file_other()));
  EXPECT_TRUE(PathExists(dir_2_file_new()));
  EXPECT_TRUE(PathExists(dir_2_file_old()));
  EXPECT_TRUE(PathExists(dir_2_file_other()));
}

// Tests that adding a directory without starting the cleaner does nothing.
TEST_F(ImportantFileWriterCleanerTest, NotStartedNoOpAdd) {
  ImportantFileWriterCleaner::GetInstance().Initialize();
  ImportantFileWriterCleaner::AddDirectory(dir_1());
  task_environment_.RunUntilIdle();
  EXPECT_TRUE(PathExists(dir_1_file_new()));
  EXPECT_TRUE(PathExists(dir_1_file_old()));
  EXPECT_TRUE(PathExists(dir_1_file_other()));
  EXPECT_TRUE(PathExists(dir_2_file_new()));
  EXPECT_TRUE(PathExists(dir_2_file_old()));
  EXPECT_TRUE(PathExists(dir_2_file_other()));
}

// Tests that starting and stopping does no harm.
TEST_F(ImportantFileWriterCleanerTest, StartStop) {
  StartCleaner();
  StopCleaner();
}

// Tests that adding a directory then starting the cleaner works.
TEST_F(ImportantFileWriterCleanerTest, AddStart) {
  ImportantFileWriterCleaner::GetInstance().Initialize();
  ImportantFileWriterCleaner::AddDirectory(dir_1());
  StartCleaner();
  task_environment_.RunUntilIdle();

  // The old file should have been cleaned from the added dir.
  EXPECT_TRUE(PathExists(dir_1_file_new()));
  EXPECT_FALSE(PathExists(dir_1_file_old()));
  EXPECT_TRUE(PathExists(dir_1_file_other()));
  EXPECT_TRUE(PathExists(dir_2_file_new()));
  EXPECT_TRUE(PathExists(dir_2_file_old()));
  EXPECT_TRUE(PathExists(dir_2_file_other()));
}

// Tests that adding multiple directories before starting cleans both.
TEST_F(ImportantFileWriterCleanerTest, AddAddStart) {
  ImportantFileWriterCleaner::GetInstance().Initialize();
  ImportantFileWriterCleaner::AddDirectory(dir_1());
  ImportantFileWriterCleaner::AddDirectory(dir_2());
  StartCleaner();
  task_environment_.RunUntilIdle();

  // The old file should have been cleaned from both added dirs.
  EXPECT_TRUE(PathExists(dir_1_file_new()));
  EXPECT_FALSE(PathExists(dir_1_file_old()));
  EXPECT_TRUE(PathExists(dir_1_file_other()));
  EXPECT_TRUE(PathExists(dir_2_file_new()));
  EXPECT_FALSE(PathExists(dir_2_file_old()));
  EXPECT_TRUE(PathExists(dir_2_file_other()));
}

// Tests that starting the cleaner then adding a directory works.
TEST_F(ImportantFileWriterCleanerTest, StartAdd) {
  StartCleaner();
  ImportantFileWriterCleaner::AddDirectory(dir_1());
  task_environment_.RunUntilIdle();

  // The old file should have been cleaned from the added dir.
  EXPECT_TRUE(PathExists(dir_1_file_new()));
  EXPECT_FALSE(PathExists(dir_1_file_old()));
  EXPECT_TRUE(PathExists(dir_1_file_other()));
  EXPECT_TRUE(PathExists(dir_2_file_new()));
  EXPECT_TRUE(PathExists(dir_2_file_old()));
  EXPECT_TRUE(PathExists(dir_2_file_other()));
}

// Tests that starting the cleaner twice doesn't cause it to clean twice.
TEST_F(ImportantFileWriterCleanerTest, StartTwice) {
  StartCleaner();
  ImportantFileWriterCleaner::AddDirectory(dir_1());
  task_environment_.RunUntilIdle();

  // Recreate the old file that was just cleaned.
  ASSERT_NO_FATAL_FAILURE(CreateOldFile(dir_1_file_old()));

  // Start again and make sure it wasn't cleaned again.
  ImportantFileWriterCleaner::GetInstance().Start();
  task_environment_.RunUntilIdle();

  EXPECT_TRUE(PathExists(dir_1_file_old()));
}

// Tests that adding a dir twice doesn't cause it to clean twice.
TEST_F(ImportantFileWriterCleanerTest, AddTwice) {
  StartCleaner();
  ImportantFileWriterCleaner::AddDirectory(dir_1());
  task_environment_.RunUntilIdle();

  // Recreate the old file that was just cleaned.
  ASSERT_NO_FATAL_FAILURE(CreateOldFile(dir_1_file_old()));

  // Add the directory again and make sure nothing else is cleaned.
  ImportantFileWriterCleaner::AddDirectory(dir_1());
  task_environment_.RunUntilIdle();

  EXPECT_TRUE(PathExists(dir_1_file_old()));
}

// Tests that AddDirectory called from another thread properly bounces back to
// the main thread for processing.
TEST_F(ImportantFileWriterCleanerTest, StartAddFromOtherThread) {
  StartCleaner();

  // Add from the ThreadPool and wait for it to finish.
  TestWaitableEvent waitable_event;
  ThreadPool::PostTask(FROM_HERE, BindLambdaForTesting([&] {
                         ImportantFileWriterCleaner::AddDirectory(dir_1());
                         waitable_event.Signal();
                       }));
  waitable_event.Wait();

  // Allow the cleaner to run.
  task_environment_.RunUntilIdle();

  // The old file should have been cleaned from the added dir.
  EXPECT_TRUE(PathExists(dir_1_file_new()));
  EXPECT_FALSE(PathExists(dir_1_file_old()));
  EXPECT_TRUE(PathExists(dir_1_file_other()));
  EXPECT_TRUE(PathExists(dir_2_file_new()));
  EXPECT_TRUE(PathExists(dir_2_file_old()));
  EXPECT_TRUE(PathExists(dir_2_file_other()));
}

// Tests that adding a directory while a session is processing a previous
// directory works.
TEST_F(ImportantFileWriterCleanerTest, AddStartAdd) {
  ImportantFileWriterCleaner::GetInstance().Initialize();
  ImportantFileWriterCleaner::AddDirectory(dir_1());
  StartCleaner();
  ImportantFileWriterCleaner::AddDirectory(dir_2());
  task_environment_.RunUntilIdle();

  // The old file should have been cleaned from both added dirs.
  EXPECT_TRUE(PathExists(dir_1_file_new()));
  EXPECT_FALSE(PathExists(dir_1_file_old()));
  EXPECT_TRUE(PathExists(dir_1_file_other()));
  EXPECT_TRUE(PathExists(dir_2_file_new()));
  EXPECT_FALSE(PathExists(dir_2_file_old()));
  EXPECT_TRUE(PathExists(dir_2_file_other()));
}

// Tests stopping while the background task is running.
TEST_F(ImportantFileWriterCleanerTest, StopWhileRunning) {
  ImportantFileWriterCleaner::GetInstance().Initialize();

  // Create a great many old files in dir1.
  for (int i = 0; i < 100; ++i) {
    FilePath path;
    CreateOldFileInDir(dir_1(), path);
  }

  ImportantFileWriterCleaner::AddDirectory(dir_1());
  StartCleaner();

  // It's possible that the background task will quickly delete all 100 files.
  // In all likelihood, though, the stop flag will be read and processed before
  // then. Either case is a success.
  StopCleaner();
  task_environment_.RunUntilIdle();
}

}  // namespace base