当被多个测试函数调用时,Pytest 是否缓存夹具数据?

Aln*_*tak 2 python unit-testing pytest

我有需要测试数据的单元测试。此测试数据已下载,文件大小相当大。

@pytest.fixture
def large_data_file():
    large_data = download_some_data('some_token')
    return large_data

# Perform tests with input data
def test_foo(large_data_file): pass
def test_bar(large_data_file): pass
def test_baz(large_data_file): pass
# ... and so on
Run Code Online (Sandbox Code Playgroud)

我不想多次下载此数据。它应该只下载一次,并传递给所有需要它的测试。pytest 是否调用large_data_file一次并将其用于使用该夹具的每个单元测试,还是large_data_file每次都调用?

在 中unittest,您只需在setUpClass方法中下载一次所有测试的数据。

我宁愿不只是large_data_file = download_some_data('some_token')在这个 py 脚本中有一个全局变量。我想知道如何使用 Pytest 处理这个用例。

hoe*_*ing 5

pytest 是否调用large_data_file一次并将其用于使用该夹具的每个单元测试,还是large_data_file每次都调用?

这取决于夹具范围。默认范围是function,因此在您的示例large_data_file中将评估 3 次。如果你扩大范围,例如

@pytest.fixture(scope="session")
def large_data_file():
    ...
Run Code Online (Sandbox Code Playgroud)

夹具将在每个测试会话中评估一次,结果将被缓存并在所有相关测试中重用。查看文档中的范围:跨类、模块、包或会话共享装置pytest获取更多详细信息。