I use the following decorator to cache a pure function:
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
This works very well, but I ran into a problem with unit tests, such as:
class TestFoo(unittest.TestCase):
def setUp(self):
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 it module1.method1is decorated memoize, and therefore from one test to another its return value is cached and does not change with subsequent method1.return_value = "..."assignments.
How can I clear the memoize cache? When I find out, I cleared the cache in the setUp method of the test case.
user3921265
source
share