1、@pytest.mark.parametrize()基本用法
@pytest.mark.parametrize(args_name, args_value)
args_name:参数名 args_value:参数值(列表,元祖,字典列表,字典元组),有多个值用例就会执行多次
第一种方式:
import pytest
class TestApi:
@pytest.mark.parametrize('args', ['百里', '星耀', '铂金'])
def test_01_single_arg(self, args):
print(args)
第二种方式:跟unittest的ddt里边的@unpack解包的一样
import pytest
class TestApi:
@pytest.mark.parametrize('name,age', [['百里', 18], ['星耀', 19], ['铂金', 20]])
def test_02_double_arg(self, name, age):
print(name, age)
2、YAML文件详解 --实现接口自动化 --数据驱动思想
1.用于全局的配置文件 ini/yaml 2.用于写测试用例(接口测试用例)
yaml是一种数据格式,支持注释,换行,多行字符串,裸字符串(整形,字符串)
语法规则:
- 区分大小写
- 使用缩进表示层级,不能使用tab键缩进,只能用空格(和python一样)
- 缩进是没有数量的,只要前面是对齐的就行
- 注释是#
封装工具类:
python使用pyyaml库进行yaml文件的解析
test_api.yaml
-
name: 获得token鉴权码的接口
request:
url: https://api.weixin.qq.com/cgi-bin/token
method: get
headers:
Content-Type: application/json
params:
grant_type: client_credential
appid: wx6b11b3efd1cdc290
secret: 106a9c6157c4db5f6029918738f9529d
validate:
- eq: {expires_in: 7200}
-
name: 获得token鉴权码的接口
request:
url: https://api.weixin.qq.com/cgi-bin/token
method: get
headers:
Content-Type: application/json
params:
grant_type: client_credential
appid: wx6b11b3efd1cdc290
secret: 106a9c6157c4db5f6029918738f9529d
validate:
- eq: {expires_in: 7200}
yaml_util.py
import yaml
class YamlUtil:
def __init__(self, yaml_file):
"""
通过init方法把yaml文件传入到这个类
:param yaml_file:
"""
self.yaml_file = yaml_file
def read_yaml(self):
"""
读取yaml,对yaml反序列化,把yaml格式转换成dict格式。
:return:
"""
with open(self.yaml_file, 'r', encoding='utf-8') as f:
value = yaml.load(f, Loader=yaml.FullLoader)
return value
if __name__ == '__main__':
obj = YamlUtil('./test_api.yaml')
obj.read_yaml()
test_api.py
import pytest
import requests
from testapi.yaml_util import YamlUtil
class TestApi:
@pytest.mark.parametrize('args', YamlUtil('testapi/test_api.yaml').read_yaml())
def test_01_single_arg(self, args):
url = args['request']['url']
params = args['request']['params']
res = requests.get(url, params=params)
print(res.content)
运行pytest,打印日志
============================= test session starts ==============================
platform darwin -- Python 3.7.9, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 --
collecting ... collected 2 items
testapi/test_api.py::TestApi::test_01_single_arg[args0] b'{"access_token":"48_qP9SU5U47fNbLbSbdnwPUU9GBN29O6jNIGPFIAxjn2Jzn_Bar4QKA0VlZ7z6iZEO_allsJJ3vXN4vAOaqgD2MF-yOYHtmN9_iOFMT3QmkBpi0FVYmbhEBAinpRRVqo622Jsmijqe98LFa8AMKWVgAGAFRQ","expires_in":7200}'
PASSED
testapi/test_api.py::TestApi::test_01_single_arg[args1] b'{"access_token":"48_qP9SU5U47fNbLbSbdnwPUU9GBN29O6jNIGPFIAxjn2Jzn_Bar4QKA0VlZ7z6iZEO_allsJJ3vXN4vAOaqgD2MF-yOYHtmN9_iOFMT3QmkBpi0FVYmbhEBAinpRRVqo622Jsmijqe98LFa8AMCLGgAGASBW","expires_in":7200}'
PASSED
============================== 2 passed in 0.62s ===============================
3、测试框架封装
- 断言的封装
- allure报告的定制
- 关键字驱动和数据驱动结合实现接口自动化测试。
- python的反射
- jenkins的持续集成和allure报告集成,并且根据自动化的报告的错误率发送电子邮件
|