gpt4 book ai didi

python - 如何在 Flask 中模拟 HTTP 身份验证进行测试?

转载 作者:行者123 更新时间:2023-12-01 04:39:46 25 4
gpt4 key购买 nike

我刚刚为我的 Flask 应用程序设置了 HTTP 身份验证,但我的测试失败了。如何模拟 request.authentication 以使测试再次通过?

这是我的代码。

server_tests.py

def test_index(self):
res = self.app.get('/')

self.assertTrue('<form' in res.data)
self.assertTrue('action="/upload"' in res.data)
self.assertEquals(200, res.status_code)

服务器.py

def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'fusiontv' and password == 'fusiontv'

def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated

@app.route("/")
@requires_auth
def index():
return render_template('index.html')

最佳答案

引用How do I mock dependencies of the views module of my Flask application in flask-testing? ,您可以通过导入链来模拟它。

假设server_tests导入application导入server,你可能需要类似的东西:

server_tests.py

def setUp(self):
application.server.request.authorization = MagicMock(return_value=True)

关于python - 如何在 Flask 中模拟 HTTP 身份验证进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30985229/

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