如何在 Flask 中模拟 HTTP 身份验证进行测试?
How to mock HTTP authentication in Flask for testing?
我刚刚为我的 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)
server.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')
参考,您可以通过导入链模拟它。
假设 server_tests
导入 application
导入 server
,您可能需要这样的东西:
server_tests.py
def setUp(self):
application.server.request.authorization = MagicMock(return_value=True)
我刚刚为我的 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)
server.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')
参考
假设 server_tests
导入 application
导入 server
,您可能需要这样的东西:
server_tests.py
def setUp(self):
application.server.request.authorization = MagicMock(return_value=True)