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

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

Issue 2368913003: Populate storage_unittests target. (Closed)
Patch Set: Removed unnecessary include from storage/browser/blob/blob_storage_context_unittest.cc. Created 4 years, 2 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/scoped_vector.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 "content/public/test/mock_special_storage_policy.h"
23 #include "content/public/test/test_file_system_backend.h"
24 #include "content/public/test/test_file_system_context.h"
25 #include "net/base/net_errors.h"
26 #include "net/base/request_priority.h"
27 #include "net/http/http_request_headers.h"
28 #include "net/url_request/url_request.h"
29 #include "net/url_request/url_request_context.h"
30 #include "net/url_request/url_request_test_util.h"
31 #include "storage/browser/fileapi/external_mount_points.h"
32 #include "storage/browser/fileapi/file_system_context.h"
33 #include "storage/browser/fileapi/file_system_dir_url_request_job.h"
34 #include "storage/browser/fileapi/file_system_file_util.h"
35 #include "storage/browser/fileapi/file_system_operation_context.h"
36 #include "storage/browser/fileapi/file_system_url.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 IsHandledURL(const GURL& url) const override { return true; }
113
114 bool IsSafeRedirectTarget(const GURL& location) const override {
115 return false;
116 }
117
118 private:
119 std::string storage_domain_;
120 FileSystemContext* file_system_context_;
121 };
122
123
124 } // namespace
125
126 class FileSystemDirURLRequestJobTest : public testing::Test {
127 protected:
128 FileSystemDirURLRequestJobTest()
129 : weak_factory_(this) {
130 }
131
132 void SetUp() override {
133 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
134
135 special_storage_policy_ = new MockSpecialStoragePolicy;
136 file_system_context_ =
137 CreateFileSystemContextForTesting(NULL, temp_dir_.GetPath());
138
139 file_system_context_->OpenFileSystem(
140 GURL("http://remote/"),
141 storage::kFileSystemTypeTemporary,
142 storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT,
143 base::Bind(&FileSystemDirURLRequestJobTest::OnOpenFileSystem,
144 weak_factory_.GetWeakPtr()));
145 base::RunLoop().RunUntilIdle();
146 }
147
148 void TearDown() override {
149 // NOTE: order matters, request must die before delegate
150 request_.reset(NULL);
151 delegate_.reset(NULL);
152 }
153
154 void SetUpAutoMountContext(base::FilePath* mnt_point) {
155 *mnt_point = temp_dir_.GetPath().AppendASCII("auto_mount_dir");
156 ASSERT_TRUE(base::CreateDirectory(*mnt_point));
157
158 ScopedVector<storage::FileSystemBackend> additional_providers;
159 additional_providers.push_back(new TestFileSystemBackend(
160 base::ThreadTaskRunnerHandle::Get().get(), *mnt_point));
161
162 std::vector<storage::URLRequestAutoMountHandler> handlers;
163 handlers.push_back(base::Bind(&TestAutoMountForURLRequest));
164
165 file_system_context_ = CreateFileSystemContextWithAutoMountersForTesting(
166 NULL, std::move(additional_providers), handlers, temp_dir_.GetPath());
167 }
168
169 void OnOpenFileSystem(const GURL& root_url,
170 const std::string& name,
171 base::File::Error result) {
172 ASSERT_EQ(base::File::FILE_OK, result);
173 }
174
175 void TestRequestHelper(const GURL& url, bool run_to_completion,
176 FileSystemContext* file_system_context) {
177 delegate_.reset(new net::TestDelegate());
178 delegate_->set_quit_on_redirect(true);
179 job_factory_.reset(new FileSystemDirURLRequestJobFactory(
180 url.GetOrigin().host(), file_system_context));
181 empty_context_.set_job_factory(job_factory_.get());
182
183 request_ = empty_context_.CreateRequest(
184 url, net::DEFAULT_PRIORITY, delegate_.get());
185 request_->Start();
186 ASSERT_TRUE(request_->is_pending()); // verify that we're starting async
187 if (run_to_completion)
188 base::RunLoop().Run();
189 }
190
191 void TestRequest(const GURL& url) {
192 TestRequestHelper(url, true, file_system_context_.get());
193 }
194
195 void TestRequestWithContext(const GURL& url,
196 FileSystemContext* file_system_context) {
197 TestRequestHelper(url, true, file_system_context);
198 }
199
200 void TestRequestNoRun(const GURL& url) {
201 TestRequestHelper(url, false, file_system_context_.get());
202 }
203
204 FileSystemURL CreateURL(const base::FilePath& file_path) {
205 return file_system_context_->CreateCrackedFileSystemURL(
206 GURL("http://remote"), storage::kFileSystemTypeTemporary, file_path);
207 }
208
209 FileSystemOperationContext* NewOperationContext() {
210 FileSystemOperationContext* context(
211 new FileSystemOperationContext(file_system_context_.get()));
212 context->set_allowed_bytes_growth(1024);
213 return context;
214 }
215
216 void CreateDirectory(const base::StringPiece& dir_name) {
217 base::FilePath path = base::FilePath().AppendASCII(dir_name);
218 std::unique_ptr<FileSystemOperationContext> context(NewOperationContext());
219 ASSERT_EQ(base::File::FILE_OK, file_util()->CreateDirectory(
220 context.get(),
221 CreateURL(path),
222 false /* exclusive */,
223 false /* recursive */));
224 }
225
226 void EnsureFileExists(const base::StringPiece file_name) {
227 base::FilePath path = base::FilePath().AppendASCII(file_name);
228 std::unique_ptr<FileSystemOperationContext> context(NewOperationContext());
229 ASSERT_EQ(base::File::FILE_OK, file_util()->EnsureFileExists(
230 context.get(), CreateURL(path), NULL));
231 }
232
233 void TruncateFile(const base::StringPiece file_name, int64_t length) {
234 base::FilePath path = base::FilePath().AppendASCII(file_name);
235 std::unique_ptr<FileSystemOperationContext> context(NewOperationContext());
236 ASSERT_EQ(base::File::FILE_OK, file_util()->Truncate(
237 context.get(), CreateURL(path), length));
238 }
239
240 base::File::Error GetFileInfo(const base::FilePath& path,
241 base::File::Info* file_info,
242 base::FilePath* platform_file_path) {
243 std::unique_ptr<FileSystemOperationContext> context(NewOperationContext());
244 return file_util()->GetFileInfo(context.get(),
245 CreateURL(path),
246 file_info, platform_file_path);
247 }
248
249 // If |size| is negative, the reported size is ignored.
250 void VerifyListingEntry(const std::string& entry_line,
251 const std::string& name,
252 const std::string& url,
253 bool is_directory,
254 int64_t size) {
255 #define NUMBER "([0-9-]*)"
256 #define STR "([^\"]*)"
257 icu::UnicodeString pattern("^<script>addRow\\(\"" STR "\",\"" STR
258 "\",(0|1)," NUMBER ",\"" STR "\"," NUMBER ",\"" STR "\"\\);</script>");
259 #undef NUMBER
260 #undef STR
261 icu::UnicodeString input(entry_line.c_str());
262
263 UErrorCode status = U_ZERO_ERROR;
264 icu::RegexMatcher match(pattern, input, 0, status);
265
266 EXPECT_TRUE(match.find());
267 EXPECT_EQ(7, match.groupCount());
268 EXPECT_EQ(icu::UnicodeString(name.c_str()), match.group(1, status));
269 EXPECT_EQ(icu::UnicodeString(url.c_str()), match.group(2, status));
270 EXPECT_EQ(icu::UnicodeString(is_directory ? "1" : "0"),
271 match.group(3, status));
272 if (size >= 0) {
273 icu::UnicodeString size_string(
274 base::FormatBytesUnlocalized(size).c_str());
275 EXPECT_EQ(size_string, match.group(5, status));
276 }
277
278 icu::UnicodeString date_ustr(match.group(7, status));
279 std::unique_ptr<icu::DateFormat> formatter(
280 icu::DateFormat::createDateTimeInstance(icu::DateFormat::kShort));
281 UErrorCode parse_status = U_ZERO_ERROR;
282 UDate udate = formatter->parse(date_ustr, parse_status);
283 EXPECT_TRUE(U_SUCCESS(parse_status));
284 base::Time date = base::Time::FromJsTime(udate);
285 EXPECT_FALSE(date.is_null());
286 }
287
288 GURL CreateFileSystemURL(const std::string& path) {
289 return GURL(kFileSystemURLPrefix + path);
290 }
291
292 storage::FileSystemFileUtil* file_util() {
293 return file_system_context_->sandbox_delegate()->sync_file_util();
294 }
295
296 // Put the message loop at the top, so that it's the last thing deleted.
297 // Delete all task runner objects before the MessageLoop, to help prevent
298 // leaks caused by tasks posted during shutdown.
299 base::MessageLoopForIO message_loop_;
300
301 base::ScopedTempDir temp_dir_;
302 net::URLRequestContext empty_context_;
303 std::unique_ptr<net::TestDelegate> delegate_;
304 std::unique_ptr<net::URLRequest> request_;
305 std::unique_ptr<FileSystemDirURLRequestJobFactory> job_factory_;
306 scoped_refptr<MockSpecialStoragePolicy> special_storage_policy_;
307 scoped_refptr<FileSystemContext> file_system_context_;
308 base::WeakPtrFactory<FileSystemDirURLRequestJobTest> weak_factory_;
309 };
310
311 namespace {
312
313 TEST_F(FileSystemDirURLRequestJobTest, DirectoryListing) {
314 CreateDirectory("foo");
315 CreateDirectory("foo/bar");
316 CreateDirectory("foo/bar/baz");
317
318 EnsureFileExists("foo/bar/hoge");
319 TruncateFile("foo/bar/hoge", 10);
320
321 TestRequest(CreateFileSystemURL("foo/bar/"));
322
323 ASSERT_FALSE(request_->is_pending());
324 EXPECT_EQ(1, delegate_->response_started_count());
325 EXPECT_FALSE(delegate_->received_data_before_response());
326 EXPECT_GT(delegate_->bytes_received(), 0);
327
328 std::istringstream in(delegate_->data_received());
329 std::string line;
330 EXPECT_TRUE(std::getline(in, line));
331
332 #if defined(OS_WIN)
333 EXPECT_EQ("<script>start(\"foo\\\\bar\");</script>", line);
334 #elif defined(OS_POSIX)
335 EXPECT_EQ("<script>start(\"/foo/bar\");</script>", line);
336 #endif
337
338 EXPECT_TRUE(std::getline(in, line));
339 VerifyListingEntry(line, "hoge", "hoge", false, 10);
340
341 EXPECT_TRUE(std::getline(in, line));
342 VerifyListingEntry(line, "baz", "baz", true, 0);
343 EXPECT_FALSE(!!std::getline(in, line));
344 }
345
346 TEST_F(FileSystemDirURLRequestJobTest, InvalidURL) {
347 TestRequest(GURL("filesystem:/foo/bar/baz"));
348 ASSERT_FALSE(request_->is_pending());
349 EXPECT_TRUE(delegate_->request_failed());
350 ASSERT_FALSE(request_->status().is_success());
351 EXPECT_EQ(net::ERR_INVALID_URL, request_->status().error());
352 }
353
354 TEST_F(FileSystemDirURLRequestJobTest, NoSuchRoot) {
355 TestRequest(GURL("filesystem:http://remote/persistent/somedir/"));
356 ASSERT_FALSE(request_->is_pending());
357 ASSERT_FALSE(request_->status().is_success());
358 EXPECT_EQ(net::ERR_FILE_NOT_FOUND, request_->status().error());
359 }
360
361 TEST_F(FileSystemDirURLRequestJobTest, NoSuchDirectory) {
362 TestRequest(CreateFileSystemURL("somedir/"));
363 ASSERT_FALSE(request_->is_pending());
364 ASSERT_FALSE(request_->status().is_success());
365 EXPECT_EQ(net::ERR_FILE_NOT_FOUND, request_->status().error());
366 }
367
368 TEST_F(FileSystemDirURLRequestJobTest, Cancel) {
369 CreateDirectory("foo");
370 TestRequestNoRun(CreateFileSystemURL("foo/"));
371 // Run StartAsync() and only StartAsync().
372 base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE,
373 request_.release());
374 base::RunLoop().RunUntilIdle();
375 // If we get here, success! we didn't crash!
376 }
377
378 TEST_F(FileSystemDirURLRequestJobTest, Incognito) {
379 CreateDirectory("foo");
380
381 scoped_refptr<FileSystemContext> file_system_context =
382 CreateIncognitoFileSystemContextForTesting(NULL, temp_dir_.GetPath());
383
384 TestRequestWithContext(CreateFileSystemURL("/"),
385 file_system_context.get());
386 ASSERT_FALSE(request_->is_pending());
387 ASSERT_TRUE(request_->status().is_success());
388
389 std::istringstream in(delegate_->data_received());
390 std::string line;
391 EXPECT_TRUE(std::getline(in, line));
392 EXPECT_FALSE(!!std::getline(in, line));
393
394 TestRequestWithContext(CreateFileSystemURL("foo"),
395 file_system_context.get());
396 ASSERT_FALSE(request_->is_pending());
397 ASSERT_FALSE(request_->status().is_success());
398 EXPECT_EQ(net::ERR_FILE_NOT_FOUND, request_->status().error());
399 }
400
401 TEST_F(FileSystemDirURLRequestJobTest, AutoMountDirectoryListing) {
402 base::FilePath mnt_point;
403 SetUpAutoMountContext(&mnt_point);
404 ASSERT_TRUE(base::CreateDirectory(mnt_point));
405 ASSERT_TRUE(base::CreateDirectory(mnt_point.AppendASCII("foo")));
406 ASSERT_EQ(10,
407 base::WriteFile(mnt_point.AppendASCII("bar"), "1234567890", 10));
408
409 TestRequest(GURL("filesystem:http://automount/external/mnt_name"));
410
411 ASSERT_FALSE(request_->is_pending());
412 EXPECT_EQ(1, delegate_->response_started_count());
413 EXPECT_FALSE(delegate_->received_data_before_response());
414 EXPECT_GT(delegate_->bytes_received(), 0);
415
416 std::istringstream in(delegate_->data_received());
417 std::string line;
418 EXPECT_TRUE(std::getline(in, line)); // |line| contains the temp dir path.
419
420 // Result order is not guaranteed, so sort the results.
421 std::vector<std::string> listing_entries;
422 while (!!std::getline(in, line))
423 listing_entries.push_back(line);
424
425 ASSERT_EQ(2U, listing_entries.size());
426 std::sort(listing_entries.begin(), listing_entries.end());
427 VerifyListingEntry(listing_entries[0], "bar", "bar", false, 10);
428 VerifyListingEntry(listing_entries[1], "foo", "foo", true, -1);
429
430 ASSERT_TRUE(
431 storage::ExternalMountPoints::GetSystemInstance()->RevokeFileSystem(
432 kValidExternalMountPoint));
433 }
434
435 TEST_F(FileSystemDirURLRequestJobTest, AutoMountInvalidRoot) {
436 base::FilePath mnt_point;
437 SetUpAutoMountContext(&mnt_point);
438 TestRequest(GURL("filesystem:http://automount/external/invalid"));
439
440 ASSERT_FALSE(request_->is_pending());
441 ASSERT_FALSE(request_->status().is_success());
442 EXPECT_EQ(net::ERR_FILE_NOT_FOUND, request_->status().error());
443
444 ASSERT_FALSE(
445 storage::ExternalMountPoints::GetSystemInstance()->RevokeFileSystem(
446 "invalid"));
447 }
448
449 TEST_F(FileSystemDirURLRequestJobTest, AutoMountNoHandler) {
450 base::FilePath mnt_point;
451 SetUpAutoMountContext(&mnt_point);
452 TestRequest(GURL("filesystem:http://noauto/external/mnt_name"));
453
454 ASSERT_FALSE(request_->is_pending());
455 ASSERT_FALSE(request_->status().is_success());
456 EXPECT_EQ(net::ERR_FILE_NOT_FOUND, request_->status().error());
457
458 ASSERT_FALSE(
459 storage::ExternalMountPoints::GetSystemInstance()->RevokeFileSystem(
460 kValidExternalMountPoint));
461 }
462
463 } // namespace
464 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698