您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:22:59 python 字数 3584 阅读 569 来源 www.jb51.cc/python

我有一个使用Flask-Restless来提供API的Flask应用程序. 我刚刚写了一些检查的身份验证 >如果消费者主机被识别 >请求包括哈希(通过加密POST的请求内容和GET的URL以及秘密API密钥计算)和 >哈希值有效 我希望能够为此编写一些单元测试,但我不确定如何因为我的函数使用请求对象.我应该嘲笑请求对象吗? 我会喜欢这方面的建议. 配置 API_CONSUMERS = [{'nam

概述

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

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

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

我会喜欢这方面的建议.

配置

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

总结

以上是编程之家为你收集整理的python – 如何对Flask应用程序进行单元测试?全部内容,希望文章能够帮你解决python – 如何对Flask应用程序进行单元测试?所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