0

I have the following setup: I have a view and two possible permission groups. I want to test if my view is reachable in all possible scenarios. Meaning:

  • Not logged in
  • Logged in with wrong group
  • Logged in with correct group

My permisson control works via a Mixin:

class PermissionMixin(object):
    group_list = None

    def in_groups(self, u):
        if u.is_authenticated():
            if u.is_superuser or bool(u.groups.filter(name__in=self.group_list)):
                return True
        return False

    def dispatch(self, request, *args, **kwargs):
        if self.in_groups(request.user):
            return super(PermissionMixin, self).dispatch(request, *args, **kwargs)
        return render(request, '403.html', status=403)

My urls look like this:

url(r'^my-view/$', login_required(views.MyView.as_view()), name='my-view-view')

When I try to use RequestFactory test, I always get status 200 instead of 403 oder 302 (redirect to login):

self.factory = RequestFactory()
request = self.factory.get(reverse('my-view'))
request.user = AnonymousUser()
response = MyView.as_view()(request)
self.assertEqual(response.status_code, 302)

When I try Client(), it works but it takes a couple of seconds to process the request. When I want to test all my views I'll want to kill myself when waiting for the CI-pipeline.

Any ideas why the RequestFactory is not working corretly? Or how I can solve my problem?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Ron
  • 22,128
  • 31
  • 108
  • 206
  • Is this helpful (the part about assertRedirects): https://stackoverflow.com/questions/48166839/how-to-follow-django-redirect-using-django-pytest – Scott Skiles Aug 24 '18 at 15:07
  • I.e., you can write `self.assertRedirects(response, "/expected_redirect/url", 302, )` depending on if you expect the redirect to work or not. – Scott Skiles Aug 24 '18 at 15:08

0 Answers0