def wait_for_element_location(self, locator): """ Wait for an element location to complete animation. Useful to wait for pages to load when there's animation. Examples: | Wait for Element Location | id=my_div | """ # find the element on the page el = self._element_find(locator, True, True) if el is None: logger._warn( "wait_for_element_location(): Failed to locate element '%s' on page" % locator) return False cur_location = el.location location_changing = True start = datetime.datetime.now() # wait for the width to stop changing while location_changing and ( datetime.datetime.now() - start).total_seconds() < self.get_selenium_timeout(): # too frequent checking will result in a false positive self.built_in.sleep(0.5) if el.location != cur_location: cur_location = el.location else: location_changing = False return True
def _retrieve_general_data(OAIP, bay_no, Formfactor_dict, hw_type, *enclosure_obj): """Reads the data of enclosure from datafile and retrieves server information and returns in the form of lists.""" ret_val = (True, []) if isinstance(enclosure_obj, test_data.DataObj): enclosure_obj = [enclosure_obj] elif isinstance(enclosure_obj, tuple): enclosure_obj = list(enclosure_obj[0][0]) enclosure_data = "" for enclosure in enclosure_obj: if enclosure.oa1hostname == OAIP: enclosure_data = enclosure break if enclosure_data == "": logger._log_to_console_and_log_file( "Given encolsure " "%s" " information is not available in the data file please verify" % OAIP) ret_val = (False, []) else: try: formfactor = Formfactor_dict[hw_type] OA_info_obj = blade_info(OAIP, enclosure_data.oa1username, enclosure_data.oa1password) model = str( OA_info_obj.get_server_model_from_OA(bay_no)).strip(' ') ret_val = [True, [model, formfactor]] except Exception as e: ret_val = (False, []) logger._warn( "Given hardware type %s formfactor is not updated in the resource file. Exception is %s" % (hw_type, e)) return ret_val
def wait_for_checkbox_and_unselect(locator, timeout=5, fail_if_false=False): """Selects checkbox identified by `locator`. Does nothing if checkbox is already selected. Key attributes for checkboxes are `id` and `name`. See `introduction` for details about locating elements. :param locator: expression for locating checkbox element :param timeout: in second, the method will return None or throw exception if can't get checkbox unselected in specified time :param fail_if_false: set to True to fail the test case if can't get checkbox unselected in :timeout seconds :return: """ start = datetime.now() while (datetime.now() - start).total_seconds() < timeout: try: wait_for_element(locator) element = get_s2l()._get_checkbox(locator) while element.is_selected(): element.click() element = get_s2l()._get_checkbox(locator) return element except Exception: time.sleep(0.1) if fail_if_false: fail_test("Failed to unselect checkbox: [ %s ] in %s seconds" % (locator, timeout)) logger._warn( "Failed to unselect checkbox within timeout due to StaleElementReferenceException on webelement" ) return None
def wait_for_element_expand(locator): """ wait_for_element_expand Description : Wait for an expanding element to complete animation | Useful to wait for pages to load when there's animation. """ selenium2lib = get_s2l() # find the element on the page el = selenium2lib._element_find(locator, True, True) if el is None: logger._warn( "wait_for_element_expand(): Failed to locate element '%s' on page" % locator) return False cur_width = el.size["width"] width_changing = True start = datetime.now() # wait for the width to stop changing while width_changing and (datetime.now() - start).total_seconds() < 5: # too frequent checking will result in a false positive BuiltIn().sleep(0.5) if el.size["width"] != cur_width: cur_width = el.size["width"] else: width_changing = False return True
def _verify_activity_owner(actname, resource, timestamp, assignusername): """ This function is to verify the user name once the activity is assigned to any user. This function is written wrt E2E UC3.it will work only when we pass all the four parameters. Example: _verify_activity_owner('Update started for interconnect CC-2-LI', 'CC-2-LI', 'Today 10.45 am', 'NetAdmin') """ selenium2lib = ui_lib.get_s2l() if not selenium2lib._is_element_present(FusionActivityPage.ID_PAGE_LABEL): selenium2lib.click_element(FusionUIBaseElements.ID_MAIN_MENU_CONTROL) ui_lib.wait_for_element_visible( FusionUIBaseElements.ID_MENU_LINK_ACTIVITY, PerfConstants.DEFAULT_SYNC_TIME) ui_lib.wait_for_element_and_click( FusionUIBaseElements.ID_MENU_LINK_ACTIVITY) ui_lib.wait_for_element_visible(FusionActivityPage.ID_PAGE_LABEL) actavailable = _is_element_present_activity_page_without_time( actname, resource) if actavailable: assignuser_name = selenium2lib.get_text( FusionActivityPage.ID_ASSIGNED_OWNER % (actname, resource, timestamp)) if assignuser_name == assignusername: logger._log_to_console_and_log_file( "Activity is available with assigned user name only") else: logger._warn( "Activity is not available with assigned user name") else: logger._warn("Assigned activity is not visible to this user %s" % assignusername)
def wait_for_element_location(locator, timeout=5): """ Description : Wait for an moving element to complete animation | Useful to wait for pages to load when there's animation. """ selenium2lib = get_s2l() el = selenium2lib._element_find(locator, True, True) if el is None: logger._warn( "wait_for_element_move(): Failed to locate element '%s' on page" % locator) return False cur_location = el.location location_changing = True start = datetime.now() while location_changing and (datetime.now() - start).total_seconds() < timeout: BuiltIn().sleep( 0.5) # too frequent checking will result in a false positive try: if el.location != cur_location: cur_location = el.location else: location_changing = False except (StaleElementReferenceException): pass return True
def get_errors_on_form(form_id): ''' Function to get all the errors seen on the form - Common for Create and edit operations Return error string separated by '\t' if errors are present else returns None ''' # if errors are seen then return a string of errors separated by \t else None error_elements = [] error_string = '' selenium2libObj = ui_lib.get_s2l() try: error_elements = selenium2libObj._current_browser().find_element_by_id( form_id).find_elements_by_class_name("hp-error") except: error_elements = [] if error_elements: logger._warn("Displaying Following errors : ...") for errorelement in error_elements: if errorelement.text is not None and errorelement.text != "": logger._warn("Error - '{}' for element : '{}'".format( errorelement.text, errorelement.get_attribute("for"))) error_string += errorelement.text + '\t' return error_string else: return None
def wait_for_element_resize(self, locator): """ wait_for_element_resize Description : Wait for an element resize to complete animation | Useful to wait for pages to load when there's animation. Examples: | Wait for Element Resize | css=#mydiv | """ # find the element on the page el = self._element_find(locator, True, True) if el is None: logger._warn( "wait_for_element_resize(): Failed to locate element '%s' on page" % locator) return False cur_width = el.size["width"] width_changing = True start = datetime.datetime.now() # wait for the width to stop changing while width_changing and ( datetime.datetime.now() - start).total_seconds() < self.get_selenium_timeout(): # too frequent checking will result in a false positive self.built_in.sleep(0.5) if el.size["width"] != cur_width: cur_width = el.size["width"] else: width_changing = False return True
def _retrieve_adapter_data(OAIP, bay_no, adapter_dict, *enclosure_obj): """Reads the data of enclosure from datafile and retrieves server information and returns in the form of lists.""" ret_val = (True, []) if isinstance(enclosure_obj, test_data.DataObj): enclosure_obj = [enclosure_obj] elif isinstance(enclosure_obj, tuple): enclosure_obj = list(enclosure_obj[0][0]) enclosure_data = "" for enclosure in enclosure_obj: if enclosure.oa1hostname == OAIP: enclosure_data = enclosure break if enclosure_data == "": logger._warn( "Given encolsure " "%s" " information is not available in the data file please verify" % OAIP) ret_val = (False, []) else: OA_info_obj = blade_info(OAIP, enclosure_data.oa1username, enclosure_data.oa1password) ret_val = OA_info_obj.get_server_adapter_information( bay_no, adapter_dict) return ret_val
def enable_switch_port(*switch_obj): """ Enable / Disable switch port Example: | Switch Enable Port | @{switch_list} """ if isinstance(switch_obj, test_data.DataObj): switch_obj = [switch_obj] elif isinstance(switch_obj, tuple): switch_obj = list(switch_obj[0]) navigate() for switch in switch_obj: logger.info("\nEditing Switch %s..." % switch.name) if (switch.name == ""): logger._warn("Mandatory field - name can't be empty") continue if not select_switch(switch.name): FusionUIBase.fail_test_or_return_false( "Switch [%s] is not selected " % switch.name) port_number = switch.port[2:] if int(switch.port[:1]) >= 2: port_number = str(int(port_number) + int(switch.increment)) if CommonOperationSwitches.edit_switch_port(port_number) is None: CommonOperationSwitches.click_ok_edit() return None CommonOperationSwitches.click_ok_edit() return CommonOperationSwitches.get_port_status(port_number)
def select_power_delivery_device(pddname): """ This function is to Select Power Delivery Device select_power_delivery_device Example: select_power_delivery_device(pddname) """ selenium2lib = ui_lib.get_s2l() navigate() if selenium2lib._is_element_present( FusionPowerDeliveryDevicePage.ID_PAGE_LABEL): """ check for Power Delivery Device exists """ if not (selenium2lib._is_element_present( FusionPowerDeliveryDevicePage.ID_ELEMENT_PDD_NAME_BASE % pddname.strip())): logger._warn("Power Delivery Device '%s' is not present" % pddname) selenium2lib.capture_page_screenshot() return False else: """ Select if Power Delivery Device exists """ ui_lib.wait_for_element_and_click( FusionPowerDeliveryDevicePage.ID_ELEMENT_PDD_NAME_BASE % pddname.strip()) ui_lib.wait_for_element( FusionPowerDeliveryDevicePage.ID_ELEMENT_PDD_NAME_BASE % pddname.strip() + "/ancestor::tr[contains(@class, hp-selected)]") # logger._log_to_console_and_log_file("Selected the Power Delivery Device %s successfully" % pddname) return True else: logger._log_to_console_and_log_file( "Fail in navigating to Power Delivery Device Page") selenium2lib.capture_page_screenshot() return False
def get_enclosure_manager_ip(variables): """ Get the floating IPv6 address of the active EM by logging into the CI and extracting the lldp data. """ if 'FUSION_IP' in variables: try: # Connect to the CI Manager. ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(variables['FUSION_IP'], username=variables['FUSION_SSH_USERNAME'], password=variables['FUSION_SSH_PASSWORD']) # We're connected. Let's run the command and get the output. print "SSH to CiMgr succeeded." stdin, stdout, stderr = ssh.exec_command("lldpcli show neighbor") output = stdout.read() # Find 'MgmtIP' followed by the IPv6 address. matches = re.search(r'MgmtIP:\s*(\S*:\S*:\S*:\S*:\S*:\S*)', output, re.MULTILINE) if matches: print "lldpcli call and regex match succeeded." return matches.group(1) except paramiko.BadHostKeyException: logger._warn( "Could not connect to %s because of BadKeyException. Need to clean up .ssh directory?" % variables['FUSION_IP']) except Exception as e: logger._warn( "Could not connect to %s to determine EM_IP address. \n%s" % (variables['FUSION_IP'], e)) return None
def edit_services_access(isEnabled): """ Edit Support Access: function to enable or disable support access """ s2l = ui_lib.get_s2l() if not ui_lib.wait_for_element(FusionSettingsPage.ID_PAGE_LABEL): navigate() logger._log_to_console_and_log_file("Edit services access") ui_lib.wait_for_element_and_click(FusionSettingsPage.ID_MENU_ACTION_MAIN_BTN) ui_lib.wait_for_element_and_click(FusionSettingsPage.ID_MENU_ACTION_EDIT_SUPPORT_ACCESS) ui_lib.wait_for_element_visible(FusionSettingsPage.ID_LABEL_EDIT_SUPPORT_ACCESS) editoption = s2l.get_text(FusionSettingsPage.ID_TOGGLE_BTN_SERVICE_ACCESS) if editoption.lower() == isEnabled.lower(): ui_lib.wait_for_element_and_click(FusionSettingsPage.ID_BTN_OK_SUPPORT_ACCESS) elif editoption == "Enabled" and isEnabled == "Disabled": ui_lib.wait_for_element_and_click(FusionSettingsPage.ID_TOGGLE_OFF) ui_lib.wait_for_element_and_click(FusionSettingsPage.ID_BTN_OK_SUPPORT_ACCESS) else: ui_lib.wait_for_element_and_click(FusionSettingsPage.ID_TOGGLE_ON) ui_lib.wait_for_element_and_click(FusionSettingsPage.ID_BTN_OK_SUPPORT_ACCESS) ui_lib.wait_for_element(FusionSettingsPage.ID_LABEL_STATUS) lablestatus = s2l.get_text(FusionSettingsPage.ID_LABEL_STATUS) if lablestatus.lower() == isEnabled.lower(): logger._log_to_console_and_log_file("Services access is successfully updated from '%s' to '%s'" % (editoption, isEnabled)) return True else: logger._warn("Failed to edit Services access ") return False
def is_visible(obj, timeout=5, fail_if_false=False): """ StaleElementException safe function to determine if a locator or webelement is visible. Works with either a locator or webelement object Example: v = is_visible("id=my_locator") v = is_visible(my_webelement_object) :param obj: expression as string for locating element, An object of WebElement :param timeout: in second, the method will return None or throw exception if can't locate element or the element not become visible in specified time :param fail_if_false: set to True to fail the test case if can't locate element or element not become visible in :timeout seconds :return: webelement if it becomes visible in specified timeout, otherwise None """ s2l = get_s2l() start = datetime.now() while (datetime.now() - start).total_seconds() < timeout: try: if isinstance(obj, str): return s2l._is_visible(obj) elif isinstance(obj, WebElement): return obj.is_displayed() else: raise TypeError("Cannot get text from unknown type {0}".format( type(obj))) except Exception: pass msg = "Failed to determine element's visibility within %s seconds due to NoSuchElementException, Timeout or StaleElementReferenceException " % timeout if fail_if_false is True: fail_test(msg) logger._warn(msg) return False
def _validate_general_information(hw_type, data_list): # Validating general tab information return_val = True selenium2lib = ui_lib.get_s2l() model = str( selenium2lib._get_text(FusionServerHardwareTypePage.ID_MODEL_TEXT)) formfactor = str( selenium2lib._get_text( FusionServerHardwareTypePage.ID_FORMFACTOR_TEXT)) if ([model, formfactor] == data_list): logger._log_to_console_and_log_file( "Values retrieved for the hardware type %s from appliance is %s and values from devices is %s" % (hw_type, str([model, formfactor]), str(data_list))) logger._log_to_console_and_log_file( "Server Hardware type general information is matching properly for the type: %s" % hw_type) else: logger._warn( "Values retrieved for the hardware type %s from appliance is %s and values from devices is %s" % (hw_type, str([model, formfactor]), str(data_list))) logger._warn( "Server Hardware type general information is mismatching for the type: %s" % hw_type) return_val = False return return_val
def navigate(): FusionUIBase.navigate_to_section(SectionType.VOLUME_TEMPLATES) selenium2lib = ui_lib.get_s2l() if not selenium2lib._is_element_present( FusionStorageTemplatesPage.ID_PAGE_LABEL): logger._warn("Failed to navigate to Storage Templates Page") return False else: return True
def add_datacenter(*datacenter_obj): ''' add_datacenter function to add data center into appliance ''' ''' QXCR1001317088 Racks layout is not resetting after clicking on ADD+ button in Data center page. In DataCenter page when we click on Add data center button by giving valid input , adding racks to the data center clicking on ADD+ button it is added , All the fields are getting reset except the racks and rack layout what we have added in previous data center, and when we are going to add one more data center by giving valid input ,adding racks to the data center we are not able to add data center. ''' logging._log_to_console_and_log_file("Adding Data center to the appliance") selenium2lib = ui_lib.get_s2l() navigate() flag = None if isinstance(datacenter_obj, test_data.DataObj): datacenter_obj = [datacenter_obj] elif isinstance(datacenter_obj, tuple): datacenter_obj = list(datacenter_obj[0]) # Go into adding the data center fail = 0 for datacenters in datacenter_obj: # Function to call _add_datacenter_property flag = _add_datacenter_property(datacenters) add_rack = None if datacenters.has_property('addrack'): add_rack = datacenters.addrack if add_rack is None: logging._log_to_console_and_log_file( "There is no new rack to be added") if isinstance(add_rack, (list)): for rack in add_rack: _add_rack_to_datacenter(rack) if flag: ui_lib.wait_for_element_and_click( FusionDataCenterPage.ID_BTN_ADD_DATACENTER) ui_lib.wait_for_element_visible( FusionDataCenterPage.ID_LINK_ADD_DATA_CENTER) if selenium2lib._is_element_present( FusionDataCenterPage.ID_LINK_ADD_DATA_CENTER): logging._log_to_console_and_log_file( "Data center is successfully added") else: logging._warn("Data Center is not added") selenium2lib.capture_page_screenshot() fail += 1 else: ui_lib.wait_for_element_and_click( FusionDataCenterPage.ID_BTN_CANCEL_PLUS_DATACENTER) logging._warn("Data center is not added") selenium2lib.capture_page_screenshot() fail += 1 if fail > 0: return False return True
def get_firefox_version(): """ Get Firefox version """ try: driver = webdriver.Firefox() version = driver.capabilities['version'] driver.quit() return version except: logger._warn("Couldn't get Firefox version") return False
def _validate_adapter_information(hw_type, data_list): # Validating adapter tab information return_val = True selenium2lib = ui_lib.get_s2l() count_hw_types_row = selenium2lib._element_find( FusionServerHardwareTypePage.ID_ADAPTER_INFO_TABLE_ROW, False, False) if (len(count_hw_types_row) == len(data_list)): for i in range(len(count_hw_types_row)): row_data = [] row_content = len( selenium2lib._element_find( FusionServerHardwareTypePage. ID_ADAPTER_INFO_TABLE_SPECIFIC_ROW % str(i + 1), False, False)) # retrieving the data from the hardware types page. for l in range(row_content): ui_lib.wait_for_element( FusionServerHardwareTypePage. ID_ADAPTER_INFO_TABLE_SPECIFIC_ROW % str(i + 1), PerfConstants.DEFAULT_SYNC_TIME) row_data.append( str( selenium2lib._get_text( FusionServerHardwareTypePage. ID_ADAPTER_INFO_TABLE_SPECIFIC_CELL % (str(i + 1), str(l + 1))))) localflag = False # Comparing the retrieved values with each type information retrieved from the device. for listdat in data_list: if (row_data[1] in listdat[1]): if ((row_data[0] == listdat[0]) and (row_data[1] == listdat[1].strip('\r')) and (row_data[2] == listdat[2]) and (((row_data[3].replace(' ', '')).strip("/s")) == listdat[3]) and (row_data[4] == listdat[4])): localflag = True else: logger._log_to_console_and_log_file( "Server Hardware type adapter information is mismatching for the adapter: %s" % row_data[1]) if not localflag: return_val = False logger._warn( "Server Hardware type adapter information is mismatching for the type: %s" % hw_type) else: logger._log_to_console_and_log_file( "Server Hardware type adapter information is matching properly for the type: %s" % hw_type) else: return_val = False logger._warn( "Server Hardware type information is mismatching for the type: %s" % hw_type) return return_val
def export_and_verify_inventory_reports(inventory_path, inventory_name): """ Export and verify the inventory reports Exports the inventory and verifies the file at destination Example: | Fusion UI Export And Verify Inventory Reports | ${inventory_path} | ${inventory_name} """ s2l = ui_lib.get_s2l() if not s2l._is_element_present(FusionReportsPage.ID_PAGE_LABEL): navigate() logger._log_to_console_and_log_file("Create inventory") # CODE TO CREATE DOWNLOAD DIRECTORY AND DELETE FILES INSIDE, IF DIRECTORY EXISTS if not os.path.exists(inventory_path): os.makedirs(inventory_path) for root, dirs, files in os.walk(inventory_path, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) ui_lib.wait_for_element_and_click(FusionReportsPage.ID_SELECT_INVENTORY_NAME % (inventory_name), PerfConstants.DEFAULT_SYNC_TIME) s2l.click_element(FusionReportsPage.ID_MENU_ACTION_BTN) s2l.click_element(FusionReportsPage.ID_MENU_ACTION_SAVE_AS) ui_lib.wait_for_element_and_click(FusionReportsPage.ID_BTN_SAVE_AS_OK, PerfConstants.DEFAULT_SYNC_TIME) logger._log_to_console_and_log_file("Save the inventory to the specified folder path") BuiltIn().sleep(5) window_name = "Opening" # Name of the Window NativeOsKeywords().find_native_window(window_name) NativeOsKeywords().send_keys_to_native_window(window_name, "{DOWN}") NativeOsKeywords().send_keys_to_native_window(window_name, "{ENTER}") # ui_lib.MyLib().handle_windows(windowname, keys) # while os.listdir(inventory_path) == []: BuiltIn().sleep(2) # CODE TO WAIT TILL THE DOWNLOAD IS IN PROGRESS for files in os.listdir(inventory_path): filesize = os.path.getsize(os.path.join(inventory_path, files)) logger._log_to_console_and_log_file("initial file size %s" % filesize) finalfilesize = 0 start = datetime.now() while filesize != finalfilesize: BuiltIn().sleep(1) if not os.path.exists(os.path.join(inventory_path, files)): files = files.split(".part")[0] finalfilesize = os.path.getsize(os.path.join(inventory_path, files)) if(datetime.now() - start).total_seconds() > PerfConstants.DOWNLOAD_BACKUP_TIMEOUT: if finalfilesize == 0: logger._warn("final file size is 0, inventory with no data is created") else: logger._log_to_console_and_log_file("final file size %s" % finalfilesize) return False break ui_lib.wait_for_element_and_click(FusionReportsPage.ID_SELECT_INVENTORY_NAME % (inventory_name), PerfConstants.DEFAULT_SYNC_TIME) return True
def navigate(): # Navigate to page base_page.navigate_base(RebrandLoginPage.ID_PAGE_SETTINGS, FusionUIBaseElements.ID_MENU_LINK_SETTINGS, "css=span.hp-page-item-count") # Verify if not ui_lib.wait_for_element_visible(RebrandLoginPage.ID_LINK_SETTINGS, PerfConstants.FUSION_PAGE_SYNC): logger._warn("Unable to open the settings page") return False return True
def navigate(): base_page.navigate_base(FusionSANManagersPage.ID_PAGE_LABEL, FusionUIBaseElements.ID_MENU_LINK_SAN_MANAGERS, "css=span.hp-page-item-count") selenium2lib = ui_lib.get_s2l() if not selenium2lib._is_element_present( FusionSANManagersPage.ID_PAGE_LABEL): logger._warn("Failed to navigate to san managers page") return False else: return True
def select_datacenter(datacenterName): """ Select Datacenter Example: | `Select Datacenter` | | """ selenium2lib = ui_lib.get_s2l() logging._log_to_console_and_log_file( "Selecting Datacenter with the Datacenter name %s :" % datacenterName) # Verifying datacenter page is opened or not. Opening if it is not opened if not selenium2lib._is_element_present( FusionDataCenterPage.ID_LINK_ADD_DATA_CENTER): logging._log_to_console_and_log_file("Datacenter Page is opening") navigate() if not ui_lib.wait_for_element( FusionDataCenterPage.ID_LINK_ADD_DATA_CENTER, PerfConstants.FUSION_PAGE_SYNC): logging._warn("Unable to open the Datacenters page") selenium2lib.capture_page_screenshot() return False else: # Verifying the presence of multiple s with same name ui_lib.wait_for_element_visible( FusionDataCenterPage.ID_SELECT_DATACENTER % datacenterName, PerfConstants.SELECT_DATACENTER) count = len( selenium2lib._element_find( FusionDataCenterPage.ID_SELECT_DATACENTER % datacenterName, False, False)) logging._log_to_console_and_log_file( "Number of datacenters %s with same name" % int(count)) # Verifying the presence of given datacenter and selecting if (count == 1): if ui_lib.wait_for_element_visible( FusionDataCenterPage.ID_SELECT_DATACENTER % datacenterName, PerfConstants.SELECT_DATACENTER): logging._log_to_console_and_log_file( "Given datacenter with name %s is selected" % datacenterName) selenium2lib.click_element( FusionDataCenterPage.ID_SELECT_DATACENTER % datacenterName) else: ui_lib.fail_test("unable to select the given datacenter %s :" % datacenterName) elif (count > 1): ui_lib.fail_test( "There is more than one datacenter with same name") else: # Data center count is 0 or somehow negative ui_lib.fail_test("Could not find the data center named %s" % datacenterName)
def verify_lig_scopes(cls, timeout=5, fail_if_false=True): ligs_list = CommonOperationLogicalInterconnectGroups.get_lig_list() for lig_name in ligs_list: logger.debug("selecting LIG: %s" % lig_name) lig_select_status = ui_lib.wait_for_element_and_click( GeneralScopesElements.ID_LIG_TABLE % lig_name, timeout, fail_if_false) logger.debug("the lig_select_status is %s" % lig_select_status) if lig_select_status is False: logger._warn("Failed to click LIG: {0}".format(lig_name)) return ui_lib.fail_test("Failed to click LIG") else: logger.debug( "'{0}' LIG is selected Successfully ".format(lig_name)) msg = 'No scopes' return ui_lib.wait_for_element_text_match( GeneralScopesElements.ID_SCOPE_MESSAGE, msg, fail_if_false)
def remove_unmanaged_device(*uds_obj): """ Delete Unmanaged device to appliance """ failed_times = 0 selenium2lib = ui_lib.get_s2l() if not ui_lib.wait_for_element(FusionUnmanagedDevicePage.ID_PAGE_LABEL): navigate() if isinstance(uds_obj, test_data.DataObj): uds_obj = [uds_obj] elif isinstance(uds_obj, tuple): uds_obj = list(uds_obj[0]) for uds in uds_obj: uds_list = [ui_lib.get_webelement_attribute("text", el) for el in selenium2lib._element_find(FusionUnmanagedDevicePage.ID_UDS_LIST_NAMES, False, False)] if uds.name not in uds_list: logger._warn("Unmanaged device '%s' does not exist" % uds.name) selenium2lib.capture_page_screenshot() failed_times = failed_times + 1 continue logger._log_to_console_and_log_file("-----------------------------") logger._log_to_console_and_log_file("Removing Unmanaged device %s" % uds.name) logger._log_to_console_and_log_file("-----------------------------") ui_lib.wait_for_element_and_click(FusionUnmanagedDevicePage.ID_ELEMENT_UNAMANGED_DEVICE_BASE % uds.name) ui_lib.wait_for_element_and_click(FusionUnmanagedDevicePage.ID_MENU_ACTION_MAIN_BTN) ui_lib.wait_for_element_and_click(FusionUnmanagedDevicePage.ID_MENU_ACTION_REMOVE) ui_lib.wait_for_element_and_click(FusionUnmanagedDevicePage.ID_BTN_REMOVE_UD_CONFIRM) ui_lib.wait_for_element_remove( FusionUnmanagedDevicePage.ID_ELEMENT_UNAMANGED_DEVICE_BASE % uds.name, PerfConstants.DEFAULT_SYNC_TIME) logger._log_to_console_and_log_file("Checking whether Unmanaged device %s is Deleted or not" % uds.name) ui_lib.wait_for_element_visible(FusionUnmanagedDevicePage.ID_LINK_CREATE_UD) uds_list = [ui_lib.get_webelement_attribute("text", el) for el in selenium2lib._element_find(FusionUnmanagedDevicePage.ID_UDS_LIST_NAMES, False, False)] if uds.name not in uds_list: logger._log_to_console_and_log_file("Unmanaged device '%s' removed successfully" % uds.name) else: ui_lib.fail_test(" The Unmanaged device '%s' not removed successfully" % uds.name) selenium2lib.capture_page_screenshot() failed_times = failed_times + 1 if failed_times > 0: return False else: return True
def _add_rack_to_datacenter(rack): ''' _add_rack_to_datacenter function to add rack into the data center ''' if rack is None: logging._log_to_console_and_log_file( "No racks have been specified to add to this data center.") return selenium2lib = ui_lib.get_s2l() ui_lib.wait_for_element_and_click(FusionDataCenterPage.ID_DROP_DOWN) ui_lib.wait_for_element_and_click(FusionDataCenterPage.ID_LINK_LAYOUT_RACK) if len(rack.rname) > 0: logging._log_to_console_and_log_file( "adding rack(s) with name '%s' to the data center" % str(rack.rname)) ui_lib.wait_for_element_and_input_text( FusionDataCenterPage.ID_INPUT_UNPOSITIONED_RACK, str(rack.rname)) ui_lib.wait_for_element_and_click( "xpath=//legend[.='Unpositioned Racks']") if selenium2lib._is_element_present( FusionDataCenterPage.ID_VALIDATE_DATACENTER % str(rack.rname)): logging._log_to_console_and_log_file( "rack(s) with name '%s' is present among the Unpositioned racks; adding..." % str(rack.rname)) ui_lib.wait_for_element_and_click( FusionDataCenterPage.ID_SELECT_RACK) ui_lib.wait_for_element_and_click( FusionDataCenterPage.ID_BTN_ADD_UNPOSITIONED_RACK) logging._log_to_console_and_log_file( "Added '%s' to the data center" % str(rack.rname)) else: logging._warn( "Rack '%s' has not been defined in Fusion, or is unavailable as an unpositioned rack" % str(rack.rname)) else: logging._log_to_console_and_log_file("rack name should not be empty") if not selenium2lib._is_element_present( FusionDataCenterPage.ID_VALIDATE_DATACENTER % str(rack.rname)): logging._log_to_console_and_log_file( "Rack(s) with name %s has been added to the datacenter's racks layout, and is cleared from the Unmanaged Racks list" % str(rack.rname)) else: logging._warn( "Rack(s) with name %s did not get cleared from the Unmanaged Racks list (recurrence of QXCR1001348527)" % str(rack.rname))
def verify_li_scopes(cls, timeout=5, fail_if_false=True): LI_list = CommonOperationLogicalInterconnect.get_li_list() logger.debug("the LI list is %s" % LI_list) for LI_name in LI_list: logger.debug("selecting LI: %s" % LI_name) LI_select_status = ui_lib.wait_for_element_and_click( GeneralScopesElements.ID_LI_TABLE % LI_name, timeout, fail_if_false) logger.debug("the LI_select_status is %s" % LI_select_status) if LI_select_status is False: logger._warn("Failed to click LI: {0}".format(LI_name)) return ui_lib.fail_test("Failed to click the element") else: logger.debug( "'{0}' LI is selected Successfully".format(LI_name)) msg = 'No scopes' return ui_lib.wait_for_element_text_match( GeneralScopesElements.ID_SCOPE_MESSAGE, msg, fail_if_false)
def login(user_name): s2l = ui_lib.get_s2l() logger._log_to_console('Login status = {0}'.format(str(base_page.logged_in()))) if base_page.logged_in(): base_page.logout() user = test_data.get_user_by_name(user_name) # check the existing login status logger._log_to_console_and_log_file("Logging into i3S as {0}/{1}".format(user.name, user.password)) if s2l._is_element_present(i3SLoginPage.ID_BTN_EULA_AGREE): s2l.click_button(i3SLoginPage.ID_BTN_EULA_AGREE) s2l.wait_until_page_contains_element(i3SLoginPage.ID_BTN_LOGIN_BUTTON) s2l.input_text(i3SLoginPage.ID_INPUT_LOGIN_USER, user.name) s2l.input_text(i3SLoginPage.ID_INPUT_LOGIN_PASSWORD, user.password) # code to login as active directory user if(user.has_property("domainName")): s2l.click_element(i3SLoginPage.ID_ELEMENT_AUTHN_PROVIDER) dirListObj = i3SLoginPage.ID_ELEMENT_DIR % user.domainName.strip() s2l.click_element(dirListObj) activedir = s2l.get_text(i3SLoginPage.ID_COMBO_AUTHN_PROVIDER) if not activedir == user.domainName.strip(): logger._warn("Not able to login to the appliance with active directory users ..") ui_lib.fail_test("not able to login as active directory users... verify AD users and groups is added to the appliance") s2l.click_button(i3SLoginPage.ID_BTN_LOGIN_BUTTON) # These elements may not exist if the login page is transitioning to the dashboard # page. In order to avoid failing conditions, we will catch any exceptions try: s2l.element_should_not_be_visible(i3SLoginPage.ID_ALL_ERROR_FIELDS) s2l.element_text_should_be(i3SLoginPage.ID_LABEL_LOGIN_STATUS, "") except: pass s2l.wait_until_page_contains_element(i3SDashboardPage.ID_PAGE_LABEL, UiConstants.i3S_LOGIN_TIME, "Failed to load the Login Page") base_page.set_logged_user(user_name) logger._log_to_console_and_log_file("Logged into i3S as {0}".format(base_page.get_logged_user())) return True
def get_webelement_attribute(attribute, locator, timeout=5, fail_if_false=False): """ Function which adds a wrapper around retrieving webelement attributes to handle a StaleElementReferenceException. Example: name = get_webelement_attribute("text", user) :param attribute: name of the attribute/property to retrieve :param locator: xpath/id/css expression to locate element :param timeout: in second, the method will return None or throw exception if can't get desire attribute value in specified time :param fail_if_false: set to True to fail the test case if can't get elements' text in :timeout seconds :return: string value otherwise return None """ start = datetime.now() while (datetime.now() - start).total_seconds() < timeout: try: webelement = get_s2l()._element_find(locator, True, False) if webelement is None: time.sleep(0.1) continue if attribute == "text": return webelement.text elif attribute == "name": return webelement.name elif attribute == "innerHTML": return webelement.get_attribute('innerHTML') else: return webelement.get_attribute(attribute) except (StaleElementReferenceException): pass if fail_if_false: fail_test("Failed to get element attribute in %s seconds" % timeout) logger._warn( "Failed to get element within timeout due to StaleElementReferenceException on webelement" ) return None
def change_activity_state_in_activity_page(activity_obj): """ This function is to change activity state from 'active' to 'Cleared' State in Activity Page """ if not ui_lib.wait_for_element(FusionActivityPage.ID_PAGE_LABEL): navigate() if isinstance(activity_obj, test_data.DataObj): activity_obj = [activity_obj] elif isinstance(activity_obj, tuple): activity_obj = list(activity_obj) for activity in activity_obj: if not _is_element_present_activity_page_without_time( activity.name, activity.resource): logger._warn("Activity '{0}' is not present in appliance".format( activity.name)) return False else: ui_lib.wait_for_element_visible( FusionActivityPage.ID_MSG_AVAILABLE % (activity.name, activity.resource) + "/descendant::div[@class='hp-state hp-select']", 20) ui_lib.wait_for_element_and_click( FusionActivityPage.ID_MSG_AVAILABLE % (activity.name, activity.resource) + "/descendant::div[@class='hp-state hp-select']") ui_lib.wait_for_element_and_click( FusionActivityPage.ID_MSG_AVAILABLE % (activity.name, activity.resource) + "/descendant::li[text()='Cleared']") if ui_lib.wait_for_element( FusionActivityPage.ID_MSG_AVAILABLE % (activity.name, activity.resource) + "/descendant::li[@class='hp-selected' and text()='Cleared']"): logger._log_to_console_and_log_file( "Activity '{0}' state successfully changed to '{1}'".format( activity.name, activity.state)) return True else: logger._warn( "Failed to change activity '{0}' status to '{1}'".format( activity.name, activity.state)) return False