【问题标题】:Does Pytest cache fixture data when called by multiple test functions?当被多个测试函数调用时,Pytest 是否缓存夹具数据?
【发布时间】:2021-02-17 18:46:30
【问题描述】:

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

@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 方法中下载所有测试的数据一次。

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

【问题讨论】:

    标签: python unit-testing pytest


    【解决方案1】:

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

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

    @pytest.fixture(scope="session")
    def large_data_file():
        ...
    

    夹具将在每个测试会话中评估一次,结果将被缓存并在所有相关测试中重复使用。查看pytest 文档中的Scope: sharing fixtures across classes, modules, packages or session 部分了解更多详情。

    【讨论】:

      猜你喜欢
      • 2021-10-05
      • 2016-11-16
      • 2018-06-07
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 2018-02-24
      相关资源
      最近更新 更多