Robot Framework SeleniumLibrary
browsermanagement.py
Go to the documentation of this file.
1 # Copyright 2008-2011 Nokia Networks
2 # Copyright 2011-2016 Ryan Tomac, Ed Manlove and contributors
3 # Copyright 2016- Robot Framework Foundation
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 
17 import time
18 import types
19 
20 from selenium import webdriver
21 from selenium.webdriver.support.event_firing_webdriver import EventFiringWebDriver
22 
23 from SeleniumLibrary.base import keyword, LibraryComponent
24 from SeleniumLibrary.locators import WindowManager
25 from SeleniumLibrary.utils import (is_truthy, is_noney, secs_to_timestr,
26  timestr_to_secs)
27 
28 from .webdrivertools import WebDriverCreator
29 
30 
32 
33  def __init__(self, ctx):
34  LibraryComponent.__init__(self, ctx)
35  self._window_manager_window_manager = WindowManager(ctx)
36 
37  @keyword
38 
46  def close_all_browsers(self):
47  self.debugdebug('Closing all browsers.')
48  self.driversdriversdrivers.close_all()
49 
50  @keyword
51 
52  def close_browser(self):
53  if self.driversdriversdrivers.current:
54  self.debugdebug('Closing browser with session id {}.'
55  .format(self.driverdriverdriver.session_id))
56  self.driversdriversdrivers.close()
57 
58  @keyword
59 
151  def open_browser(self, url, browser='firefox', alias=None,
152  remote_url=False, desired_capabilities=None,
153  ff_profile_dir=None, service_log_path=None):
154  index = self.driversdriversdrivers.get_index(alias)
155  if index:
156  self.infoinfo('Using existing browser from index %s.' % index)
157  self.switch_browserswitch_browser(alias)
158  self.go_togo_to(url)
159  return index
160  return self._make_new_browser_make_new_browser(url, browser, alias, remote_url,
161  desired_capabilities, ff_profile_dir,
162  service_log_path)
163 
164  def _make_new_browser(self, url, browser='firefox', alias=None,
165  remote_url=False, desired_capabilities=None,
166  ff_profile_dir=None, service_log_path=None):
167  if is_truthy(remote_url):
168  self.infoinfo("Opening browser '%s' to base url '%s' through "
169  "remote server at '%s'." % (browser, url, remote_url))
170  else:
171  self.infoinfo("Opening browser '%s' to base url '%s'." % (browser, url))
172  driver = self._make_driver_make_driver(browser, desired_capabilities,
173  ff_profile_dir, remote_url,
174  service_log_path)
175  driver = self._wrap_event_firing_webdriver_wrap_event_firing_webdriver(driver)
176  try:
177  driver.get(url)
178  except Exception:
179  self.ctxctx.register_driver(driver, alias)
180  self.debugdebug("Opened browser with session id %s but failed "
181  "to open url '%s'." % (driver.session_id, url))
182  raise
183  self.debugdebug('Opened browser with session id %s.' % driver.session_id)
184  return self.ctxctx.register_driver(driver, alias)
185 
186  @keyword
187 
216  def create_webdriver(self, driver_name, alias=None, kwargs={},
217  **init_kwargs):
218  if not isinstance(kwargs, dict):
219  raise RuntimeError("kwargs must be a dictionary.")
220  for arg_name in kwargs:
221  if arg_name in init_kwargs:
222  raise RuntimeError("Got multiple values for argument '%s'." % arg_name)
223  init_kwargs[arg_name] = kwargs[arg_name]
224  driver_name = driver_name.strip()
225  try:
226  creation_func = getattr(webdriver, driver_name)
227  except AttributeError:
228  raise RuntimeError("'%s' is not a valid WebDriver name." % driver_name)
229  self.infoinfo("Creating an instance of the %s WebDriver." % driver_name)
230  driver = creation_func(**init_kwargs)
231  self.debugdebug("Created %s WebDriver instance with session id %s."
232  % (driver_name, driver.session_id))
233  driver = self._wrap_event_firing_webdriver_wrap_event_firing_webdriver(driver)
234  return self.ctxctx.register_driver(driver, alias)
235 
236  def _wrap_event_firing_webdriver(self, driver):
237  if not self.ctxctx.event_firing_webdriver:
238  return driver
239  self.debugdebug('Wrapping driver to event_firing_webdriver.')
240  return EventFiringWebDriver(driver, self.ctxctx.event_firing_webdriver())
241 
242  @keyword
243 
268  def switch_browser(self, index_or_alias):
269  try:
270  self.driversdriversdrivers.switch(index_or_alias)
271  except RuntimeError:
272  raise RuntimeError("No browser with index or alias '%s' found."
273  % index_or_alias)
274  self.debugdebug('Switched to browser with Selenium session id %s.'
275  % self.driverdriverdriver.session_id)
276 
277  @keyword
278 
282  def get_session_id(self):
283  return self.driverdriverdriver.session_id
284 
285  @keyword
286 
287  def get_source(self):
288  return self.driverdriverdriver.page_source
289 
290  @keyword
291 
292  def get_title(self):
293  return self.driverdriverdriver.title
294 
295  @keyword
296 
297  def get_location(self):
298  return self.driverdriverdriver.current_url
299 
300  @keyword
301 
310  def location_should_be(self, url, message=None):
311  actual = self.get_locationget_location()
312  if actual != url:
313  if is_noney(message):
314  message = ("Location should have been '%s' but "
315  "was '%s'." % (url, actual))
316  raise AssertionError(message)
317  self.infoinfo("Current location is '%s'." % url)
318 
319  @keyword
320 
329  def location_should_contain(self, expected, message=None):
330  actual = self.get_locationget_location()
331  if expected not in actual:
332  if is_noney(message):
333  message = ("Location should have contained '%s' but "
334  "it was '%s'." % (expected, actual))
335  raise AssertionError(message)
336  self.infoinfo("Current location contains '%s'." % expected)
337 
338  @keyword
339 
340  def log_location(self):
341  url = self.get_locationget_location()
342  self.infoinfo(url)
343  return url
344 
345  @keyword
346 
352  def log_source(self, loglevel='INFO'):
353  source = self.get_sourceget_source()
354  self.loglog(source, loglevel)
355  return source
356 
357  @keyword
358 
359  def log_title(self):
360  title = self.get_titleget_title()
361  self.infoinfo(title)
362  return title
363 
364  @keyword
365 
372  def title_should_be(self, title, message=None):
373  actual = self.get_titleget_title()
374  if actual != title:
375  if is_noney(message):
376  message = "Title should have been '%s' but was '%s'." % (title, actual)
377  raise AssertionError(message)
378  self.infoinfo("Page title is '%s'." % title)
379 
380  @keyword
381 
382  def go_back(self):
383  self.driverdriverdriver.back()
384 
385  @keyword
386 
387  def go_to(self, url):
388  self.infoinfo("Opening url '%s'" % url)
389  self.driverdriverdriver.get(url)
390 
391  @keyword
392 
393  def reload_page(self):
394  self.driverdriverdriver.refresh()
395 
396  @keyword
397 
404  return secs_to_timestr(self.ctxctx.speed)
405 
406  @keyword
407 
414  return secs_to_timestr(self.ctxctx.timeout)
415 
416  @keyword
417 
424  return secs_to_timestr(self.ctxctx.implicit_wait)
425 
426  @keyword
427 
439  def set_selenium_speed(self, value):
440  old_speed = self.get_selenium_speedget_selenium_speed()
441  self.ctxctx.speed = timestr_to_secs(value)
442  for driver in self.driversdriversdrivers.active_drivers:
443  self._monkey_patch_speed_monkey_patch_speed(driver)
444  return old_speed
445 
446  @keyword
447 
461  def set_selenium_timeout(self, value):
462  old_timeout = self.get_selenium_timeoutget_selenium_timeout()
463  self.ctxctx.timeout = timestr_to_secs(value)
464  for driver in self.driversdriversdrivers.active_drivers:
465  driver.set_script_timeout(self.ctxctx.timeout)
466  return old_timeout
467 
468  @keyword
469 
487  def set_selenium_implicit_wait(self, value):
488  old_wait = self.get_selenium_implicit_waitget_selenium_implicit_wait()
489  self.ctxctx.implicit_wait = timestr_to_secs(value)
490  for driver in self.driversdriversdrivers.active_drivers:
491  driver.implicitly_wait(self.ctxctx.implicit_wait)
492  return old_wait
493 
494  @keyword
495 
500  def set_browser_implicit_wait(self, value):
501  self.driverdriverdriver.implicitly_wait(timestr_to_secs(value))
502 
503  def _make_driver(self, browser, desired_capabilities=None,
504  profile_dir=None, remote=None, service_log_path=None):
505  driver = WebDriverCreator(self.log_dirlog_dirlog_dir).create_driver(
506  browser=browser, desired_capabilities=desired_capabilities,
507  remote_url=remote, profile_dir=profile_dir, service_log_path=service_log_path)
508  driver.set_script_timeout(self.ctxctx.timeout)
509  driver.implicitly_wait(self.ctxctx.implicit_wait)
510  if self.ctxctx.speed:
511  self._monkey_patch_speed_monkey_patch_speed(driver)
512  return driver
513 
514  def _monkey_patch_speed(self, driver):
515  def execute(self, driver_command, params=None):
516  result = self._base_execute(driver_command, params)
517  speed = self._speed if hasattr(self, '_speed') else 0.0
518  if speed > 0:
519  time.sleep(speed)
520  return result
521  if not hasattr(driver, '_base_execute'):
522  driver._base_execute = driver.execute
523  driver.execute = types.MethodType(execute, driver)
524  driver._speed = self.ctxctx.speed
def log(self, msg, level='INFO', html=False)
def get_selenium_timeout(self)
Gets the timeout that is used by various keywords.
def set_browser_implicit_wait(self, value)
Sets the implicit wait value used by Selenium.
def get_selenium_implicit_wait(self)
Gets the implicit wait value used by Selenium.
def location_should_contain(self, expected, message=None)
Verifies that current URL contains expected.
def open_browser(self, url, browser='firefox', alias=None, remote_url=False, desired_capabilities=None, ff_profile_dir=None, service_log_path=None)
Opens a new browser instance to the given url.
def __init__(self, ctx)
Base class exposing attributes from the common context.
def set_selenium_implicit_wait(self, value)
Sets the implicit wait value used by Selenium.
def log_source(self, loglevel='INFO')
Logs and returns the HTML source of the current page or frame.
def _make_driver(self, browser, desired_capabilities=None, profile_dir=None, remote=None, service_log_path=None)
def set_selenium_timeout(self, value)
Sets the timeout that is used by various keywords.
def _make_new_browser(self, url, browser='firefox', alias=None, remote_url=False, desired_capabilities=None, ff_profile_dir=None, service_log_path=None)
def location_should_be(self, url, message=None)
Verifies that current URL is exactly url.
def go_back(self)
Simulates the user clicking the back button on their browser.
def set_selenium_speed(self, value)
Sets the delay that is waited after each Selenium command.
def get_session_id(self)
Returns the currently active browser session id.
def close_all_browsers(self)
Closes all open browsers and resets the browser cache.
def go_to(self, url)
Navigates the active browser instance to the provided url.
def get_source(self)
Returns the entire HTML source of the current page or frame.
def get_selenium_speed(self)
Gets the delay that is waited after each Selenium command.
def log_title(self)
Logs and returns the title of current page.
def title_should_be(self, title, message=None)
Verifies that current page title equals title.
def switch_browser(self, index_or_alias)
Switches between active browsers using index_or_alias.
def create_webdriver(self, driver_name, alias=None, kwargs={}, **init_kwargs)
Creates an instance of Selenium WebDriver.