简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM