fixture:这个就是pytest中到前置后置。
定义:
1、pytest如何实现前置和后置的,都是写在一个函数里。
@pytest.fixture
def fix():
前置代码
yeild # 分割区
后置代码
2、还有4个作用域:
测试函数(function)\测试类(class)测试模块文件(module)\测试会话(session)
例如4:运行main文件后。就是产生的会话。
@pytest.fixture(scope=function)默认。(scope=class)或者(scope=module)或者(scope=session)
def fix():
前置代码
yeild # 分割区
后置代码
3、fixture相对独立,不跟测试类和测试函数放在一起,
后面如果有需要的话,就再调用。
4、fixture的共享机制,放在conftest.py
conftest.py 定义fixture,可以定义多个。
5、fixture的调用:
a.用例和类主动调用fixture
b.哪儿需要哪儿调:
@pytest.mark.usefixtures(“fixture的函数名称”)
测试类/测试函数
c.如果fixture有返回值,
那么,将它作为测试函数的参数时,则可以不用使用: @pytest.mark.usefixtures(“fixture的函数名称”)
6、返回值,yield 返回值(下面代码没有进行操作)
下面是代码:小试牛刀
@pytest.fixture
def front_and_postposition():
print("前置********代码")
yield
print("后置********代码")
@pytest.mark.usefixtures("front_and_postposition")
def test_start():
print("函数测试开始")
class TestBasics:
def test_start_1(self):
print("类测试开始1")
def test_start_2(self):
print("类测试开始2")
pytest执行顺序,从上往下执行,记得浮标一定放在最下面,才能执行全部,如果放在一个方法的行内,就会执行当前一条。