samedi 9 novembre 2019

Test a redirect (and checking messages) in django

I have a view that redirect and I want to check for the messages.

I found other questions like this and I read I should use follow=True.

I'm a begginner so maybe I miss something but I'm not testing using client so I can't use follow (or anyway I don't know where to use it).

So I have the doubt If I'm doing the things in the right way and if so how I can test the messagges.

Here my code to test

# my view
def ImportName(request):
    if request.method == 'POST':
    # code
    else:
        messages.add_message(request, messages.ERROR,
                             _('Form non valida.'), extra_tags='import_name')
        return redirect('lists:addname')

# my test
def test_importname(self):
    self.request = RequestFactory(spec=NameForm)
    # test a not POST call
    self.request.method = 'GET'
    self.request._messages = Mock()
    resposte = ImportName(self.request)
    resposte.client = Client()
    self.assertEqual(resposte.status_code, 302)
    self.assertRedirects(resposte, reverse('lists:addname'))

Like you can see I need to definite the attributes _messages and .client so probabily there are better ways to do but I tested all my views like this (with RequestFactory()) and until I meet the message it worked fine.

Advices, opinions, solutions? Thank you

Aucun commentaire:

Enregistrer un commentaire