pythonmockingpytestjoblib

Mocking joblib cache using pytest


I want to test a function that uses joblib's caching functionality.

I am wondering how to skip the cache and call the actual function when performing a unit test using pytest? Is it suitable to mock something like joblib.Memory?

Let's say I have the following function:

from joblib import Memory

memory = Memory(location="cache")

@memory.cache
def func(a):
    return a**2

def test_func():
   assert func(2) == 4

How am I supposed to mock the caching functionality and force func to be executed everytime I call it from within the test function?


Solution

  • Functions cached by joblib.Memory have a .func attribute that provides access to the underlying function. See the documentation here. So you could write your test as follows:

    from joblib import Memory
    
    memory = Memory(location="cache")
    
    @memory.cache
    def func(a):
        return a**2
    
    def test_func():
       assert func.func(2) == 4