pytest+yaml数据驱动自动化测试
项目结构设计
项目结构如下
yaml文件
yaml文件如下,yaml格式非常严谨,一定要注意
-
url: http://127.0.0.1:5000/login
data: {
"username":"zj",
"password":"123456"
}
recode: {
"code":"1",
"msg":"登录成功"
}
-
url: http://127.0.0.1:5000/login
data: {
"username":"zj",
"password":""
}
recode: {
"code":"-1",
"msg":"用户名或密码错误"
}
utils包下的getYaml.py
读取yaml文件,并将其转为列表或字典
import yaml
def get_yaml(yaml_file):
with open(yaml_file, "r", encoding="utf-8") as f:
gy = f.read()
return yaml.load(gy, Loader=yaml.FullLoader)
testcase包下的test_login.py
因为我这里是模仿的ajax登录,所以headers里加了这些,你们可以注释掉headers。
首先调用get_yaml方法获取返回来的list,然后放入装饰器的第二个参数中,@pytest.mark.parametrize()这个装饰器相当于给你来了遍for循环,循环次数等于你list里元素的数量,比如list中有两个元素,则循环执行两次。
import allure
import requests
import json
import pytest
from utils import getYaml
yaml_url = "test.yaml"
file = getYaml.get_yaml(yaml_url)
class TestLogin:
@pytest.mark.parametrize("case", file)
def test_login(self, case):
url = case['url']
data = case['data']
recode = case['recode']
headers = {'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'}
data = {'username': data['username'],
'password': data['password']}
params = json.dumps(data)
res = requests.post(url, data=params, headers=headers)
print(recode['msg'])
assert res.json()['msg'] == recode['msg']
testAll.py
import pytest
import os
if __name__ == '__main__':
pytest.main(["./testcase","-vs","--alluredir=./report/tmp"])
os.system("allure generate ./report/tmp -o ./report/html --clean")
os.system("allure serve ./report/tmp")