signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
---|---|---|---|
def remove_all_matching(self, address=None, name=None): | if self.entries:<EOL><INDENT>if address and name:<EOL><INDENT>func = lambda entry: not entry.is_real_entry() or (entry.address != address and name not in entry.names)<EOL><DEDENT>elif address:<EOL><INDENT>func = lambda entry: not entry.is_real_entry() or entry.address != address<EOL><DEDENT>elif name:<EOL><INDENT>func = lambda entry: not entry.is_real_entry() or name not in entry.names<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self.entries = list(filter(func, self.entries))<EOL><DEDENT> | Remove all HostsEntry instances from the Hosts object
where the supplied ip address or name matches
:param address: An ipv4 or ipv6 address
:param name: A host name
:return: None | f2656:c1:m8 |
def import_url(self, url=None, force=None): | file_contents = self.get_hosts_by_url(url=url).decode('<STR_LIT:utf-8>')<EOL>file_contents = file_contents.rstrip().replace('<STR_LIT>', '<STR_LIT:\n>')<EOL>file_contents = file_contents.rstrip().replace('<STR_LIT:\r\n>', '<STR_LIT:\n>')<EOL>lines = file_contents.split('<STR_LIT:\n>')<EOL>skipped = <NUM_LIT:0><EOL>import_entries = []<EOL>for line in lines:<EOL><INDENT>stripped_entry = line.strip()<EOL>if (not stripped_entry) or (stripped_entry.startswith('<STR_LIT:#>')):<EOL><INDENT>skipped += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>line = line.partition('<STR_LIT:#>')[<NUM_LIT:0>]<EOL>line = line.rstrip()<EOL>import_entry = HostsEntry.str_to_hostentry(line)<EOL>if import_entry:<EOL><INDENT>import_entries.append(import_entry)<EOL><DEDENT><DEDENT><DEDENT>add_result = self.add(entries=import_entries, force=force)<EOL>write_result = self.write()<EOL>return {'<STR_LIT:result>': '<STR_LIT:success>',<EOL>'<STR_LIT>': skipped,<EOL>'<STR_LIT>': add_result,<EOL>'<STR_LIT>': write_result}<EOL> | Read a list of host entries from a URL, convert them into instances of HostsEntry and
then append to the list of entries in Hosts
:param url: The URL of where to download a hosts file
:return: Counts reflecting the attempted additions | f2656:c1:m9 |
def import_file(self, import_file_path=None): | skipped = <NUM_LIT:0><EOL>invalid_count = <NUM_LIT:0><EOL>if is_readable(import_file_path):<EOL><INDENT>import_entries = []<EOL>with open(import_file_path, '<STR_LIT:r>') as infile:<EOL><INDENT>for line in infile:<EOL><INDENT>stripped_entry = line.strip()<EOL>if (not stripped_entry) or (stripped_entry.startswith('<STR_LIT:#>')):<EOL><INDENT>skipped += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>line = line.partition('<STR_LIT:#>')[<NUM_LIT:0>]<EOL>line = line.rstrip()<EOL>import_entry = HostsEntry.str_to_hostentry(line)<EOL>if import_entry:<EOL><INDENT>import_entries.append(import_entry)<EOL><DEDENT>else:<EOL><INDENT>invalid_count += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT><DEDENT>add_result = self.add(entries=import_entries)<EOL>write_result = self.write()<EOL>return {'<STR_LIT:result>': '<STR_LIT:success>',<EOL>'<STR_LIT>': skipped,<EOL>'<STR_LIT>': invalid_count,<EOL>'<STR_LIT>': add_result,<EOL>'<STR_LIT>': write_result}<EOL><DEDENT>else:<EOL><INDENT>return {'<STR_LIT:result>': '<STR_LIT>',<EOL>'<STR_LIT:message>': '<STR_LIT>'.format(import_file_path)}<EOL><DEDENT> | Read a list of host entries from a file, convert them into instances
of HostsEntry and then append to the list of entries in Hosts
:param import_file_path: The path to the file containing the host entries
:return: Counts reflecting the attempted additions | f2656:c1:m10 |
def add(self, entries=None, force=False, allow_address_duplication=False): | ipv4_count = <NUM_LIT:0><EOL>ipv6_count = <NUM_LIT:0><EOL>comment_count = <NUM_LIT:0><EOL>invalid_count = <NUM_LIT:0><EOL>duplicate_count = <NUM_LIT:0><EOL>replaced_count = <NUM_LIT:0><EOL>import_entries = []<EOL>existing_addresses = [x.address for x in self.entries if x.address]<EOL>existing_names = []<EOL>for item in self.entries:<EOL><INDENT>if item.names:<EOL><INDENT>existing_names.extend(item.names)<EOL><DEDENT><DEDENT>existing_names = dedupe_list(existing_names)<EOL>for entry in entries:<EOL><INDENT>if entry.entry_type == '<STR_LIT>':<EOL><INDENT>entry.comment = entry.comment.strip()<EOL>if entry.comment[<NUM_LIT:0>] != "<STR_LIT:#>":<EOL><INDENT>entry.comment = "<STR_LIT>" + entry.comment<EOL><DEDENT>import_entries.append(entry)<EOL><DEDENT>elif entry.address in ('<STR_LIT>', '<STR_LIT:127.0.0.1>') or allow_address_duplication:<EOL><INDENT>if set(entry.names).intersection(existing_names):<EOL><INDENT>if force:<EOL><INDENT>for name in entry.names:<EOL><INDENT>self.remove_all_matching(name=name)<EOL><DEDENT>import_entries.append(entry)<EOL><DEDENT>else:<EOL><INDENT>duplicate_count += <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>import_entries.append(entry)<EOL><DEDENT><DEDENT>elif entry.address in existing_addresses:<EOL><INDENT>if not force:<EOL><INDENT>duplicate_count += <NUM_LIT:1><EOL><DEDENT>elif force:<EOL><INDENT>self.remove_all_matching(address=entry.address)<EOL>replaced_count += <NUM_LIT:1><EOL>import_entries.append(entry)<EOL><DEDENT><DEDENT>elif set(entry.names).intersection(existing_names):<EOL><INDENT>if not force:<EOL><INDENT>duplicate_count += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>for name in entry.names:<EOL><INDENT>self.remove_all_matching(name=name)<EOL><DEDENT>replaced_count += <NUM_LIT:1><EOL>import_entries.append(entry)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>import_entries.append(entry)<EOL><DEDENT><DEDENT>for item in import_entries:<EOL><INDENT>if item.entry_type == '<STR_LIT>':<EOL><INDENT>comment_count += <NUM_LIT:1><EOL>self.entries.append(item)<EOL><DEDENT>elif item.entry_type == '<STR_LIT>':<EOL><INDENT>ipv4_count += <NUM_LIT:1><EOL>self.entries.append(item)<EOL><DEDENT>elif item.entry_type == '<STR_LIT>':<EOL><INDENT>ipv6_count += <NUM_LIT:1><EOL>self.entries.append(item)<EOL><DEDENT><DEDENT>return {'<STR_LIT>': comment_count,<EOL>'<STR_LIT>': ipv4_count,<EOL>'<STR_LIT>': ipv6_count,<EOL>'<STR_LIT>': invalid_count,<EOL>'<STR_LIT>': duplicate_count,<EOL>'<STR_LIT>': replaced_count}<EOL> | Add instances of HostsEntry to the instance of Hosts.
:param entries: A list of instances of HostsEntry
:param force: Remove matching before adding
:param allow_address_duplication: Allow using multiple entries for same address
:return: The counts of successes and failures | f2656:c1:m11 |
def populate_entries(self): | try:<EOL><INDENT>with open(self.hosts_path, '<STR_LIT:r>') as hosts_file:<EOL><INDENT>hosts_entries = [line for line in hosts_file]<EOL>for hosts_entry in hosts_entries:<EOL><INDENT>entry_type = HostsEntry.get_entry_type(hosts_entry)<EOL>if entry_type == "<STR_LIT>":<EOL><INDENT>hosts_entry = hosts_entry.replace("<STR_LIT:\r>", "<STR_LIT>")<EOL>hosts_entry = hosts_entry.replace("<STR_LIT:\n>", "<STR_LIT>")<EOL>self.entries.append(HostsEntry(entry_type="<STR_LIT>",<EOL>comment=hosts_entry))<EOL><DEDENT>elif entry_type == "<STR_LIT:blank>":<EOL><INDENT>self.entries.append(HostsEntry(entry_type="<STR_LIT:blank>"))<EOL><DEDENT>elif entry_type in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>chunked_entry = hosts_entry.split()<EOL>stripped_name_list = [name.strip() for name in chunked_entry[<NUM_LIT:1>:]]<EOL>self.entries.append(<EOL>HostsEntry(<EOL>entry_type=entry_type,<EOL>address=chunked_entry[<NUM_LIT:0>].strip(),<EOL>names=stripped_name_list))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except IOError:<EOL><INDENT>return {'<STR_LIT:result>': '<STR_LIT>',<EOL>'<STR_LIT:message>': '<STR_LIT>'.format(self.hosts_path)}<EOL><DEDENT> | Called by the initialiser of Hosts. This reads the entries from the local hosts file,
converts them into instances of HostsEntry and adds them to the Hosts list of entries.
:return: None | f2656:c1:m12 |
@register.tag<EOL>def top_objects(parser, token): | return TopObjectsNode.handle_token(parser, token)<EOL> | Usage::
{% top_objects "auth.User" as top_users limit 10 %}
or::
{% top_objects "auth.User" as top_users %}
or::
{% top_objects "auth.User" as top_users limit 10 timeframe 7 days %}
All variations return a queryset of the model passed in with points annotated. | f2667:m4 |
@register.tag<EOL>def points_for_object(parser, token): | return PointsForObjectNode.handle_token(parser, token)<EOL> | Gets the current points for an object, usage:
{% points_for_object user %}
or
{% points_for_object user as points %}
or
{% points_for_object user limit 7 days as points %} | f2667:m5 |
@register.tag<EOL>def user_has_voted(parser, token): | return UserHasVotedNode.handle_token(parser, token)<EOL> | Usage::
{% user_has_voted user obj as var %} | f2667:m6 |
def award_points(target, key, reason="<STR_LIT>", source=None): | point_value, points = get_points(key)<EOL>if not ALLOW_NEGATIVE_TOTALS:<EOL><INDENT>total = points_awarded(target)<EOL>if total + points < <NUM_LIT:0>:<EOL><INDENT>reason = reason + "<STR_LIT>".format(points)<EOL>points = -total<EOL><DEDENT><DEDENT>apv = AwardedPointValue(points=points, value=point_value, reason=reason)<EOL>if isinstance(target, get_user_model()):<EOL><INDENT>apv.target_user = target<EOL>lookup_params = {<EOL>"<STR_LIT>": target<EOL>}<EOL><DEDENT>else:<EOL><INDENT>apv.target_object = target<EOL>lookup_params = {<EOL>"<STR_LIT>": apv.target_content_type,<EOL>"<STR_LIT>": apv.target_object_id,<EOL>}<EOL><DEDENT>if source is not None:<EOL><INDENT>if isinstance(source, get_user_model()):<EOL><INDENT>apv.source_user = source<EOL><DEDENT>else:<EOL><INDENT>apv.source_object = source<EOL><DEDENT><DEDENT>apv.save()<EOL>if not TargetStat.update_points(points, lookup_params):<EOL><INDENT>try:<EOL><INDENT>sid = transaction.savepoint()<EOL>TargetStat._default_manager.create(<EOL>**dict(lookup_params, points=points)<EOL>)<EOL>transaction.savepoint_commit(sid)<EOL><DEDENT>except IntegrityError:<EOL><INDENT>transaction.savepoint_rollback(sid)<EOL>TargetStat.update_points(points, lookup_params)<EOL><DEDENT><DEDENT>signals.points_awarded.send(<EOL>sender=target.__class__,<EOL>target=target,<EOL>key=key,<EOL>points=points,<EOL>source=source<EOL>)<EOL>new_points = points_awarded(target)<EOL>old_points = new_points - points<EOL>TargetStat.update_positions((old_points, new_points))<EOL>return apv<EOL> | Awards target the point value for key. If key is an integer then it's a
one off assignment and should be interpreted as the actual point value. | f2672:m1 |
def points_awarded(target=None, source=None, since=None): | lookup_params = {}<EOL>if target is not None:<EOL><INDENT>if isinstance(target, get_user_model()):<EOL><INDENT>lookup_params["<STR_LIT>"] = target<EOL><DEDENT>else:<EOL><INDENT>lookup_params.update({<EOL>"<STR_LIT>": ContentType.objects.get_for_model(target),<EOL>"<STR_LIT>": target.pk,<EOL>})<EOL><DEDENT><DEDENT>if source is not None:<EOL><INDENT>if isinstance(source, get_user_model()):<EOL><INDENT>lookup_params["<STR_LIT>"] = source<EOL><DEDENT>else:<EOL><INDENT>lookup_params.update({<EOL>"<STR_LIT>": ContentType.objects.get_for_model(source),<EOL>"<STR_LIT>": source.pk,<EOL>})<EOL><DEDENT><DEDENT>if since is None:<EOL><INDENT>if target is not None and source is None:<EOL><INDENT>try:<EOL><INDENT>return TargetStat.objects.get(**lookup_params).points<EOL><DEDENT>except TargetStat.DoesNotExist:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT><DEDENT>else:<EOL><INDENT>return AwardedPointValue.points_awarded(**lookup_params)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>lookup_params["<STR_LIT>"] = since<EOL>return AwardedPointValue.points_awarded(**lookup_params)<EOL><DEDENT> | Determine out how many points the given target has received. | f2672:m2 |
@property<EOL><INDENT>def target(self):<DEDENT> | if self.target_user_id:<EOL><INDENT>return self.target_user<EOL><DEDENT>else:<EOL><INDENT>return self.target_object<EOL><DEDENT> | Abstraction to getting the target object of this stat object. | f2672:c2:m2 |
@property<EOL><INDENT>def source(self):<DEDENT> | return self.source_object<EOL> | Match the ``target`` abstraction so the interface is consistent. | f2672:c2:m3 |
def merge(dict_1, dict_2): | return dict((str(key), dict_1.get(key) or dict_2.get(key))<EOL>for key in set(dict_2) | set(dict_1))<EOL> | Merge two dictionaries. Values that evaluate to true take priority over
falsy values. `dict_1` takes priority over `dict_2`.
https://github.com/docopt/docopt/blob/
5112ecc663a18a0b25c361b2a30c55b64311d285/examples/
config_file_example.py#L53 | f2675:m0 |
def validate(args): | provided = {key: val for key, val in args.iteritems() if val is not None}<EOL>schema = Schema({<EOL>'<STR_LIT>': And(str, len, Use(str.lower)),<EOL>'<STR_LIT>': And(str, len, Use(str.lower)),<EOL>'<STR_LIT>': os.path.isfile,<EOL>Optional('<STR_LIT>'): Use(bool),<EOL>Optional('<STR_LIT>'): Use(bool),<EOL>Optional('<STR_LIT>'): Use(bool),<EOL>Optional('<STR_LIT>'): Use(bool),<EOL>Optional('<STR_LIT>'): Use(bool),<EOL>Optional('<STR_LIT>'): Use(bool),<EOL>Optional('<STR_LIT>'): Use(bool),<EOL>Optional('<STR_LIT>'): Use(bool),<EOL>Optional('<STR_LIT>'): And(str, len),<EOL>Optional('<STR_LIT>'): Use(int),<EOL>Optional('<STR_LIT>'): And(str, len, Use(str.lower)),<EOL>Optional('<STR_LIT>'): Use(int),<EOL>Optional('<STR_LIT>'): And(str, len),<EOL>Optional('<STR_LIT>'): os.path.isfile,<EOL>Optional('<STR_LIT>'): And(str, len, Use(str.lower)),<EOL>Optional('<STR_LIT>'): And(str, len, Use(str.lower)),<EOL>})<EOL>try:<EOL><INDENT>return merge(schema.validate(provided), args)<EOL><DEDENT>except SchemaError as ex:<EOL><INDENT>abort("<STR_LIT>".format(ex.message))<EOL><DEDENT> | Validate args | f2675:m1 |
def load_args(args): | config = kaptan.Kaptan(handler='<STR_LIT>')<EOL>conf_parent = os.path.expanduser('<STR_LIT>')<EOL>conf_app = '<STR_LIT>'<EOL>conf_filename = '<STR_LIT>'<EOL>conf_dir = os.path.join(conf_parent, conf_app)<EOL>for loc in [os.curdir, conf_dir]:<EOL><INDENT>configpath = os.path.join(loc, conf_filename)<EOL>try:<EOL><INDENT>if os.path.isfile(configpath):<EOL><INDENT>config.import_config(configpath)<EOL>break<EOL><DEDENT><DEDENT>except (ValueError, ParserError, ScannerError):<EOL><INDENT>warn("<STR_LIT>".format(configpath))<EOL><DEDENT><DEDENT>config = (config.configuration_data<EOL>if config.configuration_data is not None else {})<EOL>for key, val in config.items():<EOL><INDENT>config['<STR_LIT>'+key] = val<EOL>del config[key]<EOL><DEDENT>return validate(merge(args, config))<EOL> | Load a config file. Merges CLI args and validates. | f2675:m2 |
def api_call(endpoint, args, payload): | headers = {'<STR_LIT>': '<STR_LIT>'}<EOL>url = '<STR_LIT>'.format(args['<STR_LIT>'], endpoint)<EOL>attempt = <NUM_LIT:0><EOL>resp = None<EOL>while True:<EOL><INDENT>try:<EOL><INDENT>attempt += <NUM_LIT:1><EOL>resp = requests.post(<EOL>url, data=json.dumps(payload), headers=headers,<EOL>verify=args['<STR_LIT>']<EOL>)<EOL>resp.raise_for_status()<EOL>break<EOL><DEDENT>except (socket_timeout, requests.Timeout,<EOL>requests.ConnectionError, requests.URLRequired) as ex:<EOL><INDENT>abort('<STR_LIT:{}>'.format(ex))<EOL><DEDENT>except requests.HTTPError as ex:<EOL><INDENT>warn('<STR_LIT>'.format(ex))<EOL>if attempt >= <NUM_LIT:5>:<EOL><INDENT>abort('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>if resp is not None:<EOL><INDENT>try:<EOL><INDENT>return resp.json()<EOL><DEDENT>except ValueError:<EOL><INDENT>abort('<STR_LIT>'.format(resp.text))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>abort("<STR_LIT>")<EOL><DEDENT> | Generic function to call the RO API | f2679:m0 |
def engage(args, password): | if args['<STR_LIT>']:<EOL><INDENT>payload = {'<STR_LIT:Name>': args['<STR_LIT>'], '<STR_LIT>': password}<EOL>goodquit_json(api_call('<STR_LIT>', args, payload))<EOL><DEDENT>elif args['<STR_LIT>']:<EOL><INDENT>payload = {<EOL>'<STR_LIT:Name>': args['<STR_LIT>'], '<STR_LIT>': password,<EOL>'<STR_LIT>': args['<STR_LIT>'], '<STR_LIT>': args['<STR_LIT>']<EOL>}<EOL>goodquit_json(api_call('<STR_LIT>', args, payload))<EOL><DEDENT>elif args['<STR_LIT>']:<EOL><INDENT>payload = {<EOL>'<STR_LIT:Name>': args['<STR_LIT>'], '<STR_LIT>': password,<EOL>'<STR_LIT>': args['<STR_LIT>'], '<STR_LIT>': args['<STR_LIT>'].split('<STR_LIT:U+002C>'),<EOL>'<STR_LIT>': (args['<STR_LIT>'] if args['<STR_LIT>'] is None<EOL>else read_file(args['<STR_LIT>']))<EOL>}<EOL>goodquit_json(api_call('<STR_LIT>', args, payload))<EOL><DEDENT>elif args['<STR_LIT>']:<EOL><INDENT>payload = {<EOL>'<STR_LIT:Name>': args['<STR_LIT>'], '<STR_LIT>': password,<EOL>'<STR_LIT>': (args['<STR_LIT>'] if args['<STR_LIT>'] is None<EOL>else read_file(args['<STR_LIT>']))<EOL>}<EOL>goodquit_json(api_call('<STR_LIT>', args, payload))<EOL><DEDENT>elif args['<STR_LIT>']:<EOL><INDENT>payload = {'<STR_LIT:Name>': args['<STR_LIT>'], '<STR_LIT>': password}<EOL>goodquit_json(api_call('<STR_LIT>', args, payload))<EOL><DEDENT>elif args['<STR_LIT>']:<EOL><INDENT>args['<STR_LIT>'] = getpass.getpass('<STR_LIT>')<EOL>payload = {<EOL>'<STR_LIT:Name>': args['<STR_LIT>'], '<STR_LIT>': password,<EOL>'<STR_LIT>': args['<STR_LIT>']<EOL>}<EOL>goodquit_json(api_call('<STR_LIT:password>', args, payload))<EOL><DEDENT>elif args['<STR_LIT>']:<EOL><INDENT>payload = {<EOL>'<STR_LIT:Name>': args['<STR_LIT>'], '<STR_LIT>': password,<EOL>'<STR_LIT>': args['<STR_LIT>'], '<STR_LIT>': args['<STR_LIT>']<EOL>}<EOL>goodquit_json(api_call('<STR_LIT>', args, payload))<EOL><DEDENT> | Construct payloads and POST to Red October | f2680:m0 |
def string_literal(content): | if '<STR_LIT:">' in content and "<STR_LIT:'>" in content:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if '<STR_LIT:">' in content: <EOL><INDENT>content = "<STR_LIT>" % content<EOL><DEDENT>else: <EOL><INDENT>content = '<STR_LIT>' % content<EOL><DEDENT>return content<EOL> | Choose a string literal that can wrap our string.
If your string contains a ``\'`` the result will be wrapped in ``\"``.
If your string contains a ``\"`` the result will be wrapped in ``\'``.
Cannot currently handle strings which contain both ``\"`` and ``\'``. | f2685:m0 |
def element_id_by_label(browser, label): | label = ElementSelector(browser,<EOL>str('<STR_LIT>' %<EOL>string_literal(label)))<EOL>if not label:<EOL><INDENT>return False<EOL><DEDENT>return label.get_attribute('<STR_LIT>')<EOL> | The ID of an element referenced by a `label`s ``for`` attribute. The label
must be visible.
:param browser: ``world.browser``
:param label: label text to return the referenced element for
Returns: ``for`` attribute value | f2685:m1 |
def field_xpath(field, attribute): | if field in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>xpath = '<STR_LIT>'<EOL><DEDENT>elif field == '<STR_LIT>':<EOL><INDENT>if attribute == '<STR_LIT:value>':<EOL><INDENT>xpath = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>xpath = '<STR_LIT>'<EOL><DEDENT><DEDENT>elif field == '<STR_LIT>':<EOL><INDENT>field = '<STR_LIT>'<EOL>if attribute == '<STR_LIT:value>':<EOL><INDENT>xpath = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>xpath = '<STR_LIT>'<EOL><DEDENT><DEDENT>elif field == '<STR_LIT>':<EOL><INDENT>xpath = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>xpath = '<STR_LIT>'<EOL><DEDENT>return xpath.format(field=field, attr=attribute)<EOL> | Field helper functions to locate select, textarea, and the other
types of input fields (text, checkbox, radio)
:param field: One of the values 'select', 'textarea', 'option', or
'button-element' to match a corresponding HTML element (and to
match a <button> in the case of 'button-element'). Otherwise a
type to match an <input> element with a type=<field> attribute.
:param attribute: An attribute to be matched against, or 'value'
to match against the content within element being matched. | f2685:m2 |
def find_button(browser, value): | field_types = (<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT:image>',<EOL>'<STR_LIT>',<EOL>)<EOL>return reduce(<EOL>operator.add,<EOL>(find_field_with_value(browser, field_type, value)<EOL>for field_type in field_types)<EOL>)<EOL> | Find a button with the given value.
Searches for the following different kinds of buttons:
<input type="submit">
<input type="reset">
<input type="button">
<input type="image">
<button>
<{a,p,div,span,...} role="button">
Returns: an :class:`ElementSelector` | f2685:m3 |
def find_field(browser, field_type, value): | return find_field_by_id(browser, field_type, value) +find_field_by_name(browser, field_type, value) +find_field_by_label(browser, field_type, value)<EOL> | Locate an input field.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string value: an id, name or label
This first looks for `value` as the id of the element, else
the name of the element, else as a label for the element.
Returns: an :class:`ElementSelector` | f2685:m6 |
def find_any_field(browser, field_types, field_name): | return reduce(<EOL>operator.add,<EOL>(find_field(browser, field_type, field_name)<EOL>for field_type in field_types)<EOL>)<EOL> | Find a field of any of the specified types.
:param browser: ``world.browser``
:param list field_types: a list of field type (i.e. `button`)
:param string value: an id, name or label
Returns: an :class:`ElementSelector`
See also: :func:`find_field`. | f2685:m7 |
def find_field_by_id(browser, field_type, id): | return ElementSelector(<EOL>browser,<EOL>xpath=field_xpath(field_type, '<STR_LIT:id>') % string_literal(id),<EOL>filter_displayed=True,<EOL>)<EOL> | Locate the control input with the given ``id``.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string id: ``id`` attribute
Returns: an :class:`ElementSelector` | f2685:m8 |
def find_field_by_name(browser, field_type, name): | return ElementSelector(<EOL>browser,<EOL>field_xpath(field_type, '<STR_LIT:name>') %<EOL>string_literal(name),<EOL>filter_displayed=True,<EOL>)<EOL> | Locate the control input with the given ``name``.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string name: ``name`` attribute
Returns: an :class:`ElementSelector` | f2685:m9 |
def find_field_by_value(browser, field_type, name): | xpath = field_xpath(field_type, '<STR_LIT:value>') % string_literal(name)<EOL>elems = ElementSelector(<EOL>browser,<EOL>xpath=str(xpath),<EOL>filter_displayed=True,<EOL>filter_enabled=True,<EOL>)<EOL>if field_type in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>elems = sorted(elems, key=lambda elem: len(elem.text))<EOL><DEDENT>else:<EOL><INDENT>elems = sorted(elems,<EOL>key=lambda elem: len(elem.get_attribute('<STR_LIT:value>')))<EOL><DEDENT>if elems:<EOL><INDENT>elems = [elems[<NUM_LIT:0>]]<EOL><DEDENT>return ElementSelector(browser, elements=elems)<EOL> | Locate the control input with the given ``value``. Useful for buttons.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string name: ``value`` attribute
Returns: an :class:`ElementSelector` | f2685:m10 |
def find_field_by_label(browser, field_type, label): | return ElementSelector(<EOL>browser,<EOL>xpath=field_xpath(field_type, '<STR_LIT:id>') %<EOL>'<STR_LIT>'.format(<EOL>string_literal(label)),<EOL>filter_displayed=True,<EOL>)<EOL> | Locate the control input that has a label pointing to it.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string label: label text
This will first locate the label element that has a label of the given
name. It then pulls the id out of the 'for' attribute, and uses it to
locate the element by its id.
Returns: an :class:`ElementSelector` | f2685:m11 |
def option_in_select(browser, select_name, option): | select = find_field(browser, '<STR_LIT>', select_name)<EOL>assert select, "<STR_LIT>".format(select_name)<EOL>try:<EOL><INDENT>return select.find_element_by_xpath(str(<EOL>'<STR_LIT>' % string_literal(option)))<EOL><DEDENT>except NoSuchElementException:<EOL><INDENT>return None<EOL><DEDENT> | Returns the Element specified by @option or None
Looks at the real <select> not the select2 widget, since that doesn't
create the DOM until we click on it. | f2685:m12 |
def wait_for(func): | @wraps(func)<EOL>def wrapped(*args, **kwargs):<EOL><INDENT>timeout = kwargs.pop('<STR_LIT>', TIMEOUT)<EOL>start = None<EOL>while True:<EOL><INDENT>try:<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT>except AssertionError:<EOL><INDENT>if not start:<EOL><INDENT>start = time()<EOL><DEDENT>if time() - start < timeout:<EOL><INDENT>sleep(CHECK_EVERY)<EOL>continue<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return wrapped<EOL> | A decorator to invoke a function, retrying on assertion errors for a
specified time interval.
Adds a kwarg `timeout` to `func` which is a number of seconds to try
for (default 15). | f2685:m13 |
def __init__(self, browser, xpath=None, elements=None, <EOL>filter_displayed=False, filter_enabled=False): | self.browser = browser<EOL>if xpath is None and elements is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if xpath is not None:<EOL><INDENT>self.xpath = xpath<EOL><DEDENT>else:<EOL><INDENT>self._elements_cached = elements<EOL><DEDENT>self.filter_displayed = filter_displayed<EOL>self.filter_enabled = filter_enabled<EOL> | Initialise the selector.
One of `xpath` or `elements` must be passed. Passing `xpath` creates a
selector delaying evaluation until it's needed, passing `elements`
stores the elements immediately. | f2685:c0:m0 |
@property<EOL><INDENT>def evaluated(self):<DEDENT> | return hasattr(self, '<STR_LIT>')<EOL> | Whether the selector has already been evaluated. | f2685:c0:m1 |
def filter(self, displayed=False, enabled=False): | if self.evaluated:<EOL><INDENT>result = self<EOL>if displayed:<EOL><INDENT>result = ElementSelector(<EOL>result.browser,<EOL>elements=[e for e in result if e.is_displayed()]<EOL>)<EOL><DEDENT>if enabled:<EOL><INDENT>result = ElementSelector(<EOL>result.browser,<EOL>elements=[e for e in result if e.is_enabled()]<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>result = copy(self)<EOL>if displayed:<EOL><INDENT>result.displayed = True<EOL><DEDENT>if enabled:<EOL><INDENT>result.enabled = True<EOL><DEDENT><DEDENT>return result<EOL> | Filter elements by visibility and enabled status.
:param displayed: whether to filter out invisible elements
:param enabled: whether to filter out disabled elements
Returns: an :class:`ElementSelector` | f2685:c0:m2 |
def _select(self): | for element in self.browser.find_elements_by_xpath(self.xpath):<EOL><INDENT>if self.filter_displayed:<EOL><INDENT>if not element.is_displayed():<EOL><INDENT>continue<EOL><DEDENT><DEDENT>if self.filter_enabled:<EOL><INDENT>if not element.is_enabled():<EOL><INDENT>continue<EOL><DEDENT><DEDENT>yield element<EOL><DEDENT> | Fetch the elements from the browser. | f2685:c0:m3 |
def _elements(self): | if not self.evaluated:<EOL><INDENT>setattr(self, '<STR_LIT>', list(self._select()))<EOL><DEDENT>return self._elements_cached<EOL> | The cached list of elements. | f2685:c0:m4 |
def __add__(self, other): | if not self.evaluatedand isinstance(other, ElementSelector)and not other.evaluatedand self.filter_displayed == other.filter_displayedand self.filter_enabled == other.filter_enabled:<EOL><INDENT>return ElementSelector(<EOL>self.browser,<EOL>xpath=self.xpath + '<STR_LIT:|>' + other.xpath,<EOL>filter_displayed=self.filter_displayed,<EOL>filter_enabled=self.filter_enabled,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>other = list(other)<EOL><DEDENT>except TypeError:<EOL><INDENT>other = [other]<EOL><DEDENT>return ElementSelector(self.browser, elements=list(self) + other)<EOL><DEDENT> | Return a union of the two selectors.
Where possible, avoid evaluating either selector to batch queries. | f2685:c0:m5 |
def __getattr__(self, attr): | if attr == '<STR_LIT>':<EOL><INDENT>raise AttributeError()<EOL><DEDENT>assert len(self) == <NUM_LIT:1>,'<STR_LIT>'.format(len(self))<EOL>return getattr(self[<NUM_LIT:0>], attr)<EOL> | Delegate all calls to the only element selected. | f2685:c0:m10 |
def feature(fails=False): | def outer(func):<EOL><INDENT>"""<STR_LIT>"""<EOL>@wraps(func)<EOL>@in_directory(os.path.dirname(__file__))<EOL>def inner(self):<EOL><INDENT>"""<STR_LIT>"""<EOL>scenario = func.__doc__<EOL>scenario = scenario.replace(<EOL>'<STR_LIT>',<EOL>os.environ.get('<STR_LIT>', '<STR_LIT>')<EOL>)<EOL>feature_string = """<STR_LIT>""".format(name=func.__name__, scenario_string=scenario)<EOL>result = self.run_feature_string(feature_string)<EOL>if fails:<EOL><INDENT>self.assertFalse(result.success)<EOL><DEDENT>else:<EOL><INDENT>self.assertTrue(result.success)<EOL><DEDENT><DEDENT>return inner<EOL><DEDENT>return outer<EOL> | Decorate a test method to test the feature contained in its docstring.
For example:
@feature(failed=False)
def test_some_feature(self):
'''
When I ...
Then I ...
'''
The method code is ignored. | f2687:m0 |
def browser_type(): | return os.environ.get('<STR_LIT>', '<STR_LIT>')<EOL> | Browser type selected for the tests. | f2687:m2 |
def skip_if_browser(browsers, message): | if not isinstance(browsers, (list, tuple)):<EOL><INDENT>browsers = [browsers]<EOL><DEDENT>if browser_type() in browsers:<EOL><INDENT>return unittest.skip(message)<EOL><DEDENT>return lambda func: func<EOL> | Decorator to skip a test with a particular browser type. | f2687:m3 |
def create_browser(): | if '<STR_LIT>' in os.environ:<EOL><INDENT>address = '<STR_LIT>'.format(os.environ['<STR_LIT>'])<EOL>capabilities = {<EOL>'<STR_LIT>': webdriver.DesiredCapabilities.CHROME,<EOL>'<STR_LIT>': webdriver.DesiredCapabilities.FIREFOX,<EOL>'<STR_LIT>': webdriver.DesiredCapabilities.PHANTOMJS,<EOL>}<EOL>try:<EOL><INDENT>browser = capabilities[browser_type()]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return webdriver.Remote(<EOL>address,<EOL>desired_capabilities=browser,<EOL>)<EOL><DEDENT>browsers = {<EOL>'<STR_LIT>': webdriver.Chrome,<EOL>'<STR_LIT>': webdriver.Firefox,<EOL>'<STR_LIT>': webdriver.PhantomJS,<EOL>}<EOL>driver = browsers[browser_type()]<EOL>old_lc_all = os.environ.get('<STR_LIT>', '<STR_LIT>')<EOL>try:<EOL><INDENT>os.environ['<STR_LIT>'] = '<STR_LIT>'<EOL>return driver()<EOL><DEDENT>finally:<EOL><INDENT>os.environ['<STR_LIT>'] = old_lc_all<EOL><DEDENT> | Create a Selenium browser for tests. | f2687:m4 |
def translate_path(self, path): | pages_dir = os.path.relpath(<EOL>os.path.join(os.path.dirname(__file__), '<STR_LIT>'))<EOL>return SimpleHTTPRequestHandler.translate_path(<EOL>self, '<STR_LIT:/>' + pages_dir + path)<EOL> | Serve the pages directory instead of the current directory. | f2687:c0:m0 |
def do_GET(self): | sleep(<NUM_LIT:0.5>)<EOL>return SimpleHTTPRequestHandler.do_GET(self)<EOL> | Artificially slow down the response to make sure there are no race
conditions. | f2687:c0:m1 |
def log_message(self, *args, **kwargs): | pass<EOL> | Turn off logging. | f2687:c0:m2 |
def get_request(self): | request, addr = socketserver.TCPServer.get_request(self)<EOL>request.settimeout(<NUM_LIT:2>) <EOL>return request, addr<EOL> | Set a timeout on the request socket. | f2687:c1:m0 |
def cleanup_screenshots(self): | for ext in ('<STR_LIT>', '<STR_LIT:html>'):<EOL><INDENT>for filename in iglob('<STR_LIT>'.format(ext)):<EOL><INDENT>os.unlink(filename)<EOL><DEDENT><DEDENT>if self.dir_path:<EOL><INDENT>shutil.rmtree(self.dir_path)<EOL><DEDENT> | Clean up any screenshots taken. | f2689:c0:m0 |
def setUp(self): | super(TestScreenshots, self).setUp()<EOL>self.cleanup_screenshots()<EOL>os.environ['<STR_LIT>'] = '<STR_LIT:1>'<EOL> | Enable the hooks for taking screenshots. | f2689:c0:m1 |
def tearDown(self): | del os.environ['<STR_LIT>']<EOL>if '<STR_LIT>' in os.environ:<EOL><INDENT>del os.environ['<STR_LIT>']<EOL><DEDENT>self.cleanup_screenshots()<EOL>super(TestScreenshots, self).tearDown()<EOL> | Remove all the screenshot files. | f2689:c0:m2 |
def show_files(self): | for filename in iglob('<STR_LIT>'):<EOL><INDENT>print(filename)<EOL><DEDENT>if self.dir_path:<EOL><INDENT>for filename in iglob(os.path.join(self.dir_path, '<STR_LIT:*>')):<EOL><INDENT>print(filename)<EOL><DEDENT><DEDENT> | Print all the file names matching the screenshot/page source pattern in
the directory. | f2689:c0:m4 |
def assert_file_present(self, filename, message): | if os.path.exists(filename):<EOL><INDENT>return<EOL><DEDENT>self.show_files()<EOL>raise AssertionError(message)<EOL> | Assert a file exists. | f2689:c0:m5 |
def assert_file_absent(self, filename, message): | if not os.path.exists(filename):<EOL><INDENT>return<EOL><DEDENT>self.show_files()<EOL>raise AssertionError(message)<EOL> | Assert a file does not exist. | f2689:c0:m6 |
@around.all<EOL>@contextmanager<EOL>def with_browser(): | world.browser = create_browser()<EOL>yield<EOL>world.browser.quit()<EOL>delattr(world, '<STR_LIT>')<EOL> | Start a browser for the tests. | f2693:m0 |
@before.each_feature<EOL>def reset_page(feature): | world.browser.get('<STR_LIT>')<EOL> | Reset the browser before each feature. | f2693:m2 |
@step(r'<STR_LIT>')<EOL>def visit_page(self, page): | url = urljoin(django_url(self), page)<EOL>self.given('<STR_LIT>' % url)<EOL> | Visit the specific page of the site, e.g.
.. code-block:: gherkin
When I visit site page "/users" | f2694:m0 |
def load_script(browser, url): | if browser.current_url.startswith('<STR_LIT>'):<EOL><INDENT>url = '<STR_LIT>' + url<EOL><DEDENT>browser.execute_script("""<STR_LIT>""", url)<EOL> | Ensure that JavaScript at a given URL is available to the browser. | f2695:m0 |
def is_jquery_not_defined_error(msg): | <EOL>return any(txt in msg for txt in (<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>))<EOL> | Check whether the JavaScript error message is due to jQuery not
being available. | f2695:m1 |
def load_jquery(func): | @wraps(func)<EOL>def wrapped(browser, *args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>try:<EOL><INDENT>return func(browser, *args, **kwargs)<EOL><DEDENT>except WebDriverException as ex:<EOL><INDENT>if not is_jquery_not_defined_error(ex.msg):<EOL><INDENT>raise<EOL><DEDENT>load_script(browser, JQUERY)<EOL>@wait_for<EOL>def jquery_available():<EOL><INDENT>"""<STR_LIT>"""<EOL>try:<EOL><INDENT>return browser.execute_script('<STR_LIT>')<EOL><DEDENT>except WebDriverException:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT><DEDENT>jquery_available()<EOL>return func(browser, *args, **kwargs)<EOL><DEDENT><DEDENT>return wrapped<EOL> | A decorator to ensure a function is run with jQuery available.
If an exception from a function indicates jQuery is missing, it is loaded
and the function re-executed.
The browser to load jQuery into must be the first argument of the function. | f2695:m2 |
@load_jquery<EOL>def find_elements_by_jquery(browser, selector): | return browser.execute_script(<EOL>"""<STR_LIT>""", selector)<EOL> | Find HTML elements using jQuery-style selectors.
Ensures that jQuery is available to the browser. | f2695:m3 |
def find_element_by_jquery(browser, selector): | elements = find_elements_by_jquery(browser, selector)<EOL>if not elements:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>if len(elements) > <NUM_LIT:1>:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>return elements[<NUM_LIT:0>]<EOL> | Find a single HTML element using jQuery-style selectors. | f2695:m4 |
@load_jquery<EOL>def find_parents_by_jquery(browser, selector): | return browser.execute_script(<EOL>"""<STR_LIT>""", selector)<EOL> | Find HTML elements' parents using jQuery-style selectors.
Ensures that jQuery is available to the browser. | f2695:m5 |
@step(r'<STR_LIT>')<EOL>@wait_for<EOL>def check_element_by_selector(self, selector): | elems = find_elements_by_jquery(world.browser, selector)<EOL>if not elems:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | Assert an element exists matching the given selector. | f2695:m6 |
@step(r'<STR_LIT>')<EOL>@wait_for<EOL>def check_no_element_by_selector(self, selector): | elems = find_elements_by_jquery(world.browser, selector)<EOL>if elems:<EOL><INDENT>raise AssertionError("<STR_LIT>".format(<EOL>len(elems)))<EOL><DEDENT> | Assert an element does not exist matching the given selector. | f2695:m7 |
@step(r'<STR_LIT>'<EOL>r'<STR_LIT>')<EOL>def wait_for_element_by_selector(self, selector, seconds): | def assert_element_present():<EOL><INDENT>"""<STR_LIT>"""<EOL>if not find_elements_by_jquery(world.browser, selector):<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT><DEDENT>wait_for(assert_element_present)(timeout=int(seconds))<EOL> | Assert an element exists matching the given selector within the given time
period. | f2695:m8 |
@step(r'<STR_LIT>')<EOL>@wait_for<EOL>def count_elements_exactly_by_selector(self, number, selector): | elems = find_elements_by_jquery(world.browser, selector)<EOL>number = int(number)<EOL>if len(elems) != number:<EOL><INDENT>raise AssertionError("<STR_LIT>".format(<EOL>number, len(elems)))<EOL><DEDENT> | Assert n elements exist matching the given selector. | f2695:m9 |
@step(r'<STR_LIT>')<EOL>@wait_for<EOL>def fill_in_by_selector(self, selector, value): | elem = find_element_by_jquery(world.browser, selector)<EOL>elem.clear()<EOL>elem.send_keys(value)<EOL> | Fill in the form element matching the CSS selector. | f2695:m10 |
@step(r'<STR_LIT>')<EOL>@wait_for<EOL>def submit_by_selector(self, selector): | elem = find_element_by_jquery(world.browser, selector)<EOL>elem.submit()<EOL> | Submit the form matching the CSS selector. | f2695:m11 |
@step(r'<STR_LIT>')<EOL>@wait_for<EOL>def check_by_selector(self, selector): | elem = find_element_by_jquery(world.browser, selector)<EOL>if not elem.is_selected():<EOL><INDENT>elem.click()<EOL><DEDENT> | Check the checkbox matching the CSS selector. | f2695:m12 |
@step(r'<STR_LIT>')<EOL>@wait_for<EOL>def click_by_selector(self, selector): | <EOL>elem = find_element_by_jquery(world.browser, selector)<EOL>elem.click()<EOL> | Click the element matching the CSS selector. | f2695:m13 |
@step(r'<STR_LIT>')<EOL>@wait_for<EOL>def follow_link_by_selector(self, selector): | elem = find_element_by_jquery(world.browser, selector)<EOL>href = elem.get_attribute('<STR_LIT>')<EOL>world.browser.get(href)<EOL> | Navigate to the href of the element matching the CSS selector.
N.B. this does not click the link, but changes the browser's URL. | f2695:m14 |
@step(r'<STR_LIT>')<EOL>@wait_for<EOL>def is_selected_by_selector(self, selector): | elem = find_element_by_jquery(world.browser, selector)<EOL>if not elem.is_selected():<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | Assert the option matching the CSS selector is selected. | f2695:m15 |
@step(r'<STR_LIT>')<EOL>@wait_for<EOL>def select_by_selector(self, selector): | option = find_element_by_jquery(world.browser, selector)<EOL>selectors = find_parents_by_jquery(world.browser, selector)<EOL>if not selectors:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT>selector = selectors[<NUM_LIT:0>]<EOL>selector.click()<EOL>sleep(<NUM_LIT>)<EOL>option.click()<EOL>if not option.is_selected():<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>")<EOL><DEDENT> | Select the option matching the CSS selector. | f2695:m16 |
def contains_content(browser, content): | for elem in browser.find_elements_by_xpath(str(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>.format(content=string_literal(content)))):<EOL><INDENT>try:<EOL><INDENT>if elem.is_displayed():<EOL><INDENT>return True<EOL><DEDENT><DEDENT>except StaleElementReferenceException:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return False<EOL> | Search for an element that contains the whole of the text we're looking
for in it or its subelements, but whose children do NOT contain that
text - otherwise matches <body> or <html> or other similarly useless
things. | f2696:m0 |
@step('<STR_LIT>')<EOL>@step('<STR_LIT>')<EOL>def visit(self, url): | world.browser.get(url)<EOL> | Navigate to the provided (fully qualified) URL. | f2696:m1 |
@step('<STR_LIT>')<EOL>@step('<STR_LIT>')<EOL>@wait_for<EOL>def url_should_be(self, url): | if world.browser.current_url != url:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>".format(<EOL>url, world.browser.current_url))<EOL><DEDENT> | Assert the absolute URL of the browser is as provided. | f2696:m2 |
@step('''<STR_LIT>''')<EOL>@wait_for<EOL>def url_should_contain(self, url): | if url not in world.browser.current_url:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>".format(<EOL>url, world.browser.current_url))<EOL><DEDENT> | Assert the absolute URL of the browser contains the provided. | f2696:m3 |
@step('''<STR_LIT>''')<EOL>@wait_for<EOL>def url_should_not_contain(self, url): | if url in world.browser.current_url:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>".format(<EOL>url, world.browser.current_url))<EOL><DEDENT> | Assert the absolute URL of the browser does not contain the provided. | f2696:m4 |
@step(r'<STR_LIT>')<EOL>@step(r"<STR_LIT>")<EOL>@wait_for<EOL>def page_title(self, title): | if world.browser.title != title:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>".format(<EOL>title, world.browser.title))<EOL><DEDENT> | Assert the page title matches the given text. | f2696:m5 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def click(self, name): | try:<EOL><INDENT>elem = world.browser.find_element_by_link_text(name)<EOL><DEDENT>except NoSuchElementException:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>".format(name))<EOL><DEDENT>elem.click()<EOL> | Click the link with the provided link text. | f2696:m6 |
@step('<STR_LIT>')<EOL>@wait_for<EOL>def should_see_link(self, link_url): | elements = ElementSelector(<EOL>world.browser,<EOL>str('<STR_LIT>' % link_url),<EOL>filter_displayed=True,<EOL>)<EOL>if not elements:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | Assert a link with the provided URL is visible on the page. | f2696:m7 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def should_see_link_text(self, link_text, link_url): | elements = ElementSelector(<EOL>world.browser,<EOL>str('<STR_LIT>' % (link_url, link_text)),<EOL>filter_displayed=True,<EOL>)<EOL>if not elements:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | Assert a link with the provided text points to the provided URL. | f2696:m8 |
@step('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>@step("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>@wait_for<EOL>def should_include_link_text(self, link_text, link_url): | elements = ElementSelector(<EOL>world.browser,<EOL>str('<STR_LIT>' %<EOL>(link_url, string_literal(link_text))),<EOL>filter_displayed=True,<EOL>)<EOL>if not elements:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | Assert a link containing the provided text points to the provided URL. | f2696:m9 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def element_contains(self, element_id, value): | elements = ElementSelector(<EOL>world.browser,<EOL>str('<STR_LIT>'.format(<EOL>id=element_id, value=value)),<EOL>filter_displayed=True,<EOL>)<EOL>if not elements:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | Assert provided content is contained within an element found by ``id``. | f2696:m10 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def element_not_contains(self, element_id, value): | elem = world.browser.find_elements_by_xpath(str(<EOL>'<STR_LIT>'.format(<EOL>id=element_id, value=value)))<EOL>assert not elem,"<STR_LIT>"<EOL> | Assert provided content is not contained within an element found by ``id``. | f2696:m11 |
@step(r'<STR_LIT>')<EOL>def should_see_id_in_seconds(self, element_id, timeout): | def check_element():<EOL><INDENT>"""<STR_LIT>"""<EOL>assert ElementSelector(<EOL>world.browser,<EOL>'<STR_LIT>' % element_id,<EOL>filter_displayed=True,<EOL>), "<STR_LIT>"<EOL><DEDENT>wait_for(check_element)(timeout=int(timeout))<EOL> | Assert an element with the given ``id`` is visible within n seconds. | f2696:m12 |
@step('<STR_LIT>')<EOL>@wait_for<EOL>def should_see_id(self, element_id): | elements = ElementSelector(<EOL>world.browser,<EOL>'<STR_LIT>' % element_id,<EOL>filter_displayed=True,<EOL>)<EOL>if not elements:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | Assert an element with the given ``id`` is visible. | f2696:m13 |
@step('<STR_LIT>')<EOL>@wait_for<EOL>def should_not_see_id(self, element_id): | elements = ElementSelector(<EOL>world.browser,<EOL>'<STR_LIT>' % element_id,<EOL>filter_displayed=True,<EOL>)<EOL>if elements:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | Assert an element with the given ``id`` is not visible. | f2696:m14 |
@step(r'<STR_LIT>')<EOL>@wait_for<EOL>def element_focused(self, id_): | try:<EOL><INDENT>elem = world.browser.find_element_by_id(id_)<EOL><DEDENT>except NoSuchElementException:<EOL><INDENT>raise AssertionError("<STR_LIT>".format(id_))<EOL><DEDENT>focused = world.browser.switch_to.active_element<EOL>if not elem == focused:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | Assert the element is focused. | f2696:m15 |
@step(r'<STR_LIT>')<EOL>@wait_for<EOL>def element_not_focused(self, id_): | try:<EOL><INDENT>elem = world.browser.find_element_by_id(id_)<EOL><DEDENT>except NoSuchElementException:<EOL><INDENT>raise AssertionError("<STR_LIT>".format(id_))<EOL><DEDENT>focused = world.browser.switch_to.active_element<EOL>if elem == focused:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | Assert the element is not focused. | f2696:m16 |
@step(r'<STR_LIT>')<EOL>@step(r"<STR_LIT>")<EOL>def should_see_in_seconds(self, text, timeout): | def check_element():<EOL><INDENT>"""<STR_LIT>"""<EOL>assert contains_content(world.browser, text),"<STR_LIT>"<EOL><DEDENT>wait_for(check_element)(timeout=int(timeout))<EOL> | Assert provided text is visible within n seconds.
Be aware this text could be anywhere on the screen. Also be aware that
it might cross several HTML nodes. No determination is made between
block and inline nodes. Whitespace can be affected. | f2696:m17 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def should_see(self, text): | if not contains_content(world.browser, text):<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | Assert provided text is visible.
Be aware this text could be anywhere on the screen. Also be aware that
it might cross several HTML nodes. No determination is made between
block and inline nodes. Whitespace can be affected. | f2696:m18 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def should_not_see(self, text): | if contains_content(world.browser, text):<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | Assert provided text is not visible.
Be aware that because of the caveats of the positive case, the text MAY
be on the screen in a slightly different form. | f2696:m19 |
@step('<STR_LIT>')<EOL>@wait_for<EOL>def see_form(self, url): | elements = ElementSelector(<EOL>world.browser,<EOL>str('<STR_LIT>' % url),<EOL>filter_displayed=True,<EOL>)<EOL>if not elements:<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT> | Assert the existence of a HTML form that submits to the given URL. | f2696:m20 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def fill_in_textfield(self, field_name, value): | date_field = find_any_field(world.browser,<EOL>DATE_FIELDS,<EOL>field_name)<EOL>if date_field:<EOL><INDENT>field = date_field<EOL><DEDENT>else:<EOL><INDENT>field = find_any_field(world.browser,<EOL>TEXT_FIELDS,<EOL>field_name)<EOL><DEDENT>if not field:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>".format(field_name))<EOL><DEDENT>if date_field:<EOL><INDENT>field.send_keys(Keys.DELETE)<EOL><DEDENT>else:<EOL><INDENT>field.clear()<EOL><DEDENT>field.send_keys(value)<EOL> | Fill in the HTML input with given label (recommended), name or id with
the given text.
Supported input types are text, textarea, password, month, time, week,
number, range, email, url, tel and color. | f2696:m21 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def press_button(self, value): | button = find_button(world.browser, value)<EOL>if not button:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>".format(value))<EOL><DEDENT>button.click()<EOL> | Click the button with the given label. | f2696:m22 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def click_on_label(self, label): | elem = ElementSelector(<EOL>world.browser,<EOL>str('<STR_LIT>' % string_literal(label)),<EOL>filter_displayed=True,<EOL>)<EOL>if not elem:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>".format(label))<EOL><DEDENT>elem.click()<EOL> | Click on the given label.
On a correctly set up form this will highlight the appropriate field. | f2696:m23 |
@step(r'<STR_LIT>')<EOL>@step(r"<STR_LIT>")<EOL>@wait_for<EOL>def input_has_value(self, field_name, value): | text_field = find_any_field(world.browser,<EOL>DATE_FIELDS + TEXT_FIELDS,<EOL>field_name)<EOL>if text_field is False:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>".format(field_name))<EOL><DEDENT>actual = text_field.get_attribute('<STR_LIT:value>')<EOL>if actual != value:<EOL><INDENT>raise AssertionError(<EOL>"<STR_LIT>".format(<EOL>value, actual))<EOL><DEDENT> | Assert the form input with label (recommended), name or id has given value. | f2696:m24 |
@step(r'<STR_LIT>')<EOL>@wait_for<EOL>def submit_the_only_form(self): | form = ElementSelector(world.browser, str('<STR_LIT>'))<EOL>assert form, "<STR_LIT>"<EOL>form.submit()<EOL> | Look for a form on the page and submit it.
Asserts if more than one form exists. | f2696:m25 |
@step(r'<STR_LIT>')<EOL>@wait_for<EOL>def submit_form_id(self, id_): | form = ElementSelector(<EOL>world.browser,<EOL>str('<STR_LIT>'.format(id=id_)),<EOL>)<EOL>assert form, "<STR_LIT>".format(id_)<EOL>form.submit()<EOL> | Submit the form with given id (used to disambiguate between multiple
forms). | f2696:m26 |
@step(r'<STR_LIT>')<EOL>def submit_form_action(self, url): | form = ElementSelector(<EOL>world.browser,<EOL>str('<STR_LIT>' % url),<EOL>)<EOL>assert form,"<STR_LIT>".format(url)<EOL>form.submit()<EOL> | Submit the form with the given action URL (i.e. the form that submits to
``/post/my/data``). | f2696:m27 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def check_checkbox(self, value): | check_box = find_field(world.browser, '<STR_LIT>', value)<EOL>assert check_box, "<STR_LIT>".format(value)<EOL>if not check_box.is_selected():<EOL><INDENT>check_box.click()<EOL><DEDENT> | Check the checkbox with label (recommended), name or id. | f2696:m28 |
@step('<STR_LIT>')<EOL>@step("<STR_LIT>")<EOL>@wait_for<EOL>def uncheck_checkbox(self, value): | check_box = find_field(world.browser, '<STR_LIT>', value)<EOL>assert check_box, "<STR_LIT>".format(value)<EOL>if check_box.is_selected():<EOL><INDENT>check_box.click()<EOL><DEDENT> | Uncheck the checkbox with label (recommended), name or id. | f2696:m29 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.