【pytest】参数化之如何启动
1、test函数前部,用注解器 @pytest.mark.parametrize
test_create.py
#!/usr/bin/python3
# -*- coding:utf-8 -*-
import pytest, eval
from get_data import test_data #从文件导入参数列表
class TestCreate:
@pytest.mark.parametrize('data', test_data) #注解器声明
def test_create(self, data): # data为注解器变量
"""
创建
"""
res = moment_api.create(eval(data)) #将data转为json串,直接传递给api
assert res.status_code == 200
assert res.json()['success']
if __name__ == '__main__':
pytest.main(['-s', 'test_create.py'])
2、从文件中读取参数的示例:
get_data.py
# !/usr/bin/python3
# -*- coding:utf-8 -*-
import os
import pytest
from data.get_conf import BASE_PATH
from util.parse_file import parse_file
def get_data(yaml_file_name):
data_file_path = os.path.join(BASE_PATH, "data/", yaml_file_name)
try:
yaml_data = parse_file.load_yaml(data_file_path)
except Exception as ex:
pytest.skip(str(ex))
else:
return yaml_data
# ==== 读取测试数据 ====
data = get_data('test.yml')
test_data = data['test_data']
util/parse_file.py
# !/usr/bin/python3
# -*- coding:utf-8 -*-
import yaml
import json
from configparser import ConfigParser
class MyConfigParser(ConfigParser):
# 重写 configparser 中的 optionxform 函数,解决 .ini 文件中的 键option 自动转为小写的问题
def __init__(self, defaults=None):
ConfigParser.__init__(self, defaults=defaults)
def optionxform(self, optionstr):
return optionstr
class ParseFileData:
def load_yaml(self, file_path):
with open(file_path, encoding='utf-8') as f:
data = yaml.safe_load(f)
return data
def load_json(self, file_path):
with open(file_path, encoding='utf-8') as f:
data = json.load(f)
return data
def load_ini(self, file_path):
config = MyConfigParser()
config.read(file_path, encoding='utf-8')
return dict(config._sections)
parse_file = ParseFileData()
3、含测试参数的文件:注意yaml文件的格式,格式不对情况下会出现报错expected ',' or '}', but got '<scalar>'
test.yml
test_data:
- "{ 'data_a' : '加油冲!' }"
- "{ 'data_a' : 'https://www.nowcoder.com' }"
python自动化 文章被收录于专栏
python写好pytest自动化的一些小妙招
