I use the following decorator to cache pure function returns:
def memoize(obj):
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
if args not in cache:
cache[args] = obj(*args, **kwargs)
return cache[args]
return memoizer
It works quite well, but I am running into a problem with unit tests such as this:
class TestFoo(unittest.TestCase):
def setUp(self):
# clear the cache here
pass
@patch('module1.method1')
def test_method1_1(self, method1):
method1.return_value = ""
d = module1.method2()
self.assertTrue(len(d) == 0)
@patch('module1.method1')
def test_method1_2(self, method1):
method1.return_value = "TEST1234"
d = module1.method2()
self.assertTrue(len(d) == 2)
My problem is that module1.method1
is decorated with memoize
, and so from one test to the other, its return value is cached and is not changed with subsequent method1.return_value = "..."
assignments.
How can the memoize cache be cleared? When I figure this out I would clear the cache in the setUp method of the test case.
Aucun commentaire:
Enregistrer un commentaire