Test for custom ModelAdmin function with GET parameters

204 Views Asked by At

I'm trying to write a test for the following modelAdmin function:

    def response_add(self, request, obj, post_url_continue=None):
        """ Redirects to the public profile details page after creation if return=true """
        if request.GET.get('return'):
            return redirect(reverse('public_profile_details', kwargs={'id': obj.id}))
        else:
            return redirect('/admin/public/publicprofile/')

The purpose of this is when staff access the admin panel from the webpage via an "Edit" link (rather than from the admin panel directly), I want to return them to that page once the object is saved. I do this by attaching ?return=True to the admin link.

However, I'm having trouble writing a test to cover this.

This is the closest I've gotten:

    def test_admin_functions(self):
        self.login_privileged_user()
        self.GET = {'return': True}
        public_profile_model_admin = admin.PublicProfileAdmin(model=models.PublicProfile, admin_site=AdminSite())
        response = self.client.get('/admin/public/publicprofile/1/change/?return=True')
        public_profile_model_admin.response_add(self, response, models.PublicProfile.objects.get(id=1))

However, this returns the following error:

AttributeError: 'TemplateResponse' object has no attribute 'id'

I can manipulate it slightly (changing from self.client.get to self.client.post) and get various other errors such as HttpResponse error, HttpResponseRedirect error, etc. But all of them have the same error of "object has no attribute 'id'".

I know I could use Selenium to do this, but I'm trying to avoid that for my smaller tests as much as possible.

1

There are 1 best solutions below

0
On

Nevermind, figured it out using the following:

    def test_admin_functions(self):
        """ Test redirects after save/delete """
        self.login_privileged_user()
        public_profile_model_admin = admin.PublicProfileAdmin(model=models.PublicProfile, admin_site=AdminSite())
        response = self.client.get('/admin/public/publicprofile/1/change/?return=True')
        admin_response = public_profile_model_admin.response_add(request=response.wsgi_request,
                                                   obj=models.PublicProfile.objects.get(id=1))
        self.assertEquals(admin_response.status_code, 302)

The difference was in accessing the .wsgi_request of the response