diff --git a/src/Selenium2Library/__init__.py b/src/Selenium2Library/__init__.py index 96bd3c3b0..4be21b4a9 100644 --- a/src/Selenium2Library/__init__.py +++ b/src/Selenium2Library/__init__.py @@ -6,11 +6,12 @@ __version__ = VERSION + class Selenium2Library( - _LoggingKeywords, - _RunOnFailureKeywords, - _BrowserManagementKeywords, - _ElementKeywords, + _LoggingKeywords, + _RunOnFailureKeywords, + _BrowserManagementKeywords, + _ElementKeywords, _TableElementKeywords, _FormElementKeywords, _SelectElementKeywords, @@ -31,7 +32,7 @@ class Selenium2Library( *Before running tests* Prior to running test cases using Selenium2Library, Selenium2Library must be - imported into your Robot test suite (see `importing` section), and the + imported into your Robot test suite (see `importing` section), and the `Open Browser` keyword must be used to open a browser to the desired location. *Locating elements* diff --git a/src/Selenium2Library/keywords/_browsermanagement.py b/src/Selenium2Library/keywords/_browsermanagement.py index dc10d2b2d..8ac96fd0a 100644 --- a/src/Selenium2Library/keywords/_browsermanagement.py +++ b/src/Selenium2Library/keywords/_browsermanagement.py @@ -16,11 +16,12 @@ 'googlechrome': "_make_chrome", 'gc': "_make_chrome", 'chrome': "_make_chrome", - 'opera' : "_make_opera", - 'htmlunit' : "_make_htmlunit", - 'htmlunitwithjs' : "_make_htmlunitwithjs" + 'opera': "_make_opera", + 'htmlunit': "_make_htmlunit", + 'htmlunitwithjs': "_make_htmlunitwithjs" } + class _BrowserManagementKeywords(KeywordGroup): def __init__(self): @@ -51,8 +52,8 @@ def close_browser(self): % self._cache.current.session_id) self._cache.close() - def open_browser(self, url, browser='firefox', alias=None,remote_url=False, - desired_capabilities=None,ff_profile_dir=None): + def open_browser(self, url, browser='firefox', alias=None, remote_url=False, + desired_capabilities=None, ff_profile_dir=None): """Opens a new browser instance to given URL. Returns the index of this browser instance which can be used later to @@ -76,7 +77,7 @@ def open_browser(self, url, browser='firefox', alias=None,remote_url=False, | opera | Opera | | htmlunit | HTMLUnit | | htmlunitwithjs | HTMLUnit with Javascipt support | - + Note, that you will encounter strange behavior, if you open multiple Internet Explorer browser instances. That is also why @@ -101,7 +102,7 @@ def open_browser(self, url, browser='firefox', alias=None,remote_url=False, else: self._info("Opening browser '%s' to base url '%s'" % (browser, url)) browser_name = browser - browser = self._make_browser(browser_name,desired_capabilities,ff_profile_dir,remote_url) + browser = self._make_browser(browser_name, desired_capabilities, ff_profile_dir, remote_url) browser.get(url) self._debug('Opened browser with session id %s' % browser.session_id) @@ -185,7 +186,7 @@ def select_window(self, locator=None): If the window is found, all subsequent commands use that window, until this keyword is used again. If the window is not found, this keyword fails. - + By default, when a locator value is provided, it is matched against the title of the window and the javascript name of the window. If multiple windows with @@ -351,26 +352,25 @@ def set_selenium_implicit_wait(self, seconds): """Sets Selenium 2's default implicit wait in seconds and sets the implicit wait for all open browsers. - From selenium 2 function 'Sets a sticky timeout to implicitly + From selenium 2 function 'Sets a sticky timeout to implicitly wait for an element to be found, or a command to complete. This method only needs to be called one time per session.' Example: | ${orig wait} = | Set Selenium Implicit Wait | 10 seconds | | Perform AJAX call that is slow | - | Set Selenium Implicit Wait | ${orig wait} | + | Set Selenium Implicit Wait | ${orig wait} | """ old_wait = self.get_selenium_implicit_wait() self._implicit_wait_in_secs = robot.utils.timestr_to_secs(seconds) for browser in self._cache.get_open_browsers(): browser.implicitly_wait(self._implicit_wait_in_secs) return old_wait - def set_browser_implicit_wait(self, seconds): """Sets current browser's implicit wait in seconds. - From selenium 2 function 'Sets a sticky timeout to implicitly + From selenium 2 function 'Sets a sticky timeout to implicitly wait for an element to be found, or a command to complete. This method only needs to be called one time per session.' @@ -392,15 +392,14 @@ def _current_browser(self): def _get_browser_token(self, browser_name): return BROWSER_NAMES.get(browser_name.lower().replace(' ', ''), browser_name) - - def _get_browser_creation_function(self,browser_name): + def _get_browser_creation_function(self, browser_name): return BROWSER_NAMES.get(browser_name.lower().replace(' ', ''), browser_name) - def _make_browser(self , browser_name , desired_capabilities=None , profile_dir=None, + def _make_browser(self, browser_name, desired_capabilities=None, profile_dir=None, remote=None): creation_func = self._get_browser_creation_function(browser_name) - browser = getattr(self,creation_func)(remote , desired_capabilities , profile_dir) + browser = getattr(self, creation_func)(remote, desired_capabilities, profile_dir) if browser is None: raise ValueError(browser_name + " is not a supported browser.") @@ -411,55 +410,51 @@ def _make_browser(self , browser_name , desired_capabilities=None , profile_dir= return browser - - def _make_ff(self , remote , desired_capabilites , profile_dir): - - if not profile_dir: profile_dir = FIREFOX_PROFILE_DIR + def _make_ff(self, remote, desired_capabilites, profile_dir): + if not profile_dir: + profile_dir = FIREFOX_PROFILE_DIR profile = webdriver.FirefoxProfile(profile_dir) if remote: - browser = self._create_remote_web_driver(webdriver.DesiredCapabilities.FIREFOX , - remote , desired_capabilites , profile) + browser = self._create_remote_web_driver(webdriver.DesiredCapabilities.FIREFOX, + remote, desired_capabilites, profile) else: browser = webdriver.Firefox(firefox_profile=profile) return browser - - def _make_ie(self , remote , desired_capabilities , profile_dir): - return self._generic_make_browser(webdriver.Ie, + + def _make_ie(self, remote, desired_capabilities, profile_dir): + return self._generic_make_browser(webdriver.Ie, webdriver.DesiredCapabilities.INTERNETEXPLORER, remote, desired_capabilities) - def _make_chrome(self , remote , desired_capabilities , profile_dir): - return self._generic_make_browser(webdriver.Chrome, + def _make_chrome(self, remote, desired_capabilities, profile_dir): + return self._generic_make_browser(webdriver.Chrome, webdriver.DesiredCapabilities.CHROME, remote, desired_capabilities) - def _make_opera(self , remote , desired_capabilities , profile_dir): - return self._generic_make_browser(webdriver.Opera, + def _make_opera(self, remote, desired_capabilities, profile_dir): + return self._generic_make_browser(webdriver.Opera, webdriver.DesiredCapabilities.OPERA, remote, desired_capabilities) - def _make_htmlunit(self , remote , desired_capabilities , profile_dir): - return self._generic_make_browser(webdriver.Remote, + def _make_htmlunit(self, remote, desired_capabilities, profile_dir): + return self._generic_make_browser(webdriver.Remote, webdriver.DesiredCapabilities.HTMLUNIT, remote, desired_capabilities) - def _make_htmlunitwithjs(self , remote , desired_capabilities , profile_dir): - return self._generic_make_browser(webdriver.Remote, + def _make_htmlunitwithjs(self, remote, desired_capabilities, profile_dir): + return self._generic_make_browser(webdriver.Remote, webdriver.DesiredCapabilities.HTMLUNITWITHJS, remote, desired_capabilities) - - def _generic_make_browser(self, webdriver_type , desired_cap_type, remote_url, desired_caps): - '''most of the make browser functions just call this function which creates the + def _generic_make_browser(self, webdriver_type, desired_cap_type, remote_url, desired_caps): + '''most of the make browser functions just call this function which creates the appropriate web-driver''' - if not remote_url: + if not remote_url: browser = webdriver_type() else: - browser = self._create_remote_web_driver(desired_cap_type,remote_url , desired_caps) + browser = self._create_remote_web_driver(desired_cap_type, remote_url, desired_caps) return browser - - def _create_remote_web_driver(self , capabilities_type , remote_url , desired_capabilities=None , profile=None): + def _create_remote_web_driver(self, capabilities_type, remote_url, desired_capabilities=None, profile=None): '''parses the string based desired_capabilities which should be in the form key1:val1,key2:val2 and creates the associated remote web driver''' - desired_cap = self._create_desired_capabilities(capabilities_type , desired_capabilities) - return webdriver.Remote(desired_capabilities=desired_cap , command_executor=str(remote_url) , browser_profile=profile) - + desired_cap = self._create_desired_capabilities(capabilities_type, desired_capabilities) + return webdriver.Remote(desired_capabilities=desired_cap, command_executor=str(remote_url), browser_profile=profile) def _create_desired_capabilities(self, capabilities_type, capabilities_string): desired_capabilities = capabilities_type @@ -468,4 +463,3 @@ def _create_desired_capabilities(self, capabilities_type, capabilities_string): (key, value) = cap.split(":") desired_capabilities[key.strip()] = value.strip() return desired_capabilities - diff --git a/src/Selenium2Library/keywords/_cookie.py b/src/Selenium2Library/keywords/_cookie.py index 2eff17196..343cdaffa 100644 --- a/src/Selenium2Library/keywords/_cookie.py +++ b/src/Selenium2Library/keywords/_cookie.py @@ -1,5 +1,6 @@ from keywordgroup import KeywordGroup + class _CookieKeywords(KeywordGroup): def delete_all_cookies(self): diff --git a/src/Selenium2Library/keywords/_element.py b/src/Selenium2Library/keywords/_element.py index b80031f58..3121e68f3 100644 --- a/src/Selenium2Library/keywords/_element.py +++ b/src/Selenium2Library/keywords/_element.py @@ -4,6 +4,7 @@ from Selenium2Library.locators import ElementFinder from keywordgroup import KeywordGroup + class _ElementKeywords(KeywordGroup): def __init__(self): @@ -287,11 +288,10 @@ def drag_and_drop(self, source, target): Examples: | Drag And Drop | elem1 | elem2 | # Move elem1 over elem2. | """ - src_elem = self._element_find(source,True,True) - trg_elem = self._element_find(target,True,True) + src_elem = self._element_find(source, True, True) + trg_elem = self._element_find(target, True, True) ActionChains(self._current_browser()).drag_and_drop(src_elem, trg_elem).perform() - def drag_and_drop_by_offset(self, source, xoffset, yoffset): """Drags element identified with `source` which is a locator. @@ -524,7 +524,7 @@ def xpath_should_match_x_times(self, xpath, expected_xpath_count, message='', lo if int(actual_xpath_count) != int(expected_xpath_count): if not message: message = "Xpath %s should have matched %s times but matched %s times"\ - %(xpath, expected_xpath_count, actual_xpath_count) + % (xpath, expected_xpath_count, actual_xpath_count) self.log_source(loglevel) raise AssertionError(message) self._info("Current page contains %s elements matching '%s'." @@ -538,7 +538,8 @@ def _element_find(self, locator, first_only, required, tag=None): if required and len(elements) == 0: raise ValueError("Element locator '" + locator + "' did not match any elements.") if first_only: - if len(elements) == 0: return None + if len(elements) == 0: + return None return elements[0] return elements @@ -573,7 +574,7 @@ def _is_enabled(self, locator): return True def _is_text_present(self, text): - locator = "xpath=//*[contains(., %s)]" % utils.escape_xpath_value(text); + locator = "xpath=//*[contains(., %s)]" % utils.escape_xpath_value(text) return self._is_element_present(locator) def _is_visible(self, locator): @@ -656,4 +657,3 @@ def _page_should_not_contain_element(self, locator, tag, message, loglevel): raise AssertionError(message) self._info("Current page does not contain %s '%s'." % (element_name, locator)) - diff --git a/src/Selenium2Library/keywords/_formelement.py b/src/Selenium2Library/keywords/_formelement.py index ff9c26b89..af83f278c 100644 --- a/src/Selenium2Library/keywords/_formelement.py +++ b/src/Selenium2Library/keywords/_formelement.py @@ -1,6 +1,7 @@ import os from keywordgroup import KeywordGroup + class _FormElementKeywords(KeywordGroup): # Public, form @@ -168,7 +169,7 @@ def choose_file(self, locator, file_path): """Inputs the `file_path` into file input field found by `identifier`. This keyword is most often used to input files into upload forms. - The file specified with `file_path` must be available on the same host + The file specified with `file_path` must be available on the same host where the Selenium Server is running. Example: @@ -244,7 +245,8 @@ def textfield_value_should_be(self, locator, expected, message=''): for details about locating elements. """ element = self._element_find(locator, True, False, 'text field') - if element is None: element = self._element_find(locator, True, False, 'file upload') + if element is None: + element = self._element_find(locator, True, False, 'file upload') actual = element.get_attribute('value') if element is not None else None if actual != expected: if not message: @@ -328,4 +330,4 @@ def _is_form_element(self, element): if element is None: return False tag = element.tag_name.lower() - return tag == 'input' or tag == 'select' or tag == 'textarea' or tag == 'button' \ No newline at end of file + return tag == 'input' or tag == 'select' or tag == 'textarea' or tag == 'button' diff --git a/src/Selenium2Library/keywords/_javascript.py b/src/Selenium2Library/keywords/_javascript.py index d9824ec5f..7307d0187 100644 --- a/src/Selenium2Library/keywords/_javascript.py +++ b/src/Selenium2Library/keywords/_javascript.py @@ -2,6 +2,7 @@ from selenium.common.exceptions import WebDriverException from keywordgroup import KeywordGroup + class _JavaScriptKeywords(KeywordGroup): def __init__(self): @@ -34,10 +35,10 @@ def choose_ok_on_next_confirmation(self): return true, as if the user had manually clicked OK, so you shouldn't need to use this command unless for some reason you need to change your mind prior to the next confirmation. After any confirmation, Selenium will resume using the - default behavior for future confirmations, automatically returning + default behavior for future confirmations, automatically returning true (OK) unless/until you explicitly use `Choose Cancel On Next Confirmation` for each confirmation. - + Note that every time a confirmation comes up, you must consume it by using a keywords such as `Get Alert Message`, or else the following selenium operations will fail. @@ -68,7 +69,7 @@ def confirm_action(self): def execute_javascript(self, *code): """Executes the given JavaScript code. - `code` may contain multiple lines of code but must contain a + `code` may contain multiple lines of code but must contain a return statement (with the value to be returned) at the end. `code` may be divided into multiple cells in the test data. In that @@ -94,7 +95,7 @@ def execute_javascript(self, *code): def execute_async_javascript(self, *code): """Executes asynchronous JavaScript code. - `code` may contain multiple lines of code but must contain a + `code` may contain multiple lines of code but must contain a return statement (with the value to be returned) at the end. `code` may be divided into multiple cells in the test data. In that @@ -132,9 +133,11 @@ def _close_alert(self, confirm=False): alert = None try: alert = self._current_browser().switch_to_alert() - text = ' '.join(alert.text.splitlines()) # collapse new lines chars - if not confirm: alert.dismiss() - else: alert.accept() + text = ' '.join(alert.text.splitlines()) # collapse new lines chars + if not confirm: + alert.dismiss() + else: + alert.accept() return text except WebDriverException: raise RuntimeError('There were no alerts') @@ -149,4 +152,4 @@ def _get_javascript_to_execute(self, code): try: return codefile.read().strip() finally: - codefile.close() \ No newline at end of file + codefile.close() diff --git a/src/Selenium2Library/keywords/_logging.py b/src/Selenium2Library/keywords/_logging.py index bea494247..37b6fb20d 100644 --- a/src/Selenium2Library/keywords/_logging.py +++ b/src/Selenium2Library/keywords/_logging.py @@ -4,6 +4,7 @@ from robot.api import logger from keywordgroup import KeywordGroup + class _LoggingKeywords(KeywordGroup): # Private @@ -25,17 +26,21 @@ def _info(self, message): def _log(self, message, level='INFO'): level = level.upper() - if (level == 'INFO'): self._info(message) - elif (level == 'DEBUG'): self._debug(message) - elif (level == 'WARN'): self._warn(message) - elif (level == 'HTML'): self._html(message) + if (level == 'INFO'): + self._info(message) + elif (level == 'DEBUG'): + self._debug(message) + elif (level == 'WARN'): + self._warn(message) + elif (level == 'HTML'): + self._html(message) def _log_list(self, items, what='item'): - msg = ['Altogether %d %s%s.' % (len(items), what, ['s',''][len(items)==1])] + msg = ['Altogether %d %s%s.' % (len(items), what, ['s', ''][len(items) == 1])] for index, item in enumerate(items): - msg.append('%d: %s' % (index+1, item)) + msg.append('%d: %s' % (index + 1, item)) self._info('\n'.join(msg)) return items def _warn(self, message): - logger.warn(message) \ No newline at end of file + logger.warn(message) diff --git a/src/Selenium2Library/keywords/_runonfailure.py b/src/Selenium2Library/keywords/_runonfailure.py index 4e9057107..9b72916d2 100644 --- a/src/Selenium2Library/keywords/_runonfailure.py +++ b/src/Selenium2Library/keywords/_runonfailure.py @@ -3,6 +3,7 @@ BUILTIN = BuiltIn.BuiltIn() + class _RunOnFailureKeywords(KeywordGroup): def __init__(self): @@ -46,7 +47,7 @@ def register_keyword_to_run_on_failure(self, keyword): self._info('%s will be run on failure.' % new_keyword_text) return old_keyword_text - + # Private def _run_on_failure(self): diff --git a/src/Selenium2Library/keywords/_screenshot.py b/src/Selenium2Library/keywords/_screenshot.py index c6ddf1e4a..b0a8fc770 100644 --- a/src/Selenium2Library/keywords/_screenshot.py +++ b/src/Selenium2Library/keywords/_screenshot.py @@ -2,6 +2,7 @@ import robot from keywordgroup import KeywordGroup + class _ScreenshotKeywords(KeywordGroup): def __init__(self): diff --git a/src/Selenium2Library/keywords/_selectelement.py b/src/Selenium2Library/keywords/_selectelement.py index df6405211..2a10f8212 100644 --- a/src/Selenium2Library/keywords/_selectelement.py +++ b/src/Selenium2Library/keywords/_selectelement.py @@ -2,6 +2,7 @@ from selenium.webdriver.support.ui import Select from keywordgroup import KeywordGroup + class _SelectElementKeywords(KeywordGroup): # Public @@ -181,10 +182,13 @@ def select_from_list(self, locator, *items): option_labels = self._get_labels_for_options(options) for item in items: option_index = None - try: option_index = option_values.index(item) + try: + option_index = option_values.index(item) except: - try: option_index = option_labels.index(item) - except: continue + try: + option_index = option_labels.index(item) + except: + continue select_func(select, options, option_index) def unselect_from_list(self, locator, *items): @@ -214,14 +218,17 @@ def unselect_from_list(self, locator, *items): option_labels = self._get_labels_for_options(options) for item in items: option_index = None - try: option_index = option_values.index(item) + try: + option_index = option_values.index(item) except: - try: option_index = option_labels.index(item) - except: continue + try: + option_index = option_labels.index(item) + except: + continue self._unselect_option_from_multi_select_list(select, options, option_index) # Private - + def _get_labels_for_options(self, options): labels = [] for option in options: @@ -245,11 +252,11 @@ def _get_select_list_options_selected(self, select_list_or_locator): if option.is_selected(): selected.append(option) return select, selected - + def _get_values_for_options(self, options): values = [] for option in options: - values.append(option.get_attribute('value')) + values.append(option.get_attribute('value')) return values def _is_multiselect_list(self, select): @@ -266,7 +273,6 @@ def _select_option_from_single_select_list(self, select, options, index): sel = Select(select) sel.select_by_index(index) - def _unselect_all_options_from_multi_select_list(self, select): self._current_browser().execute_script("arguments[0].selectedIndex = -1;", select) diff --git a/src/Selenium2Library/keywords/_tableelement.py b/src/Selenium2Library/keywords/_tableelement.py index 5306a1158..fd6159233 100644 --- a/src/Selenium2Library/keywords/_tableelement.py +++ b/src/Selenium2Library/keywords/_tableelement.py @@ -5,6 +5,7 @@ from Selenium2Library.locators import TableElementFinder from keywordgroup import KeywordGroup + class _TableElementKeywords(KeywordGroup): def __init__(self): @@ -28,11 +29,14 @@ def get_table_cell(self, table_locator, row, column, loglevel='INFO'): table = self._table_element_finder.find(self._current_browser(), table_locator) if table is not None: rows = table.find_elements_by_xpath("./thead/tr") - if row_index >= len(rows): rows.extend(table.find_elements_by_xpath("./tbody/tr")) - if row_index >= len(rows): rows.extend(table.find_elements_by_xpath("./tfoot/tr")) + if row_index >= len(rows): + rows.extend(table.find_elements_by_xpath("./tbody/tr")) + if row_index >= len(rows): + rows.extend(table.find_elements_by_xpath("./tfoot/tr")) if row_index < len(rows): columns = rows[row_index].find_elements_by_tag_name('th') - if column_index >= len(columns): columns.extend(rows[row_index].find_elements_by_tag_name('td')) + if column_index >= len(columns): + columns.extend(rows[row_index].find_elements_by_tag_name('td')) if column_index < len(columns): return columns[column_index].text self.log_source(loglevel) @@ -158,4 +162,4 @@ def table_should_contain(self, table_locator, expected, loglevel='INFO'): if element is None: self.log_source(loglevel) raise AssertionError("Table identified by '%s' should have contained text '%s'." \ - % (table_locator, expected)) \ No newline at end of file + % (table_locator, expected)) diff --git a/src/Selenium2Library/keywords/_waiting.py b/src/Selenium2Library/keywords/_waiting.py index 28805cece..7df224c08 100644 --- a/src/Selenium2Library/keywords/_waiting.py +++ b/src/Selenium2Library/keywords/_waiting.py @@ -2,6 +2,7 @@ import robot from keywordgroup import KeywordGroup + class _WaitingKeywords(KeywordGroup): # Public @@ -9,10 +10,10 @@ class _WaitingKeywords(KeywordGroup): def wait_for_condition(self, condition, timeout=None, error=None): """Waits until the given `condition` is true or `timeout` expires. - `code` may contain multiple lines of code but must contain a + `code` may contain multiple lines of code but must contain a return statement (with the value to be returned) at the end - The `condition` can be arbitrary JavaScript expression but must contain a + The `condition` can be arbitrary JavaScript expression but must contain a return statement (with the value to be returned) at the end. See `Execute JavaScript` for information about accessing the actual contents of the window through JavaScript. @@ -71,4 +72,4 @@ def _wait_until(self, timeout, error, function, *args): while not function(*args): if time.time() > maxtime: raise AssertionError(error) - time.sleep(0.2) \ No newline at end of file + time.sleep(0.2) diff --git a/src/Selenium2Library/keywords/keywordgroup.py b/src/Selenium2Library/keywords/keywordgroup.py index ff4f319ca..d05090ff5 100644 --- a/src/Selenium2Library/keywords/keywordgroup.py +++ b/src/Selenium2Library/keywords/keywordgroup.py @@ -2,10 +2,11 @@ import inspect try: from decorator import decorator -except SyntaxError: # decorator module requires Python/Jython 2.4+ +except SyntaxError: # decorator module requires Python/Jython 2.4+ decorator = None if sys.platform == 'cli': - decorator = None # decorator module doesn't work with IronPython 2.6 + decorator = None # decorator module doesn't work with IronPython 2.6 + def _run_on_failure_decorator(method, *args, **kwargs): try: @@ -16,6 +17,7 @@ def _run_on_failure_decorator(method, *args, **kwargs): self._run_on_failure() raise + class KeywordGroupMetaClass(type): def __new__(cls, clsname, bases, dict): if decorator: @@ -24,5 +26,6 @@ def __new__(cls, clsname, bases, dict): dict[name] = decorator(_run_on_failure_decorator, method) return type.__new__(cls, clsname, bases, dict) + class KeywordGroup(object): __metaclass__ = KeywordGroupMetaClass diff --git a/src/Selenium2Library/locators/__init__.py b/src/Selenium2Library/locators/__init__.py index c7a5d18a7..8911e606f 100644 --- a/src/Selenium2Library/locators/__init__.py +++ b/src/Selenium2Library/locators/__init__.py @@ -3,7 +3,7 @@ from windowmanager import WindowManager __all__ = [ - "ElementFinder", - "TableElementFinder", + "ElementFinder", + "TableElementFinder", "WindowManager" -] \ No newline at end of file +] diff --git a/src/Selenium2Library/locators/elementfinder.py b/src/Selenium2Library/locators/elementfinder.py index 821d183f8..cfcbeff4e 100644 --- a/src/Selenium2Library/locators/elementfinder.py +++ b/src/Selenium2Library/locators/elementfinder.py @@ -1,5 +1,6 @@ from Selenium2Library import utils + class ElementFinder(object): def __init__(self): @@ -105,7 +106,8 @@ def _find_by_key_attrs(self, browser, criteria, tag, constraints): } def _get_tag_and_constraints(self, tag): - if tag is None: return None, {} + if tag is None: + return None, {} tag = tag.lower() constraints = {} @@ -138,7 +140,8 @@ def _element_matches(self, element, tag, constraints): return True def _filter_elements(self, elements, tag, constraints): - if tag is None: return elements + if tag is None: + return elements return filter( lambda element: self._element_matches(element, tag, constraints), elements) diff --git a/src/Selenium2Library/locators/tableelementfinder.py b/src/Selenium2Library/locators/tableelementfinder.py index 47abef6ea..34f58948b 100644 --- a/src/Selenium2Library/locators/tableelementfinder.py +++ b/src/Selenium2Library/locators/tableelementfinder.py @@ -2,6 +2,7 @@ from Selenium2Library import utils from elementfinder import ElementFinder + class TableElementFinder(object): def __init__(self, element_finder=None): @@ -23,7 +24,7 @@ def __init__(self, element_finder=None): ('xpath', 'footer'): ['//tfoot//td'], ('xpath', 'row'): ['//tr[%s]//*'], ('xpath', 'col'): ['//tr//*[self::td or self::th][%s]'] - }; + } def find(self, browser, table_locator): locators = self._parse_table_locator(table_locator, 'default') @@ -69,7 +70,8 @@ def _search_in_locators(self, browser, locators, content): for locator in locators: elements = self._element_finder.find(browser, locator) for element in elements: - if content is None: return element + if content is None: + return element element_text = element.text if element_text and content in element_text: return element diff --git a/src/Selenium2Library/locators/windowmanager.py b/src/Selenium2Library/locators/windowmanager.py index c03fac8eb..e53f02ac2 100644 --- a/src/Selenium2Library/locators/windowmanager.py +++ b/src/Selenium2Library/locators/windowmanager.py @@ -3,6 +3,7 @@ from selenium.webdriver.remote.webdriver import WebDriver from selenium.common.exceptions import NoSuchWindowException + class WindowManager(object): def __init__(self): @@ -14,13 +15,13 @@ def __init__(self): } def get_window_ids(self, browser): - return [ window_info[1] for window_info in self._get_window_infos(browser) ] + return [window_info[1] for window_info in self._get_window_infos(browser)] def get_window_names(self, browser): - return [ window_info[2] for window_info in self._get_window_infos(browser) ] + return [window_info[2] for window_info in self._get_window_infos(browser)] def get_window_titles(self, browser): - return [ window_info[3] for window_info in self._get_window_infos(browser) ] + return [window_info[3] for window_info in self._get_window_infos(browser)] def select(self, browser, locator): assert browser is not None @@ -59,12 +60,14 @@ def _select_by_default(self, browser, criteria): try: self._select_by_name(browser, criteria) return - except ValueError: pass + except ValueError: + pass try: self._select_by_title(browser, criteria) return - except ValueError: pass + except ValueError: + pass raise ValueError("Unable to locate window with name or title '" + criteria + "'") @@ -74,7 +77,7 @@ def _parse_locator(self, locator): prefix = None criteria = locator if locator is not None and len(locator) > 0: - locator_parts = locator.partition('=') + locator_parts = locator.partition('=') if len(locator_parts[1]) > 0: prefix = locator_parts[0].strip().lower() criteria = locator_parts[2].strip() diff --git a/src/Selenium2Library/utils/__init__.py b/src/Selenium2Library/utils/__init__.py index c73348123..acd7c04b1 100644 --- a/src/Selenium2Library/utils/__init__.py +++ b/src/Selenium2Library/utils/__init__.py @@ -10,18 +10,19 @@ "BrowserCache" ] -# Public +# Public def get_child_packages_in(root_dir, include_root_package_name=True, exclusions=None): packages = [] root_package_str = os.path.basename(root_dir) + '.' if include_root_package_name else "" _discover_child_package_dirs( root_dir, _clean_exclusions(exclusions), - lambda abs_path, relative_path, name: + lambda abs_path, relative_path, name: packages.append(root_package_str + relative_path.replace(os.sep, '.'))) return packages + def get_module_names_under(root_dir, include_root_package_name=True, exclusions=None, pattern=None): module_names = [] root_package_str = os.path.basename(root_dir) + '.' if include_root_package_name else "" @@ -29,16 +30,18 @@ def get_module_names_under(root_dir, include_root_package_name=True, exclusions= root_dir, _clean_exclusions(exclusions), pattern if pattern is not None else "*.*", - lambda abs_path, relative_path, name: + lambda abs_path, relative_path, name: module_names.append(root_package_str + os.path.splitext(relative_path)[0].replace(os.sep, '.'))) return module_names + def import_modules_under(root_dir, include_root_package_name=True, exclusions=None, pattern=None): module_names = get_module_names_under(root_dir, include_root_package_name, exclusions, pattern) - modules = [ __import__(module_name, globals(), locals(), ['*'], -1) - for module_name in module_names ] + modules = [__import__(module_name, globals(), locals(), ['*'], -1) + for module_name in module_names] return (module_names, modules) + def escape_xpath_value(value): value = unicode(value) if '"' in value and '\'' in value: @@ -48,15 +51,18 @@ def escape_xpath_value(value): return "\"%s\"" % value return "'%s'" % value -# Private +# Private def _clean_exclusions(exclusions): - if exclusions is None: exclusions = [] - if not isinstance(exclusions, list): exclusions = [ exclusions ] - exclusions = [ os.sep + exclusion.lower().strip(os.sep) + os.sep - for exclusion in exclusions ] + if exclusions is None: + exclusions = [] + if not isinstance(exclusions, list): + exclusions = [exclusions] + exclusions = [os.sep + exclusion.lower().strip(os.sep) + os.sep + for exclusion in exclusions] return exclusions + def _discover_child_package_dirs(root_dir, exclusions, callback, relative_dir=None): relative_dir = relative_dir if relative_dir is not None else '' abs_dir = os.path.join(root_dir, relative_dir) @@ -65,12 +71,13 @@ def _discover_child_package_dirs(root_dir, exclusions, callback, relative_dir=No item_abs_path = os.path.join(root_dir, item_relative_path) if os.path.isdir(item_abs_path): if os.path.exists(os.path.join(item_abs_path, "__init__.py")): - exclusion_matches = [ exclusion for exclusion in exclusions - if os.sep + item_relative_path.lower() + os.sep == exclusion ] + exclusion_matches = [exclusion for exclusion in exclusions + if os.sep + item_relative_path.lower() + os.sep == exclusion] if not exclusion_matches: callback(item_abs_path, item_relative_path, item) _discover_child_package_dirs(root_dir, exclusions, callback, item_relative_path) + def _discover_module_files_in(root_dir, exclusions, pattern, callback): def find_matching_files(relative_dir): abs_dir = os.path.join(root_dir, relative_dir) diff --git a/src/Selenium2Library/utils/browsercache.py b/src/Selenium2Library/utils/browsercache.py index f05f2f055..f155626a7 100644 --- a/src/Selenium2Library/utils/browsercache.py +++ b/src/Selenium2Library/utils/browsercache.py @@ -1,5 +1,6 @@ from robot.utils import ConnectionCache + class BrowserCache(ConnectionCache): def __init__(self): @@ -16,7 +17,7 @@ def get_open_browsers(self): if browser not in self._closed: open_browsers.append(browser) return open_browsers - + def close(self): if self.current: browser = self.current diff --git a/src/Selenium2Library/webdrivermonkeypatches.py b/src/Selenium2Library/webdrivermonkeypatches.py index 88474f06e..95c816d56 100644 --- a/src/Selenium2Library/webdrivermonkeypatches.py +++ b/src/Selenium2Library/webdrivermonkeypatches.py @@ -3,6 +3,7 @@ from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver from locators import WindowManager + class WebDriverMonkeyPatches: RemoteWebDriver._base_execute = RemoteWebDriver.execute @@ -22,8 +23,8 @@ def get_current_window_handle(self): def get_current_window_info(self): atts = self.execute_script("return [ window.id, window.name, document.title, document.location ];") - atts = [ att if att is not None and len(att) else 'undefined' - for att in atts ] + atts = [att if att is not None and len(att) else 'undefined' + for att in atts] return (self.current_window_handle, atts[0], atts[1], atts[2], atts[3]) def get_page_source(self): @@ -36,7 +37,7 @@ def get_window_handles(self): return self.window_handles def current_window_is_main(self): - return self.current_window_handle == self.window_handles[0]; + return self.current_window_handle == self.window_handles[0] def set_speed(self, seconds): self._speed = seconds