1 // Copyright 2015 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 "chrome/browser/chromeos/file_system_provider/operations/get_actions.h"
6 
7 #include <memory>
8 #include <string>
9 #include <utility>
10 #include <vector>
11 
12 #include "base/bind.h"
13 #include "base/files/file.h"
14 #include "base/files/file_path.h"
15 #include "base/json/json_reader.h"
16 #include "base/macros.h"
17 #include "base/values.h"
18 #include "chrome/browser/chromeos/file_system_provider/icon_set.h"
19 #include "chrome/browser/chromeos/file_system_provider/operations/get_metadata.h"
20 #include "chrome/browser/chromeos/file_system_provider/operations/test_util.h"
21 #include "chrome/common/extensions/api/file_system_provider.h"
22 #include "chrome/common/extensions/api/file_system_provider_capabilities/file_system_provider_capabilities_handler.h"
23 #include "chrome/common/extensions/api/file_system_provider_internal.h"
24 #include "extensions/browser/event_router.h"
25 #include "storage/browser/file_system/async_file_util.h"
26 #include "testing/gtest/include/gtest/gtest.h"
27 
28 namespace chromeos {
29 namespace file_system_provider {
30 namespace operations {
31 namespace {
32 
33 const char kExtensionId[] = "mbflcebpggnecokmikipoihdbecnjfoj";
34 const char kFileSystemId[] = "testing-file-system";
35 const int kRequestId = 2;
36 const base::FilePath::CharType kDirectoryPath[] =
37     FILE_PATH_LITERAL("/directory");
38 const base::FilePath::CharType kFilePath[] = FILE_PATH_LITERAL("/file");
39 
40 // Callback invocation logger. Acts as a fileapi end-point.
41 class CallbackLogger {
42  public:
43   class Event {
44    public:
Event(const Actions & actions,base::File::Error result)45     Event(const Actions& actions, base::File::Error result)
46         : actions_(actions), result_(result) {}
~Event()47     virtual ~Event() {}
48 
actions() const49     const Actions& actions() const { return actions_; }
result() const50     base::File::Error result() const { return result_; }
51 
52    private:
53     Actions actions_;
54     base::File::Error result_;
55 
56     DISALLOW_COPY_AND_ASSIGN(Event);
57   };
58 
CallbackLogger()59   CallbackLogger() {}
~CallbackLogger()60   virtual ~CallbackLogger() {}
61 
OnGetActions(const Actions & actions,base::File::Error result)62   void OnGetActions(const Actions& actions, base::File::Error result) {
63     events_.push_back(std::make_unique<Event>(actions, result));
64   }
65 
events() const66   const std::vector<std::unique_ptr<Event>>& events() const { return events_; }
67 
68  private:
69   std::vector<std::unique_ptr<Event>> events_;
70 
71   DISALLOW_COPY_AND_ASSIGN(CallbackLogger);
72 };
73 
74 // Returns the request value as |result| in case of successful parse.
CreateRequestValueFromJSON(const std::string & json,std::unique_ptr<RequestValue> * result)75 void CreateRequestValueFromJSON(const std::string& json,
76                                 std::unique_ptr<RequestValue>* result) {
77   using extensions::api::file_system_provider_internal::
78       GetActionsRequestedSuccess::Params;
79 
80   base::JSONReader::ValueWithError parsed_json =
81       base::JSONReader::ReadAndReturnValueWithError(json);
82   ASSERT_TRUE(parsed_json.value) << parsed_json.error_message;
83 
84   base::ListValue* value_as_list;
85   ASSERT_TRUE(parsed_json.value->GetAsList(&value_as_list));
86   std::unique_ptr<Params> params(Params::Create(*value_as_list));
87   ASSERT_TRUE(params.get());
88   *result = RequestValue::CreateForGetActionsSuccess(std::move(params));
89   ASSERT_TRUE(result->get());
90 }
91 
92 }  // namespace
93 
94 class FileSystemProviderOperationsGetActionsTest : public testing::Test {
95  protected:
FileSystemProviderOperationsGetActionsTest()96   FileSystemProviderOperationsGetActionsTest() {}
~FileSystemProviderOperationsGetActionsTest()97   ~FileSystemProviderOperationsGetActionsTest() override {}
98 
SetUp()99   void SetUp() override {
100     file_system_info_ = ProvidedFileSystemInfo(
101         kExtensionId, MountOptions(kFileSystemId, "" /* display_name */),
102         base::FilePath(), false /* configurable */, true /* watchable */,
103         extensions::SOURCE_FILE, IconSet());
104     entry_paths_.clear();
105     entry_paths_.push_back(base::FilePath(kDirectoryPath));
106     entry_paths_.push_back(base::FilePath(kFilePath));
107   }
108 
109   ProvidedFileSystemInfo file_system_info_;
110   std::vector<base::FilePath> entry_paths_;
111 };
112 
TEST_F(FileSystemProviderOperationsGetActionsTest,Execute)113 TEST_F(FileSystemProviderOperationsGetActionsTest, Execute) {
114   using extensions::api::file_system_provider::GetActionsRequestedOptions;
115 
116   util::LoggingDispatchEventImpl dispatcher(true /* dispatch_reply */);
117   CallbackLogger callback_logger;
118 
119   GetActions get_actions(NULL, file_system_info_, entry_paths_,
120                          base::Bind(&CallbackLogger::OnGetActions,
121                                     base::Unretained(&callback_logger)));
122   get_actions.SetDispatchEventImplForTesting(
123       base::Bind(&util::LoggingDispatchEventImpl::OnDispatchEventImpl,
124                  base::Unretained(&dispatcher)));
125 
126   EXPECT_TRUE(get_actions.Execute(kRequestId));
127 
128   ASSERT_EQ(1u, dispatcher.events().size());
129   extensions::Event* event = dispatcher.events()[0].get();
130   EXPECT_EQ(
131       extensions::api::file_system_provider::OnGetActionsRequested::kEventName,
132       event->event_name);
133   base::ListValue* event_args = event->event_args.get();
134   ASSERT_EQ(1u, event_args->GetSize());
135 
136   const base::DictionaryValue* options_as_value = NULL;
137   ASSERT_TRUE(event_args->GetDictionary(0, &options_as_value));
138 
139   GetActionsRequestedOptions options;
140   ASSERT_TRUE(
141       GetActionsRequestedOptions::Populate(*options_as_value, &options));
142   EXPECT_EQ(kFileSystemId, options.file_system_id);
143   EXPECT_EQ(kRequestId, options.request_id);
144   ASSERT_EQ(entry_paths_.size(), options.entry_paths.size());
145   EXPECT_EQ(entry_paths_[0].value(), options.entry_paths[0]);
146   EXPECT_EQ(entry_paths_[1].value(), options.entry_paths[1]);
147 }
148 
TEST_F(FileSystemProviderOperationsGetActionsTest,Execute_NoListener)149 TEST_F(FileSystemProviderOperationsGetActionsTest, Execute_NoListener) {
150   util::LoggingDispatchEventImpl dispatcher(false /* dispatch_reply */);
151   CallbackLogger callback_logger;
152 
153   GetActions get_actions(NULL, file_system_info_, entry_paths_,
154                          base::Bind(&CallbackLogger::OnGetActions,
155                                     base::Unretained(&callback_logger)));
156   get_actions.SetDispatchEventImplForTesting(
157       base::Bind(&util::LoggingDispatchEventImpl::OnDispatchEventImpl,
158                  base::Unretained(&dispatcher)));
159 
160   EXPECT_FALSE(get_actions.Execute(kRequestId));
161 }
162 
TEST_F(FileSystemProviderOperationsGetActionsTest,OnSuccess)163 TEST_F(FileSystemProviderOperationsGetActionsTest, OnSuccess) {
164   util::LoggingDispatchEventImpl dispatcher(true /* dispatch_reply */);
165   CallbackLogger callback_logger;
166 
167   GetActions get_actions(NULL, file_system_info_, entry_paths_,
168                          base::Bind(&CallbackLogger::OnGetActions,
169                                     base::Unretained(&callback_logger)));
170   get_actions.SetDispatchEventImplForTesting(
171       base::Bind(&util::LoggingDispatchEventImpl::OnDispatchEventImpl,
172                  base::Unretained(&dispatcher)));
173 
174   EXPECT_TRUE(get_actions.Execute(kRequestId));
175 
176   // Sample input as JSON. Keep in sync with file_system_provider_api.idl.
177   // As for now, it is impossible to create *::Params class directly, not from
178   // base::Value.
179   const std::string input =
180       "[\n"
181       "  \"testing-file-system\",\n"  // kFileSystemId
182       "  2,\n"                        // kRequestId
183       "  [\n"
184       "    {\n"
185       "      \"id\": \"SAVE_FOR_OFFLINE\"\n"
186       "    },\n"
187       "    {\n"
188       "      \"id\": \"OFFLINE_NOT_NECESSARY\",\n"
189       "      \"title\": \"Ignored title.\"\n"
190       "    },\n"
191       "    {\n"
192       "      \"id\": \"SomeCustomActionId\",\n"
193       "      \"title\": \"Custom action.\"\n"
194       "    }\n"
195       "  ],\n"
196       "  0\n"  // execution_time
197       "]\n";
198   std::unique_ptr<RequestValue> request_value;
199   ASSERT_NO_FATAL_FAILURE(CreateRequestValueFromJSON(input, &request_value));
200 
201   const bool has_more = false;
202   get_actions.OnSuccess(kRequestId, std::move(request_value), has_more);
203 
204   ASSERT_EQ(1u, callback_logger.events().size());
205   CallbackLogger::Event* event = callback_logger.events()[0].get();
206   EXPECT_EQ(base::File::FILE_OK, event->result());
207 
208   ASSERT_EQ(3u, event->actions().size());
209   const Action action_share = event->actions()[0];
210   EXPECT_EQ("SAVE_FOR_OFFLINE", action_share.id);
211   EXPECT_EQ("", action_share.title);
212 
213   const Action action_pin_toggle = event->actions()[1];
214   EXPECT_EQ("OFFLINE_NOT_NECESSARY", action_pin_toggle.id);
215   EXPECT_EQ("Ignored title.", action_pin_toggle.title);
216 
217   const Action action_custom = event->actions()[2];
218   EXPECT_EQ("SomeCustomActionId", action_custom.id);
219   EXPECT_EQ("Custom action.", action_custom.title);
220 }
221 
TEST_F(FileSystemProviderOperationsGetActionsTest,OnError)222 TEST_F(FileSystemProviderOperationsGetActionsTest, OnError) {
223   util::LoggingDispatchEventImpl dispatcher(true /* dispatch_reply */);
224   CallbackLogger callback_logger;
225 
226   GetActions get_actions(NULL, file_system_info_, entry_paths_,
227                          base::Bind(&CallbackLogger::OnGetActions,
228                                     base::Unretained(&callback_logger)));
229   get_actions.SetDispatchEventImplForTesting(
230       base::Bind(&util::LoggingDispatchEventImpl::OnDispatchEventImpl,
231                  base::Unretained(&dispatcher)));
232 
233   EXPECT_TRUE(get_actions.Execute(kRequestId));
234 
235   get_actions.OnError(kRequestId,
236                       std::unique_ptr<RequestValue>(new RequestValue()),
237                       base::File::FILE_ERROR_TOO_MANY_OPENED);
238 
239   ASSERT_EQ(1u, callback_logger.events().size());
240   CallbackLogger::Event* event = callback_logger.events()[0].get();
241   EXPECT_EQ(base::File::FILE_ERROR_TOO_MANY_OPENED, event->result());
242   ASSERT_EQ(0u, event->actions().size());
243 }
244 
245 }  // namespace operations
246 }  // namespace file_system_provider
247 }  // namespace chromeos
248