在 pytest 单元测试中,可通过访问 `joblib` 缓存函数的 `.func` 属性获取未装饰的原始函数,从而跳过缓存、确保每次执行真实逻辑,避免测试受缓存状态干扰。
当使用 joblib.M

例如,针对如下带缓存的函数:
from joblib import Memory
memory = Memory(location="cache")
@memory.cache
def func(a):
print("Executing real computation...") # 可用于验证是否真正执行
return a ** 2在测试中直接调用 func.func 即可绕过缓存,强制执行原始逻辑:
def test_func():
assert func.func(2) == 4 # ✅ 执行真实函数,不查缓存
assert func.func(-3) == 9 # ✅ 每次调用均为新鲜计算⚠️ 注意事项:
综上,利用 .func 属性是测试 joblib 缓存函数最轻量、最可靠的方式——无需外部依赖、无副作用、语义清晰,推荐作为标准实践。