INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
This method opens the start_page creates a referral link there and clicks on that link which goes to the destination_page. ( This generates real traffic for testing analytics software. ) | def generate_referral(self, start_page, destination_page):
""" This method opens the start_page, creates a referral link there,
and clicks on that link, which goes to the destination_page.
(This generates real traffic for testing analytics software.) """
if not page_utils.is_vali... |
Similar to generate_referral () but can do multiple loops. | def generate_traffic(self, start_page, destination_page, loops=1):
""" Similar to generate_referral(), but can do multiple loops. """
for loop in range(loops):
self.generate_referral(start_page, destination_page)
time.sleep(0.05) |
Use this method to chain the action of creating button links on one website page that will take you to the next page. ( When you want to create a referral to a website for traffic generation without increasing the bounce rate you ll want to visit at least one additional page on that site with a button click. ) | def generate_referral_chain(self, pages):
""" Use this method to chain the action of creating button links on
one website page that will take you to the next page.
(When you want to create a referral to a website for traffic
generation without increasing the bounce rate, you'... |
Similar to generate_referral_chain () but for multiple loops. | def generate_traffic_chain(self, pages, loops=1):
""" Similar to generate_referral_chain(), but for multiple loops. """
for loop in range(loops):
self.generate_referral_chain(pages)
time.sleep(0.05) |
Similar to wait_for_element_present () but returns nothing. Waits for an element to appear in the HTML of a page. The element does not need be visible ( it may be hidden ). Returns True if successful. Default timeout = SMALL_TIMEOUT. | def assert_element_present(self, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" Similar to wait_for_element_present(), but returns nothing.
Waits for an element to appear in the HTML of a page.
The element does not need be visible (it ma... |
Waits for an element to appear in the HTML of a page. The element must be visible ( it cannot be hidden ). | def wait_for_element_visible(self, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
""" Waits for an element to appear in the HTML of a page.
The element must be visible (it cannot be hidden). """
if page_utils.is_xpath_selector(selector):
... |
The shorter version of wait_for_element_visible () | def wait_for_element(self, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
""" The shorter version of wait_for_element_visible() """
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
ret... |
Same as self. assert_element () As above will raise an exception if nothing can be found. | def assert_element_visible(self, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" Same as self.assert_element()
As above, will raise an exception if nothing can be found. """
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
... |
The shorter version of wait_for_text_visible () | def wait_for_text(self, text, selector="html", by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
""" The shorter version of wait_for_text_visible() """
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
... |
Same as assert_text () | def assert_text_visible(self, text, selector="html", by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" Same as assert_text() """
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.... |
Similar to assert_text () but the text must be exact rather than exist as a subset of the full text. ( Extra whitespace at the beginning or the end doesn t count. ) Raises an exception if the element or the text is not found. Returns True if successful. Default timeout = SMALL_TIMEOUT. | def assert_exact_text(self, text, selector="html", by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" Similar to assert_text(), but the text must be exact, rather than
exist as a subset of the full text.
(Extra whitespace at the beginning or the end doesn'... |
The shorter version of wait_for_link_text_visible () | def wait_for_link_text(self, link_text, timeout=settings.LARGE_TIMEOUT):
""" The shorter version of wait_for_link_text_visible() """
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.wait_for_link_text_visible(link... |
Similar to wait_for_link_text_visible () but returns nothing. As above will raise an exception if nothing can be found. Returns True if successful. Default timeout = SMALL_TIMEOUT. | def assert_link_text(self, link_text, timeout=settings.SMALL_TIMEOUT):
""" Similar to wait_for_link_text_visible(), but returns nothing.
As above, will raise an exception if nothing can be found.
Returns True if successful. Default timeout = SMALL_TIMEOUT. """
if self.timeout_mul... |
Same as wait_for_partial_link_text () - returns the element | def find_partial_link_text(self, partial_link_text,
timeout=settings.LARGE_TIMEOUT):
""" Same as wait_for_partial_link_text() - returns the element """
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
... |
Similar to wait_for_partial_link_text () but returns nothing. As above will raise an exception if nothing can be found. Returns True if successful. Default timeout = SMALL_TIMEOUT. | def assert_partial_link_text(self, partial_link_text,
timeout=settings.SMALL_TIMEOUT):
""" Similar to wait_for_partial_link_text(), but returns nothing.
As above, will raise an exception if nothing can be found.
Returns True if successful. Default timeout... |
Waits for an element to no longer appear in the HTML of a page. A hidden element still counts as appearing in the page HTML. If an element with hidden status is acceptable use wait_for_element_not_visible () instead. | def wait_for_element_absent(self, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
""" Waits for an element to no longer appear in the HTML of a page.
A hidden element still counts as appearing in the page HTML.
If an element with "hidden" st... |
Similar to wait_for_element_absent () - returns nothing. As above will raise an exception if the element stays present. Returns True if successful. Default timeout = SMALL_TIMEOUT. | def assert_element_absent(self, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" Similar to wait_for_element_absent() - returns nothing.
As above, will raise an exception if the element stays present.
Returns True if successful. Default tim... |
Similar to wait_for_element_not_visible () - returns nothing. As above will raise an exception if the element stays visible. Returns True if successful. Default timeout = SMALL_TIMEOUT. | def assert_element_not_visible(self, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" Similar to wait_for_element_not_visible() - returns nothing.
As above, will raise an exception if the element stays visible.
Returns True if successf... |
Sets driver control to the specified browser frame. | def switch_to_frame(self, frame, timeout=settings.SMALL_TIMEOUT):
""" Sets driver control to the specified browser frame. """
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
page_actions.switch_to_frame(self.driver, frame, t... |
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) |
*** Automated Visual Testing with SeleniumBase *** | def check_window(self, name="default", level=0, baseline=False):
""" *** Automated Visual Testing with SeleniumBase ***
The first time a test calls self.check_window() for a unique "name"
parameter provided, it will set a visual baseline, meaning that it
creates a folder, ... |
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) |
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, disable_csp=None):
""" This method spins up an extra browser for tests that require
more than one. The first browser ... |
When using -- timeout_multiplier = #. # | def __get_new_timeout(self, timeout):
""" When using --timeout_multiplier=#.# """
try:
timeout_multiplier = float(self.timeout_multiplier)
if timeout_multiplier <= 0.5:
timeout_multiplier = 0.5
timeout = int(math.ceil(timeout_multiplier * timeout))
... |
This method extracts the message from an exception if there was an exception that occurred during the test assuming that the exception was in a try/ except block and not thrown. | def __get_exception_message(self):
""" This method extracts the message from an exception if there
was an exception that occurred during the test, assuming
that the exception was in a try/except block and not thrown. """
exception_info = sys.exc_info()[1]
if hasattr(excep... |
If Chromedriver is out - of - date make it clear! Given the high popularity of the following StackOverflow article: https:// stackoverflow. com/ questions/ 49162667/ unknown - error - call - function - result - missing - value - for - selenium - send - keys - even... the original error message was not helpful. Tell peo... | def __get_improved_exception_message(self):
"""
If Chromedriver is out-of-date, make it clear!
Given the high popularity of the following StackOverflow article:
https://stackoverflow.com/questions/49162667/unknown-error-
call-function-result-missing-value-for-selenium-sen... |
Add a delayed_assert failure into a list for future processing. | def __add_delayed_assert_failure(self):
""" Add a delayed_assert failure into a list for future processing. """
current_url = self.driver.current_url
message = self.__get_exception_message()
self.__delayed_assert_failures.append(
"CHECK #%s: (%s)\n %s" % (
sel... |
A non - terminating assertion for an element on a page. Failures will be saved until the process_delayed_asserts () method is called from inside a test likely at the end of it. | def delayed_assert_element(self, selector, by=By.CSS_SELECTOR,
timeout=settings.MINI_TIMEOUT):
""" A non-terminating assertion for an element on a page.
Failures will be saved until the process_delayed_asserts()
method is called from inside a test, likely a... |
A non - terminating assertion for text from an element on a page. Failures will be saved until the process_delayed_asserts () method is called from inside a test likely at the end of it. | def delayed_assert_text(self, text, selector="html", by=By.CSS_SELECTOR,
timeout=settings.MINI_TIMEOUT):
""" A non-terminating assertion for text from an element on a page.
Failures will be saved until the process_delayed_asserts()
method is called from inside... |
To be used with any test that uses delayed_asserts which are non - terminating verifications that only raise exceptions after this method is called. This is useful for pages with multiple elements to be checked when you want to find as many bugs as possible in a single test run before having all the exceptions get rais... | def process_delayed_asserts(self, print_only=False):
""" To be used with any test that uses delayed_asserts, which are
non-terminating verifications that only raise exceptions
after this method is called.
This is useful for pages with multiple elements to be checked when
... |
Clicks an element using pure JS. Does not use jQuery. | def __js_click(self, selector, by=By.CSS_SELECTOR):
""" Clicks an element using pure JS. Does not use jQuery. """
selector, by = self.__recalculate_selector(selector, by)
css_selector = self.convert_to_css_selector(selector, by=by)
css_selector = re.escape(css_selector)
css_selec... |
When a link may be hidden under a dropdown menu use this. | def __click_dropdown_link_text(self, link_text, link_css):
""" When a link may be hidden under a dropdown menu, use this. """
soup = self.get_beautiful_soup()
drop_down_list = soup.select('[class*=dropdown]')
for item in soup.select('[class*=HeaderMenu]'):
drop_down_list.appe... |
Be careful if a subclass of BaseCase overrides setUp () You ll need to add the following line to the subclass setUp () method: super ( SubClassOfBaseCase self ). setUp () | def setUp(self, masterqa_mode=False):
"""
Be careful if a subclass of BaseCase overrides setUp()
You'll need to add the following line to the subclass setUp() method:
super(SubClassOfBaseCase, self).setUp()
"""
self.masterqa_mode = masterqa_mode
self.is_pytest = N... |
self. __last_page_screenshot is only for pytest html report logs self. __last_page_screenshot_png is for all screenshot log files | def __set_last_page_screenshot(self):
""" self.__last_page_screenshot is only for pytest html report logs
self.__last_page_screenshot_png is for all screenshot log files """
if not self.__last_page_screenshot and (
not self.__last_page_screenshot_png):
try:
... |
Be careful if a subclass of BaseCase overrides setUp () You ll need to add the following line to the subclass s tearDown (): super ( SubClassOfBaseCase self ). tearDown () | def tearDown(self):
"""
Be careful if a subclass of BaseCase overrides setUp()
You'll need to add the following line to the subclass's tearDown():
super(SubClassOfBaseCase, self).tearDown()
"""
has_exception = False
if sys.version.startswith('3') and hasattr(self,... |
Upload a given file from the file_path to the bucket with the new name/ path file_name. | def upload_file(self, file_name, file_path):
""" Upload a given file from the file_path to the bucket
with the new name/path file_name. """
upload_key = Key(bucket=self.bucket, name=file_name)
content_type = "text/plain"
if file_name.endswith(".html"):
content_typ... |
Create an index. html file with links to all the log files that were just uploaded. | def upload_index_file(self, test_address, timestamp):
""" Create an index.html file with links to all the log files
that were just uploaded. """
global already_uploaded_files
already_uploaded_files = list(set(already_uploaded_files))
already_uploaded_files.sort()
file... |
Allows you to use Bootstrap Tours with SeleniumBase http:// bootstraptour. com/ | def activate_bootstrap(driver):
""" Allows you to use Bootstrap Tours with SeleniumBase
http://bootstraptour.com/
"""
bootstrap_tour_css = constants.BootstrapTour.MIN_CSS
bootstrap_tour_js = constants.BootstrapTour.MIN_JS
verify_script = ("""// Verify Bootstrap Tour activated
... |
Allows you to use Hopscotch Tours with SeleniumBase http:// linkedin. github. io/ hopscotch/ | def activate_hopscotch(driver):
""" Allows you to use Hopscotch Tours with SeleniumBase
http://linkedin.github.io/hopscotch/
"""
hopscotch_css = constants.Hopscotch.MIN_CSS
hopscotch_js = constants.Hopscotch.MIN_JS
backdrop_style = style_sheet.hops_backdrop_style
verify_script = ("""// ... |
Allows you to use IntroJS Tours with SeleniumBase https:// introjs. com/ | def activate_introjs(driver):
""" Allows you to use IntroJS Tours with SeleniumBase
https://introjs.com/
"""
intro_css = constants.IntroJS.MIN_CSS
intro_js = constants.IntroJS.MIN_JS
verify_script = ("""// Verify IntroJS activated
var intro2 = introJs();
... |
Allows you to use Shepherd Tours with SeleniumBase http:// github. hubspot. com/ shepherd/ docs/ welcome/ | def activate_shepherd(driver):
""" Allows you to use Shepherd Tours with SeleniumBase
http://github.hubspot.com/shepherd/docs/welcome/
"""
shepherd_js = constants.Shepherd.MIN_JS
sh_theme_arrows_css = constants.Shepherd.THEME_ARROWS_CSS
sh_theme_arrows_fix_css = constants.Shepherd.THEME_ARR_... |
Plays a Shepherd tour on the current website. | def play_shepherd_tour(driver, tour_steps, msg_dur, name=None, interval=0):
""" Plays a Shepherd tour on the current website. """
instructions = ""
for tour_step in tour_steps[name]:
instructions += tour_step
instructions += ("""
// Start the tour
tour.start();
$tour = to... |
Plays a Bootstrap tour on the current website. | def play_bootstrap_tour(
driver, tour_steps, browser, msg_dur, name=None, interval=0):
""" Plays a Bootstrap tour on the current website. """
instructions = ""
for tour_step in tour_steps[name]:
instructions += tour_step
instructions += (
"""]);
// Initialize the tour
... |
Plays an IntroJS tour on the current website. | def play_introjs_tour(
driver, tour_steps, browser, msg_dur, name=None, interval=0):
""" Plays an IntroJS tour on the current website. """
instructions = ""
for tour_step in tour_steps[name]:
instructions += tour_step
instructions += (
"""]
});
intro.setOption("di... |
Exports a tour as a JS file. It will include necessary resources as well such as jQuery. You ll be able to copy the tour directly into the Console of any web browser to play the tour outside of SeleniumBase runs. | def export_tour(tour_steps, name=None, filename="my_tour.js", url=None):
""" Exports a tour as a JS file.
It will include necessary resources as well, such as jQuery.
You'll be able to copy the tour directly into the Console of
any web browser to play the tour outside of SeleniumBase runs. "... |
Clears the downloads folder. If settings. ARCHIVE_EXISTING_DOWNLOADS is set to True archives it. | def reset_downloads_folder():
''' Clears the downloads folder.
If settings.ARCHIVE_EXISTING_DOWNLOADS is set to True, archives it. '''
if os.path.exists(downloads_path) and not os.listdir(downloads_path) == []:
archived_downloads_folder = os.path.join(downloads_path, '..',
... |
Returns whether the specified element selector is present on the page. | def is_element_present(driver, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified element selector is present on the page.
@Params
driver - the webdriver object (required)
selector - the locator that is used (required)
by - the method to search for the locator (Default: By.CSS_SELE... |
Returns whether the specified element selector is visible on the page. | def is_element_visible(driver, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified element selector is visible on the page.
@Params
driver - the webdriver object (required)
selector - the locator that is used (required)
by - the method to search for the locator (Default: By.CSS_SELE... |
Returns whether the specified text is visible in the specified selector. | def is_text_visible(driver, text, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified text is visible in the specified selector.
@Params
driver - the webdriver object (required)
text - the text string to search for
selector - the locator that is used (required)
by - the method t... |
Fires the hover event for the specified element by the given selector. | def hover_on_element(driver, selector, by=By.CSS_SELECTOR):
"""
Fires the hover event for the specified element by the given selector.
@Params
driver - the webdriver object (required)
selector - the locator (css selector) that is used (required)
by - the method to search for the locator (Default... |
Similar to hover_and_click () but assumes top element is already found. | def hover_element_and_click(driver, element, click_selector,
click_by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
"""
Similar to hover_and_click(), but assumes top element is already found.
"""
start_ms = time.time() * 1000.0
stop_ms = st... |
Searches for the specified element by the given selector. Returns the element object if the element is present on the page. The element can be invisible. Raises an exception if the element does not appear in the specified timeout. | def wait_for_element_present(driver, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
"""
Searches for the specified element by the given selector. Returns the
element object if the element is present on the page. The element can be
invisible. Raises an excepti... |
Searches for the specified element by the given selector. Returns the element object if the element is present and visible on the page. Raises an exception if the element does not appear in the specified timeout. @Params driver - the webdriver object ( required ) selector - the locator that is used ( required ) by - th... | def wait_for_element_visible(driver, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
"""
Searches for the specified element by the given selector. Returns the
element object if the element is present and visible on the page.
Raises an exception if the element ... |
Finds all WebElements that match a selector and are visible. Similar to webdriver. find_elements. | def find_visible_elements(driver, selector, by=By.CSS_SELECTOR):
"""
Finds all WebElements that match a selector and are visible.
Similar to webdriver.find_elements.
@Params
driver - the webdriver object (required)
selector - the locator that is used to search the DOM (required)
by - the met... |
Saves a screenshot to the current directory ( or to a subfolder if provided ) If the folder provided doesn t exist it will get created. The screenshot will be in PNG format. | def save_screenshot(driver, name, folder=None):
"""
Saves a screenshot to the current directory (or to a subfolder if provided)
If the folder provided doesn't exist, it will get created.
The screenshot will be in PNG format.
"""
if "." not in name:
name = name + ".png"
if folder:
... |
Wait for and accept an alert. Returns the text from the alert. | def wait_for_and_accept_alert(driver, timeout=settings.LARGE_TIMEOUT):
"""
Wait for and accept an alert. Returns the text from the alert.
@Params
driver - the webdriver object (required)
timeout - the time to wait for the alert in seconds
"""
alert = wait_for_and_switch_to_alert(driver, time... |
Wait for and dismiss an alert. Returns the text from the alert. | def wait_for_and_dismiss_alert(driver, timeout=settings.LARGE_TIMEOUT):
"""
Wait for and dismiss an alert. Returns the text from the alert.
@Params
driver - the webdriver object (required)
timeout - the time to wait for the alert in seconds
"""
alert = wait_for_and_switch_to_alert(driver, ti... |
Wait for a browser alert to appear and switch to it. This should be usable as a drop - in replacement for driver. switch_to. alert when the alert box may not exist yet. | def wait_for_and_switch_to_alert(driver, timeout=settings.LARGE_TIMEOUT):
"""
Wait for a browser alert to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.alert when the alert box
may not exist yet.
@Params
driver - the webdriver object (required)
... |
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(driver, frame, timeout=settings.SMALL_TIMEOUT):
"""
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
driver - the webdriver object (required)
frame - the frame element, name, or index
time... |
Wait for a window to appear and switch to it. This should be usable as a drop - in replacement for driver. switch_to. window (). | def switch_to_window(driver, window, timeout=settings.SMALL_TIMEOUT):
"""
Wait for a window to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.window().
@Params
driver - the webdriver object (required)
window - the window index or window handle
t... |
Use this to convert a url like this: https:// blog. xkcd. com/ 2014/ 07/ 22/ what - if - book - tour/ Into this: https:// blog. xkcd. com | def get_domain_url(url):
"""
Use this to convert a url like this:
https://blog.xkcd.com/2014/07/22/what-if-book-tour/
Into this:
https://blog.xkcd.com
"""
if "http://" not in url and "https://" not in url:
return url
url_header = url.split('://')[0]
simple_url = url.split(':/... |
A basic method to determine if a selector is an xpath selector. | def is_xpath_selector(selector):
"""
A basic method to determine if a selector is an xpath selector.
"""
if (selector.startswith('/') or selector.startswith('./') or (
selector.startswith('('))):
return True
return False |
A basic method to get the link text from a link text selector. | def get_link_text_from_selector(selector):
"""
A basic method to get the link text from a link text selector.
"""
if selector.startswith('link='):
return selector.split('link=')[1]
elif selector.startswith('link_text='):
return selector.split('link_text=')[1]
return selector |
Returns all unique links. Includes: a - > href img - > src link - > href and script - > src links. | def _get_unique_links(page_url, soup):
"""
Returns all unique links.
Includes:
"a"->"href", "img"->"src", "link"->"href", and "script"->"src" links.
"""
if "http://" not in page_url and "https://" not in page_url:
return []
prefix = 'http:'
if page_url.startswith('https:'):
... |
Get the status code of a link. If the timeout is exceeded will return a 404. For a list of available status codes see: https:// en. wikipedia. org/ wiki/ List_of_HTTP_status_codes | def _get_link_status_code(link, allow_redirects=False, timeout=5):
""" Get the status code of a link.
If the timeout is exceeded, will return a 404.
For a list of available status codes, see:
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
"""
status_code = None
try:
... |
Finds all unique links in the html of the page source and then prints out those links with their status codes. Format: [ link - > status_code ] ( per line ) Page links include those obtained from: a - > href img - > src link - > href and script - > src. | def _print_unique_links_with_status_codes(page_url, soup):
""" Finds all unique links in the html of the page source
and then prints out those links with their status codes.
Format: ["link" -> "status_code"] (per line)
Page links include those obtained from:
"a"->"href", "img"->"... |
Decorator for implementing exponential backoff for retrying on failures. | def retry_on_exception(tries=6, delay=1, backoff=2, max_delay=32):
'''
Decorator for implementing exponential backoff for retrying on failures.
tries: Max number of tries to execute the wrapped function before failing.
delay: Delay time in seconds before the FIRST retry.
backoff: Multiplier to exte... |
This decorator limits how often a method can get called in a second. If the limit is exceeded the call will be held in a queue until enough time has passed. Useful when trying to avoid overloading a system with rapid calls. | def rate_limited(max_per_second):
""" This decorator limits how often a method can get called in a second.
If the limit is exceeded, the call will be held in a queue until
enough time has passed.
Useful when trying to avoid overloading a system with rapid calls. """
min_interval = 1.0 / ... |
This decorator marks methods as deprecated. A warning is displayed if the method is called. | def deprecated(message=None):
""" This decorator marks methods as deprecated.
A warning is displayed if the method is called. """
def decorated_method_to_deprecate(func):
if inspect.isclass(func):
# Handle a deprecated class differently from a deprecated method
msg = "Cl... |
Connect to the IMAP mailbox. | def imap_connect(self):
"""
Connect to the IMAP mailbox.
"""
self.mailbox = imaplib.IMAP4_SSL(self.imap_string, self.port)
self.mailbox.login(self.uname, self.pwd)
self.mailbox.select() |
Searches for query in the given IMAP criteria and returns the message numbers that match as a list of strings. | def __imap_search(self, ** criteria_dict):
""" Searches for query in the given IMAP criteria and returns
the message numbers that match as a list of strings.
Criteria without values (eg DELETED) should be keyword args
with KEY=True, or else not passed. Criteria with values should
... |
This takes the result of imap_search and returns SANE results | def __parse_imap_search_result(self, result):
"""
This takes the result of imap_search and returns SANE results
@Params
result - result from an imap_search call
@Returns
List of IMAP search results
"""
if isinstance(result, types.ListType):
# A... |
Given a message number that we found with imap_search get the text/ html content. | def fetch_html(self, msg_nums):
"""
Given a message number that we found with imap_search,
get the text/html content.
@Params
msg_nums - message number to get html message for
@Returns
HTML content of message matched by message number
"""
if not ms... |
Given a message number that we found with imap_search get the text/ plain content. | def fetch_plaintext(self, msg_nums):
"""
Given a message number that we found with imap_search,
get the text/plain content.
@Params
msg_nums - message number to get message for
@Returns
Plaintext content of message matched by message number
"""
if ... |
Given a message number that we found with imap_search fetch the whole source dump that into an email object and pick out the part that matches the content type specified. Return that if we got multiple emails return dict of all the parts. | def __imap_fetch_content_type(self, msg_nums, content_type):
"""
Given a message number that we found with imap_search, fetch the
whole source, dump that into an email object, and pick out the part
that matches the content type specified. Return that, if we got
multiple emails, r... |
Get the html of an email searching by subject. | def fetch_html_by_subject(self, email_name):
"""
Get the html of an email, searching by subject.
@Params
email_name - the subject to search for
@Returns
HTML content of the matched email
"""
if not email_name:
raise EmailException("Subject cann... |
Get the plain text of an email searching by subject. | def fetch_plaintext_by_subject(self, email_name):
"""
Get the plain text of an email, searching by subject.
@Params
email_name - the subject to search for
@Returns
Plaintext content of the matched email
"""
if not email_name:
raise EmailExcepti... |
Get content of emails sent to a specific email address. | def search_for_recipient(self, email, timeout=None, content_type=None):
"""
Get content of emails, sent to a specific email address.
@Params
email - the recipient email address to search for
timeout - seconds to try beore timing out
content_type - type of email string to ... |
Get content of emails sent to a specific email address. | def search_for_subject(self, subject, timeout=None, content_type=None):
"""
Get content of emails, sent to a specific email address.
@Params
email - the recipient email address to search for
timeout - seconds to try beore timing out
content_type - type of email string to ... |
A search that keeps searching up until timeout for a specific number of matches to a search. If timeout is not specified we use the default. If count = is not specified we will fail. Return values are the same as search () except for count = 0 where we will return an empty list. Use this if you need to wait for a numbe... | def search_for_count(self, ** args):
"""
A search that keeps searching up until timeout for a
specific number of matches to a search. If timeout is not
specified we use the default. If count= is not specified we
will fail. Return values are the same as search(), except for count... |
Checks an Email. Message object for the headers in email_headers. | def __check_msg_for_headers(self, msg, ** email_headers):
"""
Checks an Email.Message object for the headers in email_headers.
Following are acceptable header names: ['Delivered-To',
'Received', 'Return-Path', 'Received-SPF',
'Authentication-Results', 'DKIM-Signature',
... |
Given a message number return the Email. Message object. | def fetch_message(self, msgnum):
"""
Given a message number, return the Email.Message object.
@Params
msgnum - message number to find
@Returns
Email.Message object for the given message number
"""
self.imap_connect()
status, data = self.mailbox.fet... |
Given an Email. Message object gets the content - type payload as specified by | def get_content_type(self, msg, content_type="HTML"):
"""
Given an Email.Message object, gets the content-type payload
as specified by @content_type. This is the actual body of the
email.
@Params
msg - Email.Message object to get message content for
content_type -... |
Checks email inbox every 15 seconds that match the criteria up until timeout. | def search(self, ** args):
"""
Checks email inbox every 15 seconds that match the criteria
up until timeout.
Search criteria should be keyword args eg
TO="selenium@gmail.com". See __imap_search docstring for list
of valid criteria. If content_type is not defined, will r... |
Clean whitespace from html | def remove_whitespace(self, html):
"""
Clean whitespace from html
@Params
html - html source to remove whitespace from
@Returns
String html without whitespace
"""
# Does python have a better way to do exactly this?
clean_html = html
for cha... |
Replace htmlentities with unicode characters | def replace_entities(self, html):
"""
Replace htmlentities with unicode characters
@Params
html - html source to replace entities in
@Returns
String html with entities replaced
"""
def fixup(text):
"""replace the htmlentities in some text"""
... |
The DOM ( Document Object Model ) has a property called readyState. When the value of this becomes complete page resources are considered fully loaded ( although AJAX and other loads might still be happening ). This method will wait until document. readyState == complete. | def wait_for_ready_state_complete(driver, timeout=settings.EXTREME_TIMEOUT):
"""
The DOM (Document Object Model) has a property called "readyState".
When the value of this becomes "complete", page resources are considered
fully loaded (although AJAX and other loads might still be happening).
This me... |
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(driver):
""" If "jQuery is not defined", use this method to activate it for use.
This happens because jQuery is not always defined on web sites. """
try:
# Let's first find out if jQuery is already defined.
driver.execute_script("jQuery('html')")
# Since that ... |
re. escape () works differently in Python 3. 7. 0 than earlier versions: | def escape_quotes_if_needed(string):
"""
re.escape() works differently in Python 3.7.0 than earlier versions:
Python 3.6.5:
>>> import re
>>> re.escape('"')
'\\"'
Python 3.7.0:
>>> import re
>>> re.escape('"')
'"'
SeleniumBase needs quotes to be properly escaped for Javasc... |
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(driver, 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:
driver.execute_script(script)
except Exception:
... |
A helper method to post a message on the screen with Messenger. ( Should only be called from post_message () in base_case. py ) | def post_message(driver, message, msg_dur, style="info"):
""" A helper method to post a message on the screen with Messenger.
(Should only be called from post_message() in base_case.py) """
if not msg_dur:
msg_dur = settings.DEFAULT_MESSAGE_DURATION
msg_dur = float(msg_dur)
message = re.... |
DEPRECATED - Use re. escape () instead which performs the intended action. Use before throwing raw code such as div [ tab = advanced ] into jQuery. Selectors with quotes inside of quotes would otherwise break jQuery. If you just want to escape quotes there s escape_quotes_if_needed (). This is similar to json. dumps ( ... | def _jq_format(code):
"""
DEPRECATED - Use re.escape() instead, which performs the intended action.
Use before throwing raw code such as 'div[tab="advanced"]' into jQuery.
Selectors with quotes inside of quotes would otherwise break jQuery.
If you just want to escape quotes, there's escape_quotes_if... |
When testing_base is specified but none of the log options to save are specified ( basic_test_info screen_shots page_source ) then save them all by default. Otherwise save only selected ones from their plugins. | def __log_all_options_if_none_specified(self, test):
"""
When testing_base is specified, but none of the log options to save are
specified (basic_test_info, screen_shots, page_source), then save them
all by default. Otherwise, save only selected ones from their plugins.
"""
... |
Since Skip Blocked and Deprecated are all technically errors but not error states we want to make sure that they don t show up in the nose output as errors. | def addError(self, test, err, capt=None):
"""
Since Skip, Blocked, and Deprecated are all technically errors, but not
error states, we want to make sure that they don't show up in
the nose output as errors.
"""
if (err[0] == errors.BlockedTest or (
err[0] ... |
If the database plugin is not present we have to handle capturing errors that shouldn t be reported as such in base. | def handleError(self, test, err, capt=None):
"""
If the database plugin is not present, we have to handle capturing
"errors" that shouldn't be reported as such in base.
"""
if not hasattr(test.test, "testcase_guid"):
if err[0] == errors.BlockedTest:
ra... |
Executes a db query gets all the values and closes the connection. | def query_fetch_all(self, query, values):
"""
Executes a db query, gets all the values, and closes the connection.
"""
self.cursor.execute(query, values)
retval = self.cursor.fetchall()
self.__close_db()
return retval |
Executes a db query gets the first value and closes the connection. | def query_fetch_one(self, query, values):
"""
Executes a db query, gets the first value, and closes the connection.
"""
self.cursor.execute(query, values)
retval = self.cursor.fetchone()
self.__close_db()
return retval |
Executes a query to the test_db and closes the connection afterwards. | def execute_query(self, query, values):
"""
Executes a query to the test_db and closes the connection afterwards.
"""
retval = self.cursor.execute(query, values)
self.__close_db()
return retval |
Combines the domain base href with the html source. This is needed for the page html to render correctly. | def get_html_source_with_base_href(driver, page_source):
''' Combines the domain base href with the html source.
This is needed for the page html to render correctly. '''
last_page = get_last_page(driver)
if '://' in last_page:
base_href_html = get_base_href_html(last_page)
return '%... |
Handle Logging | def log_folder_setup(log_path, archive_logs=False):
""" Handle Logging """
if log_path.endswith("/"):
log_path = log_path[:-1]
if not os.path.exists(log_path):
try:
os.makedirs(log_path)
except Exception:
pass # Should only be reachable during multi-threaded ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.