测试运行后清除缓存文件

2024-04-28 21:29:30 发布

您现在位置:Python中文网/ 问答频道 /正文

当使用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

效果很好。我知道使用^{}fixture可以更优雅地完成这项工作,但这不是重点。

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

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

Tags: 代码frompytestimportinputdefds
2条回答

is it possible to share a global variable among all tests (which would contains e.g. a list of path to the cached objects) ?

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

is there a mechanism in py.test to call some command once all the tests are run (whether they succeed or not)?

是,将自动使用的会话范围的fixture添加到项目级文件中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

屈服之后的代码将在测试套件的末尾运行一次,无论通过与否。

is it possible to share a global variable among all tests (which would contains e.g. a list of path to the cached objects) ?

其实有几种方法可以做到这一点,每种方法都有利弊。我认为这个答案很好地概括了它们-https://stackoverflow.com/a/22793013/3023841-但是例如:

def pytest_namespace():
     return  {'my_global_variable': 0}

def test_namespace(self):
     assert pytest.my_global_variable == 0

is there a mechanism in py.test to call some command once all the tests are run (whether they succeed or not)?

是的,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.
    """

相关问题 更多 >