我对python的行为非常陌生,但在本例中,我决定用Selenium来尝试一下。
- test.feature
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!
- test.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.
问题是,浏览器在测试失败后不会关闭,只有在测试通过时才会关闭。这就是为什么我尝试尝试尝试& except的原因。这一个做它的工作-测试失败后,它关闭浏览器,但是...显示错误的测试结果-标记所有三个步骤为通过,而它应该是一个失败-因为按钮没有显示在页面上!我怎么才能使它工作呢?我的意思是,即使测试失败并给出正确的结果,也要关闭浏览器?
1条答案
按热度按时间ttp71kqs1#
下面是一个示例,说明如何使用此方法处理测试失败和浏览器关闭:
在这里,测试失败后,脚本将引发一个
AssertionError
,将context.failed
变量设置为True,然后脚本将执行下一步关闭浏览器,即关闭浏览器,这样即使测试失败,浏览器也会关闭,测试结果也会准确。