pytest扫盲7--fixture之 autouse 参数

1、源码解释如下:
:arg autouse: if True, the fixture func is activated for all tests that can see it. If False (the default) then an explicit reference is needed to activate the fixture.
# autouse=True 时,自动使用 fixture
#
autouse=False 时,则调用函数名来实现 fixture

2、调用 fixture 的三种方式
  • 函数内直接传 fixture 的函数参数名称
  • 使用装饰器 @pytest.mark.usefixtures('func_name')
  • 定义fixture参数 autouse=True
3、autouse=True 自动使用 fixture(在conftest中编辑,作用范围为在同一级目录中全部自动调用):
# File  : conftest.py
# IDE   : PyCharm

import pytest

@pytest.fixture(autouse=True)
def automaticallyUs():
    print('
实例化webdriver')
    yield
    print('
关闭webdriver')
在同一级目录中新建 .py 文件:
# File  : test_demo_9.py
# IDE   : PyCharm

def test_1():
    print('
打开百度...')

def test_2():
    print('
登录系统...')
运行脚本:
E:personalpython38python.exe E:/personal/GitWorkSpace/pytest_basic/main.py

实例化webdriver

打开百度...
.
关闭webdriver

实例化webdriver

登录系统...
.
关闭webdriver

2 passed in 0.07s
喜时之言,多失信;怒时之言,多失体
原文地址:https://www.cnblogs.com/xiaohuboke/p/13528520.html