Search code examples
pythonunit-testingflaskpython-unittest

How to test redirection In Flask with Python unittest?


I am currently trying to write some unit tests for my Flask application. In many of my view functions (such as my login), I redirect to a new page. So for example:

@user.route('/login', methods=['GET', 'POST'])
def login():
    ....
    return redirect(url_for('splash.dashboard'))

I'm trying to verify that this redirect happens in my unit tests. Right now, I have:

def test_register(self):
    rv = self.create_user('John','Smith','John.Smith@myschool.edu', 'helloworld')
    self.assertEquals(rv.status, "200 OK")
    # self.assert_redirects(rv, url_for('splash.dashboard'))

This function does make sure that the returned response is 200, but the last line is obviously not valid syntax. How can I assert this? My create_user function is simply:

def create_user(self, firstname, lastname, email, password):
        return self.app.post('/user/register', data=dict(
            firstname=firstname,
            lastname=lastname,
            email=email,
            password=password
        ), follow_redirects=True)

Solution

  • 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','John.Smith@myschool.edu', 'helloworld')
        assertRedirects(rv, url of splash.dashboard)