GoogleGit

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