Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Python Decorators?

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') 
like image 672
Jama22 Avatar asked Apr 29 '10 15:04

Jama22


People also ask

Do decorators do anything Python?

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.

How do you call a decorator in Python?

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.

What is decorator in Python with example?

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.

How do I run a Python test from the command line?

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.


Video Answer


1 Answers

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.

like image 121
nkrkv Avatar answered Sep 21 '22 12:09

nkrkv