Flask login_user不适用于pytest

问题描述 投票:5回答:2

我是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

client为:

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

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

python flask pytest flask-login
2个回答
3
投票

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


0
投票

这对我有用(基于this comment:]

def test_with_authenticated_user(app):
    @app.login_manager.request_loader
    def load_user_from_request(request):
        return User.query.first()
    # now you can call client.post or similar methods
© www.soinside.com 2019 - 2024. All rights reserved.