Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / google_apis / drive / drive_api_requests_unittest.cc
1 // Copyright (c) 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 "base/bind.h"
6 #include "base/files/file_path.h"
7 #include "base/files/file_util.h"
8 #include "base/files/scoped_temp_dir.h"
9 #include "base/json/json_reader.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/run_loop.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/values.h"
14 #include "google_apis/drive/drive_api_parser.h"
15 #include "google_apis/drive/drive_api_requests.h"
16 #include "google_apis/drive/drive_api_url_generator.h"
17 #include "google_apis/drive/dummy_auth_service.h"
18 #include "google_apis/drive/request_sender.h"
19 #include "google_apis/drive/test_util.h"
20 #include "net/test/embedded_test_server/embedded_test_server.h"
21 #include "net/test/embedded_test_server/http_request.h"
22 #include "net/test/embedded_test_server/http_response.h"
23 #include "net/url_request/url_request_test_util.h"
24 #include "testing/gtest/include/gtest/gtest.h"
25
26 namespace google_apis {
27
28 namespace {
29
30 const char kTestETag[] = "test_etag";
31 const char kTestUserAgent[] = "test-user-agent";
32
33 const char kTestChildrenResponse[] =
34     "{\n"
35     "\"kind\": \"drive#childReference\",\n"
36     "\"id\": \"resource_id\",\n"
37     "\"selfLink\": \"self_link\",\n"
38     "\"childLink\": \"child_link\",\n"
39     "}\n";
40
41 const char kTestPermissionResponse[] =
42     "{\n"
43     "\"kind\": \"drive#permission\",\n"
44     "\"id\": \"resource_id\",\n"
45     "\"selfLink\": \"self_link\",\n"
46     "}\n";
47
48 const char kTestUploadExistingFilePath[] = "/upload/existingfile/path";
49 const char kTestUploadNewFilePath[] = "/upload/newfile/path";
50 const char kTestDownloadPathPrefix[] = "/download/";
51
52 // Used as a GetContentCallback.
53 void AppendContent(std::string* out,
54                    GDataErrorCode error,
55                    scoped_ptr<std::string> content) {
56   EXPECT_EQ(HTTP_SUCCESS, error);
57   out->append(*content);
58 }
59
60 }  // namespace
61
62 class DriveApiRequestsTest : public testing::Test {
63  public:
64   DriveApiRequestsTest() {
65   }
66
67   virtual void SetUp() override {
68     request_context_getter_ = new net::TestURLRequestContextGetter(
69         message_loop_.message_loop_proxy());
70
71     request_sender_.reset(new RequestSender(new DummyAuthService,
72                                             request_context_getter_.get(),
73                                             message_loop_.message_loop_proxy(),
74                                             kTestUserAgent));
75
76     ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
77
78     ASSERT_TRUE(test_server_.InitializeAndWaitUntilReady());
79     test_server_.RegisterRequestHandler(
80         base::Bind(&DriveApiRequestsTest::HandleChildrenDeleteRequest,
81                    base::Unretained(this)));
82     test_server_.RegisterRequestHandler(
83         base::Bind(&DriveApiRequestsTest::HandleDataFileRequest,
84                    base::Unretained(this)));
85     test_server_.RegisterRequestHandler(
86         base::Bind(&DriveApiRequestsTest::HandleDeleteRequest,
87                    base::Unretained(this)));
88     test_server_.RegisterRequestHandler(
89         base::Bind(&DriveApiRequestsTest::HandlePreconditionFailedRequest,
90                    base::Unretained(this)));
91     test_server_.RegisterRequestHandler(
92         base::Bind(&DriveApiRequestsTest::HandleResumeUploadRequest,
93                    base::Unretained(this)));
94     test_server_.RegisterRequestHandler(
95         base::Bind(&DriveApiRequestsTest::HandleInitiateUploadRequest,
96                    base::Unretained(this)));
97     test_server_.RegisterRequestHandler(
98         base::Bind(&DriveApiRequestsTest::HandleContentResponse,
99                    base::Unretained(this)));
100     test_server_.RegisterRequestHandler(
101         base::Bind(&DriveApiRequestsTest::HandleDownloadRequest,
102                    base::Unretained(this)));
103
104     GURL test_base_url = test_util::GetBaseUrlForTesting(test_server_.port());
105     url_generator_.reset(new DriveApiUrlGenerator(
106         test_base_url, test_base_url.Resolve(kTestDownloadPathPrefix)));
107
108     // Reset the server's expected behavior just in case.
109     ResetExpectedResponse();
110     received_bytes_ = 0;
111     content_length_ = 0;
112   }
113
114   base::MessageLoopForIO message_loop_;  // Test server needs IO thread.
115   net::test_server::EmbeddedTestServer test_server_;
116   scoped_ptr<RequestSender> request_sender_;
117   scoped_ptr<DriveApiUrlGenerator> url_generator_;
118   scoped_refptr<net::TestURLRequestContextGetter> request_context_getter_;
119   base::ScopedTempDir temp_dir_;
120
121   // This is a path to the file which contains expected response from
122   // the server. See also HandleDataFileRequest below.
123   base::FilePath expected_data_file_path_;
124
125   // This is a path string in the expected response header from the server
126   // for initiating file uploading.
127   std::string expected_upload_path_;
128
129   // This is a path to the file which contains expected response for
130   // PRECONDITION_FAILED response.
131   base::FilePath expected_precondition_failed_file_path_;
132
133   // These are content and its type in the expected response from the server.
134   // See also HandleContentResponse below.
135   std::string expected_content_type_;
136   std::string expected_content_;
137
138   // The incoming HTTP request is saved so tests can verify the request
139   // parameters like HTTP method (ex. some requests should use DELETE
140   // instead of GET).
141   net::test_server::HttpRequest http_request_;
142
143  private:
144   void ResetExpectedResponse() {
145     expected_data_file_path_.clear();
146     expected_upload_path_.clear();
147     expected_content_type_.clear();
148     expected_content_.clear();
149   }
150
151   // For "Children: delete" request, the server will return "204 No Content"
152   // response meaning "success".
153   scoped_ptr<net::test_server::HttpResponse> HandleChildrenDeleteRequest(
154       const net::test_server::HttpRequest& request) {
155     if (request.method != net::test_server::METHOD_DELETE ||
156         request.relative_url.find("/children/") == string::npos) {
157       // The request is not the "Children: delete" request. Delegate the
158       // processing to the next handler.
159       return scoped_ptr<net::test_server::HttpResponse>();
160     }
161
162     http_request_ = request;
163
164     // Return the response with just "204 No Content" status code.
165     scoped_ptr<net::test_server::BasicHttpResponse> http_response(
166         new net::test_server::BasicHttpResponse);
167     http_response->set_code(net::HTTP_NO_CONTENT);
168     return http_response.Pass();
169   }
170
171   // Reads the data file of |expected_data_file_path_| and returns its content
172   // for the request.
173   // To use this method, it is necessary to set |expected_data_file_path_|
174   // to the appropriate file path before sending the request to the server.
175   scoped_ptr<net::test_server::HttpResponse> HandleDataFileRequest(
176       const net::test_server::HttpRequest& request) {
177     if (expected_data_file_path_.empty()) {
178       // The file is not specified. Delegate the processing to the next
179       // handler.
180       return scoped_ptr<net::test_server::HttpResponse>();
181     }
182
183     http_request_ = request;
184
185     // Return the response from the data file.
186     return test_util::CreateHttpResponseFromFile(expected_data_file_path_);
187   }
188
189   // Deletes the resource and returns no content with HTTP_NO_CONTENT status
190   // code.
191   scoped_ptr<net::test_server::HttpResponse> HandleDeleteRequest(
192       const net::test_server::HttpRequest& request) {
193     if (request.method != net::test_server::METHOD_DELETE ||
194         request.relative_url.find("/files/") == string::npos) {
195       // The file is not file deletion request. Delegate the processing to the
196       // next handler.
197       return scoped_ptr<net::test_server::HttpResponse>();
198     }
199
200     http_request_ = request;
201
202     scoped_ptr<net::test_server::BasicHttpResponse> response(
203         new net::test_server::BasicHttpResponse);
204     response->set_code(net::HTTP_NO_CONTENT);
205
206     return response.Pass();
207   }
208
209   // Returns PRECONDITION_FAILED response for ETag mismatching with error JSON
210   // content specified by |expected_precondition_failed_file_path_|.
211   // To use this method, it is necessary to set the variable to the appropriate
212   // file path before sending the request to the server.
213   scoped_ptr<net::test_server::HttpResponse> HandlePreconditionFailedRequest(
214       const net::test_server::HttpRequest& request) {
215     if (expected_precondition_failed_file_path_.empty()) {
216       // The file is not specified. Delegate the process to the next handler.
217       return scoped_ptr<net::test_server::HttpResponse>();
218     }
219
220     http_request_ = request;
221
222     scoped_ptr<net::test_server::BasicHttpResponse> response(
223         new net::test_server::BasicHttpResponse);
224     response->set_code(net::HTTP_PRECONDITION_FAILED);
225
226     std::string content;
227     if (base::ReadFileToString(expected_precondition_failed_file_path_,
228                                &content)) {
229       response->set_content(content);
230       response->set_content_type("application/json");
231     }
232
233     return response.Pass();
234   }
235
236   // Returns the response based on set expected upload url.
237   // The response contains the url in its "Location: " header. Also, it doesn't
238   // have any content.
239   // To use this method, it is necessary to set |expected_upload_path_|
240   // to the string representation of the url to be returned.
241   scoped_ptr<net::test_server::HttpResponse> HandleInitiateUploadRequest(
242       const net::test_server::HttpRequest& request) {
243     if (request.relative_url == expected_upload_path_ ||
244         expected_upload_path_.empty()) {
245       // The request is for resume uploading or the expected upload url is not
246       // set. Delegate the processing to the next handler.
247       return scoped_ptr<net::test_server::HttpResponse>();
248     }
249
250     http_request_ = request;
251
252     scoped_ptr<net::test_server::BasicHttpResponse> response(
253         new net::test_server::BasicHttpResponse);
254
255     // Check if the X-Upload-Content-Length is present. If yes, store the
256     // length of the file.
257     std::map<std::string, std::string>::const_iterator found =
258         request.headers.find("X-Upload-Content-Length");
259     if (found == request.headers.end() ||
260         !base::StringToInt64(found->second, &content_length_)) {
261       return scoped_ptr<net::test_server::HttpResponse>();
262     }
263     received_bytes_ = 0;
264
265     response->set_code(net::HTTP_OK);
266     response->AddCustomHeader(
267         "Location",
268         test_server_.base_url().Resolve(expected_upload_path_).spec());
269     return response.Pass();
270   }
271
272   scoped_ptr<net::test_server::HttpResponse> HandleResumeUploadRequest(
273       const net::test_server::HttpRequest& request) {
274     if (request.relative_url != expected_upload_path_) {
275       // The request path is different from the expected path for uploading.
276       // Delegate the processing to the next handler.
277       return scoped_ptr<net::test_server::HttpResponse>();
278     }
279
280     http_request_ = request;
281
282     if (!request.content.empty()) {
283       std::map<std::string, std::string>::const_iterator iter =
284           request.headers.find("Content-Range");
285       if (iter == request.headers.end()) {
286         // The range must be set.
287         return scoped_ptr<net::test_server::HttpResponse>();
288       }
289
290       int64 length = 0;
291       int64 start_position = 0;
292       int64 end_position = 0;
293       if (!test_util::ParseContentRangeHeader(
294               iter->second, &start_position, &end_position, &length)) {
295         // Invalid "Content-Range" value.
296         return scoped_ptr<net::test_server::HttpResponse>();
297       }
298
299       EXPECT_EQ(start_position, received_bytes_);
300       EXPECT_EQ(length, content_length_);
301
302       // end_position is inclusive, but so +1 to change the range to byte size.
303       received_bytes_ = end_position + 1;
304     }
305
306     if (received_bytes_ < content_length_) {
307       scoped_ptr<net::test_server::BasicHttpResponse> response(
308           new net::test_server::BasicHttpResponse);
309       // Set RESUME INCOMPLETE (308) status code.
310       response->set_code(static_cast<net::HttpStatusCode>(308));
311
312       // Add Range header to the response, based on the values of
313       // Content-Range header in the request.
314       // The header is annotated only when at least one byte is received.
315       if (received_bytes_ > 0) {
316         response->AddCustomHeader(
317             "Range", "bytes=0-" + base::Int64ToString(received_bytes_ - 1));
318       }
319
320       return response.Pass();
321     }
322
323     // All bytes are received. Return the "success" response with the file's
324     // (dummy) metadata.
325     scoped_ptr<net::test_server::BasicHttpResponse> response =
326         test_util::CreateHttpResponseFromFile(
327             test_util::GetTestFilePath("drive/file_entry.json"));
328
329     // The response code is CREATED if it is new file uploading.
330     if (http_request_.relative_url == kTestUploadNewFilePath) {
331       response->set_code(net::HTTP_CREATED);
332     }
333
334     return response.Pass();
335   }
336
337   // Returns the response based on set expected content and its type.
338   // To use this method, both |expected_content_type_| and |expected_content_|
339   // must be set in advance.
340   scoped_ptr<net::test_server::HttpResponse> HandleContentResponse(
341       const net::test_server::HttpRequest& request) {
342     if (expected_content_type_.empty() || expected_content_.empty()) {
343       // Expected content is not set. Delegate the processing to the next
344       // handler.
345       return scoped_ptr<net::test_server::HttpResponse>();
346     }
347
348     http_request_ = request;
349
350     scoped_ptr<net::test_server::BasicHttpResponse> response(
351         new net::test_server::BasicHttpResponse);
352     response->set_code(net::HTTP_OK);
353     response->set_content_type(expected_content_type_);
354     response->set_content(expected_content_);
355     return response.Pass();
356   }
357
358   // Handles a request for downloading a file.
359   scoped_ptr<net::test_server::HttpResponse> HandleDownloadRequest(
360       const net::test_server::HttpRequest& request) {
361     http_request_ = request;
362
363     const GURL absolute_url = test_server_.GetURL(request.relative_url);
364     std::string id;
365     if (!test_util::RemovePrefix(absolute_url.path(),
366                                  kTestDownloadPathPrefix,
367                                  &id)) {
368       return scoped_ptr<net::test_server::HttpResponse>();
369     }
370
371     // For testing, returns a text with |id| repeated 3 times.
372     scoped_ptr<net::test_server::BasicHttpResponse> response(
373         new net::test_server::BasicHttpResponse);
374     response->set_code(net::HTTP_OK);
375     response->set_content(id + id + id);
376     response->set_content_type("text/plain");
377     return response.Pass();
378   }
379
380   // These are for the current upload file status.
381   int64 received_bytes_;
382   int64 content_length_;
383 };
384
385 TEST_F(DriveApiRequestsTest, DriveApiDataRequest_Fields) {
386   // Make sure that "fields" query param is supported by using its subclass,
387   // AboutGetRequest.
388
389   // Set an expected data file containing valid result.
390   expected_data_file_path_ = test_util::GetTestFilePath(
391       "drive/about.json");
392
393   GDataErrorCode error = GDATA_OTHER_ERROR;
394   scoped_ptr<AboutResource> about_resource;
395
396   {
397     base::RunLoop run_loop;
398     drive::AboutGetRequest* request = new drive::AboutGetRequest(
399         request_sender_.get(),
400         *url_generator_,
401         test_util::CreateQuitCallback(
402             &run_loop,
403             test_util::CreateCopyResultCallback(&error, &about_resource)));
404     request->set_fields(
405         "kind,quotaBytesTotal,quotaBytesUsed,largestChangeId,rootFolderId");
406     request_sender_->StartRequestWithRetry(request);
407     run_loop.Run();
408   }
409
410   EXPECT_EQ(HTTP_SUCCESS, error);
411   EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method);
412   EXPECT_EQ("/drive/v2/about?"
413             "fields=kind%2CquotaBytesTotal%2CquotaBytesUsed%2C"
414             "largestChangeId%2CrootFolderId",
415             http_request_.relative_url);
416
417   scoped_ptr<AboutResource> expected(
418       AboutResource::CreateFrom(
419           *test_util::LoadJSONFile("drive/about.json")));
420   ASSERT_TRUE(about_resource.get());
421   EXPECT_EQ(expected->largest_change_id(), about_resource->largest_change_id());
422   EXPECT_EQ(expected->quota_bytes_total(), about_resource->quota_bytes_total());
423   EXPECT_EQ(expected->quota_bytes_used(), about_resource->quota_bytes_used());
424   EXPECT_EQ(expected->root_folder_id(), about_resource->root_folder_id());
425 }
426
427 TEST_F(DriveApiRequestsTest, FilesInsertRequest) {
428   const base::Time::Exploded kModifiedDate = {2012, 7, 0, 19, 15, 59, 13, 123};
429   const base::Time::Exploded kLastViewedByMeDate =
430       {2013, 7, 0, 19, 15, 59, 13, 123};
431
432   // Set an expected data file containing the directory's entry data.
433   expected_data_file_path_ =
434       test_util::GetTestFilePath("drive/directory_entry.json");
435
436   GDataErrorCode error = GDATA_OTHER_ERROR;
437   scoped_ptr<FileResource> file_resource;
438
439   // Create "new directory" in the root directory.
440   {
441     base::RunLoop run_loop;
442     drive::FilesInsertRequest* request = new drive::FilesInsertRequest(
443         request_sender_.get(),
444         *url_generator_,
445         test_util::CreateQuitCallback(
446             &run_loop,
447             test_util::CreateCopyResultCallback(&error, &file_resource)));
448     request->set_last_viewed_by_me_date(
449         base::Time::FromUTCExploded(kLastViewedByMeDate));
450     request->set_mime_type("application/vnd.google-apps.folder");
451     request->set_modified_date(base::Time::FromUTCExploded(kModifiedDate));
452     request->add_parent("root");
453     request->set_title("new directory");
454     request_sender_->StartRequestWithRetry(request);
455     run_loop.Run();
456   }
457
458   EXPECT_EQ(HTTP_SUCCESS, error);
459   EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method);
460   EXPECT_EQ("/drive/v2/files", http_request_.relative_url);
461   EXPECT_EQ("application/json", http_request_.headers["Content-Type"]);
462
463   EXPECT_TRUE(http_request_.has_content);
464   EXPECT_EQ("{\"lastViewedByMeDate\":\"2013-07-19T15:59:13.123Z\","
465             "\"mimeType\":\"application/vnd.google-apps.folder\","
466             "\"modifiedDate\":\"2012-07-19T15:59:13.123Z\","
467             "\"parents\":[{\"id\":\"root\"}],"
468             "\"title\":\"new directory\"}",
469             http_request_.content);
470
471   scoped_ptr<FileResource> expected(
472       FileResource::CreateFrom(
473           *test_util::LoadJSONFile("drive/directory_entry.json")));
474
475   // Sanity check.
476   ASSERT_TRUE(file_resource.get());
477
478   EXPECT_EQ(expected->file_id(), file_resource->file_id());
479   EXPECT_EQ(expected->title(), file_resource->title());
480   EXPECT_EQ(expected->mime_type(), file_resource->mime_type());
481   EXPECT_EQ(expected->parents().size(), file_resource->parents().size());
482 }
483
484 TEST_F(DriveApiRequestsTest, FilesPatchRequest) {
485   const base::Time::Exploded kModifiedDate = {2012, 7, 0, 19, 15, 59, 13, 123};
486   const base::Time::Exploded kLastViewedByMeDate =
487       {2013, 7, 0, 19, 15, 59, 13, 123};
488
489   // Set an expected data file containing valid result.
490   expected_data_file_path_ =
491       test_util::GetTestFilePath("drive/file_entry.json");
492
493   GDataErrorCode error = GDATA_OTHER_ERROR;
494   scoped_ptr<FileResource> file_resource;
495
496   {
497     base::RunLoop run_loop;
498     drive::FilesPatchRequest* request = new drive::FilesPatchRequest(
499         request_sender_.get(),
500         *url_generator_,
501         test_util::CreateQuitCallback(
502             &run_loop,
503             test_util::CreateCopyResultCallback(&error, &file_resource)));
504     request->set_file_id("resource_id");
505     request->set_set_modified_date(true);
506     request->set_update_viewed_date(false);
507
508     request->set_title("new title");
509     request->set_modified_date(base::Time::FromUTCExploded(kModifiedDate));
510     request->set_last_viewed_by_me_date(
511         base::Time::FromUTCExploded(kLastViewedByMeDate));
512     request->add_parent("parent_resource_id");
513
514     request_sender_->StartRequestWithRetry(request);
515     run_loop.Run();
516   }
517
518   EXPECT_EQ(HTTP_SUCCESS, error);
519   EXPECT_EQ(net::test_server::METHOD_PATCH, http_request_.method);
520   EXPECT_EQ("/drive/v2/files/resource_id"
521             "?setModifiedDate=true&updateViewedDate=false",
522             http_request_.relative_url);
523
524   EXPECT_EQ("application/json", http_request_.headers["Content-Type"]);
525   EXPECT_TRUE(http_request_.has_content);
526   EXPECT_EQ("{\"lastViewedByMeDate\":\"2013-07-19T15:59:13.123Z\","
527             "\"modifiedDate\":\"2012-07-19T15:59:13.123Z\","
528             "\"parents\":[{\"id\":\"parent_resource_id\"}],"
529             "\"title\":\"new title\"}",
530             http_request_.content);
531   EXPECT_TRUE(file_resource);
532 }
533
534 TEST_F(DriveApiRequestsTest, AboutGetRequest_ValidJson) {
535   // Set an expected data file containing valid result.
536   expected_data_file_path_ = test_util::GetTestFilePath(
537       "drive/about.json");
538
539   GDataErrorCode error = GDATA_OTHER_ERROR;
540   scoped_ptr<AboutResource> about_resource;
541
542   {
543     base::RunLoop run_loop;
544     drive::AboutGetRequest* request = new drive::AboutGetRequest(
545         request_sender_.get(),
546         *url_generator_,
547         test_util::CreateQuitCallback(
548             &run_loop,
549             test_util::CreateCopyResultCallback(&error, &about_resource)));
550     request_sender_->StartRequestWithRetry(request);
551     run_loop.Run();
552   }
553
554   EXPECT_EQ(HTTP_SUCCESS, error);
555   EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method);
556   EXPECT_EQ("/drive/v2/about", http_request_.relative_url);
557
558   scoped_ptr<AboutResource> expected(
559       AboutResource::CreateFrom(
560           *test_util::LoadJSONFile("drive/about.json")));
561   ASSERT_TRUE(about_resource.get());
562   EXPECT_EQ(expected->largest_change_id(), about_resource->largest_change_id());
563   EXPECT_EQ(expected->quota_bytes_total(), about_resource->quota_bytes_total());
564   EXPECT_EQ(expected->quota_bytes_used(), about_resource->quota_bytes_used());
565   EXPECT_EQ(expected->root_folder_id(), about_resource->root_folder_id());
566 }
567
568 TEST_F(DriveApiRequestsTest, AboutGetRequest_InvalidJson) {
569   // Set an expected data file containing invalid result.
570   expected_data_file_path_ = test_util::GetTestFilePath(
571       "drive/testfile.txt");
572
573   GDataErrorCode error = GDATA_OTHER_ERROR;
574   scoped_ptr<AboutResource> about_resource;
575
576   {
577     base::RunLoop run_loop;
578     drive::AboutGetRequest* request = new drive::AboutGetRequest(
579         request_sender_.get(),
580         *url_generator_,
581         test_util::CreateQuitCallback(
582             &run_loop,
583             test_util::CreateCopyResultCallback(&error, &about_resource)));
584     request_sender_->StartRequestWithRetry(request);
585     run_loop.Run();
586   }
587
588   // "parse error" should be returned, and the about resource should be NULL.
589   EXPECT_EQ(GDATA_PARSE_ERROR, error);
590   EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method);
591   EXPECT_EQ("/drive/v2/about", http_request_.relative_url);
592   EXPECT_FALSE(about_resource);
593 }
594
595 TEST_F(DriveApiRequestsTest, AppsListRequest) {
596   // Set an expected data file containing valid result.
597   expected_data_file_path_ = test_util::GetTestFilePath(
598       "drive/applist.json");
599
600   GDataErrorCode error = GDATA_OTHER_ERROR;
601   scoped_ptr<AppList> app_list;
602
603   {
604     base::RunLoop run_loop;
605     drive::AppsListRequest* request = new drive::AppsListRequest(
606         request_sender_.get(),
607         *url_generator_,
608         false,  // use_internal_endpoint
609         test_util::CreateQuitCallback(
610             &run_loop,
611             test_util::CreateCopyResultCallback(&error, &app_list)));
612     request_sender_->StartRequestWithRetry(request);
613     run_loop.Run();
614   }
615
616   EXPECT_EQ(HTTP_SUCCESS, error);
617   EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method);
618   EXPECT_EQ("/drive/v2/apps", http_request_.relative_url);
619   EXPECT_TRUE(app_list);
620 }
621
622 TEST_F(DriveApiRequestsTest, ChangesListRequest) {
623   // Set an expected data file containing valid result.
624   expected_data_file_path_ = test_util::GetTestFilePath(
625       "drive/changelist.json");
626
627   GDataErrorCode error = GDATA_OTHER_ERROR;
628   scoped_ptr<ChangeList> result;
629
630   {
631     base::RunLoop run_loop;
632     drive::ChangesListRequest* request = new drive::ChangesListRequest(
633         request_sender_.get(), *url_generator_,
634         test_util::CreateQuitCallback(
635             &run_loop,
636             test_util::CreateCopyResultCallback(&error, &result)));
637     request->set_include_deleted(true);
638     request->set_start_change_id(100);
639     request->set_max_results(500);
640     request_sender_->StartRequestWithRetry(request);
641     run_loop.Run();
642   }
643
644   EXPECT_EQ(HTTP_SUCCESS, error);
645   EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method);
646   EXPECT_EQ("/drive/v2/changes?maxResults=500&startChangeId=100",
647             http_request_.relative_url);
648   EXPECT_TRUE(result);
649 }
650
651 TEST_F(DriveApiRequestsTest, ChangesListNextPageRequest) {
652   // Set an expected data file containing valid result.
653   expected_data_file_path_ = test_util::GetTestFilePath(
654       "drive/changelist.json");
655
656   GDataErrorCode error = GDATA_OTHER_ERROR;
657   scoped_ptr<ChangeList> result;
658
659   {
660     base::RunLoop run_loop;
661     drive::ChangesListNextPageRequest* request =
662         new drive::ChangesListNextPageRequest(
663             request_sender_.get(),
664             test_util::CreateQuitCallback(
665                 &run_loop,
666                 test_util::CreateCopyResultCallback(&error, &result)));
667     request->set_next_link(test_server_.GetURL("/continue/get/change/list"));
668     request_sender_->StartRequestWithRetry(request);
669     run_loop.Run();
670   }
671
672   EXPECT_EQ(HTTP_SUCCESS, error);
673   EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method);
674   EXPECT_EQ("/continue/get/change/list", http_request_.relative_url);
675   EXPECT_TRUE(result);
676 }
677
678 TEST_F(DriveApiRequestsTest, FilesCopyRequest) {
679   const base::Time::Exploded kModifiedDate = {2012, 7, 0, 19, 15, 59, 13, 123};
680
681   // Set an expected data file containing the dummy file entry data.
682   // It'd be returned if we copy a file.
683   expected_data_file_path_ =
684       test_util::GetTestFilePath("drive/file_entry.json");
685
686   GDataErrorCode error = GDATA_OTHER_ERROR;
687   scoped_ptr<FileResource> file_resource;
688
689   // Copy the file to a new file named "new title".
690   {
691     base::RunLoop run_loop;
692     drive::FilesCopyRequest* request = new drive::FilesCopyRequest(
693         request_sender_.get(),
694         *url_generator_,
695         test_util::CreateQuitCallback(
696             &run_loop,
697             test_util::CreateCopyResultCallback(&error, &file_resource)));
698     request->set_file_id("resource_id");
699     request->set_modified_date(base::Time::FromUTCExploded(kModifiedDate));
700     request->add_parent("parent_resource_id");
701     request->set_title("new title");
702     request_sender_->StartRequestWithRetry(request);
703     run_loop.Run();
704   }
705
706   EXPECT_EQ(HTTP_SUCCESS, error);
707   EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method);
708   EXPECT_EQ("/drive/v2/files/resource_id/copy", http_request_.relative_url);
709   EXPECT_EQ("application/json", http_request_.headers["Content-Type"]);
710
711   EXPECT_TRUE(http_request_.has_content);
712   EXPECT_EQ(
713       "{\"modifiedDate\":\"2012-07-19T15:59:13.123Z\","
714       "\"parents\":[{\"id\":\"parent_resource_id\"}],\"title\":\"new title\"}",
715       http_request_.content);
716   EXPECT_TRUE(file_resource);
717 }
718
719 TEST_F(DriveApiRequestsTest, FilesCopyRequest_EmptyParentResourceId) {
720   // Set an expected data file containing the dummy file entry data.
721   // It'd be returned if we copy a file.
722   expected_data_file_path_ =
723       test_util::GetTestFilePath("drive/file_entry.json");
724
725   GDataErrorCode error = GDATA_OTHER_ERROR;
726   scoped_ptr<FileResource> file_resource;
727
728   // Copy the file to a new file named "new title".
729   {
730     base::RunLoop run_loop;
731     drive::FilesCopyRequest* request = new drive::FilesCopyRequest(
732         request_sender_.get(),
733         *url_generator_,
734         test_util::CreateQuitCallback(
735             &run_loop,
736             test_util::CreateCopyResultCallback(&error, &file_resource)));
737     request->set_file_id("resource_id");
738     request->set_title("new title");
739     request_sender_->StartRequestWithRetry(request);
740     run_loop.Run();
741   }
742
743   EXPECT_EQ(HTTP_SUCCESS, error);
744   EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method);
745   EXPECT_EQ("/drive/v2/files/resource_id/copy", http_request_.relative_url);
746   EXPECT_EQ("application/json", http_request_.headers["Content-Type"]);
747
748   EXPECT_TRUE(http_request_.has_content);
749   EXPECT_EQ("{\"title\":\"new title\"}", http_request_.content);
750   EXPECT_TRUE(file_resource);
751 }
752
753 TEST_F(DriveApiRequestsTest, FilesListRequest) {
754   // Set an expected data file containing valid result.
755   expected_data_file_path_ = test_util::GetTestFilePath(
756       "drive/filelist.json");
757
758   GDataErrorCode error = GDATA_OTHER_ERROR;
759   scoped_ptr<FileList> result;
760
761   {
762     base::RunLoop run_loop;
763     drive::FilesListRequest* request = new drive::FilesListRequest(
764         request_sender_.get(), *url_generator_,
765         test_util::CreateQuitCallback(
766             &run_loop,
767             test_util::CreateCopyResultCallback(&error, &result)));
768     request->set_max_results(50);
769     request->set_q("\"abcde\" in parents");
770     request_sender_->StartRequestWithRetry(request);
771     run_loop.Run();
772   }
773
774   EXPECT_EQ(HTTP_SUCCESS, error);
775   EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method);
776   EXPECT_EQ("/drive/v2/files?maxResults=50&q=%22abcde%22+in+parents",
777             http_request_.relative_url);
778   EXPECT_TRUE(result);
779 }
780
781 TEST_F(DriveApiRequestsTest, FilesListNextPageRequest) {
782   // Set an expected data file containing valid result.
783   expected_data_file_path_ = test_util::GetTestFilePath(
784       "drive/filelist.json");
785
786   GDataErrorCode error = GDATA_OTHER_ERROR;
787   scoped_ptr<FileList> result;
788
789   {
790     base::RunLoop run_loop;
791     drive::FilesListNextPageRequest* request =
792         new drive::FilesListNextPageRequest(
793             request_sender_.get(),
794             test_util::CreateQuitCallback(
795                 &run_loop,
796                 test_util::CreateCopyResultCallback(&error, &result)));
797     request->set_next_link(test_server_.GetURL("/continue/get/file/list"));
798     request_sender_->StartRequestWithRetry(request);
799     run_loop.Run();
800   }
801
802   EXPECT_EQ(HTTP_SUCCESS, error);
803   EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method);
804   EXPECT_EQ("/continue/get/file/list", http_request_.relative_url);
805   EXPECT_TRUE(result);
806 }
807
808 TEST_F(DriveApiRequestsTest, FilesDeleteRequest) {
809   GDataErrorCode error = GDATA_OTHER_ERROR;
810
811   // Delete a resource with the given resource id.
812   {
813     base::RunLoop run_loop;
814     drive::FilesDeleteRequest* request = new drive::FilesDeleteRequest(
815         request_sender_.get(),
816         *url_generator_,
817         test_util::CreateQuitCallback(
818             &run_loop, test_util::CreateCopyResultCallback(&error)));
819     request->set_file_id("resource_id");
820     request->set_etag(kTestETag);
821     request_sender_->StartRequestWithRetry(request);
822     run_loop.Run();
823   }
824
825   EXPECT_EQ(HTTP_NO_CONTENT, error);
826   EXPECT_EQ(net::test_server::METHOD_DELETE, http_request_.method);
827   EXPECT_EQ(kTestETag, http_request_.headers["If-Match"]);
828   EXPECT_EQ("/drive/v2/files/resource_id", http_request_.relative_url);
829   EXPECT_FALSE(http_request_.has_content);
830 }
831
832 TEST_F(DriveApiRequestsTest, FilesTrashRequest) {
833   // Set data for the expected result. Directory entry should be returned
834   // if the trashing entry is a directory, so using it here should be fine.
835   expected_data_file_path_ =
836       test_util::GetTestFilePath("drive/directory_entry.json");
837
838   GDataErrorCode error = GDATA_OTHER_ERROR;
839   scoped_ptr<FileResource> file_resource;
840
841   // Trash a resource with the given resource id.
842   {
843     base::RunLoop run_loop;
844     drive::FilesTrashRequest* request = new drive::FilesTrashRequest(
845         request_sender_.get(),
846         *url_generator_,
847         test_util::CreateQuitCallback(
848             &run_loop,
849             test_util::CreateCopyResultCallback(&error, &file_resource)));
850     request->set_file_id("resource_id");
851     request_sender_->StartRequestWithRetry(request);
852     run_loop.Run();
853   }
854
855   EXPECT_EQ(HTTP_SUCCESS, error);
856   EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method);
857   EXPECT_EQ("/drive/v2/files/resource_id/trash", http_request_.relative_url);
858   EXPECT_TRUE(http_request_.has_content);
859   EXPECT_TRUE(http_request_.content.empty());
860 }
861
862 TEST_F(DriveApiRequestsTest, ChildrenInsertRequest) {
863   // Set an expected data file containing the children entry.
864   expected_content_type_ = "application/json";
865   expected_content_ = kTestChildrenResponse;
866
867   GDataErrorCode error = GDATA_OTHER_ERROR;
868
869   // Add a resource with "resource_id" to a directory with
870   // "parent_resource_id".
871   {
872     base::RunLoop run_loop;
873     drive::ChildrenInsertRequest* request = new drive::ChildrenInsertRequest(
874         request_sender_.get(),
875         *url_generator_,
876         test_util::CreateQuitCallback(
877             &run_loop,
878             test_util::CreateCopyResultCallback(&error)));
879     request->set_folder_id("parent_resource_id");
880     request->set_id("resource_id");
881     request_sender_->StartRequestWithRetry(request);
882     run_loop.Run();
883   }
884
885   EXPECT_EQ(HTTP_SUCCESS, error);
886   EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method);
887   EXPECT_EQ("/drive/v2/files/parent_resource_id/children",
888             http_request_.relative_url);
889   EXPECT_EQ("application/json", http_request_.headers["Content-Type"]);
890
891   EXPECT_TRUE(http_request_.has_content);
892   EXPECT_EQ("{\"id\":\"resource_id\"}", http_request_.content);
893 }
894
895 TEST_F(DriveApiRequestsTest, ChildrenDeleteRequest) {
896   GDataErrorCode error = GDATA_OTHER_ERROR;
897
898   // Remove a resource with "resource_id" from a directory with
899   // "parent_resource_id".
900   {
901     base::RunLoop run_loop;
902     drive::ChildrenDeleteRequest* request = new drive::ChildrenDeleteRequest(
903         request_sender_.get(),
904         *url_generator_,
905         test_util::CreateQuitCallback(
906             &run_loop,
907             test_util::CreateCopyResultCallback(&error)));
908     request->set_child_id("resource_id");
909     request->set_folder_id("parent_resource_id");
910     request_sender_->StartRequestWithRetry(request);
911     run_loop.Run();
912   }
913
914   EXPECT_EQ(HTTP_NO_CONTENT, error);
915   EXPECT_EQ(net::test_server::METHOD_DELETE, http_request_.method);
916   EXPECT_EQ("/drive/v2/files/parent_resource_id/children/resource_id",
917             http_request_.relative_url);
918   EXPECT_FALSE(http_request_.has_content);
919 }
920
921 TEST_F(DriveApiRequestsTest, UploadNewFileRequest) {
922   // Set an expected url for uploading.
923   expected_upload_path_ = kTestUploadNewFilePath;
924
925   const char kTestContentType[] = "text/plain";
926   const std::string kTestContent(100, 'a');
927   const base::FilePath kTestFilePath =
928       temp_dir_.path().AppendASCII("upload_file.txt");
929   ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent));
930
931   GDataErrorCode error = GDATA_OTHER_ERROR;
932   GURL upload_url;
933
934   // Initiate uploading a new file to the directory with
935   // "parent_resource_id".
936   {
937     base::RunLoop run_loop;
938     drive::InitiateUploadNewFileRequest* request =
939         new drive::InitiateUploadNewFileRequest(
940             request_sender_.get(),
941             *url_generator_,
942             kTestContentType,
943             kTestContent.size(),
944             "parent_resource_id",  // The resource id of the parent directory.
945             "new file title",  // The title of the file being uploaded.
946             test_util::CreateQuitCallback(
947                 &run_loop,
948                 test_util::CreateCopyResultCallback(&error, &upload_url)));
949     request_sender_->StartRequestWithRetry(request);
950     run_loop.Run();
951   }
952
953   EXPECT_EQ(HTTP_SUCCESS, error);
954   EXPECT_EQ(kTestUploadNewFilePath, upload_url.path());
955   EXPECT_EQ(kTestContentType, http_request_.headers["X-Upload-Content-Type"]);
956   EXPECT_EQ(base::Int64ToString(kTestContent.size()),
957             http_request_.headers["X-Upload-Content-Length"]);
958
959   EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method);
960   EXPECT_EQ("/upload/drive/v2/files?uploadType=resumable",
961             http_request_.relative_url);
962   EXPECT_EQ("application/json", http_request_.headers["Content-Type"]);
963   EXPECT_TRUE(http_request_.has_content);
964   EXPECT_EQ("{\"parents\":[{"
965             "\"id\":\"parent_resource_id\","
966             "\"kind\":\"drive#fileLink\""
967             "}],"
968             "\"title\":\"new file title\"}",
969             http_request_.content);
970
971   // Upload the content to the upload URL.
972   UploadRangeResponse response;
973   scoped_ptr<FileResource> new_entry;
974
975   {
976     base::RunLoop run_loop;
977     drive::ResumeUploadRequest* resume_request =
978         new drive::ResumeUploadRequest(
979             request_sender_.get(),
980             upload_url,
981             0,  // start_position
982             kTestContent.size(),  // end_position (exclusive)
983             kTestContent.size(),  // content_length,
984             kTestContentType,
985             kTestFilePath,
986             test_util::CreateQuitCallback(
987                 &run_loop,
988                 test_util::CreateCopyResultCallback(&response, &new_entry)),
989             ProgressCallback());
990     request_sender_->StartRequestWithRetry(resume_request);
991     run_loop.Run();
992   }
993
994   // METHOD_PUT should be used to upload data.
995   EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method);
996   // Request should go to the upload URL.
997   EXPECT_EQ(upload_url.path(), http_request_.relative_url);
998   // Content-Range header should be added.
999   EXPECT_EQ("bytes 0-" +
1000             base::Int64ToString(kTestContent.size() - 1) + "/" +
1001             base::Int64ToString(kTestContent.size()),
1002             http_request_.headers["Content-Range"]);
1003   // The upload content should be set in the HTTP request.
1004   EXPECT_TRUE(http_request_.has_content);
1005   EXPECT_EQ(kTestContent, http_request_.content);
1006
1007   // Check the response.
1008   EXPECT_EQ(HTTP_CREATED, response.code);  // Because it's a new file
1009   // The start and end positions should be set to -1, if an upload is complete.
1010   EXPECT_EQ(-1, response.start_position_received);
1011   EXPECT_EQ(-1, response.end_position_received);
1012 }
1013
1014 TEST_F(DriveApiRequestsTest, UploadNewEmptyFileRequest) {
1015   // Set an expected url for uploading.
1016   expected_upload_path_ = kTestUploadNewFilePath;
1017
1018   const char kTestContentType[] = "text/plain";
1019   const char kTestContent[] = "";
1020   const base::FilePath kTestFilePath =
1021       temp_dir_.path().AppendASCII("empty_file.txt");
1022   ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent));
1023
1024   GDataErrorCode error = GDATA_OTHER_ERROR;
1025   GURL upload_url;
1026
1027   // Initiate uploading a new file to the directory with "parent_resource_id".
1028   {
1029     base::RunLoop run_loop;
1030     drive::InitiateUploadNewFileRequest* request =
1031         new drive::InitiateUploadNewFileRequest(
1032             request_sender_.get(),
1033             *url_generator_,
1034             kTestContentType,
1035             0,
1036             "parent_resource_id",  // The resource id of the parent directory.
1037             "new file title",  // The title of the file being uploaded.
1038             test_util::CreateQuitCallback(
1039                 &run_loop,
1040                 test_util::CreateCopyResultCallback(&error, &upload_url)));
1041     request_sender_->StartRequestWithRetry(request);
1042     run_loop.Run();
1043   }
1044
1045   EXPECT_EQ(HTTP_SUCCESS, error);
1046   EXPECT_EQ(kTestUploadNewFilePath, upload_url.path());
1047   EXPECT_EQ(kTestContentType, http_request_.headers["X-Upload-Content-Type"]);
1048   EXPECT_EQ("0", http_request_.headers["X-Upload-Content-Length"]);
1049
1050   EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method);
1051   EXPECT_EQ("/upload/drive/v2/files?uploadType=resumable",
1052             http_request_.relative_url);
1053   EXPECT_EQ("application/json", http_request_.headers["Content-Type"]);
1054   EXPECT_TRUE(http_request_.has_content);
1055   EXPECT_EQ("{\"parents\":[{"
1056             "\"id\":\"parent_resource_id\","
1057             "\"kind\":\"drive#fileLink\""
1058             "}],"
1059             "\"title\":\"new file title\"}",
1060             http_request_.content);
1061
1062   // Upload the content to the upload URL.
1063   UploadRangeResponse response;
1064   scoped_ptr<FileResource> new_entry;
1065
1066   {
1067     base::RunLoop run_loop;
1068     drive::ResumeUploadRequest* resume_request =
1069         new drive::ResumeUploadRequest(
1070             request_sender_.get(),
1071             upload_url,
1072             0,  // start_position
1073             0,  // end_position (exclusive)
1074             0,  // content_length,
1075             kTestContentType,
1076             kTestFilePath,
1077             test_util::CreateQuitCallback(
1078                 &run_loop,
1079                 test_util::CreateCopyResultCallback(&response, &new_entry)),
1080             ProgressCallback());
1081     request_sender_->StartRequestWithRetry(resume_request);
1082     run_loop.Run();
1083   }
1084
1085   // METHOD_PUT should be used to upload data.
1086   EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method);
1087   // Request should go to the upload URL.
1088   EXPECT_EQ(upload_url.path(), http_request_.relative_url);
1089   // Content-Range header should NOT be added.
1090   EXPECT_EQ(0U, http_request_.headers.count("Content-Range"));
1091   // The upload content should be set in the HTTP request.
1092   EXPECT_TRUE(http_request_.has_content);
1093   EXPECT_EQ(kTestContent, http_request_.content);
1094
1095   // Check the response.
1096   EXPECT_EQ(HTTP_CREATED, response.code);  // Because it's a new file
1097   // The start and end positions should be set to -1, if an upload is complete.
1098   EXPECT_EQ(-1, response.start_position_received);
1099   EXPECT_EQ(-1, response.end_position_received);
1100 }
1101
1102 TEST_F(DriveApiRequestsTest, UploadNewLargeFileRequest) {
1103   // Set an expected url for uploading.
1104   expected_upload_path_ = kTestUploadNewFilePath;
1105
1106   const char kTestContentType[] = "text/plain";
1107   const size_t kNumChunkBytes = 10;  // Num bytes in a chunk.
1108   const std::string kTestContent(100, 'a');
1109   const base::FilePath kTestFilePath =
1110       temp_dir_.path().AppendASCII("upload_file.txt");
1111   ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent));
1112
1113   GDataErrorCode error = GDATA_OTHER_ERROR;
1114   GURL upload_url;
1115
1116   // Initiate uploading a new file to the directory with "parent_resource_id".
1117   {
1118     base::RunLoop run_loop;
1119     drive::InitiateUploadNewFileRequest* request =
1120         new drive::InitiateUploadNewFileRequest(
1121             request_sender_.get(),
1122             *url_generator_,
1123             kTestContentType,
1124             kTestContent.size(),
1125             "parent_resource_id",  // The resource id of the parent directory.
1126             "new file title",  // The title of the file being uploaded.
1127             test_util::CreateQuitCallback(
1128                 &run_loop,
1129                 test_util::CreateCopyResultCallback(&error, &upload_url)));
1130     request_sender_->StartRequestWithRetry(request);
1131     run_loop.Run();
1132   }
1133
1134   EXPECT_EQ(HTTP_SUCCESS, error);
1135   EXPECT_EQ(kTestUploadNewFilePath, upload_url.path());
1136   EXPECT_EQ(kTestContentType, http_request_.headers["X-Upload-Content-Type"]);
1137   EXPECT_EQ(base::Int64ToString(kTestContent.size()),
1138             http_request_.headers["X-Upload-Content-Length"]);
1139
1140   EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method);
1141   EXPECT_EQ("/upload/drive/v2/files?uploadType=resumable",
1142             http_request_.relative_url);
1143   EXPECT_EQ("application/json", http_request_.headers["Content-Type"]);
1144   EXPECT_TRUE(http_request_.has_content);
1145   EXPECT_EQ("{\"parents\":[{"
1146             "\"id\":\"parent_resource_id\","
1147             "\"kind\":\"drive#fileLink\""
1148             "}],"
1149             "\"title\":\"new file title\"}",
1150             http_request_.content);
1151
1152   // Before sending any data, check the current status.
1153   // This is an edge case test for GetUploadStatusRequest.
1154   {
1155     UploadRangeResponse response;
1156     scoped_ptr<FileResource> new_entry;
1157
1158     // Check the response by GetUploadStatusRequest.
1159     {
1160       base::RunLoop run_loop;
1161       drive::GetUploadStatusRequest* get_upload_status_request =
1162           new drive::GetUploadStatusRequest(
1163               request_sender_.get(),
1164               upload_url,
1165               kTestContent.size(),
1166               test_util::CreateQuitCallback(
1167                   &run_loop,
1168                   test_util::CreateCopyResultCallback(&response, &new_entry)));
1169       request_sender_->StartRequestWithRetry(get_upload_status_request);
1170       run_loop.Run();
1171     }
1172
1173     // METHOD_PUT should be used to upload data.
1174     EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method);
1175     // Request should go to the upload URL.
1176     EXPECT_EQ(upload_url.path(), http_request_.relative_url);
1177     // Content-Range header should be added.
1178     EXPECT_EQ("bytes */" + base::Int64ToString(kTestContent.size()),
1179               http_request_.headers["Content-Range"]);
1180     EXPECT_TRUE(http_request_.has_content);
1181     EXPECT_TRUE(http_request_.content.empty());
1182
1183     // Check the response.
1184     EXPECT_EQ(HTTP_RESUME_INCOMPLETE, response.code);
1185     EXPECT_EQ(0, response.start_position_received);
1186     EXPECT_EQ(0, response.end_position_received);
1187   }
1188
1189   // Upload the content to the upload URL.
1190   for (size_t start_position = 0; start_position < kTestContent.size();
1191        start_position += kNumChunkBytes) {
1192     const std::string payload = kTestContent.substr(
1193         start_position,
1194         std::min(kNumChunkBytes, kTestContent.size() - start_position));
1195     const size_t end_position = start_position + payload.size();
1196
1197     UploadRangeResponse response;
1198     scoped_ptr<FileResource> new_entry;
1199
1200     {
1201       base::RunLoop run_loop;
1202       drive::ResumeUploadRequest* resume_request =
1203           new drive::ResumeUploadRequest(
1204               request_sender_.get(),
1205               upload_url,
1206               start_position,
1207               end_position,
1208               kTestContent.size(),  // content_length,
1209               kTestContentType,
1210               kTestFilePath,
1211               test_util::CreateQuitCallback(
1212                   &run_loop,
1213                   test_util::CreateCopyResultCallback(&response, &new_entry)),
1214               ProgressCallback());
1215       request_sender_->StartRequestWithRetry(resume_request);
1216       run_loop.Run();
1217     }
1218
1219     // METHOD_PUT should be used to upload data.
1220     EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method);
1221     // Request should go to the upload URL.
1222     EXPECT_EQ(upload_url.path(), http_request_.relative_url);
1223     // Content-Range header should be added.
1224     EXPECT_EQ("bytes " +
1225               base::Int64ToString(start_position) + "-" +
1226               base::Int64ToString(end_position - 1) + "/" +
1227               base::Int64ToString(kTestContent.size()),
1228               http_request_.headers["Content-Range"]);
1229     // The upload content should be set in the HTTP request.
1230     EXPECT_TRUE(http_request_.has_content);
1231     EXPECT_EQ(payload, http_request_.content);
1232
1233     if (end_position == kTestContent.size()) {
1234       // Check the response.
1235       EXPECT_EQ(HTTP_CREATED, response.code);  // Because it's a new file
1236       // The start and end positions should be set to -1, if an upload is
1237       // complete.
1238       EXPECT_EQ(-1, response.start_position_received);
1239       EXPECT_EQ(-1, response.end_position_received);
1240       break;
1241     }
1242
1243     // Check the response.
1244     EXPECT_EQ(HTTP_RESUME_INCOMPLETE, response.code);
1245     EXPECT_EQ(0, response.start_position_received);
1246     EXPECT_EQ(static_cast<int64>(end_position), response.end_position_received);
1247
1248     // Check the response by GetUploadStatusRequest.
1249     {
1250       base::RunLoop run_loop;
1251       drive::GetUploadStatusRequest* get_upload_status_request =
1252           new drive::GetUploadStatusRequest(
1253               request_sender_.get(),
1254               upload_url,
1255               kTestContent.size(),
1256               test_util::CreateQuitCallback(
1257                   &run_loop,
1258                   test_util::CreateCopyResultCallback(&response, &new_entry)));
1259       request_sender_->StartRequestWithRetry(get_upload_status_request);
1260       run_loop.Run();
1261     }
1262
1263     // METHOD_PUT should be used to upload data.
1264     EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method);
1265     // Request should go to the upload URL.
1266     EXPECT_EQ(upload_url.path(), http_request_.relative_url);
1267     // Content-Range header should be added.
1268     EXPECT_EQ("bytes */" + base::Int64ToString(kTestContent.size()),
1269               http_request_.headers["Content-Range"]);
1270     EXPECT_TRUE(http_request_.has_content);
1271     EXPECT_TRUE(http_request_.content.empty());
1272
1273     // Check the response.
1274     EXPECT_EQ(HTTP_RESUME_INCOMPLETE, response.code);
1275     EXPECT_EQ(0, response.start_position_received);
1276     EXPECT_EQ(static_cast<int64>(end_position),
1277               response.end_position_received);
1278   }
1279 }
1280
1281 TEST_F(DriveApiRequestsTest, UploadNewFileWithMetadataRequest) {
1282   const base::Time::Exploded kModifiedDate = {2012, 7, 0, 19, 15, 59, 13, 123};
1283   const base::Time::Exploded kLastViewedByMeDate =
1284       {2013, 7, 0, 19, 15, 59, 13, 123};
1285
1286   // Set an expected url for uploading.
1287   expected_upload_path_ = kTestUploadNewFilePath;
1288
1289   const char kTestContentType[] = "text/plain";
1290   const std::string kTestContent(100, 'a');
1291
1292   GDataErrorCode error = GDATA_OTHER_ERROR;
1293   GURL upload_url;
1294
1295   // Initiate uploading a new file to the directory with "parent_resource_id".
1296   {
1297     base::RunLoop run_loop;
1298     drive::InitiateUploadNewFileRequest* request =
1299         new drive::InitiateUploadNewFileRequest(
1300             request_sender_.get(),
1301             *url_generator_,
1302             kTestContentType,
1303             kTestContent.size(),
1304             "parent_resource_id",  // The resource id of the parent directory.
1305             "new file title",  // The title of the file being uploaded.
1306             test_util::CreateQuitCallback(
1307                 &run_loop,
1308                 test_util::CreateCopyResultCallback(&error, &upload_url)));
1309     request->set_modified_date(base::Time::FromUTCExploded(kModifiedDate));
1310     request->set_last_viewed_by_me_date(
1311         base::Time::FromUTCExploded(kLastViewedByMeDate));
1312     request_sender_->StartRequestWithRetry(request);
1313     run_loop.Run();
1314   }
1315
1316   EXPECT_EQ(HTTP_SUCCESS, error);
1317   EXPECT_EQ(kTestUploadNewFilePath, upload_url.path());
1318   EXPECT_EQ(kTestContentType, http_request_.headers["X-Upload-Content-Type"]);
1319   EXPECT_EQ(base::Int64ToString(kTestContent.size()),
1320             http_request_.headers["X-Upload-Content-Length"]);
1321
1322   EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method);
1323   EXPECT_EQ("/upload/drive/v2/files?uploadType=resumable&setModifiedDate=true",
1324             http_request_.relative_url);
1325   EXPECT_EQ("application/json", http_request_.headers["Content-Type"]);
1326   EXPECT_TRUE(http_request_.has_content);
1327   EXPECT_EQ("{\"lastViewedByMeDate\":\"2013-07-19T15:59:13.123Z\","
1328             "\"modifiedDate\":\"2012-07-19T15:59:13.123Z\","
1329             "\"parents\":[{\"id\":\"parent_resource_id\","
1330             "\"kind\":\"drive#fileLink\"}],"
1331             "\"title\":\"new file title\"}",
1332             http_request_.content);
1333 }
1334
1335 TEST_F(DriveApiRequestsTest, UploadExistingFileRequest) {
1336   // Set an expected url for uploading.
1337   expected_upload_path_ = kTestUploadExistingFilePath;
1338
1339   const char kTestContentType[] = "text/plain";
1340   const std::string kTestContent(100, 'a');
1341   const base::FilePath kTestFilePath =
1342       temp_dir_.path().AppendASCII("upload_file.txt");
1343   ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent));
1344
1345   GDataErrorCode error = GDATA_OTHER_ERROR;
1346   GURL upload_url;
1347
1348   // Initiate uploading a new file to the directory with "parent_resource_id".
1349   {
1350     base::RunLoop run_loop;
1351     drive::InitiateUploadExistingFileRequest* request =
1352         new drive::InitiateUploadExistingFileRequest(
1353             request_sender_.get(),
1354             *url_generator_,
1355             kTestContentType,
1356             kTestContent.size(),
1357             "resource_id",  // The resource id of the file to be overwritten.
1358             std::string(),  // No etag.
1359             test_util::CreateQuitCallback(
1360                 &run_loop,
1361                 test_util::CreateCopyResultCallback(&error, &upload_url)));
1362     request_sender_->StartRequestWithRetry(request);
1363     run_loop.Run();
1364   }
1365
1366   EXPECT_EQ(HTTP_SUCCESS, error);
1367   EXPECT_EQ(kTestUploadExistingFilePath, upload_url.path());
1368   EXPECT_EQ(kTestContentType, http_request_.headers["X-Upload-Content-Type"]);
1369   EXPECT_EQ(base::Int64ToString(kTestContent.size()),
1370             http_request_.headers["X-Upload-Content-Length"]);
1371   EXPECT_EQ("*", http_request_.headers["If-Match"]);
1372
1373   EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method);
1374   EXPECT_EQ("/upload/drive/v2/files/resource_id?uploadType=resumable",
1375             http_request_.relative_url);
1376   EXPECT_TRUE(http_request_.has_content);
1377   EXPECT_TRUE(http_request_.content.empty());
1378
1379   // Upload the content to the upload URL.
1380   UploadRangeResponse response;
1381   scoped_ptr<FileResource> new_entry;
1382
1383   {
1384     base::RunLoop run_loop;
1385     drive::ResumeUploadRequest* resume_request =
1386         new drive::ResumeUploadRequest(
1387             request_sender_.get(),
1388             upload_url,
1389             0,  // start_position
1390             kTestContent.size(),  // end_position (exclusive)
1391             kTestContent.size(),  // content_length,
1392             kTestContentType,
1393             kTestFilePath,
1394             test_util::CreateQuitCallback(
1395                 &run_loop,
1396                 test_util::CreateCopyResultCallback(&response, &new_entry)),
1397             ProgressCallback());
1398     request_sender_->StartRequestWithRetry(resume_request);
1399     run_loop.Run();
1400   }
1401
1402   // METHOD_PUT should be used to upload data.
1403   EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method);
1404   // Request should go to the upload URL.
1405   EXPECT_EQ(upload_url.path(), http_request_.relative_url);
1406   // Content-Range header should be added.
1407   EXPECT_EQ("bytes 0-" +
1408             base::Int64ToString(kTestContent.size() - 1) + "/" +
1409             base::Int64ToString(kTestContent.size()),
1410             http_request_.headers["Content-Range"]);
1411   // The upload content should be set in the HTTP request.
1412   EXPECT_TRUE(http_request_.has_content);
1413   EXPECT_EQ(kTestContent, http_request_.content);
1414
1415   // Check the response.
1416   EXPECT_EQ(HTTP_SUCCESS, response.code);  // Because it's an existing file
1417   // The start and end positions should be set to -1, if an upload is complete.
1418   EXPECT_EQ(-1, response.start_position_received);
1419   EXPECT_EQ(-1, response.end_position_received);
1420 }
1421
1422 TEST_F(DriveApiRequestsTest, UploadExistingFileRequestWithETag) {
1423   // Set an expected url for uploading.
1424   expected_upload_path_ = kTestUploadExistingFilePath;
1425
1426   const char kTestContentType[] = "text/plain";
1427   const std::string kTestContent(100, 'a');
1428   const base::FilePath kTestFilePath =
1429       temp_dir_.path().AppendASCII("upload_file.txt");
1430   ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent));
1431
1432   GDataErrorCode error = GDATA_OTHER_ERROR;
1433   GURL upload_url;
1434
1435   // Initiate uploading a new file to the directory with "parent_resource_id".
1436   {
1437     base::RunLoop run_loop;
1438     drive::InitiateUploadExistingFileRequest* request =
1439         new drive::InitiateUploadExistingFileRequest(
1440             request_sender_.get(),
1441             *url_generator_,
1442             kTestContentType,
1443             kTestContent.size(),
1444             "resource_id",  // The resource id of the file to be overwritten.
1445             kTestETag,
1446             test_util::CreateQuitCallback(
1447                 &run_loop,
1448                 test_util::CreateCopyResultCallback(&error, &upload_url)));
1449     request_sender_->StartRequestWithRetry(request);
1450     run_loop.Run();
1451   }
1452
1453   EXPECT_EQ(HTTP_SUCCESS, error);
1454   EXPECT_EQ(kTestUploadExistingFilePath, upload_url.path());
1455   EXPECT_EQ(kTestContentType, http_request_.headers["X-Upload-Content-Type"]);
1456   EXPECT_EQ(base::Int64ToString(kTestContent.size()),
1457             http_request_.headers["X-Upload-Content-Length"]);
1458   EXPECT_EQ(kTestETag, http_request_.headers["If-Match"]);
1459
1460   EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method);
1461   EXPECT_EQ("/upload/drive/v2/files/resource_id?uploadType=resumable",
1462             http_request_.relative_url);
1463   EXPECT_TRUE(http_request_.has_content);
1464   EXPECT_TRUE(http_request_.content.empty());
1465
1466   // Upload the content to the upload URL.
1467   UploadRangeResponse response;
1468   scoped_ptr<FileResource> new_entry;
1469
1470   {
1471     base::RunLoop run_loop;
1472     drive::ResumeUploadRequest* resume_request =
1473         new drive::ResumeUploadRequest(
1474             request_sender_.get(),
1475             upload_url,
1476             0,  // start_position
1477             kTestContent.size(),  // end_position (exclusive)
1478             kTestContent.size(),  // content_length,
1479             kTestContentType,
1480             kTestFilePath,
1481             test_util::CreateQuitCallback(
1482                 &run_loop,
1483                 test_util::CreateCopyResultCallback(&response, &new_entry)),
1484             ProgressCallback());
1485     request_sender_->StartRequestWithRetry(resume_request);
1486     run_loop.Run();
1487   }
1488
1489   // METHOD_PUT should be used to upload data.
1490   EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method);
1491   // Request should go to the upload URL.
1492   EXPECT_EQ(upload_url.path(), http_request_.relative_url);
1493   // Content-Range header should be added.
1494   EXPECT_EQ("bytes 0-" +
1495             base::Int64ToString(kTestContent.size() - 1) + "/" +
1496             base::Int64ToString(kTestContent.size()),
1497             http_request_.headers["Content-Range"]);
1498   // The upload content should be set in the HTTP request.
1499   EXPECT_TRUE(http_request_.has_content);
1500   EXPECT_EQ(kTestContent, http_request_.content);
1501
1502   // Check the response.
1503   EXPECT_EQ(HTTP_SUCCESS, response.code);  // Because it's an existing file
1504   // The start and end positions should be set to -1, if an upload is complete.
1505   EXPECT_EQ(-1, response.start_position_received);
1506   EXPECT_EQ(-1, response.end_position_received);
1507 }
1508
1509 TEST_F(DriveApiRequestsTest, UploadExistingFileRequestWithETagConflicting) {
1510   // Set an expected url for uploading.
1511   expected_upload_path_ = kTestUploadExistingFilePath;
1512
1513   // If it turned out that the etag is conflicting, PRECONDITION_FAILED should
1514   // be returned.
1515   expected_precondition_failed_file_path_ =
1516       test_util::GetTestFilePath("drive/error.json");
1517
1518   const char kTestContentType[] = "text/plain";
1519   const std::string kTestContent(100, 'a');
1520
1521   GDataErrorCode error = GDATA_OTHER_ERROR;
1522   GURL upload_url;
1523
1524   // Initiate uploading a new file to the directory with "parent_resource_id".
1525   {
1526     base::RunLoop run_loop;
1527     drive::InitiateUploadExistingFileRequest* request =
1528         new drive::InitiateUploadExistingFileRequest(
1529             request_sender_.get(),
1530             *url_generator_,
1531             kTestContentType,
1532             kTestContent.size(),
1533             "resource_id",  // The resource id of the file to be overwritten.
1534             "Conflicting-etag",
1535             test_util::CreateQuitCallback(
1536                 &run_loop,
1537                 test_util::CreateCopyResultCallback(&error, &upload_url)));
1538     request_sender_->StartRequestWithRetry(request);
1539     run_loop.Run();
1540   }
1541
1542   EXPECT_EQ(HTTP_PRECONDITION, error);
1543   EXPECT_EQ(kTestContentType, http_request_.headers["X-Upload-Content-Type"]);
1544   EXPECT_EQ(base::Int64ToString(kTestContent.size()),
1545             http_request_.headers["X-Upload-Content-Length"]);
1546   EXPECT_EQ("Conflicting-etag", http_request_.headers["If-Match"]);
1547
1548   EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method);
1549   EXPECT_EQ("/upload/drive/v2/files/resource_id?uploadType=resumable",
1550             http_request_.relative_url);
1551   EXPECT_TRUE(http_request_.has_content);
1552   EXPECT_TRUE(http_request_.content.empty());
1553 }
1554
1555 TEST_F(DriveApiRequestsTest,
1556        UploadExistingFileRequestWithETagConflictOnResumeUpload) {
1557   // Set an expected url for uploading.
1558   expected_upload_path_ = kTestUploadExistingFilePath;
1559
1560   const char kTestContentType[] = "text/plain";
1561   const std::string kTestContent(100, 'a');
1562   const base::FilePath kTestFilePath =
1563       temp_dir_.path().AppendASCII("upload_file.txt");
1564   ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent));
1565
1566   GDataErrorCode error = GDATA_OTHER_ERROR;
1567   GURL upload_url;
1568
1569   // Initiate uploading a new file to the directory with "parent_resource_id".
1570   {
1571     base::RunLoop run_loop;
1572     drive::InitiateUploadExistingFileRequest* request =
1573         new drive::InitiateUploadExistingFileRequest(
1574             request_sender_.get(),
1575             *url_generator_,
1576             kTestContentType,
1577             kTestContent.size(),
1578             "resource_id",  // The resource id of the file to be overwritten.
1579             kTestETag,
1580             test_util::CreateQuitCallback(
1581                 &run_loop,
1582                 test_util::CreateCopyResultCallback(&error, &upload_url)));
1583     request_sender_->StartRequestWithRetry(request);
1584     run_loop.Run();
1585   }
1586
1587   EXPECT_EQ(HTTP_SUCCESS, error);
1588   EXPECT_EQ(kTestUploadExistingFilePath, upload_url.path());
1589   EXPECT_EQ(kTestContentType, http_request_.headers["X-Upload-Content-Type"]);
1590   EXPECT_EQ(base::Int64ToString(kTestContent.size()),
1591             http_request_.headers["X-Upload-Content-Length"]);
1592   EXPECT_EQ(kTestETag, http_request_.headers["If-Match"]);
1593
1594   EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method);
1595   EXPECT_EQ("/upload/drive/v2/files/resource_id?uploadType=resumable",
1596             http_request_.relative_url);
1597   EXPECT_TRUE(http_request_.has_content);
1598   EXPECT_TRUE(http_request_.content.empty());
1599
1600   // Set PRECONDITION_FAILED to the server. This is the emulation of the
1601   // confliction during uploading.
1602   expected_precondition_failed_file_path_ =
1603       test_util::GetTestFilePath("drive/error.json");
1604
1605   // Upload the content to the upload URL.
1606   UploadRangeResponse response;
1607   scoped_ptr<FileResource> new_entry;
1608
1609   {
1610     base::RunLoop run_loop;
1611     drive::ResumeUploadRequest* resume_request =
1612         new drive::ResumeUploadRequest(
1613             request_sender_.get(),
1614             upload_url,
1615             0,  // start_position
1616             kTestContent.size(),  // end_position (exclusive)
1617             kTestContent.size(),  // content_length,
1618             kTestContentType,
1619             kTestFilePath,
1620             test_util::CreateQuitCallback(
1621                 &run_loop,
1622                 test_util::CreateCopyResultCallback(&response, &new_entry)),
1623             ProgressCallback());
1624     request_sender_->StartRequestWithRetry(resume_request);
1625     run_loop.Run();
1626   }
1627
1628   // METHOD_PUT should be used to upload data.
1629   EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method);
1630   // Request should go to the upload URL.
1631   EXPECT_EQ(upload_url.path(), http_request_.relative_url);
1632   // Content-Range header should be added.
1633   EXPECT_EQ("bytes 0-" +
1634             base::Int64ToString(kTestContent.size() - 1) + "/" +
1635             base::Int64ToString(kTestContent.size()),
1636             http_request_.headers["Content-Range"]);
1637   // The upload content should be set in the HTTP request.
1638   EXPECT_TRUE(http_request_.has_content);
1639   EXPECT_EQ(kTestContent, http_request_.content);
1640
1641   // Check the response.
1642   EXPECT_EQ(HTTP_PRECONDITION, response.code);
1643   // The start and end positions should be set to -1 for error.
1644   EXPECT_EQ(-1, response.start_position_received);
1645   EXPECT_EQ(-1, response.end_position_received);
1646
1647   // New entry should be NULL.
1648   EXPECT_FALSE(new_entry.get());
1649 }
1650
1651 TEST_F(DriveApiRequestsTest, UploadExistingFileWithMetadataRequest) {
1652   const base::Time::Exploded kModifiedDate = {2012, 7, 0, 19, 15, 59, 13, 123};
1653   const base::Time::Exploded kLastViewedByMeDate =
1654       {2013, 7, 0, 19, 15, 59, 13, 123};
1655
1656   // Set an expected url for uploading.
1657   expected_upload_path_ = kTestUploadExistingFilePath;
1658
1659   const char kTestContentType[] = "text/plain";
1660   const std::string kTestContent(100, 'a');
1661
1662   GDataErrorCode error = GDATA_OTHER_ERROR;
1663   GURL upload_url;
1664
1665   // Initiate uploading a new file to the directory with "parent_resource_id".
1666   {
1667     base::RunLoop run_loop;
1668     drive::InitiateUploadExistingFileRequest* request =
1669         new drive::InitiateUploadExistingFileRequest(
1670             request_sender_.get(),
1671             *url_generator_,
1672             kTestContentType,
1673             kTestContent.size(),
1674             "resource_id",  // The resource id of the file to be overwritten.
1675             kTestETag,
1676             test_util::CreateQuitCallback(
1677                 &run_loop,
1678                 test_util::CreateCopyResultCallback(&error, &upload_url)));
1679     request->set_parent_resource_id("new_parent_resource_id");
1680     request->set_title("new file title");
1681     request->set_modified_date(base::Time::FromUTCExploded(kModifiedDate));
1682     request->set_last_viewed_by_me_date(
1683         base::Time::FromUTCExploded(kLastViewedByMeDate));
1684
1685     request_sender_->StartRequestWithRetry(request);
1686     run_loop.Run();
1687   }
1688
1689   EXPECT_EQ(HTTP_SUCCESS, error);
1690   EXPECT_EQ(kTestUploadExistingFilePath, upload_url.path());
1691   EXPECT_EQ(kTestContentType, http_request_.headers["X-Upload-Content-Type"]);
1692   EXPECT_EQ(base::Int64ToString(kTestContent.size()),
1693             http_request_.headers["X-Upload-Content-Length"]);
1694   EXPECT_EQ(kTestETag, http_request_.headers["If-Match"]);
1695
1696   EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method);
1697   EXPECT_EQ("/upload/drive/v2/files/resource_id?"
1698             "uploadType=resumable&setModifiedDate=true",
1699             http_request_.relative_url);
1700   EXPECT_EQ("application/json", http_request_.headers["Content-Type"]);
1701   EXPECT_TRUE(http_request_.has_content);
1702   EXPECT_EQ("{\"lastViewedByMeDate\":\"2013-07-19T15:59:13.123Z\","
1703             "\"modifiedDate\":\"2012-07-19T15:59:13.123Z\","
1704             "\"parents\":[{\"id\":\"new_parent_resource_id\","
1705             "\"kind\":\"drive#fileLink\"}],"
1706             "\"title\":\"new file title\"}",
1707             http_request_.content);
1708 }
1709
1710 TEST_F(DriveApiRequestsTest, DownloadFileRequest) {
1711   const base::FilePath kDownloadedFilePath =
1712       temp_dir_.path().AppendASCII("cache_file");
1713   const std::string kTestId("dummyId");
1714
1715   GDataErrorCode result_code = GDATA_OTHER_ERROR;
1716   base::FilePath temp_file;
1717   {
1718     base::RunLoop run_loop;
1719     drive::DownloadFileRequest* request = new drive::DownloadFileRequest(
1720         request_sender_.get(),
1721         *url_generator_,
1722         kTestId,
1723         kDownloadedFilePath,
1724         test_util::CreateQuitCallback(
1725             &run_loop,
1726             test_util::CreateCopyResultCallback(&result_code, &temp_file)),
1727         GetContentCallback(),
1728         ProgressCallback());
1729     request_sender_->StartRequestWithRetry(request);
1730     run_loop.Run();
1731   }
1732
1733   std::string contents;
1734   base::ReadFileToString(temp_file, &contents);
1735   base::DeleteFile(temp_file, false);
1736
1737   EXPECT_EQ(HTTP_SUCCESS, result_code);
1738   EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method);
1739   EXPECT_EQ(kTestDownloadPathPrefix + kTestId, http_request_.relative_url);
1740   EXPECT_EQ(kDownloadedFilePath, temp_file);
1741
1742   const std::string expected_contents = kTestId + kTestId + kTestId;
1743   EXPECT_EQ(expected_contents, contents);
1744 }
1745
1746 TEST_F(DriveApiRequestsTest, DownloadFileRequest_GetContentCallback) {
1747   const base::FilePath kDownloadedFilePath =
1748       temp_dir_.path().AppendASCII("cache_file");
1749   const std::string kTestId("dummyId");
1750
1751   GDataErrorCode result_code = GDATA_OTHER_ERROR;
1752   base::FilePath temp_file;
1753   std::string contents;
1754   {
1755     base::RunLoop run_loop;
1756     drive::DownloadFileRequest* request = new drive::DownloadFileRequest(
1757         request_sender_.get(),
1758         *url_generator_,
1759         kTestId,
1760         kDownloadedFilePath,
1761         test_util::CreateQuitCallback(
1762             &run_loop,
1763             test_util::CreateCopyResultCallback(&result_code, &temp_file)),
1764         base::Bind(&AppendContent, &contents),
1765         ProgressCallback());
1766     request_sender_->StartRequestWithRetry(request);
1767     run_loop.Run();
1768   }
1769
1770   base::DeleteFile(temp_file, false);
1771
1772   EXPECT_EQ(HTTP_SUCCESS, result_code);
1773   EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method);
1774   EXPECT_EQ(kTestDownloadPathPrefix + kTestId, http_request_.relative_url);
1775   EXPECT_EQ(kDownloadedFilePath, temp_file);
1776
1777   const std::string expected_contents = kTestId + kTestId + kTestId;
1778   EXPECT_EQ(expected_contents, contents);
1779 }
1780
1781 TEST_F(DriveApiRequestsTest, PermissionsInsertRequest) {
1782   expected_content_type_ = "application/json";
1783   expected_content_ = kTestPermissionResponse;
1784
1785   GDataErrorCode error = GDATA_OTHER_ERROR;
1786
1787   // Add comment permission to the user "user@example.com".
1788   {
1789     base::RunLoop run_loop;
1790     drive::PermissionsInsertRequest* request =
1791         new drive::PermissionsInsertRequest(
1792             request_sender_.get(),
1793             *url_generator_,
1794             test_util::CreateQuitCallback(
1795                 &run_loop,
1796                 test_util::CreateCopyResultCallback(&error)));
1797     request->set_id("resource_id");
1798     request->set_role(drive::PERMISSION_ROLE_COMMENTER);
1799     request->set_type(drive::PERMISSION_TYPE_USER);
1800     request->set_value("user@example.com");
1801     request_sender_->StartRequestWithRetry(request);
1802     run_loop.Run();
1803   }
1804
1805   EXPECT_EQ(HTTP_SUCCESS, error);
1806   EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method);
1807   EXPECT_EQ("/drive/v2/files/resource_id/permissions",
1808             http_request_.relative_url);
1809   EXPECT_EQ("application/json", http_request_.headers["Content-Type"]);
1810
1811   scoped_ptr<base::Value> expected(base::JSONReader::Read(
1812       "{\"additionalRoles\":[\"commenter\"], \"role\":\"reader\", "
1813       "\"type\":\"user\",\"value\":\"user@example.com\"}"));
1814   ASSERT_TRUE(expected);
1815
1816   scoped_ptr<base::Value> result(base::JSONReader::Read(http_request_.content));
1817   EXPECT_TRUE(http_request_.has_content);
1818   EXPECT_TRUE(base::Value::Equals(expected.get(), result.get()));
1819
1820   // Add "can edit" permission to users in "example.com".
1821   error = GDATA_OTHER_ERROR;
1822   {
1823     base::RunLoop run_loop;
1824     drive::PermissionsInsertRequest* request =
1825         new drive::PermissionsInsertRequest(
1826             request_sender_.get(),
1827             *url_generator_,
1828             test_util::CreateQuitCallback(
1829                 &run_loop,
1830                 test_util::CreateCopyResultCallback(&error)));
1831     request->set_id("resource_id2");
1832     request->set_role(drive::PERMISSION_ROLE_WRITER);
1833     request->set_type(drive::PERMISSION_TYPE_DOMAIN);
1834     request->set_value("example.com");
1835     request_sender_->StartRequestWithRetry(request);
1836     run_loop.Run();
1837   }
1838
1839   EXPECT_EQ(HTTP_SUCCESS, error);
1840   EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method);
1841   EXPECT_EQ("/drive/v2/files/resource_id2/permissions",
1842             http_request_.relative_url);
1843   EXPECT_EQ("application/json", http_request_.headers["Content-Type"]);
1844
1845   expected.reset(base::JSONReader::Read(
1846       "{\"role\":\"writer\", \"type\":\"domain\",\"value\":\"example.com\"}"));
1847   ASSERT_TRUE(expected);
1848
1849   result.reset(base::JSONReader::Read(http_request_.content));
1850   EXPECT_TRUE(http_request_.has_content);
1851   EXPECT_TRUE(base::Value::Equals(expected.get(), result.get()));
1852 }
1853
1854 }  // namespace google_apis