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
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// 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.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace {
std::string GetFileContent(const FilePath& path) {
std::string content;
if (!ReadFileToString(path, &content)) {
NOTREACHED();
}
return content;
}
class DataSerializer : public ImportantFileWriter::DataSerializer {
public:
explicit DataSerializer(const std::string& data) : data_(data) {
}
bool SerializeData(std::string* output) override {
output->assign(data_);
return true;
}
private:
const std::string data_;
};
enum WriteCallbackObservationState {
NOT_CALLED,
CALLED_WITH_ERROR,
CALLED_WITH_SUCCESS,
};
class WriteCallbacksObserver {
public:
WriteCallbacksObserver() = default;
// Register OnBeforeWrite() and OnAfterWrite() to be called on the next write
// of |writer|.
void ObserveNextWriteCallbacks(ImportantFileWriter* writer);
// Returns the |WriteCallbackObservationState| which was observed, then resets
// it to |NOT_CALLED|.
WriteCallbackObservationState GetAndResetObservationState();
private:
void OnBeforeWrite() {
EXPECT_FALSE(before_write_called_);
before_write_called_ = true;
}
void OnAfterWrite(bool success) {
EXPECT_EQ(NOT_CALLED, after_write_observation_state_);
after_write_observation_state_ =
success ? CALLED_WITH_SUCCESS : CALLED_WITH_ERROR;
}
bool before_write_called_ = false;
WriteCallbackObservationState after_write_observation_state_ = NOT_CALLED;
DISALLOW_COPY_AND_ASSIGN(WriteCallbacksObserver);
};
void WriteCallbacksObserver::ObserveNextWriteCallbacks(
ImportantFileWriter* writer) {
writer->RegisterOnNextWriteCallbacks(
base::Bind(&WriteCallbacksObserver::OnBeforeWrite,
base::Unretained(this)),
base::Bind(&WriteCallbacksObserver::OnAfterWrite,
base::Unretained(this)));
}
WriteCallbackObservationState
WriteCallbacksObserver::GetAndResetObservationState() {
EXPECT_EQ(after_write_observation_state_ != NOT_CALLED, before_write_called_)
<< "The before-write callback should always be called before the "
"after-write callback";
WriteCallbackObservationState state = after_write_observation_state_;
before_write_called_ = false;
after_write_observation_state_ = NOT_CALLED;
return state;
}
} // namespace
class ImportantFileWriterTest : public testing::Test {
public:
ImportantFileWriterTest() { }
void SetUp() override {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
file_ = temp_dir_.GetPath().AppendASCII("test-file");
}
protected:
WriteCallbacksObserver write_callback_observer_;
FilePath file_;
MessageLoop loop_;
private:
ScopedTempDir temp_dir_;
};
TEST_F(ImportantFileWriterTest, Basic) {
ImportantFileWriter writer(file_, ThreadTaskRunnerHandle::Get());
EXPECT_FALSE(PathExists(writer.path()));
EXPECT_EQ(NOT_CALLED, write_callback_observer_.GetAndResetObservationState());
writer.WriteNow(MakeUnique<std::string>("foo"));
RunLoop().RunUntilIdle();
EXPECT_EQ(NOT_CALLED, write_callback_observer_.GetAndResetObservationState());
ASSERT_TRUE(PathExists(writer.path()));
EXPECT_EQ("foo", GetFileContent(writer.path()));
}
TEST_F(ImportantFileWriterTest, WriteWithObserver) {
ImportantFileWriter writer(file_, ThreadTaskRunnerHandle::Get());
EXPECT_FALSE(PathExists(writer.path()));
EXPECT_EQ(NOT_CALLED, write_callback_observer_.GetAndResetObservationState());
// Confirm that the observer is invoked.
write_callback_observer_.ObserveNextWriteCallbacks(&writer);
writer.WriteNow(MakeUnique<std::string>("foo"));
RunLoop().RunUntilIdle();
EXPECT_EQ(CALLED_WITH_SUCCESS,
write_callback_observer_.GetAndResetObservationState());
ASSERT_TRUE(PathExists(writer.path()));
EXPECT_EQ("foo", GetFileContent(writer.path()));
// Confirm that re-installing the observer works for another write.
EXPECT_EQ(NOT_CALLED, write_callback_observer_.GetAndResetObservationState());
write_callback_observer_.ObserveNextWriteCallbacks(&writer);
writer.WriteNow(MakeUnique<std::string>("bar"));
RunLoop().RunUntilIdle();
EXPECT_EQ(CALLED_WITH_SUCCESS,
write_callback_observer_.GetAndResetObservationState());
ASSERT_TRUE(PathExists(writer.path()));
EXPECT_EQ("bar", GetFileContent(writer.path()));
// Confirm that writing again without re-installing the observer doesn't
// result in a notification.
EXPECT_EQ(NOT_CALLED, write_callback_observer_.GetAndResetObservationState());
writer.WriteNow(MakeUnique<std::string>("baz"));
RunLoop().RunUntilIdle();
EXPECT_EQ(NOT_CALLED, write_callback_observer_.GetAndResetObservationState());
ASSERT_TRUE(PathExists(writer.path()));
EXPECT_EQ("baz", GetFileContent(writer.path()));
}
TEST_F(ImportantFileWriterTest, FailedWriteWithObserver) {
// Use an invalid file path (relative paths are invalid) to get a
// FILE_ERROR_ACCESS_DENIED error when trying to write the file.
ImportantFileWriter writer(FilePath().AppendASCII("bad/../path"),
ThreadTaskRunnerHandle::Get());
EXPECT_FALSE(PathExists(writer.path()));
EXPECT_EQ(NOT_CALLED, write_callback_observer_.GetAndResetObservationState());
write_callback_observer_.ObserveNextWriteCallbacks(&writer);
writer.WriteNow(MakeUnique<std::string>("foo"));
RunLoop().RunUntilIdle();
// Confirm that the write observer was invoked with its boolean parameter set
// to false.
EXPECT_EQ(CALLED_WITH_ERROR,
write_callback_observer_.GetAndResetObservationState());
EXPECT_FALSE(PathExists(writer.path()));
}
TEST_F(ImportantFileWriterTest, CallbackRunsOnWriterThread) {
base::Thread file_writer_thread("ImportantFileWriter test thread");
file_writer_thread.Start();
ImportantFileWriter writer(file_, file_writer_thread.task_runner());
EXPECT_EQ(NOT_CALLED, write_callback_observer_.GetAndResetObservationState());
// Block execution on |file_writer_thread| to verify that callbacks are
// executed on it.
base::WaitableEvent wait_helper(
base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED);
file_writer_thread.task_runner()->PostTask(
FROM_HERE,
base::Bind(&base::WaitableEvent::Wait, base::Unretained(&wait_helper)));
write_callback_observer_.ObserveNextWriteCallbacks(&writer);
writer.WriteNow(MakeUnique<std::string>("foo"));
RunLoop().RunUntilIdle();
// Expect the callback to not have been executed before the
// |file_writer_thread| is unblocked.
EXPECT_EQ(NOT_CALLED, write_callback_observer_.GetAndResetObservationState());
wait_helper.Signal();
file_writer_thread.FlushForTesting();
EXPECT_EQ(CALLED_WITH_SUCCESS,
write_callback_observer_.GetAndResetObservationState());
ASSERT_TRUE(PathExists(writer.path()));
EXPECT_EQ("foo", GetFileContent(writer.path()));
}
TEST_F(ImportantFileWriterTest, ScheduleWrite) {
ImportantFileWriter writer(file_,
ThreadTaskRunnerHandle::Get(),
TimeDelta::FromMilliseconds(25));
EXPECT_FALSE(writer.HasPendingWrite());
DataSerializer serializer("foo");
writer.ScheduleWrite(&serializer);
EXPECT_TRUE(writer.HasPendingWrite());
ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, MessageLoop::QuitWhenIdleClosure(),
TimeDelta::FromMilliseconds(100));
RunLoop().Run();
EXPECT_FALSE(writer.HasPendingWrite());
ASSERT_TRUE(PathExists(writer.path()));
EXPECT_EQ("foo", GetFileContent(writer.path()));
}
TEST_F(ImportantFileWriterTest, DoScheduledWrite) {
ImportantFileWriter writer(file_, ThreadTaskRunnerHandle::Get());
EXPECT_FALSE(writer.HasPendingWrite());
DataSerializer serializer("foo");
writer.ScheduleWrite(&serializer);
EXPECT_TRUE(writer.HasPendingWrite());
writer.DoScheduledWrite();
ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, MessageLoop::QuitWhenIdleClosure(),
TimeDelta::FromMilliseconds(100));
RunLoop().Run();
EXPECT_FALSE(writer.HasPendingWrite());
ASSERT_TRUE(PathExists(writer.path()));
EXPECT_EQ("foo", GetFileContent(writer.path()));
}
TEST_F(ImportantFileWriterTest, BatchingWrites) {
ImportantFileWriter writer(file_,
ThreadTaskRunnerHandle::Get(),
TimeDelta::FromMilliseconds(25));
DataSerializer foo("foo"), bar("bar"), baz("baz");
writer.ScheduleWrite(&foo);
writer.ScheduleWrite(&bar);
writer.ScheduleWrite(&baz);
ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, MessageLoop::QuitWhenIdleClosure(),
TimeDelta::FromMilliseconds(100));
RunLoop().Run();
ASSERT_TRUE(PathExists(writer.path()));
EXPECT_EQ("baz", GetFileContent(writer.path()));
}
} // namespace base
|