Avoid crashing when going back/forward to debug URLs on a sad WebUI tab.
[chromium-blink-merge.git] / chrome / service / cloud_print / printer_job_handler_unittest.cc
blobda396dd335ad39ce9d363f73dace7e4294570d0c
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.
5 #include "base/files/file_path.h"
6 #include "base/location.h"
7 #include "base/md5.h"
8 #include "base/memory/ref_counted.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/single_thread_task_runner.h"
12 #include "base/strings/stringprintf.h"
13 #include "base/thread_task_runner_handle.h"
14 #include "chrome/common/cloud_print/cloud_print_constants.h"
15 #include "chrome/service/cloud_print/cloud_print_service_helpers.h"
16 #include "chrome/service/cloud_print/cloud_print_token_store.h"
17 #include "chrome/service/cloud_print/print_system.h"
18 #include "chrome/service/cloud_print/printer_job_handler.h"
19 #include "net/http/http_response_headers.h"
20 #include "net/http/http_status_code.h"
21 #include "net/url_request/test_url_fetcher_factory.h"
22 #include "net/url_request/url_request_status.h"
23 #include "net/url_request/url_request_test_util.h"
24 #include "printing/backend/print_backend.h"
25 #include "testing/gmock/include/gmock/gmock.h"
26 #include "testing/gtest/include/gtest/gtest.h"
28 using ::testing::AtLeast;
29 using ::testing::DoAll;
30 using ::testing::Exactly;
31 using ::testing::Invoke;
32 using ::testing::InvokeWithoutArgs;
33 using ::testing::NiceMock;
34 using ::testing::Return;
35 using ::testing::SaveArg;
36 using ::testing::Sequence;
37 using ::testing::SetArgPointee;
38 using ::testing::StrictMock;
39 using ::testing::_;
41 namespace cloud_print {
43 namespace {
45 using base::StringPrintf;
47 const char kExampleCloudPrintServerURL[] = "https://www.google.com/cloudprint/";
49 const char kExamplePrintTicket[] = "{\"MediaType\":\"plain\","
50 "\"Resolution\":\"300x300dpi\",\"PageRegion\":\"Letter\","
51 "\"InputSlot\":\"auto\",\"PageSize\":\"Letter\",\"EconoMode\":\"off\"}";
54 // The fillowing constants will all be constructed with StringPrintf. The
55 // following types of parameters are possible:
56 // job number(int): ID # of job from given job list. All job IDs follow the
57 // format __example_job_idN for some N.
58 // fetch reason(string): Fetch reason used by the code. The job list URL
59 // requested by PrinterJobHandler has an extra parameter that signifies when
60 // the request was triggered.
61 // status string(string): Status of print job, one of IN_PROGRESS, DONE or ERROR
62 // job object list(string/JSON formatted): a comma-separated list of job objects
64 // StringPrintf parameters: job number, job number, job number, job number
65 const char kExampleJobObject[] = "{"
66 " \"tags\": ["
67 " \"^own\""
68 " ],"
69 " \"printerName\": \"Example Printer\","
70 " \"status\": \"QUEUED\","
71 " \"ownerId\": \"sampleuser@gmail.com\","
72 " \"ticketUrl\": \"https://www.google.com/cloudprint/ticket?exampleURI%d\","
73 " \"printerid\": \"__example_printer_id\","
74 " \"printerType\": \"GOOGLE\","
75 " \"contentType\": \"text/html\","
76 " \"fileUrl\": \"https://www.google.com/cloudprint/download?exampleURI%d\","
77 " \"id\": \"__example_job_id%d\","
78 " \"message\": \"\","
79 " \"title\": \"Example Job %d\","
80 " \"errorCode\": \"\","
81 " \"numberOfPages\": 3"
82 " }";
84 // StringPrintf parameters: job object list
85 const char kExampleJobListResponse[] = "{"
86 " \"success\": true,"
87 " \"jobs\": ["
88 " %s"
89 " ],"
90 " \"xsrf_token\": \"AIp06DjUd3AV6BO0aujB9NvM2a9ZbogxOQ:1360021066932\","
91 " \"request\": {"
92 " \"time\": \"0\","
93 " \"users\": ["
94 " \"sampleuser@gmail.com\""
95 " ],"
96 " \"params\": {"
97 " \"printerid\": ["
98 " \"__example_printer_id\""
99 " ]"
100 " },"
101 " \"user\": \"sampleuser@gmail.com\""
102 " }"
103 "}";
106 // StringPrintf parameters: job number
107 const char kExampleJobID[] = "__example_job_id%d";
109 // StringPrintf parameters: job number
110 const char kExamplePrintTicketURI[] =
111 "https://www.google.com/cloudprint/ticket?exampleURI%d";
113 // StringPrintf parameters: job number
114 const char kExamplePrintDownloadURI[] =
115 "https://www.google.com/cloudprint/download?exampleURI%d";
117 // StringPrintf parameters: job number
118 const char kExampleUpdateDoneURI[] =
119 "https://www.google.com/cloudprint/control?jobid=__example_job_id%d"
120 "&status=DONE&code=0&message=&numpages=0&pagesprinted=0";
122 // StringPrintf parameters: job number
123 const char kExampleUpdateErrorURI[] =
124 "https://www.google.com/cloudprint/control?jobid=__example_job_id%d"
125 "&status=ERROR";
127 // StringPrintf parameters: fetch reason
128 const char kExamplePrinterJobListURI[] =
129 "https://www.google.com/cloudprint/fetch"
130 "?printerid=__example_printer_id&deb=%s";
132 // StringPrintf parameters: status string, job number, status string (repeat)
133 const char kExampleControlResponse[] = "{"
134 " \"success\": true,"
135 " \"message\": \"Print job updated successfully.\","
136 " \"xsrf_token\": \"AIp06DjKgbfGalbqzj23V1bU6i-vtR2B4w:1360023068789\","
137 " \"request\": {"
138 " \"time\": \"0\","
139 " \"users\": ["
140 " \"sampleuser@gmail.com\""
141 " ],"
142 " \"params\": {"
143 " \"xsrf\": ["
144 " \"AIp06DgeGIETs42Cj28QWmxGPWVDiaXwVQ:1360023041852\""
145 " ],"
146 " \"status\": ["
147 " \"%s\""
148 " ],"
149 " \"jobid\": ["
150 " \"__example_job_id%d\""
151 " ]"
152 " },"
153 " \"user\": \"sampleuser@gmail.com\""
154 " },"
155 " \"job\": {"
156 " \"tags\": ["
157 " \"^own\""
158 " ],"
159 " \"printerName\": \"Example Printer\","
160 " \"status\": \"%s\","
161 " \"ownerId\": \"sampleuser@gmail.com\","
162 " \"ticketUrl\": \"https://www.google.com/cloudprint/ticket?exampleURI1\","
163 " \"printerid\": \"__example_printer_id\","
164 " \"contentType\": \"text/html\","
165 " \"fileUrl\": \"https://www.google.com/cloudprint/download?exampleURI1\","
166 " \"id\": \"__example_job_id1\","
167 " \"message\": \"\","
168 " \"title\": \"Example Job\","
169 " \"errorCode\": \"\","
170 " \"numberOfPages\": 3"
171 " }"
172 "}";
174 const char kExamplePrinterID[] = "__example_printer_id";
176 const char kExamplePrinterCapabilities[] = "";
178 const char kExampleCapsMimeType[] = "";
180 // These can stay empty
181 const char kExampleDefaults[] = "";
183 const char kExampleDefaultMimeType[] = "";
185 // Since we're not connecting to the server, this can be any non-empty string.
186 const char kExampleCloudPrintOAuthToken[] = "__SAMPLE_TOKEN";
189 // Not actually printing, no need for real PDF.
190 const char kExamplePrintData[] = "__EXAMPLE_PRINT_DATA";
192 const char kExampleJobDownloadResponseHeaders[] =
193 "Content-Type: Application/PDF\n";
195 const char kExampleTicketDownloadResponseHeaders[] =
196 "Content-Type: application/json\n";
198 const char kExamplePrinterName[] = "Example Printer";
200 const char kExamplePrinterDescription[] = "Example Description";
202 // These are functions used to construct the various sample strings.
203 std::string JobListResponse(int num_jobs) {
204 std::string job_objects;
205 for (int i = 0; i < num_jobs; i++) {
206 job_objects = job_objects + StringPrintf(kExampleJobObject, i+1, i+1, i+1,
207 i+1);
208 if (i != num_jobs-1) job_objects = job_objects + ",";
210 return StringPrintf(kExampleJobListResponse, job_objects.c_str());
213 GURL JobListURI(const char* reason) {
214 return GURL(StringPrintf(kExamplePrinterJobListURI, reason));
217 GURL DoneURI(int job_num) {
218 return GURL(StringPrintf(kExampleUpdateDoneURI, job_num));
221 GURL ErrorURI(int job_num) {
222 return GURL(StringPrintf(kExampleUpdateErrorURI, job_num));
225 GURL TicketURI(int job_num) {
226 return GURL(StringPrintf(kExamplePrintTicketURI, job_num));
229 GURL DownloadURI(int job_num) {
230 return GURL(StringPrintf(kExamplePrintDownloadURI, job_num));
233 GURL InProgressURI(int job_num) {
234 return GetUrlForJobStatusUpdate(GURL(kExampleCloudPrintServerURL),
235 StringPrintf(kExampleJobID, job_num),
236 PRINT_JOB_STATUS_IN_PROGRESS,
240 std::string StatusResponse(int job_num, const char* status_string) {
241 return StringPrintf(kExampleControlResponse,
242 status_string,
243 job_num,
244 status_string);
247 } // namespace
249 class CloudPrintURLFetcherNoServiceProcess
250 : public CloudPrintURLFetcher {
251 public:
252 CloudPrintURLFetcherNoServiceProcess()
253 : context_getter_(new net::TestURLRequestContextGetter(
254 base::ThreadTaskRunnerHandle::Get())) {}
256 protected:
257 net::URLRequestContextGetter* GetRequestContextGetter() override {
258 return context_getter_.get();
261 ~CloudPrintURLFetcherNoServiceProcess() override {}
263 private:
264 scoped_refptr<net::URLRequestContextGetter> context_getter_;
268 class CloudPrintURLFetcherNoServiceProcessFactory
269 : public CloudPrintURLFetcherFactory {
270 public:
271 CloudPrintURLFetcher* CreateCloudPrintURLFetcher() override {
272 return new CloudPrintURLFetcherNoServiceProcess;
275 ~CloudPrintURLFetcherNoServiceProcessFactory() override {}
279 // This class handles the callback from FakeURLFetcher
280 // It is a separate class because callback methods must be
281 // on RefCounted classes
283 class TestURLFetcherCallback {
284 public:
285 scoped_ptr<net::FakeURLFetcher> CreateURLFetcher(
286 const GURL& url,
287 net::URLFetcherDelegate* d,
288 const std::string& response_data,
289 net::HttpStatusCode response_code,
290 net::URLRequestStatus::Status status) {
291 scoped_ptr<net::FakeURLFetcher> fetcher(
292 new net::FakeURLFetcher(url, d, response_data, response_code, status));
293 OnRequestCreate(url, fetcher.get());
294 return fetcher.Pass();
296 MOCK_METHOD2(OnRequestCreate,
297 void(const GURL&, net::FakeURLFetcher*));
301 class MockPrinterJobHandlerDelegate
302 : public PrinterJobHandler::Delegate {
303 public:
304 MOCK_METHOD0(OnAuthError, void());
305 MOCK_METHOD1(OnPrinterDeleted, void(const std::string& str));
307 virtual ~MockPrinterJobHandlerDelegate() {}
311 class MockPrintServerWatcher
312 : public PrintSystem::PrintServerWatcher {
313 public:
314 MOCK_METHOD1(StartWatching,
315 bool(PrintSystem::PrintServerWatcher::Delegate* d));
316 MOCK_METHOD0(StopWatching, bool());
318 MockPrintServerWatcher();
319 PrintSystem::PrintServerWatcher::Delegate* delegate() const {
320 return delegate_;
323 friend class scoped_refptr<NiceMock<MockPrintServerWatcher> >;
324 friend class scoped_refptr<StrictMock<MockPrintServerWatcher> >;
325 friend class scoped_refptr<MockPrintServerWatcher>;
327 protected:
328 virtual ~MockPrintServerWatcher() {}
330 private:
331 PrintSystem::PrintServerWatcher::Delegate* delegate_;
334 class MockPrinterWatcher : public PrintSystem::PrinterWatcher {
335 public:
336 MOCK_METHOD1(StartWatching, bool(PrintSystem::PrinterWatcher::Delegate* d));
337 MOCK_METHOD0(StopWatching, bool());
338 MOCK_METHOD1(GetCurrentPrinterInfo,
339 bool(printing::PrinterBasicInfo* printer_info));
341 MockPrinterWatcher();
342 PrintSystem::PrinterWatcher::Delegate* delegate() const { return delegate_; }
344 friend class scoped_refptr<NiceMock<MockPrinterWatcher> >;
345 friend class scoped_refptr<StrictMock<MockPrinterWatcher> >;
346 friend class scoped_refptr<MockPrinterWatcher>;
348 protected:
349 virtual ~MockPrinterWatcher() {}
351 private:
352 PrintSystem::PrinterWatcher::Delegate* delegate_;
356 class MockJobSpooler : public PrintSystem::JobSpooler {
357 public:
358 MOCK_METHOD8(Spool, bool(
359 const std::string& print_ticket,
360 const std::string& print_ticket_mime_type,
361 const base::FilePath& print_data_file_path,
362 const std::string& print_data_mime_type,
363 const std::string& printer_name,
364 const std::string& job_title,
365 const std::vector<std::string>& tags,
366 PrintSystem::JobSpooler::Delegate* delegate));
368 MockJobSpooler();
369 PrintSystem::JobSpooler::Delegate* delegate() const { return delegate_; }
371 friend class scoped_refptr<NiceMock<MockJobSpooler> >;
372 friend class scoped_refptr<StrictMock<MockJobSpooler> >;
373 friend class scoped_refptr<MockJobSpooler>;
375 protected:
376 virtual ~MockJobSpooler() {}
378 private:
379 PrintSystem::JobSpooler::Delegate* delegate_;
384 class MockPrintSystem : public PrintSystem {
385 public:
386 MockPrintSystem();
387 PrintSystem::PrintSystemResult succeed() {
388 return PrintSystem::PrintSystemResult(true, "success");
391 PrintSystem::PrintSystemResult fail() {
392 return PrintSystem::PrintSystemResult(false, "failure");
395 MockJobSpooler& JobSpooler() { return *job_spooler_.get(); }
397 MockPrinterWatcher& PrinterWatcher() { return *printer_watcher_.get(); }
399 MockPrintServerWatcher& PrintServerWatcher() {
400 return *print_server_watcher_.get();
403 MOCK_METHOD0(Init, PrintSystem::PrintSystemResult());
404 MOCK_METHOD1(EnumeratePrinters, PrintSystem::PrintSystemResult(
405 printing::PrinterList* printer_list));
407 MOCK_METHOD2(
408 GetPrinterCapsAndDefaults,
409 void(const std::string& printer_name,
410 const PrintSystem::PrinterCapsAndDefaultsCallback& callback));
412 MOCK_METHOD1(IsValidPrinter, bool(const std::string& printer_name));
414 MOCK_METHOD3(ValidatePrintTicket,
415 bool(const std::string& printer_name,
416 const std::string& print_ticket_data,
417 const std::string& print_ticket_mime_type));
419 MOCK_METHOD3(GetJobDetails, bool(const std::string& printer_name,
420 PlatformJobId job_id,
421 PrintJobDetails* job_details));
423 MOCK_METHOD0(CreatePrintServerWatcher, PrintSystem::PrintServerWatcher*());
424 MOCK_METHOD1(CreatePrinterWatcher,
425 PrintSystem::PrinterWatcher*(const std::string& printer_name));
426 MOCK_METHOD0(CreateJobSpooler, PrintSystem::JobSpooler*());
428 MOCK_METHOD0(UseCddAndCjt, bool());
429 MOCK_METHOD0(GetSupportedMimeTypes, std::string());
431 friend class scoped_refptr<NiceMock<MockPrintSystem> >;
432 friend class scoped_refptr<StrictMock<MockPrintSystem> >;
433 friend class scoped_refptr<MockPrintSystem>;
435 protected:
436 virtual ~MockPrintSystem() {}
438 private:
439 scoped_refptr<MockJobSpooler> job_spooler_;
440 scoped_refptr<MockPrinterWatcher> printer_watcher_;
441 scoped_refptr<MockPrintServerWatcher> print_server_watcher_;
445 class PrinterJobHandlerTest : public ::testing::Test {
446 public:
447 PrinterJobHandlerTest();
448 void SetUp() override;
449 void TearDown() override;
450 void IdleOut();
451 bool GetPrinterInfo(printing::PrinterBasicInfo* info);
452 void SendCapsAndDefaults(
453 const std::string& printer_name,
454 const PrintSystem::PrinterCapsAndDefaultsCallback& callback);
455 void AddMimeHeader(const GURL& url, net::FakeURLFetcher* fetcher);
456 void AddTicketMimeHeader(const GURL& url, net::FakeURLFetcher* fetcher);
457 bool PostSpoolSuccess();
458 void SetUpJobSuccessTest(int job_num);
459 void BeginTest(int timeout_seconds);
460 void MakeJobFetchReturnNoJobs();
462 static void MessageLoopQuitNowHelper(base::MessageLoop* message_loop);
463 static void MessageLoopQuitSoonHelper(base::MessageLoop* message_loop);
465 base::MessageLoopForIO loop_;
466 TestURLFetcherCallback url_callback_;
467 MockPrinterJobHandlerDelegate jobhandler_delegate_;
468 CloudPrintTokenStore token_store_;
469 CloudPrintURLFetcherNoServiceProcessFactory cloud_print_factory_;
470 scoped_refptr<PrinterJobHandler> job_handler_;
471 scoped_refptr<NiceMock<MockPrintSystem> > print_system_;
472 net::FakeURLFetcherFactory factory_;
473 printing::PrinterBasicInfo basic_info_;
474 printing::PrinterCapsAndDefaults caps_and_defaults_;
475 PrinterJobHandler::PrinterInfoFromCloud info_from_cloud_;
479 void PrinterJobHandlerTest::SetUp() {
480 basic_info_.printer_name = kExamplePrinterName;
481 basic_info_.printer_description = kExamplePrinterDescription;
482 basic_info_.is_default = 0;
484 info_from_cloud_.printer_id = kExamplePrinterID;
485 info_from_cloud_.tags_hash = GetHashOfPrinterInfo(basic_info_);
487 info_from_cloud_.caps_hash = base::MD5String(kExamplePrinterCapabilities);
488 info_from_cloud_.current_xmpp_timeout = 300;
489 info_from_cloud_.pending_xmpp_timeout = 0;
491 caps_and_defaults_.printer_capabilities = kExamplePrinterCapabilities;
492 caps_and_defaults_.caps_mime_type = kExampleCapsMimeType;
493 caps_and_defaults_.printer_defaults = kExampleDefaults;
494 caps_and_defaults_.defaults_mime_type = kExampleDefaultMimeType;
496 print_system_ = new NiceMock<MockPrintSystem>();
498 token_store_.SetToken(kExampleCloudPrintOAuthToken);
500 ON_CALL(print_system_->PrinterWatcher(), GetCurrentPrinterInfo(_))
501 .WillByDefault(Invoke(this, &PrinterJobHandlerTest::GetPrinterInfo));
503 ON_CALL(*print_system_.get(), GetPrinterCapsAndDefaults(_, _))
504 .WillByDefault(Invoke(this, &PrinterJobHandlerTest::SendCapsAndDefaults));
506 CloudPrintURLFetcher::set_factory(&cloud_print_factory_);
509 void PrinterJobHandlerTest::MakeJobFetchReturnNoJobs() {
510 factory_.SetFakeResponse(JobListURI(kJobFetchReasonStartup),
511 JobListResponse(0), net::HTTP_OK,
512 net::URLRequestStatus::SUCCESS);
513 factory_.SetFakeResponse(JobListURI(kJobFetchReasonFailure),
514 JobListResponse(0), net::HTTP_OK,
515 net::URLRequestStatus::SUCCESS);
516 factory_.SetFakeResponse(JobListURI(kJobFetchReasonRetry),
517 JobListResponse(0), net::HTTP_OK,
518 net::URLRequestStatus::SUCCESS);
521 void PrinterJobHandlerTest::MessageLoopQuitNowHelper(
522 base::MessageLoop* message_loop) {
523 message_loop->QuitWhenIdle();
526 void PrinterJobHandlerTest::MessageLoopQuitSoonHelper(
527 base::MessageLoop* message_loop) {
528 message_loop->task_runner()->PostTask(
529 FROM_HERE, base::Bind(&MessageLoopQuitNowHelper, message_loop));
532 PrinterJobHandlerTest::PrinterJobHandlerTest()
533 : factory_(NULL, base::Bind(&TestURLFetcherCallback::CreateURLFetcher,
534 base::Unretained(&url_callback_))) {
537 bool PrinterJobHandlerTest::PostSpoolSuccess() {
538 base::ThreadTaskRunnerHandle::Get()->PostTask(
539 FROM_HERE,
540 base::Bind(&PrinterJobHandler::OnJobSpoolSucceeded, job_handler_, 0));
542 // Everything that would be posted on the printer thread queue
543 // has been posted, we can tell the main message loop to quit when idle
544 // and not worry about it idling while the print thread does work
545 base::ThreadTaskRunnerHandle::Get()->PostTask(
546 FROM_HERE, base::Bind(&MessageLoopQuitSoonHelper, &loop_));
547 return true;
550 void PrinterJobHandlerTest::AddMimeHeader(const GURL& url,
551 net::FakeURLFetcher* fetcher) {
552 scoped_refptr<net::HttpResponseHeaders> download_headers =
553 new net::HttpResponseHeaders(kExampleJobDownloadResponseHeaders);
554 fetcher->set_response_headers(download_headers);
557 void PrinterJobHandlerTest::AddTicketMimeHeader(const GURL& url,
558 net::FakeURLFetcher* fetcher) {
559 scoped_refptr<net::HttpResponseHeaders> download_headers =
560 new net::HttpResponseHeaders(kExampleTicketDownloadResponseHeaders);
561 fetcher->set_response_headers(download_headers);
565 void PrinterJobHandlerTest::SetUpJobSuccessTest(int job_num) {
566 factory_.SetFakeResponse(TicketURI(job_num),
567 kExamplePrintTicket, net::HTTP_OK,
568 net::URLRequestStatus::SUCCESS);
569 factory_.SetFakeResponse(DownloadURI(job_num),
570 kExamplePrintData, net::HTTP_OK,
571 net::URLRequestStatus::SUCCESS);
573 factory_.SetFakeResponse(DoneURI(job_num),
574 StatusResponse(job_num, "DONE"),
575 net::HTTP_OK,
576 net::URLRequestStatus::SUCCESS);
577 factory_.SetFakeResponse(InProgressURI(job_num),
578 StatusResponse(job_num, "IN_PROGRESS"),
579 net::HTTP_OK,
580 net::URLRequestStatus::SUCCESS);
582 // The times requirement is relaxed for the ticket URI
583 // in order to accommodate TicketDownloadFailureTest
584 EXPECT_CALL(url_callback_, OnRequestCreate(TicketURI(job_num), _))
585 .Times(AtLeast(1))
586 .WillOnce(Invoke(this, &PrinterJobHandlerTest::AddTicketMimeHeader));
588 EXPECT_CALL(url_callback_, OnRequestCreate(DownloadURI(job_num), _))
589 .Times(Exactly(1))
590 .WillOnce(Invoke(this, &PrinterJobHandlerTest::AddMimeHeader));
592 EXPECT_CALL(url_callback_, OnRequestCreate(InProgressURI(job_num), _))
593 .Times(Exactly(1));
595 EXPECT_CALL(url_callback_, OnRequestCreate(DoneURI(job_num), _))
596 .Times(Exactly(1));
598 EXPECT_CALL(print_system_->JobSpooler(),
599 Spool(kExamplePrintTicket, _, _, _, _, _, _, _))
600 .Times(Exactly(1))
601 .WillOnce(InvokeWithoutArgs(this,
602 &PrinterJobHandlerTest::PostSpoolSuccess));
605 void PrinterJobHandlerTest::BeginTest(int timeout_seconds) {
606 job_handler_ = new PrinterJobHandler(basic_info_,
607 info_from_cloud_,
608 GURL(kExampleCloudPrintServerURL),
609 print_system_.get(),
610 &jobhandler_delegate_);
612 job_handler_->Initialize();
614 base::MessageLoop::current()->PostDelayedTask(
615 FROM_HERE,
616 base::Bind(&PrinterJobHandlerTest::MessageLoopQuitSoonHelper,
617 base::MessageLoop::current()),
618 base::TimeDelta::FromSeconds(timeout_seconds));
620 base::MessageLoop::current()->Run();
623 void PrinterJobHandlerTest::SendCapsAndDefaults(
624 const std::string& printer_name,
625 const PrintSystem::PrinterCapsAndDefaultsCallback& callback) {
626 callback.Run(true, printer_name, caps_and_defaults_);
629 bool PrinterJobHandlerTest::GetPrinterInfo(printing::PrinterBasicInfo* info) {
630 *info = basic_info_;
631 return true;
634 void PrinterJobHandlerTest::TearDown() {
635 IdleOut();
636 CloudPrintURLFetcher::set_factory(NULL);
639 void PrinterJobHandlerTest::IdleOut() {
640 base::MessageLoop::current()->RunUntilIdle();
643 MockPrintServerWatcher::MockPrintServerWatcher() : delegate_(NULL) {
644 ON_CALL(*this, StartWatching(_))
645 .WillByDefault(DoAll(SaveArg<0>(&delegate_), Return(true)));
646 ON_CALL(*this, StopWatching()).WillByDefault(Return(true));
650 MockPrinterWatcher::MockPrinterWatcher() : delegate_(NULL) {
651 ON_CALL(*this, StartWatching(_))
652 .WillByDefault(DoAll(SaveArg<0>(&delegate_), Return(true)));
653 ON_CALL(*this, StopWatching()).WillByDefault(Return(true));
656 MockJobSpooler::MockJobSpooler() : delegate_(NULL) {
657 ON_CALL(*this, Spool(_, _, _, _, _, _, _, _))
658 .WillByDefault(DoAll(SaveArg<7>(&delegate_), Return(true)));
661 MockPrintSystem::MockPrintSystem()
662 : job_spooler_(new NiceMock<MockJobSpooler>()),
663 printer_watcher_(new NiceMock<MockPrinterWatcher>()),
664 print_server_watcher_(new NiceMock<MockPrintServerWatcher>()) {
665 ON_CALL(*this, CreateJobSpooler()).WillByDefault(Return(job_spooler_.get()));
667 ON_CALL(*this, CreatePrinterWatcher(_))
668 .WillByDefault(Return(printer_watcher_.get()));
670 ON_CALL(*this, CreatePrintServerWatcher())
671 .WillByDefault(Return(print_server_watcher_.get()));
673 ON_CALL(*this, IsValidPrinter(_)).
674 WillByDefault(Return(true));
676 ON_CALL(*this, ValidatePrintTicket(_, _, _)).
677 WillByDefault(Return(true));
680 // This test simulates an end-to-end printing of a document
681 // but tests only non-failure cases.
682 // Disabled - http://crbug.com/184245
683 TEST_F(PrinterJobHandlerTest, DISABLED_HappyPathTest) {
684 factory_.SetFakeResponse(JobListURI(kJobFetchReasonStartup),
685 JobListResponse(1), net::HTTP_OK,
686 net::URLRequestStatus::SUCCESS);
687 factory_.SetFakeResponse(JobListURI(kJobFetchReasonQueryMore),
688 JobListResponse(0), net::HTTP_OK,
689 net::URLRequestStatus::SUCCESS);
691 EXPECT_CALL(url_callback_,
692 OnRequestCreate(JobListURI(kJobFetchReasonStartup), _))
693 .Times(Exactly(1));
694 EXPECT_CALL(url_callback_,
695 OnRequestCreate(JobListURI(kJobFetchReasonQueryMore), _))
696 .Times(Exactly(1));
698 SetUpJobSuccessTest(1);
699 BeginTest(20);
702 TEST_F(PrinterJobHandlerTest, TicketDownloadFailureTest) {
703 factory_.SetFakeResponse(JobListURI(kJobFetchReasonStartup),
704 JobListResponse(2), net::HTTP_OK,
705 net::URLRequestStatus::SUCCESS);
706 factory_.SetFakeResponse(JobListURI(kJobFetchReasonFailure),
707 JobListResponse(2), net::HTTP_OK,
708 net::URLRequestStatus::SUCCESS);
709 factory_.SetFakeResponse(JobListURI(kJobFetchReasonQueryMore),
710 JobListResponse(0), net::HTTP_OK,
711 net::URLRequestStatus::SUCCESS);
712 factory_.SetFakeResponse(TicketURI(1), std::string(),
713 net::HTTP_INTERNAL_SERVER_ERROR,
714 net::URLRequestStatus::FAILED);
716 EXPECT_CALL(url_callback_, OnRequestCreate(TicketURI(1), _))
717 .Times(AtLeast(1))
718 .WillOnce(Invoke(this, &PrinterJobHandlerTest::AddTicketMimeHeader));
720 EXPECT_CALL(url_callback_,
721 OnRequestCreate(JobListURI(kJobFetchReasonStartup), _))
722 .Times(AtLeast(1));
724 EXPECT_CALL(url_callback_,
725 OnRequestCreate(JobListURI(kJobFetchReasonQueryMore), _))
726 .Times(AtLeast(1));
728 EXPECT_CALL(url_callback_,
729 OnRequestCreate(JobListURI(kJobFetchReasonFailure), _))
730 .Times(AtLeast(1));
732 SetUpJobSuccessTest(2);
733 BeginTest(20);
736 // TODO(noamsml): Figure out how to make this test not take 1 second and
737 // re-enable it
738 TEST_F(PrinterJobHandlerTest, DISABLED_ManyFailureTest) {
739 factory_.SetFakeResponse(JobListURI(kJobFetchReasonStartup),
740 JobListResponse(1), net::HTTP_OK,
741 net::URLRequestStatus::SUCCESS);
742 factory_.SetFakeResponse(JobListURI(kJobFetchReasonFailure),
743 JobListResponse(1), net::HTTP_OK,
744 net::URLRequestStatus::SUCCESS);
745 factory_.SetFakeResponse(JobListURI(kJobFetchReasonRetry),
746 JobListResponse(1), net::HTTP_OK,
747 net::URLRequestStatus::SUCCESS);
748 factory_.SetFakeResponse(JobListURI(kJobFetchReasonQueryMore),
749 JobListResponse(0), net::HTTP_OK,
750 net::URLRequestStatus::SUCCESS);
752 EXPECT_CALL(url_callback_,
753 OnRequestCreate(JobListURI(kJobFetchReasonStartup), _))
754 .Times(AtLeast(1));
756 EXPECT_CALL(url_callback_,
757 OnRequestCreate(JobListURI(kJobFetchReasonQueryMore), _))
758 .Times(AtLeast(1));
760 EXPECT_CALL(url_callback_,
761 OnRequestCreate(JobListURI(kJobFetchReasonFailure), _))
762 .Times(AtLeast(1));
764 EXPECT_CALL(url_callback_,
765 OnRequestCreate(JobListURI(kJobFetchReasonRetry), _))
766 .Times(AtLeast(1));
768 SetUpJobSuccessTest(1);
770 factory_.SetFakeResponse(TicketURI(1),
771 std::string(),
772 net::HTTP_INTERNAL_SERVER_ERROR,
773 net::URLRequestStatus::FAILED);
775 loop_.task_runner()->PostDelayedTask(
776 FROM_HERE,
777 base::Bind(&net::FakeURLFetcherFactory::SetFakeResponse,
778 base::Unretained(&factory_), TicketURI(1), kExamplePrintTicket,
779 net::HTTP_OK, net::URLRequestStatus::SUCCESS),
780 base::TimeDelta::FromSeconds(1));
782 BeginTest(5);
786 // TODO(noamsml): Figure out how to make this test not take ~64-~2048 (depending
787 // constant values) seconds and re-enable it
788 TEST_F(PrinterJobHandlerTest, DISABLED_CompleteFailureTest) {
789 factory_.SetFakeResponse(JobListURI(kJobFetchReasonStartup),
790 JobListResponse(1), net::HTTP_OK,
791 net::URLRequestStatus::SUCCESS);
792 factory_.SetFakeResponse(JobListURI(kJobFetchReasonFailure),
793 JobListResponse(1), net::HTTP_OK,
794 net::URLRequestStatus::SUCCESS);
795 factory_.SetFakeResponse(JobListURI(kJobFetchReasonRetry),
796 JobListResponse(1), net::HTTP_OK,
797 net::URLRequestStatus::SUCCESS);
798 factory_.SetFakeResponse(ErrorURI(1), StatusResponse(1, "ERROR"),
799 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
800 factory_.SetFakeResponse(TicketURI(1), std::string(),
801 net::HTTP_INTERNAL_SERVER_ERROR,
802 net::URLRequestStatus::FAILED);
804 EXPECT_CALL(url_callback_,
805 OnRequestCreate(JobListURI(kJobFetchReasonStartup), _))
806 .Times(AtLeast(1));
808 EXPECT_CALL(url_callback_,
809 OnRequestCreate(JobListURI(kJobFetchReasonFailure), _))
810 .Times(AtLeast(1));
812 EXPECT_CALL(url_callback_,
813 OnRequestCreate(JobListURI(kJobFetchReasonRetry), _))
814 .Times(AtLeast(1));
816 EXPECT_CALL(url_callback_, OnRequestCreate(ErrorURI(1), _))
817 .Times(Exactly(1))
818 .WillOnce(InvokeWithoutArgs(
819 this, &PrinterJobHandlerTest::MakeJobFetchReturnNoJobs));
821 EXPECT_CALL(url_callback_, OnRequestCreate(TicketURI(1), _))
822 .Times(AtLeast(kNumRetriesBeforeAbandonJob));
824 BeginTest(70);
827 } // namespace cloud_print