jeudi 25 avril 2019

Django Test Client client.post() sends GET request in my Testcase

How can I submit a POST request with Django test Client? I just want to test the login function of my application. It's strange that I put response = self.client.post(reverse('rbac:login'), data=data) in my testcase, and I want to validate it so I print response.status_code.Actually it should return 302 coz it should turn to another page. but it return 200. This situation happens when I use "python manage.py test testmodel" to test. However, if I use "python manage.py shell" to make an InteractiveConsole and write exactly the same code, it return 302 at last.

I have nearly tried all the methods provided from stack overflow, e.g. change the url, offer the content-type when I post....but these are meaningless.

from django.test import TestCase
from django.test.utils import setup_test_environment,teardown_test_environment
from django.test import Client
from django.urls import reverse
import django
from rbac.models import RbacUser, RbacRole
from system_module.models import Redeploy
from urllib import urlencode
class CreateUser(TestCase):
    @classmethod
    def setUp(self):
        self.client = Client()

    def test_create_user(self):
        data = {"Username": "admin_xy", "Password": "aaa"}

        response = self.client.post(reverse('rbac:login'), data=data)
        print response

and it shows me 200..... However, in interactive console:

>>> response = client.post('/', data, content_type="application/x-www-form-urlencoded")
>>> print response.status_code                                                                                                                 
302

it shows the right result. I want to know how to cope with this annoying problem. Thx

I expect when I use test file to test my test case, it works fine....like show 302 code.

Aucun commentaire:

Enregistrer un commentaire