我有需要测试数据的单元测试。此测试数据已下载,文件大小相当大。
@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
我不想多次下载此数据。它应该只下载一次,并传递给所有需要它的测试。 pytest 是否调用 large_data_file
一次并在使用该装置的每个单元测试中使用它,或者它是否调用 large_data_file
每一次?在
unittest
,您只需在 setUpClass
中下载一次所有测试的数据。方法。我宁愿不只是一个全局
large_data_file = download_some_data('some_token')
在这个 py 脚本中。我想知道如何使用 Pytest 处理这个用例。
最佳答案
Does pytest call on
large_data_file
once and use it for every unit test that uses that fixture, or does it call thelarge_data_file
each time?
这取决于 fixture 范围。默认范围是
function
,所以在你的例子中 large_data_file
将被评估三遍。如果您扩大范围,例如@pytest.fixture(scope="session")
def large_data_file():
...
fixture 将在每个测试 session 中评估一次,结果将被缓存并在所有相关测试中重用。查看部分 Scope: sharing fixtures across classes, modules, packages or session在 pytest
文档了解更多详情。
关于python - 当被多个测试函数调用时,Pytest 是否缓存 fixture 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64690820/