RuntimeError: working outside of application context

102,720

Solution 1

Flask has an Application Context, and it seems like you'll need to do something like:

def test_connection(self):
    with app.app_context():
        #test code

You can probably also shove the app.app_context() call into a test setup method as well. Hope this helps.

Solution 2

I followed the answer from @brenns10 when I ran into a similar problem when using pytest.

I followed the suggestion of putting it into test setup, this works:

import pytest
from src.app import app


@pytest.fixture
def app_context():
    with app.app_context():
        yield


def some_test(app_context):
    # <test code that needs the app context>
Share:
102,720
guri
Author by

guri

Updated on July 05, 2022

Comments

  • guri
    guri almost 2 years

    app.py

    from flask import Flask, render_template, request,jsonify,json,g
    import mysql.connector
    
    app = Flask(__name__)
    **class TestMySQL():**
      @app.before_request
      def before_request():
        try:
           g.db = mysql.connector.connect(user='root', password='root', database='mysql')
        except mysql.connector.errors.Error as err:
          resp = jsonify({'status': 500, 'error': "Error:{}".format(err)})
          resp.status_code = 500
          return resp
    @app.route('/')
    def input_info(self):
        try:     
            cursor = g.db.cursor()
            cursor.execute ('CREATE TABLE IF NOT EXISTS testmysql (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(40) NOT NULL, \
                     email VARCHAR(40) NOT NULL UNIQUE)')
            cursor.close()
    

    test.py

    from app import *
    class Test(unittest.TestCase):         
     def test_connection1(self):  
       with patch('__main__.mysql.connector.connect') as  mock_mysql_connector_connect:
       object=TestMySQL()
       object.before_request()  """Runtime error on calling this"  
    

    I am importing app into test.py for unit testing.On calling 'before_request' function into test.py ,it is throwing RuntimeError: working outside of application context same is happening on calling 'input_info()'

  • aks
    aks over 6 years
    @brenns10 can you please tell more about this? Why does this happen?
  • brenns10
    brenns10 over 6 years
    @aks The linked page probably has a better explanation than I could give. Basically, the way Flask is designed, (1) code should be able to access a global variable containing the current Flask app object, but (2) multiple applications might exist in a single process. Flask manages this by setting up some variables before you handle a request. But when you're testing, you have to set up the "application context" yourself, so that your code can find the correct global variables.
  • milosmns
    milosmns over 4 years
    I get this for using jsonify. It's really bad that a simple JSON conversion requires the app to run "in context".
  • StefanTflch
    StefanTflch over 2 years
    @milosmns: jsonify is more than a simple json conversion though. It actually builds a proper http response. You can either use json.dumps() directly if you want a simple json conversion. Otherwise I bet even flask.json.dumps will want the context.
  • milosmns
    milosmns over 2 years
    @Eddie Parker: I guess that's exactly what I didn't like. I was expecting the basic (or better: default, well known) functionality to run without any additional requirements (like app context)... and then maybe compose on top of that by adding extra functionality (like HTTP) via some opt-in API. Maybe it's also a communication/documentation issue. I don't know what is being used more - plain JSON conversion or JSON+HTTP, so I could be wrong in assuming that most people want just plain conversion.
  • StefanTflch
    StefanTflch over 2 years
    Yeah; I hear you. When I started with flask I figured 'jsonify' just meant that: 'make this into json'. If they renamed it to something like "make_json_response' it would fit better with what it does.