Testing Python Decorators? Testing Python Decorators? django django

Testing Python Decorators?


Simply:

from nose.tools import assert_equalfrom mock import Mockclass 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.


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.


Example for Django's UnitTest

class TestCaseExample(TestCase):    def test_decorator(self):        request = HttpRequest()        # Set the required properties of your request        function = lambda x: x        decorator = login_required(function)        response = decorator(request)        self.assertRedirects(response)

In general, the approach I've utilized is the following:

  1. Set up your request.
  2. Create a dummy function to allow the decorator magic to happen (lambda). This is where you can control the number of arguments that will eventually be passed into the decorator.
  3. Conduct an assertion based on your decorator's response.