summaryrefslogtreecommitdiffstats
path: root/chrome/test/data/webui/print_preview.js
blob: 09bec48e1ba4c7ebd8eb2b51c30d416cebbefa4a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Test fixture for print preview WebUI testing.
 * @extends {testing.Test}
 * @constructor
 */
function PrintPreviewWebUITest() {}

PrintPreviewWebUITest.prototype = {
  __proto__: testing.Test.prototype,

  /**
   * Browse to the sample page, cause print preview & call preLoad().
   * @type {string}
   * @override
   */
  browsePrintPreload: 'print_preview_hello_world_test.html',

  /**
   * Register a mock handler to ensure expectations are met and print preview
   * behaves correctly.
   * @type {Function}
   * @override
   */
  preLoad: function() {
    // TODO(scr) remove this after tests pass consistently.
    console.info('preLoad');

    /**
     * Create a handler class with empty methods to allow mocking to register
     * expectations and for registration of handlers with chrome.send.
     * @constructor
     */
    function MockPrintPreviewHandler() {}

    MockPrintPreviewHandler.prototype = {
      getDefaultPrinter: function() {},
      getPrinters: function() {},
      getPreview: function(settings, draft_page_count, modifiable) {},
      print: function(settings) {},
      getPrinterCapabilities: function(printerName) {},
      showSystemDialog: function() {},
      morePrinters: function() {},
      signIn: function() {},
      addCloudPrinter: function() {},
      manageCloudPrinters: function() {},
      manageLocalPrinters: function() {},
      closePrintPreviewTab: function() {},
      hidePreview: function() {},
      cancelPendingPrintRequest: function() {},
      saveLastPrinter: function(name, cloud_print_data) {},
    };

    // Create the actual mock and register stubs for methods expected to be
    // called before tests run.  Specific expectations can be made in the
    // tests themselves.
    var mockHandler = this.mockHandler = mock(MockPrintPreviewHandler);
    mockHandler.stubs().getDefaultPrinter().
        will(callFunction(function() {
          setDefaultPrinter('FooDevice');
        }));
    mockHandler.stubs().getPrinterCapabilities(NOT_NULL).
        will(callFunction(function() {
          updateWithPrinterCapabilities({
            disableColorOption: true,
            setColorAsDefault: true,
            disableCopiesOption: true,
            printerDefaultDuplexValue: copiesSettings.SIMPLEX,
          });
        }));
    var savedArgs = new SaveMockArguments();
    mockHandler.stubs().getPreview(savedArgs.match(NOT_NULL)).
        will(callFunctionWithSavedArgs(savedArgs, function(args) {
          updatePrintPreview(1, JSON.parse(args[0]).requestID);
        }));

    mockHandler.stubs().getPrinters().
        will(callFunction(function() {
          setUseCloudPrint(false, '');
          setPrinters([{
              printerName: 'FooName',
              deviceName: 'FooDevice',
            }, {
              printerName: 'BarName',
              deviceName: 'BarDevice',
            },
          ]);
        }));

    // Register mock as a handler of the chrome.send messages.
    registerMockMessageCallbacks(mockHandler, MockPrintPreviewHandler);

    /**
     * Create a class to hold global functions to watch for.
     * @constructor
     */
    function MockGlobals() {}

    MockGlobals.prototype = {
      updateWithPrinterCapabilities: function(settingInfo) {},
    };

    var mockGlobals = this.mockGlobals = mock(MockGlobals);
    mockGlobals.stubs().updateWithPrinterCapabilities(
        savedArgs.match(ANYTHING)).
            will(callGlobalWithSavedArgs(
                savedArgs, 'updateWithPrinterCapabilities'));

    // Register globals to mock out for us.
    registerMockGlobals(mockGlobals, MockGlobals);

    // Override checkCompatiblePluginExists to return a value consistent with
    // the state being tested and stub out the pdf viewer if it doesn't exist,
    // such as on non-official builds. When the plugin exists, use the real
    // thing.
    var self = this;
    window.addEventListener('DOMContentLoaded', function() {
      if (!this.checkCompatiblePluginExists()) {
        // TODO(scr) remove this after tests pass consistently.
        console.info('no PDF Plugin; providing fake methods.');
        this.createPDFPlugin = self.createPDFPlugin;
      }

      this.checkCompatiblePluginExists =
          self.checkCompatiblePluginExists;
    });
  },

  /**
   * Generate a real C++ class; don't typedef.
   * @type {?string}
   * @override
   */
  typedefCppFixture: null,

  /**
   * Create the PDF plugin or reload the existing one. This function replaces
   * createPDFPlugin defined in
   * chrome/browser/resources/print_preview/print_preview.js when there is no
   * official pdf plugin so that the WebUI logic can be tested. It creates and
   * attaches an HTMLDivElement to the |mainview| element with attributes and
   * empty methods, which are used by testing and that would be provided by the
   * HTMLEmbedElement when the PDF plugin exists.
   * @param {number} srcDataIndex Preview data source index.
   */
  createPDFPlugin: function(srcDataIndex) {
    var pdfViewer = $('pdf-viewer');
    if (pdfViewer)
      return;

    var previewUid = 1;
    pdfViewer = document.createElement('div');
    pdfViewer.setAttribute('id', 'pdf-viewer');
    pdfViewer.setAttribute('type',
                           'application/x-google-chrome-print-preview-pdf');
    pdfViewer.setAttribute(
        'src',
        'chrome://print/' + previewUid + '/' + srcDataIndex + '/print.pdf');
    pdfViewer.setAttribute('aria-live', 'polite');
    pdfViewer.setAttribute('aria-atomic', 'true');
    function fakeFunction() {}
    pdfViewer.onload = fakeFunction;
    pdfViewer.goToPage = fakeFunction;
    pdfViewer.removePrintButton = fakeFunction;
    pdfViewer.fitToHeight = fakeFunction;
    pdfViewer.grayscale = fakeFunction;
    $('mainview').appendChild(pdfViewer);
    onPDFLoad();
  },

  /**
   * Always return true so tests run on systems without plugin available.
   * @return {boolean} Always true.
   */
  checkCompatiblePluginExists: function() {
    return true;
  },
};

