Skip to content

Instantly share code, notes, and snippets.

@kstrauser
Created October 20, 2011 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kstrauser/1300151 to your computer and use it in GitHub Desktop.
Save kstrauser/1300151 to your computer and use it in GitHub Desktop.
Python unittest for a named object's existence

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'"""
@mjkrause
Copy link

Hi Kirk, I like your approach. Would you mind posting the other decorator @wraps?
Thanks,
Michael

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment