Flask login_user不适用于pytest

Acu*_*ute 5 python pytest flask flask-login

我是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
Run Code Online (Sandbox Code Playgroud)

哪里client是:

@pytest.fixture(scope='session')
def client(request, app):
    return app.test_client()
Run Code Online (Sandbox Code Playgroud)

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

dus*_*san 6

这对我有用(基于此评论):

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
Run Code Online (Sandbox Code Playgroud)


bro*_*bas 4

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