Commit 5e01981e authored by Noel Gordon's avatar Noel Gordon Committed by Commit Bot

Closure compile media_import_handler_unittest

 - remove media_inport_handler_unittest.html
 - add BUILD rules to auto-generate and compile this unittest
 - define mockChrome, install it during the unittest
 - remove unused unittest vars and JS auto-format
 - document test fixtures and test helpers
 - fix Closure compile errors (there were lots).

No change in test behavior, no new tests.

Bug: 907970
Change-Id: Id90b4b1eaf84764521fb0d77aa2c29ff56db7c07
Reviewed-on: https://chromium-review.googlesource.com/c/1356728
Commit-Queue: Noel Gordon <noel@chromium.org>
Reviewed-by: default avatarLuciano Pacheco <lucmult@chromium.org>
Cr-Commit-Position: refs/heads/master@{#612997}
parent d1df6533
...@@ -75,8 +75,7 @@ IN_PROC_BROWSER_TEST_F(FileManagerJsTest, LRUCacheTest) { ...@@ -75,8 +75,7 @@ IN_PROC_BROWSER_TEST_F(FileManagerJsTest, LRUCacheTest) {
} }
IN_PROC_BROWSER_TEST_F(FileManagerJsTest, MediaImportHandlerTest) { IN_PROC_BROWSER_TEST_F(FileManagerJsTest, MediaImportHandlerTest) {
RunTest(base::FilePath( RunGeneratedTest("/background/js/media_import_handler_unittest.html");
FILE_PATH_LITERAL("background/js/media_import_handler_unittest.html")));
} }
IN_PROC_BROWSER_TEST_F(FileManagerJsTest, TaskQueueTest) { IN_PROC_BROWSER_TEST_F(FileManagerJsTest, TaskQueueTest) {
......
...@@ -334,6 +334,22 @@ js_library("media_import_handler") { ...@@ -334,6 +334,22 @@ js_library("media_import_handler") {
"../../common/js:importer_common", "../../common/js:importer_common",
"../../common/js:metrics", "../../common/js:metrics",
] ]
externs_list = [ "//ui/file_manager/externs/background/import_runner.js" ]
}
js_unittest("media_import_handler_unittest") {
deps = [
":media_import_handler",
":mock_drive_sync_handler",
":mock_media_scanner",
":mock_progress_center",
":mock_volume_manager",
":test_import_history",
"//ui/file_manager/base/js:mock_chrome",
"//ui/file_manager/base/js:test_error_reporting",
"//ui/file_manager/file_manager/common/js:mock_entry",
"//ui/file_manager/file_manager/common/js:test_importer_common",
]
} }
js_library("mock_media_scanner") { js_library("mock_media_scanner") {
...@@ -499,6 +515,7 @@ js_unit_tests("unit_tests") { ...@@ -499,6 +515,7 @@ js_unit_tests("unit_tests") {
":file_operation_handler_unittest", ":file_operation_handler_unittest",
":file_operation_manager_unittest", ":file_operation_manager_unittest",
":import_history_unittest", ":import_history_unittest",
":media_import_handler_unittest",
":media_scanner_unittest", ":media_scanner_unittest",
":task_queue_unittest", ":task_queue_unittest",
":volume_manager_unittest", ":volume_manager_unittest",
......
<!DOCTYPE html>
<!-- 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.
-->
<html>
<body>
<script src="../../../../../ui/webui/resources/js/cr.js"></script>
<script src="../../../../../ui/webui/resources/js/assert.js"></script>
<script src="../../../../../ui/webui/resources/js/cr/event_target.js"></script>
<script src="../../../../../ui/webui/resources/js/cr/ui/array_data_model.js"></script>
<script src="../../../../../ui/webui/resources/js/load_time_data.js"></script>
<script src="../../common/js/async_util.js"></script>
<script src="../../common/js/metrics_base.js"></script>
<script src="../../common/js/mock_entry.js"></script>
<script src="../../../base/js/test_error_reporting.js"></script>
<script src="../../../base/js/mock_chrome.js"></script>
<script src="../../common/js/unittest_util.js"></script>
<script src="../../common/js/files_app_entry_types.js"></script>
<script src="../../common/js/util.js"></script>
<script src="../../../base/js/volume_manager_types.js"></script>
<script src="../../common/js/importer_common.js"></script>
<script src="../../common/js/test_importer_common.js"></script>
<script src="../../common/js/progress_center_common.js"></script>
<script src="drive_sync_handler.js"></script>
<script src="entry_location_impl.js"></script>
<script src="test_import_history.js"></script>
<script src="mock_drive_sync_handler.js"></script>
<script src="mock_progress_center.js"></script>
<script src="mock_media_scanner.js"></script>
<script src="task_queue.js"></script>
<script src="media_import_handler.js"></script>
<script src="duplicate_finder.js"></script>
<script src="volume_info_impl.js"></script>
<script src="volume_info_list_impl.js"></script>
<script src="volume_manager_factory.js"></script>
<script src="volume_manager_impl.js"></script>
<script src="volume_manager_util.js"></script>
<script src="mock_volume_manager.js"></script>
<script src="file_operation_util.js"></script>
<script src="media_import_handler_unittest.js"></script>
</body>
</html>
...@@ -2,11 +2,10 @@ ...@@ -2,11 +2,10 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
/** @type {!MockFileOperationManager} */ 'use strict';
var progressCenter;
/** @type {!TestMediaScanner} */ /** @type {!MockProgressCenter} */
var mediaScanner; var progressCenter;
/** @type {!importer.MediaImportHandler} */ /** @type {!importer.MediaImportHandler} */
var mediaImporter; var mediaImporter;
...@@ -14,12 +13,9 @@ var mediaImporter; ...@@ -14,12 +13,9 @@ var mediaImporter;
/** @type {!importer.TestImportHistory} */ /** @type {!importer.TestImportHistory} */
var importHistory; var importHistory;
/** @param {!importer.DispositionChecker.CheckerFunction} */ /** @type {!importer.DispositionChecker.CheckerFunction} */
var dispositionChecker; var dispositionChecker;
/** @type {!VolumeInfo} */
var drive;
/** @type {!MockCopyTo} */ /** @type {!MockCopyTo} */
var mockCopier; var mockCopier;
...@@ -32,8 +28,10 @@ var destinationFactory; ...@@ -32,8 +28,10 @@ var destinationFactory;
/** @type {!MockDriveSyncHandler} */ /** @type {!MockDriveSyncHandler} */
var driveSyncHandler; var driveSyncHandler;
var chrome; /**
* Mock metrics.
* @type {!Object}
*/
window.metrics = { window.metrics = {
recordSmallCount: function() {}, recordSmallCount: function() {},
recordUserAction: function() {}, recordUserAction: function() {},
...@@ -41,63 +39,75 @@ window.metrics = { ...@@ -41,63 +39,75 @@ window.metrics = {
recordBoolean: function() {}, recordBoolean: function() {},
}; };
/**
* Mock Chrome APIs
* @type {!Object}
*/
var mockChrome;
// Set up the test components.
function setUp() { function setUp() {
// Mock loadTimeData strings.
window.loadTimeData.getString = id => id; window.loadTimeData.getString = id => id;
// Set up mock chrome APIs.
chrome = { // Setup mock chrome APIs.
mockChrome = {
power: { power: {
requestKeepAwakeWasCalled: false, requestKeepAwakeWasCalled: false,
requestKeepAwakeStatus: false, requestKeepAwakeStatus: false,
requestKeepAwake: function() { requestKeepAwake: function() {
chrome.power.requestKeepAwakeWasCalled = true; mockChrome.power.requestKeepAwakeWasCalled = true;
chrome.power.requestKeepAwakeStatus = true; mockChrome.power.requestKeepAwakeStatus = true;
}, },
releaseKeepAwake: function() { releaseKeepAwake: function() {
chrome.power.requestKeepAwakeStatus = false; mockChrome.power.requestKeepAwakeStatus = false;
} }
}, },
fileManagerPrivate: { fileManagerPrivate: {
setEntryTag: function() {} setEntryTag: function() {},
} },
}; };
new MockCommandLinePrivate();
importer.setupTestLogger();
progressCenter = new MockProgressCenter(); installMockChrome(mockChrome);
new MockCommandLinePrivate();
// Replaces fileOperationUtil.copyTo with test function. // Replace fileOperationUtil.copyTo with mock test function.
mockCopier = new MockCopyTo(); mockCopier = new MockCopyTo();
// Create and install MockVolumeManager.
var volumeManager = new MockVolumeManager(); var volumeManager = new MockVolumeManager();
drive = volumeManager.getCurrentProfileVolumeInfo(
VolumeManagerCommon.VolumeType.DRIVE);
// Create fake parented and non-parented roots.
drive.fileSystem.populate([
'/root/',
'/other/'
]);
MockVolumeManager.installMockSingleton(volumeManager); MockVolumeManager.installMockSingleton(volumeManager);
importHistory = new importer.TestImportHistory(); // Add fake parented and non-parented roots: /root/ and /other/.
var driveVolumeType = VolumeManagerCommon.VolumeType.DRIVE;
var driveVolumeInfo = /** @type {!VolumeInfo} */
(volumeManager.getCurrentProfileVolumeInfo(driveVolumeType));
var driveFileSystem =
/** @type {!MockFileSystem} */ (driveVolumeInfo.fileSystem);
driveFileSystem.populate(['/root/', '/other/']);
// This is the default disposition checker used by mediaImporter. // Setup a default disposition checker. Tests can replace it at runtime
// Tests can replace this at runtime if they want specialized behaviors. // if they need specialized disposition check behavior.
dispositionChecker = function() { dispositionChecker = function() {
return Promise.resolve(importer.Disposition.ORIGINAL); return Promise.resolve(importer.Disposition.ORIGINAL);
}; };
mediaScanner = new TestMediaScanner(); // Setup MediaImporter.
destinationFileSystem = new MockFileSystem('googleDriveFilesystem'); progressCenter = new MockProgressCenter();
destinationFactory = Promise.resolve(destinationFileSystem.root); importHistory = new importer.TestImportHistory();
driveSyncHandler = new MockDriveSyncHandler(); driveSyncHandler = new MockDriveSyncHandler();
importer.setupTestLogger();
mediaImporter = new importer.MediaImportHandler( mediaImporter = new importer.MediaImportHandler(
progressCenter, importHistory, function(entry, destination) { progressCenter, importHistory, dispositionChecker, driveSyncHandler);
return dispositionChecker(entry, destination);
}, driveSyncHandler); // Setup the copy destination.
destinationFileSystem = new MockFileSystem('googleDriveFilesystem');
destinationFactory = Promise.resolve(destinationFileSystem.root);
} }
/**
* Tests media imports.
*/
function testImportMedia(callback) { function testImportMedia(callback) {
var media = setupFileSystem([ var media = setupFileSystem([
'/DCIM/photos0/IMG00001.jpg', '/DCIM/photos0/IMG00001.jpg',
...@@ -113,36 +123,40 @@ function testImportMedia(callback) { ...@@ -113,36 +123,40 @@ function testImportMedia(callback) {
scanResult, scanResult,
importer.Destination.GOOGLE_DRIVE, importer.Destination.GOOGLE_DRIVE,
destinationFactory); destinationFactory);
var whenImportDone = new Promise(
function(resolve, reject) { var whenImportDone = new Promise(function(resolve, reject) {
importTask.addObserver( importTask.addObserver(
/** /**
* @param {!importer.TaskQueue.UpdateType} updateType * @param {!importer.TaskQueue.UpdateType} updateType
* @param {!importer.TaskQueue.Task} task * @param {Object=} opt_task
*/ */
function(updateType, task) { function(updateType, opt_task) {
switch (updateType) { switch (updateType) {
case importer.TaskQueue.UpdateType.COMPLETE: case importer.TaskQueue.UpdateType.COMPLETE:
resolve(); resolve();
break; break;
case importer.TaskQueue.UpdateType.ERROR: case importer.TaskQueue.UpdateType.ERROR:
reject(new Error(importer.TaskQueue.UpdateType.ERROR)); reject(new Error(importer.TaskQueue.UpdateType.ERROR));
break; break;
} }
}); });
}); });
reportPromise( reportPromise(
whenImportDone.then( whenImportDone.then(function() {
function() { var mockDirectoryEntry =
var copiedEntries = destinationFileSystem.root.getAllChildren(); /** @type {!MockDirectoryEntry} */ (destinationFileSystem.root);
assertEquals(media.length, copiedEntries.length); var copiedEntries = mockDirectoryEntry.getAllChildren();
}), assertEquals(media.length, copiedEntries.length);
}),
callback); callback);
scanResult.finalize(); scanResult.finalize();
} }
/**
* Tests media import duplicate detection.
*/
function testImportMedia_skipAndMarkDuplicatedFiles(callback) { function testImportMedia_skipAndMarkDuplicatedFiles(callback) {
var DUPLICATED_FILE_PATH_1 = '/DCIM/photos0/duplicated_1.jpg'; var DUPLICATED_FILE_PATH_1 = '/DCIM/photos0/duplicated_1.jpg';
var DUPLICATED_FILE_PATH_2 = '/DCIM/photos0/duplicated_2.jpg'; var DUPLICATED_FILE_PATH_2 = '/DCIM/photos0/duplicated_2.jpg';
...@@ -171,46 +185,51 @@ function testImportMedia_skipAndMarkDuplicatedFiles(callback) { ...@@ -171,46 +185,51 @@ function testImportMedia_skipAndMarkDuplicatedFiles(callback) {
scanResult, scanResult,
importer.Destination.GOOGLE_DRIVE, importer.Destination.GOOGLE_DRIVE,
destinationFactory); destinationFactory);
var whenImportDone = new Promise(
function(resolve, reject) { var whenImportDone = new Promise(function(resolve, reject) {
importTask.addObserver( importTask.addObserver(
/** /**
* @param {!importer.TaskQueue.UpdateType} updateType * @param {!importer.TaskQueue.UpdateType} updateType
* @param {!importer.TaskQueue.Task} task * @param {Object=} opt_task
*/ */
function(updateType, task) { function(updateType, opt_task) {
switch (updateType) { switch (updateType) {
case importer.TaskQueue.UpdateType.COMPLETE: case importer.TaskQueue.UpdateType.COMPLETE:
resolve(); resolve();
break; break;
case importer.TaskQueue.UpdateType.ERROR: case importer.TaskQueue.UpdateType.ERROR:
reject(new Error(importer.TaskQueue.UpdateType.ERROR)); reject(new Error(importer.TaskQueue.UpdateType.ERROR));
break; break;
} }
}); });
}); });
reportPromise( reportPromise(
whenImportDone.then( whenImportDone.then(
function() { function() {
// Only the new file should be copied. // Only the new file should be copied.
var copiedEntries = destinationFileSystem.root.getAllChildren(); var mockDirectoryEntry =
/** @type {!MockDirectoryEntry} */ (destinationFileSystem.root);
var copiedEntries = mockDirectoryEntry.getAllChildren();
assertEquals(1, copiedEntries.length); assertEquals(1, copiedEntries.length);
assertEquals(ORIGINAL_FILE_DEST_PATH, copiedEntries[0].fullPath); assertEquals(ORIGINAL_FILE_DEST_PATH, copiedEntries[0].fullPath);
importHistory.assertCopied(media[1], var mockFileEntry = /** @type {!MockFileEntry} */ (media[1]);
importer.Destination.GOOGLE_DRIVE); importHistory.assertCopied(
mockFileEntry, importer.Destination.GOOGLE_DRIVE);
// The 2 duplicated files should be marked as imported. // The 2 duplicated files should be marked as imported.
[media[0], media[2]].forEach( [media[0], media[2]].forEach(function(entry) {
/** @param {!FileEntry} entry */ entry = /** @type {!MockFileEntry} */ (entry);
function(entry) { importHistory.assertImported(
importHistory.assertImported( entry, importer.Destination.GOOGLE_DRIVE);
entry, importer.Destination.GOOGLE_DRIVE); });
});
}), callback); }), callback);
scanResult.finalize(); scanResult.finalize();
} }
/**
* Tests media import uses encoded URLs.
*/
function testImportMedia_EmploysEncodedUrls(callback) { function testImportMedia_EmploysEncodedUrls(callback) {
var media = setupFileSystem([ var media = setupFileSystem([
'/DCIM/photos0/Mom and Dad.jpg', '/DCIM/photos0/Mom and Dad.jpg',
...@@ -222,40 +241,41 @@ function testImportMedia_EmploysEncodedUrls(callback) { ...@@ -222,40 +241,41 @@ function testImportMedia_EmploysEncodedUrls(callback) {
importer.Destination.GOOGLE_DRIVE, importer.Destination.GOOGLE_DRIVE,
destinationFactory); destinationFactory);
var promise = new Promise( var promise =
function(resolve, reject) { new Promise(function(resolve, reject) {
importTask.addObserver( importTask.addObserver(
/** /**
* @param {!importer.TaskQueue.UpdateType} updateType * @param {!importer.TaskQueue.UpdateType} updateType
* @param {!importer.TaskQueue.Task} task * @param {Object=} opt_task
*/ */
function(updateType, task) { function(updateType, opt_task) {
switch (updateType) { switch (updateType) {
case importer.TaskQueue.UpdateType.COMPLETE: case importer.TaskQueue.UpdateType.COMPLETE:
resolve(destinationFileSystem.root.getAllChildren()); resolve(/** @type {!MockDirectoryEntry} */
(destinationFileSystem.root).getAllChildren());
break; break;
case importer.TaskQueue.UpdateType.ERROR: case importer.TaskQueue.UpdateType.ERROR:
reject('Task failed :('); reject('Task failed :(');
break; break;
} }
}); });
}) }).then(function(copiedEntries) {
.then( var expected = 'Mom%20and%20Dad.jpg';
function(copiedEntries) { var url = copiedEntries[0].toURL();
var expected = 'Mom%20and%20Dad.jpg'; assertTrue(url.length > expected.length);
var url = copiedEntries[0].toURL(); var actual = url.substring(url.length - expected.length);
assertTrue(url.length > expected.length); assertEquals(expected, actual);
var actual = url.substring(url.length - expected.length); });
assertEquals(expected, actual);
});
reportPromise(promise, callback); reportPromise(promise, callback);
scanResult.finalize(); scanResult.finalize();
} }
// Verifies that when files with duplicate names are imported, that they don't /**
// overwrite one another. * Tests that when files with duplicate names are imported, that they don't
* overwrite one another.
*/
function testImportMediaWithDuplicateFilenames(callback) { function testImportMediaWithDuplicateFilenames(callback) {
var media = setupFileSystem([ var media = setupFileSystem([
'/DCIM/photos0/IMG00001.jpg', '/DCIM/photos0/IMG00001.jpg',
...@@ -271,37 +291,41 @@ function testImportMediaWithDuplicateFilenames(callback) { ...@@ -271,37 +291,41 @@ function testImportMediaWithDuplicateFilenames(callback) {
scanResult, scanResult,
importer.Destination.GOOGLE_DRIVE, importer.Destination.GOOGLE_DRIVE,
destinationFactory); destinationFactory);
var whenImportDone = new Promise(
function(resolve, reject) { var whenImportDone = new Promise(function(resolve, reject) {
importTask.addObserver( importTask.addObserver(
/** /**
* @param {!importer.TaskQueue.UpdateType} updateType * @param {!importer.TaskQueue.UpdateType} updateType
* @param {!importer.TaskQueue.Task} task * @param {Object=} opt_task
*/ */
function(updateType, task) { function(updateType, opt_task) {
switch (updateType) { switch (updateType) {
case importer.TaskQueue.UpdateType.COMPLETE: case importer.TaskQueue.UpdateType.COMPLETE:
resolve(); resolve();
break; break;
case importer.TaskQueue.UpdateType.ERROR: case importer.TaskQueue.UpdateType.ERROR:
reject(new Error(importer.TaskQueue.UpdateType.ERROR)); reject(new Error(importer.TaskQueue.UpdateType.ERROR));
break; break;
} }
}); });
}); });
// Verify that we end up with 6, and not 3, destination entries. // Verify that we end up with 6, and not 3, destination entries.
reportPromise( reportPromise(
whenImportDone.then( whenImportDone.then(function() {
function() { var mockDirectoryEntry =
var copiedEntries = destinationFileSystem.root.getAllChildren(); /** @type {!MockDirectoryEntry} */ (destinationFileSystem.root);
assertEquals(media.length, copiedEntries.length); var copiedEntries = mockDirectoryEntry.getAllChildren();
}), assertEquals(media.length, copiedEntries.length);
}),
callback); callback);
scanResult.finalize(); scanResult.finalize();
} }
/**
* Tests that active media imports keep chrome.power awake.
*/
function testKeepAwakeDuringImport(callback) { function testKeepAwakeDuringImport(callback) {
var media = setupFileSystem([ var media = setupFileSystem([
'/DCIM/photos0/IMG00001.jpg', '/DCIM/photos0/IMG00001.jpg',
...@@ -317,40 +341,44 @@ function testKeepAwakeDuringImport(callback) { ...@@ -317,40 +341,44 @@ function testKeepAwakeDuringImport(callback) {
scanResult, scanResult,
importer.Destination.GOOGLE_DRIVE, importer.Destination.GOOGLE_DRIVE,
destinationFactory); destinationFactory);
var whenImportDone = new Promise(
function(resolve, reject) { var whenImportDone = new Promise(function(resolve, reject) {
importTask.addObserver( importTask.addObserver(
/** /**
* @param {!importer.TaskQueue.UpdateType} updateType * @param {!importer.TaskQueue.UpdateType} updateType
* @param {!importer.TaskQueue.Task} task * @param {Object=} opt_task
*/ */
function(updateType, task) { function(updateType, opt_task) {
// Assert that keepAwake is set while the task is active. // Assert that keepAwake is set while the task is active.
assertTrue(chrome.power.requestKeepAwakeStatus); assertTrue(mockChrome.power.requestKeepAwakeStatus);
switch (updateType) { switch (updateType) {
case importer.TaskQueue.UpdateType.COMPLETE: case importer.TaskQueue.UpdateType.COMPLETE:
resolve(); resolve();
break; break;
case importer.TaskQueue.UpdateType.ERROR: case importer.TaskQueue.UpdateType.ERROR:
reject(new Error(importer.TaskQueue.UpdateType.ERROR)); reject(new Error(importer.TaskQueue.UpdateType.ERROR));
break; break;
} }
}); });
}); });
reportPromise( reportPromise(
whenImportDone.then( whenImportDone.then(function() {
function() { assertTrue(mockChrome.power.requestKeepAwakeWasCalled);
assertTrue(chrome.power.requestKeepAwakeWasCalled); assertFalse(mockChrome.power.requestKeepAwakeStatus);
assertFalse(chrome.power.requestKeepAwakeStatus); var mockDirectoryEntry =
var copiedEntries = destinationFileSystem.root.getAllChildren(); /** @type {!MockDirectoryEntry} */ (destinationFileSystem.root);
assertEquals(media.length, copiedEntries.length); var copiedEntries = mockDirectoryEntry.getAllChildren();
}), assertEquals(media.length, copiedEntries.length);
}),
callback); callback);
scanResult.finalize(); scanResult.finalize();
} }
/**
* Tests that media imports update import history.
*/
function testUpdatesHistoryAfterImport(callback) { function testUpdatesHistoryAfterImport(callback) {
var entries = setupFileSystem([ var entries = setupFileSystem([
'/DCIM/photos0/IMG00001.jpg', '/DCIM/photos0/IMG00001.jpg',
...@@ -369,45 +397,46 @@ function testUpdatesHistoryAfterImport(callback) { ...@@ -369,45 +397,46 @@ function testUpdatesHistoryAfterImport(callback) {
importer.Destination.GOOGLE_DRIVE, importer.Destination.GOOGLE_DRIVE,
destinationFactory); destinationFactory);
var whenImportDone = new Promise( var whenImportDone = new Promise(function(resolve, reject) {
function(resolve, reject) { importTask.addObserver(
importTask.addObserver( /**
/** * @param {!importer.TaskQueue.UpdateType} updateType
* @param {!importer.TaskQueue.UpdateType} updateType * @param {Object=} opt_task
* @param {!importer.TaskQueue.Task} task */
*/ function(updateType, opt_task) {
function(updateType, task) { switch (updateType) {
switch (updateType) { case importer.TaskQueue.UpdateType.COMPLETE:
case importer.TaskQueue.UpdateType.COMPLETE: resolve();
resolve(); break;
break; case importer.TaskQueue.UpdateType.ERROR:
case importer.TaskQueue.UpdateType.ERROR: reject(new Error(importer.TaskQueue.UpdateType.ERROR));
reject(new Error(importer.TaskQueue.UpdateType.ERROR)); break;
break; }
} });
}); });
});
var promise = whenImportDone.then( var promise = whenImportDone.then(function() {
function() { mockCopier.copiedFiles.forEach(
mockCopier.copiedFiles.forEach( /** @param {!MockCopyTo.CopyInfo} copy */
/** @param {!MockCopyTo.CopyInfo} copy */ function(copy) {
function(copy) { var mockFileEntry = /** @type {!MockFileEntry} */ (copy.source);
importHistory.assertCopied( importHistory.assertCopied(
copy.source, importer.Destination.GOOGLE_DRIVE); mockFileEntry, importer.Destination.GOOGLE_DRIVE);
}); });
dupeFiles.forEach( dupeFiles.forEach(function(entry) {
/** @param {!FileEntry} entry */ var mockFileEntry = /** @type {!MockFileEntry} */ (entry);
function(entry) { importHistory.assertImported(
importHistory.assertImported( mockFileEntry, importer.Destination.GOOGLE_DRIVE);
entry, importer.Destination.GOOGLE_DRIVE); });
}); });
});
scanResult.finalize(); scanResult.finalize();
reportPromise(promise, callback); reportPromise(promise, callback);
} }
/**
* Tests that media imports tag entries after import.
*/
function testTagsEntriesAfterImport(callback) { function testTagsEntriesAfterImport(callback) {
var entries = setupFileSystem([ var entries = setupFileSystem([
'/DCIM/photos0/IMG00001.jpg', '/DCIM/photos0/IMG00001.jpg',
...@@ -419,28 +448,28 @@ function testTagsEntriesAfterImport(callback) { ...@@ -419,28 +448,28 @@ function testTagsEntriesAfterImport(callback) {
scanResult, scanResult,
importer.Destination.GOOGLE_DRIVE, importer.Destination.GOOGLE_DRIVE,
destinationFactory); destinationFactory);
var whenImportDone = new Promise(
function(resolve, reject) { var whenImportDone = new Promise(function(resolve, reject) {
importTask.addObserver( importTask.addObserver(
/** /**
* @param {!importer.TaskQueue.UpdateType} updateType * @param {!importer.TaskQueue.UpdateType} updateType
* @param {!importer.TaskQueue.Task} task * @param {Object=} opt_task
*/ */
function(updateType, task) { function(updateType, opt_task) {
switch (updateType) { switch (updateType) {
case importer.TaskQueue.UpdateType.COMPLETE: case importer.TaskQueue.UpdateType.COMPLETE:
resolve(); resolve();
break; break;
case importer.TaskQueue.UpdateType.ERROR: case importer.TaskQueue.UpdateType.ERROR:
reject(new Error(importer.TaskQueue.UpdateType.ERROR)); reject(new Error(importer.TaskQueue.UpdateType.ERROR));
break; break;
} }
}); });
}); });
var taggedEntries = []; var taggedEntries = [];
// Replace chrome.fileManagerPrivate.setEntryTag with a listener. // Replace chrome.fileManagerPrivate.setEntryTag with a listener.
chrome.fileManagerPrivate.setEntryTag = function(entry) { mockChrome.fileManagerPrivate.setEntryTag = function(entry) {
taggedEntries.push(entry); taggedEntries.push(entry);
}; };
...@@ -454,7 +483,9 @@ function testTagsEntriesAfterImport(callback) { ...@@ -454,7 +483,9 @@ function testTagsEntriesAfterImport(callback) {
scanResult.finalize(); scanResult.finalize();
} }
// Tests that cancelling an import works properly. /**
* Tests cancelling a media import.
*/
function testImportCancellation(callback) { function testImportCancellation(callback) {
var media = setupFileSystem([ var media = setupFileSystem([
'/DCIM/photos0/IMG00001.jpg', '/DCIM/photos0/IMG00001.jpg',
...@@ -473,19 +504,19 @@ function testImportCancellation(callback) { ...@@ -473,19 +504,19 @@ function testImportCancellation(callback) {
scanResult, scanResult,
importer.Destination.GOOGLE_DRIVE, importer.Destination.GOOGLE_DRIVE,
destinationFactory); destinationFactory);
var whenImportCancelled = new Promise(
function(resolve, reject) { var whenImportCancelled = new Promise(function(resolve, reject) {
importTask.addObserver( importTask.addObserver(
/** /**
* @param {!importer.TaskQueue.UpdateType} updateType * @param {!importer.TaskQueue.UpdateType} updateType
* @param {!importer.TaskQueue.Task} task * @param {Object=} opt_task
*/ */
function(updateType, task) { function(updateType, opt_task) {
if (updateType === importer.TaskQueue.UpdateType.CANCELED) { if (updateType === importer.TaskQueue.UpdateType.CANCELED) {
resolve(); resolve();
} }
}); });
}); });
// Simulate cancellation after the expected number of copies is done. // Simulate cancellation after the expected number of copies is done.
var copyCount = 0; var copyCount = 0;
...@@ -500,19 +531,22 @@ function testImportCancellation(callback) { ...@@ -500,19 +531,22 @@ function testImportCancellation(callback) {
}); });
reportPromise( reportPromise(
whenImportCancelled.then( whenImportCancelled.then(function() {
function() { var mockDirectoryEntry =
var copiedEntries = destinationFileSystem.root.getAllChildren(); /** @type {!MockDirectoryEntry} */ (destinationFileSystem.root);
assertEquals(EXPECTED_COPY_COUNT, copiedEntries.length); var copiedEntries = mockDirectoryEntry.getAllChildren();
}), assertEquals(EXPECTED_COPY_COUNT, copiedEntries.length);
}),
callback); callback);
scanResult.finalize(); scanResult.finalize();
} }
/**
* Tests media imports with errors.
*/
function testImportWithErrors(callback) { function testImportWithErrors(callback) {
// Quieten the logger just in this test, since we expect errors.
// Quiet the logger just in this test where we expect errors.
// Elsewhere, it's better for errors to be seen by test authors. // Elsewhere, it's better for errors to be seen by test authors.
importer.setupTestLogger().quiet(); importer.setupTestLogger().quiet();
...@@ -533,19 +567,19 @@ function testImportWithErrors(callback) { ...@@ -533,19 +567,19 @@ function testImportWithErrors(callback) {
scanResult, scanResult,
importer.Destination.GOOGLE_DRIVE, importer.Destination.GOOGLE_DRIVE,
destinationFactory); destinationFactory);
var whenImportDone = new Promise(
function(resolve, reject) { var whenImportDone = new Promise(function(resolve, reject) {
importTask.addObserver( importTask.addObserver(
/** /**
* @param {!importer.TaskQueue.UpdateType} updateType * @param {!importer.TaskQueue.UpdateType} updateType
* @param {!importer.TaskQueue.Task} task * @param {Object=} opt_task
*/ */
function(updateType, task) { function(updateType, opt_task) {
if (updateType === importer.TaskQueue.UpdateType.COMPLETE) { if (updateType === importer.TaskQueue.UpdateType.COMPLETE) {
resolve(); resolve();
} }
}); });
}); });
// Simulate an error after 3 imports. // Simulate an error after 3 imports.
var copyCount = 0; var copyCount = 0;
...@@ -561,42 +595,43 @@ function testImportWithErrors(callback) { ...@@ -561,42 +595,43 @@ function testImportWithErrors(callback) {
// Verify that the error didn't result in some files not being copied. // Verify that the error didn't result in some files not being copied.
reportPromise( reportPromise(
whenImportDone.then( whenImportDone.then(function() {
function() { var mockDirectoryEntry =
var copiedEntries = destinationFileSystem.root.getAllChildren(); /** @type {!MockDirectoryEntry} */ (destinationFileSystem.root);
assertEquals(EXPECTED_COPY_COUNT, copiedEntries.length); var copiedEntries = mockDirectoryEntry.getAllChildren();
}), assertEquals(EXPECTED_COPY_COUNT, copiedEntries.length);
}),
callback); callback);
scanResult.finalize(); scanResult.finalize();
} }
/** /**
* Setup a file system containing the given |fileNames| and return the file
* system's entries in an array.
*
* @param {!Array<string>} fileNames * @param {!Array<string>} fileNames
* @return {!Array<!Entry>} * @return {!Array<!Entry>}
*/ */
function setupFileSystem(fileNames) { function setupFileSystem(fileNames) {
// Set up a filesystem with some files. let fileSystem = new MockFileSystem('fake-media-volume');
var fileSystem = new MockFileSystem('fake-media-volume');
fileSystem.populate(fileNames); fileSystem.populate(fileNames);
return fileNames.map((name) => fileSystem.entries[name]);
return fileNames.map(
function(filename) {
return fileSystem.entries[filename];
});
} }
/** /**
* Replaces fileOperationUtil.copyTo with some mock functionality for testing. * Replaces fileOperationUtil.copyTo with a mock for testing.
* @constructor * @constructor
*/ */
function MockCopyTo() { function MockCopyTo() {
/** @type {!Array<!MockCopyTo.CopyInfo>} */ /** @type {!Array<!MockCopyTo.CopyInfo>} */
this.copiedFiles = []; this.copiedFiles = [];
// Replace with test function. // Replace fileOperationUtil.copyTo with our mock test function.
fileOperationUtil.copyTo = this.copyTo_.bind(this); fileOperationUtil.copyTo =
/** @type {function(*)} */ (this.copyTo_.bind(this));
/** @private {boolean} */
this.simulateError_ = false; this.simulateError_ = false;
this.entryChangedCallback_ = null; this.entryChangedCallback_ = null;
...@@ -607,9 +642,9 @@ function MockCopyTo() { ...@@ -607,9 +642,9 @@ function MockCopyTo() {
/** /**
* @typedef {{ * @typedef {{
* source: source, * source: !Entry,
* destination: parent, * destination: !DirectoryEntry,
* newName: newName * newName: string,
* }} * }}
*/ */
MockCopyTo.CopyInfo; MockCopyTo.CopyInfo;
...@@ -623,14 +658,13 @@ MockCopyTo.prototype.simulateOneError = function() { ...@@ -623,14 +658,13 @@ MockCopyTo.prototype.simulateOneError = function() {
/** /**
* A mock to replace fileOperationUtil.copyTo. See the original for details. * A mock to replace fileOperationUtil.copyTo. See the original for details.
* @param {Entry} source * @param {!Entry} source
* @param {DirectoryEntry} parent * @param {!DirectoryEntry} parent
* @param {string} newName * @param {string} newName
* @param {function(string, Entry)} entryChangedCallback * @param {function(string, Entry)} entryChangedCallback
* @param {function(string, number)} progressCallback * @param {function(string, number)} progressCallback
* @param {function(Entry)} successCallback * @param {function(Entry)} successCallback
* @param {function(DOMError)} errorCallback * @param {function(Error)} errorCallback
* @return {function()}
*/ */
MockCopyTo.prototype.copyTo_ = function(source, parent, newName, MockCopyTo.prototype.copyTo_ = function(source, parent, newName,
entryChangedCallback, progressCallback, successCallback, errorCallback) { entryChangedCallback, progressCallback, successCallback, errorCallback) {
...@@ -641,22 +675,23 @@ MockCopyTo.prototype.copyTo_ = function(source, parent, newName, ...@@ -641,22 +675,23 @@ MockCopyTo.prototype.copyTo_ = function(source, parent, newName,
if (this.simulateError_) { if (this.simulateError_) {
this.simulateError_ = false; this.simulateError_ = false;
this.errorCallback_(new Error('test error')); var error = new Error('test error');
this.errorCallback_(error);
return; return;
} }
// Log the copy, then copy the file. // Log the copy details.
this.copiedFiles.push({ this.copiedFiles.push(/** @type {!MockCopyTo.CopyInfo} */ ({
source: source, source: source,
destination: parent, destination: parent,
newName: newName newName: newName,
}); }));
source.copyTo(
parent, // Copy the file.
newName, var copyErrorCallback = /** @type {!function(FileError):*} */
function(newEntry) { (this.errorCallback_.bind(this));
this.entryChangedCallback_(source.toURL(), parent); source.copyTo(parent, newName, function(newEntry) {
this.successCallback_(newEntry); this.entryChangedCallback_(source.toURL(), parent);
}.bind(this), this.successCallback_(newEntry);
this.errorCallback_.bind(this)); }.bind(this), copyErrorCallback);
}; };
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment