Search code examples
pythonpython-3.xdjangodjango-rest-frameworkpython-unittest

APIClient headers for testing


I'm working with django rest_framework and consuming an API that brings a header value to validate the sender. I have the problem when I use APIClient to test the webhook that I made.

@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

The problem is when I tried to get the X-Extserv-Signature from headers. I tried with:

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

this way only works when I receive a request from postman.. but the below form works when I do the request from APIClient and cannot get the value using the same above code.

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

You know how I can set the X-Extserv-Signature key value to headers in APIClient?


Solution

  • From the docs:

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

    request.headers will only contain headers that are HTTP-prefixed, so:

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