【发布时间】:2023-01-19 19:46:34
【问题描述】:
我对 python 的行为很陌生,但在这种情况下,我决定尝试使用 Selenium。我有两个文件:
- 测试功能
Feature: Testing buttons on page. Scenario: We check if button appears and disappears after clicking. Given we visit "Buttons" webpage When we click "Add button" button, then "Delete" Then there should not exist any "Delete" button on page!- 测试.py
import time from behave import * from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import NoSuchElementException options = Options() options.add_argument("start-maximized") options.add_argument('--disable-notifications') webdriver_service = Service('C:\webdriver\chromedriver.exe') driver = webdriver.Chrome(options=options, service=webdriver_service) wait = WebDriverWait(driver, 10) @given('we visit "Buttons" webpage') def step_impl(context): url = "http://the-internet.herokuapp.com/add_remove_elements/" driver.get(url) @when('we click "Add button" button, then "Delete"') def step_impl(context): wait = WebDriverWait(driver, 10) wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[onclick*='add']"))).click() wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[onclick*='delete']"))).click() time.sleep(0.5) @then('there should not exist any "Delete" button on page!') def step_impl(context): try: driver.find_element(By.CSS_SELECTOR, "button[onclick*='delete']").is_displayed() except NoSuchElementException: driver.quit()我有两个案例。在第一种情况下,我有一些不同的“@then”代码——它只是检查按钮是否显示:
@then('there should not exist any "Delete" button on page!') def step_impl(context): if driver.find_element(By.CSS_SELECTOR, "button[onclick*='delete']").is_displayed: assert False driver.quit()这个有效,并显示测试结果为“2 步通过,1 步失败,0 步跳过,0 步未定义”和
Failing scenarios: tutorial.feature:3 We check if button appears and disappears after clicking.问题是,浏览器在测试失败后不会关闭,只有在测试通过时才会关闭。这就是我尝试 try & except 的原因。这个完成它的工作 - 测试失败后,它关闭浏览器,但是......显示错误的测试结果 - 将所有三个步骤标记为已通过,而它应该是一个失败 - 因为页面上没有显示按钮! 我怎样才能让它发挥作用?我的意思是,即使在测试失败并给出正确结果后也关闭浏览器?
【问题讨论】:
标签: python selenium selenium-webdriver python-behave