• Now all data be ready for publish, We had made our blog alive now. Haha.

  • These days CCP GFW blocked all the IPs from US and when I switch my IP in google Cloud, the disk data cannot be restore again. I have to restart my blog totally, Now the website is still building…

Testing code that requires a Flask app or request context- Stack Overflow

Python PingBook 1 months ago (10-23) 20 0


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__)

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()


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.

Copyright from PingBook Blog, If not specified, they are original. This site uses BY-NC-SAProtocol authenticated.
For reprinting, please indicate the link of the original text:Testing code that requires a Flask app or request context- Stack Overflow
LIKE (0)
We create, We sharing! Tag every value data your sharing
Submit comments
Cancel comments
emoji picture bold strikethrough center italic check in

Hi,you need to provide your name and email adress!

  • Name (Required)
  • Email (Required)
  • Website