【问题标题】:Removing cached files after a pytest runpytest 运行后删除缓存文件
【发布时间】:2017-07-27 21:26:11
【问题描述】:

在使用py.test 运行测试时,我使用joblib.Memory 来缓存昂贵的计算。我正在使用的代码简化为以下内容,

from joblib import Memory

memory = Memory(cachedir='/tmp/')

@memory.cache
def expensive_function(x):
    return x**2   # some computationally expensive operation here

def test_other_function():
    input_ds = expensive_function(x=10)
    ## run some tests with input_ds

效果很好。我知道使用tmpdir_factory 固定装置可能会更优雅地完成此操作,但这不是重点。

我遇到的问题是如何在所有测试运行后清理缓存的文件,

  • 是否可以在所有测试之间共享一个全局变量(例如包含缓存对象的路径列表)?
  • py.test 中是否有一种机制可以在所有测试运行后调用某些命令(无论它们是否成功)?

【问题讨论】:

    标签: python pytest joblib


    【解决方案1】:

    是否可以在所有测试之间共享一个全局变量(例如包含缓存对象的路径列表)?

    我不会走那条路。最好避免全局可变状态,尤其是在测试中。

    py.test 中是否有一种机制可以在所有测试运行后调用某个命令(无论它们是否成功)?

    是的,将一个自动使用的会话范围固定装置添加到您的项目级 conftest.py 文件中:

    # conftest.py
    import pytest
    
    @pytest.yield_fixture(autouse=True, scope='session')
    def test_suite_cleanup_thing():
        # setup
        yield
        # teardown - put your command here
    

    yield 之后的代码将在测试套件结束时运行一次,无论通过还是失败。

    【讨论】:

    • 谢谢,这就是我想要的。同意你关于测试中的全局变量的看法..
    【解决方案2】:

    是否可以在所有测试之间共享一个全局变量(这将 包含例如缓存对象的路径列表)?

    实际上有几种方法可以做到这一点,每种方法各有利弊。我认为这个 SO 答案总结得很好 - https://stackoverflow.com/a/22793013/3023841 - 但例如:

    def pytest_namespace():
         return  {'my_global_variable': 0}
    
    def test_namespace(self):
         assert pytest.my_global_variable == 0
    

    py.test 中是否有一种机制可以在所有测试运行后调用某个命令(无论它们是否成功)?

    是的,py.test 有 teardown 可用的函数:

    def setup_module(module):
        """ setup any state specific to the execution of the given module."""
    
    def teardown_module(module):
        """ teardown any state that was previously setup with a setup_module
        method.
        """
    

    【讨论】:

    • 感谢您的回复。我想我会选择其他解决方案,但这绝对是有用的信息。我不知道模块级别的拆卸功能。
    猜你喜欢
    • 1970-01-01
    • 2021-02-25
    • 2020-09-10
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多