Skip to content
Myr

test_headers.py

This file

Path

tests/client/test_headers.py

182 lines · 5.5 KiB · Python

Last changed by

Httpcore interface (#804)Tom Christiebefore adoption3046e92

History of this file

Take it

1#!/usr/bin/env python323import typing45import httpcore6import pytest78from httpx import AsyncClient, Headers, __version__9from httpx._content_streams import ContentStream, JSONStream101112class MockDispatch(httpcore.AsyncHTTPTransport):13    async def request(14        self,15        method: bytes,16        url: typing.Tuple[bytes, bytes, int, bytes],17        headers: typing.List[typing.Tuple[bytes, bytes]],18        stream: ContentStream,19        timeout: typing.Dict[str, typing.Optional[float]] = None,20    ) -> typing.Tuple[21        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream22    ]:23        headers_dict = dict(24            [(key.decode("ascii"), value.decode("ascii")) for key, value in headers]25        )26        body = JSONStream({"headers": headers_dict})27        return b"HTTP/1.1", 200, b"OK", [], body282930@pytest.mark.asyncio31async def test_client_header():32    """33    Set a header in the Client.34    """35    url = "http://example.org/echo_headers"36    headers = {"Example-Header": "example-value"}3738    client = AsyncClient(dispatch=MockDispatch(), headers=headers)39    response = await client.get(url)4041    assert response.status_code == 20042    assert response.json() == {43        "headers": {44            "accept": "*/*",45            "accept-encoding": "gzip, deflate, br",46            "connection": "keep-alive",47            "example-header": "example-value",48            "host": "example.org",49            "user-agent": f"python-httpx/{__version__}",50        }51    }525354@pytest.mark.asyncio55async def test_header_merge():56    url = "http://example.org/echo_headers"57    client_headers = {"User-Agent": "python-myclient/0.2.1"}58    request_headers = {"X-Auth-Token": "FooBarBazToken"}59    client = AsyncClient(dispatch=MockDispatch(), headers=client_headers)60    response = await client.get(url, headers=request_headers)6162    assert response.status_code == 20063    assert response.json() == {64        "headers": {65            "accept": "*/*",66            "accept-encoding": "gzip, deflate, br",67            "connection": "keep-alive",68            "host": "example.org",69            "user-agent": "python-myclient/0.2.1",70            "x-auth-token": "FooBarBazToken",71        }72    }737475@pytest.mark.asyncio76async def test_header_merge_conflicting_headers():77    url = "http://example.org/echo_headers"78    client_headers = {"X-Auth-Token": "FooBar"}79    request_headers = {"X-Auth-Token": "BazToken"}80    client = AsyncClient(dispatch=MockDispatch(), headers=client_headers)81    response = await client.get(url, headers=request_headers)8283    assert response.status_code == 20084    assert response.json() == {85        "headers": {86            "accept": "*/*",87            "accept-encoding": "gzip, deflate, br",88            "connection": "keep-alive",89            "host": "example.org",90            "user-agent": f"python-httpx/{__version__}",91            "x-auth-token": "BazToken",92        }93    }949596@pytest.mark.asyncio97async def test_header_update():98    url = "http://example.org/echo_headers"99    client = AsyncClient(dispatch=MockDispatch())100    first_response = await client.get(url)101    client.headers.update(102        {"User-Agent": "python-myclient/0.2.1", "Another-Header": "AThing"}103    )104    second_response = await client.get(url)105106    assert first_response.status_code == 200107    assert first_response.json() == {108        "headers": {109            "accept": "*/*",110            "accept-encoding": "gzip, deflate, br",111            "connection": "keep-alive",112            "host": "example.org",113            "user-agent": f"python-httpx/{__version__}",114        }115    }116117    assert second_response.status_code == 200118    assert second_response.json() == {119        "headers": {120            "accept": "*/*",121            "accept-encoding": "gzip, deflate, br",122            "another-header": "AThing",123            "connection": "keep-alive",124            "host": "example.org",125            "user-agent": "python-myclient/0.2.1",126        }127    }128129130def test_header_does_not_exist():131    headers = Headers({"foo": "bar"})132    with pytest.raises(KeyError):133        del headers["baz"]134135136@pytest.mark.asyncio137async def test_host_with_auth_and_port_in_url():138    """139    The Host header should only include the hostname, or hostname:port140    (for non-default ports only). Any userinfo or default port should not141    be present.142    """143    url = "http://username:password@example.org:80/echo_headers"144145    client = AsyncClient(dispatch=MockDispatch())146    response = await client.get(url)147148    assert response.status_code == 200149    assert response.json() == {150        "headers": {151            "accept": "*/*",152            "accept-encoding": "gzip, deflate, br",153            "connection": "keep-alive",154            "host": "example.org",155            "user-agent": f"python-httpx/{__version__}",156            "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",157        }158    }159160161@pytest.mark.asyncio162async def test_host_with_non_default_port_in_url():163    """164    If the URL includes a non-default port, then it should be included in165    the Host header.166    """167    url = "http://username:password@example.org:123/echo_headers"168169    client = AsyncClient(dispatch=MockDispatch())170    response = await client.get(url)171172    assert response.status_code == 200173    assert response.json() == {174        "headers": {175            "accept": "*/*",176            "accept-encoding": "gzip, deflate, br",177            "connection": "keep-alive",178            "host": "example.org:123",179            "user-agent": f"python-httpx/{__version__}",180            "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",181        }182    }