Search code examples
pythonflaskflask-testing

how to write test cases for authenticated urls in flask


I am using flask with mongoengine and Login Manager for session maintaining. I want to write test cases for authenticated views. can any one help/suggestions regarding this.


Solution

  • First off, I recommend using pytest, and the flask-pytest library which contains some great convenience features to make all of this easier.

    flask-pytest comes out of the box with a client fixture, which, per the docs, refers to Flask.test_client

    What you want to do is mimic a valid session (e.g. however you app is validating that a user is "logged in").

    Here is how to do this without any supporting libraries:

    import app
    from flask import url_for
    
    def test_authenticated_route():
        app.testing = True
        client = app.test_client()
    
        with client.session_transaction() as sess:
            # here you can assign whatever you need to
            # emulate a "logged in" user...
            sess["user"] = {"email": "test_user@example.com"}
    
        # now, you can access "authenticated" endpoints
        response = client.get(url_for(".protected_route"))
        assert response.status_code == 200
    

    This is also discussed in the Flask docs.