def get_current_menu_state(self): """Returns the current menu state This function returns what each level of the menu is pointing to, or None, if that level of menu is unused. Future work could possibly see this method using recursion to allow unlimited levels of menu to be used, however it is unlikely that more than 3 will ever be used. """ lev = [None, None, None] lev[0] = (sel.text(self.CURRENT_TOP_MENU).encode("utf-8").strip()) if version.current_version() < "5.6.0.1": try: lev[1] = sel.text("//nav[contains(@class, 'navbar')]//ul/li[@class='active']/a") \ .encode("utf-8").strip() except NoSuchElementException: pass else: lev[1] = sel.get_attribute("{}{}".format( self.CURRENT_TOP_MENU, self.ACTIVE_LEV), "textContent").encode("utf-8").strip() try: lev[2] = sel.get_attribute("{}{}{}".format( self.CURRENT_TOP_MENU, self.ACTIVE_LEV, self.ACTIVE_LEV), "textContent") \ .encode("utf-8").strip() except NoSuchElementException: pass return lev
def get_all_vms(do_not_navigate=False): """Returns list of all vms""" if not do_not_navigate: sel.force_navigate('infra_vms') vms = set([]) # This is really stupid, but I cannot come up with better getting of the attributes :( if not paginator.page_controls_exist(): for title in sel.elements(QUADICON_TITLE_LOCATOR): title_value = sel.get_attribute(title, "title") if not title_value: title_value = sel.get_attribute(title, "data-original-title") vms.add(title_value) return vms paginator.results_per_page(1000) for page in paginator.pages(): try: for page in paginator.pages(): for title in sel.elements(QUADICON_TITLE_LOCATOR): title_value = sel.get_attribute(title, "title") if not title_value: title_value = sel.get_attribute(title, "data-original-title") vms.add(title_value) except sel.NoSuchElementException: pass return vms
def load(self): self._keys = [] key_values = [] for row in sel.elements(self.ROWS, root=self._entry): tds = sel.elements('./td', root=row) key = tds[0] klass = sel.get_attribute(key, 'class') if klass and 'label' in klass: # Ordinary field key_id = attributize_string(sel.text_sane(key)) value = tuple(tds[1:]) try: rowspan = int(sel.get_attribute(key, 'rowspan')) except (ValueError, TypeError): rowspan = None if rowspan: key_values.append((key, key_id, [value])) else: key_values.append((key, key_id, value)) else: # value of last key_values should be extended key_values[-1][2].append(tuple(tds)) for key, key_id, value in key_values: value_object = process_field(value) setattr(self, key_id, value_object) self._keys.append(key_id)
def get_all_vms(do_not_navigate=False): """Returns list of all vms""" if not do_not_navigate: sel.force_navigate('infra_vms') vms = set([]) # This is really stupid, but I cannot come up with better getting of the attributes :( if not paginator.page_controls_exist(): for title in sel.elements(QUADICON_TITLE_LOCATOR): title_value = sel.get_attribute(title, "title") if not title_value: title_value = sel.get_attribute(title, "data-original-title") vms.add(title_value) return vms paginator.results_per_page(1000) for page in paginator.pages(): try: for page in paginator.pages(): for title in sel.elements(QUADICON_TITLE_LOCATOR): title_value = sel.get_attribute(title, "title") if not title_value: title_value = sel.get_attribute( title, "data-original-title") vms.add(title_value) except sel.NoSuchElementException: pass return vms
def f(_): # Can't do this currently because silly menu traps us # if is_page_active(toplevel, secondlevel): # return if callable(toplevel): top_level = toplevel() else: top_level = toplevel if secondlevel is not None: if callable(secondlevel): second_level = secondlevel() else: second_level = secondlevel if secondlevel.startswith('/'): active_loc = (TOP_LEV_ACTIVE + SECOND_LEV_ACTIVE_HREF).format( top_level, second_level) inactive_loc = (TOP_LEV_INACTIVE + SECOND_LEV_INACTIVE_HREF).format( top_level, second_level) else: active_loc = (TOP_LEV_ACTIVE + SECOND_LEV_ACTIVE).format( top_level, second_level) inactive_loc = (TOP_LEV_INACTIVE + SECOND_LEV_INACTIVE).format( top_level, second_level) el = "{} | {}".format(active_loc, inactive_loc) try: href = sel.get_attribute(el, 'href') sel.execute_script('document.location.href="{}"'.format(href)) except NoSuchElementException: raise else: active_loc = TOP_LEV_ACTIVE.format(top_level) inactive_loc = TOP_LEV_INACTIVE.format(top_level) el = "{} | {}".format(active_loc, inactive_loc) try: href = sel.get_attribute(el, 'href') sel.execute_script('document.location.href="{}"'.format(href)) except NoSuchElementException: raise sel.wait_for_ajax() if reset_action is not None: try: if callable(reset_action): reset_action() else: sel.click(reset_action) except NoSuchElementException: if _final: # We have tried to renavigate but still some problem. Never mind and explode. raise else: # Work around the problem when the display selector disappears after returning # from VM summary view. Can be fixed by renavigating, it then appears again. nav_to_fn(toplevel, secondlevel, reset_action, _final=True) # todo move to element on the active tab to clear the menubox sel.wait_for_ajax()
def get_current_menu_state(self): """Returns the current menu state This function returns what each level of the menu is pointing to, or None, if that level of menu is unused. Future work could possibly see this method using recursion to allow unlimited levels of menu to be used, however it is unlikely that more than 3 will ever be used. """ lev = [None, None, None] lev[0] = (sel.text(self.CURRENT_TOP_MENU).encode("utf-8").strip()) if version.current_version() < "5.6.0.1": try: lev[1] = sel.text("//nav[contains(@class, 'navbar')]//ul/li[@class='active']/a") \ .encode("utf-8").strip() except NoSuchElementException: pass else: lev[1] = sel.get_attribute("{}{}".format( self.CURRENT_TOP_MENU, self.ACTIVE_LEV), "textContent").encode("utf-8").strip() try: lev[2] = sel.get_attribute("{}{}{}".format( self.CURRENT_TOP_MENU, self.ACTIVE_LEV, self.ACTIVE_LEV), "textContent") \ .encode("utf-8").strip() except NoSuchElementException: pass return lev
def content_type(self): if version.current_version() <= "5.4": return sel.get_attribute(self._content_type.format(self._div_id), "class").strip() else: return sel.get_attribute(self._content_type.format(self._div_id), "class").rsplit(" ", 1)[-1]
def load(self): self._keys = [] key_values = [] if sel.is_displayed(self.MULTIKEY_LOC, root=self._entry): # WE cannot process this kind of table yet. return for row in sel.elements(self.ROWS, root=self._entry): tds = sel.elements('./td', root=row) key = tds[0] klass = sel.get_attribute(key, 'class') if klass and 'label' in klass: # Ordinary field key_id = attributize_string(sel.text_sane(key)) value = tuple(tds[1:]) try: rowspan = int(sel.get_attribute(key, 'rowspan')) except (ValueError, TypeError): rowspan = None if rowspan: key_values.append((key, key_id, [value])) else: key_values.append((key, key_id, value)) else: # value of last key_values should be extended key_values[-1][2].append(tuple(tds)) for key, key_id, value in key_values: value_object = process_field(value) setattr(self, key_id, value_object) self._keys.append(key_id)
def f(_): # Can't do this currently because silly menu traps us # if is_page_active(toplevel, secondlevel): # return if callable(toplevel): top_level = toplevel() else: top_level = toplevel if secondlevel is not None: if callable(secondlevel): second_level = secondlevel() else: second_level = secondlevel if secondlevel.startswith('/'): active_loc = (TOP_LEV_ACTIVE + SECOND_LEV_ACTIVE_HREF).format( top_level, second_level) inactive_loc = (TOP_LEV_INACTIVE + SECOND_LEV_INACTIVE_HREF).format( top_level, second_level) else: active_loc = (TOP_LEV_ACTIVE + SECOND_LEV_ACTIVE).format(top_level, second_level) inactive_loc = (TOP_LEV_INACTIVE + SECOND_LEV_INACTIVE).format( top_level, second_level) el = "{} | {}".format(active_loc, inactive_loc) try: href = sel.get_attribute(el, 'href') sel.execute_script('document.location.href="{}"'.format(href)) except NoSuchElementException: raise else: active_loc = TOP_LEV_ACTIVE.format(top_level) inactive_loc = TOP_LEV_INACTIVE.format(top_level) el = "{} | {}".format(active_loc, inactive_loc) try: href = sel.get_attribute(el, 'href') sel.execute_script('document.location.href="{}"'.format(href)) except NoSuchElementException: raise sel.wait_for_ajax() if reset_action is not None: try: if callable(reset_action): reset_action() else: sel.click(reset_action) except NoSuchElementException: if _final: # We have tried to renavigate but still some problem. Never mind and explode. raise else: # Work around the problem when the display selector disappears after returning # from VM summary view. Can be fixed by renavigating, it then appears again. nav_to_fn(toplevel, secondlevel, reset_action, _final=True) # todo move to element on the active tab to clear the menubox sel.wait_for_ajax()
def _fill_recordgrouper(rg, d): logger.info(" Filling {} with data {}".format(str(rg), str(d))) for row_column_name, content in d.iteritems(): row = rg.table.find_row("column_name", row_column_name) if version.current_version() >= "5.5": select = sel.element("./select", root=row.calculations) select_id = sel.get_attribute(select, "id") fill(AngularSelect(select_id, multi=True), content) else: fill(PivotCalcSelect(sel.get_attribute(row.calculations, "id")), content)
def _fill_recordgrouper(rg, d): logger.info(" Filling {} with data {}".format(str(rg), str(d))) for row_column_name, content in d.iteritems(): row = rg.table.find_row("column_name", row_column_name) if version.current_version() >= "5.5": select = sel.element("./select", root=row.calculations) select_id = sel.get_attribute(select, "id") fill(AngularSelect(select_id, multi=True), content) else: fill(PivotCalcSelect(sel.get_attribute(row.calculations, "id")), content)
def is_dimmed(btn): tag = sel.tag(btn) if tag in {"li", "img"}: class_attr = sel.get_attribute(btn, "class") elif tag == "span": class_attr = sel.get_attribute(sel.element("..", root=btn), "class") else: raise TypeError("Wrong tag name {}".format(tag)) class_att = set(re.split(r"\s+", class_attr)) if {"dimmed", "disabled"}.intersection(class_att): return True
def is_dimmed(btn): tag = sel.tag(btn) if tag in {"li", "img"}: class_attr = sel.get_attribute(btn, "class") elif tag == "span": class_attr = sel.get_attribute(sel.element("..", root=btn), "class") else: raise TypeError("Wrong tag name {}".format(tag)) class_att = set(re.split(r"\s+", class_attr)) if {"dimmed", "disabled"}.intersection(class_att): return True
def is_internal(title): """ Checks if the link leads internally or not Args: title: The title of the button to check. Returns: ``True`` if the element is an internal link, ``False`` if not. """ loc = sel.element(locate(title)) href = sel.get_attribute(loc, 'href').replace(sel.base_url(), '') img = sel.element('//div[@class="panecontent"]//a[@href="%s"]/img' % href) if 'internal' in sel.get_attribute(img, 'src'): return True else: return False
def f(_): # Can't do this currently because silly menu traps us # if is_page_active(toplevel, secondlevel): # return if callable(toplevel): top_level = toplevel() else: top_level = toplevel if secondlevel is not None: if callable(secondlevel): second_level = secondlevel() else: second_level = secondlevel if secondlevel.startswith('/'): active_loc = (TOP_LEV_ACTIVE + SECOND_LEV_ACTIVE_HREF).format( top_level, second_level) inactive_loc = (TOP_LEV_INACTIVE + SECOND_LEV_INACTIVE_HREF).format( top_level, second_level) else: active_loc = (TOP_LEV_ACTIVE + SECOND_LEV_ACTIVE).format(top_level, second_level) inactive_loc = (TOP_LEV_INACTIVE + SECOND_LEV_INACTIVE).format( top_level, second_level) el = "{} | {}".format(active_loc, inactive_loc) try: href = sel.get_attribute(el, 'href') sel.execute_script('document.location.href="{}"'.format(href)) except NoSuchElementException: raise else: active_loc = TOP_LEV_ACTIVE.format(top_level) inactive_loc = TOP_LEV_INACTIVE.format(top_level) el = "{} | {}".format(active_loc, inactive_loc) try: href = sel.get_attribute(el, 'href') sel.execute_script('document.location.href="{}"'.format(href)) except NoSuchElementException: raise sel.wait_for_ajax() if reset_action is not None: if callable(reset_action): reset_action() else: sel.click(reset_action) # todo move to element on the active tab to clear the menubox sel.wait_for_ajax()
def is_task_finished(tab, page, task_name, expected_status, clear_tasks_after_success=True): el = None try: if not sel.is_displayed(tasks_table) or not tabs.is_tab_selected(tab): sel.force_navigate(page) el = tasks_table.find_row_by_cells({ 'task_name': task_name, 'state': expected_status }) if el is None: return False except Exception: return False # throw exception if status is error if 'Error' in sel.get_attribute(sel.element('.//td/img', root=el), 'title'): raise Exception("Task {} errored".format(task_name)) if clear_tasks_after_success: # Remove all finished tasks so they wouldn't poison other tests toolbar.select('Delete Tasks', 'Delete All', invokes_alert=True) sel.handle_alert(cancel=False) return True
def all(cls): """For debugging purposes""" return [ cls(sel.get_attribute(x, "id")) for x in sel.elements("//td[contains(@id, 'pivotcalc_id_')]") ]
def is_vm_analysis_finished(vm_name): """ Check if analysis is finished - if not, reload page """ el = None try: if not pytest.sel.is_displayed(tasks.tasks_table) or \ not tabs.is_tab_selected('All VM Analysis Tasks'): pytest.sel.force_navigate('tasks_all_vm') el = tasks.tasks_table.find_row_by_cells({ 'task_name': "Scan from Vm {}".format(vm_name), 'state': 'finished' }) if el is None: return False except: return False # throw exception if status is error if 'Error' in sel.get_attribute(sel.element('.//td/img', root=el), 'title'): raise Exception("Smart State Analysis errored") # Remove all finished tasks so they wouldn't poison other tests tb.select('Delete Tasks', 'Delete All', invokes_alert=True) sel.handle_alert(cancel=False) return True
def mapping(self): """Determine mapping Menu item => menu item id. Needed because the boxes with shortcuts are accessible only via ids. Need to close boxes because boxes displayed are not in the Select. """ # Save opened boxes closed_boxes = [] for box_id in self.opened_boxes_ids: closed_boxes.append((self.get_text_of(box_id), box_id)) self.close_box(box_id) # Check the select result = {} for option in self.select.options: try: result[sel.text(option)] = int( sel.get_attribute(option, "value")) except (ValueError, TypeError): pass # Restore box layout for name, id in closed_boxes: sel.select(self.select, sel.ByValue(str(id))) self.set_text_of(id, name) return result
def all(cls): """For debugging purposes""" return [ cls(sel.get_attribute(x, "id")) for x in sel.elements("//td[contains(@id, 'pivotcalc_id_')]") ]
def is_selected(self): """Looks whether this option is selected""" self._check_exists() e = sel.element(self.locate(), root=self.root) parent_li = sel.element('..', root=e) return 'active' in (sel.get_attribute(parent_li, 'class') or '') # Ensure it is a str
def test_perf_ui_infra_resource_pools(ui_worker_pid, soft_assert): pages, prod_tail = standup_perf_ui(ui_worker_pid, soft_assert) nav_limit = 0 if 'resource_pools' in perf_tests['ui']['page_check']['infrastructure']: nav_limit = perf_tests['ui']['page_check']['infrastructure'][ 'resource_pools'] pages.extend( analyze_page_stat( perf_click(ui_worker_pid, prod_tail, True, sel.force_navigate, 'infrastructure_resource_pools'), soft_assert)) resource_pools = set([]) for page in paginator.pages(): for title in sel.elements( "//div[@id='quadicon']/../../../tr/td/a[contains(@href," "'resource_pool/show')]"): resource_pools.add(sel.get_attribute(title, "title")) acc_bars = ['Properties', 'Relationships'] pages.extend( navigate_quadicons(resource_pools, 'resource_pool', 'infrastructure_resource_pools', nav_limit, ui_worker_pid, prod_tail, soft_assert, acc_bars)) pages_to_csv(pages, 'perf_ui_infra_resource_pools.csv') pages_to_statistics_csv(pages, resource_pool_filters, 'ui-statistics.csv')
def all(cls): """Returns objects with all Widgets currently present.""" sel.force_navigate('dashboard') result = [] for el in sel.elements(cls._all): result.append(cls(sel.get_attribute(el, "id"))) return result
def tree(name, *path): """Get underlying Tree() object. And eventually click path. If the accordion is not active, will be clicked. Attention! The object is 'live' so when it's obscured, it won't work! Usage: accordion.tree("Something").click_path("level 1", "level 2") accordion.tree("Something", "level 1", "level 2") # is the same Args: *path: If specified, it will directly pass these parameters into click_path of Tree. Otherwise it returns the Tree object. """ try: if not is_active(name): click(name) except AccordionItemNotFound: click(name) root_element = sel.element(locate(name)) if sel.is_displayed(DYNATREE, root=root_element): # Dynatree detected tree = Tree(sel.element(DYNATREE, root=root_element)) elif sel.is_displayed(TREEVIEW, root=root_element): # treeview detected el = sel.element(TREEVIEW, root=root_element) tree_id = sel.get_attribute(el, 'id') tree = BootstrapTreeview(tree_id) if path: return tree.click_path(*path) else: return tree
def all(cls): """Returns objects with all Widgets currently present.""" navigate_to(Server, 'Dashboard') result = [] for el in sel.elements(cls._all): result.append(cls(sel.get_attribute(el, "id"))) return result
def test_modify_action(random_action): new_name = randomness.generate_random_string() with update(random_action): random_action.description = new_name flash.assert_no_errors() sel.force_navigate("control_explorer_action_edit", context={"action_name": random_action.description}) assert sel.get_attribute(random_action.form.description, "value").strip() == new_name
def opened_boxes_ids(self): """Return ids of all opened boxes.""" return [ # it's like 's_3' int(sel.get_attribute(el, "id").rsplit("_", 1)[-1]) for el in sel.elements("//div[@title='Drag this Shortcut to a new location']") if sel.is_displayed(el) ]
def left_half_size(): if not sel.is_displayed(screen_splitter) or not sel.is_displayed(left_half): return None style = sel.get_attribute(left_half, "style") match = re.search(r"width:\s*(\d+)px", style) if match is None: return None return int(match.groups()[0])
def message(el): """ Turns an element into a :py:class:`Message` object. Args: el: The element containing the flass message. Returns: A :py:class:`Message` object. """ return Message(message=sel.text(el), level=sel.get_attribute(el, 'class'))
def change_stored_password(): try: if version.current_version() > '5.5': sel.execute_script( sel.get_attribute( sel.element('//a[@id="change_stored_password"]'), 'onClick')) except NoSuchElementException: logger.info('Change stored PW not found, probably no creds already') return
def opened_boxes_ids(self): """Return ids of all opened boxes.""" return [ # it's like 's_3' int(sel.get_attribute(el, "id").rsplit("_", 1)[-1]) for el in sel.elements( "//div[@title='Drag this Shortcut to a new location']") if sel.is_displayed(el) ]
def change_stored_password(): if sel.is_displayed(_stored_pw_script): sel.execute_script( sel.get_attribute(sel.element(_stored_pw_script), 'onClick')) sel.wait_for_ajax() # To play safe elif sel.is_displayed(_stored_pw_angular): sel.click(_stored_pw_angular) else: logger.info("Probably no creds")
def get_form(self, blank=False): """Gets a form for a field that already exists (by its name). Or if blank=True, get the form for a new field. Must be on the correct page before calling this. """ idx = "" if blank: row_id = "" # for new entries, id attribute has no trailing '_x' else: idx = sel.get_attribute( "//input[starts-with(@id, 'fields_name') and @value='%s']" % self.name, 'id').split("_")[-1] row_id = "_" + idx def loc(fmt, underscore=True): if blank: plural = "" else: plural = "s" return fmt % (plural, row_id if underscore else row_id.lstrip("_")) def remove(loc): """Return a callable that clicks but still allows popup dismissal""" return lambda _: sel.click(loc, wait_ajax=False) return Form(fields=[ ('name_text', Input(loc('field%s_name%s'))), ('type_select', { version.LOWEST: DHTMLSelect(loc("//div[@id='field%s_aetype_id%s']")), "5.5": AngularSelect(loc("field%s_aetype%s", underscore=False)) }), ('data_type_select', { version.LOWEST: DHTMLSelect(loc("//div[@id='field%s_datatype_id%s']")), "5.5": AngularSelect(loc("field%s_datatype%s", underscore=False)) }), ('default_value_text', Input(loc('field%s_default_value%s'))), ('display_name_text', Input(loc('field%s_display_name%s')) ), ('description_text', Input(loc('field%s_description%s')) ), ('sub_cb', Input(loc('field%s_substitution%s')) ), ('collect_text', Input(loc('field%s_collect%s'))), ('message_text', Input(loc('field%s_message%s')) ), ('on_entry_text', Input(loc('field%s_on_entry%s')) ), ('on_exit_text', Input(loc('field%s_on_exit%s'))), ('max_retries_text', Input(loc('field%s_max_retries%s')) ), ('max_time_text', Input(loc('field%s_max_time%s')) ), ('add_entry_button', "//img[@alt='Add this entry']"), ('remove_entry_button', remove("//a[(contains(@title, 'delete this') or " "contains(@confirm, 'delete field')) and " "contains(@href, 'arr_id=%s')]/img" % idx)) ])
def change_stored_password(): if version.current_version() > '5.5': if sel.is_displayed(_stored_pw_script): sel.execute_script( sel.get_attribute(sel.element(_stored_pw_script), 'onClick')) sel.wait_for_ajax() # To play safe elif sel.is_displayed(_stored_pw_angular): sel.click(_stored_pw_angular) else: logger.info("Probably no creds")
def get_all_hosts(do_not_navigate=False): """Returns list of all hosts""" if not do_not_navigate: navigate_to(Host, 'All') hosts = set([]) for page in paginator.pages(): for title in sel.elements( "//div[@id='quadicon']/../../../tr/td/a[contains(@href,'host/show')]"): hosts.add(sel.get_attribute(title, "title")) return hosts
def get_all_hosts(do_not_navigate=False): """Returns list of all hosts""" if not do_not_navigate: sel.force_navigate('infrastructure_hosts') hosts = set([]) for page in paginator.pages(): for title in sel.elements( "//div[@id='quadicon']/../../../tr/td/a[contains(@href,'host/show')]"): hosts.add(sel.get_attribute(title, "title")) return hosts
def get_all_clusters(do_not_navigate=False): """Returns list of all clusters""" if not do_not_navigate: sel.force_navigate('infrastructure_clusters') clusters = set([]) for page in paginator.pages(): for title in sel.elements( "//div[@id='quadicon']/../../../tr/td/a[contains(@href,'cluster/show')]"): clusters.add(sel.get_attribute(title, "title")) return clusters
def test_about_links(): sel.force_navigate('about') for link_key, link_loc in about.product_assistance.locators.items(): href = sel.get_attribute(link_loc, 'href') try: resp = requests.head(href, verify=False, timeout=20) except (requests.Timeout, requests.ConnectionError) as ex: pytest.fail(ex.message) assert 200 <= resp.status_code < 400, "Unable to access '{}' ({})".format(link_key, href)
def old_select(root, sub=None, invokes_alert=False): """ Clicks on a button by calling the dhtmlx toolbar callEvent. Args: root: The root button's name as a string. sub: The sub button's name as a string. (optional) invokes_alert: If ``True``, then the behaviour is little bit different. After the last click, no ajax wait and no move away is done to be able to operate the alert that appears after click afterwards. Defaults to ``False``. Returns: ``True`` if everything went smoothly Raises: :py:class:`cfme.exceptions.ToolbarOptionGreyedOrUnavailable` """ # wait for ajax on select to prevent pickup up a toolbar button in the middle of a page change sel.wait_for_ajax() if isinstance(root, dict): root = version.pick(root) if sub is not None and isinstance(sub, dict): sub = version.pick(sub) root_obj = version.pick({ '5.4': 'miq_toolbars', '5.5.0.7': 'ManageIQ.toolbars' }) if sub: search = sub_loc(sub) else: search = root_loc(root) eles = sel.elements(search) for ele in eles: idd = sel.get_attribute(ele, 'idd') if idd: break else: raise ToolbarOptionGreyedOrUnavailable( "Toolbar button {}/{} is greyed or unavailable!".format(root, sub)) buttons = sel.execute_script('return {}'.format(root_obj)) tb_name = None for tb_key, tb_obj in buttons.iteritems(): for btn_key, btn_obj in tb_obj['buttons'].iteritems(): if btn_obj['name'] == idd: tb_name = tb_key if not tb_name: raise ToolbarOptionGreyedOrUnavailable( "Toolbar button {}/{} is greyed or unavailable!".format(root, sub)) sel.execute_script("{}['{}']['obj'].callEvent('onClick', ['{}'])".format( root_obj, tb_name, idd)) if not invokes_alert: sel.wait_for_ajax() return True
def test_about_links(): sel.force_navigate('about') for link_key, link_loc in about.product_assistance.locators.items(): href = sel.get_attribute(link_loc, 'href') try: resp = requests.head(href, verify=False, timeout=20) except (requests.Timeout, requests.ConnectionError) as ex: pytest.fail(ex.message) assert resp.status_code == 200,\ "Unable to access link '{}' ({})".format(link_key, href)
def get_all_providers(do_not_navigate=False): """Returns list of all providers""" if not do_not_navigate: navigate_to(CloudProvider, 'All') providers = set([]) link_marker = "ems_cloud" for page in paginator.pages(): for title in sel.elements("//div[@id='quadicon']/../../../tr/td/a[contains(@href," "'{}/show')]".format(link_marker)): providers.add(sel.get_attribute(title, "title")) return providers
def selected_field_element(self): """Return selected field's element. Returns: :py:class:`WebElement` if field is selected, else `None` """ selected_fields = filter(lambda el: "cellselected" in sel.get_attribute(el, "class"), self._all_fields) if len(selected_fields) == 0: return None else: return selected_fields[0]
def _get_accordion_collapsed(name): """ Returns if an accordion is collapsed or not, used with is_active Args: name: The name of the accordion Returns: ``True`` if the accordion is open, ``False`` if it is closed. """ if version.current_version() < '5.5.0.6': root = sel.element(locate(name)) # It seems there are two possibilities, so let's handle both. loc = "|".join([ "./{}/{}".format(DHX_LABEL, DHX_ARROW), "../{}".format(DHX_ARROW)]) el = sel.element(loc, root=root) class_att = sel.get_attribute(el, 'class').split(" ") return "item_opened" in class_att else: class_att = sel.get_attribute(sel.element(locate(name)), 'class').split(" ") return "collapsed" not in class_att
def selected_field_element(self): """Return selected field's element. Returns: :py:class:`WebElement` if field is selected, else `None` """ selected_fields = filter(lambda el: "cellselected" in sel.get_attribute(el, "class"), self._all_fields) if len(selected_fields) == 0: return None else: return selected_fields[0]
def get_datastores(self): """ Gets list of all datastores used by this host""" sel.force_navigate('infrastructure_host', context={'host': self}) list_acc.select('Relationships', 'Datastores', by_title=False, partial=True) datastores = set([]) for page in paginator.pages(): for title in sel.elements( "//div[@id='quadicon']/../../../tr/td/a[contains(@href,'storage/show')]"): datastores.add(sel.get_attribute(title, "title")) return datastores
def get_datastores(self): """ Gets list of all datastores used by this host""" sel.force_navigate('infrastructure_host', context={'host': self}) list_acc.select('Relationships', 'Show all Datastores') datastores = set([]) for page in paginator.pages(): for title in sel.elements( "//div[@id='quadicon']/../../../tr/td/a[contains(@href,'storage/show')]"): datastores.add(sel.get_attribute(title, "title")) return datastores
def get_all_providers(do_not_navigate=False): """Returns list of all providers""" if not do_not_navigate: sel.force_navigate('clouds_providers') providers = set([]) link_marker = "ems_cloud" for page in paginator.pages(): for title in sel.elements("//div[@id='quadicon']/../../../tr/td/a[contains(@href," "'{}/show')]".format(link_marker)): providers.add(sel.get_attribute(title, "title")) return providers
def is_internal(self): """ Checks if the link leads internally or not Returns: ``True`` if the element is an internal link, ``False`` if not. """ self._check_exists() el = sel.element(self.locate(), root=self.root) img = sel.element('./img', root=el) if 'internal' in sel.get_attribute(img, 'src'): return True else: return False
def old_select(root, sub=None, invokes_alert=False): """ Clicks on a button by calling the dhtmlx toolbar callEvent. Args: root: The root button's name as a string. sub: The sub button's name as a string. (optional) invokes_alert: If ``True``, then the behaviour is little bit different. After the last click, no ajax wait and no move away is done to be able to operate the alert that appears after click afterwards. Defaults to ``False``. Returns: ``True`` if everything went smoothly Raises: :py:class:`cfme.exceptions.ToolbarOptionGreyedOrUnavailable` """ # wait for ajax on select to prevent pickup up a toolbar button in the middle of a page change sel.wait_for_ajax() if isinstance(root, dict): root = version.pick(root) if sub is not None and isinstance(sub, dict): sub = version.pick(sub) root_obj = version.pick({'5.4': 'miq_toolbars', '5.5.0.7': 'ManageIQ.toolbars'}) if sub: search = sub_loc(sub) else: search = root_loc(root) eles = sel.elements(search) for ele in eles: idd = sel.get_attribute(ele, 'idd') if idd: break else: raise ToolbarOptionGreyedOrUnavailable( "Toolbar button {}/{} is greyed or unavailable!".format(root, sub)) buttons = sel.execute_script('return {}'.format(root_obj)) tb_name = None for tb_key, tb_obj in buttons.iteritems(): for btn_key, btn_obj in tb_obj['buttons'].iteritems(): if btn_obj['name'] == idd: tb_name = tb_key if not tb_name: raise ToolbarOptionGreyedOrUnavailable( "Toolbar button {}/{} is greyed or unavailable!".format(root, sub)) sel.execute_script( "{}['{}']['obj'].callEvent('onClick', ['{}'])".format(root_obj, tb_name, idd)) if not invokes_alert: sel.wait_for_ajax() return True
def all_selected(self): result = [] for item in self._selected.options: sync = None desc = sel.text(item).encode("utf-8").lstrip() value = sel.get_attribute(item, "value") if self._sync: # Or _async, this does not matter, protected in constructor # Extract sync_res, desc = re.match(r"^\(([AS])\) (.*?)$", desc).groups() sync = sync_res == "S" result.append(SelectItem(sync=sync, value=value, text=desc)) return result
def all_selected(self): result = [] for item in self._selected.options: sync = None desc = sel.text(item).encode("utf-8").lstrip() value = sel.get_attribute(item, "value") if self._sync: # Or _async, this does not matter, protected in constructor # Extract sync_res, desc = re.match(r"^\(([AS])\) (.*?)$", desc).groups() sync = sync_res == "S" result.append(SelectItem(sync=sync, value=value, text=desc)) return result
def get_all_providers(do_not_navigate=False): """Returns list of all providers""" if not do_not_navigate: sel.force_navigate("clouds_providers") providers = set([]) link_marker = version.pick({version.LOWEST: "ext_management_system", "5.2.5": "ems_cloud"}) for page in paginator.pages(): for title in sel.elements( "//div[@id='quadicon']/../../../tr/td/a[contains(@href," "'{}/show')]".format(link_marker) ): providers.add(sel.get_attribute(title, "title")) return providers
def is_internal(self): """ Checks if the link leads internally or not Returns: ``True`` if the element is an internal link, ``False`` if not. """ self._check_exists() el = sel.element(self.locate(), root=self.root) img = sel.element('./img', root=el) if 'internal' in sel.get_attribute(img, 'src'): return True else: return False
def is_active(root): """ Checks if a button is currently depressed Args: root: The root button's name as a string. Returns: ``True`` if the button is depressed, ``False`` if not. """ el = sel.element(root_loc(root)) class_att = sel.get_attribute(el, 'class').split(" ") if {"pres", "active", "pres_dis"}.intersection(set(class_att)): return True else: return False
def is_active(root): """ Checks if a button is currently depressed Args: root: The root button's name as a string. Returns: ``True`` if the button is depressed, ``False`` if not. """ el = sel.element(root_loc(root)) class_att = sel.get_attribute(el, 'class').split(" ") if "over" in class_att: return True else: return False
def is_active(root): """ Checks if a button is currently depressed Args: root: The root button's name as a string. Returns: ``True`` if the button is depressed, ``False`` if not. """ el = sel.element(root_loc(root)) class_att = sel.get_attribute(el, 'class').split(" ") if {"pres", "active", "pres_dis"}.intersection(set(class_att)): return True else: return False
def is_greyed(root, sub=None): """ Checks if a button is greyed out. Args: root: The root button's name as a string. Returns: ``True`` if the button is greyed, ``False`` if not. """ if sub: btn = sub_loc(sub) else: btn = root_loc(root) el = sel.element(btn) class_att = sel.get_attribute(el, "class").split(" ") if sub: if {"tr_btn_disabled", "disabled"}.intersection(set(class_att)): logger.debug("%s option greyed out, mouseover reason: %s", sub, sel.get_attribute(el, "title")) return True else: if {"disabled", "dis"}.intersection(set(class_att)): return True return False
def is_greyed(root, sub=None): """ Checks if a button is greyed out. Args: root: The root button's name as a string. Returns: ``True`` if the button is greyed, ``False`` if not. """ if sub: btn = sub_loc(sub) else: btn = root_loc(root) el = sel.element(btn) class_att = sel.get_attribute(el, 'class').split(" ") if sub: if {"tr_btn_disabled", "disabled"}.intersection(set(class_att)): logger.debug("{} option greyed out, mouseover reason: {}".format( sub, sel.get_attribute(el, 'title'))) return True else: if {"disabled", "dis"}.intersection(set(class_att)): return True return False
def test_about_links(): sel.force_navigate('about') for link_key, link_loc in about.product_assistance.locators.items(): # If its a dict to be ver-picked and the resulting loc is None if isinstance(link_loc, dict) and version.pick(link_loc) is None: logger.info("Skipping link '{}'; not present in this version".format(link_key)) continue href = sel.get_attribute(link_loc, 'href') try: resp = requests.head(href, verify=False, timeout=20) except (requests.Timeout, requests.ConnectionError) as ex: pytest.fail(ex.message) assert 200 <= resp.status_code < 400, "Unable to access '{}' ({})".format(link_key, href)