我正在尝试使用以下测试:
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.authorization
是None
.虽然如果我启动服务器并使用 curl -X POST <webhook_url>
或 requests.post(<webhook_url>)
, 然后 request.authorization
已正确填充。
试图弄清楚如何解决这个问题的主要问题。
最佳答案
使用 snippet代码和 Flask Test Client ,下一个 pytest 代码对我有用。我发送 HTTP Basic Auth 的方式与 curl 和 HTTPie 发送它的方式相同;在 Authorization
header 中使用 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'
发送凭据的请求 header 如下所示:
POST /secret-page HTTP/1.1
Accept: */*
Authorization: Basic YWRtaW46c2VjcmV0
Connection: keep-alive
Content-Length: 0
Host: localhost:5000
...
关于python - 当用户名和密码经过 URL 编码时,Flask 测试不会填充 request.authorization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39925335/