Skipping decorators in unit tests
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Oct 10 22:55:33 EDT 2013
On Fri, 11 Oct 2013 09:12:38 +1100, Cameron Simpson wrote:
> On 10Oct2013 07:00, Gilles Lenfant <gilles.lenfant at gmail.com> wrote:
>> (explaining the title) : my app has functions and methods (and maybe
>> classes in the future) that are decorated by decorators provided by the
>> standard library or 3rd party packages.
>>
>> But I need to test "undecorated" functions and methods in my unit
>> tests, preferably without adding "special stuffs" in my target tested
>> modules.
>>
>> Can someone point out good practices or dedicated tools that "remove
>> temporarily" the decorations. I pasted a small example of what I heed
>> at http://pastebin.com/20CmHQ7Y
>
> Speaking for myself, I would be include to recast this code:
>
> @absolutize
> def addition(a, b):
> return a + b
>
> into:
>
> def _addition(a, b):
> return a + b
>
> addition = absolutize(_addition)
>
> Then you can unit test both _addition() and addition().
*shudders*
Ew ew ew ew.
I would much rather do something like this:
def undecorate(f):
"""Return the undecorated inner function from function f."""
return f.func_closure[0].cell_contents
def decorate(func):
def inner(arg):
return func(arg) + 1
return inner
@decorate
def f(x):
return 2*x
And in use:
py> f(100)
201
py> undecorate(f)(100)
200
--
Steven
More information about the Python-list
mailing list