13.接口自动化学习-Pytest结合Yaml使用

发布于:2024-04-26 ⋅ 阅读:(28) ⋅ 点赞:(0)

问题:项目自动化测试脚本迭代出现变革技术方案
要求:测试用例从excel–变为yaml用例
注意事项:
1)尽可能少改代码
2)新技术方案yaml读取,尽可能写成一样的数据返回
[(请求体1,响应数据1),(请求体2,响应数据2)]
3)给pytest框架使用

  • handel_yaml.py
#安装环境yaml库 pip install pyYaml
import yaml

# -------获取yaml测试用例------
"""
问题:项目自动化测试脚本迭代出现变革技术方案
要求:测试用例从excel--变为yaml用例
注意事项:
1)尽可能少改代码
2)新技术方案yaml读取,尽可能写成一样的数据返回
[(请求体1,响应数据1),(请求体2,响应数据2)]
3)给pytest框架使用
"""
def get_yamlCase_data(fileDir):
    resList=[]
    with open(fileDir,encoding='utf-8') as fo:
        res=yaml.safe_load(fo.read())
        print(res)
        for one in res:
            resList.append((one['title'],one['data'],one['resp']))
        return resList

if __name__ == '__main__':v
    resList=get_yamlCase_data('../data/loginCase.yaml')
    print(resList)
   
  • loginCase.yaml
#-
#  url: &url1 /account/sLogin
#  method: &method1 POST
-
  title: 用户名正确,密码正确
  data:
    username: zz088
    password: "123456"
  resp:
    code: 20000
    msg: 登录成功
-
  title: 用户名正确,密码为空
  data:
    username: zz088
    password: ""
  resp:
    code: 9999
    msg: 用户名或密码错误

  • test_login.py yaml代替excel
import pytest,allure,os
from libs.login import Login
from utils.handle_excel import get_excel_data
from utils.handle_yaml import get_yamlCase_data
from utils.handle_path import report_path,data_path
from common.baseApi import BaseAssert
#TestLogin继承BaseAssert

@allure.epic('项目名称-外卖项目')
@allure.feature('登录模块')
class TestLogin(BaseAssert):
    @pytest.mark.parametrize('title,inBody,expData', get_yamlCase_data( data_path+'\\loginCase.yaml'))
    # @pytest.mark.parametrize('inBody,expData,title', get_excel_data( '登录模块', 'Login','请求参数','响应预期结果','标题'))
    @allure.story('登录接口')
    @allure.title("{title}")
    def test_login(self,title,inBody,expData):
        # 1.调用业务层封装的接口代码
        res=Login().login(inBody)
        print(res['msg'],expData['msg'])
        # 2.断言实际返回结果与预期结果
        self.define_assert(res['msg'],expData['msg'])

if __name__ == '__main__':
    pytest.main([__file__,'-sv','--alluredir',report_path,'--clean-alluredir'])
    os.system(f'allure serve {report_path}')