GEN('#include "base/command_line.h"');
GEN('#include "chrome/browser/ui/webui/web_ui_browsertest.h"');
GEN('#include "chrome/common/chrome_switches.h"');
GEN('');
GEN('class PrintPreviewWebUITest');
GEN('    : public WebUIBrowserTest {');
GEN(' protected:');
GEN('  // WebUIBrowserTest override.');
GEN('  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {');
GEN('    WebUIBrowserTest::SetUpCommandLine(command_line);');
GEN('    command_line->AppendSwitch(switches::kEnablePrintPreview);');
GEN('  }');
GEN('');
GEN('};');
GEN('');

/**
 * The expected length of the |printer-list| element.
 * @type {number}
 * @const
 */
var printerListMinLength = 2;

/**
 * The expected index of the "foo" printer returned by the stubbed handler.
 * @type {number}
 * @const
 */
var fooIndex = 0;

/**
 * The expected index of the "bar" printer returned by the stubbed handler.
 * @type {number}
 * @const
 */
var barIndex = 1;

// Test some basic assumptions about the print preview WebUI.
TEST_F('PrintPreviewWebUITest', 'TestPrinterList', function() {
  var printerList = $('printer-list');
  assertNotEquals(null, printerList);
  assertGE(printerList.options.length, printerListMinLength);
  expectEquals(fooIndex, printerList.selectedIndex);
  expectEquals('FooName', printerList.options[fooIndex].text,
               'fooIndex=' + fooIndex);
  expectEquals('FooDevice', printerList.options[fooIndex].value,
               'fooIndex=' + fooIndex);
  expectEquals('BarName', printerList.options[barIndex].text,
               'barIndex=' + barIndex);
  expectEquals('BarDevice', printerList.options[barIndex].value,
               'barIndex=' + barIndex);
});

// Test that the printer list is structured correctly after calling
// addCloudPrinters with an empty list.
TEST_F('PrintPreviewWebUITest', 'FLAKY_TestPrinterListCloudEmpty', function() {
  addCloudPrinters([]);
  var printerList = $('printer-list');
  assertNotEquals(null, printerList);
  expectEquals(localStrings.getString('cloudPrinters'),
               printerList.options[0].text);
  expectEquals(localStrings.getString('addCloudPrinter'),
               printerList.options[1].text);
});

