python – 如何对Flask应用程序进行单元测试?

前端之家收集整理的这篇文章主要介绍了python – 如何对Flask应用程序进行单元测试?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个使用Flask-Restless来提供API的Flask应用程序.

我刚刚写了一些检查的身份验证

>如果消费者主机被识别
>请求包括哈希(通过加密POST的请求内容和GET的URL以及秘密API密钥计算)和
>哈希值有效

我希望能够为此编写一些单元测试,但我不确定如何因为我的函数使用请求对象.我应该嘲笑请求对象吗?

我会喜欢这方面的建议.

配置

  1. API_CONSUMERS = [{'name': 'localhost','host': '12.0.0.1:5000','api_key': 'Ahth2ea5Ohngoop5'},{'name': 'localhost2','host': '127.0.0.1:5001','api_key': 'Ahth2ea5Ohngoop6'}]

验证方法

  1. import hashlib
  2. from flask import request
  3.  
  4.  
  5. def is_authenticated(app):
  6. """
  7. Checks that the consumers host is valid,the request has a hash and the
  8. hash is the same when we excrypt the data with that hosts api key
  9.  
  10. Arguments:
  11. app -- instance of the application
  12. """
  13. consumers = app.config.get('API_CONSUMERS')
  14. host = request.host
  15.  
  16. try:
  17. api_key = next(d['api_key'] for d in consumers if d['host'] == host)
  18. except StopIteration:
  19. app.logger.info('Authentication Failed: Unknown Host (' + host + ')')
  20. return False
  21.  
  22. if not request.headers.get('hash'):
  23. app.logger.info('Authentication Failed: Missing Hash (' + host + ')')
  24. return False
  25.  
  26. if request.method == 'GET':
  27. hash = calculate_hash_from_url(api_key)
  28. elif request.method == 'POST':
  29. hash = calculate_hash_from_content(api_key)
  30.  
  31. if hash != request.headers.get('hash'):
  32. app.logger.info('Authentication Failed: Hash Mismatch (' + host + ')')
  33. return False
  34. return True
  35.  
  36.  
  37. def calculate_hash_from_url(api_key):
  38. """
  39. Calculates the hash using the url and that hosts api key
  40.  
  41. Arguments:
  42. api_key -- api key for this host
  43. """
  44. data_to_hash = request.base_url + '?' + request.query_string
  45. data_to_hash += api_key
  46. return hashlib.sha1(request_uri).hexdigest()
  47.  
  48.  
  49. def calculate_hash_from_content(api_key):
  50. """
  51. Calculates the hash using the request data and that hosts api key
  52.  
  53. Arguments:
  54. api_key -- api key for this host
  55. """
  56. data_to_hash = request.data
  57. data_to_hash += api_key
  58. return hashlib.sha1(data_to_hash).hexdigest()

解决方法

test_request_object()做了伎俩,谢谢猴子.
  1. from flask import request
  2.  
  3. with app.test_request_context('/hello',method='POST'):
  4. # now you can do something with the request until the
  5. # end of the with block,such as basic assertions:
  6. assert request.path == '/hello'
  7. assert request.method == 'POST'

猜你在找的Python相关文章