编程语言
首页 > 编程语言> > python – Flask login_user不能与pytest一起使用

python – Flask login_user不能与pytest一起使用

作者:互联网

我是Pytest的新手.我想测试我需要登录的视图(用@login_required修饰).
我有以下测试功能:

def test_add_new_post(self, client, user):
    login_user(user)
    assert current_user == user
    data = {
        'title': 'This is test post',
        'body': 'This is test body'
    }
    client.post(url_for('posts.add_new'), data=data)
    assert Post.query.count() == 1

客户在哪里:

@pytest.fixture(scope='session')
def client(request, app):
    return app.test_client()

assert current_user == user返回True,但client.post返回登录页面,因为login_required重定向到登录页面.为什么会发生这种情况?这样做的正确方法是什么?

解决方法:

也许不是最简化的方法,但是:“在单元测试时全局关闭身份验证可能很方便.要启用此功能,如果应用程序配置变量LOGIN_DISABLED或TESTING中的任何一个设置为True,则此装饰器将被忽略.”通过https://pythonhosted.org/Flask-Security/api.html

标签:python,flask,pytest,flask-login
来源: https://codeday.me/bug/20190703/1362246.html