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