Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask app.config during unit testing

What is the best way handle unit tests that rely on calling code that in turn relies on the current app's configuration?

eg

code.py

from flask import current_app

def some_method():
    app = current_app._get_current_object()
    value = (app.config['APP_STATIC_VAR'])*10
    return value

test_code.py

class TestCode(unittest.TestCase):
    def test_some_method(self):
        app = create_app('app.settings.TestConfig')
        value = some_method()
        self.assertEqual(10, value)

Running the test above I get an 'RuntimeError: working outside of application context' error when the app = create_app('app.settings.TestConfig') line is executed.

Calling app = create_app during the test doesn't do the trick. What is the best way to unit test in this case where I am needing the config to be read in the the application?

like image 584
Don Smythe Avatar asked Mar 20 '16 06:03

Don Smythe


People also ask

How do I use app config in Flask?

Putting that information in a configuration variable makes it easy to change it in the future. # app.py or app/__init__.py from flask import Flask app = Flask(__name__) app. config. from_object('config') # Now we can access the configuration variables via app.

What does app config do in Flask?

Allows you to configure an application using pre-set methods. The application returned by create_app will, in order: Load default settings from a module called myapp.

What is app config [' Secret_key ']?

SECRET_KEY: Flask "secret keys" are random strings used to encrypt sensitive user data, such as passwords. Encrypting data in Flask depends on the randomness of this string, which means decrypting the same data is as simple as getting a hold of this string's value.


1 Answers

You are using accessing the app within an app context when you call some_method() to fix it replace your call with:

with app.app_context():
    value = some_method()
like image 72
Jase Rieger Avatar answered Oct 06 '22 01:10

Jase Rieger