APIClient headers 用于测试

APIClient headers for testing

我正在使用 django rest_framework 并使用 API 带来 header 值来验证发件人。我在使用 APIClient 测试我制作的 webhook 时遇到问题。

@pytest.mark.django_db
def test_change_status_webhook_ok(webhook_client, status_changes):
    fixture_signature = (
        "51b93156c361bfce14c527ddcb27cc3791e9ea6ede23bc5a56efa3be28e6a54d"
    )

    url = reverse("webhook_v1:notification")
    response = webhook_client.post(
        url,
        json.dumps(status_changes),
        content_type="application/json",
        **{"X-Extserv-Signature": fixture_signature}
    )

    assert response.status_code == 200

问题是当我试图从 header 中获取 X-Extserv-Signature 时。 我试过:

ret = request.headers.get("X-Extserv-Signature")            

这种方式仅在我收到邮递员的请求时才有效。但是当我从 APIClient 发出请求并且无法使用上面相同的代码获取值时,下面的表格有效。

ret = request.META["X-Extserv-Signature"]

你知道我如何在 APIClient 中将 X-Extserv-Signature 键值设置为 headers 吗?

来自docs

A case insensitive, dict-like object that provides access to all HTTP-prefixed headers

request.headers 将只包含 headers 即 HTTP-prefixed,因此:

    response = webhook_client.post(
        url,
        json.dumps(status_changes),
        content_type="application/json",
        **{"HTTP_X_EXTSERV_SIGNATURE": fixture_signature} # <-- Use this
    )