gustavgans February 2016

how to test a django decorator?

I have a decorator where I can verify if the user has any permission. The code is working for me but I want to write a test for it. How can I test the any_permission_required function?

from django.contrib.auth.decorators import user_passes_test


def any_permission_required(*perms):
    return user_passes_test(lambda u: any(u.has_perm(perm) for perm in perms))


@any_permission_required('app.ticket_admin', 'app.ticket_read')
def ticket_list(request):
...

Answers


gustavgans February 2016

Finally with help of Alasdair and the Django test code I found a solution.

class TestFoo(TestCase):

    def setUp(self):
        self.user = models.User.objects.create(username='foo', password='bar')
        self.factory = RequestFactory()

    def test_any_permissions_pass(self):
        perms = Permission.objects.filter(codename__in=('ticket_admin', 'ticket_read'))
        self.user.user_permissions.add(*perms)
        @any_permission_required('app.ticket_admin', 'app.ticket_read')
        def a_view(request):
            return HttpResponse()
        request = self.factory.get('/foo')
        request.user = self.user
        resp = a_view(request)
        self.assertEqual(resp.status_code, 200)

Post Status

Asked in February 2016
Viewed 2,471 times
Voted 14
Answered 1 times

Search




Leave an answer