django test client doesnt call POST, but GET

2019-09-20 13:33发布

问题:

I try to test view calling by POST. I use follow=True. But test client uses GET method and my POST data are not passed.

here is my view:

def aaa(request):
    n = request.method
    d = request.POST
    template = 'shop/test.html'
    return render(request, template, d)

Here is my test:

from django.utils import unittest
from django.test.client import Client

def test_add_to_cart_page(self):
    response = self.client.post('/aaa/', {'product': 11}, follow=True)
    self.assertEqual(response.status_code, 200)

When the view is called. It is not POST, but GET used and my POST params are empty of course. Can somebody say why its happened?

EDIT: I made a clean venv with fresh Django. And it works as expected(calls POST) Looks like there is something rotten in the state of Denmark.

回答1:

follow=True

means that the client follows the redirection.

response = self.client.post('/aaa/', {'product': 11}, follow=True)

means that the response contains the followed response content. There is nothing wrong with your test; it must be doing a POST.


What's weird is that your view doesn't redirect to anything so I don't understand why you use follow=True. Also I don't see why you assume that post isn't working. What's the result of your test?



回答2:

After investigation I realize that using PREPEND_WWW breaks the test client post requests.