gpt4 book ai didi

python - Flask login_user 不适用于 pytest

转载 作者:太空狗 更新时间:2023-10-30 01:01:19 24 4
gpt4 key购买 nike

我是 Pytest 的新手。我想测试需要登录的 View (用 @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 重定向到登录页面。为什么会发生这种情况,正确的做法是什么?

最佳答案

这对我有用(基于 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

关于python - Flask login_user 不适用于 pytest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27340913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com