py.test to test flask register, AssertionError: Popped wrong request context

守給你的承諾、 提交于 2019-11-29 16:58:29

问题


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


回答1:


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




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/26647032/py-test-to-test-flask-register-assertionerror-popped-wrong-request-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!