1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
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/files/important_file_writer.h"
6 
7 #include "base/bind.h"
8 #include "base/compiler_specific.h"
9 #include "base/files/file_path.h"
10 #include "base/files/file_util.h"
11 #include "base/files/scoped_temp_dir.h"
12 #include "base/location.h"
13 #include "base/logging.h"
14 #include "base/macros.h"
15 #include "base/run_loop.h"
16 #include "base/single_thread_task_runner.h"
17 #include "base/thread_task_runner_handle.h"
18 #include "base/threading/thread.h"
19 #include "base/time/time.h"
20 #include "testing/gtest/include/gtest/gtest.h"
21 
22 namespace base {
23 
24 namespace {
25 
GetFileContent(const FilePath & path)26 std::string GetFileContent(const FilePath& path) {
27   std::string content;
28   if (!ReadFileToString(path, &content)) {
29     NOTREACHED();
30   }
31   return content;
32 }
33 
34 class DataSerializer : public ImportantFileWriter::DataSerializer {
35  public:
DataSerializer(const std::string & data)36   explicit DataSerializer(const std::string& data) : data_(data) {
37   }
38 
SerializeData(std::string * output)39   bool SerializeData(std::string* output) override {
40     output->assign(data_);
41     return true;
42   }
43 
44  private:
45   const std::string data_;
46 };
47 
48 class SuccessfulWriteObserver {
49  public:
SuccessfulWriteObserver()50   SuccessfulWriteObserver() : successful_write_observed_(false) {}
51 
52   // Register on_successful_write() to be called on the next successful write
53   // of |writer|.
54   void ObserveNextSuccessfulWrite(ImportantFileWriter* writer);
55 
56   // Returns true if a successful write was observed via on_successful_write()
57   // and resets the observation state to false regardless.
58   bool GetAndResetObservationState();
59 
60  private:
on_successful_write()61   void on_successful_write() {
62     EXPECT_FALSE(successful_write_observed_);
63     successful_write_observed_ = true;
64   }
65 
66   bool successful_write_observed_;
67 
68   DISALLOW_COPY_AND_ASSIGN(SuccessfulWriteObserver);
69 };
70 
ObserveNextSuccessfulWrite(ImportantFileWriter * writer)71 void SuccessfulWriteObserver::ObserveNextSuccessfulWrite(
72     ImportantFileWriter* writer) {
73   writer->RegisterOnNextSuccessfulWriteCallback(base::Bind(
74       &SuccessfulWriteObserver::on_successful_write, base::Unretained(this)));
75 }
76 
GetAndResetObservationState()77 bool SuccessfulWriteObserver::GetAndResetObservationState() {
78   bool was_successful_write_observed = successful_write_observed_;
79   successful_write_observed_ = false;
80   return was_successful_write_observed;
81 }
82 
83 }  // namespace
84 
85 class ImportantFileWriterTest : public testing::Test {
86  public:
ImportantFileWriterTest()87   ImportantFileWriterTest() { }
SetUp()88   void SetUp() override {
89     ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
90     file_ = temp_dir_.path().AppendASCII("test-file");
91   }
92 
93  protected:
94   SuccessfulWriteObserver successful_write_observer_;
95   FilePath file_;
96   MessageLoop loop_;
97 
98  private:
99   ScopedTempDir temp_dir_;
100 };
101 
TEST_F(ImportantFileWriterTest,Basic)102 TEST_F(ImportantFileWriterTest, Basic) {
103   ImportantFileWriter writer(file_, ThreadTaskRunnerHandle::Get());
104   EXPECT_FALSE(PathExists(writer.path()));
105   EXPECT_FALSE(successful_write_observer_.GetAndResetObservationState());
106   writer.WriteNow(make_scoped_ptr(new std::string("foo")));
107   RunLoop().RunUntilIdle();
108 
109   EXPECT_FALSE(successful_write_observer_.GetAndResetObservationState());
110   ASSERT_TRUE(PathExists(writer.path()));
111   EXPECT_EQ("foo", GetFileContent(writer.path()));
112 }
113 
TEST_F(ImportantFileWriterTest,BasicWithSuccessfulWriteObserver)114 TEST_F(ImportantFileWriterTest, BasicWithSuccessfulWriteObserver) {
115   ImportantFileWriter writer(file_, ThreadTaskRunnerHandle::Get());
116   EXPECT_FALSE(PathExists(writer.path()));
117   EXPECT_FALSE(successful_write_observer_.GetAndResetObservationState());
118   successful_write_observer_.ObserveNextSuccessfulWrite(&writer);
119   writer.WriteNow(make_scoped_ptr(new std::string("foo")));
120   RunLoop().RunUntilIdle();
121 
122   // Confirm that the observer is invoked.
123   EXPECT_TRUE(successful_write_observer_.GetAndResetObservationState());
124   ASSERT_TRUE(PathExists(writer.path()));
125   EXPECT_EQ("foo", GetFileContent(writer.path()));
126 
127   // Confirm that re-installing the observer works for another write.
128   EXPECT_FALSE(successful_write_observer_.GetAndResetObservationState());
129   successful_write_observer_.ObserveNextSuccessfulWrite(&writer);
130   writer.WriteNow(make_scoped_ptr(new std::string("bar")));
131   RunLoop().RunUntilIdle();
132 
133   EXPECT_TRUE(successful_write_observer_.GetAndResetObservationState());
134   ASSERT_TRUE(PathExists(writer.path()));
135   EXPECT_EQ("bar", GetFileContent(writer.path()));
136 
137   // Confirm that writing again without re-installing the observer doesn't
138   // result in a notification.
139   EXPECT_FALSE(successful_write_observer_.GetAndResetObservationState());
140   writer.WriteNow(make_scoped_ptr(new std::string("baz")));
141   RunLoop().RunUntilIdle();
142 
143   EXPECT_FALSE(successful_write_observer_.GetAndResetObservationState());
144   ASSERT_TRUE(PathExists(writer.path()));
145   EXPECT_EQ("baz", GetFileContent(writer.path()));
146 }
147 
TEST_F(ImportantFileWriterTest,ScheduleWrite)148 TEST_F(ImportantFileWriterTest, ScheduleWrite) {
149   ImportantFileWriter writer(file_,
150                              ThreadTaskRunnerHandle::Get(),
151                              TimeDelta::FromMilliseconds(25));
152   EXPECT_FALSE(writer.HasPendingWrite());
153   DataSerializer serializer("foo");
154   writer.ScheduleWrite(&serializer);
155   EXPECT_TRUE(writer.HasPendingWrite());
156   ThreadTaskRunnerHandle::Get()->PostDelayedTask(
157       FROM_HERE, MessageLoop::QuitWhenIdleClosure(),
158       TimeDelta::FromMilliseconds(100));
159   MessageLoop::current()->Run();
160   EXPECT_FALSE(writer.HasPendingWrite());
161   ASSERT_TRUE(PathExists(writer.path()));
162   EXPECT_EQ("foo", GetFileContent(writer.path()));
163 }
164 
TEST_F(ImportantFileWriterTest,DoScheduledWrite)165 TEST_F(ImportantFileWriterTest, DoScheduledWrite) {
166   ImportantFileWriter writer(file_, ThreadTaskRunnerHandle::Get());
167   EXPECT_FALSE(writer.HasPendingWrite());
168   DataSerializer serializer("foo");
169   writer.ScheduleWrite(&serializer);
170   EXPECT_TRUE(writer.HasPendingWrite());
171   writer.DoScheduledWrite();
172   ThreadTaskRunnerHandle::Get()->PostDelayedTask(
173       FROM_HERE, MessageLoop::QuitWhenIdleClosure(),
174       TimeDelta::FromMilliseconds(100));
175   MessageLoop::current()->Run();
176   EXPECT_FALSE(writer.HasPendingWrite());
177   ASSERT_TRUE(PathExists(writer.path()));
178   EXPECT_EQ("foo", GetFileContent(writer.path()));
179 }
180 
TEST_F(ImportantFileWriterTest,BatchingWrites)181 TEST_F(ImportantFileWriterTest, BatchingWrites) {
182   ImportantFileWriter writer(file_,
183                              ThreadTaskRunnerHandle::Get(),
184                              TimeDelta::FromMilliseconds(25));
185   DataSerializer foo("foo"), bar("bar"), baz("baz");
186   writer.ScheduleWrite(&foo);
187   writer.ScheduleWrite(&bar);
188   writer.ScheduleWrite(&baz);
189   ThreadTaskRunnerHandle::Get()->PostDelayedTask(
190       FROM_HERE, MessageLoop::QuitWhenIdleClosure(),
191       TimeDelta::FromMilliseconds(100));
192   MessageLoop::current()->Run();
193   ASSERT_TRUE(PathExists(writer.path()));
194   EXPECT_EQ("baz", GetFileContent(writer.path()));
195 }
196 
197 }  // namespace base
198