Dan Shi | c1d263b | 2013-10-04 17:31:38 -0700 | [diff] [blame] | 1 | # 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 | |
| 5 | import atexit |
| 6 | import logging |
| 7 | import os |
| 8 | import urllib2 |
| 9 | |
Dan Shi | 96c77cb | 2013-11-19 10:30:37 -0800 | [diff] [blame] | 10 | try: |
| 11 | from selenium import webdriver |
| 12 | except 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 Shi | c1d263b | 2013-10-04 17:31:38 -0700 | [diff] [blame] | 17 | |
| 18 | import common |
| 19 | from autotest_lib.client.bin import utils |
| 20 | from autotest_lib.client.common_lib.cros import chrome |
| 21 | |
| 22 | CHROMEDRIVER_EXE_PATH = '/usr/local/chromedriver/chromedriver' |
beeps | 47a5129 | 2013-11-20 08:55:23 -0800 | [diff] [blame] | 23 | X_SERVER_DISPLAY = ':0' |
| 24 | X_AUTHORITY = '/home/chronos/.Xauthority' |
| 25 | |
Dan Shi | c1d263b | 2013-10-04 17:31:38 -0700 | [diff] [blame] | 26 | |
| 27 | class 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=[], |
Nathan Stoddard | ab58304 | 2014-08-11 10:41:47 -0700 | [diff] [blame^] | 31 | extension_paths=[], is_component=True, username=None, |
| 32 | password=None, *args, **kwargs): |
Dan Shi | c1d263b | 2013-10-04 17:31:38 -0700 | [diff] [blame] | 33 | """Initialize. |
| 34 | |
| 35 | @param extra_chrome_flags: Extra chrome flags to pass to chrome, if any. |
| 36 | @param subtract_extra_chrome_flags: Remove default flags passed to |
| 37 | chrome by chromedriver, if any. |
beeps | 47a5129 | 2013-11-20 08:55:23 -0800 | [diff] [blame] | 38 | @param extension_paths: A list of paths to unzipped extensions. Note |
| 39 | that paths to crx files won't work. |
| 40 | @param is_component: True if the manifest.json has a key. |
Nathan Stoddard | ab58304 | 2014-08-11 10:41:47 -0700 | [diff] [blame^] | 41 | @param username: Log in using this username instead of the default. |
| 42 | @param username: Log in using this password instead of the default. |
Dan Shi | c1d263b | 2013-10-04 17:31:38 -0700 | [diff] [blame] | 43 | """ |
| 44 | assert os.geteuid() == 0, 'Need superuser privileges' |
| 45 | |
| 46 | # Log in with telemetry |
beeps | bff9f9d | 2013-12-06 11:14:08 -0800 | [diff] [blame] | 47 | self._chrome = chrome.Chrome(extension_paths=extension_paths, |
| 48 | is_component=is_component, |
Nathan Stoddard | ab58304 | 2014-08-11 10:41:47 -0700 | [diff] [blame^] | 49 | username=username, |
| 50 | password=password, |
beeps | bff9f9d | 2013-12-06 11:14:08 -0800 | [diff] [blame] | 51 | extra_browser_args=extra_chrome_flags) |
| 52 | self._browser = self._chrome.browser |
Dan Shi | 2bff39b | 2014-03-28 11:36:13 -0700 | [diff] [blame] | 53 | # Close all tabs owned and opened by Telemetry, as these cannot be |
| 54 | # transferred to ChromeDriver. |
| 55 | self._browser.tabs[0].Close() |
Dan Shi | c1d263b | 2013-10-04 17:31:38 -0700 | [diff] [blame] | 56 | |
| 57 | # Start ChromeDriver server |
| 58 | self._server = chromedriver_server(CHROMEDRIVER_EXE_PATH) |
| 59 | |
Dan Shi | 2bff39b | 2014-03-28 11:36:13 -0700 | [diff] [blame] | 60 | # Open a new tab using Chrome remote debugging. ChromeDriver expects |
| 61 | # a tab opened for remote to work. Tabs opened using Telemetry will be |
| 62 | # owned by Telemetry, and will be inaccessible to ChromeDriver. |
| 63 | urllib2.urlopen('http://localhost:%i/json/new' % |
| 64 | utils.get_chrome_remote_debugging_port()) |
| 65 | |
Dan Shi | c1d263b | 2013-10-04 17:31:38 -0700 | [diff] [blame] | 66 | chromeOptions = {'debuggerAddress': |
| 67 | ('localhost:%d' % |
| 68 | utils.get_chrome_remote_debugging_port())} |
| 69 | capabilities = {'chromeOptions':chromeOptions} |
| 70 | # Handle to chromedriver, for chrome automation. |
Dan Shi | 96c77cb | 2013-11-19 10:30:37 -0800 | [diff] [blame] | 71 | try: |
| 72 | self.driver = webdriver.Remote(command_executor=self._server.url, |
| 73 | desired_capabilities=capabilities) |
| 74 | except NameError: |
| 75 | logging.error('selenium module failed to be imported.') |
| 76 | raise |
Dan Shi | c1d263b | 2013-10-04 17:31:38 -0700 | [diff] [blame] | 77 | |
| 78 | |
| 79 | def __enter__(self): |
| 80 | return self |
| 81 | |
| 82 | |
| 83 | def __exit__(self, *args): |
| 84 | """Clean up after running the test. |
| 85 | |
| 86 | """ |
| 87 | if hasattr(self, 'driver') and self.driver: |
| 88 | self.driver.close() |
| 89 | del self.driver |
| 90 | |
| 91 | if hasattr(self, '_server') and self._server: |
| 92 | self._server.close() |
| 93 | del self._server |
| 94 | |
| 95 | if hasattr(self, '_browser') and self._browser: |
| 96 | self._browser.Close() |
| 97 | del self._browser |
| 98 | |
| 99 | |
beeps | bff9f9d | 2013-12-06 11:14:08 -0800 | [diff] [blame] | 100 | def get_extension(self, extension_path): |
| 101 | """Gets an extension by proxying to the browser. |
| 102 | |
| 103 | @param extension_path: Path to the extension loaded in the browser. |
| 104 | |
| 105 | @return: A telemetry extension object representing the extension. |
| 106 | """ |
| 107 | return self._chrome.get_extension(extension_path) |
| 108 | |
| 109 | |
Dan Shi | c1d263b | 2013-10-04 17:31:38 -0700 | [diff] [blame] | 110 | class chromedriver_server(object): |
| 111 | """A running ChromeDriver server. |
| 112 | |
| 113 | This code is migrated from chrome: |
| 114 | src/chrome/test/chromedriver/server/server.py |
| 115 | """ |
| 116 | |
| 117 | def __init__(self, exe_path): |
| 118 | """Starts the ChromeDriver server and waits for it to be ready. |
| 119 | |
| 120 | Args: |
| 121 | exe_path: path to the ChromeDriver executable |
| 122 | Raises: |
| 123 | RuntimeError if ChromeDriver fails to start |
| 124 | """ |
| 125 | if not os.path.exists(exe_path): |
| 126 | raise RuntimeError('ChromeDriver exe not found at: ' + exe_path) |
| 127 | |
| 128 | port = utils.get_unused_port() |
| 129 | chromedriver_args = [exe_path, '--port=%d' % port] |
beeps | 47a5129 | 2013-11-20 08:55:23 -0800 | [diff] [blame] | 130 | |
| 131 | # Chromedriver will look for an X server running on the display |
| 132 | # specified through the DISPLAY environment variable. |
| 133 | os.environ['DISPLAY'] = X_SERVER_DISPLAY |
| 134 | os.environ['XAUTHORITY'] = X_AUTHORITY |
| 135 | |
Dan Shi | c1d263b | 2013-10-04 17:31:38 -0700 | [diff] [blame] | 136 | self.bg_job = utils.BgJob(chromedriver_args, stderr_level=logging.DEBUG) |
| 137 | self.url = 'http://localhost:%d' % port |
| 138 | if self.bg_job is None: |
| 139 | raise RuntimeError('ChromeDriver server cannot be started') |
| 140 | |
| 141 | try: |
| 142 | timeout_msg = 'Timeout on waiting for ChromeDriver to start.' |
| 143 | utils.poll_for_condition(self.is_running, |
| 144 | exception=utils.TimeoutError(timeout_msg), |
| 145 | timeout=10, |
| 146 | sleep_interval=.1) |
| 147 | except utils.TimeoutError: |
| 148 | self.close_bgjob() |
| 149 | raise RuntimeError('ChromeDriver server did not start') |
| 150 | |
| 151 | logging.debug('Chrome Driver server is up and listening at port %d.', |
| 152 | port) |
| 153 | atexit.register(self.close) |
| 154 | |
| 155 | |
| 156 | def is_running(self): |
| 157 | """Returns whether the server is up and running.""" |
| 158 | try: |
| 159 | urllib2.urlopen(self.url + '/status') |
| 160 | return True |
| 161 | except urllib2.URLError as e: |
| 162 | return False |
| 163 | |
| 164 | |
| 165 | def close_bgjob(self): |
| 166 | """Close background job and log stdout and stderr.""" |
| 167 | utils.nuke_subprocess(self.bg_job.sp) |
| 168 | utils.join_bg_jobs([self.bg_job], timeout=1) |
| 169 | result = self.bg_job.result |
| 170 | if result.stdout or result.stderr: |
| 171 | logging.info('stdout of Chrome Driver:\n%s', result.stdout) |
| 172 | logging.error('stderr of Chrome Driver:\n%s', result.stderr) |
| 173 | |
| 174 | |
| 175 | def close(self): |
| 176 | """Kills the ChromeDriver server, if it is running.""" |
| 177 | if self.bg_job is None: |
| 178 | return |
| 179 | |
| 180 | try: |
| 181 | urllib2.urlopen(self.url + '/shutdown', timeout=10).close() |
| 182 | except: |
| 183 | pass |
| 184 | |
| 185 | self.close_bgjob() |