I use this decorator in unittest modules to verify that a particularly-named object exists:
def existsin(namespace):
"""Given a namespace, this decorator asserts that an object with
the same name as the function it's wrapping (minus ) exists in that
namespace"""
def wrapper(namedunittest):
assert namedunittest.__name__.startswith('test_'), \
"The wrapped '%s' function doesn't look like a unit test" % namedunittest.__name__
@wraps(namedunittest)
def inner(self, *args, **kwargs):
self.assertTrue(hasattr(namespace, namedunittest.__name__.split('_')[1]))
return namedunittest(self, *args, **kwargs)
return inner
return wrapper
For example:
import unittest
import mymodule
class MyTests(unittest.TestCase):
@existsin(mymodule)
def test_function(self):
"""Verifies that mymodule.function exists"""
@existsin(mymodule.MyClass)
def test_method(self):
"""Verifies that the MyClass class from mymodule has an attr named 'method'"""
Hi Kirk, I like your approach. Would you mind posting the other decorator
@wraps
?Thanks,
Michael