Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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):
...
like image 660
gustavgans Avatar asked Feb 08 '16 14:02

gustavgans


1 Answers

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

from django.test import RequestFactory

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)
like image 154
gustavgans Avatar answered Oct 01 '22 00:10

gustavgans