繁体   English   中英

Pytest 夹具 scope 和 @pytest.mark.parametrize

[英]Pytest fixture scope and @pytest.mark.parametrize

我对 pytest 中的夹具 scope 有点困惑。假设我有一个夹具

@pytest.fixture(scope="function")
def data():
    data = generate_some_data()
    yeild data
    teardown()

和测试 function

@pytest.mark.parametrize("runs", ["one", "two"])
def my_test(data, runs):
    run_some_tests(runs)

我的理解是,在这种情况下,将为每个参数化运行 generate_some_data() function,然后拆除固定装置 beign 设置。 是否可以保留 scope,以便对所有参数化仅设置和拆卸一次夹具?

如果您真的需要为 function 执行一次夹具并且不能将其限定为sessionmodule ,那么您可以使用class scope (将测试移至类中)

import pytest

_iter = iter(range(10))


@pytest.fixture(scope="class")
def iter_next():
    yield next(_iter)


class TestUseFixtureUsedOnce:

    @pytest.mark.parametrize("run", list("abcdefghij"))
    def test_function(self, iter_next, run):
        print(iter_next, run)

运行此打印(不计算 pytest 输出):

0 a
0 b
0 c
0 d
0 e
0 f
0 g
0 h
0 i
0 j

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM