pytest的fixture

Posted 永远不要矫情

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pytest的fixture相关的知识,希望对你有一定的参考价值。

fixture的作用类似于setup/teardown。
fixture命名不以test开头,用于区分用例。
在函数前使用装饰器@pytest.fixture(),括号中有个scope的参数,用于控制fixture的范围。默认取值为function,控制范围的排序为:session > module > class > function。取值范围如下所示:
在这里插入图片描述
代码如下:定义了一个init方法,作为参数传入test_1和test_02函数,在test_1函数中对init的返回值做了断言

import pytest


@pytest.fixture()
def init():
    print('init...')
    return 1


def test_1(init):
    print('test1')
    assert init == 1


def test_2(init):
    print('test2')

输出如下:

======================================================================== test session starts ========================================================================
platform win32 -- Python 3.7.6, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- d:\\python3.7.6\\python.exe
cachedir: .pytest_cache
rootdir: D:\\pythonProject\\my_selenium_project\\testcases\\pytest, configfile: pytest.ini
collected 2 items                                                                                                                                                    

test_fixture.py::test_1 init...
test1
PASSED
test_fixture.py::test_2 init...
test2
PASSED

========================================================================= 2 passed in 0.03s =========================================================================

以上是关于pytest的fixture的主要内容,如果未能解决你的问题,请参考以下文章

07-pytest-fixture实现teardown

10-pytest-parametrize中使用fixture

pytest文档62-内置fixture之request

33-pytest-内置fixture之pytestconfig使用

12-pytest-fixture使用别名

pytest之fixture