【问题标题】:How can I unit test this Flask app?如何对这个 Flask 应用程序进行单元测试?
【发布时间】:2012-12-19 18:57:31
【问题描述】:

我有一个使用 Flask-Restless 来提供 API 的 Flask 应用程序。

我刚刚写了一些验证来检查

  1. 如果消费者主机被识别
  2. 请求包含一个哈希(通过加密 POST 的请求内容和 GET 的 URL 以及 API 密钥来计算)和
  3. 哈希有效

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

希望对此有一些建议。

配置

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()

【问题讨论】:

标签: python unit-testing flask


【解决方案1】:

test_request_object() 成功了,谢谢猴子。

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'

【讨论】:

  • 您能发布更多代码吗?看看这如何适应单元测试框架的上下文会很有帮助。
【解决方案2】:

我制作了一个鼻子测试套件,通过调用该方法并将 URL 段作为方法参数传递来测试我的 Graffiti 应用程序。即:

response = self.app.do_something("/item/1234567890")
assert response.status_code == 200

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2012-03-21
    • 2011-03-25
    相关资源
    最近更新 更多