如何测试django装饰器?

时间:2016-02-08 14:04:35

标签: django python-3.x testing

我有一个装饰器,我可以验证用户是否拥有任何权限。代码对我有用,但我想为它编写一个测试。 如何测试 any_permission_required 函数?

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):
...

1 个答案:

答案 0 :(得分:2)

最后在Alasdair和Django测试代码的帮助下,我找到了解决方案。

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)