text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Constructs the where clause based on a dictionary of values <END_TASK> <USER_TASK:> Description: def build_where_clause(mappings, operator='AND'): """Constructs the where clause based on a dictionary of values >>> build_where_clause({'id': 456, 'name': 'myrecord'}, operator='OR') >>> 'WHERE id = 456 OR name = "myrecord" ' """
where_clause_mappings = {} where_clause_mappings.update(mappings) where_clause = 'WHERE ' + ' {} '.format(operator).join( '{k} = {v}'.format(k=k, v='"{}"'.format(v) if isinstance(v, basestring) else v) for k, v in where_clause_mappings.iteritems() ) return where_clause
<SYSTEM_TASK:> Executes and commits the sql statement <END_TASK> <USER_TASK:> Description: def execute_and_commit(*args, **kwargs): """Executes and commits the sql statement @return: None """
db, cursor = CoyoteDb.execute(*args, **kwargs) db.commit() return cursor
<SYSTEM_TASK:> Updates and commits with an insert sql statement, returns the record, but with a small chance of a race <END_TASK> <USER_TASK:> Description: def update(sql, *args, **kwargs): """Updates and commits with an insert sql statement, returns the record, but with a small chance of a race condition @param sql: sql to execute @return: The last row inserted """
assert "update" in sql.lower(), 'This function requires an update statement, provided: {}'.format(sql) cursor = CoyoteDb.execute_and_commit(sql, *args, **kwargs) # now get that id last_row_id = cursor.lastrowid return last_row_id
<SYSTEM_TASK:> Deletes and commits with an insert sql statement <END_TASK> <USER_TASK:> Description: def delete(sql, *args, **kwargs): """Deletes and commits with an insert sql statement"""
assert "delete" in sql.lower(), 'This function requires a delete statement, provided: {}'.format(sql) CoyoteDb.execute_and_commit(sql, *args, **kwargs)
<SYSTEM_TASK:> Given a dictionary and an object instance, will set all object attributes equal to the dictionary's keys and <END_TASK> <USER_TASK:> Description: def update_object_from_dictionary_representation(dictionary, instance): """Given a dictionary and an object instance, will set all object attributes equal to the dictionary's keys and values. Assumes dictionary does not have any keys for which object does not have attributes @type dictionary: dict @param dictionary: Dictionary representation of the object @param instance: Object instance to populate @return: None """
for key, value in dictionary.iteritems(): if hasattr(instance, key): setattr(instance, key, value) return instance
<SYSTEM_TASK:> Formats a time to be Shapeways database-compatible <END_TASK> <USER_TASK:> Description: def format_time(time): """Formats a time to be Shapeways database-compatible @param time: Datetime or string object to format @rtype: str @return: Time formatted as a string """
# Handle time typing try: time = time.isoformat() except AttributeError: # Not a datetime object time = str(time) time = parser.parse(time).strftime('%Y-%m-%d %H:%M:%S') return time
<SYSTEM_TASK:> Formats a date to be Shapeways database-compatible <END_TASK> <USER_TASK:> Description: def format_date(date): """Formats a date to be Shapeways database-compatible @param date: Datetime or string object to format @rtype: str @return: Date formatted as a string """
# Handle time typing try: date = date.isoformat() except AttributeError: # Not a datetime object date = str(date) date = parser.parse(date).strftime('%Y-%m-%d') return date
<SYSTEM_TASK:> Driver gets the provided url in the browser, returns True if successful <END_TASK> <USER_TASK:> Description: def visit(self, url=''): """ Driver gets the provided url in the browser, returns True if successful url -- An absolute or relative url stored as a string """
def _visit(url): if len(url) > 0 and url[0] == '/': # url's first character is a forward slash; treat as relative path path = url full_url = self.driver.current_url parsed_url = urlparse(full_url) base_url = str(parsed_url.scheme) + '://' + str(parsed_url.netloc) url = urljoin(base_url, path) try: return self.driver.get(url) except TimeoutException: if self.ignore_page_load_timeouts: pass else: raise PageTimeoutException.PageTimeoutException(self, url) return self.execute_and_handle_webdriver_exceptions(lambda: _visit(url))
<SYSTEM_TASK:> Tests if an alert is present <END_TASK> <USER_TASK:> Description: def is_alert_present(self): """Tests if an alert is present @return: True if alert is present, False otherwise """
current_frame = None try: current_frame = self.driver.current_window_handle a = self.driver.switch_to_alert() a.text except NoAlertPresentException: # No alert return False except UnexpectedAlertPresentException: # Alert exists return True finally: if current_frame: self.driver.switch_to_window(current_frame) return True
<SYSTEM_TASK:> Attempts to locate an element, trying the number of times specified by the driver wrapper; <END_TASK> <USER_TASK:> Description: def find(self, locator, find_all=False, search_object=None, force_find=False, exclude_invisible=False): """ Attempts to locate an element, trying the number of times specified by the driver wrapper; Will throw a WebDriverWrapperException if no element is found @type locator: webdriverwrapper.support.locator.Locator @param locator: the locator or css string used to query the element @type find_all: bool @param find_all: set to True to locate all located elements as a list @type search_object: webdriverwrapper.WebElementWrapper @param force_find: If true will use javascript to find elements @type force_find: bool @param search_object: A WebDriver or WebElement object to call find_element(s)_by_xxxxx """
search_object = self.driver if search_object is None else search_object attempts = 0 while attempts < self.find_attempts + 1: if bool(force_find): js_locator = self.locator_handler.parse_locator(locator) if js_locator.By != 'css selector': raise ValueError( 'You must use a css locator in order to force find an element; this was "{}"'.format( js_locator)) elements = self.js_executor.execute_template_and_return_result( 'getElementsTemplate.js', variables={'selector': js_locator.value}) else: elements = self.locator_handler.find_by_locator(search_object, locator, True) # Save original elements found before applying filters to the list all_elements = elements # Check for only visible elements visible_elements = elements if exclude_invisible: visible_elements = [element for element in all_elements if element.is_displayed()] elements = visible_elements if len(elements) > 0: if find_all is True: # return list of wrapped elements for index in range(len(elements)): elements[index] = WebElementWrapper.WebElementWrapper(self, locator, elements[index], search_object=search_object) return elements elif find_all is False: # return first element return WebElementWrapper.WebElementWrapper(self, locator, elements[0], search_object=search_object) else: if attempts >= self.find_attempts: if find_all is True: # returns an empty list if finding all elements return [] else: # raise exception if attempting to find one element error_message = "Unable to find element after {0} attempts with locator: {1}".format( attempts, locator ) # Check if filters limited the results if exclude_invisible and len(visible_elements) == 0 and len(all_elements) > 0: error_message = "Elements found using locator {}, but none were visible".format(locator) raise WebDriverWrapperException.WebDriverWrapperException(self, error_message) else: attempts += 1
<SYSTEM_TASK:> Determines whether an element is present on the page, retrying once if unable to locate <END_TASK> <USER_TASK:> Description: def is_present(self, locator, search_object=None): """ Determines whether an element is present on the page, retrying once if unable to locate @type locator: webdriverwrapper.support.locator.Locator @param locator: the locator or css string used to query the element @type search_object: webdriverwrapper.WebElementWrapper @param search_object: Optional WebElement to start search with. If null, search will be on self.driver """
all_elements = self._find_immediately(locator, search_object=search_object) if all_elements is not None and len(all_elements) > 0: return True else: return False
<SYSTEM_TASK:> Determines whether an element is present on the page with no wait <END_TASK> <USER_TASK:> Description: def is_present_no_wait(self, locator): """ Determines whether an element is present on the page with no wait @type locator: webdriverwrapper.support.locator.Locator @param locator: the locator or css string used to query the element """
# first attempt to locate the element def execute(): ''' Generic function to execute wait ''' return True if len(self.locator_handler.find_by_locator(self.driver, locator, True)) < 0 else False return self.execute_and_handle_webdriver_exceptions( execute, timeout=0, locator=locator, failure_message='Error running webdriver.find_all.')
<SYSTEM_TASK:> Waits for an element to be present <END_TASK> <USER_TASK:> Description: def wait_until_present(self, locator, timeout=None, failure_message='Timeout waiting for element to be present'): """ Waits for an element to be present @type locator: webdriverwrapper.support.locator.Locator @param locator: the locator or css string to search for the element @type timeout: int @param timeout: the maximum number of seconds the driver will wait before timing out @rtype: webdriverwrapper.WebElementWrapper @return: Returns the element found """
timeout = timeout if timeout is not None else self.timeout def wait(): ''' Wait function passed to executor ''' element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located( (self.locator_handler.parse_locator(locator).By, self.locator_handler.parse_locator(locator).value))) return WebElementWrapper.WebElementWrapper(self, locator, element) return self.execute_and_handle_webdriver_exceptions( wait, timeout, locator, failure_message=failure_message)
<SYSTEM_TASK:> Waits for an element to no longer be present <END_TASK> <USER_TASK:> Description: def wait_until_not_present(self, locator, timeout=None): """ Waits for an element to no longer be present @type locator: webdriverwrapper.support.locator.Locator @param locator: the locator or css string to search for the element @type timeout: int @param timeout: the maximum number of seconds the driver will wait before timing out @rtype: webdriverwrapper.WebElementWrapper @return: Returns the element found """
# TODO: rethink about neg case with is_present and waiting too long timeout = timeout if timeout is not None else self.timeout this = self # for passing WebDriverWrapperReference to WebDriverWait def wait(): ''' Wait function pasted to executor ''' return WebDriverWait(self.driver, timeout).until(lambda d: not this.is_present(locator)) return self.execute_and_handle_webdriver_exceptions( wait, timeout, locator, 'Timeout waiting for element not to be present')
<SYSTEM_TASK:> Waits for an element to be invisible <END_TASK> <USER_TASK:> Description: def wait_until_invisibility_of(self, locator, timeout=None): """ Waits for an element to be invisible @type locator: webdriverwrapper.support.locator.Locator @param locator: the locator or css string to search for the element @type timeout: int @param timeout: the maximum number of seconds the driver will wait before timing out @rtype: webdriverwrapper.WebElementWrapper @return: Returns the element found """
timeout = timeout if timeout is not None else self.timeout def wait(): ''' Wait function passed to executor ''' element = WebDriverWait(self.driver, timeout).until(EC.invisibility_of_element_located( (self.locator_handler.parse_locator(locator).By, self.locator_handler.parse_locator(locator).value))) return WebElementWrapper.WebElementWrapper(self, locator, element) return self.execute_and_handle_webdriver_exceptions( wait, timeout, locator, 'Timeout waiting for element to be invisible')
<SYSTEM_TASK:> Waits for an element to be clickable <END_TASK> <USER_TASK:> Description: def wait_until_clickable(self, locator, timeout=None): """ Waits for an element to be clickable @type locator: webdriverwrapper.support.locator.Locator @param locator: the locator or css string to search for the element @type timeout: int @param timeout: the maximum number of seconds the driver will wait before timing out @rtype: webdriverwrapper.WebElementWrapper @return: Returns the element found """
timeout = timeout if timeout is not None else self.timeout def wait(): ''' Wait function passed to executor ''' element = WebDriverWait(self.driver, timeout).until(EC.element_to_be_clickable( (self.locator_handler.parse_locator(locator).By, self.locator_handler.parse_locator(locator).value))) return WebElementWrapper.WebElementWrapper(self, locator, element) return self.execute_and_handle_webdriver_exceptions( wait, timeout, locator, 'Timeout waiting for element to be clickable')
<SYSTEM_TASK:> Waits for an element to be stale in the DOM <END_TASK> <USER_TASK:> Description: def wait_until_stale(self, locator, timeout=None): """ Waits for an element to be stale in the DOM @type locator: webdriverwrapper.support.locator.Locator @param locator: the locator or css string to search for the element @type timeout: int @param timeout: the maximum number of seconds the driver will wait before timing out @rtype: webdriverwrapper.WebElementWrapper @return: Returns the element found """
timeout = timeout if timeout is not None else self.timeout def wait(): ''' Wait function passed to executor ''' element = WebDriverWait(self.driver, timeout).until(EC.staleness_of( (self.locator_handler.parse_locator(locator).By, self.locator_handler.parse_locator(locator).value))) return WebElementWrapper.WebElementWrapper(self, locator, element) return self.execute_and_handle_webdriver_exceptions( wait, timeout, locator, 'Timeout waiting for element to become stale')
<SYSTEM_TASK:> Waits for an alert to be present <END_TASK> <USER_TASK:> Description: def wait_until_alert_is_present(self, timeout=None): """ Waits for an alert to be present @type timeout: int @param timeout: the maximum number of seconds the driver will wait before timing out @rtype: webdriverwrapper.WebElementWrapper @return: Returns the element found """
timeout = timeout if timeout is not None else self.timeout locator = None def wait(): ''' Wait function passed to executor ''' return WebDriverWait(self.driver, timeout).until(EC.alert_is_present()) return self.execute_and_handle_webdriver_exceptions( wait, timeout, locator, 'Timeout waiting for alert to be present')
<SYSTEM_TASK:> Waits for an element's text to not be empty <END_TASK> <USER_TASK:> Description: def wait_until_text_is_not_empty(self, locator, timeout=None): """ Waits for an element's text to not be empty @type locator: webdriverwrapper.support.locator.Locator @param locator: locator used to find element @type timeout: int @param timeout: the maximum number of seconds the driver will wait before timing out @rtype: webdriverwrapper.WebElementWrapper @return: Returns the element found """
timeout = timeout if timeout is not None else self.timeout self.wait_for(locator) # first check that element exists def wait(): ''' Wait function passed to executor ''' WebDriverWait(self.driver, timeout).until(lambda d: len(self.find(locator).text()) > 0) return self.find(locator) return self.execute_and_handle_webdriver_exceptions( wait, timeout, locator, 'Timeout waiting for element to contain some text')
<SYSTEM_TASK:> Waits for AJAX requests made through <END_TASK> <USER_TASK:> Description: def wait_until_jquery_requests_are_closed(self, timeout=None): """Waits for AJAX requests made through @type timeout: int @param timeout: the maximum number of seconds the driver will wait before timing out @return: None """
timeout = timeout if timeout is not None else self.timeout def wait(): ''' Wait function passed to executor ''' WebDriverWait(self.driver, timeout).until( lambda d: self.js_executor.execute_template('isJqueryAjaxComplete', {})) return True return self.execute_and_handle_webdriver_exceptions( wait, timeout, None, 'Timeout waiting for all jQuery AJAX requests to close')
<SYSTEM_TASK:> Executor for wait functions <END_TASK> <USER_TASK:> Description: def execute_and_handle_webdriver_exceptions(self, function_to_execute, timeout=None, locator=None, failure_message=None): """ Executor for wait functions @type function_to_execute: types.FunctionType @param function_to_execute: wait function specifying the type of wait @type timeout: int @param timeout: the maximum number of seconds the driver will wait before timing out @type locator: webdriverwrapper.support.locator.Locator @param locator: locator used to find element @type failure_message: str @param failure_message: message shown in exception if wait fails @rtype: webdriverwrapper.WebElementWrapper @return: Returns the element found """
logger = logging.getLogger(__name__) try: val = function_to_execute() for cb in self.action_callbacks: cb.__call__(self) return val except TimeoutException: raise WebDriverTimeoutException.WebDriverTimeoutException(self, timeout, locator, failure_message) except httplib.BadStatusLine, e: logger.error('BadStatusLine error raised on WebDriver action (line: {}, args:{}, message: {})'.format( e.line, e.args, e.message )) raise except httplib.CannotSendRequest: logger.error('CannotSendRequest error raised on WebDriver action') raise except UnexpectedAlertPresentException: # NOTE: handling alerts in this way expects that WebDriver does not dismiss unexpected alerts. That # setting can be changed by modifying the unexpectedAlertBehaviour setting msg = '<failed to parse message from alert>' try: a = self.driver.switch_to_alert() msg = a.text except Exception, e: msg = '<error parsing alert due to {} (note: parsing ' \ 'alert text expects "unexpectedAlertBehaviour" to be set to "ignore")>'.format(e) logger.critical(msg) finally: logger.error('Unexpected alert raised on a WebDriver action; alert message was: {}'.format(msg)) raise UnexpectedAlertPresentException('Unexpected alert on page, alert message was: "{}"'.format(msg))
<SYSTEM_TASK:> Injects a radio button into the page and waits for the user to click it; will raise an exception if the <END_TASK> <USER_TASK:> Description: def pause_and_wait_for_user(self, timeout=None, prompt_text='Click to resume (WebDriver is paused)'): """Injects a radio button into the page and waits for the user to click it; will raise an exception if the radio to resume is never checked @return: None """
timeout = timeout if timeout is not None else self.user_wait_timeout # Set the browser state paused self.paused = True def check_user_ready(driver): """Polls for the user to be "ready" (meaning they checked the checkbox) and the driver to be unpaused. If the checkbox is not displayed (e.g. user navigates the page), it will re-insert it into the page @type driver: WebDriverWrapper @param driver: Driver to execute @return: True if user is ready, false if not """ if driver.paused: if driver.is_user_ready(): # User indicated they are ready; free the browser lock driver.paused = False return True else: if not driver.is_present(Locator('css', '#webdriver-resume-radio', 'radio to unpause webdriver')): # Display the prompt pause_html = staticreader.read_html_file('webdriverpaused.html')\ .replace('\n', '')\ .replace('PROMPT_TEXT', prompt_text) webdriver_style = staticreader.read_css_file('webdriverstyle.css').replace('\n', '') # Insert the webdriver style driver.js_executor.execute_template_and_return_result( 'injectCssTemplate.js', {'css': webdriver_style}) # Insert the paused html driver.js_executor.execute_template_and_return_result( 'injectHtmlTemplate.js', {'selector': 'body', 'html': pause_html}) return False self.wait_until( lambda: check_user_ready(self), timeout=timeout, failure_message='Webdriver actions were paused but did not receive the command to continue. ' 'You must click the on-screen message to resume.' ) # Remove all injected elements self.js_executor.execute_template_and_return_result( 'deleteElementsTemplate.js', {'selector': '.webdriver-injected'} )
<SYSTEM_TASK:> Gets the console log of the browser <END_TASK> <USER_TASK:> Description: def get_browser_log(self, levels=None): """Gets the console log of the browser @type levels: @return: List of browser log entries """
logs = self.driver.get_log('browser') self.browser_logs += logs if levels is not None: logs = [entry for entry in logs if entry.get(u'level') in levels] return logs
<SYSTEM_TASK:> Close driver and kill all associated displays <END_TASK> <USER_TASK:> Description: def quit(self): """Close driver and kill all associated displays """
# Kill the driver def _quit(): try: self.driver.quit() except Exception, err_driver: os.kill(self.driver_pid, signal.SIGKILL) raise finally: # Kill the display for this driver window try: if self.display: self.display.stop() except Exception, err_display: os.kill(self.display_pid, signal.SIGKILL) raise return self.execute_and_handle_webdriver_exceptions(_quit)
<SYSTEM_TASK:> Visit the url, checking for rr errors in the response <END_TASK> <USER_TASK:> Description: def visit(self, url=''): """Visit the url, checking for rr errors in the response @param url: URL @return: Visit result """
result = super(CoyoteDriver, self).visit(url) source = self.page_source() return result
<SYSTEM_TASK:> Loads all attributes from source config into target config <END_TASK> <USER_TASK:> Description: def load_config_vars(target_config, source_config): """Loads all attributes from source config into target config @type target_config: TestRunConfigManager @param target_config: Config to dump variables into @type source_config: TestRunConfigManager @param source_config: The other config @return: True """
# Overwrite all attributes in config with new config for attr in dir(source_config): # skip all private class attrs if attr.startswith('_'): continue val = getattr(source_config, attr) if val is not None: setattr(target_config, attr, val)
<SYSTEM_TASK:> Runs a series of functions in parallel. Return values are ordered by the order in which their functions <END_TASK> <USER_TASK:> Description: def run_parallel(*functions): """Runs a series of functions in parallel. Return values are ordered by the order in which their functions were passed. >>> val1, val2 = run_parallel( >>> lambda: 1 + 1 >>> lambda: 0 >>> ) If an exception is raised within one of the processes, that exception will be caught at the process level and raised by the parent process as an ErrorInProcessException, which will track all errors raised in all processes. You can catch the exception raised for more details into the process exceptions: >>> try: >>> val1, val2 = run_parallel(fn1, fn2) >>> except ErrorInProcessException, e: >>> print.e.errors @param functions: The functions to run specified as individual arguments @return: List of results for those functions. Unpacking is recommended if you do not need to iterate over the results as it enforces the number of functions you pass in. >>> val1, val2 = run_parallel(fn1, fn2, fn3) # Will raise an error >>> vals = run_parallel(fn1, fn2, fn3) # Will not raise an error @raise: ErrorInProcessException """
def target(fn): def wrapped(results_queue, error_queue, index): result = None try: result = fn() except Exception, e: # Swallow errors or else the process will hang error_queue.put(e) warnings.warn('Exception raised in parallel threads: {}'.format(e)) results_queue.put((index, result)) return wrapped errors = Queue() queue = Queue() jobs = list() for i, function in enumerate(functions): jobs.append(Process(target=target(function), args=(queue, errors, i))) [job.start() for job in jobs] [job.join() for job in jobs] # Get the results in the queue and put them back in the order in which the function was specified in the args results = [queue.get() for _ in jobs] results = sorted(results, key=lambda x: x[0]) if not errors.empty(): error_list = list() while not errors.empty(): error_list.append(errors.get()) raise ErrorInProcessException('Exceptions raised in parallel threads: {}'.format(error_list), errors=error_list) return [r[1] for r in results]
<SYSTEM_TASK:> Returns an updated copy of the dictionary without modifying the original <END_TASK> <USER_TASK:> Description: def copy_and_update(dictionary, update): """Returns an updated copy of the dictionary without modifying the original"""
newdict = dictionary.copy() newdict.update(update) return newdict
<SYSTEM_TASK:> Retrieves the full path of the static directory <END_TASK> <USER_TASK:> Description: def get_static_directory(): """Retrieves the full path of the static directory @return: Full path of the static directory """
directory = templates_dir = os.path.join(os.path.dirname(__file__), 'static') return directory
<SYSTEM_TASK:> Reads the contents of an html file in the css directory <END_TASK> <USER_TASK:> Description: def read_html_file(filename): """Reads the contents of an html file in the css directory @return: Contents of the specified file """
with open(os.path.join(get_static_directory(), 'html/{filename}'.format(filename=filename))) as f: contents = f.read() return contents
<SYSTEM_TASK:> Parses a valid selenium By and value from a locator; <END_TASK> <USER_TASK:> Description: def parse_locator(locator): """ Parses a valid selenium By and value from a locator; returns as a named tuple with properties 'By' and 'value' locator -- a valid element locator or css string """
# handle backwards compatibility to support new Locator class if isinstance(locator, loc.Locator): locator = '{by}={locator}'.format(by=locator.by, locator=locator.locator) locator_tuple = namedtuple('Locator', 'By value') if locator.count('=') > 0 and locator.count('css=') < 1: by = locator[:locator.find('=')].replace('_', ' ') value = locator[locator.find('=')+1:] return locator_tuple(by, value) else: # assume default is css selector value = locator[locator.find('=')+1:] return locator_tuple('css selector', value)
<SYSTEM_TASK:> Asserts that assertion function passed to it will return True, <END_TASK> <USER_TASK:> Description: def spin_assert(self, assertion, failure_message='Failed Assertion', timeout=None): """ Asserts that assertion function passed to it will return True, trying every 'step' seconds until 'timeout' seconds have passed. """
timeout = self.timeout if timeout is None else timeout time_spent = 0 while time_spent < timeout: try: assert assertion() is True return True except AssertionError: pass sleep(self.step) time_spent += 1 raise WebDriverAssertionException.WebDriverAssertionException(self.driver_wrapper, failure_message)
<SYSTEM_TASK:> Assert the assertion, but throw a WebDriverAssertionException if assertion fails <END_TASK> <USER_TASK:> Description: def webdriver_assert(self, assertion, failure_message='Failed Assertion'): """ Assert the assertion, but throw a WebDriverAssertionException if assertion fails """
try: assert assertion() is True except AssertionError: raise WebDriverAssertionException.WebDriverAssertionException(self.driver_wrapper, failure_message) return True
<SYSTEM_TASK:> Asserts that a value is true <END_TASK> <USER_TASK:> Description: def assert_true(self, value, failure_message='Expected value to be True, was: {}'): """ Asserts that a value is true @type value: bool @param value: value to test for True """
assertion = lambda: bool(value) self.webdriver_assert(assertion, unicode(failure_message).format(value))
<SYSTEM_TASK:> Calls smart_assert, but creates its own assertion closure using <END_TASK> <USER_TASK:> Description: def assert_equals(self, actual_val, expected_val, failure_message='Expected values to be equal: "{}" and "{}"'): """ Calls smart_assert, but creates its own assertion closure using the expected and provided values with the '==' operator """
assertion = lambda: expected_val == actual_val self.webdriver_assert(assertion, unicode(failure_message).format(actual_val, expected_val))
<SYSTEM_TASK:> Asserts that two numbers are within an allowed delta of each other <END_TASK> <USER_TASK:> Description: def assert_numbers_almost_equal(self, actual_val, expected_val, allowed_delta=0.0001, failure_message='Expected numbers to be within {} of each other: "{}" and "{}"'): """ Asserts that two numbers are within an allowed delta of each other """
assertion = lambda: abs(expected_val - actual_val) <= allowed_delta self.webdriver_assert(assertion, unicode(failure_message).format(allowed_delta, actual_val, expected_val))
<SYSTEM_TASK:> Calls smart_assert, but creates its own assertion closure using <END_TASK> <USER_TASK:> Description: def assert_not_equal(self, actual_val, unexpected_val, failure_message='Expected values to differ: "{}" and "{}"'): """ Calls smart_assert, but creates its own assertion closure using the expected and provided values with the '!=' operator """
assertion = lambda: unexpected_val != actual_val self.webdriver_assert(assertion, unicode(failure_message).format(actual_val, unexpected_val))
<SYSTEM_TASK:> Calls smart_assert, but creates its own assertion closure using <END_TASK> <USER_TASK:> Description: def assert_is(self, actual_val, expected_type, failure_message='Expected type to be "{1}," but was "{0}"'): """ Calls smart_assert, but creates its own assertion closure using the expected and provided values with the 'is' operator """
assertion = lambda: expected_type is actual_val self.webdriver_assert(assertion, unicode(failure_message).format(actual_val, expected_type))
<SYSTEM_TASK:> Calls smart_assert, but creates its own assertion closure using <END_TASK> <USER_TASK:> Description: def assert_is_not(self, actual_val, unexpected_type, failure_message='Expected type not to be "{1}," but was "{0}"'): """ Calls smart_assert, but creates its own assertion closure using the expected and provided values with the 'is not' operator """
assertion = lambda: unexpected_type is not actual_val self.webdriver_assert(assertion, unicode(failure_message).format(actual_val, unexpected_type))
<SYSTEM_TASK:> Calls smart_assert, but creates its own assertion closure using <END_TASK> <USER_TASK:> Description: def assert_in(self, actual_collection_or_string, expected_value, failure_message='Expected "{1}" to be in "{0}"'): """ Calls smart_assert, but creates its own assertion closure using the expected and provided values with the 'in' operator """
assertion = lambda: expected_value in actual_collection_or_string self.webdriver_assert(assertion, unicode(failure_message).format(actual_collection_or_string, expected_value))
<SYSTEM_TASK:> Calls smart_assert, but creates its own assertion closure using <END_TASK> <USER_TASK:> Description: def assert_not_in(self, actual_collection_or_string, unexpected_value, failure_message='Expected "{1}" not to be in "{0}"'): """ Calls smart_assert, but creates its own assertion closure using the expected and provided values with the 'not in' operator """
assertion = lambda: unexpected_value not in actual_collection_or_string self.webdriver_assert(assertion, unicode(failure_message).format(actual_collection_or_string, unexpected_value))
<SYSTEM_TASK:> Asserts that the page source contains the string passed in expected_value <END_TASK> <USER_TASK:> Description: def assert_page_source_contains(self, expected_value, failure_message='Expected page source to contain: "{}"'): """ Asserts that the page source contains the string passed in expected_value """
assertion = lambda: expected_value in self.driver_wrapper.page_source() self.webdriver_assert(assertion, unicode(failure_message).format(expected_value))
<SYSTEM_TASK:> Asserts that a superset contains all elements of a subset <END_TASK> <USER_TASK:> Description: def assert_subset(self, subset, superset, failure_message='Expected collection "{}" to be a subset of "{}'): """ Asserts that a superset contains all elements of a subset """
assertion = lambda: set(subset).issubset(set(superset)) failure_message = unicode(failure_message).format(superset, subset) self.webdriver_assert(assertion, failure_message)
<SYSTEM_TASK:> Clears the field represented by this element <END_TASK> <USER_TASK:> Description: def clear(self): """ Clears the field represented by this element @rtype: WebElementWrapper @return: Returns itself """
def clear_element(): """ Wrapper to clear element """ return self.element.clear() self.execute_and_handle_webelement_exceptions(clear_element, 'clear') return self
<SYSTEM_TASK:> Deletes content in the input field by repeatedly typing HOME, then DELETE <END_TASK> <USER_TASK:> Description: def delete_content(self, max_chars=100): """ Deletes content in the input field by repeatedly typing HOME, then DELETE @rtype: WebElementWrapper @return: Returns itself """
def delete_content_element(): chars_deleted = 0 while len(self.get_attribute('value')) > 0 and chars_deleted < max_chars: self.click() self.send_keys(Keys.HOME) self.send_keys(Keys.DELETE) chars_deleted += 1 self.execute_and_handle_webelement_exceptions(delete_content_element, 'delete input contents') return self
<SYSTEM_TASK:> Clicks the element <END_TASK> <USER_TASK:> Description: def click(self, force_click=False): """ Clicks the element @type force_click: bool @param force_click: force a click on the element using javascript, skipping webdriver @rtype: WebElementWrapper @return: Returns itself """
js_executor = self.driver_wrapper.js_executor def click_element(): """ Wrapper to call click """ return self.element.click() def force_click_element(): """ Javascript wrapper to force_click the element """ js_executor.execute_template('clickElementTemplate', {}, self.element) return True if force_click: self.execute_and_handle_webelement_exceptions(force_click_element, 'click element by javascript') else: self.execute_and_handle_webelement_exceptions(click_element, 'click') return self
<SYSTEM_TASK:> Gets the value of a select or input element <END_TASK> <USER_TASK:> Description: def get_value(self): """Gets the value of a select or input element @rtype: str @return: The value of the element @raise: ValueError if element is not of type input or select, or has multiple selected options """
def get_element_value(): if self.tag_name() == 'input': return self.get_attribute('value') elif self.tag_name() == 'select': selected_options = self.element.all_selected_options if len(selected_options) > 1: raise ValueError( 'Select {} has multiple selected options, only one selected ' 'option is valid for this method'.format(self) ) return selected_options[0].get_attribute('value') else: raise ValueError('Can not get the value of elements or type "{}"'.format(self.tag_name())) return self.execute_and_handle_webelement_exceptions(get_element_value, name_of_action='get value')
<SYSTEM_TASK:> Retrieves specified attribute from WebElement <END_TASK> <USER_TASK:> Description: def get_attribute(self, name): """ Retrieves specified attribute from WebElement @type name: str @param name: Attribute to retrieve @rtype: str @return: String representation of the attribute """
def get_attribute_element(): """ Wrapper to retrieve element """ return self.element.get_attribute(name) return self.execute_and_handle_webelement_exceptions(get_attribute_element, 'get attribute "' + str(name) + '"')
<SYSTEM_TASK:> Test if an element has a specific classname <END_TASK> <USER_TASK:> Description: def has_class(self, classname): """Test if an element has a specific classname @type classname: str @param classname: Classname to test for; cannot contain spaces @rtype: bool @return: True if classname exists; false otherwise """
def element_has_class(): """Wrapper to test if element has a class""" pattern = re.compile('(\s|^){classname}(\s|$)'.format(classname=classname)) classes = self.element.get_attribute('class') matches = re.search(pattern, classes) if matches is not None: return True return False return self.execute_and_handle_webelement_exceptions( element_has_class, 'check for element class "{}"'.format(classname) )
<SYSTEM_TASK:> Get the text of the element <END_TASK> <USER_TASK:> Description: def text(self, force_get=False): """ Get the text of the element @rtype: str @return: Text of the element """
def text_element(): """ Wrapper to get text of element """ return self.element.text def force_text_element(): """Get text by javascript""" return self.driver_wrapper.js_executor.execute_template_and_return_result( 'getElementText.js', {}, self.element ) if force_get: return self.execute_and_handle_webelement_exceptions(force_text_element, 'get text by javascript') else: return self.execute_and_handle_webelement_exceptions(text_element, 'get text')
<SYSTEM_TASK:> Draws a dotted red box around the wrapped element using javascript <END_TASK> <USER_TASK:> Description: def highlight(self): """ Draws a dotted red box around the wrapped element using javascript @rtype: WebElementWrapper @return: Self """
js_executor = self.driver_wrapper.js_executor def highlight_element(): """ Wrapper to highlight elements """ location = self.element.location size = self.element.size js_executor.execute_template('elementHighlighterTemplate', { 'x': str(location['x']), 'y': str(location['y']), 'width': str(size['width']), 'height': str(size['height'])}) return True self.execute_and_handle_webelement_exceptions(highlight_element, 'highlight') return self
<SYSTEM_TASK:> Sets the attribute of the element to a specified value <END_TASK> <USER_TASK:> Description: def set_attribute(self, name, value): """Sets the attribute of the element to a specified value @type name: str @param name: the name of the attribute @type value: str @param value: the attribute of the value """
js_executor = self.driver_wrapper.js_executor def set_attribute_element(): """ Wrapper to set attribute """ js_executor.execute_template('setAttributeTemplate', { 'attribute_name': str(name), 'attribute_value': str(value)}, self.element) return True self.execute_and_handle_webelement_exceptions(set_attribute_element, 'set attribute "' + str(name) + '" to "' + str(value) + '"') return self
<SYSTEM_TASK:> Selects an option by value, text, or index. You must name the parameter <END_TASK> <USER_TASK:> Description: def select_option(self, value=None, text=None, index=None): """ Selects an option by value, text, or index. You must name the parameter @type value: str @param value: the value of the option @type text: str @param text: the option's visible text @type index: int @param index: the zero-based index of the option @rtype: WebElementWrapper @return: self """
def do_select(): """ Perform selection """ return self.set_select('select', value, text, index) return self.execute_and_handle_webelement_exceptions(do_select, 'select option')
<SYSTEM_TASK:> De-selects an option by value, text, or index. You must name the parameter <END_TASK> <USER_TASK:> Description: def deselect_option(self, value=None, text=None, index=None): """ De-selects an option by value, text, or index. You must name the parameter @type value: str @param value: the value of the option @type text: str @param text: the option's visible text @type index: int @param index: the zero-based index of the option @rtype: WebElementWrapper @return: self """
def do_deselect(): """ Perform selection """ return self.set_select('deselect', value, text, index) return self.execute_and_handle_webelement_exceptions(do_deselect, 'deselect option')
<SYSTEM_TASK:> Private method used by select methods <END_TASK> <USER_TASK:> Description: def set_select(self, select_or_deselect = 'select', value=None, text=None, index=None): """ Private method used by select methods @type select_or_deselect: str @param select_or_deselect: Should I select or deselect the element @type value: str @type value: Value to be selected @type text: str @type text: Text to be selected @type index: int @type index: index to be selected @rtype: WebElementWrapper @return: Self """
# TODO: raise exception if element is not select element if select_or_deselect is 'select': if value is not None: Select(self.element).select_by_value(value) elif text is not None: Select(self.element).select_by_visible_text(text) elif index is not None: Select(self.element).select_by_index(index) elif select_or_deselect is 'deselect': if value is not None: Select(self.element).deselect_by_value(value) elif text is not None: Select(self.element).deselect_by_visible_text(text) elif index is not None: Select(self.element).deselect_by_index(index) elif select_or_deselect is 'deselect all': Select(self.element).deselect_all() return self
<SYSTEM_TASK:> Hovers the element <END_TASK> <USER_TASK:> Description: def hover(self): """ Hovers the element """
def do_hover(): """ Perform hover """ ActionChains(self.driver_wrapper.driver).move_to_element(self.element).perform() return self.execute_and_handle_webelement_exceptions(do_hover, 'hover')
<SYSTEM_TASK:> Find wrapper, invokes webDriverWrapper find with the current element as the search object <END_TASK> <USER_TASK:> Description: def find(self, locator, find_all=False, search_object=None, exclude_invisible=None, *args, **kwargs): """ Find wrapper, invokes webDriverWrapper find with the current element as the search object @type locator: webdriverwrapper.support.locator.Locator @param locator: locator used in search @type find_all: bool @param find_all: should I find all elements, or just one? @type search_object: WebElementWrapper @param search_object: Used to override the starting point of the driver search @rtype: WebElementWrapper or list[WebElementWrapper] @return: Either a single WebElementWrapper, or a list of WebElementWrappers """
search_object = self.element if search_object is None else search_object return self.driver_wrapper.find( locator, find_all, search_object=search_object, exclude_invisible=exclude_invisible )
<SYSTEM_TASK:> Find wrapper to run a single find <END_TASK> <USER_TASK:> Description: def find_once(self, locator): """ Find wrapper to run a single find @type locator: webdriverwrapper.support.locator.Locator @param locator: locator used in search @type find_all: bool @param find_all: should I find all elements, or just one? @rtype: WebElementWrapper or list[WebElementWrapper] @return: Either a single WebElementWrapper, or a list of WebElementWrappers """
params = [] params.append(self.driver_wrapper.find_attempts) params.append(self.driver_wrapper.implicit_wait) self.driver_wrapper.find_attempts = 1 self.driver_wrapper.implicit_wait = 0 result = self.driver_wrapper._find_immediately(locator, self.element) # restore the original params self.driver_wrapper.implicit_wait = params.pop() self.driver_wrapper.find_attempts = params.pop() return result
<SYSTEM_TASK:> Find wrapper, finds all elements <END_TASK> <USER_TASK:> Description: def find_all(self, locator): """ Find wrapper, finds all elements @type locator: webdriverwrapper.support.locator.Locator @param locator: locator used in search @rtype: list @return: A list of WebElementWrappers """
return self.driver_wrapper.find(locator, True, self.element)
<SYSTEM_TASK:> Tests to see if an element is present <END_TASK> <USER_TASK:> Description: def is_present(self, locator): """ Tests to see if an element is present @type locator: webdriverwrapper.support.locator.Locator @param locator: locator used in search @rtype: bool @return: True if present, False if not present """
return self.driver_wrapper.is_present(locator, search_object=self.element)
<SYSTEM_TASK:> Waits for the element to go stale in the DOM <END_TASK> <USER_TASK:> Description: def wait_until_stale(self, timeout=None): """ Waits for the element to go stale in the DOM @type timeout: int @param timeout: override for default timeout @rtype: WebElementWrapper @return: Self """
timeout = timeout if timeout is not None else self.driver_wrapper.timeout def wait(): """ Wrapper to wait for element to be stale """ WebDriverWait(self.driver, timeout).until(EC.staleness_of(self.element)) return self return self.execute_and_handle_webelement_exceptions(wait, 'wait for staleness')
<SYSTEM_TASK:> Private method to be called by other methods to handle common WebDriverExceptions or throw <END_TASK> <USER_TASK:> Description: def execute_and_handle_webelement_exceptions(self, function_to_execute, name_of_action): """ Private method to be called by other methods to handle common WebDriverExceptions or throw a custom exception @type function_to_execute: types.FunctionType @param function_to_execute: A function containing some webdriver calls @type name_of_action: str @param name_of_action: The name of the action you are trying to perform for building the error message """
if self.element is not None: attempts = 0 while attempts < self.driver_wrapper.find_attempts+1: try: attempts = attempts + 1 val = function_to_execute() for cb in self.driver_wrapper.action_callbacks: cb.__call__(self.driver_wrapper) return val except StaleElementReferenceException: self.element = self.driver_wrapper.find(self.locator, search_object=self.search_object).element except ElementNotVisibleException: raise WebElementNotVisibleException.WebElementNotVisibleException(self, 'WebElement with locator: {} was not visible, so could not {}'.format( self.locator, name_of_action)) except MoveTargetOutOfBoundsException: raise WebElementNotVisibleException.WebElementNotVisibleException(self, 'WebElement with locator: {} was out of window, so could not {}'.format( self.locator, name_of_action)) except TimeoutException: raise WebDriverTimeoutException.WebDriverTimeoutException( self.driver_wrapper, timeout=self.driver_wrapper.timeout, locator=self.locator, msg='Timeout on action: {}'.format(name_of_action)) except UnexpectedAlertPresentException: msg = 'failed to parse message from alert' try: a = self.driver.switch_to_alert() msg = a.text finally: raise UnexpectedAlertPresentException('Unexpected alert on page: {}'.format(msg)) except BadStatusLine, e: logging.getLogger(__name__).error('{} error raised on action: {} (line: {}, args:{}, message: {})'.format( BadStatusLine.__class__.__name__, name_of_action, e.line, e.args, e.message )) raise raise StaleWebElementException.StaleWebElementException(self, 'Cannot {} element with locator: {}; the reference to the WebElement was stale ({} attempts)' .format(name_of_action, self.locator, self.driver_wrapper.find_attempts)) else: raise WebElementDoesNotExist.WebElementDoesNotExist(self, 'Cannot {} element with locator: {}; it does not exist'.format(name_of_action, self.locator))
<SYSTEM_TASK:> Makes a request using requests <END_TASK> <USER_TASK:> Description: def request(self, uri, method=GET, headers=None, cookies=None, params=None, data=None, post_files=None,**kwargs): """Makes a request using requests @param uri: The uri to send request @param method: Method to use to send request @param headers: Any headers to send with request @param cookies: Request cookies (in addition to session cookies) @param params: Request parameters @param data: Request data @param kwargs: other options to pass to underlying request @rtype: requests.Response @return: The response """
coyote_args = { 'headers': headers, 'cookies': cookies, 'params': params, 'files': post_files, 'data': data, 'verify': self.verify_certificates, } coyote_args.update(kwargs) if method == self.POST: response = self.session.post(uri, **coyote_args) elif method == self.PUT: response = self.session.put(uri, **coyote_args) elif method == self.PATCH: response = self.session.patch(uri, **coyote_args) elif method == self.DELETE: response = self.session.delete(uri, **coyote_args) else: # Default to GET response = self.session.get(uri, **coyote_args) self.responses.append(response) while len(self.responses) > self.max_response_history: self.responses.popleft() return response
<SYSTEM_TASK:> Validates that a list of urls can be opened and each responds with an allowed response code <END_TASK> <USER_TASK:> Description: def validate_urls(urls, allowed_response_codes=None): """Validates that a list of urls can be opened and each responds with an allowed response code urls -- the list of urls to ping allowed_response_codes -- a list of response codes that the validator will ignore """
for url in urls: validate_url(url, allowed_response_codes=allowed_response_codes) return True
<SYSTEM_TASK:> Instantiates a new WebDriver instance, determining class by environment variables <END_TASK> <USER_TASK:> Description: def new_driver(browser_name, *args, **kwargs): """Instantiates a new WebDriver instance, determining class by environment variables """
if browser_name == FIREFOX: return webdriver.Firefox(*args, **kwargs) # elif options['local'] and options['browser_name'] == CHROME: # return webdriver.Chrome(*args, **kwargs) # # elif options['local'] and options['browser_name'] == IE: # return webdriver.Ie(*args, **kwargs) # # elif options['local'] and options['browser_name'] == OPERA: # return webdriver.Opera(*args, **kwargs) elif browser_name == PHANTOMJS: executable_path = os.path.join(os.path.dirname(__file__), 'phantomjs/executable/phantomjs_64bit') driver = webdriver.PhantomJS(executable_path=executable_path, **kwargs) driver.set_window_size(1280, 800) # Set a default because phantom needs it return driver else: # remote driver = webdriver.Remote(*args, **kwargs) return driver
<SYSTEM_TASK:> Encodes all the string keys and values in a collection with specified encoding <END_TASK> <USER_TASK:> Description: def encode_collection(collection, encoding='utf-8'): """Encodes all the string keys and values in a collection with specified encoding"""
if isinstance(collection, dict): return dict((encode_collection(key), encode_collection(value)) for key, value in collection.iteritems()) elif isinstance(collection, list): return [encode_collection(element) for element in input] elif isinstance(collection, unicode): return collection.encode(encoding) else: return collection
<SYSTEM_TASK:> Given a list, returns a string representation of that list with specified delimiter and optional string chars <END_TASK> <USER_TASK:> Description: def get_delimited_string_from_list(_list, delimiter=', ', wrap_values_with_char=None, wrap_strings_with_char=None): """Given a list, returns a string representation of that list with specified delimiter and optional string chars _list -- the list or tuple to stringify delimiter -- the the character to seperate all values wrap_values_with_char -- if specified, will wrap all values in list with this character in the representation wrap_strings_with_char -- if specified, will wrap only values of type str with this character in the representation """
if wrap_values_with_char is not None: return delimiter.join('{wrapper}{val}{wrapper}'.format( val=v, wrapper=wrap_values_with_char ) for v in _list) elif wrap_strings_with_char is not None: return delimiter.join(str(v) if not isinstance(v, str) else '{wrapper}{val}{wrapper}'.format( val=v, wrapper=wrap_strings_with_char ) for v in _list) else: return delimiter.join(str(v) for v in _list)
<SYSTEM_TASK:> Execute script passed in to function <END_TASK> <USER_TASK:> Description: def execute_script(self, string, args=None): """ Execute script passed in to function @type string: str @value string: Script to execute @type args: dict @value args: Dictionary representing command line args @rtype: int @rtype: response code """
result = None try: result = self.driver_wrapper.driver.execute_script(string, args) return result except WebDriverException: if result is not None: message = 'Returned: ' + str(result) else: message = "No message. Check your Javascript source: {}".format(string) raise WebDriverJavascriptException.WebDriverJavascriptException(self.driver_wrapper, message)
<SYSTEM_TASK:> Execute script from a template <END_TASK> <USER_TASK:> Description: def execute_template(self, template_name, variables, args=None): """ Execute script from a template @type template_name: str @value template_name: Script template to implement @type args: dict @value args: Dictionary representing command line args @rtype: bool @rtype: Success or failure """
js_text = self.build_js_from_template(template_name, variables) try: self.execute_script(js_text, args) except WebDriverException: return False return True
<SYSTEM_TASK:> Execute script from a template and return result <END_TASK> <USER_TASK:> Description: def execute_template_and_return_result(self, template_name, variables, args=None): """ Execute script from a template and return result @type template_name: str @value template_name: Script template to implement @type variables: dict @value variables: Dictionary representing template construction args @type args: dict @value args: Dictionary representing command line args @rtype: int @rtype: exit code """
js_text = self.build_js_from_template(template_name, variables) return self.execute_script(js_text, args)
<SYSTEM_TASK:> Build a JS script from a template and args <END_TASK> <USER_TASK:> Description: def build_js_from_template(self, template_file, variables): """ Build a JS script from a template and args @type template_file: str @param template_file: Script template to implement; can be the name of a built-in script or full filepath to a js file that contains the script. E.g. 'clickElementTemplate.js', 'clickElementTemplate', and '/path/to/custom/template/script.js' are all acceptable @type variables: dict @param variables: Dictionary representing template construction args @rtype: int @rtype: exit code """
template_variable_character = '%' # raise an exception if user passed non-dictionary variables if not isinstance(variables, dict): raise TypeError('You must use a dictionary to populate variables in a javascript template') # This filename is not a full file, attempt to locate the file in built-in templates if not os.path.isfile(template_file): # append the .js extension if not included if '.js' not in template_file: template_file += '.js' # find the template and read the text into a string variable templates_dir = os.path.join(os.path.dirname(__file__), 'jsTemplates') template_full_path = os.path.join(templates_dir, template_file) # The filename specified should be the full path else: template_full_path = template_file # Ensure that the file exists if not os.path.isfile(template_full_path): raise ValueError('File "{}" was not found; you must specify the name of a built-in javascript template ' 'or the full filepath of a custom template'.format(template_full_path)) try: js_text = open(template_full_path).read() except IOError: raise IOError('The template was not found or did not have read permissions: {}'.format(template_full_path)) # replace all variables that match the keys in 'variables' dict for key in variables.keys(): # double escape single and double quotes after variable replacement if hasattr(variables[key], 'replace'): variables[key] = variables[key].replace("'", "\\'") variables[key] = variables[key].replace('"', '\\"') else: # variable is not a string variables[key] = str(variables[key]) js_text = js_text.replace(template_variable_character + key, variables[key]) return js_text
<SYSTEM_TASK:> Formats the locator with specified parameters <END_TASK> <USER_TASK:> Description: def build(self, **variables): """Formats the locator with specified parameters"""
return Locator(self.by, self.locator.format(**variables), self.description)
<SYSTEM_TASK:> Adds all cookies in the RequestDriver session to Webdriver <END_TASK> <USER_TASK:> Description: def dump_requestdriver_cookies_into_webdriver(requestdriver, webdriverwrapper, handle_sub_domain=True): """Adds all cookies in the RequestDriver session to Webdriver @type requestdriver: RequestDriver @param requestdriver: RequestDriver with cookies @type webdriverwrapper: WebDriverWrapper @param webdriverwrapper: WebDriverWrapper to receive cookies @param handle_sub_domain: If True, will check driver url and change cookies with subdomains of that domain to match the current driver domain in order to avoid cross-domain cookie errors @rtype: None @return: None """
driver_hostname = urlparse(webdriverwrapper.current_url()).netloc for cookie in requestdriver.session.cookies: # Check if there will be a cross-domain violation and handle if necessary cookiedomain = cookie.domain if handle_sub_domain: if is_subdomain(cookiedomain, driver_hostname): # Cookies of requestdriver are subdomain cookies of webdriver; make them the base domain cookiedomain = driver_hostname try: webdriverwrapper.add_cookie({ 'name': cookie.name, 'value': cookie.value, 'domain': cookiedomain, 'path': cookie.path }) except WebDriverException, e: raise WebDriverException( msg='Cannot set cookie "{name}" with domain "{domain}" on url "{url}" {override}: {message}'.format( name=cookie.name, domain=cookiedomain, url=webdriverwrapper.current_url(), override='(Note that subdomain override is set!)' if handle_sub_domain else '', message=e.message), screen=e.screen, stacktrace=e.stacktrace )
<SYSTEM_TASK:> Adds all cookies in the Webdriver session to requestdriver <END_TASK> <USER_TASK:> Description: def dump_webdriver_cookies_into_requestdriver(requestdriver, webdriverwrapper): """Adds all cookies in the Webdriver session to requestdriver @type requestdriver: RequestDriver @param requestdriver: RequestDriver with cookies @type webdriver: WebDriverWrapper @param webdriver: WebDriverWrapper to receive cookies @rtype: None @return: None """
for cookie in webdriverwrapper.get_cookies(): # Wedbriver uses "expiry"; requests uses "expires", adjust for this expires = cookie.pop('expiry', {'expiry': None}) cookie.update({'expires': expires}) requestdriver.session.cookies.set(**cookie)
<SYSTEM_TASK:> Raises an assertion error if the page has severe console errors <END_TASK> <USER_TASK:> Description: def _log_fail_callback(driver, *args, **kwargs): """Raises an assertion error if the page has severe console errors @param driver: ShapewaysDriver @return: None """
try: logs = driver.get_browser_log(levels=[BROWSER_LOG_LEVEL_SEVERE]) failure_message = 'There were severe console errors on this page: {}'.format(logs) failure_message = failure_message.replace('{', '{{').replace('}', '}}') # Escape braces for error message driver.assertion.assert_false( logs, failure_message=failure_message ) except (urllib2.URLError, socket.error, WebDriverException): # The session has ended, don't check the logs pass
<SYSTEM_TASK:> Clones the object and updates the clone with the args <END_TASK> <USER_TASK:> Description: def clone_and_update(self, **kwargs): """Clones the object and updates the clone with the args @param kwargs: Keyword arguments to set @return: The cloned copy with updated values """
cloned = self.clone() cloned.update(**kwargs) return cloned
<SYSTEM_TASK:> Render the body of the message to a string. <END_TASK> <USER_TASK:> Description: def message(self): """ Render the body of the message to a string. """
template_name = self.template_name() if \ callable(self.template_name) \ else self.template_name return loader.render_to_string( template_name, self.get_context(), request=self.request )
<SYSTEM_TASK:> Render the subject of the message to a string. <END_TASK> <USER_TASK:> Description: def subject(self): """ Render the subject of the message to a string. """
template_name = self.subject_template_name() if \ callable(self.subject_template_name) \ else self.subject_template_name subject = loader.render_to_string( template_name, self.get_context(), request=self.request ) return ''.join(subject.splitlines())
<SYSTEM_TASK:> Return the context used to render the templates for the email <END_TASK> <USER_TASK:> Description: def get_context(self): """ Return the context used to render the templates for the email subject and body. By default, this context includes: * All of the validated values in the form, as variables of the same names as their fields. * The current ``Site`` object, as the variable ``site``. * Any additional variables added by context processors (this will be a ``RequestContext``). """
if not self.is_valid(): raise ValueError( "Cannot generate Context from invalid contact form" ) return dict(self.cleaned_data, site=get_current_site(self.request))
<SYSTEM_TASK:> Initialise the Shopify session with the Shopify App's API credentials. <END_TASK> <USER_TASK:> Description: def initialise_shopify_session(): """ Initialise the Shopify session with the Shopify App's API credentials. """
if not settings.SHOPIFY_APP_API_KEY or not settings.SHOPIFY_APP_API_SECRET: raise ImproperlyConfigured("SHOPIFY_APP_API_KEY and SHOPIFY_APP_API_SECRET must be set in settings") shopify.Session.setup(api_key=settings.SHOPIFY_APP_API_KEY, secret=settings.SHOPIFY_APP_API_SECRET)
<SYSTEM_TASK:> Creates and saves a ShopUser with the given domain and password. <END_TASK> <USER_TASK:> Description: def create_user(self, myshopify_domain, password=None): """ Creates and saves a ShopUser with the given domain and password. """
if not myshopify_domain: raise ValueError('ShopUsers must have a myshopify domain') user = self.model(myshopify_domain=myshopify_domain) # Never want to be able to log on externally. # Authentication will be taken care of by Shopify OAuth. user.set_unusable_password() user.save(using=self._db) return user
<SYSTEM_TASK:> Merge a dictionary of query parameters into the given URL. <END_TASK> <USER_TASK:> Description: def add_query_parameters_to_url(url, query_parameters): """ Merge a dictionary of query parameters into the given URL. Ensures all parameters are sorted in dictionary order when returning the URL. """
# Parse the given URL into parts. url_parts = urllib.parse.urlparse(url) # Parse existing parameters and add new parameters. qs_args = urllib.parse.parse_qs(url_parts[4]) qs_args.update(query_parameters) # Sort parameters to ensure consistent order. sorted_qs_args = OrderedDict() for k in sorted(qs_args.keys()): sorted_qs_args[k] = qs_args[k] # Encode the new parameters and return the updated URL. new_qs = urllib.parse.urlencode(sorted_qs_args, True) return urllib.parse.urlunparse(list(url_parts[0:4]) + [new_qs] + list(url_parts[5:]))
<SYSTEM_TASK:> Send an event to the Pusher server. <END_TASK> <USER_TASK:> Description: def send_event(self, event_name, data, channel_name=None): """Send an event to the Pusher server. :param str event_name: :param Any data: :param str channel_name: """
event = {'event': event_name, 'data': data} if channel_name: event['channel'] = channel_name self.logger.info("Connection: Sending event - %s" % event) try: self.socket.send(json.dumps(event)) except Exception as e: self.logger.error("Failed send event: %s" % e)
<SYSTEM_TASK:> Trigger an event on this channel. Only available for private or <END_TASK> <USER_TASK:> Description: def trigger(self, event_name, data): """Trigger an event on this channel. Only available for private or presence channels :param event_name: The name of the event. Must begin with 'client-'' :type event_name: str :param data: The data to send with the event. """
if self.connection: if event_name.startswith("client-"): if self.name.startswith("private-") or self.name.startswith("presence-"): self.connection.send_event(event_name, data, channel_name=self.name)
<SYSTEM_TASK:> Subscribe to a channel. <END_TASK> <USER_TASK:> Description: def subscribe(self, channel_name, auth=None): """Subscribe to a channel. :param str channel_name: The name of the channel to subscribe to. :param str auth: The token to use if authenticated externally. :rtype: pysher.Channel """
data = {'channel': channel_name} if auth is None: if channel_name.startswith('presence-'): data['auth'] = self._generate_presence_token(channel_name) data['channel_data'] = json.dumps(self.user_data) elif channel_name.startswith('private-'): data['auth'] = self._generate_auth_token(channel_name) else: data['auth'] = auth self.connection.send_event('pusher:subscribe', data) self.channels[channel_name] = Channel(channel_name, self.connection) return self.channels[channel_name]
<SYSTEM_TASK:> Unsubscribe from a channel <END_TASK> <USER_TASK:> Description: def unsubscribe(self, channel_name): """Unsubscribe from a channel :param str channel_name: The name of the channel to unsubscribe from. """
if channel_name in self.channels: self.connection.send_event( 'pusher:unsubscribe', { 'channel': channel_name, } ) del self.channels[channel_name]
<SYSTEM_TASK:> Handle incoming data. <END_TASK> <USER_TASK:> Description: def _connection_handler(self, event_name, data, channel_name): """Handle incoming data. :param str event_name: Name of the event. :param Any data: Data received. :param str channel_name: Name of the channel this event and data belongs to. """
if channel_name in self.channels: self.channels[channel_name]._handle_event(event_name, data)
<SYSTEM_TASK:> Handle a reconnect. <END_TASK> <USER_TASK:> Description: def _reconnect_handler(self): """Handle a reconnect."""
for channel_name, channel in self.channels.items(): data = {'channel': channel_name} if channel.auth: data['auth'] = channel.auth self.connection.send_event('pusher:subscribe', data)
<SYSTEM_TASK:> Generate a token for authentication with the given channel. <END_TASK> <USER_TASK:> Description: def _generate_auth_token(self, channel_name): """Generate a token for authentication with the given channel. :param str channel_name: Name of the channel to generate a signature for. :rtype: str """
subject = "{}:{}".format(self.connection.socket_id, channel_name) h = hmac.new(self.secret_as_bytes, subject.encode('utf-8'), hashlib.sha256) auth_key = "{}:{}".format(self.key, h.hexdigest()) return auth_key
<SYSTEM_TASK:> Generate a presence token. <END_TASK> <USER_TASK:> Description: def _generate_presence_token(self, channel_name): """Generate a presence token. :param str channel_name: Name of the channel to generate a signature for. :rtype: str """
subject = "{}:{}:{}".format(self.connection.socket_id, channel_name, json.dumps(self.user_data)) h = hmac.new(self.secret_as_bytes, subject.encode('utf-8'), hashlib.sha256) auth_key = "{}:{}".format(self.key, h.hexdigest()) return auth_key
<SYSTEM_TASK:> Adds a new host to the cluster. This is only really useful for <END_TASK> <USER_TASK:> Description: def add_host(self, host_id=None, host='localhost', port=6379, unix_socket_path=None, db=0, password=None, ssl=False, ssl_options=None): """Adds a new host to the cluster. This is only really useful for unittests as normally hosts are added through the constructor and changes after the cluster has been used for the first time are unlikely to make sense. """
if host_id is None: raise RuntimeError('Host ID is required') elif not isinstance(host_id, (int, long)): raise ValueError('The host ID has to be an integer') host_id = int(host_id) with self._lock: if host_id in self.hosts: raise TypeError('Two hosts share the same host id (%r)' % (host_id,)) self.hosts[host_id] = HostInfo(host_id=host_id, host=host, port=port, db=db, unix_socket_path=unix_socket_path, password=password, ssl=ssl, ssl_options=ssl_options) self._hosts_age += 1
<SYSTEM_TASK:> Removes a host from the client. This only really useful for <END_TASK> <USER_TASK:> Description: def remove_host(self, host_id): """Removes a host from the client. This only really useful for unittests. """
with self._lock: rv = self._hosts.pop(host_id, None) is not None pool = self._pools.pop(host_id, None) if pool is not None: pool.disconnect() self._hosts_age += 1 return rv
<SYSTEM_TASK:> Disconnects all connections from the internal pools. <END_TASK> <USER_TASK:> Description: def disconnect_pools(self): """Disconnects all connections from the internal pools."""
with self._lock: for pool in self._pools.itervalues(): pool.disconnect() self._pools.clear()
<SYSTEM_TASK:> Returns the router for the cluster. If the cluster reconfigures <END_TASK> <USER_TASK:> Description: def get_router(self): """Returns the router for the cluster. If the cluster reconfigures the router will be recreated. Usually you do not need to interface with the router yourself as the cluster's routing client does that automatically. This returns an instance of :class:`BaseRouter`. """
cached_router = self._router ref_age = self._hosts_age if cached_router is not None: router, router_age = cached_router if router_age == ref_age: return router with self._lock: router = self.router_cls(self, **(self.router_options or {})) self._router = (router, ref_age) return router
<SYSTEM_TASK:> Returns the connection pool for the given host. <END_TASK> <USER_TASK:> Description: def get_pool_for_host(self, host_id): """Returns the connection pool for the given host. This connection pool is used by the redis clients to make sure that it does not have to reconnect constantly. If you want to use a custom redis client you can pass this in as connection pool manually. """
if isinstance(host_id, HostInfo): host_info = host_id host_id = host_info.host_id else: host_info = self.hosts.get(host_id) if host_info is None: raise LookupError('Host %r does not exist' % (host_id,)) rv = self._pools.get(host_id) if rv is not None: return rv with self._lock: rv = self._pools.get(host_id) if rv is None: opts = dict(self.pool_options or ()) opts['db'] = host_info.db opts['password'] = host_info.password if host_info.unix_socket_path is not None: opts['path'] = host_info.unix_socket_path opts['connection_class'] = UnixDomainSocketConnection if host_info.ssl: raise TypeError('SSL is not supported for unix ' 'domain sockets.') else: opts['host'] = host_info.host opts['port'] = host_info.port if host_info.ssl: if SSLConnection is None: raise TypeError('This version of py-redis does ' 'not support SSL connections.') opts['connection_class'] = SSLConnection opts.update(('ssl_' + k, v) for k, v in (host_info.ssl_options or {}).iteritems()) rv = self.pool_cls(**opts) self._pools[host_id] = rv return rv
<SYSTEM_TASK:> Shortcut context manager for getting a routing client, beginning <END_TASK> <USER_TASK:> Description: def map(self, timeout=None, max_concurrency=64, auto_batch=True): """Shortcut context manager for getting a routing client, beginning a map operation and joining over the result. `max_concurrency` defines how many outstanding parallel queries can exist before an implicit join takes place. In the context manager the client available is a :class:`MappingClient`. Example usage:: results = {} with cluster.map() as client: for key in keys_to_fetch: results[key] = client.get(key) for key, promise in results.iteritems(): print '%s => %s' % (key, promise.value) """
return self.get_routing_client(auto_batch).map( timeout=timeout, max_concurrency=max_concurrency)
<SYSTEM_TASK:> Shortcut context manager for getting a routing client, beginning <END_TASK> <USER_TASK:> Description: def fanout(self, hosts=None, timeout=None, max_concurrency=64, auto_batch=True): """Shortcut context manager for getting a routing client, beginning a fanout operation and joining over the result. In the context manager the client available is a :class:`FanoutClient`. Example usage:: with cluster.fanout(hosts='all') as client: client.flushdb() """
return self.get_routing_client(auto_batch).fanout( hosts=hosts, timeout=timeout, max_concurrency=max_concurrency)
<SYSTEM_TASK:> Given a pipeline of commands this attempts to merge the commands <END_TASK> <USER_TASK:> Description: def auto_batch_commands(commands): """Given a pipeline of commands this attempts to merge the commands into more efficient ones if that is possible. """
pending_batch = None for command_name, args, options, promise in commands: # This command cannot be batched, return it as such. if command_name not in AUTO_BATCH_COMMANDS: if pending_batch: yield merge_batch(*pending_batch) pending_batch = None yield command_name, args, options, promise continue assert not options, 'batch commands cannot merge options' if pending_batch and pending_batch[0] == command_name: pending_batch[1].append((args, promise)) else: if pending_batch: yield merge_batch(*pending_batch) pending_batch = (command_name, [(args, promise)]) if pending_batch: yield merge_batch(*pending_batch)
<SYSTEM_TASK:> Enqueue a new command into this pipeline. <END_TASK> <USER_TASK:> Description: def enqueue_command(self, command_name, args, options): """Enqueue a new command into this pipeline."""
assert_open(self) promise = Promise() self.commands.append((command_name, args, options, promise)) return promise
<SYSTEM_TASK:> Utility function that sends the buffer into the provided socket. <END_TASK> <USER_TASK:> Description: def send_buffer(self): """Utility function that sends the buffer into the provided socket. The buffer itself will slowly clear out and is modified in place. """
buf = self._send_buf sock = self.connection._sock try: timeout = sock.gettimeout() sock.setblocking(False) try: for idx, item in enumerate(buf): sent = 0 while 1: try: sent = sock.send(item) except IOError as e: if e.errno == errno.EAGAIN: continue elif e.errno == errno.EWOULDBLOCK: break raise self.sent_something = True break if sent < len(item): buf[:idx + 1] = [item[sent:]] break else: del buf[:] finally: sock.settimeout(timeout) except IOError as e: self.connection.disconnect() if isinstance(e, socket.timeout): raise TimeoutError('Timeout writing to socket (host %s)' % self.host_id) raise ConnectionError('Error while writing to socket (host %s): %s' % (self.host_id, e))