title: RuntimeError: working outside of request context Flask Session
body: <p>I am getting <strong>RuntimeError: working outside of request context</strong> error while running a test in Flask. I've tried multiple suggestions from other threads, but none has worked for me.</p>
  <p>Part of my views.py:</p>
  <pre><code>    @user_app.route('/login', methods =('GET', 'POST'))
      def login():
          form = LoginForm()
          error = None
          if form.validate_on_submit():
              user = User.objects.filter(username=form.username.data).first()
              if user:
                  if bc.hashpw(form.password.data, user.password) == user.password:
                      session['username']=form.username.data
                      return 'User Logged In'
                  else:
                      user = None
              if not user:
                  error = 'Incorrect credentials'
  
          return render_template('user/login.html',form=form,error=error)
  </code></pre>
  <p>Relevant part of my tests.py:</p>
  <pre><code>    from application import create_app as create_app_base
  
      def create_app(self):
          self.db_name = 'flaskbook_test'
          return create_app_base(
              MONGODB_SETTINGS={'DB':self.db_name},
              TESTING=True,
              WTF_CSRF_ENABLED=False,
              SECRET_KEY='SecretKey'
          )
  
      def setUp(self):
          self.app_factory = self.create_app()
          self.app = self.app_factory.test_client()
          #self.app.application.app_context().push() &lt;-- this did not help
  
      def tearDown(self):
          db = _get_db()
          db.client.drop_database(db)
  
      def test_login_user(self):
          #create user
          self.app.post('/register', data=self.user_dict())
          #login user
          rv = self.app.post('/login',data=dict(
              username='username',
              password='password'
          ))
          #check session is set
          with self.app as c:
              rv = c.get('/')
          assert session.get('username') == self.user_dict()['username']
  </code></pre>
  <p>I have already tried adding app_context and <code>self.app.application.app_context().push()</code> as mentioned above:</p>
  <pre><code>    with self.app.application.app_context():
          assert session.get('username') == self.user_dict()['username']
  </code></pre>
  <p>But it didn't work. <strong>Whenever I call <code>session['username']</code> I get RuntimeError: working outside of request context.</strong></p>
  <p>My requirements.txt: Flask0.10.1 Flask-Script 2.0.5 flask-mongoengine 0.7.4</p>
  <p>Please help.</p>