Python使用allure-behave结合Selenium测试截图失败如何解决
问题根源
- 代码执行逻辑错误:你在
except分支中先执行assert False,该语句会直接抛出断言异常终止函数运行,后续的context.driver.close()永远不会被执行,driver进程未被正常销毁,残留无效进程句柄触发WinError 6报错。 - Allure附件上传参数顺序错误:原代码中
allure.attach的第一个参数为附件名、第二个为附件内容,和官方要求的参数顺序完全相反,执行时会直接抛出异常。 - 重复调用元素查找函数:你先后两次执行
login_error_message(context)查找页面元素,若页面加载状态变化会导致第二次调用失败,也会触发异常。
修复方案
方案1:直接修改当前步骤函数
调整执行逻辑,保证driver进程被正常关闭,修正Allure参数,代码如下:
@then('the home page does not open with invalid username') def assert_login_unsuccessful(context): test_pass = False try: error_msg = login_error_message(context) if error_msg == "Please, enter valid credentials": print("***Login Not Successful - Home page is not open***") # 修正allure.attach参数顺序:内容在前,名称在后 allure.attach(context.driver.get_screenshot_as_png(), name="login_failed_screenshot", attachment_type=allure.attachment_type.PNG) # 直接用selenium自带截图方法,比pyautogui更稳定,无需额外依赖 context.driver.save_screenshot(r'C:\Users\lakshmi krishnaswamy\screenshots\assert_login_unsuccessful_error_message_invalid_username.png') test_pass = True except Exception as e: # 异常时也截图方便排查问题 allure.attach(context.driver.get_screenshot_as_png(), name="run_error_screenshot", attachment_type=allure.attachment_type.PNG) assert False, f"Test Failed: {str(e)}" finally: # 无论执行结果如何都关闭driver,销毁进程 context.driver.quit() assert test_pass, "Test Passed: Login failed as expected"
方案2:全局钩子自动截图(更推荐)
在项目根目录新建environment.py文件,添加behave钩子函数,实现所有失败步骤自动截图、场景结束自动关闭driver,无需在每个步骤中重复编写逻辑:
import allure def after_step(context, step): # 步骤失败时自动截图存入Allure报告 if step.status == "failed": allure.attach(context.driver.get_screenshot_as_png(), name=f"failed_at_{step.name}", attachment_type=allure.attachment_type.PNG) def after_scenario(context, scenario): # 每个场景执行完成后统一关闭driver if hasattr(context, "driver"): context.driver.quit()
运行注意事项
- 每次运行测试前先清空
reports目录,避免旧的测试结果影响Allure报告生成 - 运行测试命令保持不变:
behave -f allure_behave.formatter:AllureFormatter -o reports/ features/d3a-login.feature - 生成可视化Allure报告执行:
allure serve reports即可直接在浏览器中查看带截图的报告
内容的提问来源于stack exchange,提问作者lakshmi krishnaswamy
相关产品推荐
相关产品推荐

