如何对该Flask应用进行单元测试? [英] How can I unit test this Flask app?
本文介绍了如何对该Flask应用进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个使用Flask-Restless来提供API的Flask应用.
I have a Flask app that is using Flask-Restless to serve an API.
我刚刚写了一些可以检查的身份验证
I have just written some authentication that checks
- 如果认可了消费者主机
- 该请求包含一个哈希(通过对POST的请求内容和GET的URL以及一个秘密API密钥进行加密来计算)和
- 哈希有效
我希望能够为此编写一些单元测试,但是由于我的函数使用了请求对象,因此我不确定如何进行测试.我应该嘲笑请求对象吗?
I want to be able to write some unit tests for this, but I'm not sure how because my functions use the request object. Should I be mocking the request object?
会喜欢一些建议.
配置
API_CONSUMERS = [{'name': 'localhost',
'host': '12.0.0.1:5000',
'api_key': 'Ahth2ea5Ohngoop5'},
{'name': 'localhost2',
'host': '127.0.0.1:5001',
'api_key': 'Ahth2ea5Ohngoop6'}]
身份验证方法
import hashlib
from flask import request
def is_authenticated(app):
"""
Checks that the consumers host is valid, the request has a hash and the
hash is the same when we excrypt the data with that hosts api key
Arguments:
app -- instance of the application
"""
consumers = app.config.get('API_CONSUMERS')
host = request.host
try:
api_key = next(d['api_key'] for d in consumers if d['host'] == host)
except StopIteration:
app.logger.info('Authentication failed: Unknown Host (' + host + ')')
return False
if not request.headers.get('hash'):
app.logger.info('Authentication failed: Missing Hash (' + host + ')')
return False
if request.method == 'GET':
hash = calculate_hash_from_url(api_key)
elif request.method == 'POST':
hash = calculate_hash_from_content(api_key)
if hash != request.headers.get('hash'):
app.logger.info('Authentication failed: Hash Mismatch (' + host + ')')
return False
return True
def calculate_hash_from_url(api_key):
"""
Calculates the hash using the url and that hosts api key
Arguments:
api_key -- api key for this host
"""
data_to_hash = request.base_url + '?' + request.query_string
data_to_hash += api_key
return hashlib.sha1(request_uri).hexdigest()
def calculate_hash_from_content(api_key):
"""
Calculates the hash using the request data and that hosts api key
Arguments:
api_key -- api key for this host
"""
data_to_hash = request.data
data_to_hash += api_key
return hashlib.sha1(data_to_hash).hexdigest()
推荐答案
test_request_object()
完成了技巧,谢谢猴子.
test_request_object()
did the trick, thanks monkey.
from flask import request
with app.test_request_context('/hello', method='POST'):
# now you can do something with the request until the
# end of the with block, such as basic assertions:
assert request.path == '/hello'
assert request.method == 'POST'
这篇关于如何对该Flask应用进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文