Skip to content
Myr

test_headers.py

This file

Path

tests/client/test_headers.py

178 lines · 5.4 KiB · Python

Last changed by

Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84

History of this file

Take it

1#!/usr/bin/env python323import json45import pytest67from httpx import AsyncClient, Headers, Request, Response, __version__8from httpx.config import CertTypes, TimeoutTypes, VerifyTypes9from httpx.dispatch.base import Dispatcher101112class MockDispatch(Dispatcher):13    async def send(14        self,15        request: Request,16        verify: VerifyTypes = None,17        cert: CertTypes = None,18        timeout: TimeoutTypes = None,19    ) -> Response:20        if request.url.path.startswith("/echo_headers"):21            request_headers = dict(request.headers.items())22            body = json.dumps({"headers": request_headers}).encode()23            return Response(200, content=body, request=request)242526@pytest.mark.asyncio27async def test_client_header():28    """29    Set a header in the Client.30    """31    url = "http://example.org/echo_headers"32    headers = {"Example-Header": "example-value"}3334    client = AsyncClient(dispatch=MockDispatch(), headers=headers)35    response = await client.get(url)3637    assert response.status_code == 20038    assert response.json() == {39        "headers": {40            "accept": "*/*",41            "accept-encoding": "gzip, deflate, br",42            "connection": "keep-alive",43            "example-header": "example-value",44            "host": "example.org",45            "user-agent": f"python-httpx/{__version__}",46        }47    }484950@pytest.mark.asyncio51async def test_header_merge():52    url = "http://example.org/echo_headers"53    client_headers = {"User-Agent": "python-myclient/0.2.1"}54    request_headers = {"X-Auth-Token": "FooBarBazToken"}55    client = AsyncClient(dispatch=MockDispatch(), headers=client_headers)56    response = await client.get(url, headers=request_headers)5758    assert response.status_code == 20059    assert response.json() == {60        "headers": {61            "accept": "*/*",62            "accept-encoding": "gzip, deflate, br",63            "connection": "keep-alive",64            "host": "example.org",65            "user-agent": "python-myclient/0.2.1",66            "x-auth-token": "FooBarBazToken",67        }68    }697071@pytest.mark.asyncio72async def test_header_merge_conflicting_headers():73    url = "http://example.org/echo_headers"74    client_headers = {"X-Auth-Token": "FooBar"}75    request_headers = {"X-Auth-Token": "BazToken"}76    client = AsyncClient(dispatch=MockDispatch(), headers=client_headers)77    response = await client.get(url, headers=request_headers)7879    assert response.status_code == 20080    assert response.json() == {81        "headers": {82            "accept": "*/*",83            "accept-encoding": "gzip, deflate, br",84            "connection": "keep-alive",85            "host": "example.org",86            "user-agent": f"python-httpx/{__version__}",87            "x-auth-token": "BazToken",88        }89    }909192@pytest.mark.asyncio93async def test_header_update():94    url = "http://example.org/echo_headers"95    client = AsyncClient(dispatch=MockDispatch())96    first_response = await client.get(url)97    client.headers.update(98        {"User-Agent": "python-myclient/0.2.1", "Another-Header": "AThing"}99    )100    second_response = await client.get(url)101102    assert first_response.status_code == 200103    assert first_response.json() == {104        "headers": {105            "accept": "*/*",106            "accept-encoding": "gzip, deflate, br",107            "connection": "keep-alive",108            "host": "example.org",109            "user-agent": f"python-httpx/{__version__}",110        }111    }112113    assert second_response.status_code == 200114    assert second_response.json() == {115        "headers": {116            "accept": "*/*",117            "accept-encoding": "gzip, deflate, br",118            "another-header": "AThing",119            "connection": "keep-alive",120            "host": "example.org",121            "user-agent": "python-myclient/0.2.1",122        }123    }124125126def test_header_does_not_exist():127    headers = Headers({"foo": "bar"})128    with pytest.raises(KeyError):129        del headers["baz"]130131132@pytest.mark.asyncio133async def test_host_with_auth_and_port_in_url():134    """135    The Host header should only include the hostname, or hostname:port136    (for non-default ports only). Any userinfo or default port should not137    be present.138    """139    url = "http://username:password@example.org:80/echo_headers"140141    client = AsyncClient(dispatch=MockDispatch())142    response = await client.get(url)143144    assert response.status_code == 200145    assert response.json() == {146        "headers": {147            "accept": "*/*",148            "accept-encoding": "gzip, deflate, br",149            "connection": "keep-alive",150            "host": "example.org",151            "user-agent": f"python-httpx/{__version__}",152            "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",153        }154    }155156157@pytest.mark.asyncio158async def test_host_with_non_default_port_in_url():159    """160    If the URL includes a non-default port, then it should be included in161    the Host header.162    """163    url = "http://username:password@example.org:123/echo_headers"164165    client = AsyncClient(dispatch=MockDispatch())166    response = await client.get(url)167168    assert response.status_code == 200169    assert response.json() == {170        "headers": {171            "accept": "*/*",172            "accept-encoding": "gzip, deflate, br",173            "connection": "keep-alive",174            "host": "example.org:123",175            "user-agent": f"python-httpx/{__version__}",176            "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",177        }178    }