簡體   English   中英

我該如何對這款Flask應用進行單元測試?

[英]How can I unit test this Flask app?

我有一個使用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()

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'

我制作了一個測試我的Graffiti應用程序的測試套件,只需調用該方法並將URL段作為方法參數傳遞。 即:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM