Commit 05540c14 authored by satorux@chromium.org's avatar satorux@chromium.org

file_manager: Remove pyauto tests for the file manager

The pyauto tests for the file manager are no longer maintained.
Besides, the file manager is now tested with browser tests.

BUG=289294
TEST=none

Review URL: https://chromiumcodereview.appspot.com/23834007

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@223545 0039d316-1c4b-4281-b951-d872f2087c98
parent 3beded07
// Copyright (c) 2012 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';
/**
* pyautoAPI object provides a set of functions used by PyAuto tests
* to drive the file manager.
*
* Refer to chrome/test/functional/chromeos_file_browser.py for examples
* of how this API is used.
*
* TODO(olege): Fix style warnings.
*/
var pyautoAPI = {
/**
* Add the item with given name to the current selection.
* @param {string} name Name of the item to add to selection.
*/
addItemToSelection: function(name) {
var entryExists = false;
var dm = fileManager.directoryModel_.getFileList();
for (var i = 0; i < dm.length; i++) {
if (dm.item(i).name == name) {
fileManager.currentList_.selectionModel.setIndexSelected(i, true);
fileManager.currentList_.scrollIndexIntoView(i);
fileManager.focusCurrentList_();
entryExists = true;
break;
}
}
pyautoAPI.sendValue_(entryExists);
},
/**
* List all items in the current directory.
* We assume names do not contain '|' charecter.
*/
listDirectory: function() {
var list = [];
var dm = fileManager.directoryModel_.getFileList();
for (var i = 0; i < dm.length; i++) {
list.push(dm.item(i).name);
}
pyautoAPI.sendJSONValue_(list);
},
/**
* Save the item using the given name.
*
* @param {string} name Name given to item to be saved.
*/
saveItemAs: function(name) {
if (fileManager.dialogType == DialogType.SELECT_SAVEAS_FILE) {
fileManager.filenameInput_.value = name;
fileManager.onOk_();
} else {
throw new Error('Cannot save an item in this dialog type.');
}
pyautoAPI.sendDone_();
},
/**
* Open selected item.
*/
openItem: function() {
switch (fileManager.dialogType) {
case DialogType.SELECT_FOLDER:
case DialogType.SELECT_OPEN_FILE:
case DialogType.SELECT_OPEN_MULTI_FILE:
fileManager.onOk_();
break;
default:
throw new Error('Cannot open an item in this dialog type.');
}
pyautoAPI.sendDone_();
},
/**
* Execute the default task for the selected item.
*/
executeDefaultTask: function() {
switch (fileManager.dialogType) {
case DialogType.FULL_PAGE:
if (fileManager.getSelection().tasks)
fileManager.getSelection().tasks.executeDefault();
else
throw new Error('Cannot execute a task on an empty selection.');
break;
default:
throw new Error('Cannot execute a task in this dialog type.');
}
pyautoAPI.sendDone_();
},
/**
* Executes the clipboard command.
* @param {string} command Command name.
*/
executeClipboardCommand_: function(command) {
// Input should not be focused, or the cut/cop/paste command
// will be treated as textual editing.
fileManager.filenameInput_.blur();
fileManager.document_.execCommand(command);
},
/**
* Copy selected items to clipboard.
*/
copyItems: function() {
pyautoAPI.executeClipboardCommand_('copy');
pyautoAPI.sendDone_();
},
/**
* Cut selected items to clipboard.
*/
cutItems: function() {
pyautoAPI.executeClipboardCommand_('cut');
pyautoAPI.sendDone_();
},
/**
* Paste items from clipboard.
*/
pasteItems: function() {
var dm = fileManager.directoryModel_;
var onRescan = function() {
dm.removeEventListener('rescan-completed', onRescan);
pyautoAPI.sendDone_();
};
dm.addEventListener('rescan-completed', onRescan);
pyautoAPI.executeClipboardCommand_('paste');
},
/**
* Rename selected item.
* @param {string} name New name of the item.
*/
renameItem: function(name) {
var entry = fileManager.getSelection().entries[0];
util.rename(entry, name,
function(newEntry) {
// Update directory model on success.
fileManager.directoryModel_.onRenameEntry(
entry, newEntry, pyautoAPI.sendDone_);
},
pyautoAPI.sendDone_);
},
/**
* Delete selected entries.
*/
deleteItems: function() {
var dm = fileManager.directoryModel_;
var onRescan = function() {
dm.removeEventListener('rescan-completed', onRescan);
pyautoAPI.sendDone_();
};
dm.addEventListener('rescan-completed', onRescan);
fileManager.deleteSelection();
},
/**
* Create directory.
* @param {string} name Name of the directory.
*/
createDirectory: function(name) {
var dm = fileManager.directoryModel_;
var onRescan = function() {
dm.removeEventListener('rescan-completed', onRescan);
pyautoAPI.sendDone_();
};
dm.addEventListener('rescan-completed', onRescan);
fileManager.directoryModel_.createDirectory(name, function() {});
},
/**
* Change to a directory.
* A path starting with '/' * is absolute, otherwise it is relative to the
* current directory.
* @param {string} path Path to directory.
*/
changeDirectory: function(path) {
if (path.charAt(0) != '/')
path = fileManager.getCurrentDirectory() + '/' + path;
var dm = fileManager.directoryModel_;
var onChanged = function() {
dm.removeEventListener('directory-changed', onChanged);
pyautoAPI.sendDone_();
};
dm.addEventListener('directory-changed', onChanged);
dm.changeDirectory(path);
},
/**
* Get the absolute path of current directory.
*/
currentDirectory: function() {
pyautoAPI.sendValue_(fileManager.getCurrentDirectory());
},
/**
* Get remaining and total size of selected directory.
*/
getSelectedDirectorySizeStats: function() {
var directoryURL = fileManager.getSelection().entries[0].toURL();
chrome.fileBrowserPrivate.getSizeStats(directoryURL, function(stats) {
pyautoAPI.sendJSONValue_(stats);
});
},
/**
* Returns whether the file manager is initialized.
* This function is polled by pyauto before calling any
* of the functions above.
*/
isInitialized: function() {
var initialized = fileManager &&
fileManager.workerInitialized_ &&
fileManager.getCurrentDirectory();
pyautoAPI.sendValue_(!!initialized);
},
/**
* Callback function for returning primitiv types (int, string, boolean)
*/
sendValue_: function(value) {
window.domAutomationController.send(value);
},
/**
* Callback function for returning a JSON encoded value.
*/
sendJSONValue_: function(value) {
window.domAutomationController.send(JSON.stringify(value));
},
/**
* Callback function signalling completion of operation.
*/
sendDone_: function() {
window.domAutomationController.send('done');
}
};
......@@ -87,7 +87,6 @@
//<include src="file_operation_manager_wrapper.js"/>
//<include src="file_grid.js"/>
//<include src="file_manager.js"/>
//<include src="file_manager_pyauto.js"/>
//<include src="file_selection.js"/>
//<include src="file_table.js"/>
//<include src="file_tasks.js"/>
......
......@@ -100,7 +100,6 @@
<script src="js/file_operation_manager_wrapper.js"></script>
<script src="js/file_grid.js"></script>
<script src="js/file_manager.js"></script>
<script src="js/file_manager_pyauto.js"></script>
<script src="js/file_selection.js"></script>
<script src="js/file_table.js"></script>
<script src="js/file_tasks.js"></script>
......
......@@ -217,12 +217,10 @@
'chromeos_basic',
'chromeos_browser',
'chromeos_crosh',
'chromeos_file_browser',
'chromeos_power',
'chromeos_prefs',
'chromeos_security',
'chromeos_time',
'doc_viewing',
'secure_shell',
'youtube',
......
#!/usr/bin/env python
# Copyright (c) 2012 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.
import pyauto_functional
import pyauto
import chromeos.file_browser
import test_utils
class ChromeosFileBrowserTest(pyauto.PyUITest):
"""Tests for ChromeOS File Browser (full page and dialog)."""
def _GetFullPageFileBrowser(self, tab_index=0, windex=0):
"""Display the full page file browser in the current tab.
Returns:
ChromeosFileBrowser object.
"""
self.NavigateToURL('chrome://files')
executor = pyauto.PyUITest.JavascriptExecutorInTab(self, tab_index, windex)
file_browser = chromeos.file_browser.FileBrowser(self, executor)
if file_browser.WaitUntilInitialized():
return file_browser
else:
return None
def _GetSaveAsDialogFileBrowser(self):
"""Display the save-as file browser dialog.
The current tab should not be 'about:blank'.
Returns:
ChromeosFileBrowser object.
"""
self.ApplyAccelerator(pyauto.IDC_SAVE_PAGE)
dialog = self.WaitUntilExtensionViewLoaded(view_type='EXTENSION_DIALOG')
self.assertTrue(
dialog,
msg='Could not find a loaded "save-as" file browser'
'dialog (views = %s).' % self.GetBrowserInfo()['extension_views'])
executor = \
pyauto.PyUITest.JavascriptExecutorInRenderView(self, dialog)
file_browser = chromeos.file_browser.FileBrowser(self, executor)
if file_browser.WaitUntilInitialized():
return file_browser
else:
return None
def _GetOpenDialogFileBrowser(self):
"""Display the open file browser dialog.
Returns:
ChromeosFileBrowser object.
"""
self.ApplyAccelerator(pyauto.IDC_OPEN_FILE)
dialog = self.WaitUntilExtensionViewLoaded(view_type='EXTENSION_DIALOG')
self.assertTrue(
dialog,
msg='Could not find a loaded "open" file browser dialog: views = %s.' %
self.GetBrowserInfo()['extension_views'])
executor = \
pyauto.PyUITest.JavascriptExecutorInRenderView(self, dialog)
file_browser = chromeos.file_browser.FileBrowser(self, executor)
if file_browser.WaitUntilInitialized():
return file_browser
else:
return None
def testOpenMediaFiles(self):
"""Test we can open media files from the file browser dialog."""
media_files = ['bear.mp4', 'bear.ogv', 'bear_pcm.wav', 'bear.webm']
private_media_files = ['emerge.m4a', 'sample.mp3', 'sample.m4v',
'sample.ogg']
# TODO: .avi, .wmv are not yet (fully) supported on ChromeOS.
# .mov and .3gp only work in the Media Player. Once these format are
# supported on ChromeOS, include them in the test.
for fname in media_files:
test_utils.CopyFileFromContentDataDirToDownloadDir(self,
'media/' + fname)
for fname in private_media_files:
test_utils.CopyFileFromDataDirToDownloadDir(self, 'pyauto_private/media/' +\
fname)
for fname in media_files + private_media_files:
file_browser = self._GetOpenDialogFileBrowser()
self.assertTrue(file_browser, msg='File browser failed to initialize.')
if file_browser.CurrentDirectory() != '/Downloads':
file_browser.ChangeDirectory('/Downloads/')
self.assertTrue(file_browser.Select(fname),
msg='"%s" does not exist.' % fname)
dialog = self.WaitUntilExtensionViewLoaded(view_type='EXTENSION_DIALOG')
file_browser.Open()
self.assertTrue(self.WaitUntilExtensionViewClosed(dialog),
msg='File browser dialog was not closed.')
self.assertFalse(self.IsDownloadShelfVisible(),
msg='Download shelf is visible. ' +
'Media format not recognized for %s.' % fname)
def testSavePage(self):
"""Test we can save the current page using the file browser dialog."""
self.NavigateToURL('chrome://version')
file_browser = self._GetSaveAsDialogFileBrowser()
self.assertTrue(file_browser, msg='File browser failed to initialize.')
dialog = self.WaitUntilExtensionViewLoaded(view_type='EXTENSION_DIALOG')
file_browser.Save('apple.html')
self.assertTrue(self.WaitUntilExtensionViewClosed(dialog))
file_browser = self._GetOpenDialogFileBrowser()
self.assertTrue(file_browser.Select('apple.html'))
def testSelectMultipleFoldersInFullPage(self):
"""Test we can select multiple folders in the full page file browser."""
file_browser = self._GetFullPageFileBrowser()
self.assertTrue(file_browser, msg='File browser failed to initialize.')
file_browser.CreateDirectory('apples')
file_browser.CreateDirectory('oranges')
self.assertEqual(file_browser.DirectoryContents(),
set(['apples', 'oranges']),
msg='Failed to create directories (list = %s).' %
file_browser.DirectoryContents())
file_browser.Select('apples')
file_browser.Select('oranges')
file_browser.Delete()
self.assertFalse(file_browser.DirectoryContents(),
msg='Failed to delete directories (list = %s).' %
file_browser.DirectoryContents())
def _CreateFolder(self, file_browser):
"""Create folders and then change into them."""
top_directory = file_browser.CurrentDirectory()
tree = ['deep', 'deeper', 'deepest']
for directory in tree:
file_browser.CreateDirectory(directory)
file_browser.ChangeDirectory(directory)
self.assertEqual(file_browser.CurrentDirectory(),
top_directory + '/' + '/'.join(tree),
msg='Ended up in wrong directory (%s)' %
file_browser.CurrentDirectory())
def testCreateFolderInFullPage(self):
"""Test we can create a folder in the full page file browser."""
file_browser = self._GetFullPageFileBrowser()
self.assertTrue(file_browser, msg='File browser failed to initialize.')
self._CreateFolder(file_browser)
def testCreateFolderInDialog(self):
"""Test we can create a folder in a save-as file browser dialog."""
self.NavigateToURL('chrome://version')
file_browser = self._GetSaveAsDialogFileBrowser()
self.assertTrue(file_browser, msg='File browser failed to initialize.')
self._CreateFolder(file_browser)
def _RenameFolder(self, file_browser):
"""Create a folder and then rename it."""
file_browser.CreateDirectory('apples')
file_browser.Select('apples')
file_browser.Rename('oranges')
self.assertFalse(file_browser.Select('apples'))
self.assertTrue(file_browser.Select('oranges'))
def testRenameFolderInFullPage(self):
"""Test we can rename a folder in the full page file browser."""
file_browser = self._GetFullPageFileBrowser()
self.assertTrue(file_browser, msg='File browser failed to initialize.')
self._RenameFolder(file_browser)
def testRenameFolderInDialog(self):
"""Test we can rename a folder in a save-as file browser dialog."""
self.NavigateToURL('chrome://version')
file_browser = self._GetSaveAsDialogFileBrowser()
self.assertTrue(file_browser, msg='File browser failed to initialize.')
self._RenameFolder(file_browser)
def _DeleteFolder(self, file_browser):
"""Create a folder and then delete it."""
file_browser.CreateDirectory('apples')
file_browser.Select('apples')
file_browser.Delete()
self.assertFalse(file_browser.Select('apples'))
def testDeleteFolderInFullPage(self):
"""Test we can delete a folder in the full page file browser."""
file_browser = self._GetFullPageFileBrowser()
self.assertTrue(file_browser, msg='File browser failed to initialize.')
self._DeleteFolder(file_browser)
def testDeleteFolderInDialog(self):
"""Test we can delete a folder in a save-as file browser dialog."""
self.NavigateToURL('chrome://version')
file_browser = self._GetSaveAsDialogFileBrowser()
self.assertTrue(file_browser, msg='File browser failed to initialize.')
self._DeleteFolder(file_browser)
def _CopyFolder(self, file_browser):
"""Create a folder and then copy and paste it to itself."""
file_browser.CreateDirectory('apples')
file_browser.Select('apples')
file_browser.Copy()
file_browser.CreateDirectory('oranges')
file_browser.ChangeDirectory('oranges')
file_browser.Paste()
self.assertTrue(file_browser.Select('apples'))
def testCopyFolderInFullPage(self):
"""Test we can copy and paste a folder in the full page file browser."""
file_browser = self._GetFullPageFileBrowser()
self.assertTrue(file_browser, msg='File browser failed to initialize.')
self._CopyFolder(file_browser)
def _CutFolder(self, file_browser):
"""Create two folders and cut and paste one inside the other."""
top_directory = file_browser.CurrentDirectory()
file_browser.CreateDirectory('apples')
file_browser.Select('apples')
file_browser.Cut()
file_browser.CreateDirectory('oranges')
file_browser.ChangeDirectory('oranges')
file_browser.Paste()
self.assertTrue(file_browser.Select('apples'))
file_browser.ChangeDirectory(top_directory)
self.assertFalse(file_browser.Select('apples'))
def testCutFolderInFullPage(self):
"""Test we can cut and paste a folder in the full page file browser."""
file_browser = self._GetFullPageFileBrowser()
self.assertTrue(file_browser, msg='File browser failed to initialize.')
self._CutFolder(file_browser)
def testGetSelectedDirectorySizeStats(self):
"""Test we can get remaining and total size of the file shelf."""
file_browser = self._GetFullPageFileBrowser()
self.assertTrue(file_browser, msg='File browser failed to initialize.')
file_browser.CreateDirectory('apples')
file_browser.Select('apples')
remaining, total = file_browser.GetSelectedDirectorySizeStats()
self.assertTrue(remaining > 0,
msg='Remaining disk space = %dKB.' % remaining)
self.assertTrue(total > 0,
msg='Total disk space = %dKB.' % total)
self.assertTrue(total > remaining,
msg='Total space(%dKB) <= remaining space(%dKB).' %
(total, remaining))
if __name__ == '__main__':
pyauto_functional.Main()
#!/usr/bin/env python
# Copyright (c) 2012 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.
import os
import pyauto_functional # must be imported before pyauto
import chromeos.file_browser
import pyauto
import test_utils
class DocViewingTest(pyauto.PyUITest):
"""Basic tests for ChromeOS document viewing.
Requires ChromeOS to be logged in.
"""
def setUp(self):
pyauto.PyUITest.setUp(self)
extension_path = '/opt/google/chrome/extensions'\
'/gbkeegbaiigmenfmjfclcdgdpimamgkj.crx'
# If crx file with doesn't exist, component extensions should be used.
if os.path.exists(extension_path):
ext_id = self.InstallExtension(extension_path, from_webstore=True)
self.assertTrue(ext_id, msg='Failed to install extension %s' %
extension_path)
def _GetFullPageFileBrowser(self):
"""Display the full page file browser.
Returns:
ChromeosFileBrowser object.
"""
self.NavigateToURL('chrome://files/#/Downloads')
executor = pyauto.PyUITest.JavascriptExecutorInTab(self)
file_browser = chromeos.file_browser.FileBrowser(self, executor)
if file_browser.WaitUntilInitialized():
return file_browser
else:
return None
def testOpenOfficeFiles(self):
"""Test we can open office files from the file manager."""
path = os.path.abspath(os.path.join(self.DataDir(),
'pyauto_private', 'office'))
# Copy sample files to Downloads directory.
for (path, dirs, private_office_files) in os.walk(path):
# Open sample files: .ppt, .pptx, .doc, .docx, xls, xlsx.
for fname in private_office_files:
test_utils.CopyFileFromDataDirToDownloadDir(self, os.path.join(path,
fname))
file_browser = self._GetFullPageFileBrowser()
self.assertTrue(file_browser, msg='File browser failed to initialize.')
def _SelectFile():
try:
file_browser.Select(fname)
return True
except AssertionError:
return False
self.assertTrue(self.WaitUntil(_SelectFile),
msg='"%s" does not exist.' % fname)
file_browser.ExecuteDefaultTask()
self.assertTrue(self.WaitUntil(self.GetActiveTabTitle,
expect_retval=fname),
msg='"%s" does not open.' % fname)
# Close the document viewing tab after use.
self.CloseTab(tab_index=1)
if __name__ == '__main__':
pyauto_functional.Main()
# Copyright (c) 2012 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.
import simplejson as json # found in third_party
class FileBrowser(object):
"""This class provides an API for automating the ChromeOS File Browser.
Example:
# Create and change into 'hello world' folder.
executor = pyauto.PyUITest.JavascriptExecutorInTab(self)
file_browser = chromeos.file_browser.FileBrowser(self, executor)
if file_browser.WaitUntilInitialized():
file_browser.CreateDirectory('hello world')
file_browser.ChangeDirectory('hello world')
For complete examples refer to chromeos_file_browser.py.
"""
def __init__(self, ui_test, executor):
"""Initialize FileBrowser.
Args:
ui_test: derived from pyauto.PyUITest - base class for UI test cases.
executor: derived from pyauto.PyUITest.JavascriptExecutor.
"""
self._ui_test = ui_test
self.executor = executor
def Select(self, name):
"""Add entry with given name to the current selection.
Args:
name: Name of the entry to add to selection
Returns:
Whether entry exists.
"""
script = """
pyautoAPI.addItemToSelection('%s');
""" % name
return self.executor.Execute(script)
def DirectoryContents(self):
"""Return a set containing all entries in the current directory.
Returns:
A set of entries.
"""
script = """
pyautoAPI.listDirectory();
"""
list = json.loads(self.executor.Execute(script))
return set(list)
def Save(self, name):
"""Save the entry using the given name.
Args:
name: Name given to entry to be saved.
"""
script = """
pyautoAPI.saveItemAs('%s');
""" % name
self.executor.Execute(script)
def Open(self):
"""Open selected entries."""
script = """
pyautoAPI.openItem();
"""
self.executor.Execute(script)
def ExecuteDefaultTask(self):
"""Open selected entries."""
script = """
pyautoAPI.executeDefaultTask()
"""
self.executor.Execute(script)
def Copy(self):
"""Copy selected entries to clipboard."""
script = """
pyautoAPI.copyItems();
"""
self.executor.Execute(script)
def Cut(self):
"""Cut selected entries to clipboard. """
script = """
pyautoAPI.cutItems();
"""
self.executor.Execute(script)
def Paste(self):
"""Paste entries from clipboard."""
script = """
pyautoAPI.pasteItems();
"""
self.executor.Execute(script)
def Rename(self, name):
"""Rename selected entry.
Args:
name: New name of the entry.
"""
script = """
pyautoAPI.renameItem('%s');
""" % name
self.executor.Execute(script)
def Delete(self):
"""Delete selected entries."""
script = """
pyautoAPI.deleteItems();
"""
self.executor.Execute(script)
def CreateDirectory(self, name):
"""Create directory.
Args:
name: Name of the directory.
"""
script = """
pyautoAPI.createDirectory('%s');
""" % name
self.executor.Execute(script)
def ChangeDirectory(self, path):
"""Change to a directory.
A path starting with '/' is absolute, otherwise it is relative to the
current directory.
Args:
name: Path to directory.
"""
script = """
pyautoAPI.changeDirectory('%s');
""" % path
self.executor.Execute(script)
def CurrentDirectory(self):
"""Get the absolute path of current directory.
Returns:
Path to the current directory.
"""
script = """
pyautoAPI.currentDirectory();
"""
return self.executor.Execute(script)
def GetSelectedDirectorySizeStats(self):
"""Get remaining and total size of selected directory.
Returns:
A tuple: (remaining size in KB, total size in KB)
"""
script = """
pyautoAPI.getSelectedDirectorySizeStats();
"""
stats = json.loads(self.executor.Execute(script))
return stats['remainingSizeKB'], stats['totalSizeKB']
def WaitUntilInitialized(self):
"""Returns whether the file manager is initialized.
This should be called before calling any of the functions above.
Returns:
Whether file manager is initialied.
"""
def _IsInitialized():
script = """
pyautoAPI.isInitialized();
"""
return self.executor.Execute(script)
return self._ui_test.WaitUntil(lambda: _IsInitialized())
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