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

Side by Side Diff: chrome/browser/local_discovery/privet_http_unittest.cc

Issue 1553333002: Move cloud print specific files out of local_discovery (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@moveprn
Patch Set: Created 4 years, 11 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 "chrome/browser/local_discovery/privet_http.h"
6
7 #include <utility>
8
9 #include "base/json/json_reader.h"
10 #include "base/json/json_writer.h"
11 #include "base/run_loop.h"
12 #include "chrome/browser/local_discovery/privet_http_impl.h"
13 #include "content/public/browser/browser_thread.h"
14 #include "content/public/test/test_browser_thread_bundle.h"
15 #include "net/test/embedded_test_server/embedded_test_server.h"
16 #include "net/url_request/test_url_fetcher_factory.h"
17 #include "net/url_request/url_request_test_util.h"
18 #include "testing/gmock/include/gmock/gmock.h"
19 #include "testing/gtest/include/gtest/gtest.h"
20
21 #if defined(ENABLE_PRINT_PREVIEW)
22 #include "chrome/browser/local_discovery/pwg_raster_converter.h"
23 #include "printing/pwg_raster_settings.h"
24 #endif // ENABLE_PRINT_PREVIEW
25
26 namespace local_discovery {
27
28 namespace {
29
30 using testing::NiceMock;
31 using testing::StrictMock;
32 using testing::TestWithParam;
33 using testing::ValuesIn;
34
35 using content::BrowserThread;
36 using net::EmbeddedTestServer;
37
38 const char kSampleInfoResponse[] = "{"
39 " \"version\": \"1.0\","
40 " \"name\": \"Common printer\","
41 " \"description\": \"Printer connected through Chrome connector\","
42 " \"url\": \"https://www.google.com/cloudprint\","
43 " \"type\": ["
44 " \"printer\""
45 " ],"
46 " \"id\": \"\","
47 " \"device_state\": \"idle\","
48 " \"connection_state\": \"online\","
49 " \"manufacturer\": \"Google\","
50 " \"model\": \"Google Chrome\","
51 " \"serial_number\": \"1111-22222-33333-4444\","
52 " \"firmware\": \"24.0.1312.52\","
53 " \"uptime\": 600,"
54 " \"setup_url\": \"http://support.google.com/\","
55 " \"support_url\": \"http://support.google.com/cloudprint/?hl=en\","
56 " \"update_url\": \"http://support.google.com/cloudprint/?hl=en\","
57 " \"x-privet-token\": \"SampleTokenForTesting\","
58 " \"api\": ["
59 " \"/privet/accesstoken\","
60 " \"/privet/capabilities\","
61 " \"/privet/printer/submitdoc\","
62 " ]"
63 "}";
64
65 const char kSampleInfoResponseRegistered[] = "{"
66 " \"version\": \"1.0\","
67 " \"name\": \"Common printer\","
68 " \"description\": \"Printer connected through Chrome connector\","
69 " \"url\": \"https://www.google.com/cloudprint\","
70 " \"type\": ["
71 " \"printer\""
72 " ],"
73 " \"id\": \"MyDeviceID\","
74 " \"device_state\": \"idle\","
75 " \"connection_state\": \"online\","
76 " \"manufacturer\": \"Google\","
77 " \"model\": \"Google Chrome\","
78 " \"serial_number\": \"1111-22222-33333-4444\","
79 " \"firmware\": \"24.0.1312.52\","
80 " \"uptime\": 600,"
81 " \"setup_url\": \"http://support.google.com/\","
82 " \"support_url\": \"http://support.google.com/cloudprint/?hl=en\","
83 " \"update_url\": \"http://support.google.com/cloudprint/?hl=en\","
84 " \"x-privet-token\": \"SampleTokenForTesting\","
85 " \"api\": ["
86 " \"/privet/accesstoken\","
87 " \"/privet/capabilities\","
88 " \"/privet/printer/submitdoc\","
89 " ]"
90 "}";
91
92 const char kSampleRegisterStartResponse[] = "{"
93 "\"user\": \"example@google.com\","
94 "\"action\": \"start\""
95 "}";
96
97 const char kSampleRegisterGetClaimTokenResponse[] = "{"
98 " \"action\": \"getClaimToken\","
99 " \"user\": \"example@google.com\","
100 " \"token\": \"MySampleToken\","
101 " \"claim_url\": \"https://domain.com/SoMeUrL\""
102 "}";
103
104 const char kSampleRegisterCompleteResponse[] = "{"
105 "\"user\": \"example@google.com\","
106 "\"action\": \"complete\","
107 "\"device_id\": \"MyDeviceID\""
108 "}";
109
110 const char kSampleXPrivetErrorResponse[] =
111 "{ \"error\": \"invalid_x_privet_token\" }";
112
113 const char kSampleRegisterErrorTransient[] =
114 "{ \"error\": \"device_busy\", \"timeout\": 1}";
115
116 const char kSampleRegisterErrorPermanent[] =
117 "{ \"error\": \"user_cancel\" }";
118
119 const char kSampleInfoResponseBadJson[] = "{";
120
121 const char kSampleRegisterCancelResponse[] = "{"
122 "\"user\": \"example@google.com\","
123 "\"action\": \"cancel\""
124 "}";
125
126 const char kSampleCapabilitiesResponse[] = "{"
127 "\"version\" : \"1.0\","
128 "\"printer\" : {"
129 " \"supported_content_type\" : ["
130 " { \"content_type\" : \"application/pdf\" },"
131 " { \"content_type\" : \"image/pwg-raster\" }"
132 " ]"
133 "}"
134 "}";
135
136 #if defined(ENABLE_PRINT_PREVIEW)
137 const char kSampleInfoResponseWithCreatejob[] = "{"
138 " \"version\": \"1.0\","
139 " \"name\": \"Common printer\","
140 " \"description\": \"Printer connected through Chrome connector\","
141 " \"url\": \"https://www.google.com/cloudprint\","
142 " \"type\": ["
143 " \"printer\""
144 " ],"
145 " \"id\": \"\","
146 " \"device_state\": \"idle\","
147 " \"connection_state\": \"online\","
148 " \"manufacturer\": \"Google\","
149 " \"model\": \"Google Chrome\","
150 " \"serial_number\": \"1111-22222-33333-4444\","
151 " \"firmware\": \"24.0.1312.52\","
152 " \"uptime\": 600,"
153 " \"setup_url\": \"http://support.google.com/\","
154 " \"support_url\": \"http://support.google.com/cloudprint/?hl=en\","
155 " \"update_url\": \"http://support.google.com/cloudprint/?hl=en\","
156 " \"x-privet-token\": \"SampleTokenForTesting\","
157 " \"api\": ["
158 " \"/privet/accesstoken\","
159 " \"/privet/capabilities\","
160 " \"/privet/printer/createjob\","
161 " \"/privet/printer/submitdoc\","
162 " ]"
163 "}";
164
165 const char kSampleLocalPrintResponse[] = "{"
166 "\"job_id\": \"123\","
167 "\"expires_in\": 500,"
168 "\"job_type\": \"application/pdf\","
169 "\"job_size\": 16,"
170 "\"job_name\": \"Sample job name\","
171 "}";
172
173 const char kSampleCapabilitiesResponsePWGOnly[] = "{"
174 "\"version\" : \"1.0\","
175 "\"printer\" : {"
176 " \"supported_content_type\" : ["
177 " { \"content_type\" : \"image/pwg-raster\" }"
178 " ]"
179 "}"
180 "}";
181
182 const char kSampleErrorResponsePrinterBusy[] = "{"
183 "\"error\": \"invalid_print_job\","
184 "\"timeout\": 1 "
185 "}";
186
187 const char kSampleInvalidDocumentTypeResponse[] = "{"
188 "\"error\" : \"invalid_document_type\""
189 "}";
190
191 const char kSampleCreatejobResponse[] = "{ \"job_id\": \"1234\" }";
192
193 const char kSampleCapabilitiesResponseWithAnyMimetype[] = "{"
194 "\"version\" : \"1.0\","
195 "\"printer\" : {"
196 " \"supported_content_type\" : ["
197 " { \"content_type\" : \"*/*\" },"
198 " { \"content_type\" : \"image/pwg-raster\" }"
199 " ]"
200 "}"
201 "}";
202
203 const char kSampleCJT[] = "{ \"version\" : \"1.0\" }";
204
205 const char kSampleCapabilitiesResponsePWGSettings[] =
206 "{"
207 "\"version\" : \"1.0\","
208 "\"printer\" : {"
209 " \"pwg_raster_config\" : {"
210 " \"document_sheet_back\" : \"MANUAL_TUMBLE\","
211 " \"reverse_order_streaming\": true"
212 " },"
213 " \"supported_content_type\" : ["
214 " { \"content_type\" : \"image/pwg-raster\" }"
215 " ]"
216 "}"
217 "}";
218
219 const char kSampleCJTDuplex[] =
220 "{"
221 "\"version\" : \"1.0\","
222 "\"print\": { \"duplex\": {\"type\": \"SHORT_EDGE\"} }"
223 "}";
224 #endif // ENABLE_PRINT_PREVIEW
225
226 const char* const kTestParams[] = {"8.8.4.4", "2001:4860:4860::8888"};
227
228 // Return the representation of the given JSON that would be outputted by
229 // JSONWriter. This ensures the same JSON values are represented by the same
230 // string.
231 std::string NormalizeJson(const std::string& json) {
232 std::string result = json;
233 scoped_ptr<base::Value> value = base::JSONReader::Read(result);
234 DCHECK(value) << result;
235 base::JSONWriter::Write(*value, &result);
236 return result;
237 }
238
239 class MockTestURLFetcherFactoryDelegate
240 : public net::TestURLFetcher::DelegateForTests {
241 public:
242 // Callback issued correspondingly to the call to the |Start()| method.
243 MOCK_METHOD1(OnRequestStart, void(int fetcher_id));
244
245 // Callback issued correspondingly to the call to |AppendChunkToUpload|.
246 // Uploaded chunks can be retrieved with the |upload_chunks()| getter.
247 MOCK_METHOD1(OnChunkUpload, void(int fetcher_id));
248
249 // Callback issued correspondingly to the destructor.
250 MOCK_METHOD1(OnRequestEnd, void(int fetcher_id));
251 };
252
253 class PrivetHTTPTest : public TestWithParam<const char*> {
254 public:
255 PrivetHTTPTest() {
256 PrivetURLFetcher::ResetTokenMapForTests();
257
258 request_context_ = new net::TestURLRequestContextGetter(
259 base::ThreadTaskRunnerHandle::Get());
260 privet_client_ = PrivetV1HTTPClient::CreateDefault(
261 make_scoped_ptr<PrivetHTTPClient>(new PrivetHTTPClientImpl(
262 "sampleDevice._privet._tcp.local",
263 net::HostPortPair(GetParam(), 6006), request_context_.get())));
264 fetcher_factory_.SetDelegateForTests(&fetcher_delegate_);
265 }
266
267 GURL GetUrl(const std::string& path) const {
268 std::string host = GetParam();
269 if (host.find(":") != std::string::npos)
270 host = "[" + host + "]";
271 return GURL("http://" + host + ":6006" + path);
272 }
273
274 bool SuccessfulResponseToURL(const GURL& url,
275 const std::string& response) {
276 net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0);
277 EXPECT_TRUE(fetcher);
278 EXPECT_EQ(url, fetcher->GetOriginalURL());
279
280 if (!fetcher || url != fetcher->GetOriginalURL())
281 return false;
282
283 fetcher->SetResponseString(response);
284 fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::SUCCESS,
285 net::OK));
286 fetcher->set_response_code(200);
287 fetcher->delegate()->OnURLFetchComplete(fetcher);
288 return true;
289 }
290
291 bool SuccessfulResponseToURLAndData(const GURL& url,
292 const std::string& data,
293 const std::string& response) {
294 net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0);
295 EXPECT_TRUE(fetcher);
296 EXPECT_EQ(url, fetcher->GetOriginalURL());
297
298 if (!fetcher) return false;
299
300 EXPECT_EQ(data, fetcher->upload_data());
301 if (data != fetcher->upload_data()) return false;
302
303 return SuccessfulResponseToURL(url, response);
304 }
305
306 bool SuccessfulResponseToURLAndJSONData(const GURL& url,
307 const std::string& data,
308 const std::string& response) {
309 net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0);
310 EXPECT_TRUE(fetcher);
311 EXPECT_EQ(url, fetcher->GetOriginalURL());
312
313 if (!fetcher)
314 return false;
315
316 std::string normalized_data = NormalizeJson(data);
317 std::string normalized_upload_data = NormalizeJson(fetcher->upload_data());
318 EXPECT_EQ(normalized_data, normalized_upload_data);
319 if (normalized_data != normalized_upload_data)
320 return false;
321
322 return SuccessfulResponseToURL(url, response);
323 }
324
325 bool SuccessfulResponseToURLAndFilePath(const GURL& url,
326 const base::FilePath& file_path,
327 const std::string& response) {
328 net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0);
329 EXPECT_TRUE(fetcher);
330 EXPECT_EQ(url, fetcher->GetOriginalURL());
331
332 if (!fetcher) return false;
333
334 EXPECT_EQ(file_path, fetcher->upload_file_path());
335 if (file_path != fetcher->upload_file_path()) return false;
336
337 return SuccessfulResponseToURL(url, response);
338 }
339
340
341 void RunFor(base::TimeDelta time_period) {
342 base::CancelableCallback<void()> callback(base::Bind(
343 &PrivetHTTPTest::Stop, base::Unretained(this)));
344 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
345 FROM_HERE, callback.callback(), time_period);
346
347 base::MessageLoop::current()->Run();
348 callback.Cancel();
349 }
350
351 void Stop() { base::MessageLoop::current()->QuitWhenIdle(); }
352
353 protected:
354 base::MessageLoop loop_;
355 scoped_refptr<net::TestURLRequestContextGetter> request_context_;
356 net::TestURLFetcherFactory fetcher_factory_;
357 scoped_ptr<PrivetV1HTTPClient> privet_client_;
358 NiceMock<MockTestURLFetcherFactoryDelegate> fetcher_delegate_;
359 };
360
361 class MockJSONCallback{
362 public:
363 void OnPrivetJSONDone(const base::DictionaryValue* value) {
364 if (!value) {
365 value_.reset();
366 } else {
367 value_.reset(value->DeepCopy());
368 }
369
370 OnPrivetJSONDoneInternal();
371 }
372
373 MOCK_METHOD0(OnPrivetJSONDoneInternal, void());
374
375 const base::DictionaryValue* value() { return value_.get(); }
376 PrivetJSONOperation::ResultCallback callback() {
377 return base::Bind(&MockJSONCallback::OnPrivetJSONDone,
378 base::Unretained(this));
379 }
380 protected:
381 scoped_ptr<base::DictionaryValue> value_;
382 };
383
384 class MockRegisterDelegate : public PrivetRegisterOperation::Delegate {
385 public:
386 void OnPrivetRegisterClaimToken(
387 PrivetRegisterOperation* operation,
388 const std::string& token,
389 const GURL& url) override {
390 OnPrivetRegisterClaimTokenInternal(token, url);
391 }
392
393 MOCK_METHOD2(OnPrivetRegisterClaimTokenInternal, void(
394 const std::string& token,
395 const GURL& url));
396
397 void OnPrivetRegisterError(
398 PrivetRegisterOperation* operation,
399 const std::string& action,
400 PrivetRegisterOperation::FailureReason reason,
401 int printer_http_code,
402 const base::DictionaryValue* json) override {
403 // TODO(noamsml): Save and test for JSON?
404 OnPrivetRegisterErrorInternal(action, reason, printer_http_code);
405 }
406
407 MOCK_METHOD3(OnPrivetRegisterErrorInternal,
408 void(const std::string& action,
409 PrivetRegisterOperation::FailureReason reason,
410 int printer_http_code));
411
412 void OnPrivetRegisterDone(
413 PrivetRegisterOperation* operation,
414 const std::string& device_id) override {
415 OnPrivetRegisterDoneInternal(device_id);
416 }
417
418 MOCK_METHOD1(OnPrivetRegisterDoneInternal,
419 void(const std::string& device_id));
420 };
421
422 class MockLocalPrintDelegate : public PrivetLocalPrintOperation::Delegate {
423 public:
424 virtual void OnPrivetPrintingDone(
425 const PrivetLocalPrintOperation* print_operation) {
426 OnPrivetPrintingDoneInternal();
427 }
428
429 MOCK_METHOD0(OnPrivetPrintingDoneInternal, void());
430
431 virtual void OnPrivetPrintingError(
432 const PrivetLocalPrintOperation* print_operation, int http_code) {
433 OnPrivetPrintingErrorInternal(http_code);
434 }
435
436 MOCK_METHOD1(OnPrivetPrintingErrorInternal, void(int http_code));
437 };
438
439 class PrivetInfoTest : public PrivetHTTPTest {
440 public:
441 void SetUp() override {
442 info_operation_ = privet_client_->CreateInfoOperation(
443 info_callback_.callback());
444 }
445
446 protected:
447 scoped_ptr<PrivetJSONOperation> info_operation_;
448 StrictMock<MockJSONCallback> info_callback_;
449 };
450
451 INSTANTIATE_TEST_CASE_P(PrivetTests, PrivetInfoTest, ValuesIn(kTestParams));
452
453 TEST_P(PrivetInfoTest, SuccessfulInfo) {
454 info_operation_->Start();
455
456 net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0);
457 ASSERT_TRUE(fetcher != NULL);
458 EXPECT_EQ(GetUrl("/privet/info"), fetcher->GetOriginalURL());
459
460 fetcher->SetResponseString(kSampleInfoResponse);
461 fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::SUCCESS,
462 net::OK));
463 fetcher->set_response_code(200);
464
465 EXPECT_CALL(info_callback_, OnPrivetJSONDoneInternal());
466 fetcher->delegate()->OnURLFetchComplete(fetcher);
467 }
468
469 TEST_P(PrivetInfoTest, InfoFailureHTTP) {
470 info_operation_->Start();
471
472 net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0);
473 ASSERT_TRUE(fetcher != NULL);
474 fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::SUCCESS,
475 net::OK));
476 fetcher->set_response_code(404);
477
478 EXPECT_CALL(info_callback_, OnPrivetJSONDoneInternal());
479 fetcher->delegate()->OnURLFetchComplete(fetcher);
480 }
481
482 class PrivetRegisterTest : public PrivetHTTPTest {
483 public:
484 void SetUp() override {
485 info_operation_ = privet_client_->CreateInfoOperation(
486 info_callback_.callback());
487 register_operation_ =
488 privet_client_->CreateRegisterOperation("example@google.com",
489 &register_delegate_);
490 }
491
492 protected:
493 bool SuccessfulResponseToURL(const GURL& url,
494 const std::string& response) {
495 net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0);
496 EXPECT_TRUE(fetcher);
497 EXPECT_EQ(url, fetcher->GetOriginalURL());
498 if (!fetcher || url != fetcher->GetOriginalURL())
499 return false;
500
501 fetcher->SetResponseString(response);
502 fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::SUCCESS,
503 net::OK));
504 fetcher->set_response_code(200);
505 fetcher->delegate()->OnURLFetchComplete(fetcher);
506 return true;
507 }
508
509 scoped_ptr<PrivetJSONOperation> info_operation_;
510 NiceMock<MockJSONCallback> info_callback_;
511 scoped_ptr<PrivetRegisterOperation> register_operation_;
512 StrictMock<MockRegisterDelegate> register_delegate_;
513 };
514
515 TEST_P(PrivetRegisterTest, RegisterSuccessSimple) {
516 register_operation_->Start();
517
518 EXPECT_TRUE(
519 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
520
521 EXPECT_TRUE(
522 SuccessfulResponseToURL(GetUrl("/privet/register?"
523 "action=start&user=example%40google.com"),
524 kSampleRegisterStartResponse));
525
526 EXPECT_CALL(register_delegate_, OnPrivetRegisterClaimTokenInternal(
527 "MySampleToken",
528 GURL("https://domain.com/SoMeUrL")));
529
530 EXPECT_TRUE(SuccessfulResponseToURL(
531 GetUrl("/privet/register?"
532 "action=getClaimToken&user=example%40google.com"),
533 kSampleRegisterGetClaimTokenResponse));
534
535 register_operation_->CompleteRegistration();
536
537 EXPECT_TRUE(SuccessfulResponseToURL(
538 GetUrl("/privet/register?"
539 "action=complete&user=example%40google.com"),
540 kSampleRegisterCompleteResponse));
541
542 EXPECT_CALL(register_delegate_, OnPrivetRegisterDoneInternal(
543 "MyDeviceID"));
544
545 EXPECT_TRUE(SuccessfulResponseToURL(GetUrl("/privet/info"),
546 kSampleInfoResponseRegistered));
547 }
548
549 TEST_P(PrivetRegisterTest, RegisterXSRFFailure) {
550 register_operation_->Start();
551
552 EXPECT_TRUE(
553 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
554
555 EXPECT_TRUE(
556 SuccessfulResponseToURL(GetUrl("/privet/register?"
557 "action=start&user=example%40google.com"),
558 kSampleRegisterStartResponse));
559
560 EXPECT_TRUE(SuccessfulResponseToURL(
561 GetUrl("/privet/register?"
562 "action=getClaimToken&user=example%40google.com"),
563 kSampleXPrivetErrorResponse));
564
565 EXPECT_TRUE(
566 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
567
568 EXPECT_CALL(register_delegate_, OnPrivetRegisterClaimTokenInternal(
569 "MySampleToken", GURL("https://domain.com/SoMeUrL")));
570
571 EXPECT_TRUE(SuccessfulResponseToURL(
572 GetUrl("/privet/register?"
573 "action=getClaimToken&user=example%40google.com"),
574 kSampleRegisterGetClaimTokenResponse));
575 }
576
577 TEST_P(PrivetRegisterTest, TransientFailure) {
578 register_operation_->Start();
579
580 EXPECT_TRUE(
581 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
582
583 EXPECT_TRUE(
584 SuccessfulResponseToURL(GetUrl("/privet/register?"
585 "action=start&user=example%40google.com"),
586 kSampleRegisterErrorTransient));
587
588 EXPECT_CALL(fetcher_delegate_, OnRequestStart(0));
589
590 RunFor(base::TimeDelta::FromSeconds(2));
591
592 testing::Mock::VerifyAndClearExpectations(&fetcher_delegate_);
593
594 EXPECT_TRUE(
595 SuccessfulResponseToURL(GetUrl("/privet/register?"
596 "action=start&user=example%40google.com"),
597 kSampleRegisterStartResponse));
598 }
599
600 TEST_P(PrivetRegisterTest, PermanentFailure) {
601 register_operation_->Start();
602
603 EXPECT_TRUE(
604 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
605
606 EXPECT_TRUE(
607 SuccessfulResponseToURL(GetUrl("/privet/register?"
608 "action=start&user=example%40google.com"),
609 kSampleRegisterStartResponse));
610
611 EXPECT_CALL(register_delegate_,
612 OnPrivetRegisterErrorInternal(
613 "getClaimToken",
614 PrivetRegisterOperation::FAILURE_JSON_ERROR,
615 200));
616
617 EXPECT_TRUE(SuccessfulResponseToURL(
618 GetUrl("/privet/register?"
619 "action=getClaimToken&user=example%40google.com"),
620 kSampleRegisterErrorPermanent));
621 }
622
623 TEST_P(PrivetRegisterTest, InfoFailure) {
624 register_operation_->Start();
625
626 EXPECT_CALL(register_delegate_,
627 OnPrivetRegisterErrorInternal(
628 "start",
629 PrivetRegisterOperation::FAILURE_TOKEN,
630 -1));
631
632 EXPECT_TRUE(SuccessfulResponseToURL(GetUrl("/privet/info"),
633 kSampleInfoResponseBadJson));
634 }
635
636 TEST_P(PrivetRegisterTest, RegisterCancel) {
637 register_operation_->Start();
638
639 EXPECT_TRUE(
640 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
641
642 EXPECT_TRUE(
643 SuccessfulResponseToURL(GetUrl("/privet/register?"
644 "action=start&user=example%40google.com"),
645 kSampleRegisterStartResponse));
646
647 register_operation_->Cancel();
648
649 EXPECT_TRUE(
650 SuccessfulResponseToURL(GetUrl("/privet/register?"
651 "action=cancel&user=example%40google.com"),
652 kSampleRegisterCancelResponse));
653
654 // Must keep mocks alive for 3 seconds so the cancelation object can be
655 // deleted.
656 RunFor(base::TimeDelta::FromSeconds(3));
657 }
658
659 class PrivetCapabilitiesTest : public PrivetHTTPTest {
660 public:
661 void SetUp() override {
662 capabilities_operation_ = privet_client_->CreateCapabilitiesOperation(
663 capabilities_callback_.callback());
664 }
665
666 protected:
667 scoped_ptr<PrivetJSONOperation> capabilities_operation_;
668 StrictMock<MockJSONCallback> capabilities_callback_;
669 };
670
671 INSTANTIATE_TEST_CASE_P(PrivetTests,
672 PrivetCapabilitiesTest,
673 ValuesIn(kTestParams));
674
675 TEST_P(PrivetCapabilitiesTest, SuccessfulCapabilities) {
676 capabilities_operation_->Start();
677
678 EXPECT_TRUE(
679 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
680
681 EXPECT_CALL(capabilities_callback_, OnPrivetJSONDoneInternal());
682
683 EXPECT_TRUE(SuccessfulResponseToURL(GetUrl("/privet/capabilities"),
684 kSampleCapabilitiesResponse));
685
686 std::string version;
687 EXPECT_TRUE(capabilities_callback_.value()->GetString("version", &version));
688 EXPECT_EQ("1.0", version);
689 }
690
691 TEST_P(PrivetCapabilitiesTest, CacheToken) {
692 capabilities_operation_->Start();
693
694 EXPECT_TRUE(
695 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
696
697 EXPECT_CALL(capabilities_callback_, OnPrivetJSONDoneInternal());
698
699 EXPECT_TRUE(SuccessfulResponseToURL(GetUrl("/privet/capabilities"),
700 kSampleCapabilitiesResponse));
701
702 capabilities_operation_ = privet_client_->CreateCapabilitiesOperation(
703 capabilities_callback_.callback());
704
705 capabilities_operation_->Start();
706
707 EXPECT_CALL(capabilities_callback_, OnPrivetJSONDoneInternal());
708
709 EXPECT_TRUE(SuccessfulResponseToURL(GetUrl("/privet/capabilities"),
710 kSampleCapabilitiesResponse));
711 }
712
713 TEST_P(PrivetCapabilitiesTest, BadToken) {
714 capabilities_operation_->Start();
715
716 EXPECT_TRUE(
717 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
718
719 EXPECT_TRUE(SuccessfulResponseToURL(GetUrl("/privet/capabilities"),
720 kSampleXPrivetErrorResponse));
721
722 EXPECT_TRUE(
723 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
724
725 EXPECT_CALL(capabilities_callback_, OnPrivetJSONDoneInternal());
726
727 EXPECT_TRUE(SuccessfulResponseToURL(GetUrl("/privet/capabilities"),
728 kSampleCapabilitiesResponse));
729 }
730
731 #if defined(ENABLE_PRINT_PREVIEW)
732 // A note on PWG raster conversion: The PWG raster converter used simply
733 // converts strings to file paths based on them by appending "test.pdf", since
734 // it's easier to test that way. Instead of using a mock, we simply check if the
735 // request is uploading a file that is based on this pattern.
736 class FakePWGRasterConverter : public PWGRasterConverter {
737 public:
738 void Start(base::RefCountedMemory* data,
739 const printing::PdfRenderSettings& conversion_settings,
740 const printing::PwgRasterSettings& bitmap_settings,
741 const ResultCallback& callback) override {
742 bitmap_settings_ = bitmap_settings;
743 std::string data_str(data->front_as<char>(), data->size());
744 callback.Run(true, base::FilePath().AppendASCII(data_str + "test.pdf"));
745 }
746
747 const printing::PwgRasterSettings& bitmap_settings() {
748 return bitmap_settings_;
749 }
750
751 private:
752 printing::PwgRasterSettings bitmap_settings_;
753 };
754
755 class PrivetLocalPrintTest : public PrivetHTTPTest {
756 public:
757 void SetUp() override {
758 PrivetURLFetcher::ResetTokenMapForTests();
759
760 local_print_operation_ = privet_client_->CreateLocalPrintOperation(
761 &local_print_delegate_);
762
763 scoped_ptr<FakePWGRasterConverter> pwg_converter(
764 new FakePWGRasterConverter);
765 pwg_converter_ = pwg_converter.get();
766 local_print_operation_->SetPWGRasterConverterForTesting(
767 std::move(pwg_converter));
768 }
769
770 scoped_refptr<base::RefCountedBytes> RefCountedBytesFromString(
771 std::string str) {
772 std::vector<unsigned char> str_vec;
773 str_vec.insert(str_vec.begin(), str.begin(), str.end());
774 return scoped_refptr<base::RefCountedBytes>(
775 base::RefCountedBytes::TakeVector(&str_vec));
776 }
777
778 protected:
779 scoped_ptr<PrivetLocalPrintOperation> local_print_operation_;
780 StrictMock<MockLocalPrintDelegate> local_print_delegate_;
781 FakePWGRasterConverter* pwg_converter_;
782 };
783
784 INSTANTIATE_TEST_CASE_P(PrivetTests,
785 PrivetLocalPrintTest,
786 ValuesIn(kTestParams));
787
788 TEST_P(PrivetLocalPrintTest, SuccessfulLocalPrint) {
789 local_print_operation_->SetUsername("sample@gmail.com");
790 local_print_operation_->SetJobname("Sample job name");
791 local_print_operation_->SetData(RefCountedBytesFromString(
792 "Sample print data"));
793 local_print_operation_->SetCapabilities(kSampleCapabilitiesResponse);
794 local_print_operation_->Start();
795
796 EXPECT_TRUE(
797 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
798
799 EXPECT_TRUE(
800 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
801
802 EXPECT_CALL(local_print_delegate_, OnPrivetPrintingDoneInternal());
803
804 // TODO(noamsml): Is encoding spaces as pluses standard?
805 EXPECT_TRUE(SuccessfulResponseToURLAndData(
806 GetUrl("/privet/printer/submitdoc?"
807 "client_name=Chrome&user_name=sample%40gmail.com&"
808 "job_name=Sample+job+name"),
809 "Sample print data", kSampleLocalPrintResponse));
810 }
811
812 TEST_P(PrivetLocalPrintTest, SuccessfulLocalPrintWithAnyMimetype) {
813 local_print_operation_->SetUsername("sample@gmail.com");
814 local_print_operation_->SetJobname("Sample job name");
815 local_print_operation_->SetData(
816 RefCountedBytesFromString("Sample print data"));
817 local_print_operation_->SetCapabilities(
818 kSampleCapabilitiesResponseWithAnyMimetype);
819 local_print_operation_->Start();
820
821 EXPECT_TRUE(
822 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
823
824 EXPECT_TRUE(
825 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
826
827 EXPECT_CALL(local_print_delegate_, OnPrivetPrintingDoneInternal());
828
829 // TODO(noamsml): Is encoding spaces as pluses standard?
830 EXPECT_TRUE(SuccessfulResponseToURLAndData(
831 GetUrl("/privet/printer/submitdoc?"
832 "client_name=Chrome&user_name=sample%40gmail.com&"
833 "job_name=Sample+job+name"),
834 "Sample print data", kSampleLocalPrintResponse));
835 }
836
837 TEST_P(PrivetLocalPrintTest, SuccessfulPWGLocalPrint) {
838 local_print_operation_->SetUsername("sample@gmail.com");
839 local_print_operation_->SetJobname("Sample job name");
840 local_print_operation_->SetData(
841 RefCountedBytesFromString("path/to/"));
842 local_print_operation_->SetCapabilities(kSampleCapabilitiesResponsePWGOnly);
843 local_print_operation_->Start();
844
845 EXPECT_TRUE(
846 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
847
848 EXPECT_TRUE(
849 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
850
851 EXPECT_CALL(local_print_delegate_, OnPrivetPrintingDoneInternal());
852
853 // TODO(noamsml): Is encoding spaces as pluses standard?
854 EXPECT_TRUE(SuccessfulResponseToURLAndFilePath(
855 GetUrl("/privet/printer/submitdoc?"
856 "client_name=Chrome&user_name=sample%40gmail.com"
857 "&job_name=Sample+job+name"),
858 base::FilePath(FILE_PATH_LITERAL("path/to/test.pdf")),
859 kSampleLocalPrintResponse));
860
861 EXPECT_EQ(printing::TRANSFORM_NORMAL,
862 pwg_converter_->bitmap_settings().odd_page_transform);
863 EXPECT_FALSE(pwg_converter_->bitmap_settings().rotate_all_pages);
864 EXPECT_FALSE(pwg_converter_->bitmap_settings().reverse_page_order);
865 }
866
867 TEST_P(PrivetLocalPrintTest, SuccessfulPWGLocalPrintDuplex) {
868 local_print_operation_->SetUsername("sample@gmail.com");
869 local_print_operation_->SetJobname("Sample job name");
870 local_print_operation_->SetData(RefCountedBytesFromString("path/to/"));
871 local_print_operation_->SetTicket(kSampleCJTDuplex);
872 local_print_operation_->SetCapabilities(
873 kSampleCapabilitiesResponsePWGSettings);
874 local_print_operation_->Start();
875
876 EXPECT_TRUE(SuccessfulResponseToURL(GetUrl("/privet/info"),
877 kSampleInfoResponseWithCreatejob));
878
879 EXPECT_TRUE(
880 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
881
882 EXPECT_TRUE(SuccessfulResponseToURLAndJSONData(
883 GetUrl("/privet/printer/createjob"), kSampleCJTDuplex,
884 kSampleCreatejobResponse));
885
886 EXPECT_CALL(local_print_delegate_, OnPrivetPrintingDoneInternal());
887
888 // TODO(noamsml): Is encoding spaces as pluses standard?
889 EXPECT_TRUE(SuccessfulResponseToURLAndFilePath(
890 GetUrl("/privet/printer/submitdoc?"
891 "client_name=Chrome&user_name=sample%40gmail.com"
892 "&job_name=Sample+job+name&job_id=1234"),
893 base::FilePath(FILE_PATH_LITERAL("path/to/test.pdf")),
894 kSampleLocalPrintResponse));
895
896 EXPECT_EQ(printing::TRANSFORM_ROTATE_180,
897 pwg_converter_->bitmap_settings().odd_page_transform);
898 EXPECT_FALSE(pwg_converter_->bitmap_settings().rotate_all_pages);
899 EXPECT_TRUE(pwg_converter_->bitmap_settings().reverse_page_order);
900 }
901
902 TEST_P(PrivetLocalPrintTest, SuccessfulLocalPrintWithCreatejob) {
903 local_print_operation_->SetUsername("sample@gmail.com");
904 local_print_operation_->SetJobname("Sample job name");
905 local_print_operation_->SetTicket(kSampleCJT);
906 local_print_operation_->SetData(
907 RefCountedBytesFromString("Sample print data"));
908 local_print_operation_->SetCapabilities(kSampleCapabilitiesResponse);
909 local_print_operation_->Start();
910
911 EXPECT_TRUE(SuccessfulResponseToURL(GetUrl("/privet/info"),
912 kSampleInfoResponseWithCreatejob));
913
914 EXPECT_TRUE(
915 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
916
917 EXPECT_TRUE(
918 SuccessfulResponseToURLAndJSONData(GetUrl("/privet/printer/createjob"),
919 kSampleCJT, kSampleCreatejobResponse));
920
921 EXPECT_CALL(local_print_delegate_, OnPrivetPrintingDoneInternal());
922
923 // TODO(noamsml): Is encoding spaces as pluses standard?
924 EXPECT_TRUE(SuccessfulResponseToURLAndData(
925 GetUrl("/privet/printer/submitdoc?"
926 "client_name=Chrome&user_name=sample%40gmail.com&"
927 "job_name=Sample+job+name&job_id=1234"),
928 "Sample print data", kSampleLocalPrintResponse));
929 }
930
931 TEST_P(PrivetLocalPrintTest, SuccessfulLocalPrintWithOverlongName) {
932 local_print_operation_->SetUsername("sample@gmail.com");
933 local_print_operation_->SetJobname(
934 "123456789:123456789:123456789:123456789:123456789:123456789:123456789:");
935 local_print_operation_->SetTicket(kSampleCJT);
936 local_print_operation_->SetCapabilities(kSampleCapabilitiesResponse);
937 local_print_operation_->SetData(
938 RefCountedBytesFromString("Sample print data"));
939 local_print_operation_->Start();
940
941 EXPECT_TRUE(SuccessfulResponseToURL(GetUrl("/privet/info"),
942 kSampleInfoResponseWithCreatejob));
943
944 EXPECT_TRUE(
945 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
946
947 EXPECT_TRUE(
948 SuccessfulResponseToURLAndJSONData(GetUrl("/privet/printer/createjob"),
949 kSampleCJT, kSampleCreatejobResponse));
950
951 EXPECT_CALL(local_print_delegate_, OnPrivetPrintingDoneInternal());
952
953 // TODO(noamsml): Is encoding spaces as pluses standard?
954 EXPECT_TRUE(SuccessfulResponseToURLAndData(
955 GetUrl("/privet/printer/submitdoc?"
956 "client_name=Chrome&user_name=sample%40gmail.com&"
957 "job_name=123456789%3A123456789%3A123456789%3A1...123456789"
958 "%3A123456789%3A123456789%3A&job_id=1234"),
959 "Sample print data", kSampleLocalPrintResponse));
960 }
961
962 TEST_P(PrivetLocalPrintTest, PDFPrintInvalidDocumentTypeRetry) {
963 local_print_operation_->SetUsername("sample@gmail.com");
964 local_print_operation_->SetJobname("Sample job name");
965 local_print_operation_->SetTicket(kSampleCJT);
966 local_print_operation_->SetCapabilities(kSampleCapabilitiesResponse);
967 local_print_operation_->SetData(
968 RefCountedBytesFromString("sample/path/"));
969 local_print_operation_->Start();
970
971 EXPECT_TRUE(SuccessfulResponseToURL(GetUrl("/privet/info"),
972 kSampleInfoResponseWithCreatejob));
973
974 EXPECT_TRUE(
975 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
976
977 EXPECT_TRUE(
978 SuccessfulResponseToURLAndJSONData(GetUrl("/privet/printer/createjob"),
979 kSampleCJT, kSampleCreatejobResponse));
980
981 // TODO(noamsml): Is encoding spaces as pluses standard?
982 EXPECT_TRUE(SuccessfulResponseToURLAndData(
983 GetUrl("/privet/printer/submitdoc?"
984 "client_name=Chrome&user_name=sample%40gmail.com&"
985 "job_name=Sample+job+name&job_id=1234"),
986 "sample/path/", kSampleInvalidDocumentTypeResponse));
987
988 EXPECT_CALL(local_print_delegate_, OnPrivetPrintingDoneInternal());
989
990 EXPECT_TRUE(SuccessfulResponseToURLAndFilePath(
991 GetUrl("/privet/printer/submitdoc?"
992 "client_name=Chrome&user_name=sample%40gmail.com&"
993 "job_name=Sample+job+name&job_id=1234"),
994 base::FilePath(FILE_PATH_LITERAL("sample/path/test.pdf")),
995 kSampleLocalPrintResponse));
996 }
997
998 TEST_P(PrivetLocalPrintTest, LocalPrintRetryOnInvalidJobID) {
999 local_print_operation_->SetUsername("sample@gmail.com");
1000 local_print_operation_->SetJobname("Sample job name");
1001 local_print_operation_->SetTicket(kSampleCJT);
1002 local_print_operation_->SetCapabilities(kSampleCapabilitiesResponse);
1003 local_print_operation_->SetData(
1004 RefCountedBytesFromString("Sample print data"));
1005 local_print_operation_->Start();
1006
1007 EXPECT_TRUE(SuccessfulResponseToURL(GetUrl("/privet/info"),
1008 kSampleInfoResponseWithCreatejob));
1009
1010 EXPECT_TRUE(
1011 SuccessfulResponseToURL(GetUrl("/privet/info"), kSampleInfoResponse));
1012
1013 EXPECT_TRUE(
1014 SuccessfulResponseToURLAndJSONData(GetUrl("/privet/printer/createjob"),
1015 kSampleCJT, kSampleCreatejobResponse));
1016
1017 EXPECT_TRUE(SuccessfulResponseToURLAndData(
1018 GetUrl("/privet/printer/submitdoc?"
1019 "client_name=Chrome&user_name=sample%40gmail.com&"
1020 "job_name=Sample+job+name&job_id=1234"),
1021 "Sample print data", kSampleErrorResponsePrinterBusy));
1022
1023 RunFor(base::TimeDelta::FromSeconds(3));
1024
1025 EXPECT_TRUE(SuccessfulResponseToURL(GetUrl("/privet/printer/createjob"),
1026 kSampleCreatejobResponse));
1027 }
1028 #endif // ENABLE_PRINT_PREVIEW
1029
1030 class PrivetHttpWithServerTest : public ::testing::Test,
1031 public PrivetURLFetcher::Delegate {
1032 protected:
1033 PrivetHttpWithServerTest()
1034 : thread_bundle_(content::TestBrowserThreadBundle::REAL_IO_THREAD) {}
1035
1036 void SetUp() override {
1037 context_getter_ = new net::TestURLRequestContextGetter(
1038 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
1039
1040 server_.reset(new EmbeddedTestServer(EmbeddedTestServer::TYPE_HTTP));
1041 ASSERT_TRUE(server_->Start());
1042
1043 base::FilePath test_data_dir;
1044 ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &test_data_dir));
1045 server_->ServeFilesFromDirectory(
1046 test_data_dir.Append(FILE_PATH_LITERAL("chrome/test/data")));
1047
1048 client_.reset(new PrivetHTTPClientImpl("test", server_->host_port_pair(),
1049 context_getter_));
1050 }
1051
1052 void OnNeedPrivetToken(
1053 PrivetURLFetcher* fetcher,
1054 const PrivetURLFetcher::TokenCallback& callback) override {
1055 callback.Run("abc");
1056 }
1057
1058 void OnError(PrivetURLFetcher* fetcher,
1059 PrivetURLFetcher::ErrorType error) override {
1060 done_ = true;
1061 success_ = false;
1062 error_ = error;
1063
1064 base::MessageLoop::current()->PostTask(FROM_HERE, quit_);
1065 }
1066
1067 void OnParsedJson(PrivetURLFetcher* fetcher,
1068 const base::DictionaryValue& value,
1069 bool has_error) override {
1070 NOTREACHED();
1071 base::MessageLoop::current()->PostTask(FROM_HERE, quit_);
1072 }
1073
1074 bool OnRawData(PrivetURLFetcher* fetcher,
1075 bool response_is_file,
1076 const std::string& data_string,
1077 const base::FilePath& data_file) override {
1078 done_ = true;
1079 success_ = true;
1080
1081 base::MessageLoop::current()->PostTask(FROM_HERE, quit_);
1082 return true;
1083 }
1084
1085 bool Run() {
1086 success_ = false;
1087 done_ = false;
1088
1089 base::RunLoop run_loop;
1090 quit_ = run_loop.QuitClosure();
1091
1092 scoped_ptr<PrivetURLFetcher> fetcher = client_->CreateURLFetcher(
1093 server_->GetURL("/simple.html"), net::URLFetcher::GET, this);
1094
1095 fetcher->SetMaxRetries(1);
1096 fetcher->Start();
1097
1098 run_loop.Run();
1099
1100 EXPECT_TRUE(done_);
1101 return success_;
1102 }
1103
1104 bool success_ = false;
1105 bool done_ = false;
1106 PrivetURLFetcher::ErrorType error_ = PrivetURLFetcher::ErrorType();
1107 content::TestBrowserThreadBundle thread_bundle_;
1108 scoped_refptr<net::TestURLRequestContextGetter> context_getter_;
1109 scoped_ptr<EmbeddedTestServer> server_;
1110 scoped_ptr<PrivetHTTPClientImpl> client_;
1111
1112 base::Closure quit_;
1113 };
1114
1115 TEST_F(PrivetHttpWithServerTest, HttpServer) {
1116 EXPECT_TRUE(Run());
1117 }
1118
1119 } // namespace
1120
1121 } // namespace local_discovery
OLDNEW
« no previous file with comments | « chrome/browser/local_discovery/privet_http_impl.cc ('k') | chrome/browser/local_discovery/privet_local_printer_lister.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698