// Test that the printer list is structured correctly after calling
// addCloudPrinters with a null list.
TEST_F('PrintPreviewWebUITest', 'FLAKY_TestPrinterListCloudNull', function() {
  addCloudPrinters(null);
  var printerList = $('printer-list');
  assertNotEquals(null, printerList);
  expectEquals(localStrings.getString('cloudPrinters'),
               printerList.options[0].text);
  expectEquals(localStrings.getString('signIn'),
               printerList.options[1].text);
});

// Test that the printer list is structured correctly after attempting to add
// individual cloud printers until no more can be added.
TEST_F('PrintPreviewWebUITest', 'FLAKY_TestPrinterListCloud', function() {
  var printerList = $('printer-list');
  assertNotEquals(null, printerList);
  var printer = new Object;
  printer['name'] = 'FooCloud';
  for (var i = 0; i < maxCloudPrinters; i++) {
    printer['id'] = String(i);
    addCloudPrinters([printer]);
    expectEquals(localStrings.getString('cloudPrinters'),
                 printerList.options[0].text);
    expectEquals('FooCloud', printerList.options[i + 1].text);
    expectEquals(String(i), printerList.options[i + 1].value);
  }
  printer['id'] = maxCloudPrinters + 1;
  addCloudPrinters([printer]);
  expectEquals('', printerList.options[maxCloudPrinters + 1].text);
  expectEquals(localStrings.getString('morePrinters'),
               printerList.options[maxCloudPrinters + 2].text);
});

/**
 * Verify that |section| visibility matches |visible|.
 * @param {HTMLDivElement} section The section to check.
 * @param {boolean} visible The expected state of visibility.
 */
function checkSectionVisible(section, visible) {
  assertNotEquals(null, section);
  expectEquals(section.classList.contains('visible'), visible,
               'section=' + section);
}

// Test that disabled settings hide the disabled sections.
TEST_F('PrintPreviewWebUITest', 'TestSectionsDisabled', function() {
  this.mockHandler.expects(once()).getPrinterCapabilities('FooDevice').
      will(callFunction(function() {
        updateWithPrinterCapabilities({
          disableColorOption: true,
          setColorAsDefault: true,
          disableCopiesOption: true,
          disableLandscapeOption: true,
          printerDefaultDuplexValue: copiesSettings.SIMPLEX,
        });
      }));

  updateControlsWithSelectedPrinterCapabilities();

  checkSectionVisible(layoutSettings.layoutOption_, false);
  checkSectionVisible(colorSettings.colorOption_, false);
  checkSectionVisible(copiesSettings.copiesOption_, false);
});

// Test that the color settings are set according to the printer capabilities.
TEST_F('PrintPreviewWebUITest', 'TestColorSettings', function() {
  this.mockHandler.expects(once()).getPrinterCapabilities('FooDevice').
      will(callFunction(function() {
        updateWithPrinterCapabilities({
          disableColorOption: false,
          setColorAsDefault: true,
          disableCopiesOption: false,
          disableLandscapeOption: false,
          printerDefaultDuplexValue: copiesSettings.SIMPLEX,
        });
      }));

  updateControlsWithSelectedPrinterCapabilities();
  expectTrue(colorSettings.colorRadioButton.checked);
  expectFalse(colorSettings.bwRadioButton.checked);

  this.mockHandler.expects(once()).getPrinterCapabilities('FooDevice').
      will(callFunction(function() {
        updateWithPrinterCapabilities({
          disableColorOption: false,
          setColorAsDefault: false,
          disableCopiesOption: false,
          disableLandscapeOption: false,
          printerDefaultDuplexValue: copiesSettings.SIMPLEX,
        });
      }));

  updateControlsWithSelectedPrinterCapabilities();
  expectFalse(colorSettings.colorRadioButton.checked);
  expectTrue(colorSettings.bwRadioButton.checked);
});

