我试图使用以下测试:
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
已正确填充。
试图弄清楚如何解决此问题的主要问题。
答案 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
...