Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(348)

Side by Side Diff: content/browser/fileapi/file_system_dir_url_request_job_unittest.cc

Issue 2813353003: Move some File API backend unit tests next to the files that they cover. (Closed)
Patch Set: Created 3 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2013 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 <stdint.h>
6 #include <string>
7 #include <utility>
8
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/format_macros.h"
13 #include "base/location.h"
14 #include "base/memory/ptr_util.h"
15 #include "base/memory/weak_ptr.h"
16 #include "base/run_loop.h"
17 #include "base/single_thread_task_runner.h"
18 #include "base/strings/string_piece.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/threading/thread_task_runner_handle.h"
21 #include "build/build_config.h"
22 #include "net/base/net_errors.h"
23 #include "net/base/request_priority.h"
24 #include "net/http/http_request_headers.h"
25 #include "net/url_request/url_request.h"
26 #include "net/url_request/url_request_context.h"
27 #include "net/url_request/url_request_test_util.h"
28 #include "storage/browser/fileapi/external_mount_points.h"
29 #include "storage/browser/fileapi/file_system_context.h"
30 #include "storage/browser/fileapi/file_system_dir_url_request_job.h"
31 #include "storage/browser/fileapi/file_system_file_util.h"
32 #include "storage/browser/fileapi/file_system_operation_context.h"
33 #include "storage/browser/fileapi/file_system_url.h"
34 #include "storage/browser/test/mock_special_storage_policy.h"
35 #include "storage/browser/test/test_file_system_backend.h"
36 #include "storage/browser/test/test_file_system_context.h"
37 #include "testing/gtest/include/gtest/gtest.h"
38 #include "third_party/icu/source/i18n/unicode/datefmt.h"
39 #include "third_party/icu/source/i18n/unicode/regex.h"
40
41 using storage::FileSystemContext;
42 using storage::FileSystemOperationContext;
43 using storage::FileSystemURL;
44
45 namespace content {
46 namespace {
47
48 // We always use the TEMPORARY FileSystem in this test.
49 const char kFileSystemURLPrefix[] = "filesystem:http://remote/temporary/";
50
51 const char kValidExternalMountPoint[] = "mnt_name";
52
53 // An auto mounter that will try to mount anything for |storage_domain| =
54 // "automount", but will only succeed for the mount point "mnt_name".
55 bool TestAutoMountForURLRequest(
56 const net::URLRequest* /*url_request*/,
57 const storage::FileSystemURL& filesystem_url,
58 const std::string& storage_domain,
59 const base::Callback<void(base::File::Error result)>& callback) {
60 if (storage_domain != "automount")
61 return false;
62
63 std::vector<base::FilePath::StringType> components;
64 filesystem_url.path().GetComponents(&components);
65 std::string mount_point = base::FilePath(components[0]).AsUTF8Unsafe();
66
67 if (mount_point == kValidExternalMountPoint) {
68 storage::ExternalMountPoints::GetSystemInstance()->RegisterFileSystem(
69 kValidExternalMountPoint,
70 storage::kFileSystemTypeTest,
71 storage::FileSystemMountOption(),
72 base::FilePath());
73 callback.Run(base::File::FILE_OK);
74 } else {
75 callback.Run(base::File::FILE_ERROR_NOT_FOUND);
76 }
77 return true;
78 }
79
80 class FileSystemDirURLRequestJobFactory : public net::URLRequestJobFactory {
81 public:
82 FileSystemDirURLRequestJobFactory(const std::string& storage_domain,
83 FileSystemContext* context)
84 : storage_domain_(storage_domain), file_system_context_(context) {
85 }
86
87 net::URLRequestJob* MaybeCreateJobWithProtocolHandler(
88 const std::string& scheme,
89 net::URLRequest* request,
90 net::NetworkDelegate* network_delegate) const override {
91 return new storage::FileSystemDirURLRequestJob(
92 request, network_delegate, storage_domain_, file_system_context_);
93 }
94
95 net::URLRequestJob* MaybeInterceptRedirect(
96 net::URLRequest* request,
97 net::NetworkDelegate* network_delegate,
98 const GURL& location) const override {
99 return nullptr;
100 }
101
102 net::URLRequestJob* MaybeInterceptResponse(
103 net::URLRequest* request,
104 net::NetworkDelegate* network_delegate) const override {
105 return nullptr;
106 }
107
108 bool IsHandledProtocol(const std::string& scheme) const override {
109 return true;
110 }
111
112 bool IsSafeRedirectTarget(const GURL& location) const override {
113 return false;
114 }
115
116 private:
117 std::string storage_domain_;
118 FileSystemContext* file_system_context_;
119 };
120
121
122 } // namespace
123
124 class FileSystemDirURLRequestJobTest : public testing::Test {
125 protected:
126 FileSystemDirURLRequestJobTest()
127 : weak_factory_(this) {
128 }
129
130 void SetUp() override {
131 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
132
133 special_storage_policy_ = new MockSpecialStoragePolicy;
134 file_system_context_ =
135 CreateFileSystemContextForTesting(NULL, temp_dir_.GetPath());
136
137 file_system_context_->OpenFileSystem(
138 GURL("http://remote/"),
139 storage::kFileSystemTypeTemporary,
140 storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT,
141 base::Bind(&FileSystemDirURLRequestJobTest::OnOpenFileSystem,
142 weak_factory_.GetWeakPtr()));
143 base::RunLoop().RunUntilIdle();
144 }
145
146 void TearDown() override {
147 // NOTE: order matters, request must die before delegate
148 request_.reset(NULL);
149 delegate_.reset(NULL);
150 }
151
152 void SetUpAutoMountContext(base::FilePath* mnt_point) {
153 *mnt_point = temp_dir_.GetPath().AppendASCII("auto_mount_dir");
154 ASSERT_TRUE(base::CreateDirectory(*mnt_point));
155
156 std::vector<std::unique_ptr<storage::FileSystemBackend>>
157 additional_providers;
158 additional_providers.push_back(base::MakeUnique<TestFileSystemBackend>(
159 base::ThreadTaskRunnerHandle::Get().get(), *mnt_point));
160
161 std::vector<storage::URLRequestAutoMountHandler> handlers;
162 handlers.push_back(base::Bind(&TestAutoMountForURLRequest));
163
164 file_system_context_ = CreateFileSystemContextWithAutoMountersForTesting(
165 NULL, std::move(additional_providers), handlers, temp_dir_.GetPath());
166 }
167
168 void OnOpenFileSystem(const GURL& root_url,
169 const std::string& name,
170 base::File::Error result) {
171 ASSERT_EQ(base::File::FILE_OK, result);
172 }
173
174 void TestRequestHelper(const GURL& url, bool run_to_completion,
175 FileSystemContext* file_system_context) {
176 delegate_.reset(new net::TestDelegate());
177 delegate_->set_quit_on_redirect(true);
178 job_factory_.reset(new FileSystemDirURLRequestJobFactory(
179 url.GetOrigin().host(), file_system_context));
180 empty_context_.set_job_factory(job_factory_.get());
181
182 request_ = empty_context_.CreateRequest(
183 url, net::DEFAULT_PRIORITY, delegate_.get());
184 request_->Start();
185 ASSERT_TRUE(request_->is_pending()); // verify that we're starting async
186 if (run_to_completion)
187 base::RunLoop().Run();
188 }
189
190 void TestRequest(const GURL& url) {
191 TestRequestHelper(url, true, file_system_context_.get());
192 }
193
194 void TestRequestWithContext(const GURL& url,
195 FileSystemContext* file_system_context) {
196 TestRequestHelper(url, true, file_system_context);
197 }
198
199 void TestRequestNoRun(const GURL& url) {
200 TestRequestHelper(url, false, file_system_context_.get());
201 }
202
203 FileSystemURL CreateURL(const base::FilePath& file_path) {
204 return file_system_context_->CreateCrackedFileSystemURL(
205 GURL("http://remote"), storage::kFileSystemTypeTemporary, file_path);
206 }
207
208 FileSystemOperationContext* NewOperationContext() {
209 FileSystemOperationContext* context(
210 new FileSystemOperationContext(file_system_context_.get()));
211 context->set_allowed_bytes_growth(1024);
212 return context;
213 }
214
215 void CreateDirectory(const base::StringPiece& dir_name) {
216 base::FilePath path = base::FilePath().AppendASCII(dir_name);
217 std::unique_ptr<FileSystemOperationContext> context(NewOperationContext());
218 ASSERT_EQ(base::File::FILE_OK, file_util()->CreateDirectory(
219 context.get(),
220 CreateURL(path),
221 false /* exclusive */,
222 false /* recursive */));
223 }
224
225 void EnsureFileExists(const base::StringPiece file_name) {
226 base::FilePath path = base::FilePath().AppendASCII(file_name);
227 std::unique_ptr<FileSystemOperationContext> context(NewOperationContext());
228 ASSERT_EQ(base::File::FILE_OK, file_util()->EnsureFileExists(
229 context.get(), CreateURL(path), NULL));
230 }
231
232 void TruncateFile(const base::StringPiece file_name, int64_t length) {
233 base::FilePath path = base::FilePath().AppendASCII(file_name);
234 std::unique_ptr<FileSystemOperationContext> context(NewOperationContext());
235 ASSERT_EQ(base::File::FILE_OK, file_util()->Truncate(
236 context.get(), CreateURL(path), length));
237 }
238
239 base::File::Error GetFileInfo(const base::FilePath& path,
240 base::File::Info* file_info,
241 base::FilePath* platform_file_path) {
242 std::unique_ptr<FileSystemOperationContext> context(NewOperationContext());
243 return file_util()->GetFileInfo(context.get(),
244 CreateURL(path),
245 file_info, platform_file_path);
246 }
247
248 // If |size| is negative, the reported size is ignored.
249 void VerifyListingEntry(const std::string& entry_line,
250 const std::string& name,
251 const std::string& url,
252 bool is_directory,
253 int64_t size) {
254 #define NUMBER "([0-9-]*)"
255 #define STR "([^\"]*)"
256 icu::UnicodeString pattern("^<script>addRow\\(\"" STR "\",\"" STR
257 "\",(0|1)," NUMBER ",\"" STR "\"," NUMBER ",\"" STR "\"\\);</script>");
258 #undef NUMBER
259 #undef STR
260 icu::UnicodeString input(entry_line.c_str());
261
262 UErrorCode status = U_ZERO_ERROR;
263 icu::RegexMatcher match(pattern, input, 0, status);
264
265 EXPECT_TRUE(match.find());
266 EXPECT_EQ(7, match.groupCount());
267 EXPECT_EQ(icu::UnicodeString(name.c_str()), match.group(1, status));
268 EXPECT_EQ(icu::UnicodeString(url.c_str()), match.group(2, status));
269 EXPECT_EQ(icu::UnicodeString(is_directory ? "1" : "0"),
270 match.group(3, status));
271 if (size >= 0) {
272 icu::UnicodeString size_string(
273 base::FormatBytesUnlocalized(size).c_str());
274 EXPECT_EQ(size_string, match.group(5, status));
275 }
276
277 icu::UnicodeString date_ustr(match.group(7, status));
278 std::unique_ptr<icu::DateFormat> formatter(
279 icu::DateFormat::createDateTimeInstance(icu::DateFormat::kShort));
280 UErrorCode parse_status = U_ZERO_ERROR;
281 UDate udate = formatter->parse(date_ustr, parse_status);
282 EXPECT_TRUE(U_SUCCESS(parse_status));
283 base::Time date = base::Time::FromJsTime(udate);
284 EXPECT_FALSE(date.is_null());
285 }
286
287 GURL CreateFileSystemURL(const std::string& path) {
288 return GURL(kFileSystemURLPrefix + path);
289 }
290
291 storage::FileSystemFileUtil* file_util() {
292 return file_system_context_->sandbox_delegate()->sync_file_util();
293 }
294
295 // Put the message loop at the top, so that it's the last thing deleted.
296 // Delete all task runner objects before the MessageLoop, to help prevent
297 // leaks caused by tasks posted during shutdown.
298 base::MessageLoopForIO message_loop_;
299
300 base::ScopedTempDir temp_dir_;
301 net::URLRequestContext empty_context_;
302 std::unique_ptr<net::TestDelegate> delegate_;
303 std::unique_ptr<net::URLRequest> request_;
304 std::unique_ptr<FileSystemDirURLRequestJobFactory> job_factory_;
305 scoped_refptr<MockSpecialStoragePolicy> special_storage_policy_;
306 scoped_refptr<FileSystemContext> file_system_context_;
307 base::WeakPtrFactory<FileSystemDirURLRequestJobTest> weak_factory_;
308 };
309
310 namespace {
311
312 TEST_F(FileSystemDirURLRequestJobTest, DirectoryListing) {
313 CreateDirectory("foo");
314 CreateDirectory("foo/bar");
315 CreateDirectory("foo/bar/baz");
316
317 EnsureFileExists("foo/bar/hoge");
318 TruncateFile("foo/bar/hoge", 10);
319
320 TestRequest(CreateFileSystemURL("foo/bar/"));
321
322 ASSERT_FALSE(request_->is_pending());
323 EXPECT_EQ(1, delegate_->response_started_count());
324 EXPECT_FALSE(delegate_->received_data_before_response());
325 EXPECT_GT(delegate_->bytes_received(), 0);
326
327 std::istringstream in(delegate_->data_received());
328 std::string line;
329 EXPECT_TRUE(std::getline(in, line));
330
331 #if defined(OS_WIN)
332 EXPECT_EQ("<script>start(\"foo\\\\bar\");</script>", line);
333 #elif defined(OS_POSIX)
334 EXPECT_EQ("<script>start(\"/foo/bar\");</script>", line);
335 #endif
336
337 EXPECT_TRUE(std::getline(in, line));
338 VerifyListingEntry(line, "hoge", "hoge", false, 10);
339
340 EXPECT_TRUE(std::getline(in, line));
341 VerifyListingEntry(line, "baz", "baz", true, 0);
342 EXPECT_FALSE(!!std::getline(in, line));
343 }
344
345 TEST_F(FileSystemDirURLRequestJobTest, InvalidURL) {
346 TestRequest(GURL("filesystem:/foo/bar/baz"));
347 ASSERT_FALSE(request_->is_pending());
348 EXPECT_TRUE(delegate_->request_failed());
349 EXPECT_EQ(net::ERR_INVALID_URL, delegate_->request_status());
350 }
351
352 TEST_F(FileSystemDirURLRequestJobTest, NoSuchRoot) {
353 TestRequest(GURL("filesystem:http://remote/persistent/somedir/"));
354 ASSERT_FALSE(request_->is_pending());
355 EXPECT_EQ(net::ERR_FILE_NOT_FOUND, delegate_->request_status());
356 }
357
358 TEST_F(FileSystemDirURLRequestJobTest, NoSuchDirectory) {
359 TestRequest(CreateFileSystemURL("somedir/"));
360 ASSERT_FALSE(request_->is_pending());
361 EXPECT_EQ(net::ERR_FILE_NOT_FOUND, delegate_->request_status());
362 }
363
364 TEST_F(FileSystemDirURLRequestJobTest, Cancel) {
365 CreateDirectory("foo");
366 TestRequestNoRun(CreateFileSystemURL("foo/"));
367 // Run StartAsync() and only StartAsync().
368 base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE,
369 request_.release());
370 base::RunLoop().RunUntilIdle();
371 // If we get here, success! we didn't crash!
372 }
373
374 TEST_F(FileSystemDirURLRequestJobTest, Incognito) {
375 CreateDirectory("foo");
376
377 scoped_refptr<FileSystemContext> file_system_context =
378 CreateIncognitoFileSystemContextForTesting(NULL, temp_dir_.GetPath());
379
380 TestRequestWithContext(CreateFileSystemURL("/"),
381 file_system_context.get());
382 ASSERT_FALSE(request_->is_pending());
383
384 std::istringstream in(delegate_->data_received());
385 std::string line;
386 EXPECT_TRUE(std::getline(in, line));
387 EXPECT_FALSE(!!std::getline(in, line));
388
389 TestRequestWithContext(CreateFileSystemURL("foo"),
390 file_system_context.get());
391 ASSERT_FALSE(request_->is_pending());
392 EXPECT_EQ(net::ERR_FILE_NOT_FOUND, delegate_->request_status());
393 }
394
395 TEST_F(FileSystemDirURLRequestJobTest, AutoMountDirectoryListing) {
396 base::FilePath mnt_point;
397 SetUpAutoMountContext(&mnt_point);
398 ASSERT_TRUE(base::CreateDirectory(mnt_point));
399 ASSERT_TRUE(base::CreateDirectory(mnt_point.AppendASCII("foo")));
400 ASSERT_EQ(10,
401 base::WriteFile(mnt_point.AppendASCII("bar"), "1234567890", 10));
402
403 TestRequest(GURL("filesystem:http://automount/external/mnt_name"));
404
405 ASSERT_FALSE(request_->is_pending());
406 EXPECT_EQ(1, delegate_->response_started_count());
407 EXPECT_FALSE(delegate_->received_data_before_response());
408 EXPECT_GT(delegate_->bytes_received(), 0);
409
410 std::istringstream in(delegate_->data_received());
411 std::string line;
412 EXPECT_TRUE(std::getline(in, line)); // |line| contains the temp dir path.
413
414 // Result order is not guaranteed, so sort the results.
415 std::vector<std::string> listing_entries;
416 while (!!std::getline(in, line))
417 listing_entries.push_back(line);
418
419 ASSERT_EQ(2U, listing_entries.size());
420 std::sort(listing_entries.begin(), listing_entries.end());
421 VerifyListingEntry(listing_entries[0], "bar", "bar", false, 10);
422 VerifyListingEntry(listing_entries[1], "foo", "foo", true, -1);
423
424 ASSERT_TRUE(
425 storage::ExternalMountPoints::GetSystemInstance()->RevokeFileSystem(
426 kValidExternalMountPoint));
427 }
428
429 TEST_F(FileSystemDirURLRequestJobTest, AutoMountInvalidRoot) {
430 base::FilePath mnt_point;
431 SetUpAutoMountContext(&mnt_point);
432 TestRequest(GURL("filesystem:http://automount/external/invalid"));
433
434 ASSERT_FALSE(request_->is_pending());
435 EXPECT_EQ(net::ERR_FILE_NOT_FOUND, delegate_->request_status());
436
437 ASSERT_FALSE(
438 storage::ExternalMountPoints::GetSystemInstance()->RevokeFileSystem(
439 "invalid"));
440 }
441
442 TEST_F(FileSystemDirURLRequestJobTest, AutoMountNoHandler) {
443 base::FilePath mnt_point;
444 SetUpAutoMountContext(&mnt_point);
445 TestRequest(GURL("filesystem:http://noauto/external/mnt_name"));
446
447 ASSERT_FALSE(request_->is_pending());
448 EXPECT_EQ(net::ERR_FILE_NOT_FOUND, delegate_->request_status());
449
450 ASSERT_FALSE(
451 storage::ExternalMountPoints::GetSystemInstance()->RevokeFileSystem(
452 kValidExternalMountPoint));
453 }
454
455 } // namespace
456 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698