量化接口,pytest的参数化方式
量化接口,pytest.fixture()方式进行参数化,fixture装饰的函数可以作为参数传入其他函数conftest.py文件中存放参数化函数,可作用于模块内的所有测试用例pytest.marparametrize()方式进行参数化
本节测试依然以is_leap_year.py方法作为测试目标:
def is_leap_year(year):
# 先判断year是不是整型
if isinstance(year, int) is not True: raise TypeError('传入的参数不是整数') elif year == 0: raise ValueError('公元元年是从公元一年开始!!') elif abs(year) != year: raise ValueError('传入的参数不是正整数') elif (year % 4 ==0 and year % 100 != 0) or year % 400 == 0:
print('%d年是闰年' % year) return True
else:
print('%d年不是闰年' % year) return False
fixture是pytest的闪光点,在pytest中fixture的功能很多,本节主要介绍用fixture的参数化功能。
pytest.fixture()中传入的参数为list,用例执行时,遍历list中的值,每传入一次值,则相当于执行一次用例。ps:@pytest.fixture()装饰的函数中,传入了一个参数为request,试试改成其他的会出现什么情况。这里的测试数据是直接存在list中的,能否存入json文件或者xml文件再进行读取转换为list呢?fixture_parapng
测试数据和用例分离
参数化数据和用例怎么进行分离呢?可以采用conftest.py文件存储参数化数据和函数,模块下的用例执行时,会自动读取conftest.py文件中的数据
# conftest.py 记住 他叫conftest.pyimport pytest# 准备测试数据is_leap = [4, 40, 400, 800, 1996, 2996]
is_not_leap = [1, 100, 500, 1000, 1999, 3000]
is_valueerror = [0, -4, -100, -400, -1996, -2000]
is_typeerror = ['-4', '4', '100', 'ins', '**', '中文']# params中需要传入list@pytest.fixture(params=is_leap)def is_leap_y(request):
return request.param@pytest.fixture(params=is_typeerror)def is_type_error(request):
return request.param
测试用例文件:
# test_para.pyimport sys
sys.path.append('.')import is_leap_yearimport pytestclass TestPara():
def test_is_leap(self, is_leap_y):
assert is_leap_year.is_leap_year(is_leap_y) == True
def test_is_typeerror(self, is_type_error):
with pytest.raises(TypeError):
is_leap_year.is_leap_year(is_type_error)
测试结果:
PS E:python_interface_test
equests_practice> pytest -q . est_para.py............ [100%]12 passed in 0.03 seconds
pytest.marparametrize()方式进行参数化
文章为作者独立观点,不代表 股票程序化软件自动交易接口观点