You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用allure-behave结合Selenium测试截图失败如何解决

问题根源

  1. 代码执行逻辑错误:你在except分支中先执行assert False,该语句会直接抛出断言异常终止函数运行,后续的context.driver.close()永远不会被执行,driver进程未被正常销毁,残留无效进程句柄触发WinError 6报错。
  2. Allure附件上传参数顺序错误:原代码中allure.attach的第一个参数为附件名、第二个为附件内容,和官方要求的参数顺序完全相反,执行时会直接抛出异常。
  3. 重复调用元素查找函数:你先后两次执行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()

运行注意事项

  1. 每次运行测试前先清空reports目录,避免旧的测试结果影响Allure报告生成
  2. 运行测试命令保持不变:behave -f allure_behave.formatter:AllureFormatter -o reports/ features/d3a-login.feature
  3. 生成可视化Allure报告执行:allure serve reports 即可直接在浏览器中查看带截图的报告

内容的提问来源于stack exchange,提问作者lakshmi krishnaswamy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 13:12:01