Add new certificateProvider extension API.
[chromium-blink-merge.git] / chrome / browser / ui / webui / print_preview / extension_printer_handler_unittest.cc
blob84384460491cedd9d913a05af8661941c0f9644c
1 // Copyright 2015 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 <queue>
6 #include <string>
8 #include "base/bind.h"
9 #include "base/files/file_util.h"
10 #include "base/files/scoped_temp_dir.h"
11 #include "base/json/json_string_value_serializer.h"
12 #include "base/macros.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/run_loop.h"
15 #include "base/strings/string16.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/test/values_test_util.h"
19 #include "base/values.h"
20 #include "chrome/browser/extensions/test_extension_environment.h"
21 #include "chrome/browser/local_discovery/pwg_raster_converter.h"
22 #include "chrome/browser/ui/webui/print_preview/extension_printer_handler.h"
23 #include "chrome/test/base/testing_profile.h"
24 #include "components/version_info/version_info.h"
25 #include "device/core/device_client.h"
26 #include "device/usb/mock_usb_device.h"
27 #include "device/usb/mock_usb_service.h"
28 #include "extensions/browser/api/device_permissions_manager.h"
29 #include "extensions/browser/api/printer_provider/printer_provider_api.h"
30 #include "extensions/browser/api/printer_provider/printer_provider_api_factory.h"
31 #include "extensions/browser/api/printer_provider/printer_provider_print_job.h"
32 #include "extensions/common/extension.h"
33 #include "extensions/common/value_builder.h"
34 #include "printing/pdf_render_settings.h"
35 #include "printing/pwg_raster_settings.h"
36 #include "printing/units.h"
37 #include "testing/gtest/include/gtest/gtest.h"
38 #include "ui/gfx/geometry/size.h"
40 using device::MockUsbDevice;
41 using device::MockUsbService;
42 using extensions::DictionaryBuilder;
43 using extensions::Extension;
44 using extensions::PrinterProviderAPI;
45 using extensions::PrinterProviderPrintJob;
46 using extensions::TestExtensionEnvironment;
47 using local_discovery::PWGRasterConverter;
49 namespace {
51 // Printer id used for requests in tests.
52 const char kPrinterId[] = "printer_id";
54 // Printer list used a result for getPrinters.
55 const char kPrinterDescriptionList[] =
56 "[{"
57 " \"id\": \"printer1\","
58 " \"name\": \"Printer 1\""
59 "}, {"
60 " \"id\": \"printer2\","
61 " \"name\": \"Printer 2\","
62 " \"description\": \"Test printer 2\""
63 "}]";
65 // Printer capability for printer that supports all content types.
66 const char kAllContentTypesSupportedPrinter[] =
67 "{"
68 " \"version\": \"1.0\","
69 " \"printer\": {"
70 " \"supported_content_type\": ["
71 " {\"content_type\": \"*/*\"}"
72 " ]"
73 " }"
74 "}";
76 // Printer capability for a printer that supports PDF.
77 const char kPdfSupportedPrinter[] =
78 "{"
79 " \"version\": \"1.0\","
80 " \"printer\": {"
81 " \"supported_content_type\": ["
82 " {\"content_type\": \"application/pdf\"},"
83 " {\"content_type\": \"image/pwg-raster\"}"
84 " ]"
85 " }"
86 "}";
88 // Printer capability for a printer that supportd only PWG raster.
89 const char kPWGRasterOnlyPrinterSimpleDescription[] =
90 "{"
91 " \"version\": \"1.0\","
92 " \"printer\": {"
93 " \"supported_content_type\": ["
94 " {\"content_type\": \"image/pwg-raster\"}"
95 " ]"
96 " }"
97 "}";
99 // Printer capability for a printer that supportd only PWG raster that has
100 // options other that supported_content_type set.
101 const char kPWGRasterOnlyPrinter[] =
103 " \"version\": \"1.0\","
104 " \"printer\": {"
105 " \"supported_content_type\": ["
106 " {\"content_type\": \"image/pwg-raster\"}"
107 " ],"
108 " \"pwg_raster_config\": {"
109 " \"document_sheet_back\": \"FLIPPED\","
110 " \"reverse_order_streaming\": true,"
111 " \"rotate_all_pages\": true"
112 " },"
113 " \"dpi\": {"
114 " \"option\": [{"
115 " \"horizontal_dpi\": 100,"
116 " \"vertical_dpi\": 200,"
117 " \"is_default\": true"
118 " }]"
119 " }"
120 " }"
121 "}";
123 // Print ticket with no parameters set.
124 const char kEmptyPrintTicket[] = "{\"version\": \"1.0\"}";
126 // Print ticket that has duplex parameter set.
127 const char kPrintTicketWithDuplex[] =
129 " \"version\": \"1.0\","
130 " \"print\": {"
131 " \"duplex\": {\"type\": \"LONG_EDGE\"}"
132 " }"
133 "}";
135 // An extension with permission for 1 printer it supports.
136 const char kExtension1[] =
138 " \"name\": \"Provider 1\","
139 " \"app\": {"
140 " \"background\": {"
141 " \"scripts\": [\"background.js\"]"
142 " }"
143 " },"
144 " \"permissions\": ["
145 " \"printerProvider\","
146 " \"usb\","
147 " {"
148 " \"usbDevices\": ["
149 " { \"vendorId\": 0, \"productId\": 1 }"
150 " ]"
151 " },"
152 " ],"
153 " \"usb_printers\": {"
154 " \"filters\": ["
155 " { \"vendorId\": 0, \"productId\": 0 },"
156 " { \"vendorId\": 0, \"productId\": 1 }"
157 " ]"
158 " }"
159 "}";
161 // An extension with permission for none of the printers it supports.
162 const char kExtension2[] =
164 " \"name\": \"Provider 2\","
165 " \"app\": {"
166 " \"background\": {"
167 " \"scripts\": [\"background.js\"]"
168 " }"
169 " },"
170 " \"permissions\": [ \"printerProvider\", \"usb\" ],"
171 " \"usb_printers\": {"
172 " \"filters\": ["
173 " { \"vendorId\": 0, \"productId\": 0 },"
174 " { \"vendorId\": 0, \"productId\": 1 }"
175 " ]"
176 " }"
177 "}";
179 const char kContentTypePDF[] = "application/pdf";
180 const char kContentTypePWG[] = "image/pwg-raster";
182 // Print request status considered to be successful by fake PrinterProviderAPI.
183 const char kPrintRequestSuccess[] = "OK";
185 // Used as a callback to StartGetPrinters in tests.
186 // Increases |*call_count| and records values returned by StartGetPrinters.
187 void RecordPrinterList(size_t* call_count,
188 scoped_ptr<base::ListValue>* printers_out,
189 bool* is_done_out,
190 const base::ListValue& printers,
191 bool is_done) {
192 ++(*call_count);
193 printers_out->reset(printers.DeepCopy());
194 *is_done_out = is_done;
197 // Used as a callback to StartGetCapability in tests.
198 // Increases |*call_count| and records values returned by StartGetCapability.
199 void RecordCapability(size_t* call_count,
200 std::string* destination_id_out,
201 scoped_ptr<base::DictionaryValue>* capability_out,
202 const std::string& destination_id,
203 const base::DictionaryValue& capability) {
204 ++(*call_count);
205 *destination_id_out = destination_id;
206 capability_out->reset(capability.DeepCopy());
209 // Used as a callback to StartPrint in tests.
210 // Increases |*call_count| and records values returned by StartPrint.
211 void RecordPrintResult(size_t* call_count,
212 bool* success_out,
213 std::string* status_out,
214 bool success,
215 const std::string& status) {
216 ++(*call_count);
217 *success_out = success;
218 *status_out = status;
221 // Used as a callback to StartGrantPrinterAccess in tests.
222 // Increases |*call_count| and records the value returned.
223 void RecordPrinterInfo(size_t* call_count,
224 scoped_ptr<base::DictionaryValue>* printer_info_out,
225 const base::DictionaryValue& printer_info) {
226 ++(*call_count);
227 printer_info_out->reset(printer_info.DeepCopy());
230 // Converts JSON string to base::ListValue object.
231 // On failure, returns NULL and fills |*error| string.
232 scoped_ptr<base::ListValue> GetJSONAsListValue(const std::string& json,
233 std::string* error) {
234 scoped_ptr<base::Value> deserialized(
235 JSONStringValueDeserializer(json).Deserialize(NULL, error));
236 if (!deserialized)
237 return scoped_ptr<base::ListValue>();
238 base::ListValue* list = nullptr;
239 if (!deserialized->GetAsList(&list)) {
240 *error = "Value is not a list.";
241 return scoped_ptr<base::ListValue>();
243 return scoped_ptr<base::ListValue>(list->DeepCopy());
246 // Converts JSON string to base::DictionaryValue object.
247 // On failure, returns NULL and fills |*error| string.
248 scoped_ptr<base::DictionaryValue> GetJSONAsDictionaryValue(
249 const std::string& json,
250 std::string* error) {
251 scoped_ptr<base::Value> deserialized(
252 JSONStringValueDeserializer(json).Deserialize(NULL, error));
253 if (!deserialized)
254 return scoped_ptr<base::DictionaryValue>();
255 base::DictionaryValue* dictionary;
256 if (!deserialized->GetAsDictionary(&dictionary)) {
257 *error = "Value is not a dictionary.";
258 return scoped_ptr<base::DictionaryValue>();
260 return scoped_ptr<base::DictionaryValue>(dictionary->DeepCopy());
263 std::string RefCountedMemoryToString(
264 const scoped_refptr<base::RefCountedMemory>& memory) {
265 return std::string(memory->front_as<char>(), memory->size());
268 // Fake PWGRasterconverter used in the tests.
269 class FakePWGRasterConverter : public PWGRasterConverter {
270 public:
271 FakePWGRasterConverter() : fail_conversion_(false), initialized_(false) {}
272 ~FakePWGRasterConverter() override = default;
274 // PWGRasterConverter implementation. It writes |data| to a temp file.
275 // Also, remembers conversion and bitmap settings passed into the method.
276 void Start(base::RefCountedMemory* data,
277 const printing::PdfRenderSettings& conversion_settings,
278 const printing::PwgRasterSettings& bitmap_settings,
279 const ResultCallback& callback) override {
280 if (fail_conversion_) {
281 callback.Run(false, base::FilePath());
282 return;
285 if (!initialized_ && !temp_dir_.CreateUniqueTempDir()) {
286 ADD_FAILURE() << "Unable to create target dir for cenverter";
287 callback.Run(false, base::FilePath());
288 return;
291 initialized_ = true;
293 path_ = temp_dir_.path().AppendASCII("output.pwg");
294 std::string data_str(data->front_as<char>(), data->size());
295 int written = WriteFile(path_, data_str.c_str(), data_str.size());
296 if (written != static_cast<int>(data_str.size())) {
297 ADD_FAILURE() << "Failed to write pwg raster file.";
298 callback.Run(false, base::FilePath());
299 return;
302 conversion_settings_ = conversion_settings;
303 bitmap_settings_ = bitmap_settings;
305 callback.Run(true, path_);
308 // Makes |Start| method always return an error.
309 void FailConversion() { fail_conversion_ = true; }
311 const base::FilePath& path() { return path_; }
312 const printing::PdfRenderSettings& conversion_settings() const {
313 return conversion_settings_;
316 const printing::PwgRasterSettings& bitmap_settings() const {
317 return bitmap_settings_;
320 private:
321 base::ScopedTempDir temp_dir_;
323 base::FilePath path_;
324 printing::PdfRenderSettings conversion_settings_;
325 printing::PwgRasterSettings bitmap_settings_;
326 bool fail_conversion_;
327 bool initialized_;
329 DISALLOW_COPY_AND_ASSIGN(FakePWGRasterConverter);
332 // Information about received print requests.
333 struct PrintRequestInfo {
334 PrinterProviderAPI::PrintCallback callback;
335 PrinterProviderPrintJob job;
338 // Fake PrinterProviderAPI used in tests.
339 // It caches requests issued to API and exposes methods to trigger their
340 // callbacks.
341 class FakePrinterProviderAPI : public PrinterProviderAPI {
342 public:
343 FakePrinterProviderAPI() = default;
344 ~FakePrinterProviderAPI() override = default;
346 void DispatchGetPrintersRequested(
347 const PrinterProviderAPI::GetPrintersCallback& callback) override {
348 pending_printers_callbacks_.push(callback);
351 void DispatchGetCapabilityRequested(
352 const std::string& destination_id,
353 const PrinterProviderAPI::GetCapabilityCallback& callback) override {
354 pending_capability_callbacks_.push(callback);
357 void DispatchPrintRequested(
358 const PrinterProviderPrintJob& job,
359 const PrinterProviderAPI::PrintCallback& callback) override {
360 PrintRequestInfo request_info;
361 request_info.callback = callback;
362 request_info.job = job;
364 pending_print_requests_.push(request_info);
367 void DispatchGetUsbPrinterInfoRequested(
368 const std::string& extension_id,
369 scoped_refptr<device::UsbDevice> device,
370 const PrinterProviderAPI::GetPrinterInfoCallback& callback) override {
371 EXPECT_EQ("fake extension id", extension_id);
372 EXPECT_TRUE(device);
373 pending_usb_info_callbacks_.push(callback);
376 size_t pending_get_printers_count() const {
377 return pending_printers_callbacks_.size();
380 const PrinterProviderPrintJob* GetPrintJob(
381 const extensions::Extension* extension,
382 int request_id) const override {
383 ADD_FAILURE() << "Not reached";
384 return nullptr;
387 void TriggerNextGetPrintersCallback(const base::ListValue& printers,
388 bool done) {
389 ASSERT_GT(pending_get_printers_count(), 0u);
390 pending_printers_callbacks_.front().Run(printers, done);
391 pending_printers_callbacks_.pop();
394 size_t pending_get_capability_count() const {
395 return pending_capability_callbacks_.size();
398 void TriggerNextGetCapabilityCallback(
399 const base::DictionaryValue& description) {
400 ASSERT_GT(pending_get_capability_count(), 0u);
401 pending_capability_callbacks_.front().Run(description);
402 pending_capability_callbacks_.pop();
405 size_t pending_print_count() const { return pending_print_requests_.size(); }
407 const PrinterProviderPrintJob* GetNextPendingPrintJob() const {
408 EXPECT_GT(pending_print_count(), 0u);
409 if (pending_print_count() == 0)
410 return NULL;
411 return &pending_print_requests_.front().job;
414 void TriggerNextPrintCallback(const std::string& result) {
415 ASSERT_GT(pending_print_count(), 0u);
416 pending_print_requests_.front().callback.Run(result == kPrintRequestSuccess,
417 result);
418 pending_print_requests_.pop();
421 size_t pending_usb_info_count() const {
422 return pending_usb_info_callbacks_.size();
425 void TriggerNextUsbPrinterInfoCallback(
426 const base::DictionaryValue& printer_info) {
427 ASSERT_GT(pending_usb_info_count(), 0u);
428 pending_usb_info_callbacks_.front().Run(printer_info);
429 pending_usb_info_callbacks_.pop();
432 private:
433 std::queue<PrinterProviderAPI::GetPrintersCallback>
434 pending_printers_callbacks_;
435 std::queue<PrinterProviderAPI::GetCapabilityCallback>
436 pending_capability_callbacks_;
437 std::queue<PrintRequestInfo> pending_print_requests_;
438 std::queue<PrinterProviderAPI::GetPrinterInfoCallback>
439 pending_usb_info_callbacks_;
441 DISALLOW_COPY_AND_ASSIGN(FakePrinterProviderAPI);
444 scoped_ptr<KeyedService> BuildTestingPrinterProviderAPI(
445 content::BrowserContext* context) {
446 return make_scoped_ptr(new FakePrinterProviderAPI());
449 class FakeDeviceClient : public device::DeviceClient {
450 public:
451 FakeDeviceClient() {}
453 // device::DeviceClient implementation:
454 device::UsbService* GetUsbService() override {
455 DCHECK(usb_service_);
456 return usb_service_;
459 void set_usb_service(device::UsbService* service) { usb_service_ = service; }
461 private:
462 device::UsbService* usb_service_ = nullptr;
465 } // namespace
467 class ExtensionPrinterHandlerTest : public testing::Test {
468 public:
469 ExtensionPrinterHandlerTest() : pwg_raster_converter_(NULL) {}
470 ~ExtensionPrinterHandlerTest() override = default;
472 void SetUp() override {
473 extensions::PrinterProviderAPIFactory::GetInstance()->SetTestingFactory(
474 env_.profile(), &BuildTestingPrinterProviderAPI);
475 extension_printer_handler_.reset(new ExtensionPrinterHandler(
476 env_.profile(), base::MessageLoop::current()->task_runner()));
478 pwg_raster_converter_ = new FakePWGRasterConverter();
479 extension_printer_handler_->SetPwgRasterConverterForTesting(
480 scoped_ptr<PWGRasterConverter>(pwg_raster_converter_));
481 device_client_.set_usb_service(&usb_service_);
484 protected:
485 FakePrinterProviderAPI* GetPrinterProviderAPI() {
486 return static_cast<FakePrinterProviderAPI*>(
487 extensions::PrinterProviderAPIFactory::GetInstance()
488 ->GetForBrowserContext(env_.profile()));
491 MockUsbService usb_service_;
492 TestExtensionEnvironment env_;
493 scoped_ptr<ExtensionPrinterHandler> extension_printer_handler_;
495 FakePWGRasterConverter* pwg_raster_converter_;
497 private:
498 FakeDeviceClient device_client_;
500 DISALLOW_COPY_AND_ASSIGN(ExtensionPrinterHandlerTest);
503 TEST_F(ExtensionPrinterHandlerTest, GetPrinters) {
504 size_t call_count = 0;
505 scoped_ptr<base::ListValue> printers;
506 bool is_done = false;
508 extension_printer_handler_->StartGetPrinters(
509 base::Bind(&RecordPrinterList, &call_count, &printers, &is_done));
511 EXPECT_FALSE(printers.get());
512 FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
513 ASSERT_TRUE(fake_api);
514 ASSERT_EQ(1u, fake_api->pending_get_printers_count());
516 std::string error;
517 scoped_ptr<base::ListValue> original_printers(
518 GetJSONAsListValue(kPrinterDescriptionList, &error));
519 ASSERT_TRUE(original_printers) << "Failed to deserialize printers: " << error;
521 fake_api->TriggerNextGetPrintersCallback(*original_printers, true);
523 EXPECT_EQ(1u, call_count);
524 EXPECT_TRUE(is_done);
525 ASSERT_TRUE(printers.get());
526 EXPECT_TRUE(printers->Equals(original_printers.get()))
527 << *printers << ", expected: " << *original_printers;
530 TEST_F(ExtensionPrinterHandlerTest, GetPrinters_Reset) {
531 size_t call_count = 0;
532 scoped_ptr<base::ListValue> printers;
533 bool is_done = false;
535 extension_printer_handler_->StartGetPrinters(
536 base::Bind(&RecordPrinterList, &call_count, &printers, &is_done));
538 EXPECT_FALSE(printers.get());
539 FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
540 ASSERT_TRUE(fake_api);
541 ASSERT_EQ(1u, fake_api->pending_get_printers_count());
543 extension_printer_handler_->Reset();
545 std::string error;
546 scoped_ptr<base::ListValue> original_printers(
547 GetJSONAsListValue(kPrinterDescriptionList, &error));
548 ASSERT_TRUE(original_printers) << "Error deserializing printers: " << error;
550 fake_api->TriggerNextGetPrintersCallback(*original_printers, true);
552 EXPECT_EQ(0u, call_count);
555 TEST_F(ExtensionPrinterHandlerTest, GetUsbPrinters) {
556 scoped_refptr<MockUsbDevice> device0 =
557 new MockUsbDevice(0, 0, "Google", "USB Printer", "");
558 usb_service_.AddDevice(device0);
559 scoped_refptr<MockUsbDevice> device1 =
560 new MockUsbDevice(0, 1, "Google", "USB Printer", "");
561 usb_service_.AddDevice(device1);
563 const Extension* extension_1 = env_.MakeExtension(
564 *base::test::ParseJson(kExtension1), "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
565 const Extension* extension_2 = env_.MakeExtension(
566 *base::test::ParseJson(kExtension2), "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
568 extensions::DevicePermissionsManager* permissions_manager =
569 extensions::DevicePermissionsManager::Get(env_.profile());
570 permissions_manager->AllowUsbDevice(extension_2->id(), device0);
572 size_t call_count = 0;
573 scoped_ptr<base::ListValue> printers;
574 bool is_done = false;
575 extension_printer_handler_->StartGetPrinters(
576 base::Bind(&RecordPrinterList, &call_count, &printers, &is_done));
578 FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
579 ASSERT_TRUE(fake_api);
580 ASSERT_EQ(1u, fake_api->pending_get_printers_count());
582 EXPECT_EQ(1u, call_count);
583 EXPECT_FALSE(is_done);
584 EXPECT_TRUE(printers.get());
585 EXPECT_EQ(2u, printers->GetSize());
586 scoped_ptr<base::DictionaryValue> extension_1_entry(
587 DictionaryBuilder()
588 .Set("id", base::StringPrintf("provisional-usb:%s:%s",
589 extension_1->id().c_str(),
590 device0->guid().c_str()))
591 .Set("name", "USB Printer")
592 .Set("extensionName", "Provider 1")
593 .Set("extensionId", extension_1->id())
594 .Set("provisional", true)
595 .Build());
596 scoped_ptr<base::DictionaryValue> extension_2_entry(
597 DictionaryBuilder()
598 .Set("id", base::StringPrintf("provisional-usb:%s:%s",
599 extension_2->id().c_str(),
600 device1->guid().c_str()))
601 .Set("name", "USB Printer")
602 .Set("extensionName", "Provider 2")
603 .Set("extensionId", extension_2->id())
604 .Set("provisional", true)
605 .Build());
606 EXPECT_TRUE(printers->Find(*extension_1_entry) != printers->end());
607 EXPECT_TRUE(printers->Find(*extension_2_entry) != printers->end());
609 fake_api->TriggerNextGetPrintersCallback(base::ListValue(), true);
611 EXPECT_EQ(2u, call_count);
612 EXPECT_TRUE(is_done);
613 EXPECT_TRUE(printers.get());
614 EXPECT_EQ(0u, printers->GetSize()); // RecordPrinterList resets |printers|.
617 TEST_F(ExtensionPrinterHandlerTest, GetCapability) {
618 size_t call_count = 0;
619 std::string destination_id;
620 scoped_ptr<base::DictionaryValue> capability;
622 extension_printer_handler_->StartGetCapability(
623 kPrinterId,
624 base::Bind(&RecordCapability, &call_count, &destination_id, &capability));
626 EXPECT_EQ(0u, call_count);
628 FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
629 ASSERT_TRUE(fake_api);
630 ASSERT_EQ(1u, fake_api->pending_get_capability_count());
632 std::string error;
633 scoped_ptr<base::DictionaryValue> original_capability(
634 GetJSONAsDictionaryValue(kPWGRasterOnlyPrinterSimpleDescription, &error));
635 ASSERT_TRUE(original_capability)
636 << "Error deserializing capability: " << error;
638 fake_api->TriggerNextGetCapabilityCallback(*original_capability);
640 EXPECT_EQ(1u, call_count);
641 EXPECT_EQ(kPrinterId, destination_id);
642 ASSERT_TRUE(capability.get());
643 EXPECT_TRUE(capability->Equals(original_capability.get()))
644 << *capability << ", expected: " << *original_capability;
647 TEST_F(ExtensionPrinterHandlerTest, GetCapability_Reset) {
648 size_t call_count = 0;
649 std::string destination_id;
650 scoped_ptr<base::DictionaryValue> capability;
652 extension_printer_handler_->StartGetCapability(
653 kPrinterId,
654 base::Bind(&RecordCapability, &call_count, &destination_id, &capability));
656 EXPECT_EQ(0u, call_count);
658 FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
659 ASSERT_TRUE(fake_api);
660 ASSERT_EQ(1u, fake_api->pending_get_capability_count());
662 extension_printer_handler_->Reset();
664 std::string error;
665 scoped_ptr<base::DictionaryValue> original_capability(
666 GetJSONAsDictionaryValue(kPWGRasterOnlyPrinterSimpleDescription, &error));
667 ASSERT_TRUE(original_capability)
668 << "Error deserializing capability: " << error;
670 fake_api->TriggerNextGetCapabilityCallback(*original_capability);
672 EXPECT_EQ(0u, call_count);
675 TEST_F(ExtensionPrinterHandlerTest, Print_Pdf) {
676 size_t call_count = 0;
677 bool success = false;
678 std::string status;
680 scoped_refptr<base::RefCountedString> print_data(
681 new base::RefCountedString());
682 print_data->data() = "print data, PDF";
683 base::string16 title = base::ASCIIToUTF16("Title");
685 extension_printer_handler_->StartPrint(
686 kPrinterId, kPdfSupportedPrinter, title, kEmptyPrintTicket,
687 gfx::Size(100, 100), print_data,
688 base::Bind(&RecordPrintResult, &call_count, &success, &status));
690 EXPECT_EQ(0u, call_count);
691 FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
692 ASSERT_TRUE(fake_api);
693 ASSERT_EQ(1u, fake_api->pending_print_count());
695 const PrinterProviderPrintJob* print_job = fake_api->GetNextPendingPrintJob();
696 ASSERT_TRUE(print_job);
698 EXPECT_EQ(kPrinterId, print_job->printer_id);
699 EXPECT_EQ(title, print_job->job_title);
700 EXPECT_EQ(kEmptyPrintTicket, print_job->ticket_json);
701 EXPECT_EQ(kContentTypePDF, print_job->content_type);
702 EXPECT_TRUE(print_job->document_path.empty());
703 ASSERT_TRUE(print_job->document_bytes);
704 EXPECT_EQ(print_data->data(),
705 RefCountedMemoryToString(print_job->document_bytes));
707 fake_api->TriggerNextPrintCallback(kPrintRequestSuccess);
709 EXPECT_EQ(1u, call_count);
710 EXPECT_TRUE(success);
711 EXPECT_EQ(kPrintRequestSuccess, status);
714 TEST_F(ExtensionPrinterHandlerTest, Print_Pdf_Reset) {
715 size_t call_count = 0;
716 bool success = false;
717 std::string status;
719 scoped_refptr<base::RefCountedString> print_data(
720 new base::RefCountedString());
721 print_data->data() = "print data, PDF";
722 base::string16 title = base::ASCIIToUTF16("Title");
724 extension_printer_handler_->StartPrint(
725 kPrinterId, kPdfSupportedPrinter, title, kEmptyPrintTicket,
726 gfx::Size(100, 100), print_data,
727 base::Bind(&RecordPrintResult, &call_count, &success, &status));
729 EXPECT_EQ(0u, call_count);
730 FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
731 ASSERT_TRUE(fake_api);
732 ASSERT_EQ(1u, fake_api->pending_print_count());
734 extension_printer_handler_->Reset();
736 fake_api->TriggerNextPrintCallback(kPrintRequestSuccess);
738 EXPECT_EQ(0u, call_count);
741 TEST_F(ExtensionPrinterHandlerTest, Print_All) {
742 size_t call_count = 0;
743 bool success = false;
744 std::string status;
746 scoped_refptr<base::RefCountedString> print_data(
747 new base::RefCountedString());
748 print_data->data() = "print data, PDF";
749 base::string16 title = base::ASCIIToUTF16("Title");
751 extension_printer_handler_->StartPrint(
752 kPrinterId, kAllContentTypesSupportedPrinter, title, kEmptyPrintTicket,
753 gfx::Size(100, 100), print_data,
754 base::Bind(&RecordPrintResult, &call_count, &success, &status));
756 EXPECT_EQ(0u, call_count);
758 FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
759 ASSERT_TRUE(fake_api);
760 ASSERT_EQ(1u, fake_api->pending_print_count());
762 const PrinterProviderPrintJob* print_job = fake_api->GetNextPendingPrintJob();
763 ASSERT_TRUE(print_job);
765 EXPECT_EQ(kPrinterId, print_job->printer_id);
766 EXPECT_EQ(title, print_job->job_title);
767 EXPECT_EQ(kEmptyPrintTicket, print_job->ticket_json);
768 EXPECT_EQ(kContentTypePDF, print_job->content_type);
769 EXPECT_TRUE(print_job->document_path.empty());
770 ASSERT_TRUE(print_job->document_bytes);
771 EXPECT_EQ(print_data->data(),
772 RefCountedMemoryToString(print_job->document_bytes));
774 fake_api->TriggerNextPrintCallback(kPrintRequestSuccess);
776 EXPECT_EQ(1u, call_count);
777 EXPECT_TRUE(success);
778 EXPECT_EQ(kPrintRequestSuccess, status);
781 TEST_F(ExtensionPrinterHandlerTest, Print_Pwg) {
782 size_t call_count = 0;
783 bool success = false;
784 std::string status;
786 scoped_refptr<base::RefCountedString> print_data(
787 new base::RefCountedString());
788 print_data->data() = "print data, PDF";
789 base::string16 title = base::ASCIIToUTF16("Title");
791 extension_printer_handler_->StartPrint(
792 kPrinterId, kPWGRasterOnlyPrinterSimpleDescription, title,
793 kEmptyPrintTicket, gfx::Size(100, 50), print_data,
794 base::Bind(&RecordPrintResult, &call_count, &success, &status));
796 EXPECT_EQ(0u, call_count);
798 base::RunLoop().RunUntilIdle();
800 FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
801 ASSERT_TRUE(fake_api);
802 ASSERT_EQ(1u, fake_api->pending_print_count());
804 EXPECT_EQ(printing::TRANSFORM_NORMAL,
805 pwg_raster_converter_->bitmap_settings().odd_page_transform);
806 EXPECT_FALSE(pwg_raster_converter_->bitmap_settings().rotate_all_pages);
807 EXPECT_FALSE(pwg_raster_converter_->bitmap_settings().reverse_page_order);
809 EXPECT_EQ(printing::kDefaultPdfDpi,
810 pwg_raster_converter_->conversion_settings().dpi());
811 EXPECT_TRUE(pwg_raster_converter_->conversion_settings().autorotate());
812 EXPECT_EQ("0,0 208x416", // vertically_oriented_size * dpi / points_per_inch
813 pwg_raster_converter_->conversion_settings().area().ToString());
815 const PrinterProviderPrintJob* print_job = fake_api->GetNextPendingPrintJob();
816 ASSERT_TRUE(print_job);
818 EXPECT_EQ(kPrinterId, print_job->printer_id);
819 EXPECT_EQ(title, print_job->job_title);
820 EXPECT_EQ(kEmptyPrintTicket, print_job->ticket_json);
821 EXPECT_EQ(kContentTypePWG, print_job->content_type);
822 EXPECT_FALSE(print_job->document_bytes);
823 EXPECT_FALSE(print_job->document_path.empty());
824 EXPECT_EQ(pwg_raster_converter_->path(), print_job->document_path);
825 EXPECT_EQ(static_cast<int64_t>(print_data->size()),
826 print_job->file_info.size);
828 fake_api->TriggerNextPrintCallback(kPrintRequestSuccess);
830 EXPECT_EQ(1u, call_count);
831 EXPECT_TRUE(success);
832 EXPECT_EQ(kPrintRequestSuccess, status);
835 TEST_F(ExtensionPrinterHandlerTest, Print_Pwg_NonDefaultSettings) {
836 size_t call_count = 0;
837 bool success = false;
838 std::string status;
840 scoped_refptr<base::RefCountedString> print_data(
841 new base::RefCountedString());
842 print_data->data() = "print data, PDF";
843 base::string16 title = base::ASCIIToUTF16("Title");
845 extension_printer_handler_->StartPrint(
846 kPrinterId, kPWGRasterOnlyPrinter, title, kPrintTicketWithDuplex,
847 gfx::Size(100, 50), print_data,
848 base::Bind(&RecordPrintResult, &call_count, &success, &status));
850 EXPECT_EQ(0u, call_count);
852 base::RunLoop().RunUntilIdle();
854 FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
855 ASSERT_TRUE(fake_api);
856 ASSERT_EQ(1u, fake_api->pending_print_count());
858 EXPECT_EQ(printing::TRANSFORM_FLIP_VERTICAL,
859 pwg_raster_converter_->bitmap_settings().odd_page_transform);
860 EXPECT_TRUE(pwg_raster_converter_->bitmap_settings().rotate_all_pages);
861 EXPECT_TRUE(pwg_raster_converter_->bitmap_settings().reverse_page_order);
863 EXPECT_EQ(200, // max(vertical_dpi, horizontal_dpi)
864 pwg_raster_converter_->conversion_settings().dpi());
865 EXPECT_TRUE(pwg_raster_converter_->conversion_settings().autorotate());
866 EXPECT_EQ("0,0 138x277", // vertically_oriented_size * dpi / points_per_inch
867 pwg_raster_converter_->conversion_settings().area().ToString());
869 const PrinterProviderPrintJob* print_job = fake_api->GetNextPendingPrintJob();
870 ASSERT_TRUE(print_job);
872 EXPECT_EQ(kPrinterId, print_job->printer_id);
873 EXPECT_EQ(title, print_job->job_title);
874 EXPECT_EQ(kPrintTicketWithDuplex, print_job->ticket_json);
875 EXPECT_EQ(kContentTypePWG, print_job->content_type);
876 EXPECT_FALSE(print_job->document_bytes);
877 EXPECT_FALSE(print_job->document_path.empty());
878 EXPECT_EQ(pwg_raster_converter_->path(), print_job->document_path);
879 EXPECT_EQ(static_cast<int64_t>(print_data->size()),
880 print_job->file_info.size);
882 fake_api->TriggerNextPrintCallback(kPrintRequestSuccess);
884 EXPECT_EQ(1u, call_count);
885 EXPECT_TRUE(success);
886 EXPECT_EQ(kPrintRequestSuccess, status);
889 TEST_F(ExtensionPrinterHandlerTest, Print_Pwg_Reset) {
890 size_t call_count = 0;
891 bool success = false;
892 std::string status;
894 scoped_refptr<base::RefCountedString> print_data(
895 new base::RefCountedString());
896 print_data->data() = "print data, PDF";
897 base::string16 title = base::ASCIIToUTF16("Title");
899 extension_printer_handler_->StartPrint(
900 kPrinterId, kPWGRasterOnlyPrinterSimpleDescription, title,
901 kEmptyPrintTicket, gfx::Size(100, 50), print_data,
902 base::Bind(&RecordPrintResult, &call_count, &success, &status));
904 EXPECT_EQ(0u, call_count);
906 base::RunLoop().RunUntilIdle();
908 FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
909 ASSERT_TRUE(fake_api);
910 ASSERT_EQ(1u, fake_api->pending_print_count());
912 extension_printer_handler_->Reset();
914 fake_api->TriggerNextPrintCallback(kPrintRequestSuccess);
916 EXPECT_EQ(0u, call_count);
919 TEST_F(ExtensionPrinterHandlerTest, Print_Pwg_InvalidTicket) {
920 size_t call_count = 0;
921 bool success = false;
922 std::string status;
924 scoped_refptr<base::RefCountedString> print_data(
925 new base::RefCountedString());
926 print_data->data() = "print data, PDF";
927 base::string16 title = base::ASCIIToUTF16("Title");
929 extension_printer_handler_->StartPrint(
930 kPrinterId, kPWGRasterOnlyPrinterSimpleDescription, title,
931 "{}" /* ticket */, gfx::Size(100, 100), print_data,
932 base::Bind(&RecordPrintResult, &call_count, &success, &status));
934 EXPECT_EQ(1u, call_count);
936 EXPECT_FALSE(success);
937 EXPECT_EQ("INVALID_TICKET", status);
940 TEST_F(ExtensionPrinterHandlerTest, Print_Pwg_FailedConversion) {
941 size_t call_count = 0;
942 bool success = false;
943 std::string status;
945 pwg_raster_converter_->FailConversion();
947 scoped_refptr<base::RefCountedString> print_data(
948 new base::RefCountedString());
949 print_data->data() = "print data, PDF";
950 base::string16 title = base::ASCIIToUTF16("Title");
952 extension_printer_handler_->StartPrint(
953 kPrinterId, kPWGRasterOnlyPrinterSimpleDescription, title,
954 kEmptyPrintTicket, gfx::Size(100, 100), print_data,
955 base::Bind(&RecordPrintResult, &call_count, &success, &status));
957 EXPECT_EQ(1u, call_count);
959 EXPECT_FALSE(success);
960 EXPECT_EQ("INVALID_DATA", status);
963 TEST_F(ExtensionPrinterHandlerTest, GrantUsbPrinterAccess) {
964 scoped_refptr<MockUsbDevice> device =
965 new MockUsbDevice(0, 0, "Google", "USB Printer", "");
966 usb_service_.AddDevice(device);
968 size_t call_count = 0;
969 scoped_ptr<base::DictionaryValue> printer_info;
971 std::string printer_id = base::StringPrintf(
972 "provisional-usb:fake extension id:%s", device->guid().c_str());
973 extension_printer_handler_->StartGrantPrinterAccess(
974 printer_id, base::Bind(&RecordPrinterInfo, &call_count, &printer_info));
976 EXPECT_FALSE(printer_info.get());
977 FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
978 ASSERT_TRUE(fake_api);
979 ASSERT_EQ(1u, fake_api->pending_usb_info_count());
981 scoped_ptr<base::DictionaryValue> original_printer_info(
982 DictionaryBuilder()
983 .Set("id", "printer1")
984 .Set("name", "Printer 1")
985 .Build());
987 fake_api->TriggerNextUsbPrinterInfoCallback(*original_printer_info);
989 EXPECT_EQ(1u, call_count);
990 ASSERT_TRUE(printer_info.get());
991 EXPECT_TRUE(printer_info->Equals(original_printer_info.get()))
992 << *printer_info << ", expected: " << *original_printer_info;
995 TEST_F(ExtensionPrinterHandlerTest, GrantUsbPrinterAccess_Reset) {
996 scoped_refptr<MockUsbDevice> device =
997 new MockUsbDevice(0, 0, "Google", "USB Printer", "");
998 usb_service_.AddDevice(device);
1000 size_t call_count = 0;
1001 scoped_ptr<base::DictionaryValue> printer_info;
1003 extension_printer_handler_->StartGrantPrinterAccess(
1004 base::StringPrintf("provisional-usb:fake extension id:%s",
1005 device->guid().c_str()),
1006 base::Bind(&RecordPrinterInfo, &call_count, &printer_info));
1008 EXPECT_FALSE(printer_info.get());
1009 FakePrinterProviderAPI* fake_api = GetPrinterProviderAPI();
1010 ASSERT_TRUE(fake_api);
1011 ASSERT_EQ(1u, fake_api->pending_usb_info_count());
1013 extension_printer_handler_->Reset();
1015 scoped_ptr<base::DictionaryValue> original_printer_info(
1016 DictionaryBuilder()
1017 .Set("id", "printer1")
1018 .Set("name", "Printer 1")
1019 .Build());
1021 fake_api->TriggerNextUsbPrinterInfoCallback(*original_printer_info);
1023 EXPECT_EQ(0u, call_count);
1024 EXPECT_FALSE(printer_info.get());