【pytest-8】fixture之autouse=True

前言

平常自动化用例中会写一些前置的fixture操作,用例需要用到就直接传该函数的参数名称就行了,当用例很多的时候,每次都传这个参数,会比较麻烦

fixture里面有个参数autouse,默认False,可以设置为True开启自动使用fixture功能,这样用例就不用每次都去传参了。

调用fixture三种方法

  •   函数或类里面方法直接传fixture 的函数参数名称
  •   使用装饰器@pytest.mark.usefixtures()修饰
  •   autouse=True自动使用

用例传fixture参数

方法一:先定义start功能,用例全部传start参数,调用该功能

#encoding:utf-8
#@Time:2020/12/1 11:12
#@Author:sunny

import time
import pytest
@pytest.fixture(scope="function")
def start(request):
    print("开始执行function...")
def test_a(start):
    print("用例a开始执行")
class Test_1():
    def test_01(self,start):
        print("用例01")
    def test_02(self,start):
        print("用例02")
if __name__ == '__main__':
    pytest.main(["-s","test_d.py"])

运行结果:

Testing started at 11:16 ...

============================= test session starts =============================
collected 3 items

test_d.py 
开始执行function...
.用例a开始执行
开始执行function...
.用例01
开始执行function...
.用例02
                                                            [100%]

========================== 3 passed in 0.02 seconds ===========================
Process finished with exit code 0

装饰器@pytest.mark.usefixtures()修饰

#encoding:utf-8
#@Time:2020/12/1 11:12
#@Author:sunny

import time
import pytest

#scope默认不加是function @pytest.fixture()
def start(request): print("开始执行function...") @pytest.mark.usefixtures("start") def test_a(): print("用例a开始执行") @pytest.mark.usefixtures("start") class Test_1(): def test_01(self): print("用例01") def test_02(self): print("用例02") if __name__ == '__main__': pytest.main(["-s","test_d.py"])

设置autouse=True自动使用

  • start设置scope为module级别,在当前.py用例模块只执行一次,autouse=True自动使用
  • open_home设置scope为function级别,每个用例前都调用一次,自动使用

示例:

#encoding:utf-8
#@Time:2020/12/1 11:12
#@Author:sunny

import time
import pytest

@pytest.fixture(scope="module",autouse=True)
def start(request):
    print("开始执行用例")
    yield
    print("结束测试")
@pytest.fixture(scope
="function", autouse=True) def test_a(): print("用例a开始执行")
class Test_1(): def test_01(self): print("用例01")
def test_02(self): print("用例02")
if __name__ == '__main__': pytest.main(["-s","test_d.py"])

运行结果:

Testing started at 11:46 ...============================= test session starts =============================

collected 2 items test_d.py 开始执行用例 用例a开始执行 .用例01 用例a开始执行 .用例02 结束测试 [100%] ========================== 2 passed in 0.02 seconds =========================== Process finished with exit code 0

上面是类里去实现用例,用函数也是一样的

 

posted @ 2020-12-01 14:06  做一只热爱生活的小透明  阅读(225)  评论(0)    收藏  举报