1.前面一篇讲了setup、teardown可以实现在执行用例前或结束后加入一些操作,但这种都是针对整个脚本全局生效的
2.fixture可以让我们自定义测试用例的前置条件
fixture 用途
1.做测试前后的初始化设置,如测试数据准备,链接数据库,打开浏览器等这些操作都可以使用fixture来实现
2.测试用例的前置条件可以使用fixture实现
3.支持经典的xunit fixture ,像unittest使用的setup和teardown
4.fixture可以实现unittest不能实现的功能,比如unittest中的测试用例和测试用例之间是无法传递参数和数据的,但是fixture却可以解决这个问题
如何使用
在函数上加个装饰器@pytest.fixture()
1.scope="function
@pytest.fixture()为空,参数scope="function",它的作用范围是每个测试用例执行之前运行一次,销毁代码在测试用例之后运行。在类中的调用也是一样的。
示例代码如下:
import pytest
#默认不填写
@pytest.fixture()
def test1():
print('\n默认不填写参数')
# 写入默认参数
@pytest.fixture(scope='function')
def test2():
print('\n 写入默认参数 function')
def test_defaultScope1(test1):
print('test1被调用')
class Testclass(object):
def test_deaultScope2(self,test2):
print('\ntest2,被调用,无返回值时,默认为None')
assert test2==None
def test_defaultScope2(test2):
print('test2被调用')
if __name__ == '__main__':
# pytest.main(['-q','test_fixture_scopeFunction.py'])
pytest.main(['-q','1.py'])
image.png
2.scope="class"
fixture为class级别的时候,如果一个class里面有多个用例,都调用了此fixture,那么此fixture只在此class里所有用例开始前执行一次。
import pytest
@pytest.fixture(scope='class')
def data():
# 这是测试数据
print('这是我的数据源,优先准备着哈')
return [1,2,3,4,5]
class TestClass(object):
def test1(self,data):
# self 可以理解为它自己英译汉我就是这么学的哈哈
print('\n输出我的数据源:'+str(data))
def test2(self,data):
# self 可以理解为它自己德,英译汉我就i是这么学的哈哈
print('\n输出我的数据源:'+str(data))
if __name__ == '__main__':
pytest.main(['-q'])
image.png
3.scope="module"
fixture为module时,在当前.py脚本里面所有用例开始前,需要执行一次
import pytest
@pytest.fixture(scope='module')
def data():
return'\nscope为module'
def test1(data):
print(data)
class TestClass(object):
def test2(self,data):
print('我在类钟'+data)
def test3(self,data):
print('我在类3'+data)
if __name__ == '__main__':
pytest.main(['-q'])
image.png
4.scope="session"
fixture为session,允许跨.py模块调用,通过conftest.py 共享fixture。
也就是当我们有多个.py文件的用例的时候,如果多个用例只需调用一次fixture也是可以实现的。必须以conftest.py命名,才会被pytest自动识别该文件.放到项目的根目录下,全局调用了;放在某个package下,在该package内有效
image.png
参考:https://www.jianshu.com/p/ef6e770f77b4
好难消化知识点,待继续更新