How do test in Django
<p>I'm trying to do my first tests on Django and I don't know do it or after reading the docs (where it explains a very easy test) I still don't know how do it.</p>

<p>I'm trying to do a test that goes to "login" url and makes the login, and after a succesfull login redirects to the authorized page.</p>

<pre><code>from unittest import TestCase

from django.test.client import Client


class Test(TestCase):
    def testLogin(self):
        client = Client()
        headers = {'X-OpenAM-Username': 'user', 'X-OpenAM-Password': 'password', 'Content-Type': 'application/json'}
        data = {}
        response = client.post('/login/', headers=headers, data=data, secure=False)
        assert(response.status_code == 200)
</code></pre>

<p>And the test success, but I don't know if it's beacuse the 200 of loading "/login/" or because the test do the login and after redirect get the 200 code.</p>

<p>How can I check on the test that after the login the url redirected it's the correct? There is a plugin or something that helps with the test? Or where I can find a good tutorial to test my views and the model?</p>

<p>Thanks and regards.</p>

<p>To properly test redirects, use the <a href="https://docs.djangoproject.com/en/1.10/topics/testing/tools/#django.test.Client.post" rel="nofollow">follow</a> parameter </p>

<blockquote>
  <p>If you set follow to True the client will follow any redirects and a
  redirect_chain attribute will be set in the response object containing
  tuples of the intermediate urls and status codes.</p>
</blockquote>

<p>Then your code is as simple as</p>

<p>from django.test import TestCase</p>

<pre><code>class Test(TestCase):
    def test_login(self):
        client = Client()
        headers = {'X-OpenAM-Username': 'user', 'X-OpenAM-Password': 'password', 'Content-Type': 'application/json'}
        data = {}
        response = client.post('/login/', headers=headers, data=data, secure=False)
        self.assertRedirects(response,'/destination/',302,200)
</code></pre>

<p>Note that it's <code>self.assertRedirects</code> rather than <code>assert</code> or <code>assertRedirects</code></p>

<p>Also note that the above test will most likely fail because you are posting an empty dictionary as the form data. Django form views do not redirect when the form is invalid and an empty form will probably be invalid here.</p>

python django django-testing