How to check Python function decorators?

I am trying to write unit tests to ensure the correctness of the various decorators I wrote. Here is the beginning of the code I'm trying to write:

import unittest from memoizer import Memoizer from strategies.mru import MRU @Memoizer(strategy=MRU(maxsize=10)) def fib(x): if x < 2: return 1 else: return fib(x-1) + fib(x-2) class TestMemoizer(unittest.TestCase): def test_simple(self): self.assertEqual(fib(0), 1) self.assertEqual(fib(1), 1) self.assertEqual(fib(10), 89) if __name__ == '__main__': unittest.main() 

Although this works decently for the MRU strategy described above, I plan to write additional strategies, in which case I will need to decorate the fib function differently. (Recall that since fib calls fib, setting fib2 = memoize (fib) does not remember intermediate values, so this will not work.) What is the correct way to test other decorators?

+7
source share
2 answers

Take a look at the tests in the standard library for examples: http://hg.python.org/cpython/file/3.2/Lib/test/test_functools.py#l553

I usually add some function wrapping tools so that I can control calls.

Instead of memoizing the test function at the module level, I create a memoized function inside the test, so a new one is created for each test and for each variant of the decorator.

+8
source

How about pretty complicated

 def mkfib(strategy): @Memoizer(strategy=strategy) def fib(x): if x < 2: return 1 else: return fib(x-1) + fib(x-2) return fib 

So you could do

 fib1 = mkfib(MRU(maxsize=10)) self.assertEqual(fib1(0), 1) self.assertEqual(fib1(1), 1) fib2 = mkfib(MRU(maxsize=10)) # produces another cache self.assertEqual(fib2(0), 1) self.assertEqual(fib2(1), 1) 
+1
source

All Articles