Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing code that requires a Flask app or request context

Tags:

python

flask

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() 
like image 536
Cory Avatar asked Jun 29 '13 00:06

Cory


People also ask

What is request context in Flask?

The request context keeps track of the request-level data during a request. Rather than passing the request object to each function that runs during a request, the request and session proxies are accessed instead.

How do you test a Flask application?

If an application has automated tests, you can safely make changes and instantly know if anything breaks. Flask provides a way to test your application by exposing the Werkzeug test Client and handling the context locals for you.


1 Answers

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.

like image 54
tbicr Avatar answered Sep 30 '22 20:09

tbicr