views:

126

answers:

2

I'm writing some unit tests for a Django project, and I was wondering if its possible (or necessary?) to test some of the decorators that I wrote for it.

Here is an example of a decorator that I wrote:

class login_required(object):

    def __init__(self, f):
        self.f = f

    def __call__(self, *args):
        request = args[0]
        if request.user and request.user.is_authenticated():
            return self.f(*args)
        return redirect('/login')
+1  A: 

A decorator like this might be tested simply thanks to duck-typing. Just supply a mock object to the call function, that seems to hold and act as a request, and see if you get the expected behaviour.

When it is necessary to use unit tests is quite individual i'd say. The example you give contain such basic code that one might say that it isn't necessary. But then again, the cost of testing a class like this is equally low.

daramarak
+2  A: 

Simply:

from nose.tools import assert_equal
from mock import Mock

class TestLoginRequired(object):
    def test_no_user(self):
        func = Mock()
        decorated_func = login_required(func)
        request = prepare_request_without_user()
        response = decorated_func(request)
        assert not func.called
        # assert response is redirect

    def test_bad_user(self):
        func = Mock()
        decorated_func = login_required(func)
        request = prepare_request_with_non_authenticated_user()
        response = decorated_func(request)
        assert not func.called
        # assert response is redirect

    def test_ok(self):
        func = Mock(return_value='my response')
        decorated_func = login_required(func)
        request = prepare_request_with_ok_user()
        response = decorated_func(request)
        func.assert_called_with(request)
        assert_equal(response, 'my response')

The mock library helps here.

nailxx