我是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
重定向到登录页面。为什么会发生这种情况,正确的方法是什么?
也许不是最简化的方法,但是:“在单元测试时全局关闭身份验证会很方便。要启用此功能,如果应用程序配置变量LOGIN_DISABLED或TESTING中的任何一个设置为True,则将忽略此装饰器。 “通过https://pythonhosted.org/Flask-Security/api.html
这对我有用(基于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