Reputation: 12161
I'm just put HTTP authentication for my Flask application and my test is broken. How do I mock request.authentication
to make the test pass again?
Here's my code.
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')
Upvotes: 1
Views: 2759
Reputation: 1947
Referring to How do I mock dependencies of the views module of my Flask application in flask-testing?, you can mock it via the import chain.
Assuming server_tests
imports application
imports server
, you probably want something like:
server_tests.py
def setUp(self):
application.server.request.authorization = MagicMock(return_value=True)
Upvotes: 2