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')
A decorator in Python is a function that takes another function as its argument, and returns yet another function . Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code.
The call() decorator is used in place of the helper functions. In python, or in any other languages, we use helper functions for three major motives: To identify the purpose of the method. The helper function is removed as soon as its job is completed.
A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
You can invoke testing through the Python interpreter from the command line: python -m pytest [...] This is almost equivalent to invoking the command line script pytest [...] directly, except that calling via python will also add the current directory to sys.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With