python - 当被多个测试函数调用时,Pytest 是否缓存 fixture 数据?

标签 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
我不想多次下载此数据。它应该只下载一次,并传递给所有需要它的测试。 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 the large_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 sessionpytest文档了解更多详情。

关于python - 当被多个测试函数调用时,Pytest 是否缓存 fixture 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64690820/

相关文章:

unit-testing - 在 Octave 中测试子函数

c# - 如何检查列表是否已排序?

python - 运行测试前的 Pytest 和数据库清理

python - py.test : get KeyboardInterrupt to call teardown

python - 如何在非主线程 QObject 中开始工作

python - 在 python 中创建缓冲区

Python - 用于将数据插入数据库的 MySql 访问

Python:分类数据的排序相关性

postgresql - pgtap:预期和获得的结果相等,但测试失败

python - 如何防止打印 fixture 的值?