python接口参数化1
- 安装pytest框架
- 熟悉HTTP协议
思路与知识点
- 首先确保自己需要测试的接口能调通
- 确定自己所需要参数化的字段
- 使用pytest框架的装饰器标记数据@pytest.fixture
- 参数化数据必须为列表
直接上手撸代码
# 导包
import requests
import pytest
#定义一个参数化需要的数据,必须是列表!
#undata1 = [['张飞9','111111'],['张飞10','222222'],['张飞11','333333'],['张飞12','444444']]
undata1 = [{'username':'嘘嘘01','password':'111111'},{'username':'嘘嘘02','password':'111111'},{'username':'嘘嘘03','password':'111111'}]
#类似于java上的注解,标记数据源,将数据源给username
@pytest.fixture(params=undata1)
def username(request):
return request.param
#类名
class Test_no():
#方法名,传的参数就是,数据给了装饰器,作为参数给了下面的方法
def test_learn(self,username):
url="http://localhost:8080/admin/register"
body={
"email": "string",
"icon": "string",
"nickName": "string",
"note": "string",
"password": "12112",
"username": "11212"
}
# 数据源是list,使用下标取值,并赋值给body
#body["username"] = username[0]
#body["password"] = username[1]
## 数据源是Dictionary,使用key取值,并赋值给body
body["username"]=username["username"]
body["password"] = username["password"]
# 调用post方法,传入url,body两个参数
r1= requests.post(url=url,json=body)
# 最后输出响应结果
print(r1.text)
# 增加断言
assert r1.json()["message"] == "操作成功"
响应报文
.{"code":200,"message":"操作成功","data":{"id":17,"username":"嘘嘘01","password":"96e79218965eb72c92a549dd5a330112","icon":"string","email":"string","nickName":"string","note":"string","createTime":1552921608805,"loginTime":null,"status":1}}
.{"code":200,"message":"操作成功","data":{"id":18,"username":"嘘嘘02","password":"96e79218965eb72c92a549dd5a330112","icon":"string","email":"string","nickName":"string","note":"string","createTime":1552921608827,"loginTime":null,"status":1}}
.{"code":200,"message":"操作成功","data":{"id":19,"username":"嘘嘘03","password":"96e79218965eb72c92a549dd5a330112","icon":"string","email":"string","nickName":"string","note":"string","createTime":1552921608840,"loginTime":null,"status":1}}
[100%]
conftest文件配置
- conftest.py配置脚本名称是固定的,不能改名称
- conftest.py与运行的用例要在同一个pakage下,并且有init.py文件
- 不需要import导入 conftest.py,pytest用例会自动查找
实例
在包中新建一个conftest文件,将数据源放入该文件中,原来文件中数据源删除.png