Home > Mobile >  Python/Django Test Framework: Response code was 200 (expected 200)
Python/Django Test Framework: Response code was 200 (expected 200)

Time:02-24

So I am using Django's test framework, and in this case im testing update_password_view that I ve created on top of the built-in PasswordChangeForm.

Could someone please help me with the error from below?

After I run tests I get the following error:

AssertionError: [] is not true : Response didn't redirect as expected: Response code was 200(expected 200)

Here is the code:

#views.py
class UpdatePassword(PasswordChangeView):
    form_class = PasswordChangeForm
    success_url = reverse_lazy('posts:home')
    template_name = 'accounts/password.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        # get the number of unseen messages
        context['inbox_count'] = Message.objects.filter(
        ~Q(sender=self.request.user), Q(seen=False), 
        (Q(chat__user1=self.request.user) |\
        Q(chat__user2=self.request.user))).count()
        return context

#tests.py
def test_update_password_view(self):
        credentials = {
            'old_password': '123secret', 
            'password1': '321secret', 
            'password2': '321secret',
        }
        response = self.client.post('http://127.0.0.1:8000/users/change-password/', 
                    credentials, follow=True)
        self.assertRedirects(response, '/posts/', status_code=200, 
        target_status_code=200)

CodePudding user response:

status_code inside assertRedirects has to be redirect status code, which should be 3XX. In your occasion it has to be 302. See more at docs.

For the proper behaviour you should replace this:

self.assertRedirects(response, '/posts/', status_code=200,  target_status_code=200)

With this:

self.assertRedirects(response, '/posts/', status_code=302, target_status_code=200)

By the way, it's similar to this:

self.assertRedirects(response, '/posts/')

CodePudding user response:

This is not tested, but perhaps the issue is that it is not redirecting because the user is not created, or logged in with the old password. Try creating a user, logging them in, then running the test.

#tests.py

def test_update_password_view(self):

        credentials = {
            'old_password': '123secret', 
            'password1': '321secret', 
            'password2': '321secret',
        }

        # Create and login the user
        self.client.user = User.objects.create(username="testuser", password="123secret")
        c = Client()
        logged_in = c.login(username='testuser', password='123secret')

        response = self.client.post('http://127.0.0.1:8000/users/change-password/', 
                    credentials, follow=True)
        self.assertRedirects(response, '/posts/', status_code=302, target_status_code=200)
  • Related