pytest框架之fixture
1.在进行接口关联时,一般很多个接口共用一个上行接口(例如)登录,可以使用fixture定义一个测试夹具,将登录的接口写在框架的conftest.py文件中:
@pytest.fixture(scope="session")
def login_fixture():
keyword = Keyword()
url = "http://xxxxxxxxxxx/s=api/user/login"
pub_params = {"application": "app", "application_client_type": "weixin"}
data = {"accounts": "xxxxx", "pwd": "xxxxxx"}
response = keyword.request_post(url=url, params=pub_params, data=data)
token = jsonpath.jsonpath(response.json(), "$..token")[0]
return token
在需要用到登录接口的测试用例中,将这个夹具当做参数传入用例函数中,将夹具函数返回的值赋给变量token_value,在需要的地方直接引用这个变量
@allure.title("xxxxxxx")
def test_02_addcart3(login_fixture):
token_value = login_fixture
url_cart = "http://xxxxxxxxxx?s=api/cart/save"
pub_params = {"application": "app", "application_client_type": "weixin", "token": token_value}
data1 = {
"goods_id": "11",
"spec": "",
"stock": 5}
response = keyword.request_post(url=url_cart, params=pub_params, json=data1)
return response.json()
注:运行方式选择:
1.一定要使用pytest框架的入口执行文件,才能在执行用例的过程中,自动将夹具应用
2.如果选择其他执行方式,如unittest,就会报错为:
TypeError: test_02_addcart3() missing 1 required positional argument: 'login_fixture'
若报错信息为:AttributeError:"str"object Has no attribute "iter_parents",可以试着降低稳定版的pytest版本重试
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构