100

I am getting working outside of request context when trying to access session in a test. How can I set up a context when I'm testing something that requires one?

import unittest
from flask import Flask, session

app = Flask(__name__)

@app.route('/')
def hello_world():
    t = Test()
    hello = t.hello()
    return hello

class Test:
    def hello(self):
        session['h'] = 'hello'
        return session['h']

class MyUnitTest(unittest.TestCase):
    def test_unit(self):
        t = tests.Test()
        t.hello()
davidism
  • 121,510
  • 29
  • 395
  • 339
Cory
  • 14,865
  • 24
  • 57
  • 72

1 Answers1

189

If you want to make a request to your application, use the test_client.

c = app.test_client()
response = c.get('/test/url')
# test response

If you want to test code which uses an application context (current_app, g, url_for), push an app_context.

with app.app_context():
    # test your app context code

If you want test code which uses a request context (request, session), push a test_request_context.

with current_app.test_request_context():
    # test your request context code

Both app and request contexts can also be pushed manually, which is useful when using the interpreter.

>>> ctx = app.app_context()
>>> ctx.push()

Flask-Script or the new Flask cli will automatically push an app context when running the shell command.


Flask-Testing is a useful library that contains helpers for testing Flask apps.

dthor
  • 1,749
  • 1
  • 18
  • 45
tbicr
  • 24,790
  • 12
  • 81
  • 106
  • Yep, i've wrapped the functions not routed nor related with Flask that needs request data to work ;) with `app_app.test_request_context():` and did worked. – m3nda Jun 17 '16 at 12:06
  • Great summary of the different contexts (test, application, request). – Jason Strimpel May 03 '18 at 09:00
  • FYI, here is the documentation for `app.test_request_context` https://flask.palletsprojects.com/en/1.1.x/api/?highlight=test%20request%20context#flask.Flask.test_request_context. –  Aug 09 '19 at 17:40
  • 1
    Does c.get('/test/url') automatically create request and application context? – variable Nov 11 '19 at 19:53
  • How difficult is it to put this in the Flask docs? Can't believe how difficult for me to land on this answer. Thank you very much! – dz902 Nov 22 '22 at 04:06