Search code examples
pythonpython-3.xflasknose

flask - unit testing session with nose


I am trying to test the following code with nose. The app.py file is as below:

from flask import Flask, session, redirect, url_for, request

app = Flask(__name__)

@app.route('/')
def index():
    session['key'] = 'value'
    print('>>>> session:', session)
    return redirect(url_for("game"))

The test file is below:

from nose.tools import *
from flask import session
from app import app

app.config['TESTING'] = True
web = app.test_client()

def test_index():

    with app.test_request_context('/'):
        print('>>>>test session:', session)
        assert_equal(session.get('key'), 'value')

When I run the test file, I get an assertion error None != 'value' and the print statement in the test file prints an empty session object. Moreover, the print statement in the app.py file does not print anything. Does this mean that the index function isn't running?

Why is this happening? According to the flask documentation (http://flask.pocoo.org/docs/1.0/testing/#other-testing-tricks), I should have access to the session contents through test_request_context().

Also, if I write the test_index function like this instead, the test works (and both print statements in the app.py and test files are executed):

def test_index():

    with app.test_client() as c:
        rv = c.get('/')
        print('>>>>test session:', session)
        assert_equal(session.get('key'), 'value')

What is the difference between using Flask.test_client() and Flask.test_request_context in a 'with' statement? As I understand it, the point in both is to keep the request context around for longer.


Solution

  • You're only setting up your request context. You need to actually have your app dispatch the request to have anything happen-- similar to your c.get() in your full Client.

    Give the following a try and I think you'll have better luck:

    def test_index():
    
        with app.test_request_context('/'):
            app.dispatch_request()
            print('>>>>test session:', session)
            assert_equal(session.get('key'), 'value')