Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
BaseCase.add_text
(self, selector, text, by=By.CSS_SELECTOR, timeout=None)
The more-reliable version of driver.send_keys() Similar to update_text(), but won't clear the text field first.
The more-reliable version of driver.send_keys() Similar to update_text(), but won't clear the text field first.
def add_text(self, selector, text, by=By.CSS_SELECTOR, timeout=None): """ The more-reliable version of driver.send_keys() Similar to update_text(), but won't clear the text field first. """ if not timeout: timeout = settings.LARGE_TIMEOUT if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT: timeout = self.__get_new_timeout(timeout) selector, by = self.__recalculate_selector(selector, by) element = self.wait_for_element_visible( selector, by=by, timeout=timeout) self.__demo_mode_highlight_if_active(selector, by) if not self.demo_mode: self.__scroll_to_element(element, selector, by) pre_action_url = self.driver.current_url try: if not text.endswith('\n'): element.send_keys(text) else: element.send_keys(text[:-1]) element.send_keys(Keys.RETURN) if settings.WAIT_FOR_RSC_ON_PAGE_LOADS: self.wait_for_ready_state_complete() except (StaleElementReferenceException, ENI_Exception): self.wait_for_ready_state_complete() time.sleep(0.06) element = self.wait_for_element_visible( selector, by=by, timeout=timeout) if not text.endswith('\n'): element.send_keys(text) else: element.send_keys(text[:-1]) element.send_keys(Keys.RETURN) if settings.WAIT_FOR_RSC_ON_PAGE_LOADS: self.wait_for_ready_state_complete() except Exception: exc_message = self.__get_improved_exception_message() raise Exception(exc_message) if self.demo_mode: if self.driver.current_url != pre_action_url: self.__demo_mode_pause_if_active() else: self.__demo_mode_pause_if_active(tiny=True) elif self.slow_mode: self.__slow_mode_pause_if_active()
[ "def", "add_text", "(", "self", ",", "selector", ",", "text", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "LARGE_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "LARGE_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "element", "=", "self", ".", "wait_for_element_visible", "(", "selector", ",", "by", "=", "by", ",", "timeout", "=", "timeout", ")", "self", ".", "__demo_mode_highlight_if_active", "(", "selector", ",", "by", ")", "if", "not", "self", ".", "demo_mode", ":", "self", ".", "__scroll_to_element", "(", "element", ",", "selector", ",", "by", ")", "pre_action_url", "=", "self", ".", "driver", ".", "current_url", "try", ":", "if", "not", "text", ".", "endswith", "(", "'\\n'", ")", ":", "element", ".", "send_keys", "(", "text", ")", "else", ":", "element", ".", "send_keys", "(", "text", "[", ":", "-", "1", "]", ")", "element", ".", "send_keys", "(", "Keys", ".", "RETURN", ")", "if", "settings", ".", "WAIT_FOR_RSC_ON_PAGE_LOADS", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "except", "(", "StaleElementReferenceException", ",", "ENI_Exception", ")", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "time", ".", "sleep", "(", "0.06", ")", "element", "=", "self", ".", "wait_for_element_visible", "(", "selector", ",", "by", "=", "by", ",", "timeout", "=", "timeout", ")", "if", "not", "text", ".", "endswith", "(", "'\\n'", ")", ":", "element", ".", "send_keys", "(", "text", ")", "else", ":", "element", ".", "send_keys", "(", "text", "[", ":", "-", "1", "]", ")", "element", ".", "send_keys", "(", "Keys", ".", "RETURN", ")", "if", "settings", ".", "WAIT_FOR_RSC_ON_PAGE_LOADS", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "except", "Exception", ":", "exc_message", "=", "self", ".", "__get_improved_exception_message", "(", ")", "raise", "Exception", "(", "exc_message", ")", "if", "self", ".", "demo_mode", ":", "if", "self", ".", "driver", ".", "current_url", "!=", "pre_action_url", ":", "self", ".", "__demo_mode_pause_if_active", "(", ")", "else", ":", "self", ".", "__demo_mode_pause_if_active", "(", "tiny", "=", "True", ")", "elif", "self", ".", "slow_mode", ":", "self", ".", "__slow_mode_pause_if_active", "(", ")" ]
[ 330, 4 ]
[ 373, 46 ]
python
en
['en', 'en', 'en']
True
BaseCase.type
(self, selector, text, by=By.CSS_SELECTOR, timeout=None, retry=False)
Same as self.update_text() This method updates an element's text field with new text. Has multiple parts: * Waits for the element to be visible. * Waits for the element to be interactive. * Clears the text field. * Types in the new text. * Hits Enter/Submit (if the text ends in "\n"). @Params selector - the selector of the text field text - the new text to type into the text field by - the type of selector to search by (Default: CSS Selector) timeout - how long to wait for the selector to be visible retry - if True, use JS if the Selenium text update fails DO NOT confuse self.type() with Python type()! They are different!
Same as self.update_text() This method updates an element's text field with new text. Has multiple parts: * Waits for the element to be visible. * Waits for the element to be interactive. * Clears the text field. * Types in the new text. * Hits Enter/Submit (if the text ends in "\n").
def type(self, selector, text, by=By.CSS_SELECTOR, timeout=None, retry=False): """ Same as self.update_text() This method updates an element's text field with new text. Has multiple parts: * Waits for the element to be visible. * Waits for the element to be interactive. * Clears the text field. * Types in the new text. * Hits Enter/Submit (if the text ends in "\n"). @Params selector - the selector of the text field text - the new text to type into the text field by - the type of selector to search by (Default: CSS Selector) timeout - how long to wait for the selector to be visible retry - if True, use JS if the Selenium text update fails DO NOT confuse self.type() with Python type()! They are different! """ if not timeout: timeout = settings.LARGE_TIMEOUT if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT: timeout = self.__get_new_timeout(timeout) selector, by = self.__recalculate_selector(selector, by) self.update_text(selector, text, by=by, timeout=timeout, retry=retry)
[ "def", "type", "(", "self", ",", "selector", ",", "text", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ",", "retry", "=", "False", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "LARGE_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "LARGE_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "self", ".", "update_text", "(", "selector", ",", "text", ",", "by", "=", "by", ",", "timeout", "=", "timeout", ",", "retry", "=", "retry", ")" ]
[ 375, 4 ]
[ 398, 77 ]
python
en
['en', 'en', 'en']
True
BaseCase.submit
(self, selector, by=By.CSS_SELECTOR)
Alternative to self.driver.find_element_by_*(SELECTOR).submit()
Alternative to self.driver.find_element_by_*(SELECTOR).submit()
def submit(self, selector, by=By.CSS_SELECTOR): """ Alternative to self.driver.find_element_by_*(SELECTOR).submit() """ selector, by = self.__recalculate_selector(selector, by) element = self.wait_for_element_visible( selector, by=by, timeout=settings.SMALL_TIMEOUT) element.submit() self.__demo_mode_pause_if_active()
[ "def", "submit", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "element", "=", "self", ".", "wait_for_element_visible", "(", "selector", ",", "by", "=", "by", ",", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", ")", "element", ".", "submit", "(", ")", "self", ".", "__demo_mode_pause_if_active", "(", ")" ]
[ 400, 4 ]
[ 406, 42 ]
python
en
['en', 'en', 'en']
True
BaseCase.refresh
(self)
The shorter version of self.refresh_page()
The shorter version of self.refresh_page()
def refresh(self): """ The shorter version of self.refresh_page() """ self.refresh_page()
[ "def", "refresh", "(", "self", ")", ":", "self", ".", "refresh_page", "(", ")" ]
[ 413, 4 ]
[ 415, 27 ]
python
en
['en', 'en', 'en']
True
BaseCase.get_title
(self)
The shorter version of self.get_page_title()
The shorter version of self.get_page_title()
def get_title(self): """ The shorter version of self.get_page_title() """ return self.get_page_title()
[ "def", "get_title", "(", "self", ")", ":", "return", "self", ".", "get_page_title", "(", ")" ]
[ 437, 4 ]
[ 439, 36 ]
python
en
['en', 'en', 'en']
True
BaseCase.is_link_text_present
(self, link_text)
Returns True if the link text appears in the HTML of the page. The element doesn't need to be visible, such as elements hidden inside a dropdown selection.
Returns True if the link text appears in the HTML of the page. The element doesn't need to be visible, such as elements hidden inside a dropdown selection.
def is_link_text_present(self, link_text): """ Returns True if the link text appears in the HTML of the page. The element doesn't need to be visible, such as elements hidden inside a dropdown selection. """ soup = self.get_beautiful_soup() html_links = soup.find_all('a') for html_link in html_links: if html_link.text.strip() == link_text.strip(): return True return False
[ "def", "is_link_text_present", "(", "self", ",", "link_text", ")", ":", "soup", "=", "self", ".", "get_beautiful_soup", "(", ")", "html_links", "=", "soup", ".", "find_all", "(", "'a'", ")", "for", "html_link", "in", "html_links", ":", "if", "html_link", ".", "text", ".", "strip", "(", ")", "==", "link_text", ".", "strip", "(", ")", ":", "return", "True", "return", "False" ]
[ 487, 4 ]
[ 496, 20 ]
python
en
['en', 'en', 'en']
True
BaseCase.is_partial_link_text_present
(self, link_text)
Returns True if the partial link appears in the HTML of the page. The element doesn't need to be visible, such as elements hidden inside a dropdown selection.
Returns True if the partial link appears in the HTML of the page. The element doesn't need to be visible, such as elements hidden inside a dropdown selection.
def is_partial_link_text_present(self, link_text): """ Returns True if the partial link appears in the HTML of the page. The element doesn't need to be visible, such as elements hidden inside a dropdown selection. """ soup = self.get_beautiful_soup() html_links = soup.find_all('a') for html_link in html_links: if link_text.strip() in html_link.text.strip(): return True return False
[ "def", "is_partial_link_text_present", "(", "self", ",", "link_text", ")", ":", "soup", "=", "self", ".", "get_beautiful_soup", "(", ")", "html_links", "=", "soup", ".", "find_all", "(", "'a'", ")", "for", "html_link", "in", "html_links", ":", "if", "link_text", ".", "strip", "(", ")", "in", "html_link", ".", "text", ".", "strip", "(", ")", ":", "return", "True", "return", "False" ]
[ 498, 4 ]
[ 507, 20 ]
python
en
['en', 'en', 'en']
True
BaseCase.get_link_attribute
(self, link_text, attribute, hard_fail=True)
Finds a link by link text and then returns the attribute's value. If the link text or attribute cannot be found, an exception will get raised if hard_fail is True (otherwise None is returned).
Finds a link by link text and then returns the attribute's value. If the link text or attribute cannot be found, an exception will get raised if hard_fail is True (otherwise None is returned).
def get_link_attribute(self, link_text, attribute, hard_fail=True): """ Finds a link by link text and then returns the attribute's value. If the link text or attribute cannot be found, an exception will get raised if hard_fail is True (otherwise None is returned). """ soup = self.get_beautiful_soup() html_links = soup.find_all('a') for html_link in html_links: if html_link.text.strip() == link_text.strip(): if html_link.has_attr(attribute): attribute_value = html_link.get(attribute) return attribute_value if hard_fail: raise Exception( 'Unable to find attribute {%s} from link text {%s}!' % (attribute, link_text)) else: return None if hard_fail: raise Exception("Link text {%s} was not found!" % link_text) else: return None
[ "def", "get_link_attribute", "(", "self", ",", "link_text", ",", "attribute", ",", "hard_fail", "=", "True", ")", ":", "soup", "=", "self", ".", "get_beautiful_soup", "(", ")", "html_links", "=", "soup", ".", "find_all", "(", "'a'", ")", "for", "html_link", "in", "html_links", ":", "if", "html_link", ".", "text", ".", "strip", "(", ")", "==", "link_text", ".", "strip", "(", ")", ":", "if", "html_link", ".", "has_attr", "(", "attribute", ")", ":", "attribute_value", "=", "html_link", ".", "get", "(", "attribute", ")", "return", "attribute_value", "if", "hard_fail", ":", "raise", "Exception", "(", "'Unable to find attribute {%s} from link text {%s}!'", "%", "(", "attribute", ",", "link_text", ")", ")", "else", ":", "return", "None", "if", "hard_fail", ":", "raise", "Exception", "(", "\"Link text {%s} was not found!\"", "%", "link_text", ")", "else", ":", "return", "None" ]
[ 509, 4 ]
[ 529, 23 ]
python
en
['en', 'en', 'en']
True
BaseCase.get_link_text_attribute
(self, link_text, attribute, hard_fail=True)
Same as self.get_link_attribute() Finds a link by link text and then returns the attribute's value. If the link text or attribute cannot be found, an exception will get raised if hard_fail is True (otherwise None is returned).
Same as self.get_link_attribute() Finds a link by link text and then returns the attribute's value. If the link text or attribute cannot be found, an exception will get raised if hard_fail is True (otherwise None is returned).
def get_link_text_attribute(self, link_text, attribute, hard_fail=True): """ Same as self.get_link_attribute() Finds a link by link text and then returns the attribute's value. If the link text or attribute cannot be found, an exception will get raised if hard_fail is True (otherwise None is returned). """ return self.get_link_attribute(link_text, attribute, hard_fail)
[ "def", "get_link_text_attribute", "(", "self", ",", "link_text", ",", "attribute", ",", "hard_fail", "=", "True", ")", ":", "return", "self", ".", "get_link_attribute", "(", "link_text", ",", "attribute", ",", "hard_fail", ")" ]
[ 531, 4 ]
[ 536, 71 ]
python
en
['en', 'af', 'en']
True
BaseCase.get_partial_link_text_attribute
(self, link_text, attribute, hard_fail=True)
Finds a link by partial link text and then returns the attribute's value. If the partial link text or attribute cannot be found, an exception will get raised if hard_fail is True (otherwise None is returned).
Finds a link by partial link text and then returns the attribute's value. If the partial link text or attribute cannot be found, an exception will get raised if hard_fail is True (otherwise None is returned).
def get_partial_link_text_attribute(self, link_text, attribute, hard_fail=True): """ Finds a link by partial link text and then returns the attribute's value. If the partial link text or attribute cannot be found, an exception will get raised if hard_fail is True (otherwise None is returned). """ soup = self.get_beautiful_soup() html_links = soup.find_all('a') for html_link in html_links: if link_text.strip() in html_link.text.strip(): if html_link.has_attr(attribute): attribute_value = html_link.get(attribute) return attribute_value if hard_fail: raise Exception( 'Unable to find attribute {%s} from ' 'partial link text {%s}!' % (attribute, link_text)) else: return None if hard_fail: raise Exception( "Partial Link text {%s} was not found!" % link_text) else: return None
[ "def", "get_partial_link_text_attribute", "(", "self", ",", "link_text", ",", "attribute", ",", "hard_fail", "=", "True", ")", ":", "soup", "=", "self", ".", "get_beautiful_soup", "(", ")", "html_links", "=", "soup", ".", "find_all", "(", "'a'", ")", "for", "html_link", "in", "html_links", ":", "if", "link_text", ".", "strip", "(", ")", "in", "html_link", ".", "text", ".", "strip", "(", ")", ":", "if", "html_link", ".", "has_attr", "(", "attribute", ")", ":", "attribute_value", "=", "html_link", ".", "get", "(", "attribute", ")", "return", "attribute_value", "if", "hard_fail", ":", "raise", "Exception", "(", "'Unable to find attribute {%s} from '", "'partial link text {%s}!'", "%", "(", "attribute", ",", "link_text", ")", ")", "else", ":", "return", "None", "if", "hard_fail", ":", "raise", "Exception", "(", "\"Partial Link text {%s} was not found!\"", "%", "link_text", ")", "else", ":", "return", "None" ]
[ 538, 4 ]
[ 562, 23 ]
python
en
['en', 'en', 'en']
True
BaseCase.click_link_text
(self, link_text, timeout=None)
This method clicks link text on a page
This method clicks link text on a page
def click_link_text(self, link_text, timeout=None): """ This method clicks link text on a page """ # If using phantomjs, might need to extract and open the link directly if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) if self.browser == 'phantomjs': if self.is_link_text_visible(link_text): element = self.wait_for_link_text_visible( link_text, timeout=timeout) element.click() return self.open(self.__get_href_from_link_text(link_text)) return if self.browser == "safari": self.__jquery_click(link_text, by=By.LINK_TEXT) return if not self.is_link_text_present(link_text): self.wait_for_link_text_present(link_text, timeout=timeout) pre_action_url = self.get_current_url() try: element = self.wait_for_link_text_visible( link_text, timeout=0.2) self.__demo_mode_highlight_if_active(link_text, by=By.LINK_TEXT) try: element.click() except (StaleElementReferenceException, ENI_Exception): self.wait_for_ready_state_complete() time.sleep(0.05) element = self.wait_for_link_text_visible( link_text, timeout=timeout) element.click() except Exception: found_css = False text_id = self.get_link_attribute(link_text, "id", False) if text_id: link_css = '[id="%s"]' % link_text found_css = True if not found_css: href = self.__get_href_from_link_text(link_text, False) if href: if href.startswith('/') or page_utils.is_valid_url(href): link_css = '[href="%s"]' % href found_css = True if not found_css: ngclick = self.get_link_attribute(link_text, "ng-click", False) if ngclick: link_css = '[ng-click="%s"]' % ngclick found_css = True if not found_css: onclick = self.get_link_attribute(link_text, "onclick", False) if onclick: link_css = '[onclick="%s"]' % onclick found_css = True success = False if found_css: if self.is_element_visible(link_css): self.click(link_css) success = True else: # The link text might be hidden under a dropdown menu success = self.__click_dropdown_link_text( link_text, link_css) if not success: element = self.wait_for_link_text_visible( link_text, timeout=settings.MINI_TIMEOUT) element.click() if settings.WAIT_FOR_RSC_ON_CLICKS: self.wait_for_ready_state_complete() if self.demo_mode: if self.driver.current_url != pre_action_url: self.__demo_mode_pause_if_active() else: self.__demo_mode_pause_if_active(tiny=True) elif self.slow_mode: self.__slow_mode_pause_if_active()
[ "def", "click_link_text", "(", "self", ",", "link_text", ",", "timeout", "=", "None", ")", ":", "# If using phantomjs, might need to extract and open the link directly", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "if", "self", ".", "browser", "==", "'phantomjs'", ":", "if", "self", ".", "is_link_text_visible", "(", "link_text", ")", ":", "element", "=", "self", ".", "wait_for_link_text_visible", "(", "link_text", ",", "timeout", "=", "timeout", ")", "element", ".", "click", "(", ")", "return", "self", ".", "open", "(", "self", ".", "__get_href_from_link_text", "(", "link_text", ")", ")", "return", "if", "self", ".", "browser", "==", "\"safari\"", ":", "self", ".", "__jquery_click", "(", "link_text", ",", "by", "=", "By", ".", "LINK_TEXT", ")", "return", "if", "not", "self", ".", "is_link_text_present", "(", "link_text", ")", ":", "self", ".", "wait_for_link_text_present", "(", "link_text", ",", "timeout", "=", "timeout", ")", "pre_action_url", "=", "self", ".", "get_current_url", "(", ")", "try", ":", "element", "=", "self", ".", "wait_for_link_text_visible", "(", "link_text", ",", "timeout", "=", "0.2", ")", "self", ".", "__demo_mode_highlight_if_active", "(", "link_text", ",", "by", "=", "By", ".", "LINK_TEXT", ")", "try", ":", "element", ".", "click", "(", ")", "except", "(", "StaleElementReferenceException", ",", "ENI_Exception", ")", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "time", ".", "sleep", "(", "0.05", ")", "element", "=", "self", ".", "wait_for_link_text_visible", "(", "link_text", ",", "timeout", "=", "timeout", ")", "element", ".", "click", "(", ")", "except", "Exception", ":", "found_css", "=", "False", "text_id", "=", "self", ".", "get_link_attribute", "(", "link_text", ",", "\"id\"", ",", "False", ")", "if", "text_id", ":", "link_css", "=", "'[id=\"%s\"]'", "%", "link_text", "found_css", "=", "True", "if", "not", "found_css", ":", "href", "=", "self", ".", "__get_href_from_link_text", "(", "link_text", ",", "False", ")", "if", "href", ":", "if", "href", ".", "startswith", "(", "'/'", ")", "or", "page_utils", ".", "is_valid_url", "(", "href", ")", ":", "link_css", "=", "'[href=\"%s\"]'", "%", "href", "found_css", "=", "True", "if", "not", "found_css", ":", "ngclick", "=", "self", ".", "get_link_attribute", "(", "link_text", ",", "\"ng-click\"", ",", "False", ")", "if", "ngclick", ":", "link_css", "=", "'[ng-click=\"%s\"]'", "%", "ngclick", "found_css", "=", "True", "if", "not", "found_css", ":", "onclick", "=", "self", ".", "get_link_attribute", "(", "link_text", ",", "\"onclick\"", ",", "False", ")", "if", "onclick", ":", "link_css", "=", "'[onclick=\"%s\"]'", "%", "onclick", "found_css", "=", "True", "success", "=", "False", "if", "found_css", ":", "if", "self", ".", "is_element_visible", "(", "link_css", ")", ":", "self", ".", "click", "(", "link_css", ")", "success", "=", "True", "else", ":", "# The link text might be hidden under a dropdown menu", "success", "=", "self", ".", "__click_dropdown_link_text", "(", "link_text", ",", "link_css", ")", "if", "not", "success", ":", "element", "=", "self", ".", "wait_for_link_text_visible", "(", "link_text", ",", "timeout", "=", "settings", ".", "MINI_TIMEOUT", ")", "element", ".", "click", "(", ")", "if", "settings", ".", "WAIT_FOR_RSC_ON_CLICKS", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "if", "self", ".", "demo_mode", ":", "if", "self", ".", "driver", ".", "current_url", "!=", "pre_action_url", ":", "self", ".", "__demo_mode_pause_if_active", "(", ")", "else", ":", "self", ".", "__demo_mode_pause_if_active", "(", "tiny", "=", "True", ")", "elif", "self", ".", "slow_mode", ":", "self", ".", "__slow_mode_pause_if_active", "(", ")" ]
[ 564, 4 ]
[ 646, 46 ]
python
en
['en', 'en', 'en']
True
BaseCase.click_partial_link_text
(self, partial_link_text, timeout=None)
This method clicks the partial link text on a page.
This method clicks the partial link text on a page.
def click_partial_link_text(self, partial_link_text, timeout=None): """ This method clicks the partial link text on a page. """ # If using phantomjs, might need to extract and open the link directly if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) if self.browser == 'phantomjs': if self.is_partial_link_text_visible(partial_link_text): element = self.wait_for_partial_link_text(partial_link_text) element.click() return soup = self.get_beautiful_soup() html_links = soup.fetch('a') for html_link in html_links: if partial_link_text in html_link.text: for html_attribute in html_link.attrs: if html_attribute[0] == 'href': href = html_attribute[1] if href.startswith('//'): link = "http:" + href elif href.startswith('/'): url = self.driver.current_url domain_url = self.get_domain_url(url) link = domain_url + href else: link = href self.open(link) return raise Exception( 'Could not parse link from partial link_text ' '{%s}' % partial_link_text) raise Exception( "Partial link text {%s} was not found!" % partial_link_text) if not self.is_partial_link_text_present(partial_link_text): self.wait_for_partial_link_text_present( partial_link_text, timeout=timeout) pre_action_url = self.get_current_url() try: element = self.wait_for_partial_link_text( partial_link_text, timeout=0.2) self.__demo_mode_highlight_if_active( partial_link_text, by=By.LINK_TEXT) try: element.click() except (StaleElementReferenceException, ENI_Exception): self.wait_for_ready_state_complete() time.sleep(0.05) element = self.wait_for_partial_link_text( partial_link_text, timeout=timeout) element.click() except Exception: found_css = False text_id = self.get_partial_link_text_attribute( partial_link_text, "id", False) if text_id: link_css = '[id="%s"]' % partial_link_text found_css = True if not found_css: href = self.__get_href_from_partial_link_text( partial_link_text, False) if href: if href.startswith('/') or page_utils.is_valid_url(href): link_css = '[href="%s"]' % href found_css = True if not found_css: ngclick = self.get_partial_link_text_attribute( partial_link_text, "ng-click", False) if ngclick: link_css = '[ng-click="%s"]' % ngclick found_css = True if not found_css: onclick = self.get_partial_link_text_attribute( partial_link_text, "onclick", False) if onclick: link_css = '[onclick="%s"]' % onclick found_css = True success = False if found_css: if self.is_element_visible(link_css): self.click(link_css) success = True else: # The link text might be hidden under a dropdown menu success = self.__click_dropdown_partial_link_text( partial_link_text, link_css) if not success: element = self.wait_for_link_text_visible( partial_link_text, timeout=settings.MINI_TIMEOUT) element.click() if settings.WAIT_FOR_RSC_ON_CLICKS: self.wait_for_ready_state_complete() if self.demo_mode: if self.driver.current_url != pre_action_url: self.__demo_mode_pause_if_active() else: self.__demo_mode_pause_if_active(tiny=True) elif self.slow_mode: self.__slow_mode_pause_if_active()
[ "def", "click_partial_link_text", "(", "self", ",", "partial_link_text", ",", "timeout", "=", "None", ")", ":", "# If using phantomjs, might need to extract and open the link directly", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "if", "self", ".", "browser", "==", "'phantomjs'", ":", "if", "self", ".", "is_partial_link_text_visible", "(", "partial_link_text", ")", ":", "element", "=", "self", ".", "wait_for_partial_link_text", "(", "partial_link_text", ")", "element", ".", "click", "(", ")", "return", "soup", "=", "self", ".", "get_beautiful_soup", "(", ")", "html_links", "=", "soup", ".", "fetch", "(", "'a'", ")", "for", "html_link", "in", "html_links", ":", "if", "partial_link_text", "in", "html_link", ".", "text", ":", "for", "html_attribute", "in", "html_link", ".", "attrs", ":", "if", "html_attribute", "[", "0", "]", "==", "'href'", ":", "href", "=", "html_attribute", "[", "1", "]", "if", "href", ".", "startswith", "(", "'//'", ")", ":", "link", "=", "\"http:\"", "+", "href", "elif", "href", ".", "startswith", "(", "'/'", ")", ":", "url", "=", "self", ".", "driver", ".", "current_url", "domain_url", "=", "self", ".", "get_domain_url", "(", "url", ")", "link", "=", "domain_url", "+", "href", "else", ":", "link", "=", "href", "self", ".", "open", "(", "link", ")", "return", "raise", "Exception", "(", "'Could not parse link from partial link_text '", "'{%s}'", "%", "partial_link_text", ")", "raise", "Exception", "(", "\"Partial link text {%s} was not found!\"", "%", "partial_link_text", ")", "if", "not", "self", ".", "is_partial_link_text_present", "(", "partial_link_text", ")", ":", "self", ".", "wait_for_partial_link_text_present", "(", "partial_link_text", ",", "timeout", "=", "timeout", ")", "pre_action_url", "=", "self", ".", "get_current_url", "(", ")", "try", ":", "element", "=", "self", ".", "wait_for_partial_link_text", "(", "partial_link_text", ",", "timeout", "=", "0.2", ")", "self", ".", "__demo_mode_highlight_if_active", "(", "partial_link_text", ",", "by", "=", "By", ".", "LINK_TEXT", ")", "try", ":", "element", ".", "click", "(", ")", "except", "(", "StaleElementReferenceException", ",", "ENI_Exception", ")", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "time", ".", "sleep", "(", "0.05", ")", "element", "=", "self", ".", "wait_for_partial_link_text", "(", "partial_link_text", ",", "timeout", "=", "timeout", ")", "element", ".", "click", "(", ")", "except", "Exception", ":", "found_css", "=", "False", "text_id", "=", "self", ".", "get_partial_link_text_attribute", "(", "partial_link_text", ",", "\"id\"", ",", "False", ")", "if", "text_id", ":", "link_css", "=", "'[id=\"%s\"]'", "%", "partial_link_text", "found_css", "=", "True", "if", "not", "found_css", ":", "href", "=", "self", ".", "__get_href_from_partial_link_text", "(", "partial_link_text", ",", "False", ")", "if", "href", ":", "if", "href", ".", "startswith", "(", "'/'", ")", "or", "page_utils", ".", "is_valid_url", "(", "href", ")", ":", "link_css", "=", "'[href=\"%s\"]'", "%", "href", "found_css", "=", "True", "if", "not", "found_css", ":", "ngclick", "=", "self", ".", "get_partial_link_text_attribute", "(", "partial_link_text", ",", "\"ng-click\"", ",", "False", ")", "if", "ngclick", ":", "link_css", "=", "'[ng-click=\"%s\"]'", "%", "ngclick", "found_css", "=", "True", "if", "not", "found_css", ":", "onclick", "=", "self", ".", "get_partial_link_text_attribute", "(", "partial_link_text", ",", "\"onclick\"", ",", "False", ")", "if", "onclick", ":", "link_css", "=", "'[onclick=\"%s\"]'", "%", "onclick", "found_css", "=", "True", "success", "=", "False", "if", "found_css", ":", "if", "self", ".", "is_element_visible", "(", "link_css", ")", ":", "self", ".", "click", "(", "link_css", ")", "success", "=", "True", "else", ":", "# The link text might be hidden under a dropdown menu", "success", "=", "self", ".", "__click_dropdown_partial_link_text", "(", "partial_link_text", ",", "link_css", ")", "if", "not", "success", ":", "element", "=", "self", ".", "wait_for_link_text_visible", "(", "partial_link_text", ",", "timeout", "=", "settings", ".", "MINI_TIMEOUT", ")", "element", ".", "click", "(", ")", "if", "settings", ".", "WAIT_FOR_RSC_ON_CLICKS", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "if", "self", ".", "demo_mode", ":", "if", "self", ".", "driver", ".", "current_url", "!=", "pre_action_url", ":", "self", ".", "__demo_mode_pause_if_active", "(", ")", "else", ":", "self", ".", "__demo_mode_pause_if_active", "(", "tiny", "=", "True", ")", "elif", "self", ".", "slow_mode", ":", "self", ".", "__slow_mode_pause_if_active", "(", ")" ]
[ 648, 4 ]
[ 752, 46 ]
python
en
['en', 'en', 'en']
True
BaseCase.get_attribute
(self, selector, attribute, by=By.CSS_SELECTOR, timeout=None, hard_fail=True)
This method uses JavaScript to get the value of an attribute.
This method uses JavaScript to get the value of an attribute.
def get_attribute(self, selector, attribute, by=By.CSS_SELECTOR, timeout=None, hard_fail=True): """ This method uses JavaScript to get the value of an attribute. """ if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) selector, by = self.__recalculate_selector(selector, by) self.wait_for_ready_state_complete() time.sleep(0.01) element = page_actions.wait_for_element_present( self.driver, selector, by, timeout) try: attribute_value = element.get_attribute(attribute) except (StaleElementReferenceException, ENI_Exception): self.wait_for_ready_state_complete() time.sleep(0.06) element = page_actions.wait_for_element_present( self.driver, selector, by, timeout) attribute_value = element.get_attribute(attribute) if attribute_value is not None: return attribute_value else: if hard_fail: raise Exception("Element {%s} has no attribute {%s}!" % ( selector, attribute)) else: return None
[ "def", "get_attribute", "(", "self", ",", "selector", ",", "attribute", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ",", "hard_fail", "=", "True", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "self", ".", "wait_for_ready_state_complete", "(", ")", "time", ".", "sleep", "(", "0.01", ")", "element", "=", "page_actions", ".", "wait_for_element_present", "(", "self", ".", "driver", ",", "selector", ",", "by", ",", "timeout", ")", "try", ":", "attribute_value", "=", "element", ".", "get_attribute", "(", "attribute", ")", "except", "(", "StaleElementReferenceException", ",", "ENI_Exception", ")", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "time", ".", "sleep", "(", "0.06", ")", "element", "=", "page_actions", ".", "wait_for_element_present", "(", "self", ".", "driver", ",", "selector", ",", "by", ",", "timeout", ")", "attribute_value", "=", "element", ".", "get_attribute", "(", "attribute", ")", "if", "attribute_value", "is", "not", "None", ":", "return", "attribute_value", "else", ":", "if", "hard_fail", ":", "raise", "Exception", "(", "\"Element {%s} has no attribute {%s}!\"", "%", "(", "selector", ",", "attribute", ")", ")", "else", ":", "return", "None" ]
[ 774, 4 ]
[ 801, 27 ]
python
en
['en', 'en', 'en']
True
BaseCase.set_attribute
(self, selector, attribute, value, by=By.CSS_SELECTOR, timeout=None)
This method uses JavaScript to set/update an attribute. Only the first matching selector from querySelector() is used.
This method uses JavaScript to set/update an attribute. Only the first matching selector from querySelector() is used.
def set_attribute(self, selector, attribute, value, by=By.CSS_SELECTOR, timeout=None): """ This method uses JavaScript to set/update an attribute. Only the first matching selector from querySelector() is used. """ if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) selector, by = self.__recalculate_selector(selector, by) if self.is_element_visible(selector, by=by): try: self.scroll_to(selector, by=by, timeout=timeout) except Exception: pass attribute = re.escape(attribute) attribute = self.__escape_quotes_if_needed(attribute) value = re.escape(value) value = self.__escape_quotes_if_needed(value) css_selector = self.convert_to_css_selector(selector, by=by) css_selector = re.escape(css_selector) css_selector = self.__escape_quotes_if_needed(css_selector) script = ("""document.querySelector('%s').setAttribute('%s','%s');""" % (css_selector, attribute, value)) self.execute_script(script)
[ "def", "set_attribute", "(", "self", ",", "selector", ",", "attribute", ",", "value", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "if", "self", ".", "is_element_visible", "(", "selector", ",", "by", "=", "by", ")", ":", "try", ":", "self", ".", "scroll_to", "(", "selector", ",", "by", "=", "by", ",", "timeout", "=", "timeout", ")", "except", "Exception", ":", "pass", "attribute", "=", "re", ".", "escape", "(", "attribute", ")", "attribute", "=", "self", ".", "__escape_quotes_if_needed", "(", "attribute", ")", "value", "=", "re", ".", "escape", "(", "value", ")", "value", "=", "self", ".", "__escape_quotes_if_needed", "(", "value", ")", "css_selector", "=", "self", ".", "convert_to_css_selector", "(", "selector", ",", "by", "=", "by", ")", "css_selector", "=", "re", ".", "escape", "(", "css_selector", ")", "css_selector", "=", "self", ".", "__escape_quotes_if_needed", "(", "css_selector", ")", "script", "=", "(", "\"\"\"document.querySelector('%s').setAttribute('%s','%s');\"\"\"", "%", "(", "css_selector", ",", "attribute", ",", "value", ")", ")", "self", ".", "execute_script", "(", "script", ")" ]
[ 803, 4 ]
[ 826, 35 ]
python
en
['en', 'en', 'en']
True
BaseCase.set_attributes
(self, selector, attribute, value, by=By.CSS_SELECTOR)
This method uses JavaScript to set/update a common attribute. All matching selectors from querySelectorAll() are used. Example => (Make all links on a website redirect to Google): self.set_attributes("a", "href", "https://google.com")
This method uses JavaScript to set/update a common attribute. All matching selectors from querySelectorAll() are used. Example => (Make all links on a website redirect to Google): self.set_attributes("a", "href", "https://google.com")
def set_attributes(self, selector, attribute, value, by=By.CSS_SELECTOR): """ This method uses JavaScript to set/update a common attribute. All matching selectors from querySelectorAll() are used. Example => (Make all links on a website redirect to Google): self.set_attributes("a", "href", "https://google.com") """ selector, by = self.__recalculate_selector(selector, by) attribute = re.escape(attribute) attribute = self.__escape_quotes_if_needed(attribute) value = re.escape(value) value = self.__escape_quotes_if_needed(value) css_selector = self.convert_to_css_selector(selector, by=by) css_selector = re.escape(css_selector) css_selector = self.__escape_quotes_if_needed(css_selector) script = ("""var $elements = document.querySelectorAll('%s'); var index = 0, length = $elements.length; for(; index < length; index++){ $elements[index].setAttribute('%s','%s');}""" % (css_selector, attribute, value)) try: self.execute_script(script) except Exception: pass
[ "def", "set_attributes", "(", "self", ",", "selector", ",", "attribute", ",", "value", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "attribute", "=", "re", ".", "escape", "(", "attribute", ")", "attribute", "=", "self", ".", "__escape_quotes_if_needed", "(", "attribute", ")", "value", "=", "re", ".", "escape", "(", "value", ")", "value", "=", "self", ".", "__escape_quotes_if_needed", "(", "value", ")", "css_selector", "=", "self", ".", "convert_to_css_selector", "(", "selector", ",", "by", "=", "by", ")", "css_selector", "=", "re", ".", "escape", "(", "css_selector", ")", "css_selector", "=", "self", ".", "__escape_quotes_if_needed", "(", "css_selector", ")", "script", "=", "(", "\"\"\"var $elements = document.querySelectorAll('%s');\n var index = 0, length = $elements.length;\n for(; index < length; index++){\n $elements[index].setAttribute('%s','%s');}\"\"\"", "%", "(", "css_selector", ",", "attribute", ",", "value", ")", ")", "try", ":", "self", ".", "execute_script", "(", "script", ")", "except", "Exception", ":", "pass" ]
[ 828, 4 ]
[ 849, 16 ]
python
en
['en', 'en', 'en']
True
BaseCase.set_attribute_all
(self, selector, attribute, value, by=By.CSS_SELECTOR)
Same as set_attributes(), but using querySelectorAll naming scheme. This method uses JavaScript to set/update a common attribute. All matching selectors from querySelectorAll() are used. Example => (Make all links on a website redirect to Google): self.set_attribute_all("a", "href", "https://google.com")
Same as set_attributes(), but using querySelectorAll naming scheme. This method uses JavaScript to set/update a common attribute. All matching selectors from querySelectorAll() are used. Example => (Make all links on a website redirect to Google): self.set_attribute_all("a", "href", "https://google.com")
def set_attribute_all(self, selector, attribute, value, by=By.CSS_SELECTOR): """ Same as set_attributes(), but using querySelectorAll naming scheme. This method uses JavaScript to set/update a common attribute. All matching selectors from querySelectorAll() are used. Example => (Make all links on a website redirect to Google): self.set_attribute_all("a", "href", "https://google.com") """ self.set_attributes(selector, attribute, value, by=by)
[ "def", "set_attribute_all", "(", "self", ",", "selector", ",", "attribute", ",", "value", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "self", ".", "set_attributes", "(", "selector", ",", "attribute", ",", "value", ",", "by", "=", "by", ")" ]
[ 851, 4 ]
[ 858, 62 ]
python
en
['en', 'en', 'en']
True
BaseCase.remove_attribute
(self, selector, attribute, by=By.CSS_SELECTOR, timeout=None)
This method uses JavaScript to remove an attribute. Only the first matching selector from querySelector() is used.
This method uses JavaScript to remove an attribute. Only the first matching selector from querySelector() is used.
def remove_attribute(self, selector, attribute, by=By.CSS_SELECTOR, timeout=None): """ This method uses JavaScript to remove an attribute. Only the first matching selector from querySelector() is used. """ if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) selector, by = self.__recalculate_selector(selector, by) if self.is_element_visible(selector, by=by): try: self.scroll_to(selector, by=by, timeout=timeout) except Exception: pass attribute = re.escape(attribute) attribute = self.__escape_quotes_if_needed(attribute) css_selector = self.convert_to_css_selector(selector, by=by) css_selector = re.escape(css_selector) css_selector = self.__escape_quotes_if_needed(css_selector) script = ("""document.querySelector('%s').removeAttribute('%s');""" % (css_selector, attribute)) self.execute_script(script)
[ "def", "remove_attribute", "(", "self", ",", "selector", ",", "attribute", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "if", "self", ".", "is_element_visible", "(", "selector", ",", "by", "=", "by", ")", ":", "try", ":", "self", ".", "scroll_to", "(", "selector", ",", "by", "=", "by", ",", "timeout", "=", "timeout", ")", "except", "Exception", ":", "pass", "attribute", "=", "re", ".", "escape", "(", "attribute", ")", "attribute", "=", "self", ".", "__escape_quotes_if_needed", "(", "attribute", ")", "css_selector", "=", "self", ".", "convert_to_css_selector", "(", "selector", ",", "by", "=", "by", ")", "css_selector", "=", "re", ".", "escape", "(", "css_selector", ")", "css_selector", "=", "self", ".", "__escape_quotes_if_needed", "(", "css_selector", ")", "script", "=", "(", "\"\"\"document.querySelector('%s').removeAttribute('%s');\"\"\"", "%", "(", "css_selector", ",", "attribute", ")", ")", "self", ".", "execute_script", "(", "script", ")" ]
[ 860, 4 ]
[ 881, 35 ]
python
en
['en', 'en', 'en']
True
BaseCase.remove_attributes
(self, selector, attribute, by=By.CSS_SELECTOR)
This method uses JavaScript to remove a common attribute. All matching selectors from querySelectorAll() are used.
This method uses JavaScript to remove a common attribute. All matching selectors from querySelectorAll() are used.
def remove_attributes(self, selector, attribute, by=By.CSS_SELECTOR): """ This method uses JavaScript to remove a common attribute. All matching selectors from querySelectorAll() are used. """ selector, by = self.__recalculate_selector(selector, by) attribute = re.escape(attribute) attribute = self.__escape_quotes_if_needed(attribute) css_selector = self.convert_to_css_selector(selector, by=by) css_selector = re.escape(css_selector) css_selector = self.__escape_quotes_if_needed(css_selector) script = ("""var $elements = document.querySelectorAll('%s'); var index = 0, length = $elements.length; for(; index < length; index++){ $elements[index].removeAttribute('%s');}""" % (css_selector, attribute)) try: self.execute_script(script) except Exception: pass
[ "def", "remove_attributes", "(", "self", ",", "selector", ",", "attribute", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "attribute", "=", "re", ".", "escape", "(", "attribute", ")", "attribute", "=", "self", ".", "__escape_quotes_if_needed", "(", "attribute", ")", "css_selector", "=", "self", ".", "convert_to_css_selector", "(", "selector", ",", "by", "=", "by", ")", "css_selector", "=", "re", ".", "escape", "(", "css_selector", ")", "css_selector", "=", "self", ".", "__escape_quotes_if_needed", "(", "css_selector", ")", "script", "=", "(", "\"\"\"var $elements = document.querySelectorAll('%s');\n var index = 0, length = $elements.length;\n for(; index < length; index++){\n $elements[index].removeAttribute('%s');}\"\"\"", "%", "(", "css_selector", ",", "attribute", ")", ")", "try", ":", "self", ".", "execute_script", "(", "script", ")", "except", "Exception", ":", "pass" ]
[ 883, 4 ]
[ 900, 16 ]
python
en
['en', 'en', 'en']
True
BaseCase.get_property_value
(self, selector, property, by=By.CSS_SELECTOR, timeout=None)
Returns the property value of a page element's computed style. Example: opacity = self.get_property_value("html body a", "opacity") self.assertTrue(float(opacity) > 0, "Element not visible!")
Returns the property value of a page element's computed style. Example: opacity = self.get_property_value("html body a", "opacity") self.assertTrue(float(opacity) > 0, "Element not visible!")
def get_property_value(self, selector, property, by=By.CSS_SELECTOR, timeout=None): """ Returns the property value of a page element's computed style. Example: opacity = self.get_property_value("html body a", "opacity") self.assertTrue(float(opacity) > 0, "Element not visible!") """ if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) selector, by = self.__recalculate_selector(selector, by) self.wait_for_ready_state_complete() page_actions.wait_for_element_present( self.driver, selector, by, timeout) try: selector = self.convert_to_css_selector(selector, by=by) except Exception: # Don't run action if can't convert to CSS_Selector for JavaScript raise Exception( "Exception: Could not convert {%s}(by=%s) to CSS_SELECTOR!" % ( selector, by)) selector = re.escape(selector) selector = self.__escape_quotes_if_needed(selector) script = ("""var $elm = document.querySelector('%s'); $val = window.getComputedStyle($elm).getPropertyValue('%s'); return $val;""" % (selector, property)) value = self.execute_script(script) if value is not None: return value else: return ""
[ "def", "get_property_value", "(", "self", ",", "selector", ",", "property", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "self", ".", "wait_for_ready_state_complete", "(", ")", "page_actions", ".", "wait_for_element_present", "(", "self", ".", "driver", ",", "selector", ",", "by", ",", "timeout", ")", "try", ":", "selector", "=", "self", ".", "convert_to_css_selector", "(", "selector", ",", "by", "=", "by", ")", "except", "Exception", ":", "# Don't run action if can't convert to CSS_Selector for JavaScript", "raise", "Exception", "(", "\"Exception: Could not convert {%s}(by=%s) to CSS_SELECTOR!\"", "%", "(", "selector", ",", "by", ")", ")", "selector", "=", "re", ".", "escape", "(", "selector", ")", "selector", "=", "self", ".", "__escape_quotes_if_needed", "(", "selector", ")", "script", "=", "(", "\"\"\"var $elm = document.querySelector('%s');\n $val = window.getComputedStyle($elm).getPropertyValue('%s');\n return $val;\"\"\"", "%", "(", "selector", ",", "property", ")", ")", "value", "=", "self", ".", "execute_script", "(", "script", ")", "if", "value", "is", "not", "None", ":", "return", "value", "else", ":", "return", "\"\"" ]
[ 902, 4 ]
[ 933, 21 ]
python
en
['en', 'en', 'en']
True
BaseCase.get_image_url
(self, selector, by=By.CSS_SELECTOR, timeout=None)
Extracts the URL from an image element on the page.
Extracts the URL from an image element on the page.
def get_image_url(self, selector, by=By.CSS_SELECTOR, timeout=None): """ Extracts the URL from an image element on the page. """ if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) return self.get_attribute(selector, attribute='src', by=by, timeout=timeout)
[ "def", "get_image_url", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "return", "self", ".", "get_attribute", "(", "selector", ",", "attribute", "=", "'src'", ",", "by", "=", "by", ",", "timeout", "=", "timeout", ")" ]
[ 935, 4 ]
[ 942, 74 ]
python
en
['en', 'en', 'en']
True
BaseCase.find_elements
(self, selector, by=By.CSS_SELECTOR, limit=0)
Returns a list of matching WebElements. Elements could be either hidden or visible on the page. If "limit" is set and > 0, will only return that many elements.
Returns a list of matching WebElements. Elements could be either hidden or visible on the page. If "limit" is set and > 0, will only return that many elements.
def find_elements(self, selector, by=By.CSS_SELECTOR, limit=0): """ Returns a list of matching WebElements. Elements could be either hidden or visible on the page. If "limit" is set and > 0, will only return that many elements. """ selector, by = self.__recalculate_selector(selector, by) self.wait_for_ready_state_complete() time.sleep(0.05) elements = self.driver.find_elements(by=by, value=selector) if limit and limit > 0 and len(elements) > limit: elements = elements[:limit] return elements
[ "def", "find_elements", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "limit", "=", "0", ")", ":", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "self", ".", "wait_for_ready_state_complete", "(", ")", "time", ".", "sleep", "(", "0.05", ")", "elements", "=", "self", ".", "driver", ".", "find_elements", "(", "by", "=", "by", ",", "value", "=", "selector", ")", "if", "limit", "and", "limit", ">", "0", "and", "len", "(", "elements", ")", ">", "limit", ":", "elements", "=", "elements", "[", ":", "limit", "]", "return", "elements" ]
[ 944, 4 ]
[ 954, 23 ]
python
en
['en', 'lb', 'en']
True
BaseCase.find_visible_elements
(self, selector, by=By.CSS_SELECTOR, limit=0)
Returns a list of matching WebElements that are visible. If "limit" is set and > 0, will only return that many elements.
Returns a list of matching WebElements that are visible. If "limit" is set and > 0, will only return that many elements.
def find_visible_elements(self, selector, by=By.CSS_SELECTOR, limit=0): """ Returns a list of matching WebElements that are visible. If "limit" is set and > 0, will only return that many elements. """ selector, by = self.__recalculate_selector(selector, by) self.wait_for_ready_state_complete() time.sleep(0.05) v_elems = page_actions.find_visible_elements(self.driver, selector, by) if limit and limit > 0 and len(v_elems) > limit: v_elems = v_elems[:limit] return v_elems
[ "def", "find_visible_elements", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "limit", "=", "0", ")", ":", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "self", ".", "wait_for_ready_state_complete", "(", ")", "time", ".", "sleep", "(", "0.05", ")", "v_elems", "=", "page_actions", ".", "find_visible_elements", "(", "self", ".", "driver", ",", "selector", ",", "by", ")", "if", "limit", "and", "limit", ">", "0", "and", "len", "(", "v_elems", ")", ">", "limit", ":", "v_elems", "=", "v_elems", "[", ":", "limit", "]", "return", "v_elems" ]
[ 956, 4 ]
[ 965, 22 ]
python
en
['en', 'en', 'en']
True
BaseCase.click_visible_elements
(self, selector, by=By.CSS_SELECTOR, limit=0)
Finds all matching page elements and clicks visible ones in order. If a click reloads or opens a new page, the clicking will stop. If no matching elements appear, an Exception will be raised. If "limit" is set and > 0, will only click that many elements. Also clicks elements that become visible from previous clicks. Works best for actions such as clicking all checkboxes on a page. Example: self.click_visible_elements('input[type="checkbox"]')
Finds all matching page elements and clicks visible ones in order. If a click reloads or opens a new page, the clicking will stop. If no matching elements appear, an Exception will be raised. If "limit" is set and > 0, will only click that many elements. Also clicks elements that become visible from previous clicks. Works best for actions such as clicking all checkboxes on a page. Example: self.click_visible_elements('input[type="checkbox"]')
def click_visible_elements(self, selector, by=By.CSS_SELECTOR, limit=0): """ Finds all matching page elements and clicks visible ones in order. If a click reloads or opens a new page, the clicking will stop. If no matching elements appear, an Exception will be raised. If "limit" is set and > 0, will only click that many elements. Also clicks elements that become visible from previous clicks. Works best for actions such as clicking all checkboxes on a page. Example: self.click_visible_elements('input[type="checkbox"]') """ selector, by = self.__recalculate_selector(selector, by) self.wait_for_element_present( selector, by=by, timeout=settings.SMALL_TIMEOUT) elements = self.find_elements(selector, by=by) if self.browser == "safari": if not limit: limit = 0 num_elements = len(elements) if num_elements == 0: raise Exception( "No matching elements found for selector {%s}!" % selector) elif num_elements < limit or limit == 0: limit = num_elements selector, by = self.__recalculate_selector(selector, by) css_selector = self.convert_to_css_selector(selector, by=by) last_css_chunk = css_selector.split(' ')[-1] if ":" in last_css_chunk: self.__js_click_all(css_selector) self.wait_for_ready_state_complete() return else: for i in range(1, limit+1): new_selector = css_selector + ":nth-of-type(%s)" % str(i) if self.is_element_visible(new_selector): self.__js_click(new_selector) self.wait_for_ready_state_complete() return click_count = 0 for element in elements: if limit and limit > 0 and click_count >= limit: return try: if element.is_displayed(): self.__scroll_to_element(element) element.click() click_count += 1 self.wait_for_ready_state_complete() except ECI_Exception: continue # ElementClickInterceptedException (Overlay likely) except (StaleElementReferenceException, ENI_Exception): self.wait_for_ready_state_complete() time.sleep(0.03) try: if element.is_displayed(): self.__scroll_to_element(element) element.click() click_count += 1 self.wait_for_ready_state_complete() except (StaleElementReferenceException, ENI_Exception): return
[ "def", "click_visible_elements", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "limit", "=", "0", ")", ":", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "self", ".", "wait_for_element_present", "(", "selector", ",", "by", "=", "by", ",", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", ")", "elements", "=", "self", ".", "find_elements", "(", "selector", ",", "by", "=", "by", ")", "if", "self", ".", "browser", "==", "\"safari\"", ":", "if", "not", "limit", ":", "limit", "=", "0", "num_elements", "=", "len", "(", "elements", ")", "if", "num_elements", "==", "0", ":", "raise", "Exception", "(", "\"No matching elements found for selector {%s}!\"", "%", "selector", ")", "elif", "num_elements", "<", "limit", "or", "limit", "==", "0", ":", "limit", "=", "num_elements", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "css_selector", "=", "self", ".", "convert_to_css_selector", "(", "selector", ",", "by", "=", "by", ")", "last_css_chunk", "=", "css_selector", ".", "split", "(", "' '", ")", "[", "-", "1", "]", "if", "\":\"", "in", "last_css_chunk", ":", "self", ".", "__js_click_all", "(", "css_selector", ")", "self", ".", "wait_for_ready_state_complete", "(", ")", "return", "else", ":", "for", "i", "in", "range", "(", "1", ",", "limit", "+", "1", ")", ":", "new_selector", "=", "css_selector", "+", "\":nth-of-type(%s)\"", "%", "str", "(", "i", ")", "if", "self", ".", "is_element_visible", "(", "new_selector", ")", ":", "self", ".", "__js_click", "(", "new_selector", ")", "self", ".", "wait_for_ready_state_complete", "(", ")", "return", "click_count", "=", "0", "for", "element", "in", "elements", ":", "if", "limit", "and", "limit", ">", "0", "and", "click_count", ">=", "limit", ":", "return", "try", ":", "if", "element", ".", "is_displayed", "(", ")", ":", "self", ".", "__scroll_to_element", "(", "element", ")", "element", ".", "click", "(", ")", "click_count", "+=", "1", "self", ".", "wait_for_ready_state_complete", "(", ")", "except", "ECI_Exception", ":", "continue", "# ElementClickInterceptedException (Overlay likely)", "except", "(", "StaleElementReferenceException", ",", "ENI_Exception", ")", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "time", ".", "sleep", "(", "0.03", ")", "try", ":", "if", "element", ".", "is_displayed", "(", ")", ":", "self", ".", "__scroll_to_element", "(", "element", ")", "element", ".", "click", "(", ")", "click_count", "+=", "1", "self", ".", "wait_for_ready_state_complete", "(", ")", "except", "(", "StaleElementReferenceException", ",", "ENI_Exception", ")", ":", "return" ]
[ 967, 4 ]
[ 1024, 26 ]
python
en
['en', 'en', 'en']
True
BaseCase.click_nth_visible_element
(self, selector, number, by=By.CSS_SELECTOR)
Finds all matching page elements and clicks the nth visible one. Example: self.click_nth_visible_element('[type="checkbox"]', 5) (Clicks the 5th visible checkbox on the page.)
Finds all matching page elements and clicks the nth visible one. Example: self.click_nth_visible_element('[type="checkbox"]', 5) (Clicks the 5th visible checkbox on the page.)
def click_nth_visible_element(self, selector, number, by=By.CSS_SELECTOR): """ Finds all matching page elements and clicks the nth visible one. Example: self.click_nth_visible_element('[type="checkbox"]', 5) (Clicks the 5th visible checkbox on the page.) """ elements = self.find_visible_elements(selector, by=by) if len(elements) < number: raise Exception("Not enough matching {%s} elements of type {%s} to" " click number %s!" % (selector, by, number)) number = number - 1 if number < 0: number = 0 element = elements[number] self.wait_for_ready_state_complete() try: self.__scroll_to_element(element) element.click() except (StaleElementReferenceException, ENI_Exception): self.wait_for_ready_state_complete() time.sleep(0.05) self.__scroll_to_element(element) element.click()
[ "def", "click_nth_visible_element", "(", "self", ",", "selector", ",", "number", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "elements", "=", "self", ".", "find_visible_elements", "(", "selector", ",", "by", "=", "by", ")", "if", "len", "(", "elements", ")", "<", "number", ":", "raise", "Exception", "(", "\"Not enough matching {%s} elements of type {%s} to\"", "\" click number %s!\"", "%", "(", "selector", ",", "by", ",", "number", ")", ")", "number", "=", "number", "-", "1", "if", "number", "<", "0", ":", "number", "=", "0", "element", "=", "elements", "[", "number", "]", "self", ".", "wait_for_ready_state_complete", "(", ")", "try", ":", "self", ".", "__scroll_to_element", "(", "element", ")", "element", ".", "click", "(", ")", "except", "(", "StaleElementReferenceException", ",", "ENI_Exception", ")", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "time", ".", "sleep", "(", "0.05", ")", "self", ".", "__scroll_to_element", "(", "element", ")", "element", ".", "click", "(", ")" ]
[ 1026, 4 ]
[ 1046, 27 ]
python
en
['en', 'en', 'en']
True
BaseCase.click_if_visible
(self, selector, by=By.CSS_SELECTOR)
If the page selector exists and is visible, clicks on the element. This method only clicks on the first matching element found. (Use click_visible_elements() to click all matching elements.)
If the page selector exists and is visible, clicks on the element. This method only clicks on the first matching element found. (Use click_visible_elements() to click all matching elements.)
def click_if_visible(self, selector, by=By.CSS_SELECTOR): """ If the page selector exists and is visible, clicks on the element. This method only clicks on the first matching element found. (Use click_visible_elements() to click all matching elements.) """ self.wait_for_ready_state_complete() if self.is_element_visible(selector, by=by): self.click(selector, by=by)
[ "def", "click_if_visible", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "if", "self", ".", "is_element_visible", "(", "selector", ",", "by", "=", "by", ")", ":", "self", ".", "click", "(", "selector", ",", "by", "=", "by", ")" ]
[ 1048, 4 ]
[ 1054, 39 ]
python
en
['en', 'en', 'en']
True
BaseCase.is_checked
(self, selector, by=By.CSS_SELECTOR, timeout=None)
Determines if a checkbox or a radio button element is checked. Returns True if the element is checked. Returns False if the element is not checked. If the element is not present on the page, raises an exception. If the element is not a checkbox or radio, raises an exception.
Determines if a checkbox or a radio button element is checked. Returns True if the element is checked. Returns False if the element is not checked. If the element is not present on the page, raises an exception. If the element is not a checkbox or radio, raises an exception.
def is_checked(self, selector, by=By.CSS_SELECTOR, timeout=None): """ Determines if a checkbox or a radio button element is checked. Returns True if the element is checked. Returns False if the element is not checked. If the element is not present on the page, raises an exception. If the element is not a checkbox or radio, raises an exception. """ if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) selector, by = self.__recalculate_selector(selector, by) kind = self.get_attribute(selector, "type", by=by, timeout=timeout) if kind != "checkbox" and kind != "radio": raise Exception("Expecting a checkbox or a radio button element!") is_checked = self.get_attribute( selector, "checked", by=by, timeout=timeout, hard_fail=False) if is_checked: return True else: # (NoneType) return False
[ "def", "is_checked", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "kind", "=", "self", ".", "get_attribute", "(", "selector", ",", "\"type\"", ",", "by", "=", "by", ",", "timeout", "=", "timeout", ")", "if", "kind", "!=", "\"checkbox\"", "and", "kind", "!=", "\"radio\"", ":", "raise", "Exception", "(", "\"Expecting a checkbox or a radio button element!\"", ")", "is_checked", "=", "self", ".", "get_attribute", "(", "selector", ",", "\"checked\"", ",", "by", "=", "by", ",", "timeout", "=", "timeout", ",", "hard_fail", "=", "False", ")", "if", "is_checked", ":", "return", "True", "else", ":", "# (NoneType)", "return", "False" ]
[ 1056, 4 ]
[ 1075, 24 ]
python
en
['en', 'en', 'en']
True
BaseCase.is_selected
(self, selector, by=By.CSS_SELECTOR, timeout=None)
Same as is_checked()
Same as is_checked()
def is_selected(self, selector, by=By.CSS_SELECTOR, timeout=None): """ Same as is_checked() """ return self.is_checked(selector, by=by, timeout=timeout)
[ "def", "is_selected", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "is_checked", "(", "selector", ",", "by", "=", "by", ",", "timeout", "=", "timeout", ")" ]
[ 1077, 4 ]
[ 1079, 64 ]
python
en
['en', 'en', 'en']
True
BaseCase.check_if_unchecked
(self, selector, by=By.CSS_SELECTOR)
If a checkbox or radio button is not checked, will check it.
If a checkbox or radio button is not checked, will check it.
def check_if_unchecked(self, selector, by=By.CSS_SELECTOR): """ If a checkbox or radio button is not checked, will check it. """ selector, by = self.__recalculate_selector(selector, by) if not self.is_checked(selector, by=by): if self.is_element_visible(selector, by=by): self.click(selector, by=by) else: selector = self.convert_to_css_selector(selector, by=by) self.js_click(selector, by=By.CSS_SELECTOR)
[ "def", "check_if_unchecked", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "if", "not", "self", ".", "is_checked", "(", "selector", ",", "by", "=", "by", ")", ":", "if", "self", ".", "is_element_visible", "(", "selector", ",", "by", "=", "by", ")", ":", "self", ".", "click", "(", "selector", ",", "by", "=", "by", ")", "else", ":", "selector", "=", "self", ".", "convert_to_css_selector", "(", "selector", ",", "by", "=", "by", ")", "self", ".", "js_click", "(", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")" ]
[ 1081, 4 ]
[ 1089, 59 ]
python
en
['en', 'en', 'en']
True
BaseCase.select_if_unselected
(self, selector, by=By.CSS_SELECTOR)
Same as check_if_unchecked()
Same as check_if_unchecked()
def select_if_unselected(self, selector, by=By.CSS_SELECTOR): """ Same as check_if_unchecked() """ self.check_if_unchecked(selector, by=by)
[ "def", "select_if_unselected", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "self", ".", "check_if_unchecked", "(", "selector", ",", "by", "=", "by", ")" ]
[ 1091, 4 ]
[ 1093, 48 ]
python
en
['en', 'en', 'en']
True
BaseCase.uncheck_if_checked
(self, selector, by=By.CSS_SELECTOR)
If a checkbox is checked, will uncheck it.
If a checkbox is checked, will uncheck it.
def uncheck_if_checked(self, selector, by=By.CSS_SELECTOR): """ If a checkbox is checked, will uncheck it. """ selector, by = self.__recalculate_selector(selector, by) if self.is_checked(selector, by=by): if self.is_element_visible(selector, by=by): self.click(selector, by=by) else: selector = self.convert_to_css_selector(selector, by=by) self.js_click(selector, by=By.CSS_SELECTOR)
[ "def", "uncheck_if_checked", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "if", "self", ".", "is_checked", "(", "selector", ",", "by", "=", "by", ")", ":", "if", "self", ".", "is_element_visible", "(", "selector", ",", "by", "=", "by", ")", ":", "self", ".", "click", "(", "selector", ",", "by", "=", "by", ")", "else", ":", "selector", "=", "self", ".", "convert_to_css_selector", "(", "selector", ",", "by", "=", "by", ")", "self", ".", "js_click", "(", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")" ]
[ 1095, 4 ]
[ 1103, 59 ]
python
en
['en', 'en', 'en']
True
BaseCase.unselect_if_selected
(self, selector, by=By.CSS_SELECTOR)
Same as uncheck_if_checked()
Same as uncheck_if_checked()
def unselect_if_selected(self, selector, by=By.CSS_SELECTOR): """ Same as uncheck_if_checked() """ self.uncheck_if_checked(selector, by=by)
[ "def", "unselect_if_selected", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "self", ".", "uncheck_if_checked", "(", "selector", ",", "by", "=", "by", ")" ]
[ 1105, 4 ]
[ 1107, 48 ]
python
en
['en', 'en', 'en']
True
BaseCase.is_element_in_an_iframe
(self, selector, by=By.CSS_SELECTOR)
Returns True if the selector's element is located in an iframe. Otherwise returns False.
Returns True if the selector's element is located in an iframe. Otherwise returns False.
def is_element_in_an_iframe(self, selector, by=By.CSS_SELECTOR): """ Returns True if the selector's element is located in an iframe. Otherwise returns False. """ selector, by = self.__recalculate_selector(selector, by) if self.is_element_present(selector, by=by): return False soup = self.get_beautiful_soup() iframe_list = soup.select('iframe') for iframe in iframe_list: iframe_identifier = None if iframe.has_attr('name') and len(iframe['name']) > 0: iframe_identifier = iframe['name'] elif iframe.has_attr('id') and len(iframe['id']) > 0: iframe_identifier = iframe['id'] elif iframe.has_attr('class') and len(iframe['class']) > 0: iframe_class = " ".join(iframe["class"]) iframe_identifier = '[class="%s"]' % iframe_class else: continue self.switch_to_frame(iframe_identifier) if self.is_element_present(selector, by=by): self.switch_to_default_content() return True self.switch_to_default_content() return False
[ "def", "is_element_in_an_iframe", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "if", "self", ".", "is_element_present", "(", "selector", ",", "by", "=", "by", ")", ":", "return", "False", "soup", "=", "self", ".", "get_beautiful_soup", "(", ")", "iframe_list", "=", "soup", ".", "select", "(", "'iframe'", ")", "for", "iframe", "in", "iframe_list", ":", "iframe_identifier", "=", "None", "if", "iframe", ".", "has_attr", "(", "'name'", ")", "and", "len", "(", "iframe", "[", "'name'", "]", ")", ">", "0", ":", "iframe_identifier", "=", "iframe", "[", "'name'", "]", "elif", "iframe", ".", "has_attr", "(", "'id'", ")", "and", "len", "(", "iframe", "[", "'id'", "]", ")", ">", "0", ":", "iframe_identifier", "=", "iframe", "[", "'id'", "]", "elif", "iframe", ".", "has_attr", "(", "'class'", ")", "and", "len", "(", "iframe", "[", "'class'", "]", ")", ">", "0", ":", "iframe_class", "=", "\" \"", ".", "join", "(", "iframe", "[", "\"class\"", "]", ")", "iframe_identifier", "=", "'[class=\"%s\"]'", "%", "iframe_class", "else", ":", "continue", "self", ".", "switch_to_frame", "(", "iframe_identifier", ")", "if", "self", ".", "is_element_present", "(", "selector", ",", "by", "=", "by", ")", ":", "self", ".", "switch_to_default_content", "(", ")", "return", "True", "self", ".", "switch_to_default_content", "(", ")", "return", "False" ]
[ 1109, 4 ]
[ 1133, 20 ]
python
en
['en', 'en', 'en']
True
BaseCase.switch_to_frame_of_element
(self, selector, by=By.CSS_SELECTOR)
Set driver control to the iframe containing element (assuming the element is in a single-nested iframe) and returns the iframe name. If element is not in an iframe, returns None, and nothing happens. May not work if multiple iframes are nested within each other.
Set driver control to the iframe containing element (assuming the element is in a single-nested iframe) and returns the iframe name. If element is not in an iframe, returns None, and nothing happens. May not work if multiple iframes are nested within each other.
def switch_to_frame_of_element(self, selector, by=By.CSS_SELECTOR): """ Set driver control to the iframe containing element (assuming the element is in a single-nested iframe) and returns the iframe name. If element is not in an iframe, returns None, and nothing happens. May not work if multiple iframes are nested within each other. """ selector, by = self.__recalculate_selector(selector, by) if self.is_element_present(selector, by=by): return None soup = self.get_beautiful_soup() iframe_list = soup.select('iframe') for iframe in iframe_list: iframe_identifier = None if iframe.has_attr('name') and len(iframe['name']) > 0: iframe_identifier = iframe['name'] elif iframe.has_attr('id') and len(iframe['id']) > 0: iframe_identifier = iframe['id'] elif iframe.has_attr('class') and len(iframe['class']) > 0: iframe_class = " ".join(iframe["class"]) iframe_identifier = '[class="%s"]' % iframe_class else: continue try: self.switch_to_frame(iframe_identifier, timeout=1) if self.is_element_present(selector, by=by): return iframe_identifier except Exception: pass self.switch_to_default_content() try: self.switch_to_frame(selector, timeout=1) return selector except Exception: if self.is_element_present(selector, by=by): return "" raise Exception("Could not switch to iframe containing " "element {%s}!" % selector)
[ "def", "switch_to_frame_of_element", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "if", "self", ".", "is_element_present", "(", "selector", ",", "by", "=", "by", ")", ":", "return", "None", "soup", "=", "self", ".", "get_beautiful_soup", "(", ")", "iframe_list", "=", "soup", ".", "select", "(", "'iframe'", ")", "for", "iframe", "in", "iframe_list", ":", "iframe_identifier", "=", "None", "if", "iframe", ".", "has_attr", "(", "'name'", ")", "and", "len", "(", "iframe", "[", "'name'", "]", ")", ">", "0", ":", "iframe_identifier", "=", "iframe", "[", "'name'", "]", "elif", "iframe", ".", "has_attr", "(", "'id'", ")", "and", "len", "(", "iframe", "[", "'id'", "]", ")", ">", "0", ":", "iframe_identifier", "=", "iframe", "[", "'id'", "]", "elif", "iframe", ".", "has_attr", "(", "'class'", ")", "and", "len", "(", "iframe", "[", "'class'", "]", ")", ">", "0", ":", "iframe_class", "=", "\" \"", ".", "join", "(", "iframe", "[", "\"class\"", "]", ")", "iframe_identifier", "=", "'[class=\"%s\"]'", "%", "iframe_class", "else", ":", "continue", "try", ":", "self", ".", "switch_to_frame", "(", "iframe_identifier", ",", "timeout", "=", "1", ")", "if", "self", ".", "is_element_present", "(", "selector", ",", "by", "=", "by", ")", ":", "return", "iframe_identifier", "except", "Exception", ":", "pass", "self", ".", "switch_to_default_content", "(", ")", "try", ":", "self", ".", "switch_to_frame", "(", "selector", ",", "timeout", "=", "1", ")", "return", "selector", "except", "Exception", ":", "if", "self", ".", "is_element_present", "(", "selector", ",", "by", "=", "by", ")", ":", "return", "\"\"", "raise", "Exception", "(", "\"Could not switch to iframe containing \"", "\"element {%s}!\"", "%", "selector", ")" ]
[ 1135, 4 ]
[ 1170, 55 ]
python
en
['en', 'en', 'en']
True
BaseCase.hover_and_click
(self, hover_selector, click_selector, hover_by=By.CSS_SELECTOR, click_by=By.CSS_SELECTOR, timeout=None)
When you want to hover over an element or dropdown menu, and then click an element that appears after that.
When you want to hover over an element or dropdown menu, and then click an element that appears after that.
def hover_and_click(self, hover_selector, click_selector, hover_by=By.CSS_SELECTOR, click_by=By.CSS_SELECTOR, timeout=None): """ When you want to hover over an element or dropdown menu, and then click an element that appears after that. """ if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) hover_selector, hover_by = self.__recalculate_selector( hover_selector, hover_by) hover_selector = self.convert_to_css_selector( hover_selector, hover_by) hover_by = By.CSS_SELECTOR click_selector, click_by = self.__recalculate_selector( click_selector, click_by) dropdown_element = self.wait_for_element_visible( hover_selector, by=hover_by, timeout=timeout) self.__demo_mode_highlight_if_active(hover_selector, hover_by) self.scroll_to(hover_selector, by=hover_by) pre_action_url = self.driver.current_url outdated_driver = False element = None try: if self.mobile_emulator: # On mobile, click to hover the element dropdown_element.click() elif self.browser == "safari": # Use the workaround for hover-clicking on Safari raise Exception("This Exception will be caught.") else: page_actions.hover_element(self.driver, dropdown_element) except Exception: outdated_driver = True element = self.wait_for_element_present( click_selector, click_by, timeout) if click_by == By.LINK_TEXT: self.open(self.__get_href_from_link_text(click_selector)) elif click_by == By.PARTIAL_LINK_TEXT: self.open(self.__get_href_from_partial_link_text( click_selector)) else: self.js_click(click_selector, by=click_by) if outdated_driver: pass # Already did the click workaround elif self.mobile_emulator: self.click(click_selector, by=click_by) elif not outdated_driver: element = page_actions.hover_and_click( self.driver, hover_selector, click_selector, hover_by, click_by, timeout) if self.demo_mode: if self.driver.current_url != pre_action_url: self.__demo_mode_pause_if_active() else: self.__demo_mode_pause_if_active(tiny=True) elif self.slow_mode: self.__slow_mode_pause_if_active() return element
[ "def", "hover_and_click", "(", "self", ",", "hover_selector", ",", "click_selector", ",", "hover_by", "=", "By", ".", "CSS_SELECTOR", ",", "click_by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "hover_selector", ",", "hover_by", "=", "self", ".", "__recalculate_selector", "(", "hover_selector", ",", "hover_by", ")", "hover_selector", "=", "self", ".", "convert_to_css_selector", "(", "hover_selector", ",", "hover_by", ")", "hover_by", "=", "By", ".", "CSS_SELECTOR", "click_selector", ",", "click_by", "=", "self", ".", "__recalculate_selector", "(", "click_selector", ",", "click_by", ")", "dropdown_element", "=", "self", ".", "wait_for_element_visible", "(", "hover_selector", ",", "by", "=", "hover_by", ",", "timeout", "=", "timeout", ")", "self", ".", "__demo_mode_highlight_if_active", "(", "hover_selector", ",", "hover_by", ")", "self", ".", "scroll_to", "(", "hover_selector", ",", "by", "=", "hover_by", ")", "pre_action_url", "=", "self", ".", "driver", ".", "current_url", "outdated_driver", "=", "False", "element", "=", "None", "try", ":", "if", "self", ".", "mobile_emulator", ":", "# On mobile, click to hover the element", "dropdown_element", ".", "click", "(", ")", "elif", "self", ".", "browser", "==", "\"safari\"", ":", "# Use the workaround for hover-clicking on Safari", "raise", "Exception", "(", "\"This Exception will be caught.\"", ")", "else", ":", "page_actions", ".", "hover_element", "(", "self", ".", "driver", ",", "dropdown_element", ")", "except", "Exception", ":", "outdated_driver", "=", "True", "element", "=", "self", ".", "wait_for_element_present", "(", "click_selector", ",", "click_by", ",", "timeout", ")", "if", "click_by", "==", "By", ".", "LINK_TEXT", ":", "self", ".", "open", "(", "self", ".", "__get_href_from_link_text", "(", "click_selector", ")", ")", "elif", "click_by", "==", "By", ".", "PARTIAL_LINK_TEXT", ":", "self", ".", "open", "(", "self", ".", "__get_href_from_partial_link_text", "(", "click_selector", ")", ")", "else", ":", "self", ".", "js_click", "(", "click_selector", ",", "by", "=", "click_by", ")", "if", "outdated_driver", ":", "pass", "# Already did the click workaround", "elif", "self", ".", "mobile_emulator", ":", "self", ".", "click", "(", "click_selector", ",", "by", "=", "click_by", ")", "elif", "not", "outdated_driver", ":", "element", "=", "page_actions", ".", "hover_and_click", "(", "self", ".", "driver", ",", "hover_selector", ",", "click_selector", ",", "hover_by", ",", "click_by", ",", "timeout", ")", "if", "self", ".", "demo_mode", ":", "if", "self", ".", "driver", ".", "current_url", "!=", "pre_action_url", ":", "self", ".", "__demo_mode_pause_if_active", "(", ")", "else", ":", "self", ".", "__demo_mode_pause_if_active", "(", "tiny", "=", "True", ")", "elif", "self", ".", "slow_mode", ":", "self", ".", "__slow_mode_pause_if_active", "(", ")", "return", "element" ]
[ 1184, 4 ]
[ 1242, 22 ]
python
en
['en', 'en', 'en']
True
BaseCase.hover_and_double_click
(self, hover_selector, click_selector, hover_by=By.CSS_SELECTOR, click_by=By.CSS_SELECTOR, timeout=None)
When you want to hover over an element or dropdown menu, and then double-click an element that appears after that.
When you want to hover over an element or dropdown menu, and then double-click an element that appears after that.
def hover_and_double_click(self, hover_selector, click_selector, hover_by=By.CSS_SELECTOR, click_by=By.CSS_SELECTOR, timeout=None): """ When you want to hover over an element or dropdown menu, and then double-click an element that appears after that. """ if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) hover_selector, hover_by = self.__recalculate_selector( hover_selector, hover_by) hover_selector = self.convert_to_css_selector( hover_selector, hover_by) click_selector, click_by = self.__recalculate_selector( click_selector, click_by) dropdown_element = self.wait_for_element_visible( hover_selector, by=hover_by, timeout=timeout) self.__demo_mode_highlight_if_active(hover_selector, hover_by) self.scroll_to(hover_selector, by=hover_by) pre_action_url = self.driver.current_url outdated_driver = False element = None try: page_actions.hover_element(self.driver, dropdown_element) except Exception: outdated_driver = True element = self.wait_for_element_present( click_selector, click_by, timeout) if click_by == By.LINK_TEXT: self.open(self.__get_href_from_link_text(click_selector)) elif click_by == By.PARTIAL_LINK_TEXT: self.open(self.__get_href_from_partial_link_text( click_selector)) else: self.js_click(click_selector, click_by) if not outdated_driver: element = page_actions.hover_element_and_double_click( self.driver, dropdown_element, click_selector, click_by=By.CSS_SELECTOR, timeout=timeout) if self.demo_mode: if self.driver.current_url != pre_action_url: self.__demo_mode_pause_if_active() else: self.__demo_mode_pause_if_active(tiny=True) elif self.slow_mode: self.__slow_mode_pause_if_active() return element
[ "def", "hover_and_double_click", "(", "self", ",", "hover_selector", ",", "click_selector", ",", "hover_by", "=", "By", ".", "CSS_SELECTOR", ",", "click_by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "hover_selector", ",", "hover_by", "=", "self", ".", "__recalculate_selector", "(", "hover_selector", ",", "hover_by", ")", "hover_selector", "=", "self", ".", "convert_to_css_selector", "(", "hover_selector", ",", "hover_by", ")", "click_selector", ",", "click_by", "=", "self", ".", "__recalculate_selector", "(", "click_selector", ",", "click_by", ")", "dropdown_element", "=", "self", ".", "wait_for_element_visible", "(", "hover_selector", ",", "by", "=", "hover_by", ",", "timeout", "=", "timeout", ")", "self", ".", "__demo_mode_highlight_if_active", "(", "hover_selector", ",", "hover_by", ")", "self", ".", "scroll_to", "(", "hover_selector", ",", "by", "=", "hover_by", ")", "pre_action_url", "=", "self", ".", "driver", ".", "current_url", "outdated_driver", "=", "False", "element", "=", "None", "try", ":", "page_actions", ".", "hover_element", "(", "self", ".", "driver", ",", "dropdown_element", ")", "except", "Exception", ":", "outdated_driver", "=", "True", "element", "=", "self", ".", "wait_for_element_present", "(", "click_selector", ",", "click_by", ",", "timeout", ")", "if", "click_by", "==", "By", ".", "LINK_TEXT", ":", "self", ".", "open", "(", "self", ".", "__get_href_from_link_text", "(", "click_selector", ")", ")", "elif", "click_by", "==", "By", ".", "PARTIAL_LINK_TEXT", ":", "self", ".", "open", "(", "self", ".", "__get_href_from_partial_link_text", "(", "click_selector", ")", ")", "else", ":", "self", ".", "js_click", "(", "click_selector", ",", "click_by", ")", "if", "not", "outdated_driver", ":", "element", "=", "page_actions", ".", "hover_element_and_double_click", "(", "self", ".", "driver", ",", "dropdown_element", ",", "click_selector", ",", "click_by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "timeout", ")", "if", "self", ".", "demo_mode", ":", "if", "self", ".", "driver", ".", "current_url", "!=", "pre_action_url", ":", "self", ".", "__demo_mode_pause_if_active", "(", ")", "else", ":", "self", ".", "__demo_mode_pause_if_active", "(", "tiny", "=", "True", ")", "elif", "self", ".", "slow_mode", ":", "self", ".", "__slow_mode_pause_if_active", "(", ")", "return", "element" ]
[ 1244, 4 ]
[ 1291, 22 ]
python
en
['en', 'en', 'en']
True
BaseCase.__select_option
(self, dropdown_selector, option, dropdown_by=By.CSS_SELECTOR, option_by="text", timeout=None)
Selects an HTML <select> option by specification. Option specifications are by "text", "index", or "value". Defaults to "text" if option_by is unspecified or unknown.
Selects an HTML <select> option by specification. Option specifications are by "text", "index", or "value". Defaults to "text" if option_by is unspecified or unknown.
def __select_option(self, dropdown_selector, option, dropdown_by=By.CSS_SELECTOR, option_by="text", timeout=None): """ Selects an HTML <select> option by specification. Option specifications are by "text", "index", or "value". Defaults to "text" if option_by is unspecified or unknown. """ from selenium.webdriver.support.ui import Select if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) if page_utils.is_xpath_selector(dropdown_selector): dropdown_by = By.XPATH self.wait_for_ready_state_complete() element = self.wait_for_element_present( dropdown_selector, by=dropdown_by, timeout=timeout) if self.is_element_visible(dropdown_selector, by=dropdown_by): self.__demo_mode_highlight_if_active( dropdown_selector, dropdown_by) pre_action_url = self.driver.current_url try: if option_by == "index": Select(element).select_by_index(option) elif option_by == "value": Select(element).select_by_value(option) else: Select(element).select_by_visible_text(option) except (StaleElementReferenceException, ENI_Exception): self.wait_for_ready_state_complete() time.sleep(0.05) element = self.wait_for_element_present( dropdown_selector, by=dropdown_by, timeout=timeout) if option_by == "index": Select(element).select_by_index(option) elif option_by == "value": Select(element).select_by_value(option) else: Select(element).select_by_visible_text(option) if settings.WAIT_FOR_RSC_ON_CLICKS: self.wait_for_ready_state_complete() if self.demo_mode: if self.driver.current_url != pre_action_url: self.__demo_mode_pause_if_active() else: self.__demo_mode_pause_if_active(tiny=True) elif self.slow_mode: self.__slow_mode_pause_if_active()
[ "def", "__select_option", "(", "self", ",", "dropdown_selector", ",", "option", ",", "dropdown_by", "=", "By", ".", "CSS_SELECTOR", ",", "option_by", "=", "\"text\"", ",", "timeout", "=", "None", ")", ":", "from", "selenium", ".", "webdriver", ".", "support", ".", "ui", "import", "Select", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "if", "page_utils", ".", "is_xpath_selector", "(", "dropdown_selector", ")", ":", "dropdown_by", "=", "By", ".", "XPATH", "self", ".", "wait_for_ready_state_complete", "(", ")", "element", "=", "self", ".", "wait_for_element_present", "(", "dropdown_selector", ",", "by", "=", "dropdown_by", ",", "timeout", "=", "timeout", ")", "if", "self", ".", "is_element_visible", "(", "dropdown_selector", ",", "by", "=", "dropdown_by", ")", ":", "self", ".", "__demo_mode_highlight_if_active", "(", "dropdown_selector", ",", "dropdown_by", ")", "pre_action_url", "=", "self", ".", "driver", ".", "current_url", "try", ":", "if", "option_by", "==", "\"index\"", ":", "Select", "(", "element", ")", ".", "select_by_index", "(", "option", ")", "elif", "option_by", "==", "\"value\"", ":", "Select", "(", "element", ")", ".", "select_by_value", "(", "option", ")", "else", ":", "Select", "(", "element", ")", ".", "select_by_visible_text", "(", "option", ")", "except", "(", "StaleElementReferenceException", ",", "ENI_Exception", ")", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "time", ".", "sleep", "(", "0.05", ")", "element", "=", "self", ".", "wait_for_element_present", "(", "dropdown_selector", ",", "by", "=", "dropdown_by", ",", "timeout", "=", "timeout", ")", "if", "option_by", "==", "\"index\"", ":", "Select", "(", "element", ")", ".", "select_by_index", "(", "option", ")", "elif", "option_by", "==", "\"value\"", ":", "Select", "(", "element", ")", ".", "select_by_value", "(", "option", ")", "else", ":", "Select", "(", "element", ")", ".", "select_by_visible_text", "(", "option", ")", "if", "settings", ".", "WAIT_FOR_RSC_ON_CLICKS", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "if", "self", ".", "demo_mode", ":", "if", "self", ".", "driver", ".", "current_url", "!=", "pre_action_url", ":", "self", ".", "__demo_mode_pause_if_active", "(", ")", "else", ":", "self", ".", "__demo_mode_pause_if_active", "(", "tiny", "=", "True", ")", "elif", "self", ".", "slow_mode", ":", "self", ".", "__slow_mode_pause_if_active", "(", ")" ]
[ 1293, 4 ]
[ 1339, 46 ]
python
en
['en', 'en', 'en']
True
BaseCase.select_option_by_text
(self, dropdown_selector, option, dropdown_by=By.CSS_SELECTOR, timeout=None)
Selects an HTML <select> option by option text. @Params dropdown_selector - the <select> selector option - the text of the option
Selects an HTML <select> option by option text.
def select_option_by_text(self, dropdown_selector, option, dropdown_by=By.CSS_SELECTOR, timeout=None): """ Selects an HTML <select> option by option text. @Params dropdown_selector - the <select> selector option - the text of the option """ if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) self.__select_option(dropdown_selector, option, dropdown_by=dropdown_by, option_by="text", timeout=timeout)
[ "def", "select_option_by_text", "(", "self", ",", "dropdown_selector", ",", "option", ",", "dropdown_by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "self", ".", "__select_option", "(", "dropdown_selector", ",", "option", ",", "dropdown_by", "=", "dropdown_by", ",", "option_by", "=", "\"text\"", ",", "timeout", "=", "timeout", ")" ]
[ 1341, 4 ]
[ 1354, 45 ]
python
en
['en', 'en', 'en']
True
BaseCase.select_option_by_index
(self, dropdown_selector, option, dropdown_by=By.CSS_SELECTOR, timeout=None)
Selects an HTML <select> option by option index. @Params dropdown_selector - the <select> selector option - the index number of the option
Selects an HTML <select> option by option index.
def select_option_by_index(self, dropdown_selector, option, dropdown_by=By.CSS_SELECTOR, timeout=None): """ Selects an HTML <select> option by option index. @Params dropdown_selector - the <select> selector option - the index number of the option """ if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) self.__select_option(dropdown_selector, option, dropdown_by=dropdown_by, option_by="index", timeout=timeout)
[ "def", "select_option_by_index", "(", "self", ",", "dropdown_selector", ",", "option", ",", "dropdown_by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "self", ".", "__select_option", "(", "dropdown_selector", ",", "option", ",", "dropdown_by", "=", "dropdown_by", ",", "option_by", "=", "\"index\"", ",", "timeout", "=", "timeout", ")" ]
[ 1356, 4 ]
[ 1369, 45 ]
python
en
['en', 'en', 'en']
True
BaseCase.select_option_by_value
(self, dropdown_selector, option, dropdown_by=By.CSS_SELECTOR, timeout=None)
Selects an HTML <select> option by option value. @Params dropdown_selector - the <select> selector option - the value property of the option
Selects an HTML <select> option by option value.
def select_option_by_value(self, dropdown_selector, option, dropdown_by=By.CSS_SELECTOR, timeout=None): """ Selects an HTML <select> option by option value. @Params dropdown_selector - the <select> selector option - the value property of the option """ if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) self.__select_option(dropdown_selector, option, dropdown_by=dropdown_by, option_by="value", timeout=timeout)
[ "def", "select_option_by_value", "(", "self", ",", "dropdown_selector", ",", "option", ",", "dropdown_by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "self", ".", "__select_option", "(", "dropdown_selector", ",", "option", ",", "dropdown_by", "=", "dropdown_by", ",", "option_by", "=", "\"value\"", ",", "timeout", "=", "timeout", ")" ]
[ 1371, 4 ]
[ 1384, 45 ]
python
en
['en', 'en', 'en']
True
BaseCase.load_html_string
(self, html_string, new_page=True)
Loads an HTML string into the web browser. If new_page==True, the page will switch to: "data:text/html," If new_page==False, will load HTML into the current page.
Loads an HTML string into the web browser. If new_page==True, the page will switch to: "data:text/html," If new_page==False, will load HTML into the current page.
def load_html_string(self, html_string, new_page=True): """ Loads an HTML string into the web browser. If new_page==True, the page will switch to: "data:text/html," If new_page==False, will load HTML into the current page. """ soup = self.get_beautiful_soup(html_string) found_base = False links = soup.findAll("link") href = None for link in links: if link.get("rel") == ["canonical"] and link.get("href"): found_base = True href = link.get("href") href = self.get_domain_url(href) if found_base and html_string.count("<head>") == 1 and ( html_string.count("<base") == 0): html_string = html_string.replace( "<head>", '<head><base href="%s">' % href) elif not found_base: bases = soup.findAll("base") for base in bases: if base.get("href"): href = base.get("href") if href: html_string = html_string.replace( 'base: "."', 'base: "%s"' % href) soup = self.get_beautiful_soup(html_string) scripts = soup.findAll("script") for script in scripts: if script.get("type") != "application/json": html_string = html_string.replace(str(script), "") soup = self.get_beautiful_soup(html_string) found_head = False found_body = False html_head = None html_body = None if soup.head and len(str(soup.head)) > 12: found_head = True html_head = str(soup.head) html_head = re.escape(html_head) html_head = self.__escape_quotes_if_needed(html_head) html_head = html_head.replace('\\ ', ' ') if soup.body and len(str(soup.body)) > 12: found_body = True html_body = str(soup.body) html_body = html_body.replace("\xc2\xa0", "&#xA0;") html_body = html_body.replace("\xc2\xa1", "&#xA1;") html_body = html_body.replace("\xc2\xa9", "&#xA9;") html_body = html_body.replace("\xc2\xb7", "&#xB7;") html_body = html_body.replace("\xc2\xbf", "&#xBF;") html_body = html_body.replace("\xc3\x97", "&#xD7;") html_body = html_body.replace("\xc3\xb7", "&#xF7;") html_body = re.escape(html_body) html_body = self.__escape_quotes_if_needed(html_body) html_body = html_body.replace('\\ ', ' ') html_string = re.escape(html_string) html_string = self.__escape_quotes_if_needed(html_string) html_string = html_string.replace('\\ ', ' ') if new_page: self.open("data:text/html,") inner_head = '''document.getElementsByTagName("head")[0].innerHTML''' inner_body = '''document.getElementsByTagName("body")[0].innerHTML''' if not found_body: self.execute_script( '''%s = \"%s\"''' % (inner_body, html_string)) elif found_body and not found_head: self.execute_script( '''%s = \"%s\"''' % (inner_body, html_body)) elif found_body and found_head: self.execute_script( '''%s = \"%s\"''' % (inner_head, html_head)) self.execute_script( '''%s = \"%s\"''' % (inner_body, html_body)) else: raise Exception("Logic Error!") for script in scripts: js_code = script.string js_src = script.get("src") if js_code and script.get("type") != "application/json": js_code_lines = js_code.split('\n') new_lines = [] for line in js_code_lines: line = line.strip() new_lines.append(line) js_code = '\n'.join(new_lines) js_utils.add_js_code(self.driver, js_code) elif js_src: js_utils.add_js_link(self.driver, js_src) else: pass
[ "def", "load_html_string", "(", "self", ",", "html_string", ",", "new_page", "=", "True", ")", ":", "soup", "=", "self", ".", "get_beautiful_soup", "(", "html_string", ")", "found_base", "=", "False", "links", "=", "soup", ".", "findAll", "(", "\"link\"", ")", "href", "=", "None", "for", "link", "in", "links", ":", "if", "link", ".", "get", "(", "\"rel\"", ")", "==", "[", "\"canonical\"", "]", "and", "link", ".", "get", "(", "\"href\"", ")", ":", "found_base", "=", "True", "href", "=", "link", ".", "get", "(", "\"href\"", ")", "href", "=", "self", ".", "get_domain_url", "(", "href", ")", "if", "found_base", "and", "html_string", ".", "count", "(", "\"<head>\"", ")", "==", "1", "and", "(", "html_string", ".", "count", "(", "\"<base\"", ")", "==", "0", ")", ":", "html_string", "=", "html_string", ".", "replace", "(", "\"<head>\"", ",", "'<head><base href=\"%s\">'", "%", "href", ")", "elif", "not", "found_base", ":", "bases", "=", "soup", ".", "findAll", "(", "\"base\"", ")", "for", "base", "in", "bases", ":", "if", "base", ".", "get", "(", "\"href\"", ")", ":", "href", "=", "base", ".", "get", "(", "\"href\"", ")", "if", "href", ":", "html_string", "=", "html_string", ".", "replace", "(", "'base: \".\"'", ",", "'base: \"%s\"'", "%", "href", ")", "soup", "=", "self", ".", "get_beautiful_soup", "(", "html_string", ")", "scripts", "=", "soup", ".", "findAll", "(", "\"script\"", ")", "for", "script", "in", "scripts", ":", "if", "script", ".", "get", "(", "\"type\"", ")", "!=", "\"application/json\"", ":", "html_string", "=", "html_string", ".", "replace", "(", "str", "(", "script", ")", ",", "\"\"", ")", "soup", "=", "self", ".", "get_beautiful_soup", "(", "html_string", ")", "found_head", "=", "False", "found_body", "=", "False", "html_head", "=", "None", "html_body", "=", "None", "if", "soup", ".", "head", "and", "len", "(", "str", "(", "soup", ".", "head", ")", ")", ">", "12", ":", "found_head", "=", "True", "html_head", "=", "str", "(", "soup", ".", "head", ")", "html_head", "=", "re", ".", "escape", "(", "html_head", ")", "html_head", "=", "self", ".", "__escape_quotes_if_needed", "(", "html_head", ")", "html_head", "=", "html_head", ".", "replace", "(", "'\\\\ '", ",", "' '", ")", "if", "soup", ".", "body", "and", "len", "(", "str", "(", "soup", ".", "body", ")", ")", ">", "12", ":", "found_body", "=", "True", "html_body", "=", "str", "(", "soup", ".", "body", ")", "html_body", "=", "html_body", ".", "replace", "(", "\"\\xc2\\xa0\"", ",", "\"&#xA0;\"", ")", "html_body", "=", "html_body", ".", "replace", "(", "\"\\xc2\\xa1\"", ",", "\"&#xA1;\"", ")", "html_body", "=", "html_body", ".", "replace", "(", "\"\\xc2\\xa9\"", ",", "\"&#xA9;\"", ")", "html_body", "=", "html_body", ".", "replace", "(", "\"\\xc2\\xb7\"", ",", "\"&#xB7;\"", ")", "html_body", "=", "html_body", ".", "replace", "(", "\"\\xc2\\xbf\"", ",", "\"&#xBF;\"", ")", "html_body", "=", "html_body", ".", "replace", "(", "\"\\xc3\\x97\"", ",", "\"&#xD7;\"", ")", "html_body", "=", "html_body", ".", "replace", "(", "\"\\xc3\\xb7\"", ",", "\"&#xF7;\"", ")", "html_body", "=", "re", ".", "escape", "(", "html_body", ")", "html_body", "=", "self", ".", "__escape_quotes_if_needed", "(", "html_body", ")", "html_body", "=", "html_body", ".", "replace", "(", "'\\\\ '", ",", "' '", ")", "html_string", "=", "re", ".", "escape", "(", "html_string", ")", "html_string", "=", "self", ".", "__escape_quotes_if_needed", "(", "html_string", ")", "html_string", "=", "html_string", ".", "replace", "(", "'\\\\ '", ",", "' '", ")", "if", "new_page", ":", "self", ".", "open", "(", "\"data:text/html,\"", ")", "inner_head", "=", "'''document.getElementsByTagName(\"head\")[0].innerHTML'''", "inner_body", "=", "'''document.getElementsByTagName(\"body\")[0].innerHTML'''", "if", "not", "found_body", ":", "self", ".", "execute_script", "(", "'''%s = \\\"%s\\\"'''", "%", "(", "inner_body", ",", "html_string", ")", ")", "elif", "found_body", "and", "not", "found_head", ":", "self", ".", "execute_script", "(", "'''%s = \\\"%s\\\"'''", "%", "(", "inner_body", ",", "html_body", ")", ")", "elif", "found_body", "and", "found_head", ":", "self", ".", "execute_script", "(", "'''%s = \\\"%s\\\"'''", "%", "(", "inner_head", ",", "html_head", ")", ")", "self", ".", "execute_script", "(", "'''%s = \\\"%s\\\"'''", "%", "(", "inner_body", ",", "html_body", ")", ")", "else", ":", "raise", "Exception", "(", "\"Logic Error!\"", ")", "for", "script", "in", "scripts", ":", "js_code", "=", "script", ".", "string", "js_src", "=", "script", ".", "get", "(", "\"src\"", ")", "if", "js_code", "and", "script", ".", "get", "(", "\"type\"", ")", "!=", "\"application/json\"", ":", "js_code_lines", "=", "js_code", ".", "split", "(", "'\\n'", ")", "new_lines", "=", "[", "]", "for", "line", "in", "js_code_lines", ":", "line", "=", "line", ".", "strip", "(", ")", "new_lines", ".", "append", "(", "line", ")", "js_code", "=", "'\\n'", ".", "join", "(", "new_lines", ")", "js_utils", ".", "add_js_code", "(", "self", ".", "driver", ",", "js_code", ")", "elif", "js_src", ":", "js_utils", ".", "add_js_link", "(", "self", ".", "driver", ",", "js_src", ")", "else", ":", "pass" ]
[ 1386, 4 ]
[ 1480, 20 ]
python
en
['en', 'en', 'en']
True
BaseCase.load_html_file
(self, html_file, new_page=True)
Loads a local html file into the browser from a relative file path. If new_page==True, the page will switch to: "data:text/html," If new_page==False, will load HTML into the current page. Local images and other local src content WILL BE IGNORED.
Loads a local html file into the browser from a relative file path. If new_page==True, the page will switch to: "data:text/html," If new_page==False, will load HTML into the current page. Local images and other local src content WILL BE IGNORED.
def load_html_file(self, html_file, new_page=True): """ Loads a local html file into the browser from a relative file path. If new_page==True, the page will switch to: "data:text/html," If new_page==False, will load HTML into the current page. Local images and other local src content WILL BE IGNORED. """ if self.__looks_like_a_page_url(html_file): self.open(html_file) return if len(html_file) < 6 or not html_file.endswith(".html"): raise Exception('Expecting a ".html" file!') abs_path = os.path.abspath('.') file_path = None if abs_path in html_file: file_path = html_file else: file_path = abs_path + "/%s" % html_file html_string = None with open(file_path, 'r') as f: html_string = f.read().strip() self.load_html_string(html_string, new_page)
[ "def", "load_html_file", "(", "self", ",", "html_file", ",", "new_page", "=", "True", ")", ":", "if", "self", ".", "__looks_like_a_page_url", "(", "html_file", ")", ":", "self", ".", "open", "(", "html_file", ")", "return", "if", "len", "(", "html_file", ")", "<", "6", "or", "not", "html_file", ".", "endswith", "(", "\".html\"", ")", ":", "raise", "Exception", "(", "'Expecting a \".html\" file!'", ")", "abs_path", "=", "os", ".", "path", ".", "abspath", "(", "'.'", ")", "file_path", "=", "None", "if", "abs_path", "in", "html_file", ":", "file_path", "=", "html_file", "else", ":", "file_path", "=", "abs_path", "+", "\"/%s\"", "%", "html_file", "html_string", "=", "None", "with", "open", "(", "file_path", ",", "'r'", ")", "as", "f", ":", "html_string", "=", "f", ".", "read", "(", ")", ".", "strip", "(", ")", "self", ".", "load_html_string", "(", "html_string", ",", "new_page", ")" ]
[ 1482, 4 ]
[ 1501, 52 ]
python
en
['en', 'en', 'en']
True
BaseCase.open_html_file
(self, html_file)
Opens a local html file into the browser from a relative file path. The URL displayed in the web browser will start with "file://".
Opens a local html file into the browser from a relative file path. The URL displayed in the web browser will start with "file://".
def open_html_file(self, html_file): """ Opens a local html file into the browser from a relative file path. The URL displayed in the web browser will start with "file://". """ if self.__looks_like_a_page_url(html_file): self.open(html_file) return if len(html_file) < 6 or not html_file.endswith(".html"): raise Exception('Expecting a ".html" file!') abs_path = os.path.abspath('.') file_path = None if abs_path in html_file: file_path = html_file else: file_path = abs_path + "/%s" % html_file self.open("file://" + file_path)
[ "def", "open_html_file", "(", "self", ",", "html_file", ")", ":", "if", "self", ".", "__looks_like_a_page_url", "(", "html_file", ")", ":", "self", ".", "open", "(", "html_file", ")", "return", "if", "len", "(", "html_file", ")", "<", "6", "or", "not", "html_file", ".", "endswith", "(", "\".html\"", ")", ":", "raise", "Exception", "(", "'Expecting a \".html\" file!'", ")", "abs_path", "=", "os", ".", "path", ".", "abspath", "(", "'.'", ")", "file_path", "=", "None", "if", "abs_path", "in", "html_file", ":", "file_path", "=", "html_file", "else", ":", "file_path", "=", "abs_path", "+", "\"/%s\"", "%", "html_file", "self", ".", "open", "(", "\"file://\"", "+", "file_path", ")" ]
[ 1503, 4 ]
[ 1517, 40 ]
python
en
['en', 'en', 'en']
True
BaseCase.safe_execute_script
(self, script)
When executing a script that contains a jQuery command, it's important that the jQuery library has been loaded first. This method will load jQuery if it wasn't already loaded.
When executing a script that contains a jQuery command, it's important that the jQuery library has been loaded first. This method will load jQuery if it wasn't already loaded.
def safe_execute_script(self, script): """ When executing a script that contains a jQuery command, it's important that the jQuery library has been loaded first. This method will load jQuery if it wasn't already loaded. """ try: self.execute_script(script) except Exception: # The likely reason this fails is because: "jQuery is not defined" self.activate_jquery() # It's a good thing we can define it here self.execute_script(script)
[ "def", "safe_execute_script", "(", "self", ",", "script", ")", ":", "try", ":", "self", ".", "execute_script", "(", "script", ")", "except", "Exception", ":", "# The likely reason this fails is because: \"jQuery is not defined\"", "self", ".", "activate_jquery", "(", ")", "# It's a good thing we can define it here", "self", ".", "execute_script", "(", "script", ")" ]
[ 1527, 4 ]
[ 1536, 39 ]
python
en
['en', 'en', 'en']
True
BaseCase.switch_to_frame
(self, frame, timeout=None)
Wait for an iframe to appear, and switch to it. This should be usable as a drop-in replacement for driver.switch_to.frame(). @Params frame - the frame element, name, id, index, or selector timeout - the time to wait for the alert in seconds
Wait for an iframe to appear, and switch to it. This should be usable as a drop-in replacement for driver.switch_to.frame().
def switch_to_frame(self, frame, timeout=None): """ Wait for an iframe to appear, and switch to it. This should be usable as a drop-in replacement for driver.switch_to.frame(). @Params frame - the frame element, name, id, index, or selector timeout - the time to wait for the alert in seconds """ if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) page_actions.switch_to_frame(self.driver, frame, timeout)
[ "def", "switch_to_frame", "(", "self", ",", "frame", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "page_actions", ".", "switch_to_frame", "(", "self", ".", "driver", ",", "frame", ",", "timeout", ")" ]
[ 1550, 4 ]
[ 1562, 65 ]
python
en
['en', 'error', 'th']
False
BaseCase.switch_to_default_content
(self)
Brings driver control outside the current iframe. (If driver control is inside an iframe, the driver control will be set to one level above the current frame. If the driver control is not currenly in an iframe, nothing will happen.)
Brings driver control outside the current iframe. (If driver control is inside an iframe, the driver control will be set to one level above the current frame. If the driver control is not currenly in an iframe, nothing will happen.)
def switch_to_default_content(self): """ Brings driver control outside the current iframe. (If driver control is inside an iframe, the driver control will be set to one level above the current frame. If the driver control is not currenly in an iframe, nothing will happen.) """ self.driver.switch_to.default_content()
[ "def", "switch_to_default_content", "(", "self", ")", ":", "self", ".", "driver", ".", "switch_to", ".", "default_content", "(", ")" ]
[ 1564, 4 ]
[ 1569, 47 ]
python
en
['en', 'en', 'en']
True
BaseCase.open_new_window
(self, switch_to=True)
Opens a new browser tab/window and switches to it by default.
Opens a new browser tab/window and switches to it by default.
def open_new_window(self, switch_to=True): """ Opens a new browser tab/window and switches to it by default. """ self.driver.execute_script("window.open('');") time.sleep(0.01) if switch_to: self.switch_to_window(len(self.driver.window_handles) - 1)
[ "def", "open_new_window", "(", "self", ",", "switch_to", "=", "True", ")", ":", "self", ".", "driver", ".", "execute_script", "(", "\"window.open('');\"", ")", "time", ".", "sleep", "(", "0.01", ")", "if", "switch_to", ":", "self", ".", "switch_to_window", "(", "len", "(", "self", ".", "driver", ".", "window_handles", ")", "-", "1", ")" ]
[ 1571, 4 ]
[ 1576, 70 ]
python
en
['en', 'en', 'en']
True
BaseCase.get_new_driver
(self, browser=None, headless=None, servername=None, port=None, proxy=None, agent=None, switch_to=True, cap_file=None, cap_string=None, disable_csp=None, enable_sync=None, use_auto_ext=None, no_sandbox=None, disable_gpu=None, incognito=None, guest_mode=None, devtools=None, user_data_dir=None, extension_zip=None, extension_dir=None, is_mobile=False, d_width=None, d_height=None, d_p_r=None)
This method spins up an extra browser for tests that require more than one. The first browser is already provided by tests that import base_case.BaseCase from seleniumbase. If parameters aren't specified, the method uses the same as the default driver. @Params browser - the browser to use. (Ex: "chrome", "firefox") headless - the option to run webdriver in headless mode servername - if using a Selenium Grid, set the host address here port - if using a Selenium Grid, set the host port here proxy - if using a proxy server, specify the "host:port" combo here switch_to - the option to switch to the new driver (default = True) cap_file - the file containing desired capabilities for the browser cap_string - the string with desired capabilities for the browser disable_csp - an option to disable Chrome's Content Security Policy enable_sync - the option to enable the Chrome Sync feature (Chrome) use_auto_ext - the option to enable Chrome's Automation Extension no_sandbox - the option to enable the "No-Sandbox" feature (Chrome) disable_gpu - the option to enable Chrome's "Disable GPU" feature incognito - the option to enable Chrome's Incognito mode (Chrome) guest - the option to enable Chrome's Guest mode (Chrome) devtools - the option to open Chrome's DevTools on start (Chrome) user_data_dir - Chrome's User Data Directory to use (Chrome-only) extension_zip - A Chrome Extension ZIP file to use (Chrome-only) extension_dir - A Chrome Extension folder to use (Chrome-only) is_mobile - the option to use the mobile emulator (Chrome-only) d_width - the device width of the mobile emulator (Chrome-only) d_height - the device height of the mobile emulator (Chrome-only) d_p_r - the device pixel ratio of the mobile emulator (Chrome-only)
This method spins up an extra browser for tests that require more than one. The first browser is already provided by tests that import base_case.BaseCase from seleniumbase. If parameters aren't specified, the method uses the same as the default driver.
def get_new_driver(self, browser=None, headless=None, servername=None, port=None, proxy=None, agent=None, switch_to=True, cap_file=None, cap_string=None, disable_csp=None, enable_sync=None, use_auto_ext=None, no_sandbox=None, disable_gpu=None, incognito=None, guest_mode=None, devtools=None, user_data_dir=None, extension_zip=None, extension_dir=None, is_mobile=False, d_width=None, d_height=None, d_p_r=None): """ This method spins up an extra browser for tests that require more than one. The first browser is already provided by tests that import base_case.BaseCase from seleniumbase. If parameters aren't specified, the method uses the same as the default driver. @Params browser - the browser to use. (Ex: "chrome", "firefox") headless - the option to run webdriver in headless mode servername - if using a Selenium Grid, set the host address here port - if using a Selenium Grid, set the host port here proxy - if using a proxy server, specify the "host:port" combo here switch_to - the option to switch to the new driver (default = True) cap_file - the file containing desired capabilities for the browser cap_string - the string with desired capabilities for the browser disable_csp - an option to disable Chrome's Content Security Policy enable_sync - the option to enable the Chrome Sync feature (Chrome) use_auto_ext - the option to enable Chrome's Automation Extension no_sandbox - the option to enable the "No-Sandbox" feature (Chrome) disable_gpu - the option to enable Chrome's "Disable GPU" feature incognito - the option to enable Chrome's Incognito mode (Chrome) guest - the option to enable Chrome's Guest mode (Chrome) devtools - the option to open Chrome's DevTools on start (Chrome) user_data_dir - Chrome's User Data Directory to use (Chrome-only) extension_zip - A Chrome Extension ZIP file to use (Chrome-only) extension_dir - A Chrome Extension folder to use (Chrome-only) is_mobile - the option to use the mobile emulator (Chrome-only) d_width - the device width of the mobile emulator (Chrome-only) d_height - the device height of the mobile emulator (Chrome-only) d_p_r - the device pixel ratio of the mobile emulator (Chrome-only) """ if self.browser == "remote" and self.servername == "localhost": raise Exception('Cannot use "remote" browser driver on localhost!' ' Did you mean to connect to a remote Grid server' ' such as BrowserStack or Sauce Labs? In that' ' case, you must specify the "server" and "port"' ' parameters on the command line! ' 'Example: ' '--server=user:[email protected] --port=80') browserstack_ref = ( 'https://browserstack.com/automate/capabilities') sauce_labs_ref = ( 'https://wiki.saucelabs.com/display/DOCS/Platform+Configurator#/') if self.browser == "remote" and not (self.cap_file or self.cap_string): raise Exception('Need to specify a desired capabilities file when ' 'using "--browser=remote". Add "--cap_file=FILE". ' 'File should be in the Python format used by: ' '%s OR ' '%s ' 'See SeleniumBase/examples/sample_cap_file_BS.py ' 'and SeleniumBase/examples/sample_cap_file_SL.py' % (browserstack_ref, sauce_labs_ref)) if browser is None: browser = self.browser browser_name = browser if headless is None: headless = self.headless if servername is None: servername = self.servername if port is None: port = self.port use_grid = False if servername != "localhost": # Use Selenium Grid (Use "127.0.0.1" for localhost Grid) use_grid = True proxy_string = proxy if proxy_string is None: proxy_string = self.proxy_string user_agent = agent if user_agent is None: user_agent = self.user_agent if disable_csp is None: disable_csp = self.disable_csp if enable_sync is None: enable_sync = self.enable_sync if use_auto_ext is None: use_auto_ext = self.use_auto_ext if no_sandbox is None: no_sandbox = self.no_sandbox if disable_gpu is None: disable_gpu = self.disable_gpu if incognito is None: incognito = self.incognito if guest_mode is None: guest_mode = self.guest_mode if devtools is None: devtools = self.devtools if user_data_dir is None: user_data_dir = self.user_data_dir if extension_zip is None: extension_zip = self.extension_zip if extension_dir is None: extension_dir = self.extension_dir # Due to https://stackoverflow.com/questions/23055651/ , skip extension # if self.demo_mode or self.masterqa_mode: # disable_csp = True test_id = self.__get_test_id() if cap_file is None: cap_file = self.cap_file if cap_string is None: cap_string = self.cap_string if is_mobile is None: is_mobile = False if d_width is None: d_width = self.__device_width if d_height is None: d_height = self.__device_height if d_p_r is None: d_p_r = self.__device_pixel_ratio valid_browsers = constants.ValidBrowsers.valid_browsers if browser_name not in valid_browsers: raise Exception("Browser: {%s} is not a valid browser option. " "Valid options = {%s}" % (browser, valid_browsers)) # Launch a web browser from seleniumbase.core import browser_launcher new_driver = browser_launcher.get_driver(browser_name=browser_name, headless=headless, use_grid=use_grid, servername=servername, port=port, proxy_string=proxy_string, user_agent=user_agent, cap_file=cap_file, cap_string=cap_string, disable_csp=disable_csp, enable_sync=enable_sync, use_auto_ext=use_auto_ext, no_sandbox=no_sandbox, disable_gpu=disable_gpu, incognito=incognito, guest_mode=guest_mode, devtools=devtools, user_data_dir=user_data_dir, extension_zip=extension_zip, extension_dir=extension_dir, test_id=test_id, mobile_emulator=is_mobile, device_width=d_width, device_height=d_height, device_pixel_ratio=d_p_r) self._drivers_list.append(new_driver) if switch_to: self.driver = new_driver if self.headless: # Make sure the invisible browser window is big enough width = settings.HEADLESS_START_WIDTH height = settings.HEADLESS_START_HEIGHT try: self.driver.set_window_size(width, height) self.wait_for_ready_state_complete() except Exception: # This shouldn't fail, but in case it does, # get safely through setUp() so that # WebDrivers can get closed during tearDown(). pass else: if self.browser == 'chrome' or self.browser == 'edge': width = settings.CHROME_START_WIDTH height = settings.CHROME_START_HEIGHT try: if self.maximize_option: self.driver.maximize_window() else: self.driver.set_window_size(width, height) self.wait_for_ready_state_complete() except Exception: pass # Keep existing browser resolution elif self.browser == 'firefox': pass # No changes elif self.browser == 'safari': if self.maximize_option: try: self.driver.maximize_window() self.wait_for_ready_state_complete() except Exception: pass # Keep existing browser resolution else: try: self.driver.set_window_rect(10, 30, 945, 630) except Exception: pass if self.start_page and len(self.start_page) >= 4: if page_utils.is_valid_url(self.start_page): self.open(self.start_page) else: new_start_page = "http://" + self.start_page if page_utils.is_valid_url(new_start_page): self.open(new_start_page) return new_driver
[ "def", "get_new_driver", "(", "self", ",", "browser", "=", "None", ",", "headless", "=", "None", ",", "servername", "=", "None", ",", "port", "=", "None", ",", "proxy", "=", "None", ",", "agent", "=", "None", ",", "switch_to", "=", "True", ",", "cap_file", "=", "None", ",", "cap_string", "=", "None", ",", "disable_csp", "=", "None", ",", "enable_sync", "=", "None", ",", "use_auto_ext", "=", "None", ",", "no_sandbox", "=", "None", ",", "disable_gpu", "=", "None", ",", "incognito", "=", "None", ",", "guest_mode", "=", "None", ",", "devtools", "=", "None", ",", "user_data_dir", "=", "None", ",", "extension_zip", "=", "None", ",", "extension_dir", "=", "None", ",", "is_mobile", "=", "False", ",", "d_width", "=", "None", ",", "d_height", "=", "None", ",", "d_p_r", "=", "None", ")", ":", "if", "self", ".", "browser", "==", "\"remote\"", "and", "self", ".", "servername", "==", "\"localhost\"", ":", "raise", "Exception", "(", "'Cannot use \"remote\" browser driver on localhost!'", "' Did you mean to connect to a remote Grid server'", "' such as BrowserStack or Sauce Labs? In that'", "' case, you must specify the \"server\" and \"port\"'", "' parameters on the command line! '", "'Example: '", "'--server=user:[email protected] --port=80'", ")", "browserstack_ref", "=", "(", "'https://browserstack.com/automate/capabilities'", ")", "sauce_labs_ref", "=", "(", "'https://wiki.saucelabs.com/display/DOCS/Platform+Configurator#/'", ")", "if", "self", ".", "browser", "==", "\"remote\"", "and", "not", "(", "self", ".", "cap_file", "or", "self", ".", "cap_string", ")", ":", "raise", "Exception", "(", "'Need to specify a desired capabilities file when '", "'using \"--browser=remote\". Add \"--cap_file=FILE\". '", "'File should be in the Python format used by: '", "'%s OR '", "'%s '", "'See SeleniumBase/examples/sample_cap_file_BS.py '", "'and SeleniumBase/examples/sample_cap_file_SL.py'", "%", "(", "browserstack_ref", ",", "sauce_labs_ref", ")", ")", "if", "browser", "is", "None", ":", "browser", "=", "self", ".", "browser", "browser_name", "=", "browser", "if", "headless", "is", "None", ":", "headless", "=", "self", ".", "headless", "if", "servername", "is", "None", ":", "servername", "=", "self", ".", "servername", "if", "port", "is", "None", ":", "port", "=", "self", ".", "port", "use_grid", "=", "False", "if", "servername", "!=", "\"localhost\"", ":", "# Use Selenium Grid (Use \"127.0.0.1\" for localhost Grid)", "use_grid", "=", "True", "proxy_string", "=", "proxy", "if", "proxy_string", "is", "None", ":", "proxy_string", "=", "self", ".", "proxy_string", "user_agent", "=", "agent", "if", "user_agent", "is", "None", ":", "user_agent", "=", "self", ".", "user_agent", "if", "disable_csp", "is", "None", ":", "disable_csp", "=", "self", ".", "disable_csp", "if", "enable_sync", "is", "None", ":", "enable_sync", "=", "self", ".", "enable_sync", "if", "use_auto_ext", "is", "None", ":", "use_auto_ext", "=", "self", ".", "use_auto_ext", "if", "no_sandbox", "is", "None", ":", "no_sandbox", "=", "self", ".", "no_sandbox", "if", "disable_gpu", "is", "None", ":", "disable_gpu", "=", "self", ".", "disable_gpu", "if", "incognito", "is", "None", ":", "incognito", "=", "self", ".", "incognito", "if", "guest_mode", "is", "None", ":", "guest_mode", "=", "self", ".", "guest_mode", "if", "devtools", "is", "None", ":", "devtools", "=", "self", ".", "devtools", "if", "user_data_dir", "is", "None", ":", "user_data_dir", "=", "self", ".", "user_data_dir", "if", "extension_zip", "is", "None", ":", "extension_zip", "=", "self", ".", "extension_zip", "if", "extension_dir", "is", "None", ":", "extension_dir", "=", "self", ".", "extension_dir", "# Due to https://stackoverflow.com/questions/23055651/ , skip extension", "# if self.demo_mode or self.masterqa_mode:", "# disable_csp = True", "test_id", "=", "self", ".", "__get_test_id", "(", ")", "if", "cap_file", "is", "None", ":", "cap_file", "=", "self", ".", "cap_file", "if", "cap_string", "is", "None", ":", "cap_string", "=", "self", ".", "cap_string", "if", "is_mobile", "is", "None", ":", "is_mobile", "=", "False", "if", "d_width", "is", "None", ":", "d_width", "=", "self", ".", "__device_width", "if", "d_height", "is", "None", ":", "d_height", "=", "self", ".", "__device_height", "if", "d_p_r", "is", "None", ":", "d_p_r", "=", "self", ".", "__device_pixel_ratio", "valid_browsers", "=", "constants", ".", "ValidBrowsers", ".", "valid_browsers", "if", "browser_name", "not", "in", "valid_browsers", ":", "raise", "Exception", "(", "\"Browser: {%s} is not a valid browser option. \"", "\"Valid options = {%s}\"", "%", "(", "browser", ",", "valid_browsers", ")", ")", "# Launch a web browser", "from", "seleniumbase", ".", "core", "import", "browser_launcher", "new_driver", "=", "browser_launcher", ".", "get_driver", "(", "browser_name", "=", "browser_name", ",", "headless", "=", "headless", ",", "use_grid", "=", "use_grid", ",", "servername", "=", "servername", ",", "port", "=", "port", ",", "proxy_string", "=", "proxy_string", ",", "user_agent", "=", "user_agent", ",", "cap_file", "=", "cap_file", ",", "cap_string", "=", "cap_string", ",", "disable_csp", "=", "disable_csp", ",", "enable_sync", "=", "enable_sync", ",", "use_auto_ext", "=", "use_auto_ext", ",", "no_sandbox", "=", "no_sandbox", ",", "disable_gpu", "=", "disable_gpu", ",", "incognito", "=", "incognito", ",", "guest_mode", "=", "guest_mode", ",", "devtools", "=", "devtools", ",", "user_data_dir", "=", "user_data_dir", ",", "extension_zip", "=", "extension_zip", ",", "extension_dir", "=", "extension_dir", ",", "test_id", "=", "test_id", ",", "mobile_emulator", "=", "is_mobile", ",", "device_width", "=", "d_width", ",", "device_height", "=", "d_height", ",", "device_pixel_ratio", "=", "d_p_r", ")", "self", ".", "_drivers_list", ".", "append", "(", "new_driver", ")", "if", "switch_to", ":", "self", ".", "driver", "=", "new_driver", "if", "self", ".", "headless", ":", "# Make sure the invisible browser window is big enough", "width", "=", "settings", ".", "HEADLESS_START_WIDTH", "height", "=", "settings", ".", "HEADLESS_START_HEIGHT", "try", ":", "self", ".", "driver", ".", "set_window_size", "(", "width", ",", "height", ")", "self", ".", "wait_for_ready_state_complete", "(", ")", "except", "Exception", ":", "# This shouldn't fail, but in case it does,", "# get safely through setUp() so that", "# WebDrivers can get closed during tearDown().", "pass", "else", ":", "if", "self", ".", "browser", "==", "'chrome'", "or", "self", ".", "browser", "==", "'edge'", ":", "width", "=", "settings", ".", "CHROME_START_WIDTH", "height", "=", "settings", ".", "CHROME_START_HEIGHT", "try", ":", "if", "self", ".", "maximize_option", ":", "self", ".", "driver", ".", "maximize_window", "(", ")", "else", ":", "self", ".", "driver", ".", "set_window_size", "(", "width", ",", "height", ")", "self", ".", "wait_for_ready_state_complete", "(", ")", "except", "Exception", ":", "pass", "# Keep existing browser resolution", "elif", "self", ".", "browser", "==", "'firefox'", ":", "pass", "# No changes", "elif", "self", ".", "browser", "==", "'safari'", ":", "if", "self", ".", "maximize_option", ":", "try", ":", "self", ".", "driver", ".", "maximize_window", "(", ")", "self", ".", "wait_for_ready_state_complete", "(", ")", "except", "Exception", ":", "pass", "# Keep existing browser resolution", "else", ":", "try", ":", "self", ".", "driver", ".", "set_window_rect", "(", "10", ",", "30", ",", "945", ",", "630", ")", "except", "Exception", ":", "pass", "if", "self", ".", "start_page", "and", "len", "(", "self", ".", "start_page", ")", ">=", "4", ":", "if", "page_utils", ".", "is_valid_url", "(", "self", ".", "start_page", ")", ":", "self", ".", "open", "(", "self", ".", "start_page", ")", "else", ":", "new_start_page", "=", "\"http://\"", "+", "self", ".", "start_page", "if", "page_utils", ".", "is_valid_url", "(", "new_start_page", ")", ":", "self", ".", "open", "(", "new_start_page", ")", "return", "new_driver" ]
[ 1588, 4 ]
[ 1783, 25 ]
python
en
['en', 'en', 'en']
True
BaseCase.switch_to_driver
(self, driver)
Sets self.driver to the specified driver. You may need this if using self.get_new_driver() in your code.
Sets self.driver to the specified driver. You may need this if using self.get_new_driver() in your code.
def switch_to_driver(self, driver): """ Sets self.driver to the specified driver. You may need this if using self.get_new_driver() in your code. """ self.driver = driver
[ "def", "switch_to_driver", "(", "self", ",", "driver", ")", ":", "self", ".", "driver", "=", "driver" ]
[ 1785, 4 ]
[ 1788, 28 ]
python
en
['en', 'en', 'en']
True
BaseCase.switch_to_default_driver
(self)
Sets self.driver to the default/original driver.
Sets self.driver to the default/original driver.
def switch_to_default_driver(self): """ Sets self.driver to the default/original driver. """ self.driver = self._default_driver
[ "def", "switch_to_default_driver", "(", "self", ")", ":", "self", ".", "driver", "=", "self", ".", "_default_driver" ]
[ 1790, 4 ]
[ 1792, 42 ]
python
en
['en', 'pt', 'en']
True
BaseCase.save_screenshot
(self, name, folder=None)
The screenshot will be in PNG format.
The screenshot will be in PNG format.
def save_screenshot(self, name, folder=None): """ The screenshot will be in PNG format. """ return page_actions.save_screenshot(self.driver, name, folder)
[ "def", "save_screenshot", "(", "self", ",", "name", ",", "folder", "=", "None", ")", ":", "return", "page_actions", ".", "save_screenshot", "(", "self", ".", "driver", ",", "name", ",", "folder", ")" ]
[ 1794, 4 ]
[ 1796, 70 ]
python
en
['en', 'en', 'en']
True
BaseCase.save_page_source
(self, name, folder=None)
Saves the page HTML to the current directory (or given subfolder). If the folder specified doesn't exist, it will get created. @Params name - The file name to save the current page's HTML to. folder - The folder to save the file to. (Default = current folder)
Saves the page HTML to the current directory (or given subfolder). If the folder specified doesn't exist, it will get created.
def save_page_source(self, name, folder=None): """ Saves the page HTML to the current directory (or given subfolder). If the folder specified doesn't exist, it will get created. @Params name - The file name to save the current page's HTML to. folder - The folder to save the file to. (Default = current folder) """ return page_actions.save_page_source(self.driver, name, folder)
[ "def", "save_page_source", "(", "self", ",", "name", ",", "folder", "=", "None", ")", ":", "return", "page_actions", ".", "save_page_source", "(", "self", ".", "driver", ",", "name", ",", "folder", ")" ]
[ 1798, 4 ]
[ 1805, 71 ]
python
en
['en', 'en', 'en']
True
BaseCase.save_cookies
(self, name="cookies.txt")
Saves the page cookies to the "saved_cookies" folder.
Saves the page cookies to the "saved_cookies" folder.
def save_cookies(self, name="cookies.txt"): """ Saves the page cookies to the "saved_cookies" folder. """ cookies = self.driver.get_cookies() json_cookies = json.dumps(cookies) if name.endswith('/'): raise Exception("Invalid filename for Cookies!") if '/' in name: name = name.split('/')[-1] if len(name) < 1: raise Exception("Filename for Cookies is too short!") if not name.endswith(".txt"): name = name + ".txt" folder = constants.SavedCookies.STORAGE_FOLDER abs_path = os.path.abspath('.') file_path = abs_path + "/%s" % folder if not os.path.exists(file_path): os.makedirs(file_path) cookies_file_path = "%s/%s" % (file_path, name) cookies_file = codecs.open(cookies_file_path, "w+") cookies_file.writelines(json_cookies) cookies_file.close()
[ "def", "save_cookies", "(", "self", ",", "name", "=", "\"cookies.txt\"", ")", ":", "cookies", "=", "self", ".", "driver", ".", "get_cookies", "(", ")", "json_cookies", "=", "json", ".", "dumps", "(", "cookies", ")", "if", "name", ".", "endswith", "(", "'/'", ")", ":", "raise", "Exception", "(", "\"Invalid filename for Cookies!\"", ")", "if", "'/'", "in", "name", ":", "name", "=", "name", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "len", "(", "name", ")", "<", "1", ":", "raise", "Exception", "(", "\"Filename for Cookies is too short!\"", ")", "if", "not", "name", ".", "endswith", "(", "\".txt\"", ")", ":", "name", "=", "name", "+", "\".txt\"", "folder", "=", "constants", ".", "SavedCookies", ".", "STORAGE_FOLDER", "abs_path", "=", "os", ".", "path", ".", "abspath", "(", "'.'", ")", "file_path", "=", "abs_path", "+", "\"/%s\"", "%", "folder", "if", "not", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "os", ".", "makedirs", "(", "file_path", ")", "cookies_file_path", "=", "\"%s/%s\"", "%", "(", "file_path", ",", "name", ")", "cookies_file", "=", "codecs", ".", "open", "(", "cookies_file_path", ",", "\"w+\"", ")", "cookies_file", ".", "writelines", "(", "json_cookies", ")", "cookies_file", ".", "close", "(", ")" ]
[ 1807, 4 ]
[ 1827, 28 ]
python
en
['en', 'en', 'en']
True
BaseCase.load_cookies
(self, name="cookies.txt")
Loads the page cookies from the "saved_cookies" folder.
Loads the page cookies from the "saved_cookies" folder.
def load_cookies(self, name="cookies.txt"): """ Loads the page cookies from the "saved_cookies" folder. """ if name.endswith('/'): raise Exception("Invalid filename for Cookies!") if '/' in name: name = name.split('/')[-1] if len(name) < 1: raise Exception("Filename for Cookies is too short!") if not name.endswith(".txt"): name = name + ".txt" folder = constants.SavedCookies.STORAGE_FOLDER abs_path = os.path.abspath('.') file_path = abs_path + "/%s" % folder cookies_file_path = "%s/%s" % (file_path, name) json_cookies = None with open(cookies_file_path, 'r') as f: json_cookies = f.read().strip() cookies = json.loads(json_cookies) for cookie in cookies: if 'expiry' in cookie: del cookie['expiry'] self.driver.add_cookie(cookie)
[ "def", "load_cookies", "(", "self", ",", "name", "=", "\"cookies.txt\"", ")", ":", "if", "name", ".", "endswith", "(", "'/'", ")", ":", "raise", "Exception", "(", "\"Invalid filename for Cookies!\"", ")", "if", "'/'", "in", "name", ":", "name", "=", "name", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "len", "(", "name", ")", "<", "1", ":", "raise", "Exception", "(", "\"Filename for Cookies is too short!\"", ")", "if", "not", "name", ".", "endswith", "(", "\".txt\"", ")", ":", "name", "=", "name", "+", "\".txt\"", "folder", "=", "constants", ".", "SavedCookies", ".", "STORAGE_FOLDER", "abs_path", "=", "os", ".", "path", ".", "abspath", "(", "'.'", ")", "file_path", "=", "abs_path", "+", "\"/%s\"", "%", "folder", "cookies_file_path", "=", "\"%s/%s\"", "%", "(", "file_path", ",", "name", ")", "json_cookies", "=", "None", "with", "open", "(", "cookies_file_path", ",", "'r'", ")", "as", "f", ":", "json_cookies", "=", "f", ".", "read", "(", ")", ".", "strip", "(", ")", "cookies", "=", "json", ".", "loads", "(", "json_cookies", ")", "for", "cookie", "in", "cookies", ":", "if", "'expiry'", "in", "cookie", ":", "del", "cookie", "[", "'expiry'", "]", "self", ".", "driver", ".", "add_cookie", "(", "cookie", ")" ]
[ 1829, 4 ]
[ 1850, 42 ]
python
en
['en', 'en', 'en']
True
BaseCase.delete_all_cookies
(self)
Deletes all cookies in the web browser. Does NOT delete the saved cookies file.
Deletes all cookies in the web browser. Does NOT delete the saved cookies file.
def delete_all_cookies(self): """ Deletes all cookies in the web browser. Does NOT delete the saved cookies file. """ self.driver.delete_all_cookies()
[ "def", "delete_all_cookies", "(", "self", ")", ":", "self", ".", "driver", ".", "delete_all_cookies", "(", ")" ]
[ 1852, 4 ]
[ 1855, 40 ]
python
en
['en', 'en', 'en']
True
BaseCase.delete_saved_cookies
(self, name="cookies.txt")
Deletes the cookies file from the "saved_cookies" folder. Does NOT delete the cookies from the web browser.
Deletes the cookies file from the "saved_cookies" folder. Does NOT delete the cookies from the web browser.
def delete_saved_cookies(self, name="cookies.txt"): """ Deletes the cookies file from the "saved_cookies" folder. Does NOT delete the cookies from the web browser. """ if name.endswith('/'): raise Exception("Invalid filename for Cookies!") if '/' in name: name = name.split('/')[-1] if len(name) < 1: raise Exception("Filename for Cookies is too short!") if not name.endswith(".txt"): name = name + ".txt" folder = constants.SavedCookies.STORAGE_FOLDER abs_path = os.path.abspath('.') file_path = abs_path + "/%s" % folder cookies_file_path = "%s/%s" % (file_path, name) if os.path.exists(cookies_file_path): if cookies_file_path.endswith('.txt'): os.remove(cookies_file_path)
[ "def", "delete_saved_cookies", "(", "self", ",", "name", "=", "\"cookies.txt\"", ")", ":", "if", "name", ".", "endswith", "(", "'/'", ")", ":", "raise", "Exception", "(", "\"Invalid filename for Cookies!\"", ")", "if", "'/'", "in", "name", ":", "name", "=", "name", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "len", "(", "name", ")", "<", "1", ":", "raise", "Exception", "(", "\"Filename for Cookies is too short!\"", ")", "if", "not", "name", ".", "endswith", "(", "\".txt\"", ")", ":", "name", "=", "name", "+", "\".txt\"", "folder", "=", "constants", ".", "SavedCookies", ".", "STORAGE_FOLDER", "abs_path", "=", "os", ".", "path", ".", "abspath", "(", "'.'", ")", "file_path", "=", "abs_path", "+", "\"/%s\"", "%", "folder", "cookies_file_path", "=", "\"%s/%s\"", "%", "(", "file_path", ",", "name", ")", "if", "os", ".", "path", ".", "exists", "(", "cookies_file_path", ")", ":", "if", "cookies_file_path", ".", "endswith", "(", "'.txt'", ")", ":", "os", ".", "remove", "(", "cookies_file_path", ")" ]
[ 1857, 4 ]
[ 1874, 44 ]
python
en
['en', 'en', 'en']
True
BaseCase.activate_jquery
(self)
If "jQuery is not defined", use this method to activate it for use. This happens because jQuery is not always defined on web sites.
If "jQuery is not defined", use this method to activate it for use. This happens because jQuery is not always defined on web sites.
def activate_jquery(self): """ If "jQuery is not defined", use this method to activate it for use. This happens because jQuery is not always defined on web sites. """ js_utils.activate_jquery(self.driver) self.wait_for_ready_state_complete()
[ "def", "activate_jquery", "(", "self", ")", ":", "js_utils", ".", "activate_jquery", "(", "self", ".", "driver", ")", "self", ".", "wait_for_ready_state_complete", "(", ")" ]
[ 1929, 4 ]
[ 1933, 44 ]
python
en
['en', 'en', 'en']
True
BaseCase.bring_to_front
(self, selector, by=By.CSS_SELECTOR)
Updates the Z-index of a page element to bring it into view. Useful when getting a WebDriverException, such as the one below: { Element is not clickable at point (#, #). Other element would receive the click: ... }
Updates the Z-index of a page element to bring it into view. Useful when getting a WebDriverException, such as the one below: { Element is not clickable at point (#, #). Other element would receive the click: ... }
def bring_to_front(self, selector, by=By.CSS_SELECTOR): """ Updates the Z-index of a page element to bring it into view. Useful when getting a WebDriverException, such as the one below: { Element is not clickable at point (#, #). Other element would receive the click: ... } """ selector, by = self.__recalculate_selector(selector, by) self.wait_for_element_visible( selector, by=by, timeout=settings.SMALL_TIMEOUT) try: selector = self.convert_to_css_selector(selector, by=by) except Exception: # Don't run action if can't convert to CSS_Selector for JavaScript return selector = re.escape(selector) selector = self.__escape_quotes_if_needed(selector) script = ("""document.querySelector('%s').style.zIndex = '999999';""" % selector) self.execute_script(script)
[ "def", "bring_to_front", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "self", ".", "wait_for_element_visible", "(", "selector", ",", "by", "=", "by", ",", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", ")", "try", ":", "selector", "=", "self", ".", "convert_to_css_selector", "(", "selector", ",", "by", "=", "by", ")", "except", "Exception", ":", "# Don't run action if can't convert to CSS_Selector for JavaScript", "return", "selector", "=", "re", ".", "escape", "(", "selector", ")", "selector", "=", "self", ".", "__escape_quotes_if_needed", "(", "selector", ")", "script", "=", "(", "\"\"\"document.querySelector('%s').style.zIndex = '999999';\"\"\"", "%", "selector", ")", "self", ".", "execute_script", "(", "script", ")" ]
[ 1941, 4 ]
[ 1958, 35 ]
python
en
['en', 'en', 'en']
True
BaseCase.highlight
(self, selector, by=By.CSS_SELECTOR, loops=None, scroll=True)
This method uses fancy JavaScript to highlight an element. Used during demo_mode. @Params selector - the selector of the element to find by - the type of selector to search by (Default: CSS) loops - # of times to repeat the highlight animation (Default: 4. Each loop lasts for about 0.18s) scroll - the option to scroll to the element first (Default: True)
This method uses fancy JavaScript to highlight an element. Used during demo_mode.
def highlight(self, selector, by=By.CSS_SELECTOR, loops=None, scroll=True): """ This method uses fancy JavaScript to highlight an element. Used during demo_mode. @Params selector - the selector of the element to find by - the type of selector to search by (Default: CSS) loops - # of times to repeat the highlight animation (Default: 4. Each loop lasts for about 0.18s) scroll - the option to scroll to the element first (Default: True) """ selector, by = self.__recalculate_selector(selector, by) element = self.wait_for_element_visible( selector, by=by, timeout=settings.SMALL_TIMEOUT) if not loops: loops = settings.HIGHLIGHTS if scroll: try: self.__slow_scroll_to_element(element) except (StaleElementReferenceException, ENI_Exception): self.wait_for_ready_state_complete() time.sleep(0.05) element = self.wait_for_element_visible( selector, by=by, timeout=settings.SMALL_TIMEOUT) self.__slow_scroll_to_element(element) try: selector = self.convert_to_css_selector(selector, by=by) except Exception: # Don't highlight if can't convert to CSS_SELECTOR return if self.highlights: loops = self.highlights if self.browser == 'ie': loops = 1 # Override previous setting because IE is slow loops = int(loops) o_bs = '' # original_box_shadow try: style = element.get_attribute('style') except (StaleElementReferenceException, ENI_Exception): self.wait_for_ready_state_complete() time.sleep(0.05) element = self.wait_for_element_visible( selector, by=By.CSS_SELECTOR, timeout=settings.SMALL_TIMEOUT) style = element.get_attribute('style') if style: if 'box-shadow: ' in style: box_start = style.find('box-shadow: ') box_end = style.find(';', box_start) + 1 original_box_shadow = style[box_start:box_end] o_bs = original_box_shadow if ":contains" not in selector and ":first" not in selector: selector = re.escape(selector) selector = self.__escape_quotes_if_needed(selector) self.__highlight_with_js(selector, loops, o_bs) else: selector = self.__make_css_match_first_element_only(selector) selector = re.escape(selector) selector = self.__escape_quotes_if_needed(selector) try: self.__highlight_with_jquery(selector, loops, o_bs) except Exception: pass # JQuery probably couldn't load. Skip highlighting. time.sleep(0.065)
[ "def", "highlight", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "loops", "=", "None", ",", "scroll", "=", "True", ")", ":", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "element", "=", "self", ".", "wait_for_element_visible", "(", "selector", ",", "by", "=", "by", ",", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", ")", "if", "not", "loops", ":", "loops", "=", "settings", ".", "HIGHLIGHTS", "if", "scroll", ":", "try", ":", "self", ".", "__slow_scroll_to_element", "(", "element", ")", "except", "(", "StaleElementReferenceException", ",", "ENI_Exception", ")", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "time", ".", "sleep", "(", "0.05", ")", "element", "=", "self", ".", "wait_for_element_visible", "(", "selector", ",", "by", "=", "by", ",", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", ")", "self", ".", "__slow_scroll_to_element", "(", "element", ")", "try", ":", "selector", "=", "self", ".", "convert_to_css_selector", "(", "selector", ",", "by", "=", "by", ")", "except", "Exception", ":", "# Don't highlight if can't convert to CSS_SELECTOR", "return", "if", "self", ".", "highlights", ":", "loops", "=", "self", ".", "highlights", "if", "self", ".", "browser", "==", "'ie'", ":", "loops", "=", "1", "# Override previous setting because IE is slow", "loops", "=", "int", "(", "loops", ")", "o_bs", "=", "''", "# original_box_shadow", "try", ":", "style", "=", "element", ".", "get_attribute", "(", "'style'", ")", "except", "(", "StaleElementReferenceException", ",", "ENI_Exception", ")", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "time", ".", "sleep", "(", "0.05", ")", "element", "=", "self", ".", "wait_for_element_visible", "(", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", ")", "style", "=", "element", ".", "get_attribute", "(", "'style'", ")", "if", "style", ":", "if", "'box-shadow: '", "in", "style", ":", "box_start", "=", "style", ".", "find", "(", "'box-shadow: '", ")", "box_end", "=", "style", ".", "find", "(", "';'", ",", "box_start", ")", "+", "1", "original_box_shadow", "=", "style", "[", "box_start", ":", "box_end", "]", "o_bs", "=", "original_box_shadow", "if", "\":contains\"", "not", "in", "selector", "and", "\":first\"", "not", "in", "selector", ":", "selector", "=", "re", ".", "escape", "(", "selector", ")", "selector", "=", "self", ".", "__escape_quotes_if_needed", "(", "selector", ")", "self", ".", "__highlight_with_js", "(", "selector", ",", "loops", ",", "o_bs", ")", "else", ":", "selector", "=", "self", ".", "__make_css_match_first_element_only", "(", "selector", ")", "selector", "=", "re", ".", "escape", "(", "selector", ")", "selector", "=", "self", ".", "__escape_quotes_if_needed", "(", "selector", ")", "try", ":", "self", ".", "__highlight_with_jquery", "(", "selector", ",", "loops", ",", "o_bs", ")", "except", "Exception", ":", "pass", "# JQuery probably couldn't load. Skip highlighting.", "time", ".", "sleep", "(", "0.065", ")" ]
[ 1972, 4 ]
[ 2037, 25 ]
python
en
['en', 'en', 'en']
True
BaseCase.press_up_arrow
(self, selector="html", times=1, by=By.CSS_SELECTOR)
Simulates pressing the UP Arrow on the keyboard. By default, "html" will be used as the CSS Selector target. You can specify how many times in-a-row the action happens.
Simulates pressing the UP Arrow on the keyboard. By default, "html" will be used as the CSS Selector target. You can specify how many times in-a-row the action happens.
def press_up_arrow(self, selector="html", times=1, by=By.CSS_SELECTOR): """ Simulates pressing the UP Arrow on the keyboard. By default, "html" will be used as the CSS Selector target. You can specify how many times in-a-row the action happens. """ if times < 1: return element = self.wait_for_element_present(selector) self.__demo_mode_highlight_if_active(selector, by) if not self.demo_mode: self.__scroll_to_element(element, selector, by) for i in range(int(times)): try: element.send_keys(Keys.ARROW_UP) except Exception: self.wait_for_ready_state_complete() element = self.wait_for_element_visible(selector) element.send_keys(Keys.ARROW_UP) time.sleep(0.01) if self.slow_mode: time.sleep(0.1)
[ "def", "press_up_arrow", "(", "self", ",", "selector", "=", "\"html\"", ",", "times", "=", "1", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "if", "times", "<", "1", ":", "return", "element", "=", "self", ".", "wait_for_element_present", "(", "selector", ")", "self", ".", "__demo_mode_highlight_if_active", "(", "selector", ",", "by", ")", "if", "not", "self", ".", "demo_mode", ":", "self", ".", "__scroll_to_element", "(", "element", ",", "selector", ",", "by", ")", "for", "i", "in", "range", "(", "int", "(", "times", ")", ")", ":", "try", ":", "element", ".", "send_keys", "(", "Keys", ".", "ARROW_UP", ")", "except", "Exception", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "element", "=", "self", ".", "wait_for_element_visible", "(", "selector", ")", "element", ".", "send_keys", "(", "Keys", ".", "ARROW_UP", ")", "time", ".", "sleep", "(", "0.01", ")", "if", "self", ".", "slow_mode", ":", "time", ".", "sleep", "(", "0.1", ")" ]
[ 2045, 4 ]
[ 2064, 31 ]
python
en
['en', 'en', 'en']
True
BaseCase.press_down_arrow
(self, selector="html", times=1, by=By.CSS_SELECTOR)
Simulates pressing the DOWN Arrow on the keyboard. By default, "html" will be used as the CSS Selector target. You can specify how many times in-a-row the action happens.
Simulates pressing the DOWN Arrow on the keyboard. By default, "html" will be used as the CSS Selector target. You can specify how many times in-a-row the action happens.
def press_down_arrow(self, selector="html", times=1, by=By.CSS_SELECTOR): """ Simulates pressing the DOWN Arrow on the keyboard. By default, "html" will be used as the CSS Selector target. You can specify how many times in-a-row the action happens. """ if times < 1: return element = self.wait_for_element_present(selector) self.__demo_mode_highlight_if_active(selector, by) if not self.demo_mode: self.__scroll_to_element(element, selector, by) for i in range(int(times)): try: element.send_keys(Keys.ARROW_DOWN) except Exception: self.wait_for_ready_state_complete() element = self.wait_for_element_visible(selector) element.send_keys(Keys.ARROW_DOWN) time.sleep(0.01) if self.slow_mode: time.sleep(0.1)
[ "def", "press_down_arrow", "(", "self", ",", "selector", "=", "\"html\"", ",", "times", "=", "1", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "if", "times", "<", "1", ":", "return", "element", "=", "self", ".", "wait_for_element_present", "(", "selector", ")", "self", ".", "__demo_mode_highlight_if_active", "(", "selector", ",", "by", ")", "if", "not", "self", ".", "demo_mode", ":", "self", ".", "__scroll_to_element", "(", "element", ",", "selector", ",", "by", ")", "for", "i", "in", "range", "(", "int", "(", "times", ")", ")", ":", "try", ":", "element", ".", "send_keys", "(", "Keys", ".", "ARROW_DOWN", ")", "except", "Exception", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "element", "=", "self", ".", "wait_for_element_visible", "(", "selector", ")", "element", ".", "send_keys", "(", "Keys", ".", "ARROW_DOWN", ")", "time", ".", "sleep", "(", "0.01", ")", "if", "self", ".", "slow_mode", ":", "time", ".", "sleep", "(", "0.1", ")" ]
[ 2066, 4 ]
[ 2085, 31 ]
python
en
['en', 'en', 'en']
True
BaseCase.press_left_arrow
(self, selector="html", times=1, by=By.CSS_SELECTOR)
Simulates pressing the LEFT Arrow on the keyboard. By default, "html" will be used as the CSS Selector target. You can specify how many times in-a-row the action happens.
Simulates pressing the LEFT Arrow on the keyboard. By default, "html" will be used as the CSS Selector target. You can specify how many times in-a-row the action happens.
def press_left_arrow(self, selector="html", times=1, by=By.CSS_SELECTOR): """ Simulates pressing the LEFT Arrow on the keyboard. By default, "html" will be used as the CSS Selector target. You can specify how many times in-a-row the action happens. """ if times < 1: return element = self.wait_for_element_present(selector) self.__demo_mode_highlight_if_active(selector, by) if not self.demo_mode: self.__scroll_to_element(element, selector, by) for i in range(int(times)): try: element.send_keys(Keys.ARROW_LEFT) except Exception: self.wait_for_ready_state_complete() element = self.wait_for_element_visible(selector) element.send_keys(Keys.ARROW_LEFT) time.sleep(0.01) if self.slow_mode: time.sleep(0.1)
[ "def", "press_left_arrow", "(", "self", ",", "selector", "=", "\"html\"", ",", "times", "=", "1", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "if", "times", "<", "1", ":", "return", "element", "=", "self", ".", "wait_for_element_present", "(", "selector", ")", "self", ".", "__demo_mode_highlight_if_active", "(", "selector", ",", "by", ")", "if", "not", "self", ".", "demo_mode", ":", "self", ".", "__scroll_to_element", "(", "element", ",", "selector", ",", "by", ")", "for", "i", "in", "range", "(", "int", "(", "times", ")", ")", ":", "try", ":", "element", ".", "send_keys", "(", "Keys", ".", "ARROW_LEFT", ")", "except", "Exception", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "element", "=", "self", ".", "wait_for_element_visible", "(", "selector", ")", "element", ".", "send_keys", "(", "Keys", ".", "ARROW_LEFT", ")", "time", ".", "sleep", "(", "0.01", ")", "if", "self", ".", "slow_mode", ":", "time", ".", "sleep", "(", "0.1", ")" ]
[ 2087, 4 ]
[ 2106, 31 ]
python
en
['en', 'en', 'en']
True
BaseCase.press_right_arrow
(self, selector="html", times=1, by=By.CSS_SELECTOR)
Simulates pressing the RIGHT Arrow on the keyboard. By default, "html" will be used as the CSS Selector target. You can specify how many times in-a-row the action happens.
Simulates pressing the RIGHT Arrow on the keyboard. By default, "html" will be used as the CSS Selector target. You can specify how many times in-a-row the action happens.
def press_right_arrow(self, selector="html", times=1, by=By.CSS_SELECTOR): """ Simulates pressing the RIGHT Arrow on the keyboard. By default, "html" will be used as the CSS Selector target. You can specify how many times in-a-row the action happens. """ if times < 1: return element = self.wait_for_element_present(selector) self.__demo_mode_highlight_if_active(selector, by) if not self.demo_mode: self.__scroll_to_element(element, selector, by) for i in range(int(times)): try: element.send_keys(Keys.ARROW_RIGHT) except Exception: self.wait_for_ready_state_complete() element = self.wait_for_element_visible(selector) element.send_keys(Keys.ARROW_RIGHT) time.sleep(0.01) if self.slow_mode: time.sleep(0.1)
[ "def", "press_right_arrow", "(", "self", ",", "selector", "=", "\"html\"", ",", "times", "=", "1", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "if", "times", "<", "1", ":", "return", "element", "=", "self", ".", "wait_for_element_present", "(", "selector", ")", "self", ".", "__demo_mode_highlight_if_active", "(", "selector", ",", "by", ")", "if", "not", "self", ".", "demo_mode", ":", "self", ".", "__scroll_to_element", "(", "element", ",", "selector", ",", "by", ")", "for", "i", "in", "range", "(", "int", "(", "times", ")", ")", ":", "try", ":", "element", ".", "send_keys", "(", "Keys", ".", "ARROW_RIGHT", ")", "except", "Exception", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "element", "=", "self", ".", "wait_for_element_visible", "(", "selector", ")", "element", ".", "send_keys", "(", "Keys", ".", "ARROW_RIGHT", ")", "time", ".", "sleep", "(", "0.01", ")", "if", "self", ".", "slow_mode", ":", "time", ".", "sleep", "(", "0.1", ")" ]
[ 2108, 4 ]
[ 2127, 31 ]
python
en
['en', 'en', 'en']
True
BaseCase.scroll_to
(self, selector, by=By.CSS_SELECTOR, timeout=None)
Fast scroll to destination
Fast scroll to destination
def scroll_to(self, selector, by=By.CSS_SELECTOR, timeout=None): ''' Fast scroll to destination ''' if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) if self.demo_mode or self.slow_mode: self.slow_scroll_to(selector, by=by, timeout=timeout) return element = self.wait_for_element_visible( selector, by=by, timeout=timeout) try: self.__scroll_to_element(element, selector, by) except (StaleElementReferenceException, ENI_Exception): self.wait_for_ready_state_complete() time.sleep(0.05) element = self.wait_for_element_visible( selector, by=by, timeout=timeout) self.__scroll_to_element(element, selector, by)
[ "def", "scroll_to", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "if", "self", ".", "demo_mode", "or", "self", ".", "slow_mode", ":", "self", ".", "slow_scroll_to", "(", "selector", ",", "by", "=", "by", ",", "timeout", "=", "timeout", ")", "return", "element", "=", "self", ".", "wait_for_element_visible", "(", "selector", ",", "by", "=", "by", ",", "timeout", "=", "timeout", ")", "try", ":", "self", ".", "__scroll_to_element", "(", "element", ",", "selector", ",", "by", ")", "except", "(", "StaleElementReferenceException", ",", "ENI_Exception", ")", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "time", ".", "sleep", "(", "0.05", ")", "element", "=", "self", ".", "wait_for_element_visible", "(", "selector", ",", "by", "=", "by", ",", "timeout", "=", "timeout", ")", "self", ".", "__scroll_to_element", "(", "element", ",", "selector", ",", "by", ")" ]
[ 2129, 4 ]
[ 2147, 59 ]
python
en
['en', 'en', 'en']
True
BaseCase.slow_scroll_to
(self, selector, by=By.CSS_SELECTOR, timeout=None)
Slow motion scroll to destination
Slow motion scroll to destination
def slow_scroll_to(self, selector, by=By.CSS_SELECTOR, timeout=None): ''' Slow motion scroll to destination ''' if not timeout: timeout = settings.SMALL_TIMEOUT if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) selector, by = self.__recalculate_selector(selector, by) element = self.wait_for_element_visible( selector, by=by, timeout=timeout) try: self.__slow_scroll_to_element(element) except (StaleElementReferenceException, ENI_Exception): self.wait_for_ready_state_complete() time.sleep(0.05) element = self.wait_for_element_visible( selector, by=by, timeout=timeout) self.__slow_scroll_to_element(element)
[ "def", "slow_scroll_to", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "__get_new_timeout", "(", "timeout", ")", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "element", "=", "self", ".", "wait_for_element_visible", "(", "selector", ",", "by", "=", "by", ",", "timeout", "=", "timeout", ")", "try", ":", "self", ".", "__slow_scroll_to_element", "(", "element", ")", "except", "(", "StaleElementReferenceException", ",", "ENI_Exception", ")", ":", "self", ".", "wait_for_ready_state_complete", "(", ")", "time", ".", "sleep", "(", "0.05", ")", "element", "=", "self", ".", "wait_for_element_visible", "(", "selector", ",", "by", "=", "by", ",", "timeout", "=", "timeout", ")", "self", ".", "__slow_scroll_to_element", "(", "element", ")" ]
[ 2149, 4 ]
[ 2165, 50 ]
python
en
['en', 'en', 'en']
True
SimpleCheckpointConfigurator.__init__
( self, name: str, data_context, site_names: Optional[Union[str, List[str]]] = "all", slack_webhook: Optional[str] = None, notify_on: Optional[str] = "all", notify_with: Optional[Union[str, List[str]]] = "all", **kwargs, )
After instantiation, call the .build() method to get a new Checkpoint. By default, the Checkpoint created will: 1. store the validation result 2. store evaluation parameters 3. update all data docs sites When configured, this builds a Checkpoint that sends a slack message. Args: name: The Checkpoint name data_context: a valid DataContext site_names: Names of sites to update. Defaults to "all". Set to None to skip updating data docs. slack_webhook: If present, a sleck message will be sent. notify_on: When to send a slack notification. Defaults to "all". Possible values: "all", "failure", "success" notify_with: optional list of DataDocs site names to display in Slack message. Defaults to showing all Examples: Most simple usage: ``` checkpoint = SimpleCheckpointBuilder("foo", data_context).build() ``` A Checkpoint that sends a slack message on all validation events. ``` checkpoint = SimpleCheckpointBuilder( "foo", data_context, slack_webhook="https://hooks.slack.com/foo/bar" ).build() ``` A Checkpoint that does not update data docs. ``` checkpoint = SimpleCheckpointBuilder("foo", data_context, site_names=None).build() ```
After instantiation, call the .build() method to get a new Checkpoint.
def __init__( self, name: str, data_context, site_names: Optional[Union[str, List[str]]] = "all", slack_webhook: Optional[str] = None, notify_on: Optional[str] = "all", notify_with: Optional[Union[str, List[str]]] = "all", **kwargs, ): """ After instantiation, call the .build() method to get a new Checkpoint. By default, the Checkpoint created will: 1. store the validation result 2. store evaluation parameters 3. update all data docs sites When configured, this builds a Checkpoint that sends a slack message. Args: name: The Checkpoint name data_context: a valid DataContext site_names: Names of sites to update. Defaults to "all". Set to None to skip updating data docs. slack_webhook: If present, a sleck message will be sent. notify_on: When to send a slack notification. Defaults to "all". Possible values: "all", "failure", "success" notify_with: optional list of DataDocs site names to display in Slack message. Defaults to showing all Examples: Most simple usage: ``` checkpoint = SimpleCheckpointBuilder("foo", data_context).build() ``` A Checkpoint that sends a slack message on all validation events. ``` checkpoint = SimpleCheckpointBuilder( "foo", data_context, slack_webhook="https://hooks.slack.com/foo/bar" ).build() ``` A Checkpoint that does not update data docs. ``` checkpoint = SimpleCheckpointBuilder("foo", data_context, site_names=None).build() ``` """ self.name = name self.data_context = data_context self.site_names = site_names self.notify_on = notify_on self.notify_with = notify_with self.slack_webhook = slack_webhook self.other_kwargs = kwargs
[ "def", "__init__", "(", "self", ",", "name", ":", "str", ",", "data_context", ",", "site_names", ":", "Optional", "[", "Union", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "\"all\"", ",", "slack_webhook", ":", "Optional", "[", "str", "]", "=", "None", ",", "notify_on", ":", "Optional", "[", "str", "]", "=", "\"all\"", ",", "notify_with", ":", "Optional", "[", "Union", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "\"all\"", ",", "*", "*", "kwargs", ",", ")", ":", "self", ".", "name", "=", "name", "self", ".", "data_context", "=", "data_context", "self", ".", "site_names", "=", "site_names", "self", ".", "notify_on", "=", "notify_on", "self", ".", "notify_with", "=", "notify_with", "self", ".", "slack_webhook", "=", "slack_webhook", "self", ".", "other_kwargs", "=", "kwargs" ]
[ 48, 4 ]
[ 103, 34 ]
python
en
['en', 'error', 'th']
False
SimpleCheckpointConfigurator.build
(self)
Build a Checkpoint.
Build a Checkpoint.
def build(self) -> CheckpointConfig: """Build a Checkpoint.""" self._validate_site_names(self.data_context) self._validate_notify_on() self._validate_notify_with() self._validate_slack_webhook() self._validate_slack_configuration() return self._build_checkpoint_config()
[ "def", "build", "(", "self", ")", "->", "CheckpointConfig", ":", "self", ".", "_validate_site_names", "(", "self", ".", "data_context", ")", "self", ".", "_validate_notify_on", "(", ")", "self", ".", "_validate_notify_with", "(", ")", "self", ".", "_validate_slack_webhook", "(", ")", "self", ".", "_validate_slack_configuration", "(", ")", "return", "self", ".", "_build_checkpoint_config", "(", ")" ]
[ 105, 4 ]
[ 113, 46 ]
python
en
['en', 'en', 'en']
True
SimpleCheckpointConfigurator._add_slack_action
(self, action_list: List[Dict])
The underlying SlackNotificationAction and SlackRenderer default to including links to all sites if the key notify_with is not present. We are intentionally hiding this from users of SimpleCheckpoint by having a default of "all" that sets the configuration appropriately.
The underlying SlackNotificationAction and SlackRenderer default to including links to all sites if the key notify_with is not present. We are intentionally hiding this from users of SimpleCheckpoint by having a default of "all" that sets the configuration appropriately.
def _add_slack_action(self, action_list: List[Dict]) -> List[Dict]: """ The underlying SlackNotificationAction and SlackRenderer default to including links to all sites if the key notify_with is not present. We are intentionally hiding this from users of SimpleCheckpoint by having a default of "all" that sets the configuration appropriately. """ _notify_with = self.notify_with if self.notify_with == "all": _notify_with = None action_list.append( ActionDicts.build_slack_action( self.slack_webhook, self.notify_on, _notify_with ) ) return action_list
[ "def", "_add_slack_action", "(", "self", ",", "action_list", ":", "List", "[", "Dict", "]", ")", "->", "List", "[", "Dict", "]", ":", "_notify_with", "=", "self", ".", "notify_with", "if", "self", ".", "notify_with", "==", "\"all\"", ":", "_notify_with", "=", "None", "action_list", ".", "append", "(", "ActionDicts", ".", "build_slack_action", "(", "self", ".", "slack_webhook", ",", "self", ".", "notify_on", ",", "_notify_with", ")", ")", "return", "action_list" ]
[ 160, 4 ]
[ 175, 26 ]
python
en
['en', 'error', 'th']
False
SimpleCheckpointConfigurator._validate_slack_configuration
(self)
Guide the user toward correct configuration.
Guide the user toward correct configuration.
def _validate_slack_configuration(self): """Guide the user toward correct configuration.""" if isinstance(self.notify_with, list) and self.slack_webhook is None: raise ValueError( "It appears you wish to send a slack message because you " "specified a list of sites in the notify_with parameter but " "you have not yet specified a slack_webhook. Please either " "specify a slack webhook or remove the notify_with parameter." ) if self.notify_on != "all" and self.slack_webhook is None: raise ValueError( "It appears you wish to send a slack message because you " "specified a condition in the notify_on parameter but " "you have not yet specified a slack_webhook. Please either " "specify a slack webhook or remove the notify_on parameter." )
[ "def", "_validate_slack_configuration", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "notify_with", ",", "list", ")", "and", "self", ".", "slack_webhook", "is", "None", ":", "raise", "ValueError", "(", "\"It appears you wish to send a slack message because you \"", "\"specified a list of sites in the notify_with parameter but \"", "\"you have not yet specified a slack_webhook. Please either \"", "\"specify a slack webhook or remove the notify_with parameter.\"", ")", "if", "self", ".", "notify_on", "!=", "\"all\"", "and", "self", ".", "slack_webhook", "is", "None", ":", "raise", "ValueError", "(", "\"It appears you wish to send a slack message because you \"", "\"specified a condition in the notify_on parameter but \"", "\"you have not yet specified a slack_webhook. Please either \"", "\"specify a slack webhook or remove the notify_on parameter.\"", ")" ]
[ 206, 4 ]
[ 221, 13 ]
python
en
['en', 'gl', 'en']
True
rgb
(dataset, at_index=0, x_coord='longitude', y_coord='latitude', bands=['red', 'green', 'blue'], paint_on_mask = [], min_possible=0, max_possible=10000, use_data_min=False, use_data_max=False, min_inten=0.15, max_inten=1.0, width=10, fig=None, ax=None)
Creates a figure showing an area, using three specified bands as the rgb componenets. Parameters ---------- dataset: xarray.Dataset A Dataset containing at least latitude and longitude coordinates and optionally time. The coordinate order should be time, latitude, and finally longitude. Must contain the data variables specified in the `bands` parameter. at_index: int The time index to show. x_coord, y_coord, time_coord: str Names of DataArrays in `dataset_in` to use as x, y, and time coordinates. bands: list-like A list-like containing 3 names of data variables in `dataset` to use as the red, green, and blue bands, respectively. min_possible, max_possible: int The minimum and maximum valid values for the selected bands according to the platform used to retrieve the data in `dataset`. For example, for Landsat these are generally 0 and 10000, respectively. use_data_min: bool Whether to use `min_possible` or the minimum among all selected bands as the band value which has a minimal intensity. use_data_max: bool Whether to use `max_possible` or the maximum among all selected bands as the band value which has a maximal intensity. min_inten, max_inten: float The min and max intensities for any band. These can be in range [0,1]. These can be used to brighten or darken the image. width: int The width of the figure in inches. fig: matplotlib.figure.Figure The figure to use for the plot. If only `fig` is supplied, the Axes object used will be the first. ax: matplotlib.axes.Axes The axes to use for the plot. Returns ------- fig, ax: matplotlib.figure.Figure, matplotlib.axes.Axes The figure and axes used for the plot.
Creates a figure showing an area, using three specified bands as the rgb componenets. Parameters ---------- dataset: xarray.Dataset A Dataset containing at least latitude and longitude coordinates and optionally time. The coordinate order should be time, latitude, and finally longitude. Must contain the data variables specified in the `bands` parameter. at_index: int The time index to show. x_coord, y_coord, time_coord: str Names of DataArrays in `dataset_in` to use as x, y, and time coordinates. bands: list-like A list-like containing 3 names of data variables in `dataset` to use as the red, green, and blue bands, respectively. min_possible, max_possible: int The minimum and maximum valid values for the selected bands according to the platform used to retrieve the data in `dataset`. For example, for Landsat these are generally 0 and 10000, respectively. use_data_min: bool Whether to use `min_possible` or the minimum among all selected bands as the band value which has a minimal intensity. use_data_max: bool Whether to use `max_possible` or the maximum among all selected bands as the band value which has a maximal intensity. min_inten, max_inten: float The min and max intensities for any band. These can be in range [0,1]. These can be used to brighten or darken the image. width: int The width of the figure in inches. fig: matplotlib.figure.Figure The figure to use for the plot. If only `fig` is supplied, the Axes object used will be the first. ax: matplotlib.axes.Axes The axes to use for the plot.
def rgb(dataset, at_index=0, x_coord='longitude', y_coord='latitude', bands=['red', 'green', 'blue'], paint_on_mask = [], min_possible=0, max_possible=10000, use_data_min=False, use_data_max=False, min_inten=0.15, max_inten=1.0, width=10, fig=None, ax=None): """ Creates a figure showing an area, using three specified bands as the rgb componenets. Parameters ---------- dataset: xarray.Dataset A Dataset containing at least latitude and longitude coordinates and optionally time. The coordinate order should be time, latitude, and finally longitude. Must contain the data variables specified in the `bands` parameter. at_index: int The time index to show. x_coord, y_coord, time_coord: str Names of DataArrays in `dataset_in` to use as x, y, and time coordinates. bands: list-like A list-like containing 3 names of data variables in `dataset` to use as the red, green, and blue bands, respectively. min_possible, max_possible: int The minimum and maximum valid values for the selected bands according to the platform used to retrieve the data in `dataset`. For example, for Landsat these are generally 0 and 10000, respectively. use_data_min: bool Whether to use `min_possible` or the minimum among all selected bands as the band value which has a minimal intensity. use_data_max: bool Whether to use `max_possible` or the maximum among all selected bands as the band value which has a maximal intensity. min_inten, max_inten: float The min and max intensities for any band. These can be in range [0,1]. These can be used to brighten or darken the image. width: int The width of the figure in inches. fig: matplotlib.figure.Figure The figure to use for the plot. If only `fig` is supplied, the Axes object used will be the first. ax: matplotlib.axes.Axes The axes to use for the plot. Returns ------- fig, ax: matplotlib.figure.Figure, matplotlib.axes.Axes The figure and axes used for the plot. """ ### < Dataset to RGB Format, needs float values between 0-1 rgb = np.stack([dataset[bands[0]], dataset[bands[1]], dataset[bands[2]]], axis = -1) # Interpolate values to be in the range [0,1] for creating the image. min_rgb = np.nanmin(rgb) if use_data_min else min_possible max_rgb = np.nanmax(rgb) if use_data_max else max_possible rgb = np.interp(rgb, (min_rgb, max_rgb), [min_inten,max_inten]) rgb = rgb.astype(float) ### > ### < takes a T/F mask, apply a color to T areas for mask, color in paint_on_mask: rgb[mask] = np.array(color)/ 255.0 ### > fig, ax = retrieve_or_create_fig_ax(fig, ax, figsize=figure_ratio(rgb.shape[:2], fixed_width = width)) xarray_set_axes_labels(dataset, ax, x_coord, y_coord) if 'time' in dataset.dims: ax.imshow(rgb[at_index]) else: ax.imshow(rgb) return fig, ax
[ "def", "rgb", "(", "dataset", ",", "at_index", "=", "0", ",", "x_coord", "=", "'longitude'", ",", "y_coord", "=", "'latitude'", ",", "bands", "=", "[", "'red'", ",", "'green'", ",", "'blue'", "]", ",", "paint_on_mask", "=", "[", "]", ",", "min_possible", "=", "0", ",", "max_possible", "=", "10000", ",", "use_data_min", "=", "False", ",", "use_data_max", "=", "False", ",", "min_inten", "=", "0.15", ",", "max_inten", "=", "1.0", ",", "width", "=", "10", ",", "fig", "=", "None", ",", "ax", "=", "None", ")", ":", "### < Dataset to RGB Format, needs float values between 0-1 ", "rgb", "=", "np", ".", "stack", "(", "[", "dataset", "[", "bands", "[", "0", "]", "]", ",", "dataset", "[", "bands", "[", "1", "]", "]", ",", "dataset", "[", "bands", "[", "2", "]", "]", "]", ",", "axis", "=", "-", "1", ")", "# Interpolate values to be in the range [0,1] for creating the image.", "min_rgb", "=", "np", ".", "nanmin", "(", "rgb", ")", "if", "use_data_min", "else", "min_possible", "max_rgb", "=", "np", ".", "nanmax", "(", "rgb", ")", "if", "use_data_max", "else", "max_possible", "rgb", "=", "np", ".", "interp", "(", "rgb", ",", "(", "min_rgb", ",", "max_rgb", ")", ",", "[", "min_inten", ",", "max_inten", "]", ")", "rgb", "=", "rgb", ".", "astype", "(", "float", ")", "### > ", "### < takes a T/F mask, apply a color to T areas ", "for", "mask", ",", "color", "in", "paint_on_mask", ":", "rgb", "[", "mask", "]", "=", "np", ".", "array", "(", "color", ")", "/", "255.0", "### > ", "fig", ",", "ax", "=", "retrieve_or_create_fig_ax", "(", "fig", ",", "ax", ",", "figsize", "=", "figure_ratio", "(", "rgb", ".", "shape", "[", ":", "2", "]", ",", "fixed_width", "=", "width", ")", ")", "xarray_set_axes_labels", "(", "dataset", ",", "ax", ",", "x_coord", ",", "y_coord", ")", "if", "'time'", "in", "dataset", ".", "dims", ":", "ax", ".", "imshow", "(", "rgb", "[", "at_index", "]", ")", "else", ":", "ax", ".", "imshow", "(", "rgb", ")", "return", "fig", ",", "ax" ]
[ 10, 0 ]
[ 82, 18 ]
python
en
['en', 'error', 'th']
False
find_filter_class
(filtername)
Lookup a filter by name. Return None if not found.
Lookup a filter by name. Return None if not found.
def find_filter_class(filtername): """Lookup a filter by name. Return None if not found.""" if filtername in FILTERS: return FILTERS[filtername] for name, cls in find_plugin_filters(): if name == filtername: return cls return None
[ "def", "find_filter_class", "(", "filtername", ")", ":", "if", "filtername", "in", "FILTERS", ":", "return", "FILTERS", "[", "filtername", "]", "for", "name", ",", "cls", "in", "find_plugin_filters", "(", ")", ":", "if", "name", "==", "filtername", ":", "return", "cls", "return", "None" ]
[ 22, 0 ]
[ 29, 15 ]
python
en
['en', 'en', 'en']
True
get_filter_by_name
(filtername, **options)
Return an instantiated filter. Options are passed to the filter initializer if wanted. Raise a ClassNotFound if not found.
Return an instantiated filter.
def get_filter_by_name(filtername, **options): """Return an instantiated filter. Options are passed to the filter initializer if wanted. Raise a ClassNotFound if not found. """ cls = find_filter_class(filtername) if cls: return cls(**options) else: raise ClassNotFound('filter %r not found' % filtername)
[ "def", "get_filter_by_name", "(", "filtername", ",", "*", "*", "options", ")", ":", "cls", "=", "find_filter_class", "(", "filtername", ")", "if", "cls", ":", "return", "cls", "(", "*", "*", "options", ")", "else", ":", "raise", "ClassNotFound", "(", "'filter %r not found'", "%", "filtername", ")" ]
[ 32, 0 ]
[ 42, 63 ]
python
en
['en', 'lb', 'en']
True
get_all_filters
()
Return a generator of all filter names.
Return a generator of all filter names.
def get_all_filters(): """Return a generator of all filter names.""" for name in FILTERS: yield name for name, _ in find_plugin_filters(): yield name
[ "def", "get_all_filters", "(", ")", ":", "for", "name", "in", "FILTERS", ":", "yield", "name", "for", "name", ",", "_", "in", "find_plugin_filters", "(", ")", ":", "yield", "name" ]
[ 45, 0 ]
[ 50, 18 ]
python
en
['en', 'en', 'en']
True
Scout.__init__
(self, app, version, install_id=None, id_plugin=None, id_plugin_args={}, scout_host="kubernaut.io", **kwargs)
Create a new Scout instance for later reports. :param app: The application name. Required. :param version: The application version. Required. :param install_id: Optional install_id. If set, Scout will believe it. :param id_plugin: Optional plugin function for obtaining an install_id. See below. :param id_plugin_args: Optional arguments to id_plugin. See below. :param kwargs: Any other keyword arguments will be merged into Scout's metadata. If an id_plugin is present, it is called with the following parameters: - this Scout instance - the passed-in app name - the passed-in id_plugin_args _as keyword arguments_ id_plugin(scout, app, **id_plugin_args) It must return - None to fall back to the default filesystem ID, or - a dict containing the ID and optional metadata: - The dict **must** have an `install_id` key with a non-empty value. - The dict **may** have other keys present, which will all be merged into Scout's `metadata`. If the plugin returns something invalid, Scout falls back to the default filesystem ID. See also Scout.configmap_install_id_plugin, which is an id_plugin that knows how to use a Kubernetes configmap (scout.config.$app) to store the install ID. Scout logs to the datawire.scout logger. It assumes that the logging system is configured to a sane default level, but you can change Scout's debug level with e.g. logging.getLogger("datawire.scout").setLevel(logging.DEBUG)
Create a new Scout instance for later reports.
def __init__(self, app, version, install_id=None, id_plugin=None, id_plugin_args={}, scout_host="kubernaut.io", **kwargs): """ Create a new Scout instance for later reports. :param app: The application name. Required. :param version: The application version. Required. :param install_id: Optional install_id. If set, Scout will believe it. :param id_plugin: Optional plugin function for obtaining an install_id. See below. :param id_plugin_args: Optional arguments to id_plugin. See below. :param kwargs: Any other keyword arguments will be merged into Scout's metadata. If an id_plugin is present, it is called with the following parameters: - this Scout instance - the passed-in app name - the passed-in id_plugin_args _as keyword arguments_ id_plugin(scout, app, **id_plugin_args) It must return - None to fall back to the default filesystem ID, or - a dict containing the ID and optional metadata: - The dict **must** have an `install_id` key with a non-empty value. - The dict **may** have other keys present, which will all be merged into Scout's `metadata`. If the plugin returns something invalid, Scout falls back to the default filesystem ID. See also Scout.configmap_install_id_plugin, which is an id_plugin that knows how to use a Kubernetes configmap (scout.config.$app) to store the install ID. Scout logs to the datawire.scout logger. It assumes that the logging system is configured to a sane default level, but you can change Scout's debug level with e.g. logging.getLogger("datawire.scout").setLevel(logging.DEBUG) """ self.app = Scout.__not_blank("app", app) self.version = Scout.__not_blank("version", version) self.metadata = kwargs if kwargs is not None else {} self.user_agent = self.create_user_agent() self.logger = logging.getLogger("datawire.scout") self.install_id = install_id if not self.install_id and id_plugin: plugin_response = id_plugin(self, app, **id_plugin_args) self.logger.debug("Scout: id_plugin returns {0}".format(json.dumps(plugin_response))) if plugin_response: if "install_id" in plugin_response: self.install_id = plugin_response["install_id"] del(plugin_response["install_id"]) if plugin_response: self.metadata = Scout.__merge_dicts(self.metadata, plugin_response) if not self.install_id: self.install_id = self.__filesystem_install_id(app) self.logger.debug("Scout using install_id {0}".format(self.install_id)) # scout options; controlled via env vars self.scout_host = os.getenv("SCOUT_HOST", scout_host) self.use_https = os.getenv("SCOUT_HTTPS", "1").lower() in {"1", "true", "yes"} self.disabled = Scout.__is_disabled()
[ "def", "__init__", "(", "self", ",", "app", ",", "version", ",", "install_id", "=", "None", ",", "id_plugin", "=", "None", ",", "id_plugin_args", "=", "{", "}", ",", "scout_host", "=", "\"kubernaut.io\"", ",", "*", "*", "kwargs", ")", ":", "self", ".", "app", "=", "Scout", ".", "__not_blank", "(", "\"app\"", ",", "app", ")", "self", ".", "version", "=", "Scout", ".", "__not_blank", "(", "\"version\"", ",", "version", ")", "self", ".", "metadata", "=", "kwargs", "if", "kwargs", "is", "not", "None", "else", "{", "}", "self", ".", "user_agent", "=", "self", ".", "create_user_agent", "(", ")", "self", ".", "logger", "=", "logging", ".", "getLogger", "(", "\"datawire.scout\"", ")", "self", ".", "install_id", "=", "install_id", "if", "not", "self", ".", "install_id", "and", "id_plugin", ":", "plugin_response", "=", "id_plugin", "(", "self", ",", "app", ",", "*", "*", "id_plugin_args", ")", "self", ".", "logger", ".", "debug", "(", "\"Scout: id_plugin returns {0}\"", ".", "format", "(", "json", ".", "dumps", "(", "plugin_response", ")", ")", ")", "if", "plugin_response", ":", "if", "\"install_id\"", "in", "plugin_response", ":", "self", ".", "install_id", "=", "plugin_response", "[", "\"install_id\"", "]", "del", "(", "plugin_response", "[", "\"install_id\"", "]", ")", "if", "plugin_response", ":", "self", ".", "metadata", "=", "Scout", ".", "__merge_dicts", "(", "self", ".", "metadata", ",", "plugin_response", ")", "if", "not", "self", ".", "install_id", ":", "self", ".", "install_id", "=", "self", ".", "__filesystem_install_id", "(", "app", ")", "self", ".", "logger", ".", "debug", "(", "\"Scout using install_id {0}\"", ".", "format", "(", "self", ".", "install_id", ")", ")", "# scout options; controlled via env vars", "self", ".", "scout_host", "=", "os", ".", "getenv", "(", "\"SCOUT_HOST\"", ",", "scout_host", ")", "self", ".", "use_https", "=", "os", ".", "getenv", "(", "\"SCOUT_HTTPS\"", ",", "\"1\"", ")", ".", "lower", "(", ")", "in", "{", "\"1\"", ",", "\"true\"", ",", "\"yes\"", "}", "self", ".", "disabled", "=", "Scout", ".", "__is_disabled", "(", ")" ]
[ 16, 4 ]
[ 87, 45 ]
python
en
['en', 'error', 'th']
False
Scout.configmap_install_id_plugin
(scout, app, map_name=None, namespace="default")
Scout id_plugin that uses a Kubernetes configmap to store the install ID. :param scout: Scout instance that's calling the plugin :param app: Name of the application that's using Scout :param map_name: Optional ConfigMap name to use; defaults to "scout.config.$app" :param namespace: Optional Kubernetes namespace to use; defaults to "default" This plugin assumes that the KUBERNETES_SERVICE_{HOST,PORT,PORT_HTTPS} environment variables are set correctly, and it assumes the default Kubernetes namespace unless the 'namespace' keyword argument is used to select a different namespace. If KUBERNETES_ACCESS_TOKEN is set in the environment, use that for the apiserver access token -- otherwise, the plugin assumes that it's running in a Kubernetes pod and tries to read its token from /var/run/secrets.
Scout id_plugin that uses a Kubernetes configmap to store the install ID.
def configmap_install_id_plugin(scout, app, map_name=None, namespace="default"): """ Scout id_plugin that uses a Kubernetes configmap to store the install ID. :param scout: Scout instance that's calling the plugin :param app: Name of the application that's using Scout :param map_name: Optional ConfigMap name to use; defaults to "scout.config.$app" :param namespace: Optional Kubernetes namespace to use; defaults to "default" This plugin assumes that the KUBERNETES_SERVICE_{HOST,PORT,PORT_HTTPS} environment variables are set correctly, and it assumes the default Kubernetes namespace unless the 'namespace' keyword argument is used to select a different namespace. If KUBERNETES_ACCESS_TOKEN is set in the environment, use that for the apiserver access token -- otherwise, the plugin assumes that it's running in a Kubernetes pod and tries to read its token from /var/run/secrets. """ plugin_response = None if not map_name: map_name = "scout.config.{0}".format(app) kube_host = os.environ.get('KUBERNETES_SERVICE_HOST', None) try: kube_port = int(os.environ.get('KUBERNETES_SERVICE_PORT', 443)) except ValueError: scout.logger.debug("Scout: KUBERNETES_SERVICE_PORT isn't numeric, defaulting to 443") kube_port = 443 kube_proto = "https" if (kube_port == 443) else "http" kube_token = os.environ.get('KUBERNETES_ACCESS_TOKEN', None) if not kube_host: # We're not running in Kubernetes. Fall back to the usual filesystem stuff. scout.logger.debug("Scout: no KUBERNETES_SERVICE_HOST, not running in Kubernetes") return None if not kube_token: try: kube_token = open("/var/run/secrets/kubernetes.io/serviceaccount/token", "r").read() except OSError: pass if not kube_token: # We're not running in Kubernetes. Fall back to the usual filesystem stuff. scout.logger.debug("Scout: not running in Kubernetes") return None # OK, we're in a cluster. Load our map. base_url = "%s://%s:%s" % (kube_proto, kube_host, kube_port) url_path = "api/v1/namespaces/%s/configmaps" % namespace auth_headers = { "Authorization": "Bearer " + kube_token } install_id = None cm_url = "%s/%s" % (base_url, url_path) fetch_url = "%s/%s" % (cm_url, map_name) scout.logger.debug("Scout: trying %s" % fetch_url) try: r = requests.get(fetch_url, headers=auth_headers, verify=False) if r.status_code == 200: # OK, the map is present. What do we see? map_data = r.json() if "data" not in map_data: # This is "impossible". scout.logger.error("Scout: no map data in returned map???") else: map_data = map_data.get("data", {}) scout.logger.debug("Scout: configmap has map data %s" % json.dumps(map_data)) install_id = map_data.get("install_id", None) if install_id: scout.logger.debug("Scout: got install_id %s from map" % install_id) plugin_response = { "install_id": install_id } except OSError as e: scout.logger.debug("Scout: could not read configmap (map %s, namespace %s): %s" % (map_name, namespace, e)) if not install_id: # No extant install_id. Try to create a new one. install_id = str(uuid4()) cm = { "apiVersion":"v1", "kind":"ConfigMap", "metadata":{ "name": map_name, "namespace": namespace, }, "data": { "install_id": install_id } } scout.logger.debug("Scout: saving new install_id %s" % install_id) saved = False try: r = requests.post(cm_url, headers=auth_headers, verify=False, json=cm) if r.status_code == 201: saved = True scout.logger.debug("Scout: saved install_id %s" % install_id) plugin_response = { "install_id": install_id, "new_install": True } else: scout.logger.error("Scout: could not save install_id: {0}, {1}".format(r.status_code, r.text)) except OSError as e: logging.debug("Scout: could not write configmap (map %s, namespace %s): %s" % (map_name, namespace, e)) scout.logger.debug("Scout: plugin_response %s" % json.dumps(plugin_response)) return plugin_response
[ "def", "configmap_install_id_plugin", "(", "scout", ",", "app", ",", "map_name", "=", "None", ",", "namespace", "=", "\"default\"", ")", ":", "plugin_response", "=", "None", "if", "not", "map_name", ":", "map_name", "=", "\"scout.config.{0}\"", ".", "format", "(", "app", ")", "kube_host", "=", "os", ".", "environ", ".", "get", "(", "'KUBERNETES_SERVICE_HOST'", ",", "None", ")", "try", ":", "kube_port", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "'KUBERNETES_SERVICE_PORT'", ",", "443", ")", ")", "except", "ValueError", ":", "scout", ".", "logger", ".", "debug", "(", "\"Scout: KUBERNETES_SERVICE_PORT isn't numeric, defaulting to 443\"", ")", "kube_port", "=", "443", "kube_proto", "=", "\"https\"", "if", "(", "kube_port", "==", "443", ")", "else", "\"http\"", "kube_token", "=", "os", ".", "environ", ".", "get", "(", "'KUBERNETES_ACCESS_TOKEN'", ",", "None", ")", "if", "not", "kube_host", ":", "# We're not running in Kubernetes. Fall back to the usual filesystem stuff.", "scout", ".", "logger", ".", "debug", "(", "\"Scout: no KUBERNETES_SERVICE_HOST, not running in Kubernetes\"", ")", "return", "None", "if", "not", "kube_token", ":", "try", ":", "kube_token", "=", "open", "(", "\"/var/run/secrets/kubernetes.io/serviceaccount/token\"", ",", "\"r\"", ")", ".", "read", "(", ")", "except", "OSError", ":", "pass", "if", "not", "kube_token", ":", "# We're not running in Kubernetes. Fall back to the usual filesystem stuff.", "scout", ".", "logger", ".", "debug", "(", "\"Scout: not running in Kubernetes\"", ")", "return", "None", "# OK, we're in a cluster. Load our map.", "base_url", "=", "\"%s://%s:%s\"", "%", "(", "kube_proto", ",", "kube_host", ",", "kube_port", ")", "url_path", "=", "\"api/v1/namespaces/%s/configmaps\"", "%", "namespace", "auth_headers", "=", "{", "\"Authorization\"", ":", "\"Bearer \"", "+", "kube_token", "}", "install_id", "=", "None", "cm_url", "=", "\"%s/%s\"", "%", "(", "base_url", ",", "url_path", ")", "fetch_url", "=", "\"%s/%s\"", "%", "(", "cm_url", ",", "map_name", ")", "scout", ".", "logger", ".", "debug", "(", "\"Scout: trying %s\"", "%", "fetch_url", ")", "try", ":", "r", "=", "requests", ".", "get", "(", "fetch_url", ",", "headers", "=", "auth_headers", ",", "verify", "=", "False", ")", "if", "r", ".", "status_code", "==", "200", ":", "# OK, the map is present. What do we see?", "map_data", "=", "r", ".", "json", "(", ")", "if", "\"data\"", "not", "in", "map_data", ":", "# This is \"impossible\".", "scout", ".", "logger", ".", "error", "(", "\"Scout: no map data in returned map???\"", ")", "else", ":", "map_data", "=", "map_data", ".", "get", "(", "\"data\"", ",", "{", "}", ")", "scout", ".", "logger", ".", "debug", "(", "\"Scout: configmap has map data %s\"", "%", "json", ".", "dumps", "(", "map_data", ")", ")", "install_id", "=", "map_data", ".", "get", "(", "\"install_id\"", ",", "None", ")", "if", "install_id", ":", "scout", ".", "logger", ".", "debug", "(", "\"Scout: got install_id %s from map\"", "%", "install_id", ")", "plugin_response", "=", "{", "\"install_id\"", ":", "install_id", "}", "except", "OSError", "as", "e", ":", "scout", ".", "logger", ".", "debug", "(", "\"Scout: could not read configmap (map %s, namespace %s): %s\"", "%", "(", "map_name", ",", "namespace", ",", "e", ")", ")", "if", "not", "install_id", ":", "# No extant install_id. Try to create a new one.", "install_id", "=", "str", "(", "uuid4", "(", ")", ")", "cm", "=", "{", "\"apiVersion\"", ":", "\"v1\"", ",", "\"kind\"", ":", "\"ConfigMap\"", ",", "\"metadata\"", ":", "{", "\"name\"", ":", "map_name", ",", "\"namespace\"", ":", "namespace", ",", "}", ",", "\"data\"", ":", "{", "\"install_id\"", ":", "install_id", "}", "}", "scout", ".", "logger", ".", "debug", "(", "\"Scout: saving new install_id %s\"", "%", "install_id", ")", "saved", "=", "False", "try", ":", "r", "=", "requests", ".", "post", "(", "cm_url", ",", "headers", "=", "auth_headers", ",", "verify", "=", "False", ",", "json", "=", "cm", ")", "if", "r", ".", "status_code", "==", "201", ":", "saved", "=", "True", "scout", ".", "logger", ".", "debug", "(", "\"Scout: saved install_id %s\"", "%", "install_id", ")", "plugin_response", "=", "{", "\"install_id\"", ":", "install_id", ",", "\"new_install\"", ":", "True", "}", "else", ":", "scout", ".", "logger", ".", "error", "(", "\"Scout: could not save install_id: {0}, {1}\"", ".", "format", "(", "r", ".", "status_code", ",", "r", ".", "text", ")", ")", "except", "OSError", "as", "e", ":", "logging", ".", "debug", "(", "\"Scout: could not write configmap (map %s, namespace %s): %s\"", "%", "(", "map_name", ",", "namespace", ",", "e", ")", ")", "scout", ".", "logger", ".", "debug", "(", "\"Scout: plugin_response %s\"", "%", "json", ".", "dumps", "(", "plugin_response", ")", ")", "return", "plugin_response" ]
[ 189, 4 ]
[ 313, 30 ]
python
en
['en', 'error', 'th']
False
clean_wiki_text
(text: str)
Clean wikipedia text by removing multiple new lines, removing extremely short lines, adding paragraph breaks and removing empty paragraphs
Clean wikipedia text by removing multiple new lines, removing extremely short lines, adding paragraph breaks and removing empty paragraphs
def clean_wiki_text(text: str) -> str: """ Clean wikipedia text by removing multiple new lines, removing extremely short lines, adding paragraph breaks and removing empty paragraphs """ # get rid of multiple new lines while "\n\n" in text: text = text.replace("\n\n", "\n") # remove extremely short lines lines = text.split("\n") cleaned = [] for l in lines: if len(l) > 30: cleaned.append(l) elif l[:2] == "==" and l[-2:] == "==": cleaned.append(l) text = "\n".join(cleaned) # add paragraphs (identified by wiki section title which is always in format "==Some Title==") text = text.replace("\n==", "\n\n\n==") # remove empty paragrahps text = re.sub(r"(==.*==\n\n\n)", "", text) return text
[ "def", "clean_wiki_text", "(", "text", ":", "str", ")", "->", "str", ":", "# get rid of multiple new lines", "while", "\"\\n\\n\"", "in", "text", ":", "text", "=", "text", ".", "replace", "(", "\"\\n\\n\"", ",", "\"\\n\"", ")", "# remove extremely short lines", "lines", "=", "text", ".", "split", "(", "\"\\n\"", ")", "cleaned", "=", "[", "]", "for", "l", "in", "lines", ":", "if", "len", "(", "l", ")", ">", "30", ":", "cleaned", ".", "append", "(", "l", ")", "elif", "l", "[", ":", "2", "]", "==", "\"==\"", "and", "l", "[", "-", "2", ":", "]", "==", "\"==\"", ":", "cleaned", ".", "append", "(", "l", ")", "text", "=", "\"\\n\"", ".", "join", "(", "cleaned", ")", "# add paragraphs (identified by wiki section title which is always in format \"==Some Title==\")", "text", "=", "text", ".", "replace", "(", "\"\\n==\"", ",", "\"\\n\\n\\n==\"", ")", "# remove empty paragrahps", "text", "=", "re", ".", "sub", "(", "r\"(==.*==\\n\\n\\n)\"", ",", "\"\"", ",", "text", ")", "return", "text" ]
[ 3, 0 ]
[ 28, 15 ]
python
en
['en', 'error', 'th']
False
xr_scale
(data, data_vars=None, min_max=None, scaling='norm', copy=False)
Scales an xarray Dataset or DataArray with standard scaling or norm scaling. Parameters ---------- data: xarray.Dataset or xarray.DataArray The NumPy array to scale. data_vars: list The names of the data variables to scale. min_max: tuple A 2-tuple which specifies the desired range of the final output - the minimum and the maximum, in that order. If all values are the same, all values will become min_max[0]. scaling: str The options are ['std', 'norm']. The option 'std' standardizes. The option 'norm' normalizes (min-max scales). copy: bool Whether or not to copy `data` before scaling.
Scales an xarray Dataset or DataArray with standard scaling or norm scaling. Parameters ---------- data: xarray.Dataset or xarray.DataArray The NumPy array to scale. data_vars: list The names of the data variables to scale. min_max: tuple A 2-tuple which specifies the desired range of the final output - the minimum and the maximum, in that order. If all values are the same, all values will become min_max[0]. scaling: str The options are ['std', 'norm']. The option 'std' standardizes. The option 'norm' normalizes (min-max scales). copy: bool Whether or not to copy `data` before scaling.
def xr_scale(data, data_vars=None, min_max=None, scaling='norm', copy=False): """ Scales an xarray Dataset or DataArray with standard scaling or norm scaling. Parameters ---------- data: xarray.Dataset or xarray.DataArray The NumPy array to scale. data_vars: list The names of the data variables to scale. min_max: tuple A 2-tuple which specifies the desired range of the final output - the minimum and the maximum, in that order. If all values are the same, all values will become min_max[0]. scaling: str The options are ['std', 'norm']. The option 'std' standardizes. The option 'norm' normalizes (min-max scales). copy: bool Whether or not to copy `data` before scaling. """ data = data.copy() if copy else data if isinstance(data, xr.Dataset): data_arr_names = list(data.data_vars) if data_vars is None else data_vars for data_arr_name in data_arr_names: data_arr = data[data_arr_name] data_arr.values = np_scale(data_arr.values, min_max=min_max, scaling=scaling) elif isinstance(data, xr.DataArray): data.values = np_scale(data.values, min_max=min_max, scaling=scaling) return data
[ "def", "xr_scale", "(", "data", ",", "data_vars", "=", "None", ",", "min_max", "=", "None", ",", "scaling", "=", "'norm'", ",", "copy", "=", "False", ")", ":", "data", "=", "data", ".", "copy", "(", ")", "if", "copy", "else", "data", "if", "isinstance", "(", "data", ",", "xr", ".", "Dataset", ")", ":", "data_arr_names", "=", "list", "(", "data", ".", "data_vars", ")", "if", "data_vars", "is", "None", "else", "data_vars", "for", "data_arr_name", "in", "data_arr_names", ":", "data_arr", "=", "data", "[", "data_arr_name", "]", "data_arr", ".", "values", "=", "np_scale", "(", "data_arr", ".", "values", ",", "min_max", "=", "min_max", ",", "scaling", "=", "scaling", ")", "elif", "isinstance", "(", "data", ",", "xr", ".", "DataArray", ")", ":", "data", ".", "values", "=", "np_scale", "(", "data", ".", "values", ",", "min_max", "=", "min_max", ",", "scaling", "=", "scaling", ")", "return", "data" ]
[ 3, 0 ]
[ 30, 15 ]
python
en
['en', 'ja', 'th']
False
np_scale
(arr, pop_arr=None, pop_min_max=None, pop_mean_std=None, min_max=None, scaling='norm')
Scales a NumPy array with standard scaling or norm scaling, default to norm scaling. Parameters ---------- arr: numpy.ndarray The NumPy array to scale. pop_arr: numpy.ndarray, optional The NumPy array to treat as the population. If specified, all members of `arr` must be within the range of `pop_arr` or `min_max` must be specified. pop_min_max: list-like, optional The population minimum and maximum, in that order. Supercedes `pop_arr` when normalizing. pop_mean_std: list-like, optional The population mean and standard deviation, in that order. Supercedes `pop_arr` when standard scaling. min_max: list-like, optional The desired minimum and maximum of the final output, in that order. If all values are the same, all values will become `min_max[0]`. scaling: str, optional The options are ['std', 'norm']. The option 'std' standardizes. The option 'norm' normalizes (min-max scales).
Scales a NumPy array with standard scaling or norm scaling, default to norm scaling. Parameters ---------- arr: numpy.ndarray The NumPy array to scale. pop_arr: numpy.ndarray, optional The NumPy array to treat as the population. If specified, all members of `arr` must be within the range of `pop_arr` or `min_max` must be specified. pop_min_max: list-like, optional The population minimum and maximum, in that order. Supercedes `pop_arr` when normalizing. pop_mean_std: list-like, optional The population mean and standard deviation, in that order. Supercedes `pop_arr` when standard scaling. min_max: list-like, optional The desired minimum and maximum of the final output, in that order. If all values are the same, all values will become `min_max[0]`. scaling: str, optional The options are ['std', 'norm']. The option 'std' standardizes. The option 'norm' normalizes (min-max scales).
def np_scale(arr, pop_arr=None, pop_min_max=None, pop_mean_std=None, min_max=None, scaling='norm'): """ Scales a NumPy array with standard scaling or norm scaling, default to norm scaling. Parameters ---------- arr: numpy.ndarray The NumPy array to scale. pop_arr: numpy.ndarray, optional The NumPy array to treat as the population. If specified, all members of `arr` must be within the range of `pop_arr` or `min_max` must be specified. pop_min_max: list-like, optional The population minimum and maximum, in that order. Supercedes `pop_arr` when normalizing. pop_mean_std: list-like, optional The population mean and standard deviation, in that order. Supercedes `pop_arr` when standard scaling. min_max: list-like, optional The desired minimum and maximum of the final output, in that order. If all values are the same, all values will become `min_max[0]`. scaling: str, optional The options are ['std', 'norm']. The option 'std' standardizes. The option 'norm' normalizes (min-max scales). """ if len(arr) == 0: return arr pop_arr = arr if pop_arr is None else pop_arr if scaling == 'norm': pop_min, pop_max = (pop_min_max[0], pop_min_max[1]) if pop_min_max is not None \ else (np.nanmin(pop_arr), np.nanmax(pop_arr)) numerator, denominator = arr - pop_min, pop_max - pop_min elif scaling == 'std': mean, std = pop_mean_std if pop_mean_std is not None else (np.nanmean(pop_arr), np.nanstd(pop_arr)) numerator, denominator = arr - mean, std # Primary scaling new_arr = arr if denominator > 0: new_arr = numerator / denominator # Optional final scaling. if min_max is not None: if denominator > 0: new_arr = np.interp(new_arr, (np.nanmin(new_arr), np.nanmax(new_arr)), min_max) else: # The values are identical - set all values to the low end of the desired range. new_arr = np.full_like(new_arr, min_max[0]) return new_arr
[ "def", "np_scale", "(", "arr", ",", "pop_arr", "=", "None", ",", "pop_min_max", "=", "None", ",", "pop_mean_std", "=", "None", ",", "min_max", "=", "None", ",", "scaling", "=", "'norm'", ")", ":", "if", "len", "(", "arr", ")", "==", "0", ":", "return", "arr", "pop_arr", "=", "arr", "if", "pop_arr", "is", "None", "else", "pop_arr", "if", "scaling", "==", "'norm'", ":", "pop_min", ",", "pop_max", "=", "(", "pop_min_max", "[", "0", "]", ",", "pop_min_max", "[", "1", "]", ")", "if", "pop_min_max", "is", "not", "None", "else", "(", "np", ".", "nanmin", "(", "pop_arr", ")", ",", "np", ".", "nanmax", "(", "pop_arr", ")", ")", "numerator", ",", "denominator", "=", "arr", "-", "pop_min", ",", "pop_max", "-", "pop_min", "elif", "scaling", "==", "'std'", ":", "mean", ",", "std", "=", "pop_mean_std", "if", "pop_mean_std", "is", "not", "None", "else", "(", "np", ".", "nanmean", "(", "pop_arr", ")", ",", "np", ".", "nanstd", "(", "pop_arr", ")", ")", "numerator", ",", "denominator", "=", "arr", "-", "mean", ",", "std", "# Primary scaling\r", "new_arr", "=", "arr", "if", "denominator", ">", "0", ":", "new_arr", "=", "numerator", "/", "denominator", "# Optional final scaling.\r", "if", "min_max", "is", "not", "None", ":", "if", "denominator", ">", "0", ":", "new_arr", "=", "np", ".", "interp", "(", "new_arr", ",", "(", "np", ".", "nanmin", "(", "new_arr", ")", ",", "np", ".", "nanmax", "(", "new_arr", ")", ")", ",", "min_max", ")", "else", ":", "# The values are identical - set all values to the low end of the desired range.\r", "new_arr", "=", "np", ".", "full_like", "(", "new_arr", ",", "min_max", "[", "0", "]", ")", "return", "new_arr" ]
[ 33, 0 ]
[ 78, 18 ]
python
en
['en', 'ja', 'th']
False
auto_not_in_place
(v=True)
Force it to not run in place
Force it to not run in place
def auto_not_in_place(v=True): """Force it to not run in place """ import itkConfig itkConfig.NotInPlace = v
[ "def", "auto_not_in_place", "(", "v", "=", "True", ")", ":", "import", "itkConfig", "itkConfig", ".", "NotInPlace", "=", "v" ]
[ 30, 0 ]
[ 34, 28 ]
python
en
['en', 'en', 'en']
True
auto_progress
(progressType=1)
Set up auto progress report progressType: 1 or True -> auto progress be used in a terminal 2 -> simple auto progress (without special characters) 0 or False -> disable auto progress
Set up auto progress report
def auto_progress(progressType=1): """Set up auto progress report progressType: 1 or True -> auto progress be used in a terminal 2 -> simple auto progress (without special characters) 0 or False -> disable auto progress """ import itkConfig if progressType is True or progressType == 1: itkConfig.ImportCallback = terminal_import_callback itkConfig.ProgressCallback = terminal_progress_callback elif progressType == 2: itkConfig.ImportCallback = simple_import_callback itkConfig.ProgressCallback = simple_progress_callback elif progressType is False or progressType == 0: itkConfig.ImportCallback = None itkConfig.ProgressCallback = None else: raise ValueError("Invalid auto progress type: " + repr(progressType))
[ "def", "auto_progress", "(", "progressType", "=", "1", ")", ":", "import", "itkConfig", "if", "progressType", "is", "True", "or", "progressType", "==", "1", ":", "itkConfig", ".", "ImportCallback", "=", "terminal_import_callback", "itkConfig", ".", "ProgressCallback", "=", "terminal_progress_callback", "elif", "progressType", "==", "2", ":", "itkConfig", ".", "ImportCallback", "=", "simple_import_callback", "itkConfig", ".", "ProgressCallback", "=", "simple_progress_callback", "elif", "progressType", "is", "False", "or", "progressType", "==", "0", ":", "itkConfig", ".", "ImportCallback", "=", "None", "itkConfig", ".", "ProgressCallback", "=", "None", "else", ":", "raise", "ValueError", "(", "\"Invalid auto progress type: \"", "+", "repr", "(", "progressType", ")", ")" ]
[ 37, 0 ]
[ 60, 77 ]
python
en
['en', 'lv', 'en']
True
terminal_progress_callback
(name, p)
Display the progress of an object and clean the display once complete This function can be used with itkConfig.ProgressCallback
Display the progress of an object and clean the display once complete
def terminal_progress_callback(name, p): """Display the progress of an object and clean the display once complete This function can be used with itkConfig.ProgressCallback """ import sys print(clrLine + "%s: %f" % (name, p), file=sys.stderr, end="") if p == 1: print(clrLine, file=sys.stderr, end="")
[ "def", "terminal_progress_callback", "(", "name", ",", "p", ")", ":", "import", "sys", "print", "(", "clrLine", "+", "\"%s: %f\"", "%", "(", "name", ",", "p", ")", ",", "file", "=", "sys", ".", "stderr", ",", "end", "=", "\"\"", ")", "if", "p", "==", "1", ":", "print", "(", "clrLine", ",", "file", "=", "sys", ".", "stderr", ",", "end", "=", "\"\"", ")" ]
[ 63, 0 ]
[ 71, 47 ]
python
en
['en', 'en', 'en']
True
terminal_import_callback
(name, p)
Display the loading of a module and clean the display once complete This function can be used with itkConfig.ImportCallback
Display the loading of a module and clean the display once complete
def terminal_import_callback(name, p): """Display the loading of a module and clean the display once complete This function can be used with itkConfig.ImportCallback """ import sys print(clrLine + "Loading %s... " % name, file=sys.stderr, end="") if p == 1: print(clrLine, file=sys.stderr, end="")
[ "def", "terminal_import_callback", "(", "name", ",", "p", ")", ":", "import", "sys", "print", "(", "clrLine", "+", "\"Loading %s... \"", "%", "name", ",", "file", "=", "sys", ".", "stderr", ",", "end", "=", "\"\"", ")", "if", "p", "==", "1", ":", "print", "(", "clrLine", ",", "file", "=", "sys", ".", "stderr", ",", "end", "=", "\"\"", ")" ]
[ 74, 0 ]
[ 82, 47 ]
python
en
['en', 'en', 'en']
True
simple_import_callback
(name, p)
Print a message when a module is loading This function can be used with itkConfig.ImportCallback
Print a message when a module is loading
def simple_import_callback(name, p): """Print a message when a module is loading This function can be used with itkConfig.ImportCallback """ import sys if p == 0: print("Loading %s... " % name, file=sys.stderr, end="") elif p == 1: print("done", file=sys.stderr)
[ "def", "simple_import_callback", "(", "name", ",", "p", ")", ":", "import", "sys", "if", "p", "==", "0", ":", "print", "(", "\"Loading %s... \"", "%", "name", ",", "file", "=", "sys", ".", "stderr", ",", "end", "=", "\"\"", ")", "elif", "p", "==", "1", ":", "print", "(", "\"done\"", ",", "file", "=", "sys", ".", "stderr", ")" ]
[ 85, 0 ]
[ 94, 38 ]
python
en
['en', 'en', 'en']
True
simple_progress_callback
(name, p)
Print a message when an object is running This function can be used with itkConfig.ProgressCallback
Print a message when an object is running
def simple_progress_callback(name, p): """Print a message when an object is running This function can be used with itkConfig.ProgressCallback """ import sys if p == 0: print("Running %s... " % name, file=sys.stderr, end="") elif p == 1: print("done", file=sys.stderr)
[ "def", "simple_progress_callback", "(", "name", ",", "p", ")", ":", "import", "sys", "if", "p", "==", "0", ":", "print", "(", "\"Running %s... \"", "%", "name", ",", "file", "=", "sys", ".", "stderr", ",", "end", "=", "\"\"", ")", "elif", "p", "==", "1", ":", "print", "(", "\"done\"", ",", "file", "=", "sys", ".", "stderr", ")" ]
[ 97, 0 ]
[ 106, 38 ]
python
en
['en', 'en', 'en']
True
force_load
()
force itk to load all the submodules
force itk to load all the submodules
def force_load(): """force itk to load all the submodules""" import itk for k in dir(itk): getattr(itk, k)
[ "def", "force_load", "(", ")", ":", "import", "itk", "for", "k", "in", "dir", "(", "itk", ")", ":", "getattr", "(", "itk", ",", "k", ")" ]
[ 109, 0 ]
[ 113, 23 ]
python
en
['en', 'en', 'en']
True
echo
(object, f=sys.stderr)
Print an object is f If the object has a method Print(), this method is used. repr(object) is used otherwise
Print an object is f
def echo(object, f=sys.stderr): """Print an object is f If the object has a method Print(), this method is used. repr(object) is used otherwise """ print(f, object)
[ "def", "echo", "(", "object", ",", "f", "=", "sys", ".", "stderr", ")", ":", "print", "(", "f", ",", "object", ")" ]
[ 119, 0 ]
[ 125, 20 ]
python
en
['en', 'en', 'en']
True
size
(imageOrFilter)
Return the size of an image, or of the output image of a filter This method take care of updating the needed informations
Return the size of an image, or of the output image of a filter
def size(imageOrFilter): """Return the size of an image, or of the output image of a filter This method take care of updating the needed informations """ # we don't need the entire output, only its size imageOrFilter.UpdateOutputInformation() img = output(imageOrFilter) return img.GetLargestPossibleRegion().GetSize()
[ "def", "size", "(", "imageOrFilter", ")", ":", "# we don't need the entire output, only its size", "imageOrFilter", ".", "UpdateOutputInformation", "(", ")", "img", "=", "output", "(", "imageOrFilter", ")", "return", "img", ".", "GetLargestPossibleRegion", "(", ")", ".", "GetSize", "(", ")" ]
[ 129, 0 ]
[ 137, 51 ]
python
en
['en', 'en', 'en']
True
physical_size
(imageOrFilter)
Return the physical size of an image, or of the output image of a filter This method take care of updating the needed informations
Return the physical size of an image, or of the output image of a filter
def physical_size(imageOrFilter): """Return the physical size of an image, or of the output image of a filter This method take care of updating the needed informations """ # required because range is overloaded in this module import sys if sys.version_info >= (3, 0): from builtins import range else: from __builtin__ import range spacing_ = spacing(imageOrFilter) size_ = size(imageOrFilter) result = [] for i in range(0, spacing_.Size()): result.append(spacing_.GetElement(i) * size_.GetElement(i)) return result
[ "def", "physical_size", "(", "imageOrFilter", ")", ":", "# required because range is overloaded in this module", "import", "sys", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "0", ")", ":", "from", "builtins", "import", "range", "else", ":", "from", "__builtin__", "import", "range", "spacing_", "=", "spacing", "(", "imageOrFilter", ")", "size_", "=", "size", "(", "imageOrFilter", ")", "result", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "spacing_", ".", "Size", "(", ")", ")", ":", "result", ".", "append", "(", "spacing_", ".", "GetElement", "(", "i", ")", "*", "size_", ".", "GetElement", "(", "i", ")", ")", "return", "result" ]
[ 140, 0 ]
[ 156, 17 ]
python
en
['en', 'en', 'en']
True
spacing
(imageOrFilter)
Return the spacing of an image, or of the output image of a filter This method take care of updating the needed informations
Return the spacing of an image, or of the output image of a filter
def spacing(imageOrFilter): """Return the spacing of an image, or of the output image of a filter This method take care of updating the needed informations """ # we don't need the entire output, only its size imageOrFilter.UpdateOutputInformation() img = output(imageOrFilter) return img.GetSpacing()
[ "def", "spacing", "(", "imageOrFilter", ")", ":", "# we don't need the entire output, only its size", "imageOrFilter", ".", "UpdateOutputInformation", "(", ")", "img", "=", "output", "(", "imageOrFilter", ")", "return", "img", ".", "GetSpacing", "(", ")" ]
[ 159, 0 ]
[ 167, 27 ]
python
en
['en', 'en', 'en']
True
origin
(imageOrFilter)
Return the origin of an image, or of the output image of a filter This method take care of updating the needed informations
Return the origin of an image, or of the output image of a filter
def origin(imageOrFilter): """Return the origin of an image, or of the output image of a filter This method take care of updating the needed informations """ # we don't need the entire output, only its size imageOrFilter.UpdateOutputInformation() img = output(imageOrFilter) return img.GetOrigin()
[ "def", "origin", "(", "imageOrFilter", ")", ":", "# we don't need the entire output, only its size", "imageOrFilter", ".", "UpdateOutputInformation", "(", ")", "img", "=", "output", "(", "imageOrFilter", ")", "return", "img", ".", "GetOrigin", "(", ")" ]
[ 170, 0 ]
[ 178, 26 ]
python
en
['en', 'en', 'en']
True
index
(imageOrFilter)
Return the index of an image, or of the output image of a filter This method take care of updating the needed informations
Return the index of an image, or of the output image of a filter
def index(imageOrFilter): """Return the index of an image, or of the output image of a filter This method take care of updating the needed informations """ # we don't need the entire output, only its size imageOrFilter.UpdateOutputInformation() img = output(imageOrFilter) return img.GetLargestPossibleRegion().GetIndex()
[ "def", "index", "(", "imageOrFilter", ")", ":", "# we don't need the entire output, only its size", "imageOrFilter", ".", "UpdateOutputInformation", "(", ")", "img", "=", "output", "(", "imageOrFilter", ")", "return", "img", ".", "GetLargestPossibleRegion", "(", ")", ".", "GetIndex", "(", ")" ]
[ 181, 0 ]
[ 189, 52 ]
python
en
['en', 'en', 'en']
True
region
(imageOrFilter)
Return the region of an image, or of the output image of a filter This method take care of updating the needed informations
Return the region of an image, or of the output image of a filter
def region(imageOrFilter): """Return the region of an image, or of the output image of a filter This method take care of updating the needed informations """ # we don't need the entire output, only its size imageOrFilter.UpdateOutputInformation() img = output(imageOrFilter) return img.GetLargestPossibleRegion()
[ "def", "region", "(", "imageOrFilter", ")", ":", "# we don't need the entire output, only its size", "imageOrFilter", ".", "UpdateOutputInformation", "(", ")", "img", "=", "output", "(", "imageOrFilter", ")", "return", "img", ".", "GetLargestPossibleRegion", "(", ")" ]
[ 192, 0 ]
[ 200, 41 ]
python
en
['en', 'en', 'en']
True
_get_itk_pixelid
(numpy_array_type)
Returns a ITK PixelID given a numpy array.
Returns a ITK PixelID given a numpy array.
def _get_itk_pixelid(numpy_array_type): """Returns a ITK PixelID given a numpy array.""" if not HAVE_NUMPY: raise ImportError('Numpy not available.') import itk # This is a Mapping from numpy array types to itk pixel types. _np_itk = {numpy.uint8:itk.UC, numpy.uint16:itk.US, numpy.uint32:itk.UI, numpy.uint64:itk.UL, numpy.int8:itk.SC, numpy.int16:itk.SS, numpy.int32:itk.SI, numpy.int64:itk.SL, numpy.float32:itk.F, numpy.float64:itk.D, numpy.complex64:itk.complex[itk.F], numpy.complex128:itk.complex[itk.D] } try: return _np_itk[numpy_array_type.dtype.type] except KeyError as e: for key in _np_itk: if numpy.issubdtype(numpy_array_type.dtype.type, key): return _np_itk[key] raise e
[ "def", "_get_itk_pixelid", "(", "numpy_array_type", ")", ":", "if", "not", "HAVE_NUMPY", ":", "raise", "ImportError", "(", "'Numpy not available.'", ")", "import", "itk", "# This is a Mapping from numpy array types to itk pixel types.", "_np_itk", "=", "{", "numpy", ".", "uint8", ":", "itk", ".", "UC", ",", "numpy", ".", "uint16", ":", "itk", ".", "US", ",", "numpy", ".", "uint32", ":", "itk", ".", "UI", ",", "numpy", ".", "uint64", ":", "itk", ".", "UL", ",", "numpy", ".", "int8", ":", "itk", ".", "SC", ",", "numpy", ".", "int16", ":", "itk", ".", "SS", ",", "numpy", ".", "int32", ":", "itk", ".", "SI", ",", "numpy", ".", "int64", ":", "itk", ".", "SL", ",", "numpy", ".", "float32", ":", "itk", ".", "F", ",", "numpy", ".", "float64", ":", "itk", ".", "D", ",", "numpy", ".", "complex64", ":", "itk", ".", "complex", "[", "itk", ".", "F", "]", ",", "numpy", ".", "complex128", ":", "itk", ".", "complex", "[", "itk", ".", "D", "]", "}", "try", ":", "return", "_np_itk", "[", "numpy_array_type", ".", "dtype", ".", "type", "]", "except", "KeyError", "as", "e", ":", "for", "key", "in", "_np_itk", ":", "if", "numpy", ".", "issubdtype", "(", "numpy_array_type", ".", "dtype", ".", "type", ",", "key", ")", ":", "return", "_np_itk", "[", "key", "]", "raise", "e" ]
[ 208, 0 ]
[ 234, 19 ]
python
en
['en', 'ca', 'en']
True
_GetArrayFromImage
(imageOrFilter, function)
Get an Array with the content of the image buffer
Get an Array with the content of the image buffer
def _GetArrayFromImage(imageOrFilter, function): """Get an Array with the content of the image buffer """ # Check for numpy if not HAVE_NUMPY: raise ImportError('Numpy not available.') # Finds the image type import itk keys = [k for k in itk.PyBuffer.keys() if k[0] == output(imageOrFilter).__class__] if len(keys ) == 0: raise RuntimeError("No suitable template parameter can be found.") ImageType = keys[0] # Create a numpy array of the type of the input image templatedFunction = getattr(itk.PyBuffer[keys[0]], function) return templatedFunction(output(imageOrFilter))
[ "def", "_GetArrayFromImage", "(", "imageOrFilter", ",", "function", ")", ":", "# Check for numpy", "if", "not", "HAVE_NUMPY", ":", "raise", "ImportError", "(", "'Numpy not available.'", ")", "# Finds the image type", "import", "itk", "keys", "=", "[", "k", "for", "k", "in", "itk", ".", "PyBuffer", ".", "keys", "(", ")", "if", "k", "[", "0", "]", "==", "output", "(", "imageOrFilter", ")", ".", "__class__", "]", "if", "len", "(", "keys", ")", "==", "0", ":", "raise", "RuntimeError", "(", "\"No suitable template parameter can be found.\"", ")", "ImageType", "=", "keys", "[", "0", "]", "# Create a numpy array of the type of the input image", "templatedFunction", "=", "getattr", "(", "itk", ".", "PyBuffer", "[", "keys", "[", "0", "]", "]", ",", "function", ")", "return", "templatedFunction", "(", "output", "(", "imageOrFilter", ")", ")" ]
[ 236, 0 ]
[ 250, 51 ]
python
en
['en', 'en', 'en']
True
GetArrayFromImage
(imageOrFilter)
Get an array with the content of the image buffer
Get an array with the content of the image buffer
def GetArrayFromImage(imageOrFilter): """Get an array with the content of the image buffer """ return _GetArrayFromImage(imageOrFilter, "GetArrayFromImage")
[ "def", "GetArrayFromImage", "(", "imageOrFilter", ")", ":", "return", "_GetArrayFromImage", "(", "imageOrFilter", ",", "\"GetArrayFromImage\"", ")" ]
[ 252, 0 ]
[ 255, 65 ]
python
en
['en', 'en', 'en']
True
GetArrayViewFromImage
(imageOrFilter)
Get an array view with the content of the image buffer
Get an array view with the content of the image buffer
def GetArrayViewFromImage(imageOrFilter): """Get an array view with the content of the image buffer """ return _GetArrayFromImage(imageOrFilter, "GetArrayViewFromImage")
[ "def", "GetArrayViewFromImage", "(", "imageOrFilter", ")", ":", "return", "_GetArrayFromImage", "(", "imageOrFilter", ",", "\"GetArrayViewFromImage\"", ")" ]
[ 257, 0 ]
[ 260, 69 ]
python
en
['en', 'en', 'en']
True
_GetImageFromArray
(arr, function)
Get an ITK image from a Python array.
Get an ITK image from a Python array.
def _GetImageFromArray(arr, function): """Get an ITK image from a Python array. """ if not HAVE_NUMPY: raise ImportError('Numpy not available.') import itk PixelType = _get_itk_pixelid(arr) ImageType = itk.Image[PixelType,arr.ndim] templatedFunction = getattr(itk.PyBuffer[ImageType], function) return templatedFunction(arr)
[ "def", "_GetImageFromArray", "(", "arr", ",", "function", ")", ":", "if", "not", "HAVE_NUMPY", ":", "raise", "ImportError", "(", "'Numpy not available.'", ")", "import", "itk", "PixelType", "=", "_get_itk_pixelid", "(", "arr", ")", "ImageType", "=", "itk", ".", "Image", "[", "PixelType", ",", "arr", ".", "ndim", "]", "templatedFunction", "=", "getattr", "(", "itk", ".", "PyBuffer", "[", "ImageType", "]", ",", "function", ")", "return", "templatedFunction", "(", "arr", ")" ]
[ 262, 0 ]
[ 271, 33 ]
python
en
['en', 'en', 'en']
True
GetImageFromArray
(arr)
Get an ITK image from a Python array.
Get an ITK image from a Python array.
def GetImageFromArray(arr): """Get an ITK image from a Python array. """ return _GetImageFromArray(arr, "GetImageFromArray")
[ "def", "GetImageFromArray", "(", "arr", ")", ":", "return", "_GetImageFromArray", "(", "arr", ",", "\"GetImageFromArray\"", ")" ]
[ 273, 0 ]
[ 276, 55 ]
python
en
['en', 'en', 'en']
True
GetImageViewFromArray
(arr)
Get an ITK image view from a Python array.
Get an ITK image view from a Python array.
def GetImageViewFromArray(arr): """Get an ITK image view from a Python array. """ return _GetImageFromArray(arr, "GetImageViewFromArray")
[ "def", "GetImageViewFromArray", "(", "arr", ")", ":", "return", "_GetImageFromArray", "(", "arr", ",", "\"GetImageViewFromArray\"", ")" ]
[ 278, 0 ]
[ 281, 59 ]
python
en
['en', 'en', 'en']
True
_GetArrayFromVnlObject
(vnlObject, function)
Get an array with the content of vnlObject
Get an array with the content of vnlObject
def _GetArrayFromVnlObject(vnlObject, function): """Get an array with the content of vnlObject """ # Check for numpy if not HAVE_NUMPY: raise ImportError('Numpy not available.') # Finds the vnl object type import itk PixelType = itk.template(vnlObject)[1][0] keys = [k for k in itk.PyVnl.keys() if k[0] == PixelType] if len(keys ) == 0: raise RuntimeError("No suitable template parameter can be found.") # Create a numpy array of the type of the vnl object templatedFunction = getattr(itk.PyVnl[keys[0]], function) return templatedFunction(vnlObject)
[ "def", "_GetArrayFromVnlObject", "(", "vnlObject", ",", "function", ")", ":", "# Check for numpy", "if", "not", "HAVE_NUMPY", ":", "raise", "ImportError", "(", "'Numpy not available.'", ")", "# Finds the vnl object type", "import", "itk", "PixelType", "=", "itk", ".", "template", "(", "vnlObject", ")", "[", "1", "]", "[", "0", "]", "keys", "=", "[", "k", "for", "k", "in", "itk", ".", "PyVnl", ".", "keys", "(", ")", "if", "k", "[", "0", "]", "==", "PixelType", "]", "if", "len", "(", "keys", ")", "==", "0", ":", "raise", "RuntimeError", "(", "\"No suitable template parameter can be found.\"", ")", "# Create a numpy array of the type of the vnl object", "templatedFunction", "=", "getattr", "(", "itk", ".", "PyVnl", "[", "keys", "[", "0", "]", "]", ",", "function", ")", "return", "templatedFunction", "(", "vnlObject", ")" ]
[ 283, 0 ]
[ 297, 39 ]
python
en
['en', 'en', 'en']
True
GetArrayFromVnlVector
(vnlVector)
Get an array with the content of vnlVector
Get an array with the content of vnlVector
def GetArrayFromVnlVector(vnlVector): """Get an array with the content of vnlVector """ return _GetArrayFromVnlObject(vnlVector, "GetArrayFromVnlVector")
[ "def", "GetArrayFromVnlVector", "(", "vnlVector", ")", ":", "return", "_GetArrayFromVnlObject", "(", "vnlVector", ",", "\"GetArrayFromVnlVector\"", ")" ]
[ 299, 0 ]
[ 302, 69 ]
python
en
['en', 'en', 'en']
True