Test Redirection In Flask with Python Unittest

Flask has built-in testing hooks and a test client, which works great for functional stuff like this.

from flask import url_for, request
import yourapp

test_client = yourapp.app.test_client()
with test_client:
    response = test_client.get(url_for('whatever.url'), follow_redirects=True)
    # check that the path changed
    assert request.path == url_for('redirected.url')

For older versions of Flask/Werkzeug the request may be available on the response:

from flask import url_for
import yourapp

test_client = yourapp.app.test_client()
response = test_client.get(url_for('whatever.url'), follow_redirects=True)

# check that the path changed
assert response.request.path == url_for('redirected.url')

The docs have more information on how to do this, although FYI if you see "flaskr", that's the name of the test class and not anything in Flask, which confused me the first time I saw it.


Try Flask-Testing

there is api for assertRedirects you can use this

assertRedirects(response, location)

Checks if response is an HTTP redirect to the given location.
Parameters: 

    response – Flask response
    location – relative URL (i.e. without http://localhost)

TEST script:

def test_register(self):
    rv = self.create_user('John','Smith','[email protected]', 'helloworld')
    assertRedirects(rv, url of splash.dashboard)

One way is to not follow the redirects (either remove follow_redirects from your request, or explicitly set it to False).

Then, you can simply replace self.assertEquals(rv.status, "200 OK") with:

self.assertEqual(rv.status_code, 302)
self.assertEqual(rv.location, url_for('splash.dashboard', _external=True))

If you want to continue using follow_redirects for some reason, another (slightly brittle) way is to check for some expected dashboard string, like an HTML element ID in the response of rv.data. e.g. self.assertIn('dashboard-id', rv.data)