白白学习笔记【pytest】:fixture

嘿嘿,工作有点忙,一份迟来的笔记 ( ̄o ̄) . z Z

fixture作用

实现前置步骤功能,方便用例调用

fixture使用

装饰器:@pytest.fixture()

import pytest


@pytest.fixture()
def fixture1():
    print("\nfixture function 1")


@pytest.fixture()
def fixture2():
    print("\nfixture function 2")


@pytest.mark.parametrize("a, b", [(1, 1)], ids=['fixture'])
def test_case_fixture(fixture1, fixture2, a, b):
    print(f"a:{a}  b:{b}")
    assert True

fixture参数

fixture(
    fixture_function: Optional[_FixtureFunction] = None,
    *,
    scope: "Union[_Scope, Callable[[str, Config], _Scope]]" = "function",
    params: Optional[Iterable[object]] = None,
    autouse: bool = False,
    ids: Optional[
        Union[
            Iterable[Union[None, str, float, int, bool]],
            Callable[[Any], Optional[object]],
        ]
    ] = None,
    name: Optional[str] = None,
)

fixture_function

还没学 ~( ̄▽ ̄)~*

scope

作用:设置fixture生效范围

值列表:

  • function:方法级别【默认值】
  • class:类级别
  • module:模块级别
  • package:包级别
  • session:项目级别

params

作用:设置fixture函数参数

值获取:函数添加入参request,函数体使用request.param依次获取参数

注:

  • params将导致多次调用fixture函数和使用它的所有测试
  • 同时使用fixture params和mark.parametrize,将会笛卡尔积方式运行

fixture params:

import pytest


@pytest.fixture(params=["a", "b", "c"])
def fixture_params(request):
    print("fixture_params print: " + request.param)


def test_case(fixture_params):
    assert True

fixture params + mark.parametrize:

import pytest


@pytest.fixture(params=["a", "b"])
def fixture_params(request):
    print("\nfixture_params print: " + request.param)


@pytest.mark.parametrize('num', [1, 2])
def test_case(fixture_params, num):
    print("test_case print: " + str(num))
    assert True

autouse

作用:设置fixture是否自动运行

值列表:

  • True:自动运行生效,等同setup/teardown
  • False:自动运行关闭【默认值】

注:

  • 直接调用实现setup效果
  • 使用yield实现teardown效果
import pytest


@pytest.fixture(autouse=True)
def fixture_autouse():
    print("\nsetup: fixture_autouse")
    yield
    print("\nteardown: fixture_autouse")


def test_case():
    assert True

ids

作用:用例命名

注:

  • 需要对应params使用
  • 同时使用fixture ids和mark.parametrize ids,将会使用 - 连接命名

fixture ids:

import pytest


@pytest.fixture(params=["a"], ids=["fixture_a"])
def fixture_params_ids(request):
    print("\nfixture_params_ids print: " + request.param)


def test_case(fixture_params_ids):
    assert True

fixture ids + mark.parametrize ids:

import pytest


@pytest.fixture(params=["a"], ids=["fixture_a"])
def fixture_params_ids(request):
    print("\nfixture_params_ids print: " + request.param)


@pytest.mark.parametrize("num", [1], ids=["case_1"])
def test_case(fixture_params_ids, num):
    print("\ntest_case print: " + str(num))
    assert True

fixture return

作用:在case中调用fixture,获取返回值

import pytest


@pytest.fixture()
def fixture_return():
    return "fixture_return return"


def test_case(fixture_return):
    print("\ntest_case print: " + fixture_return)
    assert True

2 个赞