title: flask - unit testing session with nose
body: <p>I am trying to test the following code with nose. The app.py file is as below:</p>
  
  <pre><code>from flask import Flask, session, redirect, url_for, request
  
  app = Flask(__name__)
  
  @app.route('/')
  def index():
      session['key'] = 'value'
      print('&gt;&gt;&gt;&gt; session:', session)
      return redirect(url_for("game"))
  </code></pre>
  
  <p>The test file is below:</p>
  
  <pre><code>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('&gt;&gt;&gt;&gt;test session:', session)
          assert_equal(session.get('key'), 'value')
  </code></pre>
  
  <p>When I run the test file, I get an assertion error <code>None != 'value'</code>
  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?</p>
  
  <p>Why is this happening? According to the flask documentation (<a href="http://flask.pocoo.org/docs/1.0/testing/#other-testing-tricks" rel="nofollow noreferrer">http://flask.pocoo.org/docs/1.0/testing/#other-testing-tricks</a>),
  I should have access to the session contents through test_request_context().</p>
  
  <p>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):</p>
  
  <pre><code>def test_index():
  
      with app.test_client() as c:
          rv = c.get('/')
          print('&gt;&gt;&gt;&gt;test session:', session)
          assert_equal(session.get('key'), 'value')
  </code></pre>
  
  <p>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.</p>