python pytest fixture

本文介绍了pytest中fixture的不同调用方式,包括作为函数参数直接使用、通过autouse自动调用以及利用pytest.mark.usefixtures进行指定。每种方法都有详细的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

fixture 是pytest 一个很重要的功能, 下面介绍如何调用fixture

目录

fixture 作为函数参数(最简单的一种方式)

利用fixture autouse 功能,自动调用fixture

利用pytest.mark.usefixture()


  • fixture 作为函数参数(最简单的一种方式)

import pytest

@pytest.fixture()
def before():
    print '\nbefore each test'

def test_1(before):
    print 'test_1()'


class Test1:
    def test_3(self, before):
        print('test_1()')


    def test_4(self, before):
        print('test_2()')

上列中, 所有使用参数before 的test function, 都会调用fixture "before"

  • 利用fixture autouse 功能,自动调用fixture

import pytest


@pytest.fixture(scope="module", autouse=True)
def before():
    print('\nonly once in each test')


def test_1():
    print('test_1()')

在scope 定义的范围内,pytest会自动调用fixture "before".

  • 利用pytest.mark.usefixture()

import pytest

@pytest.fixture()
def before():
    print('\nbefore each test')

@pytest.mark.usefixtures("before")
def test_1():
    print('test_1()')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值