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

pytest-bdd中target_fixture触发PytestDeprecationWarning的问题排查

问题原因及修复方案

警告产生原因

pytest 8.0.0对内部私有API的使用做了更严格的限制,而你使用的pytest-bdd==7.0.1版本在处理target_fixture参数时,直接调用了pytest内部的私有类FixtureDef,违反了pytest的API使用规范,因此触发了弃用警告。本质是pytest-bdd该版本与pytest 8.x系列存在兼容性问题。

修复方案

有两种可行的解决方式:

方式一:升级pytest-bdd到兼容版本

pytest-bdd在7.1.0及以上版本已修复了与pytest 8.x的兼容性问题。修改requirements.txt中的pytest-bdd版本:

pytest==8.0.0
boto3==1.34.39
pytest-bdd==7.1.0  # 或更高兼容版本
devtools==0.12.2
requests==2.31.0

重新安装依赖:

pip install -r requirements.txt

此方法可保留target_fixture的原有用法,同时消除警告。

方式二:改用pytest原生fixture替代target_fixture

如果不想升级pytest-bdd,可将target_fixture的用法替换为pytest原生fixture定义,结合pytest-bdd步骤装饰器使用:

import requests
from pytest_bdd import scenario, given, when, then
import pytest

@scenario('../features/user.feature', 'Create a new user')
def test_create_user():
    pass

@given('a valid user payload')
def valid_user_payload():
    return {
        "username": "TEST"
    }

# 定义原生pytest fixture
@pytest.fixture
def response(valid_user_payload):
    api_base_url = "https://localhost:8080"
    # 注意:原代码中json参数传了字符串"user_payload"是错误的,此处修正为传入valid_user_payload变量
    response = requests.post(f"{api_base_url}/users", json=valid_user_payload)
    return response

@when('a client calls POST /users')
def create_user(response):
    # 直接使用已定义的fixture即可,无需返回值
    pass

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 14:42:40