blob: 65bd0a09acbc8ee8c865c4c7fb106b9b31d21e0e [file] [log] [blame]
Dan Shic1d263b2013-10-04 17:31:38 -07001# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import atexit
6import logging
7import os
8import urllib2
9
Dan Shi96c77cb2013-11-19 10:30:37 -080010try:
11 from selenium import webdriver
12except ImportError:
13 # Ignore import error, as this can happen when builder tries to call the
14 # setup method of test that imports chromedriver.
15 logging.error('selenium module failed to be imported.')
16 pass
Dan Shic1d263b2013-10-04 17:31:38 -070017
18import common
19from autotest_lib.client.bin import utils
20from autotest_lib.client.common_lib.cros import chrome
21
22CHROMEDRIVER_EXE_PATH = '/usr/local/chromedriver/chromedriver'
beeps47a51292013-11-20 08:55:23 -080023X_SERVER_DISPLAY = ':0'
24X_AUTHORITY = '/home/chronos/.Xauthority'
25
Dan Shic1d263b2013-10-04 17:31:38 -070026
27class chromedriver(object):
28 """Wrapper class, a context manager type, for tests to use Chrome Driver."""
29
30 def __init__(self, extra_chrome_flags=[], subtract_extra_chrome_flags=[],
beeps47a51292013-11-20 08:55:23 -080031 extension_paths=[], is_component=True, *args, **kwargs):
Dan Shic1d263b2013-10-04 17:31:38 -070032 """Initialize.
33
34 @param extra_chrome_flags: Extra chrome flags to pass to chrome, if any.
35 @param subtract_extra_chrome_flags: Remove default flags passed to
36 chrome by chromedriver, if any.
beeps47a51292013-11-20 08:55:23 -080037 @param extension_paths: A list of paths to unzipped extensions. Note
38 that paths to crx files won't work.
39 @param is_component: True if the manifest.json has a key.
Dan Shic1d263b2013-10-04 17:31:38 -070040 """
41 assert os.geteuid() == 0, 'Need superuser privileges'
42
43 # Log in with telemetry
beepsbff9f9d2013-12-06 11:14:08 -080044 self._chrome = chrome.Chrome(extension_paths=extension_paths,
45 is_component=is_component,
46 extra_browser_args=extra_chrome_flags)
47 self._browser = self._chrome.browser
Dan Shic1d263b2013-10-04 17:31:38 -070048
49 # Start ChromeDriver server
50 self._server = chromedriver_server(CHROMEDRIVER_EXE_PATH)
51
52 chromeOptions = {'debuggerAddress':
53 ('localhost:%d' %
54 utils.get_chrome_remote_debugging_port())}
55 capabilities = {'chromeOptions':chromeOptions}
56 # Handle to chromedriver, for chrome automation.
Dan Shi96c77cb2013-11-19 10:30:37 -080057 try:
58 self.driver = webdriver.Remote(command_executor=self._server.url,
59 desired_capabilities=capabilities)
60 except NameError:
61 logging.error('selenium module failed to be imported.')
62 raise
Dan Shic1d263b2013-10-04 17:31:38 -070063
64
65 def __enter__(self):
66 return self
67
68
69 def __exit__(self, *args):
70 """Clean up after running the test.
71
72 """
73 if hasattr(self, 'driver') and self.driver:
74 self.driver.close()
75 del self.driver
76
77 if hasattr(self, '_server') and self._server:
78 self._server.close()
79 del self._server
80
81 if hasattr(self, '_browser') and self._browser:
82 self._browser.Close()
83 del self._browser
84
85
beepsbff9f9d2013-12-06 11:14:08 -080086 def get_extension(self, extension_path):
87 """Gets an extension by proxying to the browser.
88
89 @param extension_path: Path to the extension loaded in the browser.
90
91 @return: A telemetry extension object representing the extension.
92 """
93 return self._chrome.get_extension(extension_path)
94
95
Dan Shic1d263b2013-10-04 17:31:38 -070096class chromedriver_server(object):
97 """A running ChromeDriver server.
98
99 This code is migrated from chrome:
100 src/chrome/test/chromedriver/server/server.py
101 """
102
103 def __init__(self, exe_path):
104 """Starts the ChromeDriver server and waits for it to be ready.
105
106 Args:
107 exe_path: path to the ChromeDriver executable
108 Raises:
109 RuntimeError if ChromeDriver fails to start
110 """
111 if not os.path.exists(exe_path):
112 raise RuntimeError('ChromeDriver exe not found at: ' + exe_path)
113
114 port = utils.get_unused_port()
115 chromedriver_args = [exe_path, '--port=%d' % port]
beeps47a51292013-11-20 08:55:23 -0800116
117 # Chromedriver will look for an X server running on the display
118 # specified through the DISPLAY environment variable.
119 os.environ['DISPLAY'] = X_SERVER_DISPLAY
120 os.environ['XAUTHORITY'] = X_AUTHORITY
121
Dan Shic1d263b2013-10-04 17:31:38 -0700122 self.bg_job = utils.BgJob(chromedriver_args, stderr_level=logging.DEBUG)
123 self.url = 'http://localhost:%d' % port
124 if self.bg_job is None:
125 raise RuntimeError('ChromeDriver server cannot be started')
126
127 try:
128 timeout_msg = 'Timeout on waiting for ChromeDriver to start.'
129 utils.poll_for_condition(self.is_running,
130 exception=utils.TimeoutError(timeout_msg),
131 timeout=10,
132 sleep_interval=.1)
133 except utils.TimeoutError:
134 self.close_bgjob()
135 raise RuntimeError('ChromeDriver server did not start')
136
137 logging.debug('Chrome Driver server is up and listening at port %d.',
138 port)
139 atexit.register(self.close)
140
141
142 def is_running(self):
143 """Returns whether the server is up and running."""
144 try:
145 urllib2.urlopen(self.url + '/status')
146 return True
147 except urllib2.URLError as e:
148 return False
149
150
151 def close_bgjob(self):
152 """Close background job and log stdout and stderr."""
153 utils.nuke_subprocess(self.bg_job.sp)
154 utils.join_bg_jobs([self.bg_job], timeout=1)
155 result = self.bg_job.result
156 if result.stdout or result.stderr:
157 logging.info('stdout of Chrome Driver:\n%s', result.stdout)
158 logging.error('stderr of Chrome Driver:\n%s', result.stderr)
159
160
161 def close(self):
162 """Kills the ChromeDriver server, if it is running."""
163 if self.bg_job is None:
164 return
165
166 try:
167 urllib2.urlopen(self.url + '/shutdown', timeout=10).close()
168 except:
169 pass
170
171 self.close_bgjob()