如何在Flask中对HTTPS请求进行单元测试? [英] How do I unit-test HTTPS requests in Flask?

查看:321
本文介绍了如何在Flask中对HTTPS请求进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我创建的Flask应用程序中的某些页面,我有一个HTTPS重定向系统,如下所示。

  def requires_https (f,code = 302):
默认为临时重定向(301是永久的)
@wraps(f)
def装饰(* args,** kwargs ):
passthrough_conditions = [
request.is_secure,
request.headers.get('X-Forwarded-Proto','http')=='https',
'本地主机'在request.url
]

如果没有任何(passthrough_conditions):
如果request.url.startswith('http://'):
url = request.url.replace('http://','https://')
r =重定向(url,code = code)
返回r
返回装饰

如果您不请求HTTPS版本的页面,它会将您重定向到该页面。我想写这个服务的单元测试。我写了一个确保你被重定向到HTTPS版本(基本上检查一个301或301)。我想测试,如果你要求https版本的页面,并已经在https上,它不会重定向你(基本上,为200)。如何让Flask在单元测试中发送一个https请求?

解决方案

您可以强制Flask测试的get以这样的方式使用HTTPS:


$ b

  response = self.app.get(' / login',base_url ='https:// localhost')
assert(response.status_code == 200)

底层Werkzeug使用base_url来添加url模式(HTTP / HTTPS)。对于像这样的本地测试调用,不使用主机名,可以省略。 您可以在这里查看base_url的代码文档中的基本信息。

For certain pages in a Flask app I'm creating, I have an HTTPS redirection system as follows.

def requires_https(f, code=302):
    """defaults to temp. redirect (301 is permanent)"""
    @wraps(f)
    def decorated(*args, **kwargs):
        passthrough_conditions = [
            request.is_secure,
            request.headers.get('X-Forwarded-Proto', 'http') == 'https',
            'localhost' in request.url
        ]

        if not any(passthrough_conditions):
            if request.url.startswith('http://'):
                url = request.url.replace('http://', 'https://')
                r = redirect(url, code=code)
                return r
    return decorated

If you're not requesting the HTTPS version of the page, it redirects you to it. I want to write unit tests for this service. I have written one that makes sure that you're redirected to the HTTPS version (check for a 301 or a 301, basically). I want to test that if you are requesting the https version of the page and are already on https, it does not redirect you (basically, for a 200). How do I get Flask to send an https request in the unit test?

解决方案

You can force the Flask test's get() call to use HTTPS like this:

response = self.app.get('/login', base_url='https://localhost')
assert(response.status_code == 200)

The addition of the base_url is used by the underlying Werkzeug to set the url scheme (HTTP/HTTPS). For local test calls like these the host name is not used, and can be left out. You can see basic in code documentation for base_url here.

这篇关于如何在Flask中对HTTPS请求进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