Django test client - sendng POST data returns 400 error

I have problem with writing tests for Django (just started with this framework). Everything works flawless in browser, but when I'm using TestCase, it seems that request method is not POST. Here's the code:

views.py:

def save(request, quiz_id):
    try:
        quiz = get_object_or_404(Quiz, pk=quiz_id)
        qset = Question.objects.filter(quiz=quiz_id)
    except IndexError:
        raise Http404
    questions = []
    if request.method == 'POST':
        f = QuizForm(request.POST, qset)
        if f.is_valid():
            do_stuff()
            return render(request, 'quiz/results.html', {'questions': questions})
    return HttpResponseBadRequest()

tests.py:

def test_results(self):
    post_data = {
        'ans10': 43,
        'ans6' : 28,
        'ans7' : 33,
        'ans8' : 36,
        'ans9' : 38,
    }
    resp = self.client.post('/1/save/', post_data)
    self.assertEqual(resp.status_code, 200)

And running test:

self.assertEqual(resp.status_code, 200)
AssertionError: 400 != 200

Form is valid, passed data is correct, in browser, like I said, everything works. I have just problem with this test, it seems like request method is not POST. Thanks for any help.

Upvotes: 0

Views: 1777

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77942

It's hard to tell given your broken indentation, but it seems your view will only return a 200 if it's a POST request and the form is valid. Could it be that your form doesn't validate ?

This being said, the recommended flow is to return a redirect to the result page on successful posts (google for "post redirect get") to avoid double submissions on page reloading.

Totally unrelated but none of the statements in you try/expect block will raise an IndexError, and if Question has a ForeignKey on Quizz you should be able to retrieve questions directly with quizz.question_set.all().

Upvotes: 1

Related Questions