// Test to verify that duplex settings are set according to the printer
// capabilities.
TEST_F('PrintPreviewWebUITest', 'TestDuplexSettings', function() {
  this.mockHandler.expects(once()).getPrinterCapabilities('FooDevice').
      will(callFunction(function() {
        updateWithPrinterCapabilities({
          disableColorOption: false,
          setColorAsDefault: false,
          disableCopiesOption: false,
          disableLandscapeOption: false,
          printerDefaultDuplexValue: copiesSettings.SIMPLEX,
        });
      }));
  updateControlsWithSelectedPrinterCapabilities();
  expectEquals(copiesSettings.duplexMode, copiesSettings.SIMPLEX);
  expectEquals(copiesSettings.twoSidedOption_.hidden, false);

  // If the printer default duplex value is UNKNOWN_DUPLEX_MODE, hide the
  // two sided option.
  this.mockHandler.expects(once()).getPrinterCapabilities('FooDevice').
      will(callFunction(function() {
        updateWithPrinterCapabilities({
          disableColorOption: false,
          setColorAsDefault: false,
          disableCopiesOption: false,
          disableLandscapeOption: false,
          printerDefaultDuplexValue: copiesSettings.UNKNOWN_DUPLEX_MODE,
        });
      }));
  updateControlsWithSelectedPrinterCapabilities();
  expectEquals(copiesSettings.duplexMode, copiesSettings.UNKNOWN_DUPLEX_MODE);
  expectEquals(copiesSettings.twoSidedOption_.hidden, true);

  this.mockHandler.expects(once()).getPrinterCapabilities('FooDevice').
      will(callFunction(function() {
        updateWithPrinterCapabilities({
          disableColorOption: false,
          setColorAsDefault: false,
          disableCopiesOption: false,
          disableLandscapeOption: false,
          printerDefaultDuplexValue: copiesSettings.SIMPLEX,
        });
      }));
  updateControlsWithSelectedPrinterCapabilities();
  expectEquals(copiesSettings.twoSidedOption_.hidden, false);
  expectEquals(copiesSettings.duplexMode, copiesSettings.SIMPLEX);
  copiesSettings.twoSidedCheckbox.checked = true;
  expectEquals(copiesSettings.duplexMode, copiesSettings.LONG_EDGE);
});

// Test that changing the selected printer updates the preview.
TEST_F('PrintPreviewWebUITest', 'TestPrinterChangeUpdatesPreview', function() {
  var savedArgs = new SaveMockArguments();
  this.mockHandler.expects(once()).getPreview(savedArgs.match(ANYTHING)).
      will(callFunctionWithSavedArgs(savedArgs, function(args) {
        updatePrintPreview(2, JSON.parse(args[0]).requestID);
      }));

  this.mockGlobals.expects(once()).updateWithPrinterCapabilities(
      savedArgs.match(ANYTHING)).
          will(callGlobalWithSavedArgs(
              savedArgs, 'updateWithPrinterCapabilities'));

  var printerList = $('printer-list');
  assertNotEquals(null, printerList, 'printerList');
  assertGE(printerList.options.length, printerListMinLength);
  expectEquals(fooIndex, printerList.selectedIndex,
               'fooIndex=' + fooIndex);
  var oldLastPreviewRequestID = lastPreviewRequestID;
  ++printerList.selectedIndex;
  updateControlsWithSelectedPrinterCapabilities();
  expectNotEquals(oldLastPreviewRequestID, lastPreviewRequestID);
});

/**
 * Test fixture to test case when no PDF plugin exists.
 * @extends {PrintPreviewWebUITest}
 * @constructor
 */
function PrintPreviewNoPDFWebUITest() {}

PrintPreviewNoPDFWebUITest.prototype = {
  __proto__: PrintPreviewWebUITest.prototype,

  /**
   * Provide a typedef for C++ to correspond to JS subclass.
   * @type {?string}
   * @override
   */
  typedefCppFixture: 'PrintPreviewWebUITest',

  /**
   * Always return false to simulate failure and check expected error condition.
   * @return {boolean} Always false.
   * @override
   */
  checkCompatiblePluginExists: function() {
    return false;
  },
};

// Test that error message is displayed when plugin doesn't exist.
TEST_F('PrintPreviewNoPDFWebUITest', 'TestErrorMessage', function() {
  var errorButton = $('error-button');
  assertNotEquals(null, errorButton);
  expectFalse(errorButton.disabled);
  var errorText = $('error-text');
  assertNotEquals(null, errorText);
  expectFalse(errorText.classList.contains('hidden'));
});