当用户名和密码是URL编码时,Flask测试不会填充request.authorization

时间:2016-10-07 20:29:54

标签: python testing flask

我试图使用以下测试:

def post_webhook(self, payload, **kwargs):
    webhook_username = 'test'
    webhook_password = 'test'

    webhook_url = 'http://{}:{}@localhost:8000/webhook_receive'
    webhook_receive = self.app.post(
        webhook_url.format(webhook_username, webhook_password),
        referrer='http://localhost:8000',
        json=payload)
    return webhook_receive.status_code

但主要问题是request.authorizationNone。虽然如果我启动服务器并使用curl -X POST <webhook_url>requests.post(<webhook_url>),则request.authorization已正确填充。

试图弄清楚如何解决此问题的主要问题。

1 个答案:

答案 0 :(得分:1)

使用snippet代码和Flask Test Client,下一个pytest代码适合我。我发送HTTP Basic Auth的方式与curl和HTTPie发送方式相同;在 Authorization 标题中,用户名和密码以 base64 编码。

import base64
from app import app

def test_secret_endpoint():
    client = app.test_client()

    # testing a route without authentication required
    rv = client.get('/')
    assert rv.status_code == 200

    # testing a secured route without credentials
    rv = client.post('/secret-page')
    assert rv.status_code == 401

    # testing a secured route with valid credentials
    value = base64.encodestring('admin:secret').replace('\n', '')

    headers = {'Authorization': 'Basic {}'.format(value)}

    rv = client.post('/secret-page', headers=headers)
    assert rv.status_code == 200
    assert 'This is secret' in rv.data

路线定义是:

@app.route('/')
def index():
    return 'Hello World :)'


@app.route('/secret-page', methods=['POST'])
@requires_auth
def secret_page():
    return 'This is secret'

发送凭据的请求标头如下所示:

POST /secret-page HTTP/1.1
Accept: */*
Authorization: Basic YWRtaW46c2VjcmV0
Connection: keep-alive
Content-Length: 0
Host: localhost:5000
...
相关问题