rth*_*rth 14 python pytest joblib
我joblib.Memory在运行测试时使用a 来缓存昂贵的计算py.test.我正在使用的代码简化为以下内容,
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
Run Code Online (Sandbox Code Playgroud)
哪个工作正常.我知道这可能会更加优雅地完成tmpdir_factory夹具,但这不是重点.
我遇到的问题是如何在所有测试运行后清理缓存的文件,
wim*_*wim 11
是否可以在所有测试中共享一个全局变量(其中包含例如缓存对象的路径列表)?
我不会走那条路.全局可变状态是最好避免的,特别是在测试中.
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
Run Code Online (Sandbox Code Playgroud)
yield之后的代码将在测试套件的末尾运行一次,无论通过或失败.
是否可以在所有测试之间共享一个全局变量(其中将包含例如缓存对象的路径列表)?
实际上有几种方法可以做到这一点,每种方法都有优点和缺点。我认为这个 SO 答案总结得很好 - /sf/answers/1595510941/ - 但例如:
def pytest_namespace():
return {'my_global_variable': 0}
def test_namespace(self):
assert pytest.my_global_variable == 0
Run Code Online (Sandbox Code Playgroud)
py.test 中是否有一种机制可以在所有测试运行后调用某些命令(无论它们是否成功)?
是的,py.test 有可用的拆卸功能:
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.
"""
Run Code Online (Sandbox Code Playgroud)