def get_replay_helper(self, replay_id, background): if background: fast_forward_btn = self.driver.find_element_by_css_selector( "[data-action='ff']") # Iterate through up to MAX_GAME_LENGTH turns for i in range(MAX_GAME_LENGTH): fast_forward_btn.click() # Once we've skipped through at least 100 turns, check if the # battle has ended every 50 turns if i > 100 & i % 50 == 0: log = self.driver.find_element_by_css_selector( ".battle-log") if "won the battle" in log.text: return log.text # If the game hasn't ended after MAX_GAME_LENGTH turns, throw an exception raise EndOfLogException("Failed to reach end of log file") else: # Open the turn picking dialogue pick_turn_btn = self.driver.find_element_by_css_selector( "[data-action='ffto']") pick_turn_btn.click() # Pick the last turn alert = Alert(self.driver) alert.send_keys(str(-1)) alert.accept() log = self.driver.find_element_by_css_selector(".battle-log") return log.text
def test_wish_check_in(self, data): self.driver.get('https://my.yyw.com/wishLists_dir.php') wish_info = self.driver.find_element_by_xpath( '//*[@id="container"]/div[2]/div[3]/div/div[2]/ul/li[1]/p[3]') wish_info.click() time.sleep(10) item_no_price = self.driver.find_element_by_xpath( '//*[@id="mywishlistForm"]/div[3]/div[2]/ul/li[3]/dl/dd[1]') item_no_price_info = item_no_price.text.replace(' ', '') if data.get('item_no') in item_no_price_info and data.get( 'item_price') in item_no_price_info: LOG.info(f'指定商品添加==>成功') else: LOG.error(f'指定商品添加==>失败') time.sleep(2) self.driver.execute_script( 'document.querySelector("#mywishlistForm > div.be2c > div:nth-child(1) > span.fl > input").click()' ) # 全选 time.sleep(0.5) rm_js = 'document.querySelector("#mywishlistForm > div.be2c > div:nth-child(1) > img.fl.ml10.removeWishList.hand").click()' self.driver.execute_script(rm_js) time.sleep(1) from selenium.webdriver.common.alert import Alert alert = Alert(self.driver) alert.accept() time.sleep(3) LOG.info('删除指定商品成功.') del alert
def test_reportar_accidente_cliente(self): driver = self.driver driver.maximize_window() driver.get("http://127.0.0.1:8000/accounts/login/") self.assertIn("Login", driver.title) usuario = driver.find_element_by_id("id_username") usuario.send_keys("Cliente") clave = driver.find_element_by_id("id_password") clave.send_keys("duoc123456") usuario.send_keys(Keys.ENTER) time.sleep(1) # ir a servicios driver.find_element_by_xpath( "/html/body/header/div/nav/ul/li[4]/a").click() time.sleep(2) #ir a ver reportar Accidente driver.find_element_by_xpath( "/html/body/main/section/div/section[1]/div/div/div[3]/div/div[2]/input" ).click() time.sleep(2) Descripcion = driver.find_element_by_name("descripcion") Descripcion.send_keys("Prueba1") driver.find_element_by_xpath( "/html/body/main/section[2]/div/div/div[2]/form/center/button" ).click() alert = Alert(driver) alert.accept() time.sleep(2) #valida el mensaje del sistema if driver.find_element_by_xpath( "/html/body/main/section[2]/div/div/div[1]" ).text == 'Accidente: Reporte enviado': print("Se reporto un accidente ") else: print("no Se reporto un accidente ")
def doLogin(self, credential): if self.driver: alert = Alert(self.driver) if alert and credential: print(alert) #alert.send_keys(f'u{Keys.TAB}p') #alert.send_keys( usr + Keys.TAB + pwd ) alert.send_keys(str(credential)) sleep(5) alert.accept() sleep(10) print(self.driver.current_url) if self.driver.current_url == MAIN_URL: self.loged = True print("Loged IN ! :)") return True else: alert.dismiss() print("Could not log in.. :(") return False else: print("Could not auth alert") return False else: print("Could not find driver FF") return False
def test_modificar_condicion(self): driver = self.driver driver.maximize_window() driver.get("http://127.0.0.1:8000/accounts/login/") self.assertIn("Login", driver.title) usuario = driver.find_element_by_id("id_username") usuario.send_keys("Benja") clave = driver.find_element_by_id("id_password") clave.send_keys("duoc123456") usuario.send_keys(Keys.ENTER) time.sleep(1) # ir a servicios driver.find_element_by_xpath( "/html/body/header/div/nav/ul/li[4]/a").click() time.sleep(2) #ir a ver listdos de las condiciones driver.find_element_by_xpath( "/html/body/main/section/div/div/div[3]/div/div[3]/input").click() #seleccionar la ultima condicion agregada driver.find_element_by_xpath( "/html/body/main/section[2]/div/center/div[1]/table/tbody/tr[15]/td[3]/a[1]" ).click() condicion = driver.find_element_by_name("nom_condicion") condicion.send_keys("prueba2") time.sleep(2) alert = Alert(driver) driver.find_element_by_xpath( "/html/body/main/section[2]/div/div/div/form/button").click() alert.accept() if driver.current_url == 'http://127.0.0.1:8000/listadoCondicion.html': print("Se modifico la condicion") else: print("no permite que se modifique la condicion")
def accept_key(bro): Alert(bro).accept() sleep(.1) key_alert = Alert(bro) my_key = key_alert.text key_alert.accept() return my_key
def test_del_know(self, title): ''' 删除知识成功_验证指定知识标题进行删除;CRM-ST-BG-016 :return: ''' # username = "******" # password = "******" # title = '123' # # 登录 # sleep(4) # lp = LoginPage(self.driver) # sleep(2) # lp.open() # lp.login(username, password) # # # 去知识页面 # sleep(3) # ip = IndexPage(self.driver) # ip.know_button_click() # sleep(6) #在知识页面 kp = KnowPage(self.driver, KNOW_URL) kp.open() kp.get_title_click(title) kp.know_del_click() #确认删除 sleep(3) confirm = Alert(self.driver) confirm.accept() #断言 text = kp.get_know_title() self.assertNotIn(title, text)
def alert_box(self): try: prompt = Alert(self.browser) time.sleep(1) prompt.accept() except: return
def get_replay_helper(self, replay_id, background): if background: fast_forward_btn = self.driver.find_element_by_css_selector("[data-action='ff']") # Iterate through up to MAX_GAME_LENGTH turns for i in range(MAX_GAME_LENGTH): fast_forward_btn.click() # Once we've skipped through at least 100 turns, check if the # battle has ended every 50 turns if i > 100 & i % 50 == 0: log = self.driver.find_element_by_css_selector(".battle-log") if "won the battle" in log.text: return log.text # If the game hasn't ended after MAX_GAME_LENGTH turns, throw an exception raise EndOfLogException("Failed to reach end of log file") else: # Open the turn picking dialogue pick_turn_btn = self.driver.find_element_by_css_selector("[data-action='ffto']") pick_turn_btn.click() # Pick the last turn alert = Alert(self.driver) alert.send_keys(str(-1)) alert.accept() log = self.driver.find_element_by_css_selector(".battle-log") return log.text
def test_name_blank_insertion(self): self.insert_data_test("", "c'est cher", "150", r'C:\Users\richa\Desktop\kirbo.jpg', r'C:\Users\richa\Desktop\kirbo.jpg') alert = Alert(self.driver) self.assertEqual("Nom manquant", alert.text) alert.accept()
def test_eliminar_cliente(self): driver = self.driver driver.maximize_window() driver.get("http://127.0.0.1:8000/accounts/login/") self.assertIn("Login", driver.title) usuario = driver.find_element_by_id("id_username") usuario.send_keys("Benja") clave = driver.find_element_by_id("id_password") clave.send_keys("duoc123456") usuario.send_keys(Keys.ENTER) time.sleep(1) #ir a servicios driver.find_element_by_xpath( "/html/body/header/div/nav/ul/li[4]/a").click() time.sleep(2) #ir a ver listdo de clientes driver.find_element_by_xpath( "/html/body/main/section/div/div/div[2]/div/div[3]/input").click() time.sleep(2) #seleccionar eliminar alert = Alert(driver) driver.find_element_by_xpath( "/html/body/main/section[2]/div/center/div[1]/table/tbody/tr/td[4]/a[2]" ).click() alert.accept() if driver.title == 'Listado Cliente': print("Se elimino el cliente ") else: print("No permite eliminar cliente")
def Restart_Modem(): options = EdgeOptions() options.use_chromium = True options.add_argument("-inprivate") edge_browser = Edge(options=options) edge_browser.get('http://192.168.0.1') time.sleep(2) print('Welcome') try: login = edge_browser.find_element_by_name('username') password = edge_browser.find_element_by_name('password') sign = edge_browser.find_element_by_class_name('styled_button_s') login.clear() password.clear() login.send_keys('admin') password.send_keys('admin') time.sleep(2) sign.click() print('Sign in') alert = Alert(edge_browser) time.sleep(2) edge_browser.get('http://192.168.0.1/saveconf.htm') time.sleep(2) system = edge_browser.find_element_by_id('three_level_menu1') system.click() time.sleep(2) reboot = edge_browser.find_element_by_name('reboot') reboot.click() alert.accept() time.sleep(70) print('Reboot') edge_browser.quit() except: print('Problem with restarting modem') edge_browser.quit()
def test_ept_task(self): ''' 导出任务成功_验证导出所有任务为excel格式;CRM-ST-BG-006 :return: ''' # username = "******" # password = "******" # path='C:/Users/40511/Documents/Downloads/5kcrm_task_2020-03-18_1.xls' # # #登录 # lp = LoginPage(self.driver) # lp.open() # lp.login(username,password) # #去到任务页面 # sleep(4) # ip = IndexPage(self.driver) # ip.task_button_click() #去到任务页面导出任务 sleep(4) tp = TaskPage(self.driver, TASK_URL) tp.open() tp.task_tool_button_click() tp.task_export_button_click() #提示框点击确认 sleep(4) confirm = Alert(self.driver) confirm.accept() sleep(4) #断言 print(os.path.exists(EPT_TASK)) #查看是否成功 self.assertTrue(os.path.exists(EPT_TASK)) os.remove(EPT_TASK) #删除数据
def test_with_isolation_and_check(mocker): with mocker.patch('selenium.webdriver.remote.webdriver.WebDriver') as MockDriver: driver = MockDriver.return_value alert = Alert(driver) alert.accept() driver.execute.assert_called_with("acceptAlert")
def delete_user_by_id(self, id): driver = self.app.driver self.select_user_by_id(id) delete_btn = driver.find_element_by_xpath(UserPageLocators.DELETE_BTN) delete_btn.click() alert = Alert(driver) alert.accept() self.user_cache = None
def login_to_reportronic(self): """Authenticate user with given username and password from config.json. """ self.logger.info('Trying to log in to Reportronic.') self.driver.get(self.url) prompt = Alert(self.driver) prompt.send_keys(self.user + Keys.TAB + self.password) prompt.accept()
def test_with_isolation_and_check(mocker): with mocker.patch( 'selenium.webdriver.remote.webdriver.WebDriver') as MockDriver: driver = MockDriver.return_value alert = Alert(driver) alert.accept() driver.execute.assert_called_with("acceptAlert")
def perform_right_click(self): self.services.wait_for_element(self.hot_spot) logging.info('## Find element on which right click need to perform. ##') hot_spot_ele = self.driver.find_element_by_xpath(self.hot_spot) actions = ActionChains(self.driver) actions.context_click(hot_spot_ele).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ENTER).perform() sleep(2) alert = Alert(self.driver) alert.accept()
def selenium_is_alert_exist(self): try: alert_element = Alert(self.driver) if alert_element: alert_element.accept() return True else: return False except Exception: return False
def cleancache_beforeload(browser): #### 获得 driver 属性 drivertypes = drivertype() ################# firefox if drivertypes>=0 and drivertypes<1: loads(browser,"about:preferences#privacy") clicks(browser,"//*[@id='clearSiteDataButton']") # 外面的按钮 # js执行 css 对应按钮 , 其它方式未成功 dialog_selector = '#dialogOverlay-0 > groupbox:nth-child(1) > browser:nth-child(2)' accept_dialog_script = ( f"const browser = document.querySelector('{dialog_selector}');" + \ "browser.contentDocument.documentElement.querySelector('#clearButton').click();") # 里一层按钮 # wait WebDriverWait(browser, 5).until(lambda the_driver: the_driver.find_element_by_css_selector(dialog_selector).is_displayed()) # click browser.execute_script(accept_dialog_script) # wait alert WebDriverWait(browser, 5).until(EC.alert_is_present()) alert = Alert(browser) alert.accept() loads(browser,"about:blank") ################# chrome if drivertypes>=1 and drivertypes<2: loads(browser,"chrome://settings/clearBrowserData") # js执行 css 对应按钮 , 其它方式未成功 dialog_selector ='* /deep/ #clearBrowsingDataConfirm' # 跳过 shadow roots # wait WebDriverWait(browser, 5).until(lambda the_driver: the_driver.find_element_by_css_selector(dialog_selector)) accept_dialog_script = ( f"const browser = document.querySelector('{dialog_selector}');" + \ "browser.click();") # click browser.execute_script(accept_dialog_script) loads(browser,"about:blank")
def accept_alert(step): """ Accept the alert """ try: alert = Alert(world.browser) alert.accept() except WebDriverException: # PhantomJS is kinda poor pass
def alert_accept(self): """弹出框的确定""" try: ele = self.alert_is_pressent() ele.accept() except: try: alert = Alert(self.driver) alert.accept() except: raise ("not find alert")
def test_pruebas_ini_sesion(self): driver = self.driver driver.get(self.base_url + "/#/VLogin") actions = ActionChains(self.driver) alert = Alert(self.driver) ######################## Contrasenha Invalida #################################################### driver.find_element_by_id("fLogin_usuario").clear() driver.find_element_by_id("fLogin_usuario").send_keys("Test Usuario") driver.find_element_by_id("fLogin_clave").clear() driver.find_element_by_id("fLogin_clave").send_keys("bbbbbbbb") driver.find_element_by_id("conectate").click() time.sleep(0.5) alert.accept() time.sleep(.5) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) ######################## Usuario no Existente #################################################### driver.find_element_by_id("fLogin_usuario").clear() driver.find_element_by_id("fLogin_usuario").send_keys("UsuarioNoExiste") driver.find_element_by_id("fLogin_clave").clear() driver.find_element_by_id("fLogin_clave").send_keys("aaaaaaaa") driver.find_element_by_id("conectate").click() time.sleep(0.5) alert.accept() time.sleep(.5) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) ######################## Usuario Vacio #################################################### driver.find_element_by_id("fLogin_clave").clear() driver.find_element_by_id("fLogin_clave").send_keys("aaaaaaaa") driver.find_element_by_id("conectate").click() actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) ######################## Clave Vacia #################################################### driver.find_element_by_id("fLogin_usuario").clear() driver.find_element_by_id("fLogin_usuario").send_keys("Test Usuario") driver.find_element_by_id("conectate").click() actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) ######################## Todo Vacio #################################################### driver.find_element_by_id("conectate").click()
def alertAccept(self, xpath, value): try: alert = Alert(self.driver) alert.accept() result = {"state": True, "info": ""} except Exception as e: result = { "state": False, "info": getErrInfo(xpath, "closeAlert", value, str(e)) } return result
def selenium_is_alert_exist(self): try: alert_element = Alert(self.driver) if alert_element: alert_element.accept() return True else: return False except Exception as e: log.logger.error(e, exc_info=True) return False
def accept_alert(test): """ Accept the alert """ try: alert = Alert(test.browser) alert.accept() except WebDriverException: # PhantomJS is kinda poor pass
def accept_alert(self): """ Accept the alert. """ try: alert = Alert(world.browser) alert.accept() except WebDriverException: # PhantomJS is kinda poor pass
def test_alert(): driver = webdriver.Remote( desired_capabilities=DesiredCapabilities.CHROME, command_executor="http://%s:4444" % host ) driver.get('http://nginx:8000') alert = Alert(driver) print alert.text assert 'Hello' in alert.text alert.accept() driver.get_screenshot_as_file('screenshot.png') driver.quit()
def deleteFirstDaily(driver): time.sleep(1) FirstDailyOptions = driver.find_element_by_css_selector( "#app > div.container-fluid > div.sticky > div > div > div.row.tasks-columns > div.tasks-column.col-lg-3.col-md-6.daily > div.tasks-list > div.sortable-tasks > div > div > div > div.task-content > div.task-clickable-area.task-clickable-area-user > div.d-flex.justify-content-between > div > div.habitica-menu-dropdown-toggle" ) FirstDailyDelete = driver.find_element_by_css_selector( "#app > div.container-fluid > div.sticky > div > div > div.row.tasks-columns > div.tasks-column.col-lg-3.col-md-6.daily > div.tasks-list > div.sortable-tasks > div:nth-child(1) > div > div > div.task-content > div.task-clickable-area.task-clickable-area-user > div.d-flex.justify-content-between > div > div.dropdown-menu > div > div:nth-child(4)" ) FirstDailyOptions.click() FirstDailyDelete.click() a = Alert(driver) a.accept()
def wd_SEL_Alert(self, target, value=None): """ Retrieve the message of a JavaScript alert generated during the previous action, or fail if there are no alerts. Getting an alert has the same effect as manually clicking OK. If an alert is generated but you do not consume it with getAlert, the next webdriver action will fail. @param target: the expected message of the most recent JavaScript alert @param value: <not used> @return: the message of the most recent JavaScript alert """ alert = Alert(self.driver) text = alert.text.strip() alert.accept() return target, text
def login_False(self): alert=Alert(UseBrowser.driver) t=alert.text alert.accept() return t # if __name__=='__main__': # l=LoginPage() # l.login('admin','123456') # time.sleep(4) # print(l.login_correct_text(l.ya.get_data('CustomerPage','frametopFrame'),l.ya.get_data('LoginPage','succes'))) # print(l.op.get_cell(5, 4)) # UseBrowser.quit()
def _handle_alert(self, alert: Alert_, action: str) -> str: """处理警告框并返回警告框文本内容""" action = action.upper() text = alert.text if action == self.ACCEPT: self.logger.info("接受警告框") alert.accept() elif action == self.DISMISS: self.logger.info("取消警告框") alert.dismiss() elif action != self.LEAVE: raise ValueError(f"无效的警告框处理行为:{action}") return text
def return_result(self, respect_result): driver = self.driver if respect_result == 'True': ele = driver.find_element(*CreateTopicPageLocator.TOPIC_TITLE) else: if self.bankuai_name == "": ele = Alert(driver) ele.accept() print(ele.text) else: ele = driver.find_element( *CreateTopicPageLocator.WRONG_MESSAGE_ELE) return ele.text
def test_alert_two(self): second_alert_btn_path = '//*[@id="content"]/div/ul/li[2]/button' alert_results_path = '//*[@id="result"]' expected_text_in_alert = 'You clicked: Ok' driver = self.driver driver.get(self.alerts_url) btn_alert = driver.find_element_by_xpath(second_alert_btn_path).click() alert = Alert(driver) print("Alert shows following message: " + alert.text) alert.accept() message = driver.find_element_by_xpath(alert_results_path).text self.assertEqual(expected_text_in_alert, message, f'Message should say: {message}') print(message)
def get_result(driver): try: body_tag = driver.find_element(By.TAG_NAME, 'body') # print(body_tag.text) return True except NoSuchElementException: # mat = re.findall('alert\((\S*)\)', driver.page_source) # msg = mat[0].replace('\\n\\r', '') if mat else 'No tips' # print("Error happens, cause : {}".format(msg)) if re.findall('alert\(', driver.page_source): # alert pops up alert = Alert(driver) print(alert.text) alert.accept() return False
def test_3(self): driver = self.driver driver.get(self.base_url + "/#/VLogin") actions = ActionChains(self.driver) alert = Alert(self.driver) driver.find_element_by_id("fLogin_usuario").clear() driver.find_element_by_id("fLogin_usuario").send_keys("Usuario") driver.find_element_by_id("fLogin_clave").clear() driver.find_element_by_id("fLogin_clave").send_keys("aaaaaaaa") driver.find_element_by_id("conectate").click() time.sleep(1) driver.find_element_by_xpath("//a[@ng-show='idUsuario']").click() time.sleep(1) driver.find_element_by_xpath(".//*[@id='invisible_interno']/div/div[2]/div[2]").click() driver.find_element_by_xpath("//input[@placeholder='Buscar amigos']").clear() driver.find_element_by_xpath("//input[@placeholder='Buscar amigos']").send_keys('Usuario3') driver.find_element_by_id("btnHilos").click() driver.find_element_by_id("config").click() actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) driver.find_element_by_xpath("//a[contains(@ng-click,'VGrupo2')]").click() actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) driver.find_element_by_xpath("//input[@placeholder='Buscar amigos']").send_keys('Usuario3') driver.find_element_by_id("btnHilos").click() driver.find_element_by_id("config").click() actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) driver.get(self.base_url + "/#/VAdminContactos/Usuario") driver.find_element_by_xpath("(//a[contains(@ng-click,'AElimContacto1')])[2]").click() time.sleep(0.5) alert.accept() time.sleep(.5) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) driver.find_element_by_xpath("//span[@ng-bind='idUsuario']").click() time.sleep(.5) driver.find_element_by_xpath("//a[@ng-click='ASalir(idUsuario)']").click() time.sleep(.5)
def accept_alert(browser): try: alert = Alert(browser) alert.accept() except WebDriverException: pass
def one_voter_votes(self, voter, direct=False): browser = self.browser if direct: url = voter["election_page_url"] browser.get(settings.SERVER_URL + "/vote.html#" + urlencode({"url": url})) else: # Bob has received 2 emails containing an invitation to vote and all necessary credentials (election page URL, username, password). He goes to the election page URL. browser.get(voter["election_page_url"]) wait_a_bit() # He clicks on the "Start" button start_button_expected_label = "Start" start_button_css_selector = "#main button" start_button_element = wait_for_element_exists_and_contains_expected_text(browser, start_button_css_selector, start_button_expected_label, settings.EXPLICIT_WAIT_TIMEOUT) start_button_element.click() wait_a_bit() # A loading screen appears, then another screen appears. He clicks on the "Here" button here_button_expected_label = "here" here_button_css_selector = "#input_code button" here_button_element = wait_for_element_exists_and_contains_expected_text(browser, here_button_css_selector, here_button_expected_label, settings.EXPLICIT_WAIT_TIMEOUT) here_button_element.click() wait_a_bit() # A modal opens (it is an HTML modal created using Window.prompt()), with an input field. He types his credential. credential_prompt = Alert(browser) credential_prompt.send_keys(voter["credential"]) credential_prompt.accept() wait_a_bit() # A new screen appears, which has a title "Step 2/6: Answer to questions", and a content: # "Question 1?" # "Question #1 of 1 — select between 1 and 2 answer(s)" # [ ] "Answer 1" # [ ] "Answer 2" # [Next] # (where "[ ]" is a checkbox, and [Next] is a button) # He fills his votes to each answer of the question answers_css_selector = "#question_div input[type=checkbox]" answers_elements = wait_for_elements_exist(browser, answers_css_selector, settings.EXPLICIT_WAIT_TIMEOUT) # or we could use find_element_by_xpath("//div[@id='question_div']/input[@type='checkbox'][2]") assert len(answers_elements) is 2 question1_answer1_element = answers_elements[0] question1_answer2_element = answers_elements[1] voter_vote_to_question_1_answer_1 = voter["votes"]["question1"]["answer1"] voter_vote_to_question_1_answer_2 = voter["votes"]["question1"]["answer2"] voter_vote_to_question_1_answer_1_is_checked = question1_answer1_element.get_attribute('checked') voter_vote_to_question_1_answer_2_is_checked = question1_answer2_element.get_attribute('checked') assert voter_vote_to_question_1_answer_1_is_checked is None assert voter_vote_to_question_1_answer_2_is_checked is None if voter_vote_to_question_1_answer_1: question1_answer1_element.click() if voter_vote_to_question_1_answer_2: question1_answer2_element.click() wait_a_bit() # He clicks on the "Next" button next_button_expected_label = "Next" next_button_css_selector = "#question_div button" next_button_element = wait_for_element_exists_and_contains_expected_text(browser, next_button_css_selector, next_button_expected_label, settings.EXPLICIT_WAIT_TIMEOUT) next_button_element.click() wait_a_bit() """ A new screen appears, showing: Step 3/6: Review and encrypt Question 1? - Answer 1 Your ballot has been successfully encrypted, but has not been cast yet! Your smart ballot tracker is sLRilXoAYcodIrjWrOqPrVXLNlRyCJAqFeeHZ4WCajU We invite you to save it in order to check later that it is taken into account. [Continue] [Restart] """ # He remembers the smart ballot tracker that is displayed. smart_ballot_tracker_css_selector = "#ballot_tracker" smart_ballot_tracker_element = wait_for_element_exists_and_has_non_empty_content(browser, smart_ballot_tracker_css_selector, settings.EXPLICIT_WAIT_TIMEOUT) smart_ballot_tracker_value = smart_ballot_tracker_element.get_attribute('innerText') assert len(smart_ballot_tracker_value) > 5 voter["smart_ballot_tracker"] = smart_ballot_tracker_value # He clicks on the "Continue" button next_button_expected_label = "Continue" next_button_css_selector = "#div_submit input[type=submit][value='" + next_button_expected_label + "']" next_button_element = browser.find_element_by_css_selector(next_button_css_selector) next_button_element.click() wait_a_bit() # He types his voter username and password, and submits the form username_field_css_selector = "#main input[name=username]" username_field_element = wait_for_element_exists(browser, username_field_css_selector, settings.EXPLICIT_WAIT_TIMEOUT) username_field_element.send_keys(voter["username"]) password_field_css_selector = "#main input[name=password]" password_field_element = browser.find_element_by_css_selector(password_field_css_selector) password_field_element.send_keys(voter["password"]) wait_a_bit() password_field_element.submit() wait_a_bit() # He checks that the smart ballot tracker value that appears on screen is the same as the one he noted smart_ballot_tracker_verification_css_selector = "#ballot_tracker" smart_ballot_tracker_verification_element = wait_for_element_exists_and_has_non_empty_content(browser, smart_ballot_tracker_verification_css_selector, settings.EXPLICIT_WAIT_TIMEOUT) smart_ballot_tracker_verification_value = smart_ballot_tracker_verification_element.get_attribute('innerText') assert len(smart_ballot_tracker_verification_value) > 5 assert smart_ballot_tracker_verification_value == voter["smart_ballot_tracker"] # He clicks on the "I cast my vote" button submit_button_css_selector = "#main input[type=submit]" submit_button_element = browser.find_element_by_css_selector(submit_button_css_selector) submit_button_element.click()
def test_pruebas_ini_sesion(self): driver = self.driver driver.get(self.base_url + "/#/VLogin") actions = ActionChains(self.driver) alert = Alert(self.driver) driver.find_element_by_id("fLogin_usuario").clear() driver.find_element_by_id("fLogin_usuario").send_keys("Usuario") time.sleep(.5) driver.find_element_by_id("fLogin_clave").clear() driver.find_element_by_id("fLogin_clave").send_keys("aaaaaaaa") time.sleep(.5) driver.find_element_by_xpath("//button[@id='conectate']").click() time.sleep(2) ######################## Ayuda y Foro sin titulo ############################################# driver.find_element_by_xpath("//a[@ng-click='VForos()']").click() time.sleep(2) driver.find_element_by_xpath("//a[@id='config']").click() time.sleep(.5) driver.find_element_by_xpath("//button[@type='submit']").click() time.sleep(1) ''' driver.find_element_by_xpath("//span[@ng-bind='idUsuario']").click() time.sleep(.5) driver.find_element_by_xpath("//a[@ng-click='__ayuda()']").click() time.sleep(1) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) ''' ######################## Creacion de Foro ############################################# driver.find_element_by_id("fForo_texto").send_keys("Foro Prueba") driver.find_element_by_xpath("//button[@type='submit']").click() time.sleep(1) ######################## Prueba Foro con mismo nombre ############################################# ''' driver.find_element_by_xpath("//button[@id='config']").click() time.sleep(.5) driver.find_element_by_id("fForo_texto").send_keys("Nuevo ForoR") driver.find_element_by_xpath("//button[@type='submit']").click() time.sleep(1) actions.key_down(Keys.CONTROL) actions.send_keys('r') actions.key_up(Keys.CONTROL) actions.perform() time.sleep(.5) ''' ######################## Hilo sin titulo ni contenido y ayuda ############################################# driver.find_element_by_link_text("Foro Prueba").click() ''' driver.find_element_by_xpath("//span[@ng-bind='idUsuario']").click() time.sleep(1) driver.find_element_by_xpath("//a[@ng-click='__ayuda()']").click() time.sleep(1) ''' actions.key_down(Keys.CONTROL) actions.send_keys('r') actions.key_up(Keys.CONTROL) actions.perform() time.sleep(.5) driver.find_element_by_xpath("//a[@id='config']").click() time.sleep(.5) driver.find_element_by_xpath("//button[@type='submit']").click() time.sleep(1) ''' driver.find_element_by_xpath("//span[@ng-bind='idUsuario']").click() time.sleep(1) driver.find_element_by_xpath("//a[@ng-click='__ayuda()']").click() time.sleep(1) actions.key_down(Keys.CONTROL) actions.send_keys('r') actions.key_up(Keys.CONTROL) actions.perform() time.sleep(.5) ''' ######################## Hilo sin titulo ############################################# driver.find_element_by_xpath("//a[@id='config']").click() time.sleep(.5) driver.find_element_by_id("fHilo_contenido").clear() driver.find_element_by_id("fHilo_contenido").send_keys("Nuevo Contenido") time.sleep(1) driver.find_element_by_xpath("//button[@type='submit']").click() time.sleep(1) ######################## Hilo sin contenido ############################################# driver.find_element_by_xpath("//a[@id='config']").click() time.sleep(.5) driver.find_element_by_id("fHilo_titulo").clear() driver.find_element_by_id("fHilo_titulo").send_keys("Nuevo Hilo") driver.find_element_by_id("fHilo_contenido").clear() time.sleep(1) driver.find_element_by_xpath("//button[@type='submit']").click() time.sleep(1) ######################## Creacion Hilo ############################################# driver.find_element_by_xpath("//a[@id='config']").click() time.sleep(.5) driver.find_element_by_id("fHilo_titulo").clear() driver.find_element_by_id("fHilo_titulo").send_keys("Nuevo Hilo") driver.find_element_by_id("fHilo_contenido").clear() driver.find_element_by_id("fHilo_contenido").send_keys("Nuevo Contenido") time.sleep(1) driver.find_element_by_xpath("//button[@type='submit']").click() time.sleep(1) ######################## Creacion Hilo Existente ############################################# ''' driver.find_element_by_xpath("//a[@id='config']").click() time.sleep(.5) driver.find_element_by_id("fHilo_titulo").clear() driver.find_element_by_id("fHilo_titulo").send_keys("Nuevo Hilo") driver.find_element_by_id("fHilo_contenido").clear() driver.find_element_by_id("fHilo_contenido").send_keys("Nuevo Contenido") time.sleep(1) driver.find_element_by_xpath("//button[@type='submit']").click() time.sleep(1) ''' ######################## Publicacion sin contenido y ayuda ############################################# driver.find_element_by_link_text("Nuevo Hilo").click() time.sleep(1) actions.key_down(Keys.CONTROL) actions.send_keys('r') actions.key_up(Keys.CONTROL) actions.perform() time.sleep(.5) driver.find_element_by_xpath("//button[@id='btnForos']").click() #driver.find_element_by_xpath("//span[@class='glyphicon glyphicon-info-sign']").click() ###### AYUDA ####################################### time.sleep(1) ######################## Publicacion sin titulo ############################################# driver.find_element_by_id("fpublicacion_titulo").clear() driver.find_element_by_id("fpublicacion_titulo").send_keys("") driver.find_element_by_id("fpublicacion_texto").clear() driver.find_element_by_id("fpublicacion_texto").send_keys("Nuevo Contenido") time.sleep(1) driver.find_element_by_xpath("//button[@type='submit']").click() time.sleep(1) ######################## Publicacion Vacia ############################################# driver.find_element_by_id("fpublicacion_titulo").clear() driver.find_element_by_id("fpublicacion_titulo").send_keys("") time.sleep(1) driver.find_element_by_xpath("//button[@type='submit']").click() time.sleep(1) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) ######################## Crear Publicacion ############################################# driver.find_element_by_id("fpublicacion_texto").clear() driver.find_element_by_id("fpublicacion_texto").send_keys("Nuevo Texto") time.sleep(1) driver.find_element_by_xpath("//button[@type='submit']").click() time.sleep(1) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) ######################## Publicacion nuevo titulo ############################################# driver.find_element_by_id("fpublicacion_titulo").clear() driver.find_element_by_id("fpublicacion_titulo").send_keys("Nueva Titulo") driver.find_element_by_id("fpublicacion_texto").clear() driver.find_element_by_id("fpublicacion_texto").send_keys("Nuevo Comentario") time.sleep(1) driver.find_element_by_xpath("//button[@type='submit']").click() time.sleep(1) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) ######################## Publicacion "duplicada" ############################################# driver.find_element_by_id("fpublicacion_titulo").clear() driver.find_element_by_id("fpublicacion_titulo").send_keys("Nueva Titulo") driver.find_element_by_id("fpublicacion_texto").clear() driver.find_element_by_id("fpublicacion_texto").send_keys("Nuevo Comentario") time.sleep(1) driver.find_element_by_xpath("//button[@type='submit']").click() time.sleep(1) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) ######################## Publicaciones Anidadas ############################################# driver.find_element_by_xpath("(//a[@ng-click='responderPublicacion(publicacion)'])[2]").click() driver.find_element_by_xpath("(//textarea[@id='fpublicacion_texto'])[2]").clear() driver.find_element_by_xpath("(//textarea[@id='fpublicacion_texto'])[2]").send_keys("Nuevo Comentario 2") time.sleep(1) driver.find_element_by_xpath("(//button[@type='submit'])[2]").click() time.sleep(1) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) driver.find_element_by_xpath("(//a[@ng-click='responderPublicacion(publicacion)'])[3]").click() driver.find_element_by_xpath("(//textarea[@id='fpublicacion_texto'])[2]").clear() driver.find_element_by_xpath("(//textarea[@id='fpublicacion_texto'])[2]").send_keys("Nuevo Comentario 3") time.sleep(1) driver.find_element_by_xpath("(//button[@type='submit'])[2]").click() time.sleep(1) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) driver.find_element_by_xpath("(//a[@ng-click='responderPublicacion(publicacion)'])[2]").click() driver.find_element_by_xpath("(//textarea[@id='fpublicacion_texto'])[2]").clear() driver.find_element_by_xpath("(//textarea[@id='fpublicacion_texto'])[2]").send_keys("Nuevo Comentario 2.2") time.sleep(1) driver.find_element_by_xpath("(//button[@type='submit'])[2]").click() time.sleep(1) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) ######################## Eliminar Publicaciones ############################################# driver.find_element_by_xpath("(//a[@ng-click='AElimPublicacion1(publicacion.id)'])[3]").click() time.sleep(0.5) alert.accept() time.sleep(.5) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) driver.find_element_by_xpath("(//a[@ng-click='AElimPublicacion1(publicacion.id)'])[2]").click() time.sleep(0.5) alert.accept() time.sleep(.5) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) driver.find_element_by_xpath("(//a[@ng-click='AElimPublicacion1(publicacion.id)'])[6]").click() time.sleep(0.5) alert.accept() time.sleep(.5) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) driver.find_element_by_xpath("(//a[@ng-click='AElimPublicacion1(publicacion.id)'])[5]").click() time.sleep(0.5) alert.accept() time.sleep(.5) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) driver.find_element_by_xpath("(//a[@ng-click='AElimPublicacion1(publicacion.id)'])[4]").click() time.sleep(0.5) alert.accept() time.sleep(.5) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform() time.sleep(.5) ######################## Eliminar Hilos ############################################# actions.send_keys(Keys.ALT) actions.send_keys(Keys.ARROW_LEFT) actions.perform() driver.find_element_by_xpath("(//a[contains(@ng-click,'AElimHilo1')])[1]").click() time.sleep(0.5) alert.accept() time.sleep(.5) actions.send_keys(Keys.ALT) actions.send_keys(Keys.ARROW_LEFT) actions.perform() ######################## Eliminar Foro ############################################# driver.find_element_by_xpath("(//a[contains(@ng-click,'AElimForo1')])[last()]").click() time.sleep(0.5) alert.accept() time.sleep(.5) actions.send_keys(Keys.CONTROL) actions.send_keys('r') actions.perform()
def add_user(self, details): """ Add a single user into ICE Assumes login() has been called details = {'firstName': '', 'surname': '', 'username': '', 'description': '', 'role': '', 'location': '', 'newPassword: ''} Returns string: comment of what happened """ try: self.driver.switch_to.default_content() # Jump to the top of the frames hierachy self.driver.find_element_by_id('a151').click() # Add/Edit user button wait = WebDriverWait(self.driver, 10) wait.until(EC.frame_to_be_available_and_switch_to_it((By.NAME, 'Right'))) wait.until(EC.frame_to_be_available_and_switch_to_it((By.NAME, 'appFrame'))) # Add new user menu self.driver.find_element_by_id('AddButton').click() self.driver.find_element_by_id('usernameTextBox').send_keys(details['username']) self.driver.find_element_by_id('PasswordTextBox').send_keys(details['newPassword']) self.driver.find_element_by_id('ConfirmPasswordTextBox').send_keys(details['newPassword']) if not self.driver.find_element_by_id('ChangePasswordCheckBox').is_selected(): # Should always be unticked on load self.driver.find_element_by_id('ChangePasswordCheckBox').click() self.driver.find_element_by_id('FullnameTextBox').send_keys(details['firstName'] + ' ' + details['surname']) self.driver.find_element_by_id('InitialsTextbox').send_keys(details['firstName'][:1] + details['surname'][:1]) self.driver.find_element_by_id('DescriptionTextBox').send_keys(details['description']) # Description/Job title Select(self.driver.find_element_by_id('RoleList')).select_by_visible_text(details['role']) # Role dropdown # Locations Profile wait.until(EC.element_to_be_clickable((By.ID, 'imgLP'))) self.driver.find_element_by_id('imgLP').click() Select(self.driver.find_element_by_id('LocationListBox')).select_by_visible_text(details['location']) #All Locations dropdown self.driver.find_element_by_id('AddButton').click() except: return "There was a problem filling in the page. Can you check the role/location etc?" try: self.driver.find_element_by_id('btnCommand').click() # Save user time.sleep(1) # Alert will display if a duplicate is found in the system alert = Alert(self.driver) alertText = alert.text alert.accept() wait.until(EC.element_to_be_clickable((By.ID, 'btnCommand'))) # Wait for Save User button self.driver.find_element_by_id('btnGoToIndex').click() if alertText[:13] == "Create failed" and alertText[-30:] == "already exists; cannot create.": return "Duplicate person found in the system" else: return alertText except NoAlertPresentException: # If you have a success message try: if self.driver.find_element_by_id('messageDisplay').text.strip() == \ 'The user has been successfully updated.'\ or self.driver.find_element_by_id('messageDisplay').text.strip() == \ 'The user has been successfully added.': return 'User added successfully' else: return self.driver.find_element_by_id('messageDisplay').text.strip() except NoSuchElementException: # You are now stuck on the page unable to save with an error (usually unrecoverable for add user) # Password problem? try: if self.driver.find_element_by_id('PasswordValidator').text == 'You have used this password before in your last three passwords.': return "Couldn't save the user as password has been used before." else: return self.driver.find_element_by_id('PasswordValidator').text except NoSuchElementException: # Location correction try: if self.driver.find_element_by_id('spanLocationError').text == "There must be at least one location in the user's profile.": Select(self.driver.find_element_by_id('LocationListBox')).select_by_visible_text(details['location']) #All Locations dropdown self.driver.find_element_by_id('AddButton').click() self.driver.find_element_by_id('btnCommand').click() # Save user time.sleep(1) try: # If you have a success message if self.driver.find_element_by_id('messageDisplay').text.strip() == "The user has been successfully updated.": return "Success (& location updated)" except NoSuchElementException: pass except: pass return "Couldn't save the user for some reason I can't determine."