INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Get the type of an image from the file s extension (. jpg etc. )
def bitmap_type(filename): """ Get the type of an image from the file's extension ( .jpg, etc. ) """ if filename == '': return None name, ext = os.path.splitext(filename) ext = ext[1:].upper() if ext == 'BMP': return wx.BITMAP_TYPE_BMP elif ext == 'GIF': return wx.BITMAP_TYPE_GIF elif ext == 'JPG' or ext == 'JPEG': return wx.BITMAP_TYPE_JPEG elif ext == 'PCX': return wx.BITMAP_TYPE_PCX elif ext == 'PICT': return wx.BITMAP_TYPE_PICT elif ext == 'PNG': return wx.BITMAP_TYPE_PNG elif ext == 'PNM': return wx.BITMAP_TYPE_PNM elif ext == 'TIF' or ext == 'TIFF': return wx.BITMAP_TYPE_TIF elif ext == 'XBM': return wx.BITMAP_TYPE_XBM elif ext == 'XPM': return wx.BITMAP_TYPE_XPM else: # KEA 2001-10-10 # rather than throw an exception, we could try and have wxPython figure out the image # type by returning wxBITMAP_TYPE_ANY raise RuntimeErro('invalid graphics format')
Get the type of an image from the file s extension (. jpg etc. )
def _getbitmap_type( self, filename ) : """ Get the type of an image from the file's extension ( .jpg, etc. ) """ # KEA 2001-07-27 # was #name, ext = filename.split( '.' ) #ext = ext.upper() if filename is None or filename == '': return None name, ext = os.path.splitext(filename) ext = ext[1:].upper() if ext == 'BMP': return wx.BITMAP_TYPE_BMP elif ext == 'GIF': return wx.BITMAP_TYPE_GIF elif ext == 'JPG' or ext == 'JPEG': return wx.BITMAP_TYPE_JPEG elif ext == 'PCX': return wx.BITMAP_TYPE_PCX #elif ext == 'PICT': # return wx.BITMAP_TYPE_PICT elif ext == 'PNG': return wx.BITMAP_TYPE_PNG elif ext == 'PNM': return wx.BITMAP_TYPE_PNM elif ext == 'TIF' or ext == 'TIFF': return wx.BITMAP_TYPE_TIF elif ext == 'XBM': return wx.BITMAP_TYPE_XBM elif ext == 'XPM': return wx.BITMAP_TYPE_XPM else: # KEA 2001-10-10 # rather than throw an exception, we could try and have wxPython figure out the image # type by returning wxBITMAP_TYPE_ANY raise RuntimeError('invalid graphics format')
Set icon based on resource values
def _set_icon(self, icon=None): """Set icon based on resource values""" if icon is not None: try: wx_icon = wx.Icon(icon, wx.BITMAP_TYPE_ICO) self.wx_obj.SetIcon(wx_icon) except: pass
Display or hide the window optionally disabling all other windows
def show(self, value=True, modal=None): "Display or hide the window, optionally disabling all other windows" self.wx_obj.Show(value) if modal: # disable all top level windows of this application (MakeModal) disabler = wx.WindowDisabler(self.wx_obj) # create an event loop to stop execution eventloop = wx.EventLoop() def on_close_modal(evt): evt.Skip() eventloop.Exit() self.wx_obj.Bind(wx.EVT_CLOSE, on_close_modal) # start the event loop to wait user interaction eventloop.Run() # reenable the windows disabled and return control to the caller del disabler
Draws an arc of a circle centered on ( xc yc ) with starting point ( x1 y1 ) and ending at ( x2 y2 ). The current pen is used for the outline and the current brush for filling the shape.
def draw_arc(self, x1y1, x2y2, xcyc): """ Draws an arc of a circle, centered on (xc, yc), with starting point (x1, y1) and ending at (x2, y2). The current pen is used for the outline and the current brush for filling the shape. The arc is drawn in an anticlockwise direction from the start point to the end point. """ self._buf_image.DrawArcPoint(x1y1, x2y2, xcyc) if self.auto_refresh: dc = wx.ClientDC(self.wx_obj) dc.BlitPointSize((0, 0), (self._size[0], self._size[1]), self._buf_image, (0, 0))
automatically adjust relative pos and size of children controls
def resize(self, evt=None): "automatically adjust relative pos and size of children controls" for child in self: if isinstance(child, Control): child.resize(evt) # call original handler (wx.HtmlWindow) if evt: evt.Skip()
Open read and eval the resource from the source file
def parse(filename=""): "Open, read and eval the resource from the source file" # use the provided resource file: s = open(filename).read() ##s.decode("latin1").encode("utf8") import datetime, decimal rsrc = eval(s) return rsrc
Save the resource to the source file
def save(filename, rsrc): "Save the resource to the source file" s = pprint.pformat(rsrc) ## s = s.encode("utf8") open(filename, "w").write(s)
Create the GUI objects defined in the resource ( filename or python struct )
def load(controller=None, filename="", name=None, rsrc=None): "Create the GUI objects defined in the resource (filename or python struct)" # if no filename is given, search for the rsrc.py with the same module name: if not filename and not rsrc: if isinstance(controller, types.ClassType): # use the controller class module (to get __file__ for rsrc.py) mod_dict = util.get_class_module_dict(controller) elif isinstance(controller, types.ModuleType): # use the module provided as controller mod_dict = controller.__dict__ elif isinstance(controller, Controller): # use the instance provided as controller mod_dict = util.get_class_module_dict(controller) else: # use the caller module (no controller explicitelly provided) mod_dict = util.get_caller_module_dict() # do not use as controller if it was explicitly False or empty if controller is None: controller = mod_dict if util.main_is_frozen(): # running standalone if '__file__' in mod_dict: filename = os.path.split(mod_dict['__file__'])[1] else: # __main__ has not __file__ under py2exe! filename = os.path.split(sys.argv[0])[-1] filename = os.path.join(util.get_app_dir(), filename) else: # figure out the .rsrc.py filename based on the module name filename = mod_dict['__file__'] # chop the .pyc or .pyo from the end base, ext = os.path.splitext(filename) filename = base + ".rsrc.py" # when rsrc is a file name, open, read and eval it: if isinstance(filename, basestring): rsrc = parse(filename) ret = [] # search over the resource to create the requested object (or all) for win in rsrc: if not name or win['name'] == name: ret.append(build_window(win)) # associate event handlers if ret and controller: connect(ret[0], controller) # return the first instance created (if any): return ret[0] else: # return all the instances created -for the designer- (if any): return ret
Create a gui2py window based on the python resource
def build_window(res): "Create a gui2py window based on the python resource" # windows specs (parameters) kwargs = dict(res.items()) wintype = kwargs.pop('type') menubar = kwargs.pop('menubar', None) components = kwargs.pop('components') panel = kwargs.pop('panel', {}) from gui import registry import gui winclass = registry.WINDOWS[wintype] win = winclass(**kwargs) # add an implicit panel by default (as pythoncard had) if False and panel is not None: panel['name'] = 'panel' p = gui.Panel(win, **panel) else: p = win if components: for comp in components: build_component(comp, parent=p) if menubar: mb = gui.MenuBar(name="menu", parent=win) for menu in menubar: build_component(menu, parent=mb) return win
Create a gui2py control based on the python resource
def build_component(res, parent=None): "Create a gui2py control based on the python resource" # control specs (parameters) kwargs = dict(res.items()) comtype = kwargs.pop('type') if 'components' in res: components = kwargs.pop('components') elif comtype == 'Menu' and 'items' in res: components = kwargs.pop('items') else: components = [] from gui import registry if comtype in registry.CONTROLS: comclass = registry.CONTROLS[comtype] elif comtype in registry.MENU: comclass = registry.MENU[comtype] elif comtype in registry.MISC: comclass = registry.MISC[comtype] else: raise RuntimeError("%s not in registry" % comtype) # Instantiate the GUI object com = comclass(parent=parent, **kwargs) for comp in components: build_component(comp, parent=com) return com
Recursive convert a live GUI object to a resource list/ dict
def dump(obj): "Recursive convert a live GUI object to a resource list/dict" from .spec import InitSpec, DimensionSpec, StyleSpec, InternalSpec import decimal, datetime from .font import Font from .graphic import Bitmap, Color from . import registry ret = {'type': obj.__class__.__name__} for (k, spec) in obj._meta.specs.items(): if k == "index": # index is really defined by creation order continue # also, avoid infinite recursion v = getattr(obj, k, "") if (not isinstance(spec, InternalSpec) and v != spec.default and (k != 'id' or v > 0) and isinstance(v, (basestring, int, long, float, bool, dict, list, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, Font, Color)) and repr(v) != 'None' and k != 'parent' ): ret[k] = v for ctl in obj: if ret['type'] in registry.MENU: ret.setdefault('items', []).append(dump(ctl)) else: res = dump(ctl) if 'menubar' in res: ret.setdefault('menubar', []).append(res.pop('menubar')) else: ret.setdefault('components', []).append(res) return ret
Associate event handlers
def connect(component, controller=None): "Associate event handlers " # get the controller functions and names (module or class) if not controller or isinstance(controller, dict): if not controller: controller = util.get_caller_module_dict() controller_name = controller['__name__'] controller_dict = controller else: controller_name = controller.__class__.__name__ controller_dict = dict([(k, getattr(controller, k)) for k in dir(controller) if k.startswith("on_")]) for fn in [n for n in controller_dict if n.startswith("on_")]: # on_mypanel_mybutton_click -> ['mypanel']['mybutton'].onclick names = fn.split("_") event_name = names.pop(0) + names.pop(-1) # find the control obj = component for name in names: try: obj = obj[name] except KeyError: obj = None break if not obj: from .component import COMPONENTS for key, obj in COMPONENTS.items(): if obj.name == name: print "WARNING: %s should be %s" % (name, key.replace(".", "_")) break else: raise NameError("'%s' component not found (%s.%s)" % (name, controller_name, fn)) # check if the control supports the event: if event_name in PYTHONCARD_EVENT_MAP: new_name = PYTHONCARD_EVENT_MAP[event_name] print "WARNING: %s should be %s (%s)" % (event_name, new_name, fn) event_name = new_name if not hasattr(obj, event_name): raise NameError("'%s' event not valid (%s.%s)" % (event_name, controller_name, fn)) # bind the event (assign the method to the on... spec) setattr(obj, event_name, controller_dict[fn])
translate gui2py attribute name from pythoncard legacy code
def convert(self, name): "translate gui2py attribute name from pythoncard legacy code" new_name = PYTHONCARD_PROPERTY_MAP.get(name) if new_name: print "WARNING: property %s should be %s (%s)" % (name, new_name, self.obj.name) return new_name else: return name
Read from the clipboard content return a suitable object ( string or bitmap )
def get_data(): "Read from the clipboard content, return a suitable object (string or bitmap)" data = None try: if wx.TheClipboard.Open(): if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)): do = wx.TextDataObject() wx.TheClipboard.GetData(do) data = do.GetText() elif wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_BITMAP)): do = wx.BitmapDataObject() wx.TheClipboard.GetData(do) data = do.GetBitmap() wx.TheClipboard.Close() except: data = None return data
Write content to the clipboard data can be either a string or a bitmap
def set_data(data): "Write content to the clipboard, data can be either a string or a bitmap" try: if wx.TheClipboard.Open(): if isinstance(data, (str, unicode)): do = wx.TextDataObject() do.SetText(data) wx.TheClipboard.SetData(do) elif isinstance(data, wx.Bitmap): do = wx.BitmapDataObject() do.SetBitmap(data) wx.TheClipboard.SetData(do) wx.TheClipboard.Close() except: pass
Find out what items are documented in source/ *. rst.
def find_autosummary_in_files(filenames): """Find out what items are documented in source/*.rst. See `find_autosummary_in_lines`. """ documented = [] for filename in filenames: f = open(filename, 'r') lines = f.read().splitlines() documented.extend(find_autosummary_in_lines(lines, filename=filename)) f.close() return documented
Find out what items are documented in the given object s docstring.
def find_autosummary_in_docstring(name, module=None, filename=None): """Find out what items are documented in the given object's docstring. See `find_autosummary_in_lines`. """ try: real_name, obj, parent = import_by_name(name) lines = pydoc.getdoc(obj).splitlines() return find_autosummary_in_lines(lines, module=name, filename=filename) except AttributeError: pass except ImportError, e: print "Failed to import '%s': %s" % (name, e) return []
Find out what items appear in autosummary:: directives in the given lines.
def find_autosummary_in_lines(lines, module=None, filename=None): """Find out what items appear in autosummary:: directives in the given lines. Returns a list of (name, toctree, template) where *name* is a name of an object and *toctree* the :toctree: path of the corresponding autosummary directive (relative to the root of the file name), and *template* the value of the :template: option. *toctree* and *template* ``None`` if the directive does not have the corresponding options set. """ autosummary_re = re.compile(r'^(\s*)\.\.\s+autosummary::\s*') automodule_re = re.compile( r'^\s*\.\.\s+automodule::\s*([A-Za-z0-9_.]+)\s*$') module_re = re.compile( r'^\s*\.\.\s+(current)?module::\s*([a-zA-Z0-9_.]+)\s*$') autosummary_item_re = re.compile(r'^\s+(~?[_a-zA-Z][a-zA-Z0-9_.]*)\s*.*?') toctree_arg_re = re.compile(r'^\s+:toctree:\s*(.*?)\s*$') template_arg_re = re.compile(r'^\s+:template:\s*(.*?)\s*$') documented = [] toctree = None template = None current_module = module in_autosummary = False base_indent = "" for line in lines: if in_autosummary: m = toctree_arg_re.match(line) if m: toctree = m.group(1) if filename: toctree = os.path.join(os.path.dirname(filename), toctree) continue m = template_arg_re.match(line) if m: template = m.group(1).strip() continue if line.strip().startswith(':'): continue # skip options m = autosummary_item_re.match(line) if m: name = m.group(1).strip() if name.startswith('~'): name = name[1:] if current_module and \ not name.startswith(current_module + '.'): name = "%s.%s" % (current_module, name) documented.append((name, toctree, template)) continue if not line.strip() or line.startswith(base_indent + " "): continue in_autosummary = False m = autosummary_re.match(line) if m: in_autosummary = True base_indent = m.group(1) toctree = None template = None continue m = automodule_re.search(line) if m: current_module = m.group(1).strip() # recurse into the automodule docstring documented.extend(find_autosummary_in_docstring( current_module, filename=filename)) continue m = module_re.match(line) if m: current_module = m.group(2) continue return documented
Add the object and all their childs
def load_object(self, obj=None): "Add the object and all their childs" # if not obj is given, do a full reload using the current root if obj: self.root_obj = obj else: obj = self.root_obj self.tree.DeleteAllItems() self.root = self.tree.AddRoot("application") self.tree.SetItemText(self.root, "App", 1) self.tree.SetItemText(self.root, "col 2 root", 2) #self.tree.SetItemImage(self.root, fldridx, which = wx.TreeItemIcon_Normal) #self.tree.SetItemImage(self.root, fldropenidx, which = wx.TreeItemIcon_Expanded) self.build_tree(self.root, obj) self.tree.Expand(self.root)
Select the object and show its properties
def inspect(self, obj, context_menu=False, edit_prop=False, mouse_pos=None): "Select the object and show its properties" child = self.tree.FindItem(self.root, obj.name) if DEBUG: print "inspect child", child if child: self.tree.ScrollTo(child) self.tree.SetCurrentItem(child) self.tree.SelectItem(child) child.Selected = True self.activate_item(child, edit_prop) if context_menu: self.show_context_menu(child, mouse_pos)
load the selected item in the property editor
def activate_item(self, child, edit_prop=False, select=False): "load the selected item in the property editor" d = self.tree.GetItemData(child) if d: o = d.GetData() self.selected_obj = o callback = lambda o=o, **kwargs: self.update(o, **kwargs) self.propeditor.load_object(o, callback) if edit_prop: wx.CallAfter(self.propeditor.edit) if select and self.designer: self.designer.select(o) else: self.selected_obj = None
Update the tree item when the object name changes
def update(self, obj, **kwargs): "Update the tree item when the object name changes" # search for the old name: child = self.tree.FindItem(self.root, kwargs['name']) if DEBUG: print "update child", child, kwargs if child: self.tree.ScrollTo(child) self.tree.SetCurrentItem(child) self.tree.SelectItem(child) child.Selected = True # update the new name self.tree.SetItemText(child, obj.name, 0)
Open a popup menu with options regarding the selected object
def show_context_menu(self, item, mouse_pos=None): "Open a popup menu with options regarding the selected object" if item: d = self.tree.GetItemData(item) if d: obj = d.GetData() if obj: # highligh and store the selected object: self.highlight(obj.wx_obj) self.obj = obj # make the context menu menu = wx.Menu() id_del, id_dup, id_raise, id_lower = [wx.NewId() for i in range(4)] menu.Append(id_del, "Delete") menu.Append(id_dup, "Duplicate") menu.Append(id_raise, "Bring to Front") menu.Append(id_lower, "Send to Back") # make submenu! sm = wx.Menu() for ctrl in sorted(obj._meta.valid_children, key=lambda c: registry.ALL.index(c._meta.name)): new_id = wx.NewId() sm.Append(new_id, ctrl._meta.name) self.Bind(wx.EVT_MENU, lambda evt, ctrl=ctrl: self.add_child(ctrl, mouse_pos), id=new_id) menu.AppendMenu(wx.NewId(), "Add child", sm) self.Bind(wx.EVT_MENU, self.delete, id=id_del) self.Bind(wx.EVT_MENU, self.duplicate, id=id_dup) self.Bind(wx.EVT_MENU, self.bring_to_front, id=id_raise) self.Bind(wx.EVT_MENU, self.send_to_back, id=id_lower) self.PopupMenu(menu) menu.Destroy() self.load_object(self.root_obj)
Re - parent a child control with the new wx_obj parent ( owner )
def set_parent(self, new_parent, init=False): "Re-parent a child control with the new wx_obj parent (owner)" ##SubComponent.set_parent(self, new_parent, init) self.wx_obj.SetOwner(new_parent.wx_obj.GetEventHandler())
Perform the actual serialization.
def to_representation(self, value): """ Perform the actual serialization. Args: value: the image to transform Returns: a url pointing at a scaled and cached image """ if not value: return None image = get_thumbnail(value, self.geometry_string, **self.options) try: request = self.context.get('request', None) return request.build_absolute_uri(image.url) except: try: return super(HyperlinkedSorlImageField, self).to_representation(image) except AttributeError: # NOQA return super(HyperlinkedSorlImageField, self).to_native(image.url) # NOQA
Builds and registers a: class: Selector object with the given name and configuration.
def add_selector(name): """ Builds and registers a :class:`Selector` object with the given name and configuration. Args: name (str): The name of the selector. Yields: SelectorFactory: The factory that will build the :class:`Selector`. """ factory = SelectorFactory(name) yield factory selectors[name] = factory.build_selector()
Dict [ str ExpressionFilter ]: Returns the expression filters for this selector.
def expression_filters(self): """ Dict[str, ExpressionFilter]: Returns the expression filters for this selector. """ return { name: filter for name, filter in iter(self.filters.items()) if isinstance(filter, ExpressionFilter)}
Dict [ str NodeFilter ]: Returns the node filters for this selector.
def node_filters(self): """ Dict[str, NodeFilter]: Returns the node filters for this selector. """ return { name: filter for name, filter in iter(self.filters.items()) if isinstance(filter, NodeFilter)}
Returns a decorator function for adding an expression filter.
def expression_filter(self, name, **kwargs): """ Returns a decorator function for adding an expression filter. Args: name (str): The name of the filter. **kwargs: Variable keyword arguments for the filter. Returns: Callable[[Callable[[AbstractExpression, Any], AbstractExpression]]]: A decorator function for adding an expression filter. """ def decorator(func): self.filters[name] = ExpressionFilter(name, func, **kwargs) return decorator
Returns a decorator function for adding a node filter.
def node_filter(self, name, **kwargs): """ Returns a decorator function for adding a node filter. Args: name (str): The name of the filter. **kwargs: Variable keyword arguments for the filter. Returns: Callable[[Callable[[Element, Any], bool]]]: A decorator function for adding a node filter. """ def decorator(func): self.filters[name] = NodeFilter(name, func, **kwargs) return decorator
Adds filters from a particular global: class: FilterSet.
def filter_set(self, name): """ Adds filters from a particular global :class:`FilterSet`. Args: name (str): The name of the set whose filters should be added. """ filter_set = filter_sets[name] for name, filter in iter(filter_set.filters.items()): self.filters[name] = filter self.descriptions += filter_set.descriptions
Selector: Returns a new: class: Selector instance with the current configuration.
def build_selector(self): """ Selector: Returns a new :class:`Selector` instance with the current configuration. """ kwargs = { 'label': self.label, 'descriptions': self.descriptions, 'filters': self.filters} if self.format == "xpath": kwargs['xpath'] = self.func if self.format == "css": kwargs['css'] = self.func return Selector(self.name, **kwargs)
Resolves this query relative to the given node.
def resolves_for(self, node): """ Resolves this query relative to the given node. Args: node (node.Base): The node to be evaluated. Returns: int: The number of matches found. """ self.node = node self.actual_styles = node.style(*self.expected_styles.keys()) return all( toregex(value).search(self.actual_styles[style]) for style, value in iter(self.expected_styles.items()))
str: A message describing the query failure.
def failure_message(self): """ str: A message describing the query failure. """ return ( "Expected node to have styles {expected}. " "Actual styles were {actual}").format( expected=desc(self.expected_styles), actual=desc(self.actual_styles))
Asserts that the page has the given path. By default this will compare against the path + query portion of the full URL.
def assert_current_path(self, path, **kwargs): """ Asserts that the page has the given path. By default this will compare against the path+query portion of the full URL. Args: path (str | RegexObject): The string or regex that the current "path" should match. **kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`. Returns: True Raises: ExpectationNotMet: If the assertion hasn't succeeded during the wait time. """ query = CurrentPathQuery(path, **kwargs) @self.document.synchronize def assert_current_path(): if not query.resolves_for(self): raise ExpectationNotMet(query.failure_message) assert_current_path() return True
Asserts that the page doesn t have the given path.
def assert_no_current_path(self, path, **kwargs): """ Asserts that the page doesn't have the given path. Args: path (str | RegexObject): The string or regex that the current "path" should match. **kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`. Returns: True Raises: ExpectationNotMet: If the assertion hasn't succeeded during the wait time. """ query = CurrentPathQuery(path, **kwargs) @self.document.synchronize def assert_no_current_path(): if query.resolves_for(self): raise ExpectationNotMet(query.negative_failure_message) assert_no_current_path() return True
Checks if the page has the given path.
def has_current_path(self, path, **kwargs): """ Checks if the page has the given path. Args: path (str | RegexObject): The string or regex that the current "path" should match. **kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`. Returns: bool: Whether it matches. """ try: return self.assert_current_path(path, **kwargs) except ExpectationNotMet: return False
Checks if the page doesn t have the given path.
def has_no_current_path(self, path, **kwargs): """ Checks if the page doesn't have the given path. Args: path (str | RegexObject): The string or regex that the current "path" should match. **kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`. Returns: bool: Whether it doesn't match. """ try: return self.assert_no_current_path(path, **kwargs) except ExpectationNotMet: return False
Retrieve the text of the element. If: data: capybara. ignore_hidden_elements is True which it is by default then this will return only text which is visible. The exact semantics of this may differ between drivers but generally any text within elements with display: none is ignored.
def text(self): """ Retrieve the text of the element. If :data:`capybara.ignore_hidden_elements` is ``True``, which it is by default, then this will return only text which is visible. The exact semantics of this may differ between drivers, but generally any text within elements with ``display: none`` is ignored. Returns: str: The text of the element. """ if capybara.ignore_hidden_elements or capybara.visible_text_only: return self.visible_text else: return self.all_text
Select this node if it is an option element inside a select tag.
def select_option(self): """ Select this node if it is an option element inside a select tag. """ if self.disabled: warn("Attempt to select disabled option: {}".format(self.value or self.text)) self.base.select_option()
Returns the given expression filtered by the given value.
def apply_filter(self, expr, value): """ Returns the given expression filtered by the given value. Args: expr (xpath.expression.AbstractExpression): The expression to filter. value (object): The desired value with which the expression should be filtered. Returns: xpath.expression.AbstractExpression: The filtered expression. """ if self.skip(value): return expr if not self._valid_value(value): msg = "Invalid value {value} passed to filter {name} - ".format( value=repr(value), name=self.name) if self.default is not None: warn(msg + "defaulting to {}".format(self.default)) value = self.default else: warn(msg + "skipping") return expr return self.func(expr, value)
Returns an instance of the given browser with the given capabilities.
def get_browser(browser_name, capabilities=None, **options): """ Returns an instance of the given browser with the given capabilities. Args: browser_name (str): The name of the desired browser. capabilities (Dict[str, str | bool], optional): The desired capabilities of the browser. Defaults to None. options: Arbitrary keyword arguments for the browser-specific subclass of :class:`webdriver.Remote`. Returns: WebDriver: An instance of the desired browser. """ if browser_name == "chrome": return webdriver.Chrome(desired_capabilities=capabilities, **options) if browser_name == "edge": return webdriver.Edge(capabilities=capabilities, **options) if browser_name in ["ff", "firefox"]: return webdriver.Firefox(capabilities=capabilities, **options) if browser_name in ["ie", "internet_explorer"]: return webdriver.Ie(capabilities=capabilities, **options) if browser_name == "phantomjs": return webdriver.PhantomJS(desired_capabilities=capabilities, **options) if browser_name == "remote": return webdriver.Remote(desired_capabilities=capabilities, **options) if browser_name == "safari": return webdriver.Safari(desired_capabilities=capabilities, **options) raise ValueError("unsupported browser: {}".format(repr(browser_name)))
Dict [ str Any ]: The keyword arguments with which this query was initialized.
def kwargs(self): """ Dict[str, Any]: The keyword arguments with which this query was initialized. """ kwargs = {} kwargs.update(self.options) kwargs.update(self.filter_options) return kwargs
str: A long description of this query.
def description(self): """ str: A long description of this query. """ description = self.label if self.locator: description += " {}".format(desc(self.locator)) if self.options["text"] is not None: description += " with text {}".format(desc(self.options["text"])) description += self.selector.description(self.filter_options) return description
str: The desired element visibility.
def visible(self): """ str: The desired element visibility. """ if self.options["visible"] is not None: if self.options["visible"] is True: return "visible" elif self.options["visible"] is False: return "all" else: return self.options["visible"] else: if capybara.ignore_hidden_elements: return "visible" else: return "all"
Returns the XPath query for this selector.
def xpath(self, exact=None): """ Returns the XPath query for this selector. Args: exact (bool, optional): Whether to exactly match text. Returns: str: The XPath query for this selector. """ exact = exact if exact is not None else self.exact if isinstance(self.expression, AbstractExpression): expression = self._apply_expression_filters(self.expression) return to_xpath(expression, exact=exact) else: return str_(self.expression)
Resolves this query relative to the given node.
def resolve_for(self, node, exact=None): """ Resolves this query relative to the given node. Args: node (node.Base): The node relative to which this query should be resolved. exact (bool, optional): Whether to exactly match text. Returns: list[Element]: A list of elements matched by this query. """ from capybara.driver.node import Node from capybara.node.element import Element from capybara.node.simple import Simple @node.synchronize def resolve(): if self.selector.format == "css": children = node._find_css(self.css()) else: children = node._find_xpath(self.xpath(exact)) def wrap(child): if isinstance(child, Node): return Element(node.session, child, node, self) else: return Simple(child) children = [wrap(child) for child in children] return Result(children, self) return resolve()
Returns whether the given node matches all filters.
def matches_filters(self, node): """ Returns whether the given node matches all filters. Args: node (Element): The node to evaluate. Returns: bool: Whether the given node matches. """ visible = self.visible if self.options["text"]: if isregex(self.options["text"]): regex = self.options["text"] elif self.exact_text is True: regex = re.compile(r"\A{}\Z".format(re.escape(self.options["text"]))) else: regex = toregex(self.options["text"]) text = normalize_text( node.all_text if visible == "all" else node.visible_text) if not regex.search(text): return False if isinstance(self.exact_text, (bytes_, str_)): regex = re.compile(r"\A{}\Z".format(re.escape(self.exact_text))) text = normalize_text( node.all_text if visible == "all" else node.visible_text) if not regex.search(text): return False if visible == "visible": if not node.visible: return False elif visible == "hidden": if node.visible: return False for name, node_filter in iter(self._node_filters.items()): if name in self.filter_options: if not node_filter.matches(node, self.filter_options[name]): return False elif node_filter.has_default: if not node_filter.matches(node, node_filter.default): return False if self.options["filter"] and not self.options["filter"](node): return False return True
node. Base: The current node relative to which all interaction will be scoped.
def current_scope(self): """ node.Base: The current node relative to which all interaction will be scoped. """ scope = self._scopes[-1] if scope in [None, "frame"]: scope = self.document return scope
str: Path of the current page without any domain information.
def current_path(self): """ str: Path of the current page, without any domain information. """ if not self.current_url: return path = urlparse(self.current_url).path return path if path else None
str: Host of the current page.
def current_host(self): """ str: Host of the current page. """ if not self.current_url: return result = urlparse(self.current_url) scheme, netloc = result.scheme, result.netloc host = netloc.split(":")[0] if netloc else None return "{0}://{1}".format(scheme, host) if host else None
Navigate to the given URL. The URL can either be a relative URL or an absolute URL. The behavior of either depends on the driver.::
def visit(self, visit_uri): """ Navigate to the given URL. The URL can either be a relative URL or an absolute URL. The behavior of either depends on the driver. :: session.visit("/foo") session.visit("http://google.com") For drivers which can run against an external application, such as the Selenium driver, giving an absolute URL will navigate to that page. This allows testing applications running on remote servers. For these drivers, setting :data:`capybara.app_host` will make the remote server the default. For example:: capybara.app_host = "http://google.com" session.visit("/") # visits the Google homepage Args: visit_uri (str): The URL to navigate to. """ self.raise_server_error() visit_uri = urlparse(visit_uri) if capybara.app_host: uri_base = urlparse(capybara.app_host) elif self.server: uri_base = urlparse("http://{}:{}".format(self.server.host, self.server.port)) else: uri_base = None visit_uri = ParseResult( scheme=visit_uri.scheme or (uri_base.scheme if uri_base else ""), netloc=visit_uri.netloc or (uri_base.netloc if uri_base else ""), path=visit_uri.path, params=visit_uri.params, query=visit_uri.query, fragment=visit_uri.fragment) self.driver.visit(visit_uri.geturl())
Executes the wrapped code within the context of a node. scope takes the same options as: meth: find. For the duration of the context any command to Capybara will be handled as though it were scoped to the given element.::
def scope(self, *args, **kwargs): """ Executes the wrapped code within the context of a node. ``scope`` takes the same options as :meth:`find`. For the duration of the context, any command to Capybara will be handled as though it were scoped to the given element. :: with scope("xpath", "//div[@id='delivery-address']"): fill_in("Street", value="12 Main Street") Just as with :meth:`find`, if multiple elements match the selector given to ``scope``, an error will be raised, and just as with :meth:`find`, this behavior can be controlled through the ``match`` and ``exact`` options. It is possible to omit the first argument, in that case, the selector is assumed to be of the type set in :data:`capybara.default_selector`. :: with scope("div#delivery-address"): fill_in("Street", value="12 Main Street") Note that a lot of uses of ``scope`` can be replaced more succinctly with chaining:: find("div#delivery-address").fill_in("Street", value="12 Main Street") Args: *args: Variable length argument list for the call to :meth:`find`. **kwargs: Arbitrary keywords arguments for the call to :meth:`find`. """ new_scope = args[0] if isinstance(args[0], Base) else self.find(*args, **kwargs) self._scopes.append(new_scope) try: yield finally: self._scopes.pop()
Execute the wrapped code within the given iframe using the given frame or frame name/ id. May not be supported by all drivers.
def frame(self, locator=None, *args, **kwargs): """ Execute the wrapped code within the given iframe using the given frame or frame name/id. May not be supported by all drivers. Args: locator (str | Element, optional): The name/id of the frame or the frame's element. Defaults to the only frame in the document. """ self.switch_to_frame(self._find_frame(locator, *args, **kwargs)) try: yield finally: self.switch_to_frame("parent")
Switch to the given frame.
def switch_to_frame(self, frame): """ Switch to the given frame. If you use this method you are responsible for making sure you switch back to the parent frame when done in the frame changed to. :meth:`frame` is preferred over this method and should be used when possible. May not be supported by all drivers. Args: frame (Element | str): The iframe/frame element to switch to. """ if isinstance(frame, Element): self.driver.switch_to_frame(frame) self._scopes.append("frame") elif frame == "parent": if self._scopes[-1] != "frame": raise ScopeError("`switch_to_frame(\"parent\")` cannot be called " "from inside a descendant frame's `scope` context.") self._scopes.pop() self.driver.switch_to_frame("parent") elif frame == "top": if "frame" in self._scopes: idx = self._scopes.index("frame") if any([scope not in ["frame", None] for scope in self._scopes[idx:]]): raise ScopeError("`switch_to_frame(\"top\")` cannot be called " "from inside a descendant frame's `scope` context.") self._scopes = self._scopes[:idx] self.driver.switch_to_frame("top") else: raise ValueError( "You must provide a frame element, \"parent\", or \"top\" " "when calling switch_to_frame")
If window is a lambda it switches to the first window for which window returns a value other than False or None. If a window that matches can t be found the window will be switched back and: exc: WindowError will be raised.
def switch_to_window(self, window, wait=None): """ If ``window`` is a lambda, it switches to the first window for which ``window`` returns a value other than False or None. If a window that matches can't be found, the window will be switched back and :exc:`WindowError` will be raised. Args: window (Window | lambda): The window that should be switched to, or a filtering lambda. wait (int | float, optional): The number of seconds to wait to find the window. Returns: Window: The new current window. Raises: ScopeError: If this method is invoked inside :meth:`scope, :meth:`frame`, or :meth:`window`. WindowError: If no window matches the given lambda. """ if len(self._scopes) > 1: raise ScopeError( "`switch_to_window` is not supposed to be invoked from " "within `scope`s, `frame`s, or other `window`s.") if isinstance(window, Window): self.driver.switch_to_window(window.handle) return window else: @self.document.synchronize(errors=(WindowError,), wait=wait) def switch_and_get_matching_window(): original_window_handle = self.driver.current_window_handle try: for handle in self.driver.window_handles: self.driver.switch_to_window(handle) result = window() if result: return Window(self, handle) except Exception: self.driver.switch_to_window(original_window_handle) raise self.driver.switch_to_window(original_window_handle) raise WindowError("Could not find a window matching lambda") return switch_and_get_matching_window()
This method does the following:
def window(self, window): """ This method does the following: 1. Switches to the given window (it can be located by window instance/lambda/string). 2. Executes the given block (within window located at previous step). 3. Switches back (this step will be invoked even if exception happens at second step). Args: window (Window | lambda): The desired :class:`Window`, or a lambda that will be run in the context of each open window and returns ``True`` for the desired window. """ original = self.current_window if window != original: self.switch_to_window(window) self._scopes.append(None) try: yield finally: self._scopes.pop() if original != window: self.switch_to_window(original)
Get the window that has been opened by the passed lambda. It will wait for it to be opened ( in the same way as other Capybara methods wait ). It s better to use this method than windows [ - 1 ] as order of windows isn t defined in some drivers __.
def window_opened_by(self, trigger_func, wait=None): """ Get the window that has been opened by the passed lambda. It will wait for it to be opened (in the same way as other Capybara methods wait). It's better to use this method than ``windows[-1]`` `as order of windows isn't defined in some drivers`__. __ https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 Args: trigger_func (func): The function that should trigger the opening of a new window. wait (int | float, optional): Maximum wait time. Defaults to :data:`capybara.default_max_wait_time`. Returns: Window: The window that has been opened within the lambda. Raises: WindowError: If lambda passed to window hasn't opened window or opened more than one window. """ old_handles = set(self.driver.window_handles) trigger_func() @self.document.synchronize(wait=wait, errors=(WindowError,)) def get_new_window(): opened_handles = set(self.driver.window_handles) - old_handles if len(opened_handles) != 1: raise WindowError("lambda passed to `window_opened_by` " "opened {0} windows instead of 1".format(len(opened_handles))) return Window(self, list(opened_handles)[0]) return get_new_window()
Execute the given script not returning a result. This is useful for scripts that return complex objects such as jQuery statements. execute_script should be used over: meth: evaluate_script whenever possible.
def execute_script(self, script, *args): """ Execute the given script, not returning a result. This is useful for scripts that return complex objects, such as jQuery statements. ``execute_script`` should be used over :meth:`evaluate_script` whenever possible. Args: script (str): A string of JavaScript to execute. *args: Variable length argument list to pass to the executed JavaScript string. """ args = [arg.base if isinstance(arg, Base) else arg for arg in args] self.driver.execute_script(script, *args)
Evaluate the given JavaScript and return the result. Be careful when using this with scripts that return complex objects such as jQuery statements.: meth: execute_script might be a better alternative.
def evaluate_script(self, script, *args): """ Evaluate the given JavaScript and return the result. Be careful when using this with scripts that return complex objects, such as jQuery statements. :meth:`execute_script` might be a better alternative. Args: script (str): A string of JavaScript to evaluate. *args: Variable length argument list to pass to the executed JavaScript string. Returns: object: The result of the evaluated JavaScript (may be driver specific). """ args = [arg.base if isinstance(arg, Base) else arg for arg in args] result = self.driver.evaluate_script(script, *args) return self._wrap_element_script_result(result)
Execute the wrapped code accepting an alert.
def accept_alert(self, text=None, wait=None): """ Execute the wrapped code, accepting an alert. Args: text (str | RegexObject, optional): Text to match against the text in the modal. wait (int | float, optional): Maximum time to wait for the modal to appear after executing the wrapped code. Raises: ModalNotFound: If a modal dialog hasn't been found. """ wait = wait or capybara.default_max_wait_time with self.driver.accept_modal("alert", text=text, wait=wait): yield
Execute the wrapped code accepting a confirm.
def accept_confirm(self, text=None, wait=None): """ Execute the wrapped code, accepting a confirm. Args: text (str | RegexObject, optional): Text to match against the text in the modal. wait (int | float, optional): Maximum time to wait for the modal to appear after executing the wrapped code. Raises: ModalNotFound: If a modal dialog hasn't been found. """ with self.driver.accept_modal("confirm", text=text, wait=wait): yield
Execute the wrapped code dismissing a confirm.
def dismiss_confirm(self, text=None, wait=None): """ Execute the wrapped code, dismissing a confirm. Args: text (str | RegexObject, optional): Text to match against the text in the modal. wait (int | float, optional): Maximum time to wait for the modal to appear after executing the wrapped code. Raises: ModalNotFound: If a modal dialog hasn't been found. """ with self.driver.dismiss_modal("confirm", text=text, wait=wait): yield
Execute the wrapped code accepting a prompt optionally responding to the prompt.
def accept_prompt(self, text=None, response=None, wait=None): """ Execute the wrapped code, accepting a prompt, optionally responding to the prompt. Args: text (str | RegexObject, optional): Text to match against the text in the modal. response (str, optional): Response to provide to the prompt. wait (int | float, optional): Maximum time to wait for the modal to appear after executing the wrapped code. Raises: ModalNotFound: If a modal dialog hasn't been found. """ with self.driver.accept_modal("prompt", text=text, response=response, wait=wait): yield
Execute the wrapped code dismissing a prompt.
def dismiss_prompt(self, text=None, wait=None): """ Execute the wrapped code, dismissing a prompt. Args: text (str | RegexObject, optional): Text to match against the text in the modal. wait (int | float, optional): Maximum time to wait for the modal to appear after executing the wrapped code. Raises: ModalNotFound: If a modal dialog hasn't been found. """ with self.driver.dismiss_modal("prompt", text=text, wait=wait): yield
Save a snapshot of the page.
def save_page(self, path=None): """ Save a snapshot of the page. If invoked without arguments, it will save a file to :data:`capybara.save_path` and the file will be given a randomly generated filename. If invoked with a relative path, the path will be relative to :data:`capybara.save_path`. Args: path (str, optional): The path to where it should be saved. Returns: str: The path to which the file was saved. """ path = _prepare_path(path, "html") with open(path, "wb") as f: f.write(encode_string(self.body)) return path
Save a screenshot of the page.
def save_screenshot(self, path=None, **kwargs): """ Save a screenshot of the page. If invoked without arguments, it will save a file to :data:`capybara.save_path` and the file will be given a randomly generated filename. If invoked with a relative path, the path will be relative to :data:`capybara.save_path`. Args: path (str, optional): The path to where it should be saved. **kwargs: Arbitrary keywords arguments for the driver. Returns: str: The path to which the file was saved. """ path = _prepare_path(path, "png") self.driver.save_screenshot(path, **kwargs) return path
Reset the session ( i. e. remove cookies and navigate to a blank page ).
def reset(self): """ Reset the session (i.e., remove cookies and navigate to a blank page). This method does not: * accept modal dialogs if they are present (the Selenium driver does, but others may not), * clear the browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc., or * modify the state of the driver/underlying browser in any other way as doing so would result in performance downsides and it's not needed to do everything from the list above for most apps. If you want to do anything from the list above on a general basis you can write a test teardown method. """ self.driver.reset() if self.server: self.server.wait_for_pending_requests() self.raise_server_error()
Raise errors encountered by the server.
def raise_server_error(self): """ Raise errors encountered by the server. """ if self.server and self.server.error: try: if capybara.raise_server_errors: raise self.server.error finally: self.server.reset_error()
Returns whether the given node matches the filter rule with the given value.
def matches(self, node, value): """ Returns whether the given node matches the filter rule with the given value. Args: node (Element): The node to filter. value (object): The desired value with which the node should be evaluated. Returns: bool: Whether the given node matches. """ if self.skip(value): return True if not self._valid_value(value): msg = "Invalid value {value} passed to filter {name} - ".format( value=repr(value), name=self.name) if self.default is not None: warn(msg + "defaulting to {}".format(self.default)) value = self.default else: warn(msg + "skipping") return True return self.func(node, value)
str: The package version.
def get_version(): """ str: The package version. """ global_vars = {} # Compile and execute the individual file to prevent # the package from being automatically loaded. source = read(os.path.join("capybara", "version.py")) code = compile(source, "version.py", "exec") exec(code, global_vars) return global_vars['__version__']
Resolves this query relative to the given node.
def resolves_for(self, node): """ Resolves this query relative to the given node. Args: node (node.Document): The node to be evaluated. Returns: bool: Whether the given node matches this query. """ self.actual_title = normalize_text(node.title) return bool(self.search_regexp.search(self.actual_title))
str: The title for the current frame.
def frame_title(self): """ str: The title for the current frame. """ elements = self._find_xpath("/html/head/title") titles = [element.all_text for element in elements] return titles[0] if len(titles) else ""
str: The value of the form element.
def value(self): """ str: The value of the form element. """ if self.tag_name == "textarea": return inner_content(self.native) elif self.tag_name == "select": if self["multiple"] == "multiple": selected_options = self._find_xpath(".//option[@selected='selected']") return [_get_option_value(option) for option in selected_options] else: options = ( self._find_xpath(".//option[@selected='selected']") + self._find_xpath(".//option")) return _get_option_value(options[0]) if options else None elif self.tag_name == "input" and self["type"] in ["checkbox", "radio"]: return self["value"] or "on" else: return self["value"]
Builds and registers a global: class: FilterSet.
def add_filter_set(name): """ Builds and registers a global :class:`FilterSet`. Args: name (str): The name of the set. Yields: FilterSetFactory: A configurable factory for building a :class:`FilterSet`. """ factory = FilterSetFactory(name) yield factory filter_sets[name] = factory.build_filter_set()
Returns the: class: Session for the current driver and app instantiating one if needed.
def current_session(): """ Returns the :class:`Session` for the current driver and app, instantiating one if needed. Returns: Session: The :class:`Session` for the current driver and app. """ driver = current_driver or default_driver session_key = "{driver}:{session}:{app}".format( driver=driver, session=session_name, app=str(id(app))) session = _session_pool.get(session_key, None) if session is None: from capybara.session import Session session = Session(driver, app) _session_pool[session_key] = session return session
Checks if allof the provided selectors are present on the given page or descendants of the current node. If options are provided the assertion will check that each locator is present with those options as well ( other than wait ).::
def has_all_of_selectors(self, selector, *locators, **kwargs): """ Checks if allof the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.has_all_of_selectors("custom", "Tom", "Joe", visible="all") page.has_all_of_selectors("css", "#my_dif", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so all of the locators must be present within ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ return self.assert_all_of_selectors(selector, *locators, **kwargs)
Checks if none of the provided selectors are present on the given page or descendants of the current node. If options are provided the assertion will check that each locator is present with those options as well ( other than wait ).::
def has_none_of_selectors(self, selector, *locators, **kwargs): """ Checks if none of the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.has_none_of_selectors("custom", "Tom", "Joe", visible="all") page.has_none_of_selectors("css", "#my_div", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so none of the locators must be present with ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ return self.assert_none_of_selectors(selector, *locators, **kwargs)
Asserts that a given selector is on the page or a descendant of the current node.::
def assert_selector(self, *args, **kwargs): """ Asserts that a given selector is on the page or a descendant of the current node. :: page.assert_selector("p#foo") By default it will check if the expression occurs at least once, but a different number can be specified. :: page.assert_selector("p.foo", count=4) This will check if the expression occurs exactly 4 times. See :meth:`find_all` for other available result size options. If a ``count`` of 0 is specified, it will behave like :meth:`assert_no_selector`; however, use of that method is preferred over this one. It also accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. :: page.assert_selector("li", text="Horse", visible=True) ``assert_selector`` can also accept XPath expressions generated by the ``xpath-py`` package:: from xpath import dsl as x page.assert_selector("xpath", x.descendant("p")) Args: *args: Variable length argument list for :class:`SelectorQuery`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: True Raises: ExpectationNotMet: The given selector did not match. """ query = SelectorQuery(*args, **kwargs) @self.synchronize(wait=query.wait) def assert_selector(): result = query.resolve_for(self) if not (result.matches_count and (len(result) > 0 or expects_none(query.options))): raise ExpectationNotMet(result.failure_message) return True return assert_selector()
Asserts that an element has the specified CSS styles.::
def assert_style(self, styles, **kwargs): """ Asserts that an element has the specified CSS styles. :: element.assert_style({"color": "rgb(0,0,255)", "font-size": re.compile(r"px")}) Args: styles (Dict[str, str | RegexObject]): The expected styles. Returns: True Raises: ExpectationNotMet: The element doesn't have the specified styles. """ query = StyleQuery(styles, **kwargs) @self.synchronize(wait=query.wait) def assert_style(): if not query.resolves_for(self): raise ExpectationNotMet(query.failure_message) return True return assert_style()
Asserts that all of the provided selectors are present on the given page or descendants of the current node. If options are provided the assertion will check that each locator is present with those options as well ( other than wait ).::
def assert_all_of_selectors(self, selector, *locators, **kwargs): """ Asserts that all of the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.assert_all_of_selectors("custom", "Tom", "Joe", visible="all") page.assert_all_of_selectors("css", "#my_dif", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so all of the locators must be present within ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ wait = kwargs['wait'] if 'wait' in kwargs else capybara.default_max_wait_time if not isinstance(selector, Hashable) or selector not in selectors: locators = (selector,) + locators selector = capybara.default_selector @self.synchronize(wait=wait) def assert_all_of_selectors(): for locator in locators: self.assert_selector(selector, locator, **kwargs) return True return assert_all_of_selectors()
Asserts that none of the provided selectors are present on the given page or descendants of the current node. If options are provided the assertion will check that each locator is present with those options as well ( other than wait ).::
def assert_none_of_selectors(self, selector, *locators, **kwargs): """ Asserts that none of the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.assert_none_of_selectors("custom", "Tom", "Joe", visible="all") page.assert_none_of_selectors("css", "#my_div", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so none of the locators must be present with ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ wait = kwargs['wait'] if 'wait' in kwargs else capybara.default_max_wait_time if not isinstance(selector, Hashable) or selector not in selectors: locators = (selector,) + locators selector = capybara.default_selector @self.synchronize(wait=wait) def assert_none_of_selectors(): for locator in locators: self.assert_no_selector(selector, locator, **kwargs) return True return assert_none_of_selectors()
Asserts that a given selector is not on the page or a descendant of the current node. Usage is identical to: meth: assert_selector.
def assert_no_selector(self, *args, **kwargs): """ Asserts that a given selector is not on the page or a descendant of the current node. Usage is identical to :meth:`assert_selector`. Query options such as ``count``, ``minimum``, and ``between`` are considered to be an integral part of the selector. This will return True, for example, if a page contains 4 anchors but the query expects 5:: page.assert_no_selector("a", minimum=1) # Found, raises ExpectationNotMet page.assert_no_selector("a", count=4) # Found, raises ExpectationNotMet page.assert_no_selector("a", count=5) # Not Found, returns True Args: *args: Variable length argument list for :class:`SelectorQuery`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: True Raises: ExpectationNotMet: The given selector matched. """ query = SelectorQuery(*args, **kwargs) @self.synchronize(wait=query.wait) def assert_no_selector(): result = query.resolve_for(self) if result.matches_count and ( len(result) > 0 or expects_none(query.options)): raise ExpectationNotMet(result.negative_failure_message) return True return assert_no_selector()
Asserts that the current node matches a given selector.::
def assert_matches_selector(self, *args, **kwargs): """ Asserts that the current node matches a given selector. :: node.assert_matches_selector("p#foo") node.assert_matches_selector("xpath", "//p[@id='foo']") It also accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. :: node.assert_matches_selector("li", text="Horse", visible=True) Args: *args: Variable length argument list for :class:`SelectorQuery`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: True Raises: ExpectationNotMet: If the selector does not match. """ query = SelectorQuery(*args, **kwargs) @self.synchronize(wait=query.wait) def assert_matches_selector(): result = query.resolve_for(self.find_first("xpath", "./parent::*", minimum=0) or self.query_scope) if self not in result: raise ExpectationNotMet("Item does not match the provided selector") return True return assert_matches_selector()
Checks if the page or current node has a radio button or checkbox with the given label value or id that is currently checked.
def has_checked_field(self, locator, **kwargs): """ Checks if the page or current node has a radio button or checkbox with the given label, value, or id, that is currently checked. Args: locator (str): The label, name, or id of a checked field. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: bool: Whether it exists. """ kwargs["checked"] = True return self.has_selector("field", locator, **kwargs)
Checks if the page or current node has no radio button or checkbox with the given label value or id that is currently checked.
def has_no_checked_field(self, locator, **kwargs): """ Checks if the page or current node has no radio button or checkbox with the given label, value, or id that is currently checked. Args: locator (str): The label, name, or id of a checked field. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: bool: Whether it doesn't exist. """ kwargs["checked"] = True return self.has_no_selector("field", locator, **kwargs)
Checks if the page or current node has a radio button or checkbox with the given label value or id that is currently unchecked.
def has_unchecked_field(self, locator, **kwargs): """ Checks if the page or current node has a radio button or checkbox with the given label, value, or id, that is currently unchecked. Args: locator (str): The label, name, or id of an unchecked field. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: bool: Whether it exists. """ kwargs["checked"] = False return self.has_selector("field", locator, **kwargs)
Checks if the page or current node has no radio button or checkbox with the given label value or id that is currently unchecked.
def has_no_unchecked_field(self, locator, **kwargs): """ Checks if the page or current node has no radio button or checkbox with the given label, value, or id, that is currently unchecked. Args: locator (str): The label, name, or id of an unchecked field. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: bool: Whether it doesn't exist. """ kwargs["checked"] = False return self.has_no_selector("field", locator, **kwargs)
Asserts that the page or current node has the given text content ignoring any HTML tags.
def assert_text(self, *args, **kwargs): """ Asserts that the page or current node has the given text content, ignoring any HTML tags. Args: *args: Variable length argument list for :class:`TextQuery`. **kwargs: Arbitrary keyword arguments for :class:`TextQuery`. Returns: True Raises: ExpectationNotMet: If the assertion hasn't succeeded during the wait time. """ query = TextQuery(*args, **kwargs) @self.synchronize(wait=query.wait) def assert_text(): count = query.resolve_for(self) if not (matches_count(count, query.options) and (count > 0 or expects_none(query.options))): raise ExpectationNotMet(query.failure_message) return True return assert_text()
Asserts that the page or current node doesn t have the given text content ignoring any HTML tags.
def assert_no_text(self, *args, **kwargs): """ Asserts that the page or current node doesn't have the given text content, ignoring any HTML tags. Args: *args: Variable length argument list for :class:`TextQuery`. **kwargs: Arbitrary keyword arguments for :class:`TextQuery`. Returns: True Raises: ExpectationNotMet: If the assertion hasn't succeeded during the wait time. """ query = TextQuery(*args, **kwargs) @self.synchronize(wait=query.wait) def assert_no_text(): count = query.resolve_for(self) if matches_count(count, query.options) and ( count > 0 or expects_none(query.options)): raise ExpectationNotMet(query.negative_failure_message) return True return assert_no_text()
Asserts that the page has the given title.
def assert_title(self, title, **kwargs): """ Asserts that the page has the given title. Args: title (str | RegexObject): The string or regex that the title should match. **kwargs: Arbitrary keyword arguments for :class:`TitleQuery`. Returns: True Raises: ExpectationNotMet: If the assertion hasn't succeeded during the wait time. """ query = TitleQuery(title, **kwargs) @self.synchronize(wait=query.wait) def assert_title(): if not query.resolves_for(self): raise ExpectationNotMet(query.failure_message) return True return assert_title()
Asserts that the page doesn t have the given title.
def assert_no_title(self, title, **kwargs): """ Asserts that the page doesn't have the given title. Args: title (str | RegexObject): The string that the title should include. **kwargs: Arbitrary keyword arguments for :class:`TitleQuery`. Returns: True Raises: ExpectationNotMet: If the assertion hasn't succeeded during the wait time. """ query = TitleQuery(title, **kwargs) @self.synchronize(wait=query.wait) def assert_no_title(): if query.resolves_for(self): raise ExpectationNotMet(query.negative_failure_message) return True return assert_no_title()
Checks if the page has the given title.
def has_title(self, title, **kwargs): """ Checks if the page has the given title. Args: title (str | RegexObject): The string or regex that the title should match. **kwargs: Arbitrary keyword arguments for :class:`TitleQuery`. Returns: bool: Whether it matches. """ try: self.assert_title(title, **kwargs) return True except ExpectationNotMet: return False
Checks if the page doesn t have the given title.
def has_no_title(self, title, **kwargs): """ Checks if the page doesn't have the given title. Args: title (str | RegexObject): The string that the title should include. **kwargs: Arbitrary keyword arguments for :class:`TitleQuery`. Returns: bool: Whether it doesn't match. """ try: self.assert_no_title(title, **kwargs) return True except ExpectationNotMet: return False
Find all elements on the page matching the given selector and options.
def find_all(self, *args, **kwargs): """ Find all elements on the page matching the given selector and options. Both XPath and CSS expressions are supported, but Capybara does not try to automatically distinguish between them. The following statements are equivalent:: page.find_all("css", "a#person_123") page.find_all("xpath", "//a[@id='person_123']") If the type of selector is left out, Capybara uses :data:`capybara.default_selector`. It's set to ``"css"`` by default. :: page.find_all("a#person_123") capybara.default_selector = "xpath" page.find_all("//a[@id='person_123']") The set of found elements can further be restricted by specifying options. It's possible to select elements by their text or visibility:: page.find_all("a", text="Home") page.find_all("#menu li", visible=True) By default if no elements are found, an empty list is returned; however, expectations can be set on the number of elements to be found which will trigger Capybara's waiting behavior for the expectations to match. The expectations can be set using:: page.assert_selector("p#foo", count=4) page.assert_selector("p#foo", maximum=10) page.assert_selector("p#foo", minimum=1) page.assert_selector("p#foo", between=range(1, 11)) See :func:`capybara.result.Result.matches_count` for additional information about count matching. Args: *args: Variable length argument list for :class:`SelectorQuery`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: Result: A collection of found elements. Raises: ExpectationNotMet: The matched results did not meet the expected criteria. """ query = SelectorQuery(*args, **kwargs) @self.synchronize(wait=query.wait) def find_all(): result = query.resolve_for(self) if not result.matches_count: raise ExpectationNotMet(result.failure_message) return result return find_all()
Find the first element on the page matching the given selector and options or None if no element matches.
def find_first(self, *args, **kwargs): """ Find the first element on the page matching the given selector and options, or None if no element matches. By default, no waiting behavior occurs. However, if ``capybara.wait_on_first_by_default`` is set to true, it will trigger Capybara's waiting behavior for a minimum of 1 matching element to be found. Args: *args: Variable length argument list for :class:`SelectorQuery`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: Element: The found element or None. """ if capybara.wait_on_first_by_default: kwargs.setdefault("minimum", 1) try: result = self.find_all(*args, **kwargs) return result[0] if len(result) > 0 else None except ExpectationNotMet: return None
Resolves this query relative to the given node.
def resolve_for(self, node): """ Resolves this query relative to the given node. Args: node (node.Base): The node to be evaluated. Returns: int: The number of matches found. """ self.node = node self.actual_text = normalize_text( node.visible_text if self.query_type == "visible" else node.all_text) self.count = len(re.findall(self.search_regexp, self.actual_text)) return self.count
Returns the inner content of a given XML node including tags.
def inner_content(node): """ Returns the inner content of a given XML node, including tags. Args: node (lxml.etree.Element): The node whose inner content is desired. Returns: str: The inner content of the node. """ from lxml import etree # Include text content at the start of the node. parts = [node.text] for child in node.getchildren(): # Include the child serialized to raw XML. parts.append(etree.tostring(child, encoding="utf-8")) # Include any text following the child. parts.append(child.tail) # Discard any non-existent text parts and return. return "".join(filter(None, parts))
Returns the inner text of a given XML node excluding tags.
def inner_text(node): """ Returns the inner text of a given XML node, excluding tags. Args: node: (lxml.etree.Element): The node whose inner text is desired. Returns: str: The inner text of the node. """ from lxml import etree # Include text content at the start of the node. parts = [node.text] for child in node.getchildren(): # Include the raw text content of the child. parts.append(etree.tostring(child, encoding="utf-8", method="text")) # Include any text following the child. parts.append(child.tail) # Discard any non-existent text parts and return. return "".join(map(decode_bytes, filter(None, parts)))