Index: extensions/browser/api/lock_screen_data/item_storage_unittest.cc |
diff --git a/extensions/browser/api/lock_screen_data/item_storage_unittest.cc b/extensions/browser/api/lock_screen_data/item_storage_unittest.cc |
new file mode 100644 |
index 0000000000000000000000000000000000000000..8ab611a0de3605c6a6e7f7855d438438b50ca8da |
--- /dev/null |
+++ b/extensions/browser/api/lock_screen_data/item_storage_unittest.cc |
@@ -0,0 +1,947 @@ |
+// Copyright 2017 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 "extensions/browser/api/lock_screen_data/item_storage.h" |
+ |
+#include <map> |
+#include <memory> |
+#include <queue> |
+#include <utility> |
+#include <vector> |
+ |
+#include "base/callback.h" |
+#include "base/files/file_path.h" |
+#include "base/files/file_util.h" |
+#include "base/files/scoped_temp_dir.h" |
+#include "base/memory/ptr_util.h" |
+#include "base/memory/ref_counted.h" |
+#include "base/run_loop.h" |
+#include "base/task_scheduler/post_task.h" |
+#include "base/time/time.h" |
+#include "chromeos/login/login_state.h" |
+#include "components/prefs/scoped_user_pref_update.h" |
+#include "components/prefs/testing_pref_service.h" |
+#include "components/sync_preferences/testing_pref_service_syncable.h" |
+#include "components/user_prefs/user_prefs.h" |
+#include "content/public/test/test_browser_context.h" |
+#include "content/public/test/test_browser_thread_bundle.h" |
+#include "extensions/browser/api/lock_screen_data/data_item.h" |
+#include "extensions/browser/api/lock_screen_data/operation_result.h" |
+#include "extensions/browser/event_router.h" |
+#include "extensions/browser/event_router_factory.h" |
+#include "extensions/browser/extension_registry.h" |
+#include "extensions/browser/extensions_test.h" |
+#include "extensions/browser/test_extensions_browser_client.h" |
+#include "extensions/common/api/lock_screen_data.h" |
+#include "extensions/common/extension_builder.h" |
+#include "extensions/common/value_builder.h" |
+#include "testing/gtest/include/gtest/gtest.h" |
+ |
+namespace extensions { |
+namespace lock_screen_data { |
+ |
+namespace { |
+ |
+const char kTestUserIdHash[] = "user_id_hash"; |
+const char kTestSymmetricKey[] = "fake_symmetric_key"; |
+ |
+const char kDataItemsPrefKey[] = "lockScreenDataItems"; |
+const char kDataItemFileKey[] = "backing_file"; |
+const char kDataItemIdKey[] = "id"; |
+ |
+void RecordWriteResult(OperationResult* result_out, OperationResult result) { |
+ *result_out = result; |
+} |
+ |
+void WriteNotCalled(OperationResult result) { |
+ ADD_FAILURE() << "Called unexpectedly"; |
+} |
+ |
+void RecordReadResult(OperationResult* result_out, |
+ std::unique_ptr<std::vector<char>>* content_out, |
+ OperationResult result, |
+ std::unique_ptr<std::vector<char>> content) { |
+ *result_out = result; |
+ *content_out = std::move(content); |
+} |
+ |
+void ReadNotCalled(OperationResult result, |
+ std::unique_ptr<std::vector<char>> content) { |
+ ADD_FAILURE() << "Called unexpectedly"; |
+} |
+ |
+class TestEventRouter : public extensions::EventRouter { |
+ public: |
+ explicit TestEventRouter(content::BrowserContext* context) |
+ : extensions::EventRouter(context, nullptr) {} |
+ ~TestEventRouter() override = default; |
+ |
+ bool ExtensionHasEventListener(const std::string& extension_id, |
+ const std::string& event_name) const override { |
+ return event_name == |
+ extensions::api::lock_screen_data::OnDataItemsAvailable::kEventName; |
+ } |
+ |
+ void BroadcastEvent(std::unique_ptr<extensions::Event> event) override {} |
+ |
+ void DispatchEventToExtension( |
+ const std::string& extension_id, |
+ std::unique_ptr<extensions::Event> event) override { |
+ if (event->event_name != |
+ extensions::api::lock_screen_data::OnDataItemsAvailable::kEventName) { |
+ return; |
+ } |
+ ASSERT_TRUE(event->event_args); |
+ const base::Value* arg_value = nullptr; |
+ ASSERT_TRUE(event->event_args->Get(0, &arg_value)); |
+ ASSERT_TRUE(arg_value); |
+ |
+ std::unique_ptr<extensions::api::lock_screen_data::DataItemsAvailableEvent> |
+ event_args = extensions::api::lock_screen_data:: |
+ DataItemsAvailableEvent::FromValue(*arg_value); |
+ ASSERT_TRUE(event_args); |
+ was_locked_values_.push_back(event_args->was_locked); |
+ } |
+ |
+ const std::vector<bool>& was_locked_values() const { |
+ return was_locked_values_; |
+ } |
+ |
+ void ClearWasLockedValues() { was_locked_values_.clear(); } |
+ |
+ private: |
+ std::vector<bool> was_locked_values_; |
+ |
+ DISALLOW_COPY_AND_ASSIGN(TestEventRouter); |
+}; |
+ |
+std::unique_ptr<KeyedService> TestEventRouterFactoryFunction( |
+ content::BrowserContext* context) { |
+ return base::MakeUnique<TestEventRouter>(context); |
+} |
+ |
+// Keeps track of all operations requested from the test data item. |
+// The operations will remain in pending state until completed by calling |
+// CompleteNextOperation. |
+// This is owned by the test class, but data items created during the test have |
+// a reference to the object. More than one data item can have a reference to |
+// this - data items with the same ID will get the same operation queue. |
+class OperationQueue { |
+ public: |
+ enum class OperationType { kWrite, kRead, kDelete }; |
+ |
+ struct PendingOperation { |
+ explicit PendingOperation(OperationType type) : type(type) {} |
+ |
+ OperationType type; |
+ // Set only for write - data to be written. |
+ std::vector<char> data; |
+ |
+ // Callback for write operation. |
+ DataItem::WriteCallback write_callback; |
+ |
+ // Callback for read operation. |
+ DataItem::ReadCallback read_callback; |
+ |
+ // Callback for delete operation. |
+ DataItem::DeleteCallback delete_callback; |
+ }; |
+ |
+ OperationQueue() = default; |
+ |
+ ~OperationQueue() = default; |
+ |
+ void AddWrite(const base::FilePath& path, |
+ const std::vector<char>& data, |
+ const DataItem::WriteCallback& callback) { |
+ ASSERT_FALSE(path.empty()); |
+ if (path_.empty()) |
+ path_ = path; |
+ ASSERT_EQ(path_, path); |
+ |
+ PendingOperation operation(OperationType::kWrite); |
+ operation.data = data; |
+ operation.write_callback = callback; |
+ |
+ pending_operations_.emplace(std::move(operation)); |
+ } |
+ |
+ void AddRead(const base::FilePath& path, |
+ const DataItem::ReadCallback& callback) { |
+ ASSERT_FALSE(path_.empty()); |
+ ASSERT_EQ(path_, path); |
+ |
+ PendingOperation operation(OperationType::kRead); |
+ operation.read_callback = callback; |
+ |
+ pending_operations_.emplace(std::move(operation)); |
+ } |
+ |
+ void AddDelete(const base::FilePath& path, |
+ const DataItem::DeleteCallback& callback) { |
+ ASSERT_FALSE(path_.empty()); |
+ ASSERT_EQ(path_, path); |
+ |
+ PendingOperation operation(OperationType::kDelete); |
+ operation.delete_callback = callback; |
+ |
+ pending_operations_.emplace(std::move(operation)); |
+ } |
+ |
+ // Completes the next pendig operation. |
+ // |expected_type| - the expected type of the next operation - this will fail |
+ // if the operation does not match. |
+ // |result| - the intended operation result. |
+ void CompleteNextOperation(OperationType expected_type, |
+ OperationResult result) { |
+ ASSERT_FALSE(pending_operations_.empty()); |
+ ASSERT_FALSE(deleted_); |
+ |
+ const PendingOperation& operation = pending_operations_.front(); |
+ |
+ ASSERT_EQ(expected_type, operation.type); |
+ |
+ switch (expected_type) { |
+ case OperationType::kWrite: { |
+ if (result == OperationResult::kSuccess) |
+ content_ = operation.data; |
+ DataItem::WriteCallback callback = operation.write_callback; |
+ pending_operations_.pop(); |
+ callback.Run(result); |
+ break; |
+ } |
+ case OperationType::kDelete: { |
+ if (result == OperationResult::kSuccess) { |
+ deleted_ = true; |
+ content_ = std::vector<char>(); |
+ } |
+ |
+ DataItem::DeleteCallback callback = operation.delete_callback; |
+ pending_operations_.pop(); |
+ callback.Run(result); |
+ break; |
+ } |
+ case OperationType::kRead: { |
+ std::unique_ptr<std::vector<char>> result_data; |
+ if (result == OperationResult::kSuccess) { |
+ result_data = base::MakeUnique<std::vector<char>>(content_.begin(), |
+ content_.end()); |
+ } |
+ |
+ DataItem::ReadCallback callback = operation.read_callback; |
+ pending_operations_.pop(); |
+ callback.Run(result, std::move(result_data)); |
+ break; |
+ } |
+ default: |
+ ADD_FAILURE() << "Unexpected operation"; |
+ return; |
+ } |
+ } |
+ |
+ bool HasPendingOperations() const { return !pending_operations_.empty(); } |
+ |
+ bool deleted() const { return deleted_; } |
+ |
+ const std::vector<char>& content() const { return content_; } |
+ |
+ const base::FilePath& path() const { return path_; } |
+ |
+ private: |
+ std::queue<PendingOperation> pending_operations_; |
+ std::vector<char> content_; |
+ bool deleted_ = false; |
+ base::FilePath path_; |
+ |
+ DISALLOW_COPY_AND_ASSIGN(OperationQueue); |
+}; |
+ |
+// Test data item - routes all requests to the OperationQueue provided through |
+// the ctor - the owning test is responsible for completing the started |
+// operations. |
+class TestDataItem : public DataItem { |
+ public: |
+ // |operations| - Operation queue used by this data item - not owned by this, |
+ // and expected to outlive this object. |
+ TestDataItem(const std::string& id, OperationQueue* operations) |
+ : DataItem(id), operations_(operations) {} |
+ |
+ ~TestDataItem() override = default; |
+ |
+ OperationResult Write( |
+ const std::vector<char>& data, |
+ const std::string& crypto_key, |
+ const scoped_refptr<base::SequencedTaskRunner>& task_runner, |
+ const WriteCallback& callback) override { |
+ if (backing_file().empty()) { |
+ ADD_FAILURE() << "Attempt to write item with unset file."; |
+ return OperationResult::kNoBackingFile; |
+ } |
+ EXPECT_EQ(kTestSymmetricKey, crypto_key); |
+ |
+ operations_->AddWrite(backing_file(), data, callback); |
+ return OperationResult::kPending; |
+ } |
+ |
+ OperationResult Read( |
+ const std::string& crypto_key, |
+ const scoped_refptr<base::SequencedTaskRunner>& task_runner, |
+ const ReadCallback& callback) override { |
+ if (backing_file().empty()) { |
+ ADD_FAILURE() << "Attempt to read item with unset file."; |
+ return OperationResult::kNoBackingFile; |
+ } |
+ |
+ EXPECT_EQ(kTestSymmetricKey, crypto_key); |
+ |
+ operations_->AddRead(backing_file(), callback); |
+ return OperationResult::kPending; |
+ } |
+ |
+ OperationResult Delete( |
+ const scoped_refptr<base::SequencedTaskRunner>& task_runner, |
+ const DeleteCallback& callback) override { |
+ if (backing_file().empty()) { |
+ ADD_FAILURE() << "Attempt to delete item with unset file."; |
+ return OperationResult::kNoBackingFile; |
+ } |
+ |
+ operations_->AddDelete(backing_file(), callback); |
+ set_backing_file(base::FilePath()); |
+ return OperationResult::kPending; |
+ } |
+ |
+ private: |
+ OperationQueue* operations_; |
+ |
+ DISALLOW_COPY_AND_ASSIGN(TestDataItem); |
+}; |
+ |
+class ItemStorageTest : public ExtensionsTest { |
+ public: |
+ ItemStorageTest() |
+ : ExtensionsTest(base::MakeUnique<content::TestBrowserThreadBundle>()) {} |
+ ~ItemStorageTest() override = default; |
+ |
+ void SetUp() override { |
+ ExtensionsTest::SetUp(); |
+ |
+ ASSERT_TRUE(test_dir_.CreateUniqueTempDir()); |
+ ItemStorage::RegisterLocalState(local_state_.registry()); |
+ user_prefs::UserPrefs::Set(browser_context(), &testing_pref_service_); |
+ extensions_browser_client()->set_lock_screen_context(&lock_screen_context_); |
+ |
+ chromeos::LoginState::Initialize(); |
+ chromeos::LoginState::Get()->SetLoggedInStateAndPrimaryUser( |
+ chromeos::LoginState::LOGGED_IN_ACTIVE, |
+ chromeos::LoginState::LOGGED_IN_USER_REGULAR, kTestUserIdHash); |
+ |
+ CreateTestExtension(); |
+ |
+ // Inject custom data item factory to be used with ItemStorage instances. |
+ item_factory_ = |
+ base::Bind(&ItemStorageTest::CreateItem, base::Unretained(this)); |
+ ItemStorage::SetItemFactoryForTesting(&item_factory_); |
+ |
+ ResetItemStorage(); |
+ } |
+ |
+ void TearDown() override { |
+ item_storage_.reset(); |
+ ItemStorage::SetItemFactoryForTesting(nullptr); |
+ chromeos::LoginState::Shutdown(); |
+ ExtensionsTest::TearDown(); |
+ } |
+ |
+ OperationQueue* GetOperations(const std::string& id) { |
+ return operations_[id].get(); |
+ } |
+ |
+ void UnsetItemStorage() { item_storage_.reset(); } |
+ |
+ void ResetItemStorage() { |
+ item_storage_.reset(); |
+ item_storage_ = |
+ base::MakeUnique<ItemStorage>(browser_context(), &local_state_, |
+ kTestSymmetricKey, test_dir_.GetPath()); |
+ } |
+ |
+ // Utility method for setting test item content. |
+ bool SetItemContent(const std::string& id, const std::vector<char>& content) { |
+ OperationQueue* item_operations = GetOperations(id); |
+ if (!item_operations) { |
+ ADD_FAILURE() << "No item operations"; |
+ return false; |
+ } |
+ OperationResult write_result = OperationResult::kFailed; |
+ if (item_storage()->SetItemContent( |
+ extension()->id(), id, content, |
+ base::Bind(&RecordWriteResult, &write_result)) != |
+ OperationResult::kPending) { |
+ ADD_FAILURE() << "Failed to initiate write"; |
+ return false; |
+ } |
+ if (!item_operations->HasPendingOperations()) { |
+ ADD_FAILURE() << "Write not registered"; |
+ return false; |
+ } |
+ item_operations->CompleteNextOperation( |
+ OperationQueue::OperationType::kWrite, OperationResult::kSuccess); |
+ EXPECT_EQ(OperationResult::kSuccess, write_result); |
+ return write_result == OperationResult::kSuccess; |
+ } |
+ |
+ // Utility method for creating a new testing data item, and setting its |
+ // content. |
+ const DataItem* CreateItemWithContent(const std::vector<char>& content) { |
+ const DataItem* item = item_storage()->CreateItem(extension()->id()); |
+ if (!item) { |
+ ADD_FAILURE() << "Item creation failed"; |
+ return nullptr; |
+ } |
+ |
+ if (!SetItemContent(item->id(), content)) |
+ return nullptr; |
+ |
+ return item; |
+ } |
+ |
+ // Finds an item with the ID |id| in list of items |items|. |
+ const DataItem* FindItem(const std::string& id, |
+ const std::vector<const DataItem*> items) { |
+ for (const auto* item : items) { |
+ if (item && item->id() == id) |
+ return item; |
+ } |
+ return nullptr; |
+ } |
+ |
+ ItemStorage* item_storage() { return item_storage_.get(); } |
+ |
+ content::BrowserContext* lock_screen_context() { |
+ return &lock_screen_context_; |
+ } |
+ |
+ const Extension* extension() const { return extension_.get(); } |
+ |
+ const base::FilePath& test_dir() const { return test_dir_.GetPath(); } |
+ |
+ PrefService* local_state() { return &local_state_; } |
+ |
+ private: |
+ void CreateTestExtension() { |
+ DictionaryBuilder app_builder; |
+ app_builder.Set("background", |
+ DictionaryBuilder() |
+ .Set("scripts", ListBuilder().Append("script").Build()) |
+ .Build()); |
+ ListBuilder app_handlers_builder; |
+ app_handlers_builder.Append(DictionaryBuilder() |
+ .Set("action", "new_note") |
+ .SetBoolean("enabled_on_lock_screen", true) |
+ .Build()); |
+ extension_ = |
+ ExtensionBuilder() |
+ .SetManifest( |
+ DictionaryBuilder() |
+ .Set("name", "Test app") |
+ .Set("version", "1.0") |
+ .Set("manifest_version", 2) |
+ .Set("app", app_builder.Build()) |
+ .Set("action_handlers", app_handlers_builder.Build()) |
+ .Set("permissions", |
+ ListBuilder().Append("lockScreen").Build()) |
+ .Build()) |
+ .Build(); |
+ ExtensionRegistry::Get(browser_context())->AddEnabled(extension_); |
+ } |
+ |
+ // Callback for creating test data items - this is the callback passed to |
+ // ItemStorage via SetItemFactoryForTesting. |
+ std::unique_ptr<DataItem> CreateItem(const std::string& id) { |
+ // If there is an operation queue for the item id, reuse it in order to |
+ // retain state on ItemStorage restart. |
+ OperationQueue* operation_queue = GetOperations(id); |
+ if (!operation_queue) { |
+ operations_[id] = base::MakeUnique<OperationQueue>(); |
+ operation_queue = operations_[id].get(); |
+ } |
+ return base::MakeUnique<TestDataItem>(id, operation_queue); |
+ } |
+ |
+ std::unique_ptr<ItemStorage> item_storage_; |
+ |
+ content::TestBrowserContext lock_screen_context_; |
+ TestingPrefServiceSimple local_state_; |
+ |
+ base::ScopedTempDir test_dir_; |
+ |
+ sync_preferences::TestingPrefServiceSyncable testing_pref_service_; |
+ |
+ ItemStorage::ItemFactoryCallback item_factory_; |
+ |
+ scoped_refptr<const Extension> extension_; |
+ |
+ std::map<std::string, std::unique_ptr<OperationQueue>> operations_; |
+ |
+ DISALLOW_COPY_AND_ASSIGN(ItemStorageTest); |
+}; |
+ |
+} // namespace |
+ |
+TEST_F(ItemStorageTest, GetDependingOnSessionState) { |
+ // Session state not initialized. |
+ EXPECT_FALSE(ItemStorage::Get(browser_context())); |
+ EXPECT_FALSE(ItemStorage::Get(lock_screen_context())); |
+ |
+ // Locked session. |
+ item_storage()->SetSessionLocked(true); |
+ EXPECT_FALSE(ItemStorage::Get(browser_context())); |
+ EXPECT_EQ(item_storage(), ItemStorage::Get(lock_screen_context())); |
+ |
+ item_storage()->SetSessionLocked(false); |
+ |
+ EXPECT_EQ(item_storage(), ItemStorage::Get(browser_context())); |
+ EXPECT_FALSE(ItemStorage::Get(lock_screen_context())); |
+} |
+ |
+TEST_F(ItemStorageTest, SetAndGetContent) { |
+ item_storage()->SetSessionLocked(true); |
+ |
+ const DataItem* item = item_storage()->CreateItem(extension()->id()); |
+ ASSERT_TRUE(item); |
+ |
+ std::vector<const DataItem*> all_items = |
+ item_storage()->GetAllForExtension(extension()->id()); |
+ ASSERT_EQ(1u, all_items.size()); |
+ EXPECT_EQ(item->id(), all_items[0]->id()); |
+ |
+ OperationQueue* item_operations = GetOperations(item->id()); |
+ ASSERT_TRUE(item_operations); |
+ EXPECT_FALSE(item_operations->HasPendingOperations()); |
+ |
+ std::vector<char> content = {'f', 'i', 'l', 'e'}; |
+ OperationResult write_result = OperationResult::kFailed; |
+ EXPECT_EQ(OperationResult::kPending, |
+ item_storage()->SetItemContent( |
+ extension()->id(), item->id(), content, |
+ base::Bind(&RecordWriteResult, &write_result))); |
+ |
+ EXPECT_FALSE(item->backing_file().empty()); |
+ EXPECT_TRUE(test_dir() |
+ .AppendASCII(kTestUserIdHash) |
+ .AppendASCII(extension()->id()) |
+ .IsParent(item->backing_file())); |
+ |
+ item_operations->CompleteNextOperation(OperationQueue::OperationType::kWrite, |
+ OperationResult::kSuccess); |
+ |
+ EXPECT_EQ(OperationResult::kSuccess, write_result); |
+ EXPECT_EQ(content, item_operations->content()); |
+ |
+ OperationResult read_result = OperationResult::kFailed; |
+ std::unique_ptr<std::vector<char>> read_content; |
+ |
+ EXPECT_EQ(OperationResult::kPending, |
+ item_storage()->GetItemContent( |
+ extension()->id(), item->id(), |
+ base::Bind(&RecordReadResult, &read_result, &read_content))); |
+ |
+ item_operations->CompleteNextOperation(OperationQueue::OperationType::kRead, |
+ OperationResult::kSuccess); |
+ EXPECT_EQ(OperationResult::kSuccess, read_result); |
+ EXPECT_EQ(content, *read_content); |
+ |
+ item_storage()->DeleteItem(extension()->id(), item->id()); |
+ |
+ item_operations->CompleteNextOperation(OperationQueue::OperationType::kDelete, |
+ OperationResult::kSuccess); |
+ EXPECT_TRUE(item_operations->deleted()); |
+} |
+ |
+TEST_F(ItemStorageTest, HandleNonExistent) { |
+ item_storage()->SetSessionLocked(true); |
+ |
+ const DataItem* item = item_storage()->CreateItem(extension()->id()); |
+ ASSERT_TRUE(item); |
+ |
+ std::vector<char> content = {'x'}; |
+ EXPECT_EQ( |
+ OperationResult::kNotFound, |
+ item_storage()->SetItemContent(extension()->id(), "non_existent", content, |
+ base::Bind(&WriteNotCalled))); |
+ EXPECT_EQ(OperationResult::kNotFound, |
+ item_storage()->SetItemContent("non_existent", item->id(), content, |
+ base::Bind(&WriteNotCalled))); |
+ |
+ EXPECT_EQ(OperationResult::kNotFound, |
+ item_storage()->GetItemContent(extension()->id(), "non_existent", |
+ base::Bind(&ReadNotCalled))); |
+ EXPECT_EQ(OperationResult::kNotFound, |
+ item_storage()->GetItemContent("non_existent", item->id(), |
+ base::Bind(&ReadNotCalled))); |
+ |
+ EXPECT_EQ(OperationResult::kNotFound, |
+ item_storage()->DeleteItem(extension()->id(), "non_existen")); |
+ EXPECT_EQ(OperationResult::kNotFound, |
+ item_storage()->DeleteItem("non_existent", item->id())); |
+} |
+ |
+TEST_F(ItemStorageTest, HandleFailure) { |
+ item_storage()->SetSessionLocked(true); |
+ |
+ const DataItem* item = CreateItemWithContent({'x'}); |
+ ASSERT_TRUE(item); |
+ OperationQueue* operations = GetOperations(item->id()); |
+ ASSERT_TRUE(operations); |
+ |
+ OperationResult write_result = OperationResult::kFailed; |
+ EXPECT_EQ(OperationResult::kPending, |
+ item_storage()->SetItemContent( |
+ extension()->id(), item->id(), {'x'}, |
+ base::Bind(&RecordWriteResult, &write_result))); |
+ operations->CompleteNextOperation(OperationQueue::OperationType::kWrite, |
+ OperationResult::kInvalidKey); |
+ EXPECT_EQ(OperationResult::kInvalidKey, write_result); |
+ |
+ OperationResult read_result = OperationResult::kFailed; |
+ std::unique_ptr<std::vector<char>> read_content; |
+ EXPECT_EQ(OperationResult::kPending, |
+ item_storage()->GetItemContent( |
+ extension()->id(), item->id(), |
+ base::Bind(&RecordReadResult, &read_result, &read_content))); |
+ operations->CompleteNextOperation(OperationQueue::OperationType::kRead, |
+ OperationResult::kWrongKey); |
+ EXPECT_EQ(OperationResult::kWrongKey, read_result); |
+ EXPECT_FALSE(read_content); |
+ |
+ EXPECT_FALSE(operations->HasPendingOperations()); |
+} |
+ |
+TEST_F(ItemStorageTest, GetUnsetContent) { |
+ item_storage()->SetSessionLocked(true); |
+ |
+ const DataItem* item = item_storage()->CreateItem(extension()->id()); |
+ ASSERT_TRUE(item); |
+ |
+ EXPECT_EQ(OperationResult::kNoBackingFile, |
+ item_storage()->GetItemContent(extension()->id(), item->id(), |
+ base::Bind(&ReadNotCalled))); |
+ OperationQueue* operations = GetOperations(item->id()); |
+ ASSERT_TRUE(operations); |
+ EXPECT_FALSE(operations->HasPendingOperations()); |
+} |
+ |
+TEST_F(ItemStorageTest, ItemPersistence) { |
+ item_storage()->SetSessionLocked(true); |
+ |
+ const DataItem* first_item = CreateItemWithContent({'f', 'i', 'l', 'e', '1'}); |
+ ASSERT_TRUE(first_item); |
+ const std::string first_id = first_item->id(); |
+ const base::FilePath first_file = first_item->backing_file(); |
+ |
+ const DataItem* second_item = |
+ CreateItemWithContent({'f', 'i', 'l', 'e', '2'}); |
+ ASSERT_TRUE(second_item); |
+ const std::string second_id = second_item->id(); |
+ const base::FilePath second_file = second_item->backing_file(); |
+ |
+ const DataItem* empty_item = item_storage()->CreateItem(extension()->id()); |
+ ASSERT_TRUE(empty_item); |
+ const std::string empty_id = empty_item->id(); |
+ |
+ const DataItem* deleted_item = CreateItemWithContent({'x'}); |
+ ASSERT_TRUE(deleted_item); |
+ EXPECT_EQ(OperationResult::kSuccess, |
+ item_storage()->DeleteItem(extension()->id(), deleted_item->id())); |
+ |
+ ResetItemStorage(); |
+ |
+ // Items that have been written should have been restored, unlike the empty |
+ // one. |
+ std::vector<const DataItem*> items = |
+ item_storage()->GetAllForExtension(extension()->id()); |
+ ASSERT_EQ(3u, items.size()); |
+ |
+ const DataItem* first_recovered = FindItem(first_id, items); |
+ ASSERT_TRUE(first_recovered); |
+ EXPECT_EQ(first_recovered->backing_file(), first_file); |
+ |
+ const DataItem* second_recovered = FindItem(second_id, items); |
+ EXPECT_EQ(second_recovered->backing_file(), second_file); |
+ |
+ const DataItem* empty_recovered = FindItem(empty_id, items); |
+ EXPECT_TRUE(empty_recovered->backing_file().empty()); |
+} |
+ |
+TEST_F(ItemStorageTest, ExtensionUninstall) { |
+ item_storage()->SetSessionLocked(true); |
+ |
+ const DataItem* item = CreateItemWithContent({'f', 'i', 'l', 'e', '1'}); |
+ const base::FilePath item_path = item->backing_file(); |
+ |
+ // Create a backing file to verify it gets deleted on extension install. |
+ ASSERT_TRUE(base::CreateDirectoryAndGetError( |
+ test_dir().AppendASCII(kTestUserIdHash).AppendASCII(extension()->id()), |
+ nullptr)); |
+ ASSERT_EQ(5, base::WriteFile(item->backing_file(), "file1", 5)); |
+ |
+ ExtensionRegistry::Get(browser_context())->RemoveEnabled(extension()->id()); |
+ ExtensionRegistry::Get(browser_context()) |
+ ->TriggerOnUninstalled(extension(), UNINSTALL_REASON_FOR_TESTING); |
+ |
+ // Drain task loop. |
+ base::RunLoop run_loop; |
+ item_storage()->task_runner_for_testing()->PostTaskAndReply( |
+ FROM_HERE, base::Bind(&base::DoNothing), run_loop.QuitClosure()); |
+ run_loop.Run(); |
+ |
+ EXPECT_FALSE(base::PathExists(item_path)); |
+ EXPECT_FALSE(item_storage()->CreateItem(extension()->id())); |
+ EXPECT_TRUE(item_storage()->GetAllForExtension(extension()->id()).empty()); |
+ |
+ ResetItemStorage(); |
+ item_storage()->SetSessionLocked(true); |
+ |
+ EXPECT_TRUE(item_storage()->GetAllForExtension(extension()->id()).empty()); |
+} |
+ |
+TEST_F(ItemStorageTest, ExtensionUninstallWhileStorageNotSet) { |
+ item_storage()->SetSessionLocked(true); |
+ |
+ const DataItem* item = CreateItemWithContent({'f', 'i', 'l', 'e', '1'}); |
+ const base::FilePath item_path = item->backing_file(); |
+ |
+ // Create a backing file to verify it gets deleted on extension install. |
+ ASSERT_TRUE(base::CreateDirectoryAndGetError( |
+ test_dir().AppendASCII(kTestUserIdHash).AppendASCII(extension()->id()), |
+ nullptr)); |
+ ASSERT_EQ(5, base::WriteFile(item->backing_file(), "file1", 5)); |
+ |
+ UnsetItemStorage(); |
+ |
+ ExtensionRegistry::Get(browser_context())->RemoveEnabled(extension()->id()); |
+ ExtensionRegistry::Get(browser_context()) |
+ ->TriggerOnUninstalled(extension(), UNINSTALL_REASON_FOR_TESTING); |
+ |
+ ResetItemStorage(); |
+ |
+ // Drain task loop. |
+ base::RunLoop run_loop; |
+ item_storage()->task_runner_for_testing()->PostTaskAndReply( |
+ FROM_HERE, base::Bind(&base::DoNothing), run_loop.QuitClosure()); |
+ run_loop.Run(); |
+ |
+ EXPECT_FALSE(item_storage()->CreateItem(extension()->id())); |
+ EXPECT_TRUE(item_storage()->GetAllForExtension(extension()->id()).empty()); |
+ EXPECT_FALSE(item_storage()->CreateItem(extension()->id())); |
+} |
+ |
+TEST_F(ItemStorageTest, ReloadWithCorruptedLocalState) { |
+ item_storage()->SetSessionLocked(true); |
+ |
+ const DataItem* item = CreateItemWithContent({'f', 'i', 'l', 'e', '1'}); |
+ const base::FilePath item_path = item->backing_file(); |
+ const std::string item_id = item->id(); |
+ |
+ // Create a backing file to verify it gets deleted on extension install. |
+ ASSERT_TRUE(base::CreateDirectoryAndGetError( |
+ test_dir().AppendASCII(kTestUserIdHash).AppendASCII(extension()->id()), |
+ nullptr)); |
+ ASSERT_EQ(5, base::WriteFile(item->backing_file(), "file1", 5)); |
+ |
+ UnsetItemStorage(); |
+ |
+ { |
+ DictionaryPrefUpdate update(local_state(), kDataItemsPrefKey); |
+ update->SetString( |
+ base::StringPrintf("%s.%s", kTestUserIdHash, extension()->id().c_str()), |
+ "invalid"); |
+ } |
+ |
+ ResetItemStorage(); |
+ |
+ // Drain task loop. |
+ base::RunLoop run_loop; |
+ item_storage()->task_runner_for_testing()->PostTaskAndReply( |
+ FROM_HERE, base::Bind(&base::DoNothing), run_loop.QuitClosure()); |
+ run_loop.Run(); |
+ |
+ EXPECT_TRUE(item_storage()->GetAllForExtension(extension()->id()).empty()); |
+} |
+ |
+TEST_F(ItemStorageTest, ReloadWithCorruptedItemInLocalState) { |
+ item_storage()->SetSessionLocked(true); |
+ |
+ const DataItem* item = CreateItemWithContent({'f', 'i', 'l', 'e', '1'}); |
+ const std::string item_id = item->id(); |
+ |
+ const DataItem* corrupted_item = |
+ CreateItemWithContent({'f', 'i', 'l', 'e', '2'}); |
+ const std::string corrupted_item_id = corrupted_item->id(); |
+ |
+ UnsetItemStorage(); |
+ |
+ { |
+ DictionaryPrefUpdate update(local_state(), kDataItemsPrefKey); |
+ update->SetInteger( |
+ base::StringPrintf("%s.%s.%s.%s", kTestUserIdHash, |
+ extension()->id().c_str(), corrupted_item_id.c_str(), |
+ kDataItemIdKey), |
+ 123456); |
+ } |
+ |
+ ResetItemStorage(); |
+ |
+ // Drain task loop. |
+ base::RunLoop run_loop; |
+ item_storage()->task_runner_for_testing()->PostTaskAndReply( |
+ FROM_HERE, base::Bind(&base::DoNothing), run_loop.QuitClosure()); |
+ run_loop.Run(); |
+ |
+ std::vector<const DataItem*> items = |
+ item_storage()->GetAllForExtension(extension()->id()); |
+ ASSERT_EQ(1u, items.size()); |
+ EXPECT_EQ(item_id, items[0]->id()); |
+} |
+ |
+TEST_F(ItemStorageTest, ReloadWithWrongPathInLocalState) { |
+ item_storage()->SetSessionLocked(true); |
+ |
+ const DataItem* item = CreateItemWithContent({'f', 'i', 'l', 'e', '1'}); |
+ const std::string item_id = item->id(); |
+ |
+ const DataItem* corrupted_item = |
+ CreateItemWithContent({'f', 'i', 'l', 'e', '2'}); |
+ const std::string corrupted_item_id = corrupted_item->id(); |
+ |
+ UnsetItemStorage(); |
+ |
+ { |
+ // Set local state item path to a path that is not allowed - i.e. that is |
+ // not under storage root. |
+ DictionaryPrefUpdate update(local_state(), kDataItemsPrefKey); |
+ update->SetString( |
+ base::StringPrintf("%s.%s.%s.%s", kTestUserIdHash, |
+ extension()->id().c_str(), corrupted_item_id.c_str(), |
+ kDataItemFileKey), |
+ "/home/chronos/user/file"); |
+ } |
+ |
+ ResetItemStorage(); |
+ |
+ // Drain task loop. |
+ base::RunLoop run_loop; |
+ item_storage()->task_runner_for_testing()->PostTaskAndReply( |
+ FROM_HERE, base::Bind(&base::DoNothing), run_loop.QuitClosure()); |
+ run_loop.Run(); |
+ |
+ std::vector<const DataItem*> items = |
+ item_storage()->GetAllForExtension(extension()->id()); |
+ ASSERT_EQ(1u, items.size()); |
+ EXPECT_EQ(item_id, items[0]->id()); |
+} |
+ |
+TEST_F(ItemStorageTest, DataItemsAvailableEventOnUnlock) { |
+ TestEventRouter* event_router = static_cast<TestEventRouter*>( |
+ extensions::EventRouterFactory::GetInstance()->SetTestingFactoryAndUse( |
+ browser_context(), &TestEventRouterFactoryFunction)); |
+ ASSERT_TRUE(event_router); |
+ |
+ EXPECT_TRUE(event_router->was_locked_values().empty()); |
+ |
+ item_storage()->SetSessionLocked(true); |
+ EXPECT_TRUE(event_router->was_locked_values().empty()); |
+ |
+ // No event since no data items associated with the app exist. |
+ item_storage()->SetSessionLocked(false); |
+ EXPECT_TRUE(event_router->was_locked_values().empty()); |
+ |
+ item_storage()->SetSessionLocked(true); |
+ const DataItem* item = CreateItemWithContent({'f', 'i', 'l', 'e', '1'}); |
+ const std::string item_id = item->id(); |
+ EXPECT_TRUE(event_router->was_locked_values().empty()); |
+ |
+ // There's an available data item, so unlock should trigger the event. |
+ item_storage()->SetSessionLocked(false); |
+ EXPECT_EQ(std::vector<bool>({true}), event_router->was_locked_values()); |
+ event_router->ClearWasLockedValues(); |
+ |
+ // Update the item content while the session is unlocked. |
+ EXPECT_TRUE(SetItemContent(item_id, {'f', 'i', 'l', 'e', '2'})); |
+ |
+ item_storage()->SetSessionLocked(true); |
+ |
+ // Data item is still around - notify the app it's available. |
+ item_storage()->SetSessionLocked(false); |
+ EXPECT_EQ(std::vector<bool>({true}), event_router->was_locked_values()); |
+ event_router->ClearWasLockedValues(); |
+ |
+ item_storage()->SetSessionLocked(true); |
+ |
+ EXPECT_TRUE(SetItemContent(item_id, {'f', 'i', 'l', 'e', '3'})); |
+ |
+ item_storage()->SetSessionLocked(false); |
+ EXPECT_EQ(std::vector<bool>({true}), event_router->was_locked_values()); |
+ event_router->ClearWasLockedValues(); |
+ |
+ // When the item is deleted, the data item avilable event should stop firing. |
+ EXPECT_EQ(OperationResult::kSuccess, |
+ item_storage()->DeleteItem(extension()->id(), item_id)); |
+ OperationQueue* operations = GetOperations(item_id); |
+ ASSERT_TRUE(operations); |
+ operations->CompleteNextOperation(OperationQueue::OperationType::kDelete, |
+ OperationResult::kSuccess); |
+ item_storage()->SetSessionLocked(false); |
+ item_storage()->SetSessionLocked(true); |
+ |
+ EXPECT_TRUE(event_router->was_locked_values().empty()); |
+} |
+ |
+TEST_F(ItemStorageTest, DataItemsAvailableEventOnRestart) { |
+ TestEventRouter* event_router = static_cast<TestEventRouter*>( |
+ extensions::EventRouterFactory::GetInstance()->SetTestingFactoryAndUse( |
+ browser_context(), &TestEventRouterFactoryFunction)); |
+ ASSERT_TRUE(event_router); |
+ |
+ EXPECT_TRUE(event_router->was_locked_values().empty()); |
+ |
+ item_storage()->SetSessionLocked(true); |
+ EXPECT_TRUE(event_router->was_locked_values().empty()); |
+ |
+ const DataItem* item = CreateItemWithContent({'f', 'i', 'l', 'e', '1'}); |
+ EXPECT_TRUE(event_router->was_locked_values().empty()); |
+ const std::string item_id = item->id(); |
+ |
+ ResetItemStorage(); |
+ |
+ EXPECT_TRUE(event_router->was_locked_values().empty()); |
+ item_storage()->SetSessionLocked(false); |
+ |
+ EXPECT_EQ(std::vector<bool>({false}), event_router->was_locked_values()); |
+ event_router->ClearWasLockedValues(); |
+ |
+ // The event should be dispatched on next unlock event, as long as a valid |
+ // item exists. |
+ ResetItemStorage(); |
+ item_storage()->SetSessionLocked(false); |
+ |
+ EXPECT_EQ(std::vector<bool>({false}), event_router->was_locked_values()); |
+ event_router->ClearWasLockedValues(); |
+ |
+ ResetItemStorage(); |
+ |
+ EXPECT_EQ(OperationResult::kSuccess, |
+ item_storage()->DeleteItem(extension()->id(), item_id)); |
+ OperationQueue* operations = GetOperations(item_id); |
+ ASSERT_TRUE(operations); |
+ operations->CompleteNextOperation(OperationQueue::OperationType::kDelete, |
+ OperationResult::kSuccess); |
+ |
+ item_storage()->SetSessionLocked(false); |
+ EXPECT_TRUE(event_router->was_locked_values().empty()); |
+} |
+ |
+} // namespace lock_screen_data |
+} // namespace extensions |