summaryrefslogtreecommitdiffstats
path: root/ui/file_manager/integration_tests/file_manager/background.js
blob: 8448bd8374d74f235ba074287badb19dee43c7dc (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
// Copyright 2014 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.

'use strict';

/**
 * Extension ID of Files.app.
 * @type {string}
 * @const
 */
var FILE_MANAGER_EXTENSIONS_ID = 'hhaomjibdihmijegdhdafkllkbggdgoj';

var remoteCall = new RemoteCallFilesApp(FILE_MANAGER_EXTENSIONS_ID);

/**
 * Extension ID of Gallery.
 * @type {string}
 * @const
 */
var GALLERY_APP_ID = 'nlkncpkkdoccmpiclbokaimcnedabhhm';

var galleryApp = new RemoteCallGallery(GALLERY_APP_ID);

/**
 * Extension ID of Audio Player.
 * @type {string}
 * @const
 */
var AUDIO_PLAYER_APP_ID = 'cjbfomnbifhcdnihkgipgfcihmgjfhbf';

var audioPlayerApp = new RemoteCall(AUDIO_PLAYER_APP_ID);

/**
 * App ID of Video Player.
 * @type {string}
 * @const
 */
var VIDEO_PLAYER_APP_ID = 'jcgeabjmjgoblfofpppfkcoakmfobdko';

var videoPlayerApp = new RemoteCall(VIDEO_PLAYER_APP_ID);

/**
 * Adds check of chrome.test to the end of the given promise.
 * @param {Promise} promise Promise.
 */
function testPromise(promise) {
  promise.then(function() {
    return new Promise(checkIfNoErrorsOccured);
  }).then(chrome.test.callbackPass(function() {
    // The callbacPass is necessary to avoid prematurely finishing tests.
    // Don't put chrome.test.succeed() here to avoid doubled success log.
  }), function(error) {
    chrome.test.fail(error.stack || error);
  });
};

/**
 * Executes a sequence of test steps.
 * @constructor
 */
function StepsRunner() {
  /**
   * List of steps.
   * @type {Array<function>}
   * @private
   */
  this.steps_ = [];
}

/**
 * Creates a StepsRunner instance and runs the passed steps.
 * @param {!Array<function>} steps
 */
StepsRunner.run = function(steps) {
  var stepsRunner = new StepsRunner();
  stepsRunner.run_(steps);
};

/**
 * Creates a StepsRunner instance and runs multiple groups of steps.
 * @param {!Array<!Array<function>>} groups
 */
StepsRunner.runGroups = function(groups) {
  // Squash all groups into a flat list of steps.
  StepsRunner.run(Array.prototype.concat.apply([], groups));
};

StepsRunner.prototype = {
  /**
   * @return {function} The next closure.
   */
  get next() {
    return this.steps_[0];
  }
};

/**
 * Runs a sequence of the added test steps.
 * @type {Array<function>} List of the sequential steps.
 */
StepsRunner.prototype.run_ = function(steps) {
  this.steps_ = steps.slice(0);

  // An extra step which acts as an empty callback for optional asynchronous
  // calls in the last provided step.
  this.steps_.push(function() {});

  this.steps_ = this.steps_.map(function(f) {
    return chrome.test.callbackPass(function() {
      this.steps_.shift();
      f.apply(this, arguments);
    }.bind(this));
  }.bind(this));

  this.next();
};

/**
 * Basic entry set for the local volume.
 * @type {Array<TestEntryInfo>}
 * @const
 */
var BASIC_LOCAL_ENTRY_SET = [
  ENTRIES.hello,
  ENTRIES.world,
  ENTRIES.desktop,
  ENTRIES.beautiful,
  ENTRIES.photos
];

/**
 * Basic entry set for the drive volume.
 *
 * TODO(hirono): Add a case for an entry cached by FileCache. For testing
 *               Drive, create more entries with Drive specific attributes.
 *
 * @type {Array<TestEntryInfo>}
 * @const
 */
var BASIC_DRIVE_ENTRY_SET = [
  ENTRIES.hello,
  ENTRIES.world,
  ENTRIES.desktop,
  ENTRIES.beautiful,
  ENTRIES.photos,
  ENTRIES.unsupported,
  ENTRIES.testDocument,
  ENTRIES.testSharedDocument
];

var NESTED_ENTRY_SET = [
  ENTRIES.directoryA,
  ENTRIES.directoryB,
  ENTRIES.directoryC
];

/**
 * Expecetd list of preset entries in fake test volumes. This should be in sync
 * with FakeTestVolume::PrepareTestEntries in the test harness.
 *
 * @type {Array<TestEntryInfo>}
 * @const
 */
var BASIC_FAKE_ENTRY_SET = [
  ENTRIES.hello,
  ENTRIES.directoryA
];

/**
 * Expected files shown in "Recent". Directories (e.g. 'photos') are not in this
 * list as they are not expected in "Recent".
 *
 * @type {Array<TestEntryInfo>}
 * @const
 */
var RECENT_ENTRY_SET = [
  ENTRIES.hello,
  ENTRIES.world,
  ENTRIES.desktop,
  ENTRIES.beautiful,
  ENTRIES.unsupported,
  ENTRIES.testDocument,
  ENTRIES.testSharedDocument
];

/**
 * Expected files shown in "Offline", which should have the files
 * "available offline". Google Documents, Google Spreadsheets, and the files
 * cached locally are "available offline".
 *
 * @type {Array<TestEntryInfo>}
 * @const
 */
var OFFLINE_ENTRY_SET = [
  ENTRIES.testDocument,
  ENTRIES.testSharedDocument
];

/**
 * Expected files shown in "Shared with me", which should be the entries labeled
 * with "shared-with-me".
 *
 * @type {Array<TestEntryInfo>}
 * @const
 */
var SHARED_WITH_ME_ENTRY_SET = [
  ENTRIES.testSharedDocument
];

/**
 * Opens a Files.app's main window.
 *
 * TODO(mtomasz): Pass a volumeId or an enum value instead of full paths.
 *
 * @param {Object} appState App state to be passed with on opening Files.app.
 *     Can be null.
 * @param {?string} initialRoot Root path to be used as a default current
 *     directory during initialization. Can be null, for no default path.
 * @param {function(string)=} opt_callback Callback with the app id.
 * @return {Promise} Promise to be fulfilled after window creating.
 */
function openNewWindow(appState, initialRoot, opt_callback) {
  // TODO(mtomasz): Migrate from full paths to a pair of a volumeId and a
  // relative path. To compose the URL communicate via messages with
  // file_manager_browser_test.cc.
  var processedAppState = appState || {};
  if (initialRoot) {
    processedAppState.currentDirectoryURL =
        'filesystem:chrome-extension://' + FILE_MANAGER_EXTENSIONS_ID +
        '/external' + initialRoot;
  }

  return remoteCall.callRemoteTestUtil('openMainWindow',
                                       null,
                                       [processedAppState],
                                       opt_callback);
}

/**
 * Opens a file dialog and waits for closing it.
 *
 * @param {Object} dialogParams Dialog parameters to be passed to chrome.
 *     fileSystem.chooseEntry() API.
 * @param {string} volumeName Volume name passed to the selectVolume remote
 *     funciton.
 * @param {Array<TestEntryInfo>} expectedSet Expected set of the entries.
 * @param {function(windowId:string):Promise} closeDialog Function to close the
 *     dialog.
 * @return {Promise} Promise to be fulfilled with the result entry of the
 *     dialog.
 */
function openAndWaitForClosingDialog(
    dialogParams, volumeName, expectedSet, closeDialog) {
  var resultPromise = new Promise(function(fulfill) {
    chrome.fileSystem.chooseEntry(
        dialogParams,
        function(entry) { fulfill(entry); });
    chrome.test.assertTrue(!chrome.runtime.lastError, 'chooseEntry failed.');
  });

  return remoteCall.waitForWindow('dialog#').then(function(windowId) {
    return remoteCall.waitForElement(windowId, '#file-list').
        then(function() {
          // Wait for initialization of Files.app.
          return remoteCall.waitForFiles(
              windowId, TestEntryInfo.getExpectedRows(BASIC_LOCAL_ENTRY_SET));
        }).
        then(function() {
          return remoteCall.callRemoteTestUtil(
              'selectVolume', windowId, [volumeName]);
        }).
        then(function() {
          var expectedRows = TestEntryInfo.getExpectedRows(expectedSet);
          return remoteCall.waitForFiles(windowId, expectedRows);
        }).
        then(closeDialog.bind(null, windowId)).
        then(function() {
          return repeatUntil(function() {
            return remoteCall.callRemoteTestUtil('getWindows', null, []).
                then(function(windows) {
                  if (windows[windowId])
                    return pending('Window %s does not hide.', windowId);
                  else
                    return resultPromise;
                });
          });
        });
  });
}

/**
 * Opens a Files.app's main window and waits until it is initialized. Fills
 * the window with initial files. Should be called for the first window only.
 *
 * TODO(hirono): Add parameters to specify the entry set to be prepared.
 * TODO(mtomasz): Pass a volumeId or an enum value instead of full paths.
 *
 * @param {Object} appState App state to be passed with on opening Files.app.
 *     Can be null.
 * @param {?string} initialRoot Root path to be used as a default current
 *     directory during initialization. Can be null, for no default path.
 * @param {function(string, Array<Array<string>>)=} opt_callback Callback with
 *     the window ID and with the file list.
 * @return {Promise} Promise to be fulfilled with window ID.
 */
function setupAndWaitUntilReady(appState, initialRoot, opt_callback) {
  var windowPromise = openNewWindow(appState, initialRoot);
  var localEntriesPromise = addEntries(['local'], BASIC_LOCAL_ENTRY_SET);
  var driveEntriesPromise = addEntries(['drive'], BASIC_DRIVE_ENTRY_SET);
  var detailedTablePromise = windowPromise.then(function(windowId) {
    return remoteCall.waitForElement(windowId, '#detail-table').
      then(function() {
        // Wait until the elements are loaded in the table.
        return remoteCall.waitForFileListChange(windowId, 0);
      });
  });

  if (opt_callback)
    opt_callback = chrome.test.callbackPass(opt_callback);

  return Promise.all([
    windowPromise,
    localEntriesPromise,
    driveEntriesPromise,
    detailedTablePromise
  ]).then(function(results) {
    if (opt_callback)
      opt_callback(results[0], results[3]);
    return results[0];
  }).catch(function(e) {
    chrome.test.fail(e.stack || e);
  });
}

/**
 * Verifies if there are no Javascript errors in any of the app windows.
 * @param {function()} Completion callback.
 */
function checkIfNoErrorsOccured(callback) {
  remoteCall.callRemoteTestUtil('getErrorCount', null, [], function(count) {
    chrome.test.assertEq(0, count, 'The error count is not 0.');
    callback();
  });
}

/**
 * Returns the name of the given file list entry.
 * @param {Array<string>} file An entry in a file list.
 * @return {string} Name of the file.
 */
function getFileName(fileListEntry) {
  return fileListEntry[0];
}

/**
 * Returns the size of the given file list entry.
 * @param {Array<string>} An entry in a file list.
 * @return {string} Size of the file.
 */
function getFileSize(fileListEntry) {
  return fileListEntry[1];
}

/**
 * Returns the type of the given file list entry.
 * @param {Array<string>} An entry in a file list.
 * @return {string} Type of the file.
 */
function getFileType(fileListEntry) {
  return fileListEntry[2];
}

/**
 * Namespace for test cases.
 */
var testcase = {};

// Ensure the test cases are loaded.
window.addEventListener('load', function() {
  var steps = [
    // Check for the guest mode.
    function() {
      chrome.test.sendMessage(
          JSON.stringify({name: 'isInGuestMode'}), steps.shift());
    },
    // Obtain the test case name.
    function(result) {
      if (JSON.parse(result) != chrome.extension.inIncognitoContext)
        return;
      chrome.test.sendMessage(
          JSON.stringify({name: 'getRootPaths'}), steps.shift());
    },
    // Obtain the root entry paths.
    function(result) {
      var roots = JSON.parse(result);
      RootPath.DOWNLOADS = roots.downloads;
      RootPath.DRIVE = roots.drive;
      chrome.test.sendMessage(
          JSON.stringify({name: 'getTestName'}), steps.shift());
    },
    // Run the test case.
    function(testCaseName) {
      var targetTest = testcase[testCaseName];
      if (!targetTest) {
        chrome.test.fail(testCaseName + ' is not found.');
        return;
      }
      // Specify the name of test to the test system.
      targetTest.generatedName = testCaseName;
      chrome.test.runTests([targetTest]);
    }
  ];
  steps.shift()();
});