repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.get_single_instance
def get_single_instance(sql, class_type, *args, **kwargs): """Returns an instance of class_type populated with attributes from the DB record; throws an error if no records are found @param sql: Sql statement to execute @param class_type: The type of class to instantiate and populate with DB record @return: Return an instance with attributes set to values from DB """ record = CoyoteDb.get_single_record(sql, *args, **kwargs) try: instance = CoyoteDb.get_object_from_dictionary_representation(dictionary=record, class_type=class_type) except AttributeError: raise NoRecordsFoundException('No records found for {class_type} with sql run on {host}: \n {sql}'.format( sql=sql, host=DatabaseConfig().get('mysql_host'), class_type=class_type )) return instance
python
def get_single_instance(sql, class_type, *args, **kwargs): """Returns an instance of class_type populated with attributes from the DB record; throws an error if no records are found @param sql: Sql statement to execute @param class_type: The type of class to instantiate and populate with DB record @return: Return an instance with attributes set to values from DB """ record = CoyoteDb.get_single_record(sql, *args, **kwargs) try: instance = CoyoteDb.get_object_from_dictionary_representation(dictionary=record, class_type=class_type) except AttributeError: raise NoRecordsFoundException('No records found for {class_type} with sql run on {host}: \n {sql}'.format( sql=sql, host=DatabaseConfig().get('mysql_host'), class_type=class_type )) return instance
[ "def", "get_single_instance", "(", "sql", ",", "class_type", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "record", "=", "CoyoteDb", ".", "get_single_record", "(", "sql", ",", "*", "args", ",", "*", "*", "kwargs", ")", "try", ":", "instance", "=", "CoyoteDb", ".", "get_object_from_dictionary_representation", "(", "dictionary", "=", "record", ",", "class_type", "=", "class_type", ")", "except", "AttributeError", ":", "raise", "NoRecordsFoundException", "(", "'No records found for {class_type} with sql run on {host}: \\n {sql}'", ".", "format", "(", "sql", "=", "sql", ",", "host", "=", "DatabaseConfig", "(", ")", ".", "get", "(", "'mysql_host'", ")", ",", "class_type", "=", "class_type", ")", ")", "return", "instance" ]
Returns an instance of class_type populated with attributes from the DB record; throws an error if no records are found @param sql: Sql statement to execute @param class_type: The type of class to instantiate and populate with DB record @return: Return an instance with attributes set to values from DB
[ "Returns", "an", "instance", "of", "class_type", "populated", "with", "attributes", "from", "the", "DB", "record", ";", "throws", "an", "error", "if", "no", "records", "are", "found" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L109-L126
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.get_all_instances
def get_all_instances(sql, class_type, *args, **kwargs): """Returns a list of instances of class_type populated with attributes from the DB record @param sql: Sql statement to execute @param class_type: The type of class to instantiate and populate with DB record @return: Return a list of instances with attributes set to values from DB """ records = CoyoteDb.get_all_records(sql, *args, **kwargs) instances = [CoyoteDb.get_object_from_dictionary_representation( dictionary=record, class_type=class_type) for record in records] for instance in instances: instance._query = sql return instances
python
def get_all_instances(sql, class_type, *args, **kwargs): """Returns a list of instances of class_type populated with attributes from the DB record @param sql: Sql statement to execute @param class_type: The type of class to instantiate and populate with DB record @return: Return a list of instances with attributes set to values from DB """ records = CoyoteDb.get_all_records(sql, *args, **kwargs) instances = [CoyoteDb.get_object_from_dictionary_representation( dictionary=record, class_type=class_type) for record in records] for instance in instances: instance._query = sql return instances
[ "def", "get_all_instances", "(", "sql", ",", "class_type", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "records", "=", "CoyoteDb", ".", "get_all_records", "(", "sql", ",", "*", "args", ",", "*", "*", "kwargs", ")", "instances", "=", "[", "CoyoteDb", ".", "get_object_from_dictionary_representation", "(", "dictionary", "=", "record", ",", "class_type", "=", "class_type", ")", "for", "record", "in", "records", "]", "for", "instance", "in", "instances", ":", "instance", ".", "_query", "=", "sql", "return", "instances" ]
Returns a list of instances of class_type populated with attributes from the DB record @param sql: Sql statement to execute @param class_type: The type of class to instantiate and populate with DB record @return: Return a list of instances with attributes set to values from DB
[ "Returns", "a", "list", "of", "instances", "of", "class_type", "populated", "with", "attributes", "from", "the", "DB", "record" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L129-L141
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.escape_dictionary
def escape_dictionary(dictionary, datetime_format='%Y-%m-%d %H:%M:%S'): """Escape dictionary values with keys as column names and values column values @type dictionary: dict @param dictionary: Key-values """ for k, v in dictionary.iteritems(): if isinstance(v, datetime.datetime): v = v.strftime(datetime_format) if isinstance(v, basestring): v = CoyoteDb.db_escape(str(v)) v = '"{}"'.format(v) if v is True: v = 1 if v is False: v = 0 if v is None: v = 'NULL' dictionary[k] = v
python
def escape_dictionary(dictionary, datetime_format='%Y-%m-%d %H:%M:%S'): """Escape dictionary values with keys as column names and values column values @type dictionary: dict @param dictionary: Key-values """ for k, v in dictionary.iteritems(): if isinstance(v, datetime.datetime): v = v.strftime(datetime_format) if isinstance(v, basestring): v = CoyoteDb.db_escape(str(v)) v = '"{}"'.format(v) if v is True: v = 1 if v is False: v = 0 if v is None: v = 'NULL' dictionary[k] = v
[ "def", "escape_dictionary", "(", "dictionary", ",", "datetime_format", "=", "'%Y-%m-%d %H:%M:%S'", ")", ":", "for", "k", ",", "v", "in", "dictionary", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "v", ",", "datetime", ".", "datetime", ")", ":", "v", "=", "v", ".", "strftime", "(", "datetime_format", ")", "if", "isinstance", "(", "v", ",", "basestring", ")", ":", "v", "=", "CoyoteDb", ".", "db_escape", "(", "str", "(", "v", ")", ")", "v", "=", "'\"{}\"'", ".", "format", "(", "v", ")", "if", "v", "is", "True", ":", "v", "=", "1", "if", "v", "is", "False", ":", "v", "=", "0", "if", "v", "is", "None", ":", "v", "=", "'NULL'", "dictionary", "[", "k", "]", "=", "v" ]
Escape dictionary values with keys as column names and values column values @type dictionary: dict @param dictionary: Key-values
[ "Escape", "dictionary", "values", "with", "keys", "as", "column", "names", "and", "values", "column", "values" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L144-L167
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.get_insert_fields_and_values_from_dict
def get_insert_fields_and_values_from_dict(dictionary, datetime_format='%Y-%m-%d %H:%M:%S', db_escape=True): """Formats a dictionary to strings of fields and values for insert statements @param dictionary: The dictionary whose keys and values are to be inserted @param db_escape: If true, will db escape values @return: Tuple of strings containing string fields and values, e.g. ('user_id, username', '5, "pandaman"') """ if db_escape: CoyoteDb.escape_dictionary(dictionary, datetime_format=datetime_format) fields = get_delimited_string_from_list(dictionary.keys(), delimiter=',') # keys have no quotes vals = get_delimited_string_from_list(dictionary.values(), delimiter=',') # strings get quotes return fields, vals
python
def get_insert_fields_and_values_from_dict(dictionary, datetime_format='%Y-%m-%d %H:%M:%S', db_escape=True): """Formats a dictionary to strings of fields and values for insert statements @param dictionary: The dictionary whose keys and values are to be inserted @param db_escape: If true, will db escape values @return: Tuple of strings containing string fields and values, e.g. ('user_id, username', '5, "pandaman"') """ if db_escape: CoyoteDb.escape_dictionary(dictionary, datetime_format=datetime_format) fields = get_delimited_string_from_list(dictionary.keys(), delimiter=',') # keys have no quotes vals = get_delimited_string_from_list(dictionary.values(), delimiter=',') # strings get quotes return fields, vals
[ "def", "get_insert_fields_and_values_from_dict", "(", "dictionary", ",", "datetime_format", "=", "'%Y-%m-%d %H:%M:%S'", ",", "db_escape", "=", "True", ")", ":", "if", "db_escape", ":", "CoyoteDb", ".", "escape_dictionary", "(", "dictionary", ",", "datetime_format", "=", "datetime_format", ")", "fields", "=", "get_delimited_string_from_list", "(", "dictionary", ".", "keys", "(", ")", ",", "delimiter", "=", "','", ")", "# keys have no quotes", "vals", "=", "get_delimited_string_from_list", "(", "dictionary", ".", "values", "(", ")", ",", "delimiter", "=", "','", ")", "# strings get quotes", "return", "fields", ",", "vals" ]
Formats a dictionary to strings of fields and values for insert statements @param dictionary: The dictionary whose keys and values are to be inserted @param db_escape: If true, will db escape values @return: Tuple of strings containing string fields and values, e.g. ('user_id, username', '5, "pandaman"')
[ "Formats", "a", "dictionary", "to", "strings", "of", "fields", "and", "values", "for", "insert", "statements" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L170-L183
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.get_kwargs
def get_kwargs(**kwargs): """This method should be used in query functions where user can query on any number of fields >>> def get_instances(entity_id=NOTSET, my_field=NOTSET): >>> kwargs = CoyoteDb.get_kwargs(entity_id=entity_id, my_field=my_field) """ d = dict() for k, v in kwargs.iteritems(): if v is not NOTSET: d[k] = v return d
python
def get_kwargs(**kwargs): """This method should be used in query functions where user can query on any number of fields >>> def get_instances(entity_id=NOTSET, my_field=NOTSET): >>> kwargs = CoyoteDb.get_kwargs(entity_id=entity_id, my_field=my_field) """ d = dict() for k, v in kwargs.iteritems(): if v is not NOTSET: d[k] = v return d
[ "def", "get_kwargs", "(", "*", "*", "kwargs", ")", ":", "d", "=", "dict", "(", ")", "for", "k", ",", "v", "in", "kwargs", ".", "iteritems", "(", ")", ":", "if", "v", "is", "not", "NOTSET", ":", "d", "[", "k", "]", "=", "v", "return", "d" ]
This method should be used in query functions where user can query on any number of fields >>> def get_instances(entity_id=NOTSET, my_field=NOTSET): >>> kwargs = CoyoteDb.get_kwargs(entity_id=entity_id, my_field=my_field)
[ "This", "method", "should", "be", "used", "in", "query", "functions", "where", "user", "can", "query", "on", "any", "number", "of", "fields" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L186-L196
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.get_update_clause_from_dict
def get_update_clause_from_dict(dictionary, datetime_format='%Y-%m-%d %H:%M:%S'): """Builds the update values clause of an update statement based on the dictionary representation of an instance""" items = [] CoyoteDb.escape_dictionary(dictionary, datetime_format=datetime_format) for k,v in dictionary.iteritems(): item = '{k} = {v}'.format(k=k, v=v) items.append(item) clause = ', '.join(item for item in items) return clause
python
def get_update_clause_from_dict(dictionary, datetime_format='%Y-%m-%d %H:%M:%S'): """Builds the update values clause of an update statement based on the dictionary representation of an instance""" items = [] CoyoteDb.escape_dictionary(dictionary, datetime_format=datetime_format) for k,v in dictionary.iteritems(): item = '{k} = {v}'.format(k=k, v=v) items.append(item) clause = ', '.join(item for item in items) return clause
[ "def", "get_update_clause_from_dict", "(", "dictionary", ",", "datetime_format", "=", "'%Y-%m-%d %H:%M:%S'", ")", ":", "items", "=", "[", "]", "CoyoteDb", ".", "escape_dictionary", "(", "dictionary", ",", "datetime_format", "=", "datetime_format", ")", "for", "k", ",", "v", "in", "dictionary", ".", "iteritems", "(", ")", ":", "item", "=", "'{k} = {v}'", ".", "format", "(", "k", "=", "k", ",", "v", "=", "v", ")", "items", ".", "append", "(", "item", ")", "clause", "=", "', '", ".", "join", "(", "item", "for", "item", "in", "items", ")", "return", "clause" ]
Builds the update values clause of an update statement based on the dictionary representation of an instance
[ "Builds", "the", "update", "values", "clause", "of", "an", "update", "statement", "based", "on", "the", "dictionary", "representation", "of", "an", "instance" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L199-L209
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.get_where_clause_from_dict
def get_where_clause_from_dict(dictionary, join_operator='AND'): """Builds a where clause from a dictionary """ CoyoteDb.escape_dictionary(dictionary) clause = join_operator.join( (' {k} is {v} ' if str(v).lower() == 'null' else ' {k} = {v} ').format(k=k, v=v) # IS should be the operator for null values for k, v in dictionary.iteritems()) return clause
python
def get_where_clause_from_dict(dictionary, join_operator='AND'): """Builds a where clause from a dictionary """ CoyoteDb.escape_dictionary(dictionary) clause = join_operator.join( (' {k} is {v} ' if str(v).lower() == 'null' else ' {k} = {v} ').format(k=k, v=v) # IS should be the operator for null values for k, v in dictionary.iteritems()) return clause
[ "def", "get_where_clause_from_dict", "(", "dictionary", ",", "join_operator", "=", "'AND'", ")", ":", "CoyoteDb", ".", "escape_dictionary", "(", "dictionary", ")", "clause", "=", "join_operator", ".", "join", "(", "(", "' {k} is {v} '", "if", "str", "(", "v", ")", ".", "lower", "(", ")", "==", "'null'", "else", "' {k} = {v} '", ")", ".", "format", "(", "k", "=", "k", ",", "v", "=", "v", ")", "# IS should be the operator for null values", "for", "k", ",", "v", "in", "dictionary", ".", "iteritems", "(", ")", ")", "return", "clause" ]
Builds a where clause from a dictionary
[ "Builds", "a", "where", "clause", "from", "a", "dictionary" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L212-L219
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.get_dictionary_representation_of_object_attributes
def get_dictionary_representation_of_object_attributes(obj, omit_null_fields=False): """Returns a dictionary of object's attributes, ignoring methods @param obj: The object to represent as dict @param omit_null_fields: If true, will not include fields in the dictionary that are null @return: Dictionary of the object's attributes """ obj_dictionary = obj.__dict__ obj_dictionary_temp = obj_dictionary.copy() for k, v in obj_dictionary.iteritems(): if omit_null_fields: if v is None: obj_dictionary_temp.pop(k, None) if k.startswith('_'): obj_dictionary_temp.pop(k, None) return obj_dictionary_temp
python
def get_dictionary_representation_of_object_attributes(obj, omit_null_fields=False): """Returns a dictionary of object's attributes, ignoring methods @param obj: The object to represent as dict @param omit_null_fields: If true, will not include fields in the dictionary that are null @return: Dictionary of the object's attributes """ obj_dictionary = obj.__dict__ obj_dictionary_temp = obj_dictionary.copy() for k, v in obj_dictionary.iteritems(): if omit_null_fields: if v is None: obj_dictionary_temp.pop(k, None) if k.startswith('_'): obj_dictionary_temp.pop(k, None) return obj_dictionary_temp
[ "def", "get_dictionary_representation_of_object_attributes", "(", "obj", ",", "omit_null_fields", "=", "False", ")", ":", "obj_dictionary", "=", "obj", ".", "__dict__", "obj_dictionary_temp", "=", "obj_dictionary", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "obj_dictionary", ".", "iteritems", "(", ")", ":", "if", "omit_null_fields", ":", "if", "v", "is", "None", ":", "obj_dictionary_temp", ".", "pop", "(", "k", ",", "None", ")", "if", "k", ".", "startswith", "(", "'_'", ")", ":", "obj_dictionary_temp", ".", "pop", "(", "k", ",", "None", ")", "return", "obj_dictionary_temp" ]
Returns a dictionary of object's attributes, ignoring methods @param obj: The object to represent as dict @param omit_null_fields: If true, will not include fields in the dictionary that are null @return: Dictionary of the object's attributes
[ "Returns", "a", "dictionary", "of", "object", "s", "attributes", "ignoring", "methods" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L222-L239
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.get_object_from_dictionary_representation
def get_object_from_dictionary_representation(dictionary, class_type): """Instantiates a new class (that takes no init params) and populates its attributes with a dictionary @type dictionary: dict @param dictionary: Dictionary representation of the object @param class_type: type @return: None """ assert inspect.isclass(class_type), 'Cannot instantiate an object that is not a class' instance = class_type() CoyoteDb.update_object_from_dictionary_representation(dictionary, instance) return instance
python
def get_object_from_dictionary_representation(dictionary, class_type): """Instantiates a new class (that takes no init params) and populates its attributes with a dictionary @type dictionary: dict @param dictionary: Dictionary representation of the object @param class_type: type @return: None """ assert inspect.isclass(class_type), 'Cannot instantiate an object that is not a class' instance = class_type() CoyoteDb.update_object_from_dictionary_representation(dictionary, instance) return instance
[ "def", "get_object_from_dictionary_representation", "(", "dictionary", ",", "class_type", ")", ":", "assert", "inspect", ".", "isclass", "(", "class_type", ")", ",", "'Cannot instantiate an object that is not a class'", "instance", "=", "class_type", "(", ")", "CoyoteDb", ".", "update_object_from_dictionary_representation", "(", "dictionary", ",", "instance", ")", "return", "instance" ]
Instantiates a new class (that takes no init params) and populates its attributes with a dictionary @type dictionary: dict @param dictionary: Dictionary representation of the object @param class_type: type @return: None
[ "Instantiates", "a", "new", "class", "(", "that", "takes", "no", "init", "params", ")", "and", "populates", "its", "attributes", "with", "a", "dictionary" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L242-L256
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.build_where_clause
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
python
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
[ "def", "build_where_clause", "(", "mappings", ",", "operator", "=", "'AND'", ")", ":", "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" ]
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" '
[ "Constructs", "the", "where", "clause", "based", "on", "a", "dictionary", "of", "values" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L259-L273
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.execute
def execute(*args, **kwargs): """Executes the sql statement, but does not commit. Returns the cursor to commit @return: DB and cursor instance following sql execution """ # Inspect the call stack for the originating call args = CoyoteDb.__add_query_comment(args[0]) db = CoyoteDb.__get_db_write_instance(target_database=kwargs.pop('target_database', None)) filtered_kwargs = {k: v for k, v in kwargs.iteritems() if k != 'target_database'} # Execute the query cursor = db.cursor() try: cursor.execute(*args, **filtered_kwargs) except OperationalError, e: raise OperationalError('{} when executing: {}'.format(e.args, args[0])) return db, cursor
python
def execute(*args, **kwargs): """Executes the sql statement, but does not commit. Returns the cursor to commit @return: DB and cursor instance following sql execution """ # Inspect the call stack for the originating call args = CoyoteDb.__add_query_comment(args[0]) db = CoyoteDb.__get_db_write_instance(target_database=kwargs.pop('target_database', None)) filtered_kwargs = {k: v for k, v in kwargs.iteritems() if k != 'target_database'} # Execute the query cursor = db.cursor() try: cursor.execute(*args, **filtered_kwargs) except OperationalError, e: raise OperationalError('{} when executing: {}'.format(e.args, args[0])) return db, cursor
[ "def", "execute", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Inspect the call stack for the originating call", "args", "=", "CoyoteDb", ".", "__add_query_comment", "(", "args", "[", "0", "]", ")", "db", "=", "CoyoteDb", ".", "__get_db_write_instance", "(", "target_database", "=", "kwargs", ".", "pop", "(", "'target_database'", ",", "None", ")", ")", "filtered_kwargs", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "kwargs", ".", "iteritems", "(", ")", "if", "k", "!=", "'target_database'", "}", "# Execute the query", "cursor", "=", "db", ".", "cursor", "(", ")", "try", ":", "cursor", ".", "execute", "(", "*", "args", ",", "*", "*", "filtered_kwargs", ")", "except", "OperationalError", ",", "e", ":", "raise", "OperationalError", "(", "'{} when executing: {}'", ".", "format", "(", "e", ".", "args", ",", "args", "[", "0", "]", ")", ")", "return", "db", ",", "cursor" ]
Executes the sql statement, but does not commit. Returns the cursor to commit @return: DB and cursor instance following sql execution
[ "Executes", "the", "sql", "statement", "but", "does", "not", "commit", ".", "Returns", "the", "cursor", "to", "commit" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L276-L293
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.execute_read_only
def execute_read_only(*args, **kwargs): # TODO: consolidate with execute """Executes the sql statement, but does not commit. Returns the cursor to commit @return: DB and cursor instance following sql execution """ # Inspect the call stack for the originating call args = CoyoteDb.__add_query_comment(args[0]) # Execute the query db = CoyoteDb.__get_db_read_instance() cursor = db.cursor() try: cursor.execute(*args, **kwargs) except OperationalError, e: raise OperationalError('{} when executing: {}'.format(e.args, args[0])) return db, cursor
python
def execute_read_only(*args, **kwargs): # TODO: consolidate with execute """Executes the sql statement, but does not commit. Returns the cursor to commit @return: DB and cursor instance following sql execution """ # Inspect the call stack for the originating call args = CoyoteDb.__add_query_comment(args[0]) # Execute the query db = CoyoteDb.__get_db_read_instance() cursor = db.cursor() try: cursor.execute(*args, **kwargs) except OperationalError, e: raise OperationalError('{} when executing: {}'.format(e.args, args[0])) return db, cursor
[ "def", "execute_read_only", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# TODO: consolidate with execute", "# Inspect the call stack for the originating call", "args", "=", "CoyoteDb", ".", "__add_query_comment", "(", "args", "[", "0", "]", ")", "# Execute the query", "db", "=", "CoyoteDb", ".", "__get_db_read_instance", "(", ")", "cursor", "=", "db", ".", "cursor", "(", ")", "try", ":", "cursor", ".", "execute", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "OperationalError", ",", "e", ":", "raise", "OperationalError", "(", "'{} when executing: {}'", ".", "format", "(", "e", ".", "args", ",", "args", "[", "0", "]", ")", ")", "return", "db", ",", "cursor" ]
Executes the sql statement, but does not commit. Returns the cursor to commit @return: DB and cursor instance following sql execution
[ "Executes", "the", "sql", "statement", "but", "does", "not", "commit", ".", "Returns", "the", "cursor", "to", "commit" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L296-L313
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.execute_and_commit
def execute_and_commit(*args, **kwargs): """Executes and commits the sql statement @return: None """ db, cursor = CoyoteDb.execute(*args, **kwargs) db.commit() return cursor
python
def execute_and_commit(*args, **kwargs): """Executes and commits the sql statement @return: None """ db, cursor = CoyoteDb.execute(*args, **kwargs) db.commit() return cursor
[ "def", "execute_and_commit", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "db", ",", "cursor", "=", "CoyoteDb", ".", "execute", "(", "*", "args", ",", "*", "*", "kwargs", ")", "db", ".", "commit", "(", ")", "return", "cursor" ]
Executes and commits the sql statement @return: None
[ "Executes", "and", "commits", "the", "sql", "statement" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L316-L323
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.insert_instance
def insert_instance(instance, table, **kwargs): """Inserts an object's values into a given table, will not populate Nonetype values @param instance: Instance of an object to insert @param table: Table in which to insert instance values @return: ID of the last inserted row """ instancedict = instance.__dict__.copy() instancedictclone = instancedict.copy() # Remove all Nonetype values for k, v in instancedictclone.iteritems(): if v is None: instancedict.pop(k) keys, values = CoyoteDb.get_insert_fields_and_values_from_dict(instancedict) sql = """INSERT INTO {table} ({keys}) VALUES ({values})""".format( table=table, keys=keys, values=values ) insert = CoyoteDb.insert(sql=sql, **kwargs) return insert
python
def insert_instance(instance, table, **kwargs): """Inserts an object's values into a given table, will not populate Nonetype values @param instance: Instance of an object to insert @param table: Table in which to insert instance values @return: ID of the last inserted row """ instancedict = instance.__dict__.copy() instancedictclone = instancedict.copy() # Remove all Nonetype values for k, v in instancedictclone.iteritems(): if v is None: instancedict.pop(k) keys, values = CoyoteDb.get_insert_fields_and_values_from_dict(instancedict) sql = """INSERT INTO {table} ({keys}) VALUES ({values})""".format( table=table, keys=keys, values=values ) insert = CoyoteDb.insert(sql=sql, **kwargs) return insert
[ "def", "insert_instance", "(", "instance", ",", "table", ",", "*", "*", "kwargs", ")", ":", "instancedict", "=", "instance", ".", "__dict__", ".", "copy", "(", ")", "instancedictclone", "=", "instancedict", ".", "copy", "(", ")", "# Remove all Nonetype values", "for", "k", ",", "v", "in", "instancedictclone", ".", "iteritems", "(", ")", ":", "if", "v", "is", "None", ":", "instancedict", ".", "pop", "(", "k", ")", "keys", ",", "values", "=", "CoyoteDb", ".", "get_insert_fields_and_values_from_dict", "(", "instancedict", ")", "sql", "=", "\"\"\"INSERT INTO {table} ({keys}) VALUES ({values})\"\"\"", ".", "format", "(", "table", "=", "table", ",", "keys", "=", "keys", ",", "values", "=", "values", ")", "insert", "=", "CoyoteDb", ".", "insert", "(", "sql", "=", "sql", ",", "*", "*", "kwargs", ")", "return", "insert" ]
Inserts an object's values into a given table, will not populate Nonetype values @param instance: Instance of an object to insert @param table: Table in which to insert instance values @return: ID of the last inserted row
[ "Inserts", "an", "object", "s", "values", "into", "a", "given", "table", "will", "not", "populate", "Nonetype", "values" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L343-L366
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.update
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
python
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
[ "def", "update", "(", "sql", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "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" ]
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
[ "Updates", "and", "commits", "with", "an", "insert", "sql", "statement", "returns", "the", "record", "but", "with", "a", "small", "chance", "of", "a", "race", "condition" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L369-L382
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.delete
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)
python
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)
[ "def", "delete", "(", "sql", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "\"delete\"", "in", "sql", ".", "lower", "(", ")", ",", "'This function requires a delete statement, provided: {}'", ".", "format", "(", "sql", ")", "CoyoteDb", ".", "execute_and_commit", "(", "sql", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Deletes and commits with an insert sql statement
[ "Deletes", "and", "commits", "with", "an", "insert", "sql", "statement" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L385-L388
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.update_object_from_dictionary_representation
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
python
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
[ "def", "update_object_from_dictionary_representation", "(", "dictionary", ",", "instance", ")", ":", "for", "key", ",", "value", "in", "dictionary", ".", "iteritems", "(", ")", ":", "if", "hasattr", "(", "instance", ",", "key", ")", ":", "setattr", "(", "instance", ",", "key", ",", "value", ")", "return", "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
[ "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" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L391-L404
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.format_time
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
python
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
[ "def", "format_time", "(", "time", ")", ":", "# 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" ]
Formats a time to be Shapeways database-compatible @param time: Datetime or string object to format @rtype: str @return: Time formatted as a string
[ "Formats", "a", "time", "to", "be", "Shapeways", "database", "-", "compatible" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L407-L421
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
CoyoteDb.format_date
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
python
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
[ "def", "format_date", "(", "date", ")", ":", "# 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" ]
Formats a date to be Shapeways database-compatible @param date: Datetime or string object to format @rtype: str @return: Date formatted as a string
[ "Formats", "a", "date", "to", "be", "Shapeways", "database", "-", "compatible" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L424-L438
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.visit
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))
python
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))
[ "def", "visit", "(", "self", ",", "url", "=", "''", ")", ":", "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", ")", ")" ]
Driver gets the provided url in the browser, returns True if successful url -- An absolute or relative url stored as a string
[ "Driver", "gets", "the", "provided", "url", "in", "the", "browser", "returns", "True", "if", "successful" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L201-L224
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.is_alert_present
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
python
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
[ "def", "is_alert_present", "(", "self", ")", ":", "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" ]
Tests if an alert is present @return: True if alert is present, False otherwise
[ "Tests", "if", "an", "alert", "is", "present" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L258-L277
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.find
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
python
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
[ "def", "find", "(", "self", ",", "locator", ",", "find_all", "=", "False", ",", "search_object", "=", "None", ",", "force_find", "=", "False", ",", "exclude_invisible", "=", "False", ")", ":", "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" ]
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
[ "Attempts", "to", "locate", "an", "element", "trying", "the", "number", "of", "times", "specified", "by", "the", "driver", "wrapper", ";", "Will", "throw", "a", "WebDriverWrapperException", "if", "no", "element", "is", "found" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L318-L387
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper._find_immediately
def _find_immediately(self, locator, search_object=None): ''' Attempts to immediately find elements on the page without waiting @type locator: webdriverwrapper.support.locator.Locator @param locator: Locator object describing @type search_object: webdriverwrapper.WebElementWrapper @param search_object: Optional WebElement to start search with. If null, search will be on self.driver @return: Single WebElemetnWrapper if find_all is False, list of WebElementWrappers if find_all is True ''' search_object = self.driver if search_object is None else search_object elements = self.locator_handler.find_by_locator(search_object, locator, True) return [WebElementWrapper.WebElementWrapper(self, locator, element) for element in elements]
python
def _find_immediately(self, locator, search_object=None): ''' Attempts to immediately find elements on the page without waiting @type locator: webdriverwrapper.support.locator.Locator @param locator: Locator object describing @type search_object: webdriverwrapper.WebElementWrapper @param search_object: Optional WebElement to start search with. If null, search will be on self.driver @return: Single WebElemetnWrapper if find_all is False, list of WebElementWrappers if find_all is True ''' search_object = self.driver if search_object is None else search_object elements = self.locator_handler.find_by_locator(search_object, locator, True) return [WebElementWrapper.WebElementWrapper(self, locator, element) for element in elements]
[ "def", "_find_immediately", "(", "self", ",", "locator", ",", "search_object", "=", "None", ")", ":", "search_object", "=", "self", ".", "driver", "if", "search_object", "is", "None", "else", "search_object", "elements", "=", "self", ".", "locator_handler", ".", "find_by_locator", "(", "search_object", ",", "locator", ",", "True", ")", "return", "[", "WebElementWrapper", ".", "WebElementWrapper", "(", "self", ",", "locator", ",", "element", ")", "for", "element", "in", "elements", "]" ]
Attempts to immediately find elements on the page without waiting @type locator: webdriverwrapper.support.locator.Locator @param locator: Locator object describing @type search_object: webdriverwrapper.WebElementWrapper @param search_object: Optional WebElement to start search with. If null, search will be on self.driver @return: Single WebElemetnWrapper if find_all is False, list of WebElementWrappers if find_all is True
[ "Attempts", "to", "immediately", "find", "elements", "on", "the", "page", "without", "waiting" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L389-L404
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.find_all
def find_all(self, locator, search_object=None, force_find=False): ''' Find all elements matching locator @type locator: webdriverwrapper.support.locator.Locator @param locator: Locator object describing @rtype: list[WebElementWrapper] @return: list of WebElementWrappers ''' return self.find(locator=locator, find_all=True, search_object=search_object, force_find=force_find)
python
def find_all(self, locator, search_object=None, force_find=False): ''' Find all elements matching locator @type locator: webdriverwrapper.support.locator.Locator @param locator: Locator object describing @rtype: list[WebElementWrapper] @return: list of WebElementWrappers ''' return self.find(locator=locator, find_all=True, search_object=search_object, force_find=force_find)
[ "def", "find_all", "(", "self", ",", "locator", ",", "search_object", "=", "None", ",", "force_find", "=", "False", ")", ":", "return", "self", ".", "find", "(", "locator", "=", "locator", ",", "find_all", "=", "True", ",", "search_object", "=", "search_object", ",", "force_find", "=", "force_find", ")" ]
Find all elements matching locator @type locator: webdriverwrapper.support.locator.Locator @param locator: Locator object describing @rtype: list[WebElementWrapper] @return: list of WebElementWrappers
[ "Find", "all", "elements", "matching", "locator" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L406-L416
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.find_by_dynamic_locator
def find_by_dynamic_locator(self, template_locator, variables, find_all=False, search_object=None): ''' Find with dynamic locator @type template_locator: webdriverwrapper.support.locator.Locator @param template_locator: Template locator w/ formatting bits to insert @type variables: dict @param variables: Dictionary of variable substitutions @type find_all: bool @param find_all: True to find all elements immediately, False for find single element only @type search_object: webdriverwrapper.WebElementWrapper @param search_object: Optional WebElement to start search with. If null, search will be on self.driver @rtype: webdriverwrapper.WebElementWrapper or list() @return: Single WebElemetnWrapper if find_all is False, list of WebElementWrappers if find_all is True ''' 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 locator variables') # replace all variables that match the keys in 'variables' dict locator = "" for key in variables.keys(): locator = template_locator.replace(template_variable_character + key, variables[key]) return self.find(locator, find_all, search_object)
python
def find_by_dynamic_locator(self, template_locator, variables, find_all=False, search_object=None): ''' Find with dynamic locator @type template_locator: webdriverwrapper.support.locator.Locator @param template_locator: Template locator w/ formatting bits to insert @type variables: dict @param variables: Dictionary of variable substitutions @type find_all: bool @param find_all: True to find all elements immediately, False for find single element only @type search_object: webdriverwrapper.WebElementWrapper @param search_object: Optional WebElement to start search with. If null, search will be on self.driver @rtype: webdriverwrapper.WebElementWrapper or list() @return: Single WebElemetnWrapper if find_all is False, list of WebElementWrappers if find_all is True ''' 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 locator variables') # replace all variables that match the keys in 'variables' dict locator = "" for key in variables.keys(): locator = template_locator.replace(template_variable_character + key, variables[key]) return self.find(locator, find_all, search_object)
[ "def", "find_by_dynamic_locator", "(", "self", ",", "template_locator", ",", "variables", ",", "find_all", "=", "False", ",", "search_object", "=", "None", ")", ":", "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 locator variables'", ")", "# replace all variables that match the keys in 'variables' dict", "locator", "=", "\"\"", "for", "key", "in", "variables", ".", "keys", "(", ")", ":", "locator", "=", "template_locator", ".", "replace", "(", "template_variable_character", "+", "key", ",", "variables", "[", "key", "]", ")", "return", "self", ".", "find", "(", "locator", ",", "find_all", ",", "search_object", ")" ]
Find with dynamic locator @type template_locator: webdriverwrapper.support.locator.Locator @param template_locator: Template locator w/ formatting bits to insert @type variables: dict @param variables: Dictionary of variable substitutions @type find_all: bool @param find_all: True to find all elements immediately, False for find single element only @type search_object: webdriverwrapper.WebElementWrapper @param search_object: Optional WebElement to start search with. If null, search will be on self.driver @rtype: webdriverwrapper.WebElementWrapper or list() @return: Single WebElemetnWrapper if find_all is False, list of WebElementWrappers if find_all is True
[ "Find", "with", "dynamic", "locator" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L418-L446
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.is_present
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
python
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
[ "def", "is_present", "(", "self", ",", "locator", ",", "search_object", "=", "None", ")", ":", "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" ]
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
[ "Determines", "whether", "an", "element", "is", "present", "on", "the", "page", "retrying", "once", "if", "unable", "to", "locate" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L463-L478
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.is_present_no_wait
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.')
python
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.')
[ "def", "is_present_no_wait", "(", "self", ",", "locator", ")", ":", "# first attempt to locate the element", "def", "execute", "(", ")", ":", "'''\n Generic function to execute wait\n '''", "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.'", ")" ]
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
[ "Determines", "whether", "an", "element", "is", "present", "on", "the", "page", "with", "no", "wait" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L481-L498
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.wait_until
def wait_until(self, wait_function, failure_message=None, timeout=None): """ Base wait method: called by other wait functions to execute wait @type wait_function: types.FunctionType @param wait_function: Generic function to be executed @type failure_message: str @param failure_message: Message to fail with if exception is raised @type timeout: int @param timeout: timeout override @rtype: webdriverwrapper.WebElementWrapper @return: Returns the element found """ timeout = timeout if timeout is not None else self.timeout failure_message = failure_message if failure_message is not None else \ 'Timeout waiting for custom function to return True' def wait(): ''' Wait function passed to executor ''' return WebDriverWait(self, timeout).until(lambda dw: wait_function()) return self.execute_and_handle_webdriver_exceptions(wait, timeout, None, failure_message)
python
def wait_until(self, wait_function, failure_message=None, timeout=None): """ Base wait method: called by other wait functions to execute wait @type wait_function: types.FunctionType @param wait_function: Generic function to be executed @type failure_message: str @param failure_message: Message to fail with if exception is raised @type timeout: int @param timeout: timeout override @rtype: webdriverwrapper.WebElementWrapper @return: Returns the element found """ timeout = timeout if timeout is not None else self.timeout failure_message = failure_message if failure_message is not None else \ 'Timeout waiting for custom function to return True' def wait(): ''' Wait function passed to executor ''' return WebDriverWait(self, timeout).until(lambda dw: wait_function()) return self.execute_and_handle_webdriver_exceptions(wait, timeout, None, failure_message)
[ "def", "wait_until", "(", "self", ",", "wait_function", ",", "failure_message", "=", "None", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "failure_message", "=", "failure_message", "if", "failure_message", "is", "not", "None", "else", "'Timeout waiting for custom function to return True'", "def", "wait", "(", ")", ":", "'''\n Wait function passed to executor\n '''", "return", "WebDriverWait", "(", "self", ",", "timeout", ")", ".", "until", "(", "lambda", "dw", ":", "wait_function", "(", ")", ")", "return", "self", ".", "execute_and_handle_webdriver_exceptions", "(", "wait", ",", "timeout", ",", "None", ",", "failure_message", ")" ]
Base wait method: called by other wait functions to execute wait @type wait_function: types.FunctionType @param wait_function: Generic function to be executed @type failure_message: str @param failure_message: Message to fail with if exception is raised @type timeout: int @param timeout: timeout override @rtype: webdriverwrapper.WebElementWrapper @return: Returns the element found
[ "Base", "wait", "method", ":", "called", "by", "other", "wait", "functions", "to", "execute", "wait" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L505-L529
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.wait_until_present
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)
python
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)
[ "def", "wait_until_present", "(", "self", ",", "locator", ",", "timeout", "=", "None", ",", "failure_message", "=", "'Timeout waiting for element to be present'", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "def", "wait", "(", ")", ":", "'''\n Wait function passed to executor\n '''", "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", ")" ]
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
[ "Waits", "for", "an", "element", "to", "be", "present" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L544-L567
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.wait_until_not_present
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')
python
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')
[ "def", "wait_until_not_present", "(", "self", ",", "locator", ",", "timeout", "=", "None", ")", ":", "# 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", "(", ")", ":", "'''\n Wait function pasted to executor\n '''", "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'", ")" ]
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
[ "Waits", "for", "an", "element", "to", "no", "longer", "be", "present" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L569-L592
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.wait_until_invisibility_of
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')
python
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')
[ "def", "wait_until_invisibility_of", "(", "self", ",", "locator", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "def", "wait", "(", ")", ":", "'''\n Wait function passed to executor\n '''", "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'", ")" ]
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
[ "Waits", "for", "an", "element", "to", "be", "invisible" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L624-L647
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.wait_until_clickable
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')
python
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')
[ "def", "wait_until_clickable", "(", "self", ",", "locator", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "def", "wait", "(", ")", ":", "'''\n Wait function passed to executor\n '''", "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'", ")" ]
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
[ "Waits", "for", "an", "element", "to", "be", "clickable" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L649-L673
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.wait_until_stale
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')
python
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')
[ "def", "wait_until_stale", "(", "self", ",", "locator", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "def", "wait", "(", ")", ":", "'''\n Wait function passed to executor\n '''", "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'", ")" ]
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
[ "Waits", "for", "an", "element", "to", "be", "stale", "in", "the", "DOM" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L675-L699
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.wait_until_title_contains
def wait_until_title_contains(self, partial_title, timeout=None): """ Waits for title to contain <partial_title> @type partial_title: str @param partial_title: the partial title to locate @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 ''' return WebDriverWait(self.driver, timeout).until(EC.title_contains(partial_title)) return self.execute_and_handle_webdriver_exceptions( wait, timeout, partial_title, 'Timeout waiting for title to contain: ' + str(partial_title))
python
def wait_until_title_contains(self, partial_title, timeout=None): """ Waits for title to contain <partial_title> @type partial_title: str @param partial_title: the partial title to locate @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 ''' return WebDriverWait(self.driver, timeout).until(EC.title_contains(partial_title)) return self.execute_and_handle_webdriver_exceptions( wait, timeout, partial_title, 'Timeout waiting for title to contain: ' + str(partial_title))
[ "def", "wait_until_title_contains", "(", "self", ",", "partial_title", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "def", "wait", "(", ")", ":", "'''\n Wait function passed to executor\n '''", "return", "WebDriverWait", "(", "self", ".", "driver", ",", "timeout", ")", ".", "until", "(", "EC", ".", "title_contains", "(", "partial_title", ")", ")", "return", "self", ".", "execute_and_handle_webdriver_exceptions", "(", "wait", ",", "timeout", ",", "partial_title", ",", "'Timeout waiting for title to contain: '", "+", "str", "(", "partial_title", ")", ")" ]
Waits for title to contain <partial_title> @type partial_title: str @param partial_title: the partial title to locate @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
[ "Waits", "for", "title", "to", "contain", "<partial_title", ">" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L702-L723
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.wait_until_title_is
def wait_until_title_is(self, title, timeout=None): """ Waits for title to be exactly <partial_title> @type title: str @param title: the exact title to locate @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 ''' return WebDriverWait(self.driver, timeout).until(EC.title_is(title)) return self.execute_and_handle_webdriver_exceptions( wait, timeout, title, 'Timeout waiting for title to be: ' + str(title))
python
def wait_until_title_is(self, title, timeout=None): """ Waits for title to be exactly <partial_title> @type title: str @param title: the exact title to locate @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 ''' return WebDriverWait(self.driver, timeout).until(EC.title_is(title)) return self.execute_and_handle_webdriver_exceptions( wait, timeout, title, 'Timeout waiting for title to be: ' + str(title))
[ "def", "wait_until_title_is", "(", "self", ",", "title", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "def", "wait", "(", ")", ":", "'''\n Wait function passed to executor\n '''", "return", "WebDriverWait", "(", "self", ".", "driver", ",", "timeout", ")", ".", "until", "(", "EC", ".", "title_is", "(", "title", ")", ")", "return", "self", ".", "execute_and_handle_webdriver_exceptions", "(", "wait", ",", "timeout", ",", "title", ",", "'Timeout waiting for title to be: '", "+", "str", "(", "title", ")", ")" ]
Waits for title to be exactly <partial_title> @type title: str @param title: the exact title to locate @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
[ "Waits", "for", "title", "to", "be", "exactly", "<partial_title", ">" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L725-L746
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.wait_until_alert_is_present
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')
python
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')
[ "def", "wait_until_alert_is_present", "(", "self", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "locator", "=", "None", "def", "wait", "(", ")", ":", "'''\n Wait function passed to executor\n '''", "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'", ")" ]
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
[ "Waits", "for", "an", "alert", "to", "be", "present" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L747-L767
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.wait_until_text_contains
def wait_until_text_contains(self, locator, text, timeout=None): """ Waits for an element's text to contain <text> @type locator: webdriverwrapper.support.locator.Locator @param locator: locator used to find element @type text: str @param text: the text to search for @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 this = self self.wait_for(locator) # first check that element exists def wait(): ''' Wait function passed to executor ''' WebDriverWait(self.driver, timeout).until(lambda d: text in this.find(locator).text()) return this.find(locator) return self.execute_and_handle_webdriver_exceptions( wait, timeout, locator, 'Timeout waiting for text to contain: ' + str(text))
python
def wait_until_text_contains(self, locator, text, timeout=None): """ Waits for an element's text to contain <text> @type locator: webdriverwrapper.support.locator.Locator @param locator: locator used to find element @type text: str @param text: the text to search for @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 this = self self.wait_for(locator) # first check that element exists def wait(): ''' Wait function passed to executor ''' WebDriverWait(self.driver, timeout).until(lambda d: text in this.find(locator).text()) return this.find(locator) return self.execute_and_handle_webdriver_exceptions( wait, timeout, locator, 'Timeout waiting for text to contain: ' + str(text))
[ "def", "wait_until_text_contains", "(", "self", ",", "locator", ",", "text", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "this", "=", "self", "self", ".", "wait_for", "(", "locator", ")", "# first check that element exists", "def", "wait", "(", ")", ":", "'''\n Wait function passed to executor\n '''", "WebDriverWait", "(", "self", ".", "driver", ",", "timeout", ")", ".", "until", "(", "lambda", "d", ":", "text", "in", "this", ".", "find", "(", "locator", ")", ".", "text", "(", ")", ")", "return", "this", ".", "find", "(", "locator", ")", "return", "self", ".", "execute_and_handle_webdriver_exceptions", "(", "wait", ",", "timeout", ",", "locator", ",", "'Timeout waiting for text to contain: '", "+", "str", "(", "text", ")", ")" ]
Waits for an element's text to contain <text> @type locator: webdriverwrapper.support.locator.Locator @param locator: locator used to find element @type text: str @param text: the text to search for @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
[ "Waits", "for", "an", "element", "s", "text", "to", "contain", "<text", ">" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L769-L796
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.wait_until_text_is_not_empty
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')
python
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')
[ "def", "wait_until_text_is_not_empty", "(", "self", ",", "locator", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "self", ".", "wait_for", "(", "locator", ")", "# first check that element exists", "def", "wait", "(", ")", ":", "'''\n Wait function passed to executor\n '''", "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'", ")" ]
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
[ "Waits", "for", "an", "element", "s", "text", "to", "not", "be", "empty" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L827-L851
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.wait_until_page_source_contains
def wait_until_page_source_contains(self, text, timeout=None): """ Waits for the page source to contain <text> @type text: str @param text: the text to search for @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 ''' WebDriverWait(self.driver, timeout).until(lambda d: text in self.page_source()) return self.page_source() return self.execute_and_handle_webdriver_exceptions( wait, timeout, text, 'Timeout waiting for source to contain: {}'.format(text))
python
def wait_until_page_source_contains(self, text, timeout=None): """ Waits for the page source to contain <text> @type text: str @param text: the text to search for @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 ''' WebDriverWait(self.driver, timeout).until(lambda d: text in self.page_source()) return self.page_source() return self.execute_and_handle_webdriver_exceptions( wait, timeout, text, 'Timeout waiting for source to contain: {}'.format(text))
[ "def", "wait_until_page_source_contains", "(", "self", ",", "text", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "def", "wait", "(", ")", ":", "'''\n Wait function passed to executor\n '''", "WebDriverWait", "(", "self", ".", "driver", ",", "timeout", ")", ".", "until", "(", "lambda", "d", ":", "text", "in", "self", ".", "page_source", "(", ")", ")", "return", "self", ".", "page_source", "(", ")", "return", "self", ".", "execute_and_handle_webdriver_exceptions", "(", "wait", ",", "timeout", ",", "text", ",", "'Timeout waiting for source to contain: {}'", ".", "format", "(", "text", ")", ")" ]
Waits for the page source to contain <text> @type text: str @param text: the text to search for @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
[ "Waits", "for", "the", "page", "source", "to", "contain", "<text", ">" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L853-L875
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.wait_until_jquery_requests_are_closed
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')
python
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')
[ "def", "wait_until_jquery_requests_are_closed", "(", "self", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "def", "wait", "(", ")", ":", "'''\n Wait function passed to executor\n '''", "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'", ")" ]
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
[ "Waits", "for", "AJAX", "requests", "made", "through" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L877-L895
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.execute_and_handle_webdriver_exceptions
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))
python
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))
[ "def", "execute_and_handle_webdriver_exceptions", "(", "self", ",", "function_to_execute", ",", "timeout", "=", "None", ",", "locator", "=", "None", ",", "failure_message", "=", "None", ")", ":", "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", ")", ")" ]
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
[ "Executor", "for", "wait", "functions" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L897-L948
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.pause_and_wait_for_user
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'} )
python
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'} )
[ "def", "pause_and_wait_for_user", "(", "self", ",", "timeout", "=", "None", ",", "prompt_text", "=", "'Click to resume (WebDriver is paused)'", ")", ":", "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.\n If the checkbox is not displayed (e.g. user navigates the page), it will re-insert it into the page\n\n @type driver: WebDriverWrapper\n @param driver: Driver to execute\n @return: True if user is ready, false if not\n \"\"\"", "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'", "}", ")" ]
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
[ "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" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L975-L1029
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.get_browser_log
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
python
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
[ "def", "get_browser_log", "(", "self", ",", "levels", "=", "None", ")", ":", "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" ]
Gets the console log of the browser @type levels: @return: List of browser log entries
[ "Gets", "the", "console", "log", "of", "the", "browser" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L1093-L1103
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py
WebDriverWrapper.quit
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)
python
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)
[ "def", "quit", "(", "self", ")", ":", "# 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", ")" ]
Close driver and kill all associated displays
[ "Close", "driver", "and", "kill", "all", "associated", "displays" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L1120-L1140
Shapeways/coyote_framework
coyote_framework/drivers/coyote_driver.py
CoyoteDriver.visit
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
python
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
[ "def", "visit", "(", "self", ",", "url", "=", "''", ")", ":", "result", "=", "super", "(", "CoyoteDriver", ",", "self", ")", ".", "visit", "(", "url", ")", "source", "=", "self", ".", "page_source", "(", ")", "return", "result" ]
Visit the url, checking for rr errors in the response @param url: URL @return: Visit result
[ "Visit", "the", "url", "checking", "for", "rr", "errors", "in", "the", "response" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/drivers/coyote_driver.py#L8-L16
Shapeways/coyote_framework
coyote_framework/config/abstract_config.py
load_config_vars
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)
python
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)
[ "def", "load_config_vars", "(", "target_config", ",", "source_config", ")", ":", "# 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", ")" ]
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
[ "Loads", "all", "attributes", "from", "source", "config", "into", "target", "config" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/config/abstract_config.py#L100-L116
Shapeways/coyote_framework
coyote_framework/config/abstract_config.py
ConfigBase._readall
def _readall(self): """Read configs from all available configs. It will read files in the following order: 1.) Read all default settings: These are located under: `<project_root>/config/*/default.cfg` 2.) Read the user's config settings: This is located on the path: `~/.aftrc` 3.) Read all config files specified by the config string in the environment variable TEST_RUN_SETTING_CONFIG A config string such as "browser.headless,scripts.no_ssh" will read paths: `<project_root>/config/browser/headless.cfg` `<project_root>/config/scripts/no_ssh.cfg` OR a config string such as "<project_root>/config/browser/headless.cfg" will load that path directly """ # First priority -- read all default configs config_path = os.path.dirname(__file__) config_defaults = [os.path.join(dirpath, f) for dirpath, dirnames, files in os.walk(config_path) for f in fnmatch.filter(files, 'default.cfg')] # Second priority -- read the user overrides user_config = os.path.expanduser('~/.aftrc') # Third priority -- read the environment variable overrides override_filenames = [] if TEST_RUN_SETTING_CONFIG in os.environ: for test_config in os.environ[TEST_RUN_SETTING_CONFIG].split(','): if os.path.exists(test_config): #is this a file path override_filenames.append(test_config) elif "." in test_config and not test_config.endswith('.cfg'): #else it might be in xxxx.yyyy format config_parts = test_config.split('.') config_parts[-1]+='.cfg' #add file ext to last part, which should be file filename = os.path.join(config_path, *config_parts) override_filenames.append(filename) else: #else unknown, might throw exception here pass all_configs = config_defaults + [user_config] + override_filenames return self.parser.read(all_configs)
python
def _readall(self): """Read configs from all available configs. It will read files in the following order: 1.) Read all default settings: These are located under: `<project_root>/config/*/default.cfg` 2.) Read the user's config settings: This is located on the path: `~/.aftrc` 3.) Read all config files specified by the config string in the environment variable TEST_RUN_SETTING_CONFIG A config string such as "browser.headless,scripts.no_ssh" will read paths: `<project_root>/config/browser/headless.cfg` `<project_root>/config/scripts/no_ssh.cfg` OR a config string such as "<project_root>/config/browser/headless.cfg" will load that path directly """ # First priority -- read all default configs config_path = os.path.dirname(__file__) config_defaults = [os.path.join(dirpath, f) for dirpath, dirnames, files in os.walk(config_path) for f in fnmatch.filter(files, 'default.cfg')] # Second priority -- read the user overrides user_config = os.path.expanduser('~/.aftrc') # Third priority -- read the environment variable overrides override_filenames = [] if TEST_RUN_SETTING_CONFIG in os.environ: for test_config in os.environ[TEST_RUN_SETTING_CONFIG].split(','): if os.path.exists(test_config): #is this a file path override_filenames.append(test_config) elif "." in test_config and not test_config.endswith('.cfg'): #else it might be in xxxx.yyyy format config_parts = test_config.split('.') config_parts[-1]+='.cfg' #add file ext to last part, which should be file filename = os.path.join(config_path, *config_parts) override_filenames.append(filename) else: #else unknown, might throw exception here pass all_configs = config_defaults + [user_config] + override_filenames return self.parser.read(all_configs)
[ "def", "_readall", "(", "self", ")", ":", "# First priority -- read all default configs", "config_path", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "config_defaults", "=", "[", "os", ".", "path", ".", "join", "(", "dirpath", ",", "f", ")", "for", "dirpath", ",", "dirnames", ",", "files", "in", "os", ".", "walk", "(", "config_path", ")", "for", "f", "in", "fnmatch", ".", "filter", "(", "files", ",", "'default.cfg'", ")", "]", "# Second priority -- read the user overrides", "user_config", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.aftrc'", ")", "# Third priority -- read the environment variable overrides", "override_filenames", "=", "[", "]", "if", "TEST_RUN_SETTING_CONFIG", "in", "os", ".", "environ", ":", "for", "test_config", "in", "os", ".", "environ", "[", "TEST_RUN_SETTING_CONFIG", "]", ".", "split", "(", "','", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "test_config", ")", ":", "#is this a file path", "override_filenames", ".", "append", "(", "test_config", ")", "elif", "\".\"", "in", "test_config", "and", "not", "test_config", ".", "endswith", "(", "'.cfg'", ")", ":", "#else it might be in xxxx.yyyy format", "config_parts", "=", "test_config", ".", "split", "(", "'.'", ")", "config_parts", "[", "-", "1", "]", "+=", "'.cfg'", "#add file ext to last part, which should be file", "filename", "=", "os", ".", "path", ".", "join", "(", "config_path", ",", "*", "config_parts", ")", "override_filenames", ".", "append", "(", "filename", ")", "else", ":", "#else unknown, might throw exception here", "pass", "all_configs", "=", "config_defaults", "+", "[", "user_config", "]", "+", "override_filenames", "return", "self", ".", "parser", ".", "read", "(", "all_configs", ")" ]
Read configs from all available configs. It will read files in the following order: 1.) Read all default settings: These are located under: `<project_root>/config/*/default.cfg` 2.) Read the user's config settings: This is located on the path: `~/.aftrc` 3.) Read all config files specified by the config string in the environment variable TEST_RUN_SETTING_CONFIG A config string such as "browser.headless,scripts.no_ssh" will read paths: `<project_root>/config/browser/headless.cfg` `<project_root>/config/scripts/no_ssh.cfg` OR a config string such as "<project_root>/config/browser/headless.cfg" will load that path directly
[ "Read", "configs", "from", "all", "available", "configs", ".", "It", "will", "read", "files", "in", "the", "following", "order", ":" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/config/abstract_config.py#L52-L97
Shapeways/coyote_framework
coyote_framework/util/apps/parallel.py
run_parallel
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]
python
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]
[ "def", "run_parallel", "(", "*", "functions", ")", ":", "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", "]" ]
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
[ "Runs", "a", "series", "of", "functions", "in", "parallel", ".", "Return", "values", "are", "ordered", "by", "the", "order", "in", "which", "their", "functions", "were", "passed", "." ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/util/apps/parallel.py#L17-L76
Shapeways/coyote_framework
coyote_framework/webdriver/webdriver/browsercapabilities.py
copy_and_update
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
python
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
[ "def", "copy_and_update", "(", "dictionary", ",", "update", ")", ":", "newdict", "=", "dictionary", ".", "copy", "(", ")", "newdict", ".", "update", "(", "update", ")", "return", "newdict" ]
Returns an updated copy of the dictionary without modifying the original
[ "Returns", "an", "updated", "copy", "of", "the", "dictionary", "without", "modifying", "the", "original" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriver/browsercapabilities.py#L4-L8
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/staticreader.py
get_static_directory
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
python
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
[ "def", "get_static_directory", "(", ")", ":", "directory", "=", "templates_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'static'", ")", "return", "directory" ]
Retrieves the full path of the static directory @return: Full path of the static directory
[ "Retrieves", "the", "full", "path", "of", "the", "static", "directory" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/staticreader.py#L10-L16
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/staticreader.py
read_html_file
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
python
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
[ "def", "read_html_file", "(", "filename", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "get_static_directory", "(", ")", ",", "'html/{filename}'", ".", "format", "(", "filename", "=", "filename", ")", ")", ")", "as", "f", ":", "contents", "=", "f", ".", "read", "(", ")", "return", "contents" ]
Reads the contents of an html file in the css directory @return: Contents of the specified file
[ "Reads", "the", "contents", "of", "an", "html", "file", "in", "the", "css", "directory" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/staticreader.py#L29-L36
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/LocatorHandler.py
LocatorHandler.parse_locator
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)
python
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)
[ "def", "parse_locator", "(", "locator", ")", ":", "# 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", ")" ]
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
[ "Parses", "a", "valid", "selenium", "By", "and", "value", "from", "a", "locator", ";", "returns", "as", "a", "named", "tuple", "with", "properties", "By", "and", "value" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/LocatorHandler.py#L16-L36
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/LocatorHandler.py
LocatorHandler.find_by_locator
def find_by_locator(webdriver_or_element, locator, find_all_elements=False): """ Locate an element using either a webdriver or webelement @param webdriver_or_element: Webdriver or Webelement object used for search @type locator: webdriver.webdriverwrapper.support.locator.Locator @param locator: locator used in search @type find_all_elements: bool @param find_all_elements: return all elements matching if true, first matching if false @return: either a single WebElement or a list of WebElements """ # handle backwards compatibility to support new Locator class if isinstance(locator, loc.Locator): locator = '{by}={locator}'.format(by=locator.by, locator=locator.locator) # use the appropriate find method given the locator type; # locators should follow the convention "css=.class" or "xpath=//div" # if locator type is unspecified, it will default to css if (locator.count('css=') > 0 or locator.count('css_selector=')) and len(locator.split('=', 1)) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_css_selector(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_css_selector(locator.split('=', 1)[-1]) elif locator.count('id=') > 0 and len(locator.split('=')) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_id(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_id(locator.split('=', 1)[-1]) elif locator.count('xpath=') > 0 and len(locator.split('=')) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_xpath(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_xpath(locator.split('=', 1)[-1]) elif locator.count('class_name=') > 0 and len(locator.split('=')) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_class_name(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_class_name(locator.split('=', 1)[-1]) elif locator.count('link_text=') > 0 and len(locator.split('=')) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_link_text(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_link_text(locator.split('=', 1)[-1]) elif locator.count('partial_link_text=') > 0 and len(locator.split('=')) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_partial_link_text(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_partial_link_text(locator.split('=', 1)[-1]) elif locator.count('name=') > 0 and len(locator.split('=')) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_name(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_name(locator.split('=', 1)[-1]) elif locator.count('tag_name=') > 0 and len(locator.split('=')) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_tag_name(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_tag_name(locator.split('=', 1)[-1]) else: # default to css if find_all_elements: return webdriver_or_element.find_elements_by_css_selector(locator) else: return webdriver_or_element.find_element_by_css_selector(locator)
python
def find_by_locator(webdriver_or_element, locator, find_all_elements=False): """ Locate an element using either a webdriver or webelement @param webdriver_or_element: Webdriver or Webelement object used for search @type locator: webdriver.webdriverwrapper.support.locator.Locator @param locator: locator used in search @type find_all_elements: bool @param find_all_elements: return all elements matching if true, first matching if false @return: either a single WebElement or a list of WebElements """ # handle backwards compatibility to support new Locator class if isinstance(locator, loc.Locator): locator = '{by}={locator}'.format(by=locator.by, locator=locator.locator) # use the appropriate find method given the locator type; # locators should follow the convention "css=.class" or "xpath=//div" # if locator type is unspecified, it will default to css if (locator.count('css=') > 0 or locator.count('css_selector=')) and len(locator.split('=', 1)) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_css_selector(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_css_selector(locator.split('=', 1)[-1]) elif locator.count('id=') > 0 and len(locator.split('=')) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_id(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_id(locator.split('=', 1)[-1]) elif locator.count('xpath=') > 0 and len(locator.split('=')) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_xpath(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_xpath(locator.split('=', 1)[-1]) elif locator.count('class_name=') > 0 and len(locator.split('=')) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_class_name(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_class_name(locator.split('=', 1)[-1]) elif locator.count('link_text=') > 0 and len(locator.split('=')) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_link_text(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_link_text(locator.split('=', 1)[-1]) elif locator.count('partial_link_text=') > 0 and len(locator.split('=')) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_partial_link_text(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_partial_link_text(locator.split('=', 1)[-1]) elif locator.count('name=') > 0 and len(locator.split('=')) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_name(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_name(locator.split('=', 1)[-1]) elif locator.count('tag_name=') > 0 and len(locator.split('=')) > 1: if find_all_elements: return webdriver_or_element.find_elements_by_tag_name(locator.split('=', 1)[-1]) else: return webdriver_or_element.find_element_by_tag_name(locator.split('=', 1)[-1]) else: # default to css if find_all_elements: return webdriver_or_element.find_elements_by_css_selector(locator) else: return webdriver_or_element.find_element_by_css_selector(locator)
[ "def", "find_by_locator", "(", "webdriver_or_element", ",", "locator", ",", "find_all_elements", "=", "False", ")", ":", "# handle backwards compatibility to support new Locator class", "if", "isinstance", "(", "locator", ",", "loc", ".", "Locator", ")", ":", "locator", "=", "'{by}={locator}'", ".", "format", "(", "by", "=", "locator", ".", "by", ",", "locator", "=", "locator", ".", "locator", ")", "# use the appropriate find method given the locator type;", "# locators should follow the convention \"css=.class\" or \"xpath=//div\"", "# if locator type is unspecified, it will default to css", "if", "(", "locator", ".", "count", "(", "'css='", ")", ">", "0", "or", "locator", ".", "count", "(", "'css_selector='", ")", ")", "and", "len", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", ")", ">", "1", ":", "if", "find_all_elements", ":", "return", "webdriver_or_element", ".", "find_elements_by_css_selector", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "else", ":", "return", "webdriver_or_element", ".", "find_element_by_css_selector", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "elif", "locator", ".", "count", "(", "'id='", ")", ">", "0", "and", "len", "(", "locator", ".", "split", "(", "'='", ")", ")", ">", "1", ":", "if", "find_all_elements", ":", "return", "webdriver_or_element", ".", "find_elements_by_id", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "else", ":", "return", "webdriver_or_element", ".", "find_element_by_id", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "elif", "locator", ".", "count", "(", "'xpath='", ")", ">", "0", "and", "len", "(", "locator", ".", "split", "(", "'='", ")", ")", ">", "1", ":", "if", "find_all_elements", ":", "return", "webdriver_or_element", ".", "find_elements_by_xpath", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "else", ":", "return", "webdriver_or_element", ".", "find_element_by_xpath", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "elif", "locator", ".", "count", "(", "'class_name='", ")", ">", "0", "and", "len", "(", "locator", ".", "split", "(", "'='", ")", ")", ">", "1", ":", "if", "find_all_elements", ":", "return", "webdriver_or_element", ".", "find_elements_by_class_name", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "else", ":", "return", "webdriver_or_element", ".", "find_element_by_class_name", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "elif", "locator", ".", "count", "(", "'link_text='", ")", ">", "0", "and", "len", "(", "locator", ".", "split", "(", "'='", ")", ")", ">", "1", ":", "if", "find_all_elements", ":", "return", "webdriver_or_element", ".", "find_elements_by_link_text", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "else", ":", "return", "webdriver_or_element", ".", "find_element_by_link_text", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "elif", "locator", ".", "count", "(", "'partial_link_text='", ")", ">", "0", "and", "len", "(", "locator", ".", "split", "(", "'='", ")", ")", ">", "1", ":", "if", "find_all_elements", ":", "return", "webdriver_or_element", ".", "find_elements_by_partial_link_text", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "else", ":", "return", "webdriver_or_element", ".", "find_element_by_partial_link_text", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "elif", "locator", ".", "count", "(", "'name='", ")", ">", "0", "and", "len", "(", "locator", ".", "split", "(", "'='", ")", ")", ">", "1", ":", "if", "find_all_elements", ":", "return", "webdriver_or_element", ".", "find_elements_by_name", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "else", ":", "return", "webdriver_or_element", ".", "find_element_by_name", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "elif", "locator", ".", "count", "(", "'tag_name='", ")", ">", "0", "and", "len", "(", "locator", ".", "split", "(", "'='", ")", ")", ">", "1", ":", "if", "find_all_elements", ":", "return", "webdriver_or_element", ".", "find_elements_by_tag_name", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "else", ":", "return", "webdriver_or_element", ".", "find_element_by_tag_name", "(", "locator", ".", "split", "(", "'='", ",", "1", ")", "[", "-", "1", "]", ")", "else", ":", "# default to css", "if", "find_all_elements", ":", "return", "webdriver_or_element", ".", "find_elements_by_css_selector", "(", "locator", ")", "else", ":", "return", "webdriver_or_element", ".", "find_element_by_css_selector", "(", "locator", ")" ]
Locate an element using either a webdriver or webelement @param webdriver_or_element: Webdriver or Webelement object used for search @type locator: webdriver.webdriverwrapper.support.locator.Locator @param locator: locator used in search @type find_all_elements: bool @param find_all_elements: return all elements matching if true, first matching if false @return: either a single WebElement or a list of WebElements
[ "Locate", "an", "element", "using", "either", "a", "webdriver", "or", "webelement" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/LocatorHandler.py#L39-L111
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py
WebDriverWrapperAssertion.spin_assert
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)
python
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)
[ "def", "spin_assert", "(", "self", ",", "assertion", ",", "failure_message", "=", "'Failed Assertion'", ",", "timeout", "=", "None", ")", ":", "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", ")" ]
Asserts that assertion function passed to it will return True, trying every 'step' seconds until 'timeout' seconds have passed.
[ "Asserts", "that", "assertion", "function", "passed", "to", "it", "will", "return", "True", "trying", "every", "step", "seconds", "until", "timeout", "seconds", "have", "passed", "." ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py#L29-L44
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py
WebDriverWrapperAssertion.webdriver_assert
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
python
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
[ "def", "webdriver_assert", "(", "self", ",", "assertion", ",", "failure_message", "=", "'Failed Assertion'", ")", ":", "try", ":", "assert", "assertion", "(", ")", "is", "True", "except", "AssertionError", ":", "raise", "WebDriverAssertionException", ".", "WebDriverAssertionException", "(", "self", ".", "driver_wrapper", ",", "failure_message", ")", "return", "True" ]
Assert the assertion, but throw a WebDriverAssertionException if assertion fails
[ "Assert", "the", "assertion", "but", "throw", "a", "WebDriverAssertionException", "if", "assertion", "fails" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py#L46-L55
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py
WebDriverWrapperAssertion.assert_true
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))
python
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))
[ "def", "assert_true", "(", "self", ",", "value", ",", "failure_message", "=", "'Expected value to be True, was: {}'", ")", ":", "assertion", "=", "lambda", ":", "bool", "(", "value", ")", "self", ".", "webdriver_assert", "(", "assertion", ",", "unicode", "(", "failure_message", ")", ".", "format", "(", "value", ")", ")" ]
Asserts that a value is true @type value: bool @param value: value to test for True
[ "Asserts", "that", "a", "value", "is", "true" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py#L63-L71
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py
WebDriverWrapperAssertion.assert_equals
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))
python
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))
[ "def", "assert_equals", "(", "self", ",", "actual_val", ",", "expected_val", ",", "failure_message", "=", "'Expected values to be equal: \"{}\" and \"{}\"'", ")", ":", "assertion", "=", "lambda", ":", "expected_val", "==", "actual_val", "self", ".", "webdriver_assert", "(", "assertion", ",", "unicode", "(", "failure_message", ")", ".", "format", "(", "actual_val", ",", "expected_val", ")", ")" ]
Calls smart_assert, but creates its own assertion closure using the expected and provided values with the '==' operator
[ "Calls", "smart_assert", "but", "creates", "its", "own", "assertion", "closure", "using", "the", "expected", "and", "provided", "values", "with", "the", "==", "operator" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py#L83-L89
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py
WebDriverWrapperAssertion.assert_numbers_almost_equal
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))
python
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))
[ "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 \"{}\"'", ")", ":", "assertion", "=", "lambda", ":", "abs", "(", "expected_val", "-", "actual_val", ")", "<=", "allowed_delta", "self", ".", "webdriver_assert", "(", "assertion", ",", "unicode", "(", "failure_message", ")", ".", "format", "(", "allowed_delta", ",", "actual_val", ",", "expected_val", ")", ")" ]
Asserts that two numbers are within an allowed delta of each other
[ "Asserts", "that", "two", "numbers", "are", "within", "an", "allowed", "delta", "of", "each", "other" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py#L91-L97
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py
WebDriverWrapperAssertion.assert_not_equal
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))
python
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))
[ "def", "assert_not_equal", "(", "self", ",", "actual_val", ",", "unexpected_val", ",", "failure_message", "=", "'Expected values to differ: \"{}\" and \"{}\"'", ")", ":", "assertion", "=", "lambda", ":", "unexpected_val", "!=", "actual_val", "self", ".", "webdriver_assert", "(", "assertion", ",", "unicode", "(", "failure_message", ")", ".", "format", "(", "actual_val", ",", "unexpected_val", ")", ")" ]
Calls smart_assert, but creates its own assertion closure using the expected and provided values with the '!=' operator
[ "Calls", "smart_assert", "but", "creates", "its", "own", "assertion", "closure", "using", "the", "expected", "and", "provided", "values", "with", "the", "!", "=", "operator" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py#L99-L105
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py
WebDriverWrapperAssertion.assert_is
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))
python
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))
[ "def", "assert_is", "(", "self", ",", "actual_val", ",", "expected_type", ",", "failure_message", "=", "'Expected type to be \"{1},\" but was \"{0}\"'", ")", ":", "assertion", "=", "lambda", ":", "expected_type", "is", "actual_val", "self", ".", "webdriver_assert", "(", "assertion", ",", "unicode", "(", "failure_message", ")", ".", "format", "(", "actual_val", ",", "expected_type", ")", ")" ]
Calls smart_assert, but creates its own assertion closure using the expected and provided values with the 'is' operator
[ "Calls", "smart_assert", "but", "creates", "its", "own", "assertion", "closure", "using", "the", "expected", "and", "provided", "values", "with", "the", "is", "operator" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py#L107-L113
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py
WebDriverWrapperAssertion.assert_is_not
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))
python
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))
[ "def", "assert_is_not", "(", "self", ",", "actual_val", ",", "unexpected_type", ",", "failure_message", "=", "'Expected type not to be \"{1},\" but was \"{0}\"'", ")", ":", "assertion", "=", "lambda", ":", "unexpected_type", "is", "not", "actual_val", "self", ".", "webdriver_assert", "(", "assertion", ",", "unicode", "(", "failure_message", ")", ".", "format", "(", "actual_val", ",", "unexpected_type", ")", ")" ]
Calls smart_assert, but creates its own assertion closure using the expected and provided values with the 'is not' operator
[ "Calls", "smart_assert", "but", "creates", "its", "own", "assertion", "closure", "using", "the", "expected", "and", "provided", "values", "with", "the", "is", "not", "operator" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py#L115-L122
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py
WebDriverWrapperAssertion.assert_in
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))
python
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))
[ "def", "assert_in", "(", "self", ",", "actual_collection_or_string", ",", "expected_value", ",", "failure_message", "=", "'Expected \"{1}\" to be in \"{0}\"'", ")", ":", "assertion", "=", "lambda", ":", "expected_value", "in", "actual_collection_or_string", "self", ".", "webdriver_assert", "(", "assertion", ",", "unicode", "(", "failure_message", ")", ".", "format", "(", "actual_collection_or_string", ",", "expected_value", ")", ")" ]
Calls smart_assert, but creates its own assertion closure using the expected and provided values with the 'in' operator
[ "Calls", "smart_assert", "but", "creates", "its", "own", "assertion", "closure", "using", "the", "expected", "and", "provided", "values", "with", "the", "in", "operator" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py#L124-L130
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py
WebDriverWrapperAssertion.assert_not_in
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))
python
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))
[ "def", "assert_not_in", "(", "self", ",", "actual_collection_or_string", ",", "unexpected_value", ",", "failure_message", "=", "'Expected \"{1}\" not to be in \"{0}\"'", ")", ":", "assertion", "=", "lambda", ":", "unexpected_value", "not", "in", "actual_collection_or_string", "self", ".", "webdriver_assert", "(", "assertion", ",", "unicode", "(", "failure_message", ")", ".", "format", "(", "actual_collection_or_string", ",", "unexpected_value", ")", ")" ]
Calls smart_assert, but creates its own assertion closure using the expected and provided values with the 'not in' operator
[ "Calls", "smart_assert", "but", "creates", "its", "own", "assertion", "closure", "using", "the", "expected", "and", "provided", "values", "with", "the", "not", "in", "operator" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py#L132-L139
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py
WebDriverWrapperAssertion.assert_page_source_contains
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))
python
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))
[ "def", "assert_page_source_contains", "(", "self", ",", "expected_value", ",", "failure_message", "=", "'Expected page source to contain: \"{}\"'", ")", ":", "assertion", "=", "lambda", ":", "expected_value", "in", "self", ".", "driver_wrapper", ".", "page_source", "(", ")", "self", ".", "webdriver_assert", "(", "assertion", ",", "unicode", "(", "failure_message", ")", ".", "format", "(", "expected_value", ")", ")" ]
Asserts that the page source contains the string passed in expected_value
[ "Asserts", "that", "the", "page", "source", "contains", "the", "string", "passed", "in", "expected_value" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py#L141-L146
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py
WebDriverWrapperAssertion.assert_union
def assert_union(self, collection1, collection2, failure_message='Expected overlap between collections: "{}" and "{}"'): """ Asserts that the union of two sets has at least one member (collections share at least one member) """ assertion = lambda: len(collection1 or collection2) > 0 failure_message = unicode(failure_message).format(collection1, collection2) self.webdriver_assert(assertion, failure_message)
python
def assert_union(self, collection1, collection2, failure_message='Expected overlap between collections: "{}" and "{}"'): """ Asserts that the union of two sets has at least one member (collections share at least one member) """ assertion = lambda: len(collection1 or collection2) > 0 failure_message = unicode(failure_message).format(collection1, collection2) self.webdriver_assert(assertion, failure_message)
[ "def", "assert_union", "(", "self", ",", "collection1", ",", "collection2", ",", "failure_message", "=", "'Expected overlap between collections: \"{}\" and \"{}\"'", ")", ":", "assertion", "=", "lambda", ":", "len", "(", "collection1", "or", "collection2", ")", ">", "0", "failure_message", "=", "unicode", "(", "failure_message", ")", ".", "format", "(", "collection1", ",", "collection2", ")", "self", ".", "webdriver_assert", "(", "assertion", ",", "failure_message", ")" ]
Asserts that the union of two sets has at least one member (collections share at least one member)
[ "Asserts", "that", "the", "union", "of", "two", "sets", "has", "at", "least", "one", "member", "(", "collections", "share", "at", "least", "one", "member", ")" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py#L148-L155
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py
WebDriverWrapperAssertion.assert_no_union
def assert_no_union(self, collection1, collection2, failure_message='Expected no overlap between collections: "{}" and "{}"'): """ Asserts that the union of two sets is empty (collections are unique) """ assertion = lambda: len(set(collection1).intersection(set(collection2))) == 0 failure_message = unicode(failure_message).format(collection1, collection2) self.webdriver_assert(assertion, failure_message)
python
def assert_no_union(self, collection1, collection2, failure_message='Expected no overlap between collections: "{}" and "{}"'): """ Asserts that the union of two sets is empty (collections are unique) """ assertion = lambda: len(set(collection1).intersection(set(collection2))) == 0 failure_message = unicode(failure_message).format(collection1, collection2) self.webdriver_assert(assertion, failure_message)
[ "def", "assert_no_union", "(", "self", ",", "collection1", ",", "collection2", ",", "failure_message", "=", "'Expected no overlap between collections: \"{}\" and \"{}\"'", ")", ":", "assertion", "=", "lambda", ":", "len", "(", "set", "(", "collection1", ")", ".", "intersection", "(", "set", "(", "collection2", ")", ")", ")", "==", "0", "failure_message", "=", "unicode", "(", "failure_message", ")", ".", "format", "(", "collection1", ",", "collection2", ")", "self", ".", "webdriver_assert", "(", "assertion", ",", "failure_message", ")" ]
Asserts that the union of two sets is empty (collections are unique)
[ "Asserts", "that", "the", "union", "of", "two", "sets", "is", "empty", "(", "collections", "are", "unique", ")" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py#L157-L164
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py
WebDriverWrapperAssertion.assert_subset
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)
python
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)
[ "def", "assert_subset", "(", "self", ",", "subset", ",", "superset", ",", "failure_message", "=", "'Expected collection \"{}\" to be a subset of \"{}'", ")", ":", "assertion", "=", "lambda", ":", "set", "(", "subset", ")", ".", "issubset", "(", "set", "(", "superset", ")", ")", "failure_message", "=", "unicode", "(", "failure_message", ")", ".", "format", "(", "superset", ",", "subset", ")", "self", ".", "webdriver_assert", "(", "assertion", ",", "failure_message", ")" ]
Asserts that a superset contains all elements of a subset
[ "Asserts", "that", "a", "superset", "contains", "all", "elements", "of", "a", "subset" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/support/WebDriverWrapperAssertion.py#L166-L172
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.clear
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
python
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
[ "def", "clear", "(", "self", ")", ":", "def", "clear_element", "(", ")", ":", "\"\"\"\n Wrapper to clear element\n \"\"\"", "return", "self", ".", "element", ".", "clear", "(", ")", "self", ".", "execute_and_handle_webelement_exceptions", "(", "clear_element", ",", "'clear'", ")", "return", "self" ]
Clears the field represented by this element @rtype: WebElementWrapper @return: Returns itself
[ "Clears", "the", "field", "represented", "by", "this", "element" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L94-L107
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.delete_content
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
python
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
[ "def", "delete_content", "(", "self", ",", "max_chars", "=", "100", ")", ":", "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" ]
Deletes content in the input field by repeatedly typing HOME, then DELETE @rtype: WebElementWrapper @return: Returns itself
[ "Deletes", "content", "in", "the", "input", "field", "by", "repeatedly", "typing", "HOME", "then", "DELETE" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L109-L125
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.click
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
python
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
[ "def", "click", "(", "self", ",", "force_click", "=", "False", ")", ":", "js_executor", "=", "self", ".", "driver_wrapper", ".", "js_executor", "def", "click_element", "(", ")", ":", "\"\"\"\n Wrapper to call click\n \"\"\"", "return", "self", ".", "element", ".", "click", "(", ")", "def", "force_click_element", "(", ")", ":", "\"\"\"\n Javascript wrapper to force_click the element\n \"\"\"", "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" ]
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
[ "Clicks", "the", "element" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L127-L157
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.get_value
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')
python
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')
[ "def", "get_value", "(", "self", ")", ":", "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'", ")" ]
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
[ "Gets", "the", "value", "of", "a", "select", "or", "input", "element" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L159-L180
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.get_attribute
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) + '"')
python
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) + '"')
[ "def", "get_attribute", "(", "self", ",", "name", ")", ":", "def", "get_attribute_element", "(", ")", ":", "\"\"\"\n Wrapper to retrieve element\n \"\"\"", "return", "self", ".", "element", ".", "get_attribute", "(", "name", ")", "return", "self", ".", "execute_and_handle_webelement_exceptions", "(", "get_attribute_element", ",", "'get attribute \"'", "+", "str", "(", "name", ")", "+", "'\"'", ")" ]
Retrieves specified attribute from WebElement @type name: str @param name: Attribute to retrieve @rtype: str @return: String representation of the attribute
[ "Retrieves", "specified", "attribute", "from", "WebElement" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L182-L197
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.is_on_screen
def is_on_screen(self): """Tests if the element is within the viewport of the screen (partially hidden by overflow will return true) @return: True if on screen, False otherwise """ width = self.get_width() height = self.get_height() loc = self.location() el_x_left = loc['x'] el_x_right = el_x_left + width el_y_top = loc['y'] el_y_bottom = el_y_top + height screen_size = self.driver_wrapper.get_window_size() screen_x = screen_size['width'] screen_y = screen_size['height'] if (((el_x_left > 0 and el_x_right < screen_x) or (el_x_right > 0 and el_x_right <screen_x)) and ((el_y_top > 0 and el_y_top < screen_y) or (el_y_bottom > 0 and el_y_bottom > screen_y)) ): return True return False
python
def is_on_screen(self): """Tests if the element is within the viewport of the screen (partially hidden by overflow will return true) @return: True if on screen, False otherwise """ width = self.get_width() height = self.get_height() loc = self.location() el_x_left = loc['x'] el_x_right = el_x_left + width el_y_top = loc['y'] el_y_bottom = el_y_top + height screen_size = self.driver_wrapper.get_window_size() screen_x = screen_size['width'] screen_y = screen_size['height'] if (((el_x_left > 0 and el_x_right < screen_x) or (el_x_right > 0 and el_x_right <screen_x)) and ((el_y_top > 0 and el_y_top < screen_y) or (el_y_bottom > 0 and el_y_bottom > screen_y)) ): return True return False
[ "def", "is_on_screen", "(", "self", ")", ":", "width", "=", "self", ".", "get_width", "(", ")", "height", "=", "self", ".", "get_height", "(", ")", "loc", "=", "self", ".", "location", "(", ")", "el_x_left", "=", "loc", "[", "'x'", "]", "el_x_right", "=", "el_x_left", "+", "width", "el_y_top", "=", "loc", "[", "'y'", "]", "el_y_bottom", "=", "el_y_top", "+", "height", "screen_size", "=", "self", ".", "driver_wrapper", ".", "get_window_size", "(", ")", "screen_x", "=", "screen_size", "[", "'width'", "]", "screen_y", "=", "screen_size", "[", "'height'", "]", "if", "(", "(", "(", "el_x_left", ">", "0", "and", "el_x_right", "<", "screen_x", ")", "or", "(", "el_x_right", ">", "0", "and", "el_x_right", "<", "screen_x", ")", ")", "and", "(", "(", "el_y_top", ">", "0", "and", "el_y_top", "<", "screen_y", ")", "or", "(", "el_y_bottom", ">", "0", "and", "el_y_bottom", ">", "screen_y", ")", ")", ")", ":", "return", "True", "return", "False" ]
Tests if the element is within the viewport of the screen (partially hidden by overflow will return true) @return: True if on screen, False otherwise
[ "Tests", "if", "the", "element", "is", "within", "the", "viewport", "of", "the", "screen", "(", "partially", "hidden", "by", "overflow", "will", "return", "true", ")" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L230-L251
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.send_special_keys
def send_special_keys(self, value): """ Send special keys such as <enter> or <delete> @rtype: WebElementWrapper @return: Self """ def send_keys_element(): """ Wrapper to send keys """ return self.element.send_keys(value) self.execute_and_handle_webelement_exceptions(send_keys_element, 'send keys') return self
python
def send_special_keys(self, value): """ Send special keys such as <enter> or <delete> @rtype: WebElementWrapper @return: Self """ def send_keys_element(): """ Wrapper to send keys """ return self.element.send_keys(value) self.execute_and_handle_webelement_exceptions(send_keys_element, 'send keys') return self
[ "def", "send_special_keys", "(", "self", ",", "value", ")", ":", "def", "send_keys_element", "(", ")", ":", "\"\"\"\n Wrapper to send keys\n \"\"\"", "return", "self", ".", "element", ".", "send_keys", "(", "value", ")", "self", ".", "execute_and_handle_webelement_exceptions", "(", "send_keys_element", ",", "'send keys'", ")", "return", "self" ]
Send special keys such as <enter> or <delete> @rtype: WebElementWrapper @return: Self
[ "Send", "special", "keys", "such", "as", "<enter", ">", "or", "<delete", ">" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L281-L294
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.set
def set(self, val, force_set=False): """ Sets an input with a specified value; if force_set=True, will set through javascript if webdriver fails NOTE: if val is None, this function will interpret this to be an empty string @type val: str @param val: string to send to element @type force_set: bool @param force_set: Use javascript if True, webdriver if False """ if val is None: val = "" self.click(force_click=True if force_set else False) self.clear() self.send_keys(val) actual = self.get_attribute('value') if val != actual: if force_set: js_executor = self.driver_wrapper.js_executor def force_set_element(): """ Wrapper to force_set element via javascript if needed """ js_executor.execute_template('setValueTemplate', {'value': val}, self.element) return True self.execute_and_handle_webelement_exceptions(force_set_element, 'set element by javascript') else: self.driver_wrapper.assertion.fail( 'Setting text field failed because final text did not match input value: "{}" != "{}"'.format( actual, val ) ) return self
python
def set(self, val, force_set=False): """ Sets an input with a specified value; if force_set=True, will set through javascript if webdriver fails NOTE: if val is None, this function will interpret this to be an empty string @type val: str @param val: string to send to element @type force_set: bool @param force_set: Use javascript if True, webdriver if False """ if val is None: val = "" self.click(force_click=True if force_set else False) self.clear() self.send_keys(val) actual = self.get_attribute('value') if val != actual: if force_set: js_executor = self.driver_wrapper.js_executor def force_set_element(): """ Wrapper to force_set element via javascript if needed """ js_executor.execute_template('setValueTemplate', {'value': val}, self.element) return True self.execute_and_handle_webelement_exceptions(force_set_element, 'set element by javascript') else: self.driver_wrapper.assertion.fail( 'Setting text field failed because final text did not match input value: "{}" != "{}"'.format( actual, val ) ) return self
[ "def", "set", "(", "self", ",", "val", ",", "force_set", "=", "False", ")", ":", "if", "val", "is", "None", ":", "val", "=", "\"\"", "self", ".", "click", "(", "force_click", "=", "True", "if", "force_set", "else", "False", ")", "self", ".", "clear", "(", ")", "self", ".", "send_keys", "(", "val", ")", "actual", "=", "self", ".", "get_attribute", "(", "'value'", ")", "if", "val", "!=", "actual", ":", "if", "force_set", ":", "js_executor", "=", "self", ".", "driver_wrapper", ".", "js_executor", "def", "force_set_element", "(", ")", ":", "\"\"\"\n Wrapper to force_set element via javascript if needed\n \"\"\"", "js_executor", ".", "execute_template", "(", "'setValueTemplate'", ",", "{", "'value'", ":", "val", "}", ",", "self", ".", "element", ")", "return", "True", "self", ".", "execute_and_handle_webelement_exceptions", "(", "force_set_element", ",", "'set element by javascript'", ")", "else", ":", "self", ".", "driver_wrapper", ".", "assertion", ".", "fail", "(", "'Setting text field failed because final text did not match input value: \"{}\" != \"{}\"'", ".", "format", "(", "actual", ",", "val", ")", ")", "return", "self" ]
Sets an input with a specified value; if force_set=True, will set through javascript if webdriver fails NOTE: if val is None, this function will interpret this to be an empty string @type val: str @param val: string to send to element @type force_set: bool @param force_set: Use javascript if True, webdriver if False
[ "Sets", "an", "input", "with", "a", "specified", "value", ";", "if", "force_set", "=", "True", "will", "set", "through", "javascript", "if", "webdriver", "fails", "NOTE", ":", "if", "val", "is", "None", "this", "function", "will", "interpret", "this", "to", "be", "an", "empty", "string" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L311-L347
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.submit
def submit(self): """ Submit a webe element @rtype: WebElementWrapper @return: Self """ def submit_element(): """ Wrapper to submit element """ return self.element.submit() self.execute_and_handle_webelement_exceptions(submit_element, 'send keys') return self
python
def submit(self): """ Submit a webe element @rtype: WebElementWrapper @return: Self """ def submit_element(): """ Wrapper to submit element """ return self.element.submit() self.execute_and_handle_webelement_exceptions(submit_element, 'send keys') return self
[ "def", "submit", "(", "self", ")", ":", "def", "submit_element", "(", ")", ":", "\"\"\"\n Wrapper to submit element\n \"\"\"", "return", "self", ".", "element", ".", "submit", "(", ")", "self", ".", "execute_and_handle_webelement_exceptions", "(", "submit_element", ",", "'send keys'", ")", "return", "self" ]
Submit a webe element @rtype: WebElementWrapper @return: Self
[ "Submit", "a", "webe", "element" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L349-L362
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.value_of_css_property
def value_of_css_property(self, property_name): """ Get value of CSS property for element @rtype: str @return: value of CSS property """ def value_of_css_property_element(): """ Wrapper to get css property """ return self.element.value_of_css_property(property_name) return self.execute_and_handle_webelement_exceptions(value_of_css_property_element, 'get css property "' + str(property_name) + '"')
python
def value_of_css_property(self, property_name): """ Get value of CSS property for element @rtype: str @return: value of CSS property """ def value_of_css_property_element(): """ Wrapper to get css property """ return self.element.value_of_css_property(property_name) return self.execute_and_handle_webelement_exceptions(value_of_css_property_element, 'get css property "' + str(property_name) + '"')
[ "def", "value_of_css_property", "(", "self", ",", "property_name", ")", ":", "def", "value_of_css_property_element", "(", ")", ":", "\"\"\"\n Wrapper to get css property\n \"\"\"", "return", "self", ".", "element", ".", "value_of_css_property", "(", "property_name", ")", "return", "self", ".", "execute_and_handle_webelement_exceptions", "(", "value_of_css_property_element", ",", "'get css property \"'", "+", "str", "(", "property_name", ")", "+", "'\"'", ")" ]
Get value of CSS property for element @rtype: str @return: value of CSS property
[ "Get", "value", "of", "CSS", "property", "for", "element" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L364-L377
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.has_class
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) )
python
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) )
[ "def", "has_class", "(", "self", ",", "classname", ")", ":", "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", ")", ")" ]
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
[ "Test", "if", "an", "element", "has", "a", "specific", "classname" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L379-L400
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.parent
def parent(self): """ Get the parent of the element @rtype: WebElementWrapper @return: Parent of webelementwrapper on which this was invoked """ def parent_element(): """ Wrapper to retrieve parent element """ return WebElementWrapper(self.driver_wrapper, self.locator, self.element.parent) return self.execute_and_handle_webelement_exceptions(parent_element, 'get parent')
python
def parent(self): """ Get the parent of the element @rtype: WebElementWrapper @return: Parent of webelementwrapper on which this was invoked """ def parent_element(): """ Wrapper to retrieve parent element """ return WebElementWrapper(self.driver_wrapper, self.locator, self.element.parent) return self.execute_and_handle_webelement_exceptions(parent_element, 'get parent')
[ "def", "parent", "(", "self", ")", ":", "def", "parent_element", "(", ")", ":", "\"\"\"\n Wrapper to retrieve parent element\n \"\"\"", "return", "WebElementWrapper", "(", "self", ".", "driver_wrapper", ",", "self", ".", "locator", ",", "self", ".", "element", ".", "parent", ")", "return", "self", ".", "execute_and_handle_webelement_exceptions", "(", "parent_element", ",", "'get parent'", ")" ]
Get the parent of the element @rtype: WebElementWrapper @return: Parent of webelementwrapper on which this was invoked
[ "Get", "the", "parent", "of", "the", "element" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L431-L443
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.parent_element
def parent_element(self): """ Get the parent of the element @rtype: WebElementWrapper @return: Parent of webelementwrapper on which this was invoked """ def parent_element(): """ Wrapper to get parent element """ parent = self.driver_wrapper.execute_script('return arguments[0].parentNode;', self.element) wrapped_parent = WebElementWrapper(self.driver_wrapper, '', parent) return wrapped_parent return self.execute_and_handle_webelement_exceptions(parent_element, 'get parent element')
python
def parent_element(self): """ Get the parent of the element @rtype: WebElementWrapper @return: Parent of webelementwrapper on which this was invoked """ def parent_element(): """ Wrapper to get parent element """ parent = self.driver_wrapper.execute_script('return arguments[0].parentNode;', self.element) wrapped_parent = WebElementWrapper(self.driver_wrapper, '', parent) return wrapped_parent return self.execute_and_handle_webelement_exceptions(parent_element, 'get parent element')
[ "def", "parent_element", "(", "self", ")", ":", "def", "parent_element", "(", ")", ":", "\"\"\"\n Wrapper to get parent element\n \"\"\"", "parent", "=", "self", ".", "driver_wrapper", ".", "execute_script", "(", "'return arguments[0].parentNode;'", ",", "self", ".", "element", ")", "wrapped_parent", "=", "WebElementWrapper", "(", "self", ".", "driver_wrapper", ",", "''", ",", "parent", ")", "return", "wrapped_parent", "return", "self", ".", "execute_and_handle_webelement_exceptions", "(", "parent_element", ",", "'get parent element'", ")" ]
Get the parent of the element @rtype: WebElementWrapper @return: Parent of webelementwrapper on which this was invoked
[ "Get", "the", "parent", "of", "the", "element" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L445-L460
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.text
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')
python
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')
[ "def", "text", "(", "self", ",", "force_get", "=", "False", ")", ":", "def", "text_element", "(", ")", ":", "\"\"\"\n Wrapper to get text of element\n \"\"\"", "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'", ")" ]
Get the text of the element @rtype: str @return: Text of the element
[ "Get", "the", "text", "of", "the", "element" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L490-L512
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.highlight
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
python
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
[ "def", "highlight", "(", "self", ")", ":", "js_executor", "=", "self", ".", "driver_wrapper", ".", "js_executor", "def", "highlight_element", "(", ")", ":", "\"\"\"\n Wrapper to highlight elements\n \"\"\"", "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" ]
Draws a dotted red box around the wrapped element using javascript @rtype: WebElementWrapper @return: Self
[ "Draws", "a", "dotted", "red", "box", "around", "the", "wrapped", "element", "using", "javascript" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L514-L535
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.set_attribute
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
python
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
[ "def", "set_attribute", "(", "self", ",", "name", ",", "value", ")", ":", "js_executor", "=", "self", ".", "driver_wrapper", ".", "js_executor", "def", "set_attribute_element", "(", ")", ":", "\"\"\"\n Wrapper to set attribute\n \"\"\"", "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" ]
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
[ "Sets", "the", "attribute", "of", "the", "element", "to", "a", "specified", "value" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L537-L556
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.select_option
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')
python
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')
[ "def", "select_option", "(", "self", ",", "value", "=", "None", ",", "text", "=", "None", ",", "index", "=", "None", ")", ":", "def", "do_select", "(", ")", ":", "\"\"\"\n Perform selection\n \"\"\"", "return", "self", ".", "set_select", "(", "'select'", ",", "value", ",", "text", ",", "index", ")", "return", "self", ".", "execute_and_handle_webelement_exceptions", "(", "do_select", ",", "'select option'", ")" ]
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
[ "Selects", "an", "option", "by", "value", "text", "or", "index", ".", "You", "must", "name", "the", "parameter" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L560-L579
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.deselect_option
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')
python
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')
[ "def", "deselect_option", "(", "self", ",", "value", "=", "None", ",", "text", "=", "None", ",", "index", "=", "None", ")", ":", "def", "do_deselect", "(", ")", ":", "\"\"\"\n Perform selection\n \"\"\"", "return", "self", ".", "set_select", "(", "'deselect'", ",", "value", ",", "text", ",", "index", ")", "return", "self", ".", "execute_and_handle_webelement_exceptions", "(", "do_deselect", ",", "'deselect option'", ")" ]
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
[ "De", "-", "selects", "an", "option", "by", "value", "text", "or", "index", ".", "You", "must", "name", "the", "parameter" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L581-L600
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.set_select
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
python
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
[ "def", "set_select", "(", "self", ",", "select_or_deselect", "=", "'select'", ",", "value", "=", "None", ",", "text", "=", "None", ",", "index", "=", "None", ")", ":", "# 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" ]
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
[ "Private", "method", "used", "by", "select", "methods" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L616-L653
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.checkbox_check
def checkbox_check(self, force_check=False): """ Wrapper to check a checkbox """ if not self.get_attribute('checked'): self.click(force_click=force_check)
python
def checkbox_check(self, force_check=False): """ Wrapper to check a checkbox """ if not self.get_attribute('checked'): self.click(force_click=force_check)
[ "def", "checkbox_check", "(", "self", ",", "force_check", "=", "False", ")", ":", "if", "not", "self", ".", "get_attribute", "(", "'checked'", ")", ":", "self", ".", "click", "(", "force_click", "=", "force_check", ")" ]
Wrapper to check a checkbox
[ "Wrapper", "to", "check", "a", "checkbox" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L655-L660
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.checkbox_uncheck
def checkbox_uncheck(self, force_check=False): """ Wrapper to uncheck a checkbox """ if self.get_attribute('checked'): self.click(force_click=force_check)
python
def checkbox_uncheck(self, force_check=False): """ Wrapper to uncheck a checkbox """ if self.get_attribute('checked'): self.click(force_click=force_check)
[ "def", "checkbox_uncheck", "(", "self", ",", "force_check", "=", "False", ")", ":", "if", "self", ".", "get_attribute", "(", "'checked'", ")", ":", "self", ".", "click", "(", "force_click", "=", "force_check", ")" ]
Wrapper to uncheck a checkbox
[ "Wrapper", "to", "uncheck", "a", "checkbox" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L662-L667
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.hover
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')
python
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')
[ "def", "hover", "(", "self", ")", ":", "def", "do_hover", "(", ")", ":", "\"\"\"\n Perform hover\n \"\"\"", "ActionChains", "(", "self", ".", "driver_wrapper", ".", "driver", ")", ".", "move_to_element", "(", "self", ".", "element", ")", ".", "perform", "(", ")", "return", "self", ".", "execute_and_handle_webelement_exceptions", "(", "do_hover", ",", "'hover'", ")" ]
Hovers the element
[ "Hovers", "the", "element" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L677-L686
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.find
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 )
python
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 )
[ "def", "find", "(", "self", ",", "locator", ",", "find_all", "=", "False", ",", "search_object", "=", "None", ",", "exclude_invisible", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "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", ")" ]
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
[ "Find", "wrapper", "invokes", "webDriverWrapper", "find", "with", "the", "current", "element", "as", "the", "search", "object" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L688-L708
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.find_once
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
python
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
[ "def", "find_once", "(", "self", ",", "locator", ")", ":", "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" ]
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
[ "Find", "wrapper", "to", "run", "a", "single", "find" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L710-L735
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.find_all
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)
python
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)
[ "def", "find_all", "(", "self", ",", "locator", ")", ":", "return", "self", ".", "driver_wrapper", ".", "find", "(", "locator", ",", "True", ",", "self", ".", "element", ")" ]
Find wrapper, finds all elements @type locator: webdriverwrapper.support.locator.Locator @param locator: locator used in search @rtype: list @return: A list of WebElementWrappers
[ "Find", "wrapper", "finds", "all", "elements" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L737-L747
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.is_present
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)
python
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)
[ "def", "is_present", "(", "self", ",", "locator", ")", ":", "return", "self", ".", "driver_wrapper", ".", "is_present", "(", "locator", ",", "search_object", "=", "self", ".", "element", ")" ]
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
[ "Tests", "to", "see", "if", "an", "element", "is", "present" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L749-L759
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.wait_until_stale
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')
python
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')
[ "def", "wait_until_stale", "(", "self", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "driver_wrapper", ".", "timeout", "def", "wait", "(", ")", ":", "\"\"\"\n Wrapper to wait for element to be stale\n \"\"\"", "WebDriverWait", "(", "self", ".", "driver", ",", "timeout", ")", ".", "until", "(", "EC", ".", "staleness_of", "(", "self", ".", "element", ")", ")", "return", "self", "return", "self", ".", "execute_and_handle_webelement_exceptions", "(", "wait", ",", "'wait for staleness'", ")" ]
Waits for the element to go stale in the DOM @type timeout: int @param timeout: override for default timeout @rtype: WebElementWrapper @return: Self
[ "Waits", "for", "the", "element", "to", "go", "stale", "in", "the", "DOM" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L774-L793
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.execute_and_handle_webelement_exceptions
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))
python
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))
[ "def", "execute_and_handle_webelement_exceptions", "(", "self", ",", "function_to_execute", ",", "name_of_action", ")", ":", "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", ")", ")" ]
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
[ "Private", "method", "to", "be", "called", "by", "other", "methods", "to", "handle", "common", "WebDriverExceptions", "or", "throw", "a", "custom", "exception" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L795-L850
Shapeways/coyote_framework
coyote_framework/requests/requestdriver.py
RequestDriver.request
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
python
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
[ "def", "request", "(", "self", ",", "uri", ",", "method", "=", "GET", ",", "headers", "=", "None", ",", "cookies", "=", "None", ",", "params", "=", "None", ",", "data", "=", "None", ",", "post_files", "=", "None", ",", "*", "*", "kwargs", ")", ":", "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" ]
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
[ "Makes", "a", "request", "using", "requests" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/requests/requestdriver.py#L34-L80
Shapeways/coyote_framework
coyote_framework/requests/requestdriver.py
RequestDriver.save_last_response_to_file
def save_last_response_to_file(self, filename): """Saves the body of the last response to a file @param filename: Filename to save to @return: Returns False if there is an OS error, True if successful """ response = self.get_last_response() return self.save_response_to_file(response, filename)
python
def save_last_response_to_file(self, filename): """Saves the body of the last response to a file @param filename: Filename to save to @return: Returns False if there is an OS error, True if successful """ response = self.get_last_response() return self.save_response_to_file(response, filename)
[ "def", "save_last_response_to_file", "(", "self", ",", "filename", ")", ":", "response", "=", "self", ".", "get_last_response", "(", ")", "return", "self", ".", "save_response_to_file", "(", "response", ",", "filename", ")" ]
Saves the body of the last response to a file @param filename: Filename to save to @return: Returns False if there is an OS error, True if successful
[ "Saves", "the", "body", "of", "the", "last", "response", "to", "a", "file" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/requests/requestdriver.py#L96-L103
Shapeways/coyote_framework
coyote_framework/requests/requestdriver.py
RequestDriver.save_response_to_file
def save_response_to_file(self, response, filename): """Saves the body of the last response to a file @param filename: Filename to save to @return: Returns False if there is an OS error, True if successful """ try: last_response = self.get_last_response() with open(filename, 'w') as f: f.write(last_response.content) except OSError, e: return False return True
python
def save_response_to_file(self, response, filename): """Saves the body of the last response to a file @param filename: Filename to save to @return: Returns False if there is an OS error, True if successful """ try: last_response = self.get_last_response() with open(filename, 'w') as f: f.write(last_response.content) except OSError, e: return False return True
[ "def", "save_response_to_file", "(", "self", ",", "response", ",", "filename", ")", ":", "try", ":", "last_response", "=", "self", ".", "get_last_response", "(", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "last_response", ".", "content", ")", "except", "OSError", ",", "e", ":", "return", "False", "return", "True" ]
Saves the body of the last response to a file @param filename: Filename to save to @return: Returns False if there is an OS error, True if successful
[ "Saves", "the", "body", "of", "the", "last", "response", "to", "a", "file" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/requests/requestdriver.py#L105-L117
Shapeways/coyote_framework
coyote_framework/mixins/URLValidator.py
validate_url
def validate_url(url, allowed_response_codes=None): """Validates that the url can be opened and responds with an allowed response code; ignores javascript: urls url -- the string url to ping allowed_response_codes -- a list of response codes that the validator will ignore """ allowed_response_codes = [200] if allowed_response_codes is None else allowed_response_codes # link calls a js function, do not try to open if str(url).startswith('javascript:'): return True try: response = urllib2.urlopen(urllib2.Request(url)) except urllib2.URLError: raise AssertionError('Url was invalid and could not be opened: {url}'.format(url=url)) if response.code not in allowed_response_codes: raise AssertionError('Invalid response code {response_code} from url: {url}' .format(response_code=response.code, url=url)) return True
python
def validate_url(url, allowed_response_codes=None): """Validates that the url can be opened and responds with an allowed response code; ignores javascript: urls url -- the string url to ping allowed_response_codes -- a list of response codes that the validator will ignore """ allowed_response_codes = [200] if allowed_response_codes is None else allowed_response_codes # link calls a js function, do not try to open if str(url).startswith('javascript:'): return True try: response = urllib2.urlopen(urllib2.Request(url)) except urllib2.URLError: raise AssertionError('Url was invalid and could not be opened: {url}'.format(url=url)) if response.code not in allowed_response_codes: raise AssertionError('Invalid response code {response_code} from url: {url}' .format(response_code=response.code, url=url)) return True
[ "def", "validate_url", "(", "url", ",", "allowed_response_codes", "=", "None", ")", ":", "allowed_response_codes", "=", "[", "200", "]", "if", "allowed_response_codes", "is", "None", "else", "allowed_response_codes", "# link calls a js function, do not try to open", "if", "str", "(", "url", ")", ".", "startswith", "(", "'javascript:'", ")", ":", "return", "True", "try", ":", "response", "=", "urllib2", ".", "urlopen", "(", "urllib2", ".", "Request", "(", "url", ")", ")", "except", "urllib2", ".", "URLError", ":", "raise", "AssertionError", "(", "'Url was invalid and could not be opened: {url}'", ".", "format", "(", "url", "=", "url", ")", ")", "if", "response", ".", "code", "not", "in", "allowed_response_codes", ":", "raise", "AssertionError", "(", "'Invalid response code {response_code} from url: {url}'", ".", "format", "(", "response_code", "=", "response", ".", "code", ",", "url", "=", "url", ")", ")", "return", "True" ]
Validates that the url can be opened and responds with an allowed response code; ignores javascript: urls url -- the string url to ping allowed_response_codes -- a list of response codes that the validator will ignore
[ "Validates", "that", "the", "url", "can", "be", "opened", "and", "responds", "with", "an", "allowed", "response", "code", ";", "ignores", "javascript", ":", "urls" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/mixins/URLValidator.py#L6-L26
Shapeways/coyote_framework
coyote_framework/mixins/URLValidator.py
validate_urls
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
python
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
[ "def", "validate_urls", "(", "urls", ",", "allowed_response_codes", "=", "None", ")", ":", "for", "url", "in", "urls", ":", "validate_url", "(", "url", ",", "allowed_response_codes", "=", "allowed_response_codes", ")", "return", "True" ]
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
[ "Validates", "that", "a", "list", "of", "urls", "can", "be", "opened", "and", "each", "responds", "with", "an", "allowed", "response", "code" ]
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/mixins/URLValidator.py#L29-L38