Permalink
Browse files

Merge pull request #245 from ombre42/custom-webdriver

Implement 'Create Webdriver' keyword
  • Loading branch information...
emanlove committed Nov 30, 2013
2 parents 8e87eb3 + c00bdac commit 8c8247f6742e4ab6302eee82749ea14ec5b12920
@@ -114,6 +114,60 @@ def open_browser(self, url, browser='firefox', alias=None,remote_url=False,
% browser.session_id)
return self._cache.register(browser, alias)
+ def create_webdriver(self, driver_name, alias=None, kwargs={}, **init_kwargs):
+ """Creates an instance of a WebDriver.
+
+ Like `Open Browser`, but allows passing arguments to a WebDriver's
+ __init__. _Open Browser_ is preferred over _Create Webdriver_ when
+ feasible.
+
+ Returns the index of this browser instance which can be used later to
+ switch back to it. Index starts from 1 and is reset back to it when
+ `Close All Browsers` keyword is used. See `Switch Browser` for
+ example.
+
+ `driver_name` must be the exact name of a WebDriver in
+ _selenium.webdriver_ to use. WebDriver names include: Firefox, Chrome,
+ Ie, Opera, Safari, PhantomJS, and Remote.
+
+ Use keyword arguments to specify the arguments you want to pass to
+ the WebDriver's __init__. The values of the arguments are not
+ processed in any way before being passed on. For Robot Framework
+ < 2.8, which does not support keyword arguments, create a keyword
+ dictionary and pass it in as argument `kwargs`. See the
+ [http://selenium.googlecode.com/git/docs/api/py/api.html|Selenium API Documentation]
+ for information about argument names and appropriate argument values.
+
+ Examples:
+ | # use proxy for Firefox | | | |
+ | ${proxy}= | Evaluate | sys.modules['selenium.webdriver'].Proxy() | sys, selenium.webdriver |
+ | ${proxy.http_proxy}= | Set Variable | localhost:8888 | |
+ | Create Webdriver | Firefox | proxy=${proxy} | |
+ | # use a proxy for PhantomJS | | | |
+ | ${service args}= | Create List | --proxy=192.168.132.104:8888 | |
+ | Create Webdriver | PhantomJS | service_args=${service args} | |
+
+ Example for Robot Framework < 2.8:
+ | # debug IE driver | | | | | |
+ | ${kwargs}= | Create Dictionary | log_level | DEBUG | log_file | %{HOMEPATH}${/}ie.log |
+ | Create Webdriver | Ie | kwargs=${kwargs} | | | |
+ """
+ if not isinstance(kwargs, dict):
+ raise RuntimeError("kwargs must be a dictionary.")
+ for arg_name in kwargs:
+ if arg_name in init_kwargs:
+ raise RuntimeError("Got multiple values for argument '%s'." % arg_name)
+ init_kwargs[arg_name] = kwargs[arg_name]
+ driver_name = driver_name.strip()
+ try:
+ creation_func = getattr(webdriver, driver_name)
+ except AttributeError:
+ raise RuntimeError("'%s' is not a valid WebDriver name" % driver_name)
+ self._info("Creating an instance of the %s WebDriver" % driver_name)
+ driver = creation_func(**init_kwargs)
+ self._debug("Created %s WebDriver instance with session id %s" % (driver_name, driver.session_id))
+ return self._cache.register(driver, alias)
+
def switch_browser(self, index_or_alias):
"""Switches between active browsers using index or alias.
@@ -0,0 +1,35 @@
+*Setting*
+Resource resource.txt
+Library Collections
+
+*Test Cases*
+Create Webdriver Creates Functioning WebDriver
+ [Documentation] LOG 2:1 INFO REGEXP: Creating an instance of the \\w+ WebDriver LOG 2:3 DEBUG REGEXP: Created \\w+ WebDriver instance with session id (\\w|-)+
+ [Setup] Set Driver Variables
+ Create Webdriver ${DRIVER_NAME} kwargs=${KWARGS}
+ Go To ${FRONT PAGE}
+ Page Should Contain needle
+ [Teardown] Close Browser
+
+Create Webdriver With Bad Driver Name
+ Run Keyword And Expect Error 'Fireox' is not a valid WebDriver name Create Webdriver Fireox
+
+Create Webdriver With Duplicate Arguments
+ ${kwargs}= Create Dictionary arg 1
+ Run Keyword And Expect Error Got multiple values for argument 'arg'. Create Webdriver Firefox kwargs=${kwargs} arg=2
+
+Create Webdriver With Bad Keyword Argument Dictionary
+ Run Keyword And Expect Error kwargs must be a dictionary. Create Webdriver Firefox kwargs={'spam': 'eggs'}
+
+*Keywords*
+Set Driver Variables
+ ${drivers}= Create Dictionary ff Firefox firefox Firefox ie Ie internetexplorer Ie googlechrome Chrome gc Chrome chome Chrome opera Opera phantomjs PhantomJS safari Safari
+ ${name}= Evaluate "Remote" if "${REMOTE_URL}"!="None" else ${drivers}["${BROWSER.lower().replace(' ', '')}"]
+ Set Test Variable ${DRIVER_NAME} ${name}
+ ${dc names}= Create Dictionary ff FIREFOX firefox FIREFOX ie INTERNETEXPLORER internetexplorer INTERNETEXPLORER googlechrome CHROME gc CHROME opera OPERA phantomjs PHANTOMJS htmlunit HTMLUNIT htmlunitwithjs HTMLUNITWITHJS android ANDROID iphone IPHONE safari SAFARI
+ ${dc name}= Get From Dictionary ${dc names} ${BROWSER.lower().replace(' ', '')}
+ ${caps}= Evaluate sys.modules['selenium.webdriver'].DesiredCapabilities.${dc name} selenium.webdriver,sys
+ ${url as str}= Evaluate str('${REMOTE_URL}') # cannot be unicode for several versions >= 2.32
+ ${kwargs}= Create Dictionary
+ Run Keyword If "${name}"=="Remote" Set To Dictionary ${kwargs} command_executor ${url as str} desired_capabilities ${caps}
+ Set Test Variable ${KWARGS} ${kwargs}
@@ -85,6 +85,28 @@ def test_bad_browser_name(self):
except ValueError, e:
self.assertEquals("fireox is not a supported browser.", e.message)
+ def test_create_webdriver(self):
+ bm = _BrowserManagementWithLoggingStubs()
+ capt_data = {}
+ class FakeWebDriver(mock):
+ def __init__(self, some_arg=None):
+ mock.__init__(self)
+ capt_data['some_arg'] = some_arg
+ capt_data['webdriver'] = self
+ webdriver.FakeWebDriver = FakeWebDriver
+ try:
+ index = bm.create_webdriver('FakeWebDriver', 'fake', some_arg=1)
+ self.assertEquals(capt_data['some_arg'], 1)
+ self.assertEquals(capt_data['webdriver'], bm._current_browser())
+ self.assertEquals(capt_data['webdriver'], bm._cache.get_connection(index))
+ self.assertEquals(capt_data['webdriver'], bm._cache.get_connection('fake'))
+ capt_data.clear()
+ my_kwargs = {'some_arg':2}
+ bm.create_webdriver('FakeWebDriver', kwargs=my_kwargs)
+ self.assertEquals(capt_data['some_arg'], 2)
+ finally:
+ del webdriver.FakeWebDriver
+
def verify_browser(self , webdriver_type , browser_name, **kw):
#todo try lambda *x: was_called = true
bm = _BrowserManagementKeywords()
@@ -104,4 +126,11 @@ def mock_init(self, *args, **kw):
self.was_called = True
+class _BrowserManagementWithLoggingStubs(_BrowserManagementKeywords):
+ def __init__(self):
+ _BrowserManagementKeywords.__init__(self)
+ def mock_logging_method(self, *args, **kwargs):
+ pass
+ for name in ['_info', '_debug', '_warn', '_log', '_html']:
+ setattr(self, name, mock_logging_method)

0 comments on commit 8c8247f

Please sign in to comment.