21

I'm using flask to do register and login:

from flask.ext.security.views import register, login

class Register(Resource):
    def post(self):
        return register()

class Login(Resource):
    def post(self):
        return login()

api.add_resource(Login, '/login')
api.add_resource(Register, '/register')

then I use py.test to test the class:

class TestAPI:
    def test_survey(self, app):
        client = app.test_client()
        data = {'email': 'test@test', 'password': 'password'}
        rv = client.post('/2014-10-17/register',
                          data=json.dumps(data))
        ...

when I ran the test, the error occurred as follow:

AssertionError: Popped wrong request context.  (<RequestContext 'http://localhost/2014-10-17/register' [POST] of panel.app> instead of <RequestContext 'http://localhost/' [GET] of panel.app>)

Do you know why? And when testing login, there was no such error

Spirit
  • 553
  • 1
  • 6
  • 16

4 Answers4

26

It's a known flask problem. You receive two exceptions instead one. Simply add PRESERVE_CONTEXT_ON_EXCEPTION = False to your test config.

Jimilian
  • 3,441
  • 26
  • 33
5

It seems that you have to wrap you testing calls with something like this:

with self.app.test_client() as client:
    data = {'email': 'test@test', 'password': 'password'}
    rv = client.post('/2014-10-17/register', data=json.dumps(data))
    ...
opyate
  • 5,039
  • 1
  • 34
  • 60
mrquintopolous
  • 147
  • 2
  • 9
2

When your testA has a syntax error or other exceptions, the tearDown() method which does the context pop job will not be reached, so the testA's context wasn't popped correctly. Then your next test we call it testB will pop the testA's context. So, that's why you got the error AssertionError: Popped wrong request context..

Check the error in your test code, fix it. Then the AssertionError will be gone automatically.

Grey Li
  • 7,945
  • 1
  • 38
  • 53
0

In my case, I've went to the flask.ctx.AppContext.__exit__ method and discovered that there was an invisible, unhandled exception in the exc_value argument which has somehow broken the whole thing to pieces.

kolypto
  • 23,092
  • 13
  • 75
  • 76
  • I was having the same problem with the exception being thrown on exit from the `with app.app_context():` clause. I found the problem went away when I set FLASK_DEBUG=0. – Lucian Thorr Mar 31 '20 at 19:38