flask create_app and setUp unittest flask create_app and setUp unittest flask flask

flask create_app and setUp unittest


I decided to explain the problem(and solution) in detail.

1) Why your way doesn't work?Because you trying to push app context using Context Manager. What does it mean? current context will be available only inside with block. You bind context and he available only in setUp, but not in tests. app will works without context when setUp() is finished. Let's look at this example:

app = Flask(__name__)class TestCase(TestCase):    def setUp(self):        with app.app_context():            # current_app is available(you will see <Flask 'app'> in terminal)            print current_app        # out of context manager - RuntimeError: Working outside of application context.        print current_app    def test_example(self):        pass

Run test. You'll be see Flask 'app' + exception. The error will disappear if you remove last print(out of with block).

2) How to fix the problem?You can bind app context without Context Manager.

class TestCase(TestCase):    def setUp(self):        ctx = app.app_context()        ctx.push()        # after this you can use current_app        print current_app    def test_example(self):        # available because we pushed context in setUp()        print current_app

Run test:

<Flask 'app'> # from setUp()<Flask 'app'> # from test_example

So, let's sum up. current_app is available ONLY 'inside' Context Manager. But you can bind context without Context Manager.

I hope that I have explained the details and answered your questions.