pytest之fixture
Xunit风格的tearup、teardown都是测试用例中用于初始化和销毁环境、数据的函数。Pytest有一个特有的功能--fixture,可以完全实现这些功能,但比它们更强大,更灵活。fixture的功能主要有:
1、初始化, 实现测试前的初始化动作
2、参数化, 给测试用例传入多个数据驱动,而不需要显式调用测试函数多次
把一个函数定义为fixture很简单,需要在函数声明之前加上@pytest.fixture进行修饰。其他测试函数如果要使用这个fixture,只需把它当做测试函数的一个输入参数即可。如
[root@localhost pytest]# vi test_s2.py
import pytest
@pytest.fixture() #默认,等价于@pytest.fixture(scope=”function”)
def mybeforefixture():
print('run beforefixture')
初始化
其他测试函数如果要使用这个fixture,只需把它当做测试函数的一个输入参数即可,如
class Test_c1:
deftest_instr(self):
x="in china"
print("\ntest instr method called")
assert 'china' in x
deftest_int(self,mybeforefixture): #传入fixture函数名
print("test int method called")
assert 1==1
if __name__ == "__main__":
pytest.main(["-s", "test_s2.py"])
运行结果
[root@localhost pytest]# python test_s2.py
….
collected 2 items
test_s2.py
test instr method called
.run beforefixture
test int method called
.
….
[root@localhost pytest]#
在运行传入fixture函数名的测试方法之前便会运行该fixture函数,另外未传入函数名的测试函数便不会执行。可以定义多个fixture函数,这样可以供多个测试函数使用,每个测试函数可以使用不同的fixture函数。
参数化
如果我们想根据传入参数的不同而调用一个测试函数多次,这通常需要使用循环来实现,而使用参数化fixture,不需要显式调用测试函数多次,每个使用该fixture的测试函数都可以被运行多次,fixture 的这个特性非常强大。
如
[root@localhost testfile]# cattest_fixture_params.py
import pytest
paramlist=[('sina.1',1),('163.2',0)]
@pytest.fixture(params=paramlist)
def smtp(request):
return request.param
def test_smtp_postfix(smtp):
var=smtp[0].split('.')[1]
assert var==str(smtp[1])
这里向fixture提供参数,参数可以是list,该list中有几条数据,fixture就会运行几次,相应的测试用例也会运行几次。
[root@localhost ~]# pytesttest_fixture.py
=============================test session starts===============================
platform linux2 -- Python 2.7.5,pytest-4.3.0, py-1.8.0, pluggy-0.9.0
rootdir: /root, inifile:
plugins: celery-4.1.0
collected 2 items
test_fixture.py .F [100%]
===================================FAILURES ==============================
__________________________________________test_smtp_postfix[smtp1] ____________________________
smtp = ('163.2', 0)
def test_smtp_postfix(smtp):
var=smtp[0].split('.')[1]
> assert var==str(smtp[1])
E AssertionError: assert '2' == '0'
E - 2
E + 0
test_fixture.py:12:AssertionError
================ 1 failed, 1 passedin 0.06 seconds =================
[root@localhost ~]#