Commit e3617337 authored by andrewcheng's avatar andrewcheng Committed by Commit bot

[chromedriver] setting browser default download directory

BUG=chromedriver:783

Review URL: https://codereview.chromium.org/613163004

Cr-Commit-Position: refs/heads/master@{#300531}
parent 353493d7
...@@ -86,8 +86,13 @@ ChromeDesktopImpl::~ChromeDesktopImpl() { ...@@ -86,8 +86,13 @@ ChromeDesktopImpl::~ChromeDesktopImpl() {
if (!quit_) { if (!quit_) {
base::FilePath user_data_dir = user_data_dir_.Take(); base::FilePath user_data_dir = user_data_dir_.Take();
base::FilePath extension_dir = extension_dir_.Take(); base::FilePath extension_dir = extension_dir_.Take();
LOG(WARNING) << "chrome detaches, user should take care of directory:" LOG(WARNING) << "chrome quit unexpectedly, leaving behind temporary "
<< user_data_dir.value() << " and " << extension_dir.value(); "directories for debugging:";
if (user_data_dir_.IsValid())
LOG(WARNING) << "chrome user data directory: " << user_data_dir.value();
if (extension_dir_.IsValid())
LOG(WARNING) << "chromedriver automation extension directory: "
<< extension_dir.value();
} }
base::CloseProcessHandle(process_); base::CloseProcessHandle(process_);
} }
......
...@@ -128,28 +128,33 @@ Status PrepareCommandLine(int port, ...@@ -128,28 +128,33 @@ Status PrepareCommandLine(int port,
switches.RemoveSwitch(*iter); switches.RemoveSwitch(*iter);
} }
switches.SetFromSwitches(capabilities.switches); switches.SetFromSwitches(capabilities.switches);
base::FilePath user_data_dir_path;
if (!switches.HasSwitch("user-data-dir")) { if (!switches.HasSwitch("user-data-dir")) {
command.AppendArg("data:,"); command.AppendArg("data:,");
if (!user_data_dir->CreateUniqueTempDir()) if (!user_data_dir->CreateUniqueTempDir())
return Status(kUnknownError, "cannot create temp dir for user data dir"); return Status(kUnknownError, "cannot create temp dir for user data dir");
switches.SetSwitch("user-data-dir", user_data_dir->path().value()); switches.SetSwitch("user-data-dir", user_data_dir->path().value());
Status status = internal::PrepareUserDataDir( user_data_dir_path = user_data_dir->path();
user_data_dir->path(), capabilities.prefs.get(), } else {
capabilities.local_state.get()); user_data_dir_path = base::FilePath(
if (status.IsError()) switches.GetSwitchValueNative("user-data-dir"));
return status;
} }
Status status = internal::PrepareUserDataDir(user_data_dir_path,
capabilities.prefs.get(),
capabilities.local_state.get());
if (status.IsError())
return status;
if (!extension_dir->CreateUniqueTempDir()) { if (!extension_dir->CreateUniqueTempDir()) {
return Status(kUnknownError, return Status(kUnknownError,
"cannot create temp dir for unpacking extensions"); "cannot create temp dir for unpacking extensions");
} }
Status status = internal::ProcessExtensions(capabilities.extensions, status = internal::ProcessExtensions(capabilities.extensions,
extension_dir->path(), extension_dir->path(),
true, true,
&switches, &switches,
extension_bg_pages); extension_bg_pages);
if (status.IsError()) if (status.IsError())
return status; return status;
switches.AppendToCommandLine(&command); switches.AppendToCommandLine(&command);
...@@ -772,14 +777,32 @@ Status PrepareUserDataDir( ...@@ -772,14 +777,32 @@ Status PrepareUserDataDir(
if (!base::CreateDirectory(default_dir)) if (!base::CreateDirectory(default_dir))
return Status(kUnknownError, "cannot create default profile directory"); return Status(kUnknownError, "cannot create default profile directory");
std::string preferences;
base::FilePath preferences_path =
default_dir.Append(chrome::kPreferencesFilename);
if (base::PathExists(preferences_path))
base::ReadFileToString(preferences_path, &preferences);
else
preferences = kPreferences;
Status status = Status status =
WritePrefsFile(kPreferences, WritePrefsFile(preferences,
custom_prefs, custom_prefs,
default_dir.Append(chrome::kPreferencesFilename)); default_dir.Append(chrome::kPreferencesFilename));
if (status.IsError()) if (status.IsError())
return status; return status;
status = WritePrefsFile(kLocalState, std::string local_state;
base::FilePath local_state_path =
user_data_dir.Append(chrome::kLocalStateFilename);
if (base::PathExists(local_state_path))
base::ReadFileToString(local_state_path, &local_state);
else
local_state = kLocalState;
status = WritePrefsFile(local_state,
custom_local_state, custom_local_state,
user_data_dir.Append(chrome::kLocalStateFilename)); user_data_dir.Append(chrome::kLocalStateFilename));
if (status.IsError()) if (status.IsError())
......
...@@ -66,7 +66,7 @@ class ChromeDriver(object): ...@@ -66,7 +66,7 @@ class ChromeDriver(object):
chrome_extensions=None, chrome_log_path=None, chrome_extensions=None, chrome_log_path=None,
debugger_address=None, browser_log_level=None, debugger_address=None, browser_log_level=None,
performance_log_level=None, mobile_emulation=None, performance_log_level=None, mobile_emulation=None,
experimental_options=None): experimental_options=None, download_dir=None):
self._executor = command_executor.CommandExecutor(server_url) self._executor = command_executor.CommandExecutor(server_url)
options = {} options = {}
...@@ -115,6 +115,14 @@ class ChromeDriver(object): ...@@ -115,6 +115,14 @@ class ChromeDriver(object):
assert performance_log_level in log_levels assert performance_log_level in log_levels
logging_prefs['performance'] = performance_log_level logging_prefs['performance'] = performance_log_level
download_prefs = {}
if download_dir:
if 'prefs' not in options:
options['prefs'] = {}
if 'download' not in options['prefs']:
options['prefs']['download'] = {}
options['prefs']['download']['default_directory'] = download_dir
params = { params = {
'desiredCapabilities': { 'desiredCapabilities': {
'chromeOptions': options, 'chromeOptions': options,
......
...@@ -18,6 +18,7 @@ import threading ...@@ -18,6 +18,7 @@ import threading
import time import time
import unittest import unittest
import urllib2 import urllib2
import shutil
_THIS_DIR = os.path.abspath(os.path.dirname(__file__)) _THIS_DIR = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(1, os.path.join(_THIS_DIR, os.pardir)) sys.path.insert(1, os.path.join(_THIS_DIR, os.pardir))
...@@ -159,7 +160,7 @@ class ChromeDriverBaseTest(unittest.TestCase): ...@@ -159,7 +160,7 @@ class ChromeDriverBaseTest(unittest.TestCase):
except: except:
pass pass
def CreateDriver(self, server_url=None, **kwargs): def CreateDriver(self, server_url=None, download_dir=None, **kwargs):
if server_url is None: if server_url is None:
server_url = _CHROMEDRIVER_SERVER_URL server_url = _CHROMEDRIVER_SERVER_URL
...@@ -177,6 +178,7 @@ class ChromeDriverBaseTest(unittest.TestCase): ...@@ -177,6 +178,7 @@ class ChromeDriverBaseTest(unittest.TestCase):
android_package=android_package, android_package=android_package,
android_activity=android_activity, android_activity=android_activity,
android_process=android_process, android_process=android_process,
download_dir=download_dir,
**kwargs) **kwargs)
self._drivers += [driver] self._drivers += [driver]
return driver return driver
...@@ -230,8 +232,8 @@ class ChromeDriverTest(ChromeDriverBaseTest): ...@@ -230,8 +232,8 @@ class ChromeDriverTest(ChromeDriverBaseTest):
Returns: Returns:
Handle to a new window. None if timeout. Handle to a new window. None if timeout.
""" """
timeout = time.time() + 20 deadline = time.time() + 20
while time.time() < timeout: while time.time() < deadline:
new_handles = self._driver.GetWindowHandles() new_handles = self._driver.GetWindowHandles()
if len(new_handles) > len(old_handles): if len(new_handles) > len(old_handles):
for index, old_handle in enumerate(old_handles): for index, old_handle in enumerate(old_handles):
...@@ -767,6 +769,61 @@ class ChromeDriverAndroidTest(ChromeDriverBaseTest): ...@@ -767,6 +769,61 @@ class ChromeDriverAndroidTest(ChromeDriverBaseTest):
self._drivers[0].Quit() self._drivers[0].Quit()
self._drivers[0] = self.CreateDriver() self._drivers[0] = self.CreateDriver()
class ChromeDownloadDirTest(ChromeDriverBaseTest):
def testFileDownLoad(self):
try:
self.download_dir = tempfile.mkdtemp()
download_name = os.path.join(self.download_dir, 'a_red_dot.png')
driver = self.CreateDriver(download_dir=self.download_dir)
driver.Load(ChromeDriverTest.GetHttpUrlForFile(
'/chromedriver/download.html'))
driver.FindElement('id', 'red-dot').Click()
deadline = time.time() + 60
while True:
time.sleep(0.1)
if os.path.isfile(download_name) or time.time() > deadline:
break
self.assertTrue(os.path.isfile(download_name), "Failed to download file!")
finally:
shutil.rmtree(self.download_dir)
def testDownloadDirectoryOverridesExistingPreferences(self):
""" test existing prefence profile - check setting if it is correct """
try:
user_data_dir = tempfile.mkdtemp()
tmp_download_dir = tempfile.mkdtemp()
sub_dir = os.path.join(user_data_dir, 'Default')
os.mkdir(sub_dir)
prefs_file_path = os.path.join(sub_dir, 'Preferences')
prefs = {
'test': 'this should not be changed',
'download': {
'default_directory': '/old/download/directory'
}
}
with open(prefs_file_path, 'w') as f:
json.dump(prefs, f)
driver = self.CreateDriver(
chrome_switches=['user-data-dir=' + user_data_dir],
download_dir = tmp_download_dir)
with open(prefs_file_path) as f:
prefs = json.load(f)
self.assertEqual('this should not be changed', prefs['test'],
"Existing preference was unexpectedly overridden")
download = prefs['download']
self.assertEqual(download['default_directory'], tmp_download_dir,
'Download directory preference was not updated to match capabilities')
finally:
shutil.rmtree(user_data_dir)
shutil.rmtree(tmp_download_dir)
class ChromeSwitchesCapabilityTest(ChromeDriverBaseTest): class ChromeSwitchesCapabilityTest(ChromeDriverBaseTest):
"""Tests that chromedriver properly processes chromeOptions.args capabilities. """Tests that chromedriver properly processes chromeOptions.args capabilities.
......
<html>
<head><title>Test Page for ChromeDownloadDirTest</title></head>
<body>
<a id='red-dot' href="anchor_download_test.png" download='a_red_dot.png'>Download Red Dot!</a>
</body>
</html>
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