Skip to content
Myr

test_headers.py

This file

Path

tests/client/test_headers.py

182 lines · 5.5 KiB · Python

Last changed by

Better test case consistency. Prefer `import httpx` and `httpx.Client`. (#1222)Tom Christiebefore adoption28c7205

History of this file

Take it

1#!/usr/bin/env python323import typing45import httpcore6import pytest78import httpx9from httpx._content_streams import ContentStream, JSONStream101112class MockTransport(httpcore.SyncHTTPTransport):13    def request(14        self,15        method: bytes,16        url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],17        headers: typing.List[typing.Tuple[bytes, bytes]] = None,18        stream: httpcore.SyncByteStream = None,19        timeout: typing.Mapping[str, typing.Optional[float]] = None,20    ) -> typing.Tuple[21        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream22    ]:23        assert headers is not None24        headers_dict = {25            key.decode("ascii"): value.decode("ascii") for key, value in headers26        }27        body = JSONStream({"headers": headers_dict})28        return b"HTTP/1.1", 200, b"OK", [], body293031def 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 = httpx.Client(transport=MockTransport(), headers=headers)39    response = 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/{httpx.__version__}",50        }51    }525354def test_header_merge():55    url = "http://example.org/echo_headers"56    client_headers = {"User-Agent": "python-myclient/0.2.1"}57    request_headers = {"X-Auth-Token": "FooBarBazToken"}58    client = httpx.Client(transport=MockTransport(), headers=client_headers)59    response = client.get(url, headers=request_headers)6061    assert response.status_code == 20062    assert response.json() == {63        "headers": {64            "accept": "*/*",65            "accept-encoding": "gzip, deflate, br",66            "connection": "keep-alive",67            "host": "example.org",68            "user-agent": "python-myclient/0.2.1",69            "x-auth-token": "FooBarBazToken",70        }71    }727374def test_header_merge_conflicting_headers():75    url = "http://example.org/echo_headers"76    client_headers = {"X-Auth-Token": "FooBar"}77    request_headers = {"X-Auth-Token": "BazToken"}78    client = httpx.Client(transport=MockTransport(), headers=client_headers)79    response = client.get(url, headers=request_headers)8081    assert response.status_code == 20082    assert response.json() == {83        "headers": {84            "accept": "*/*",85            "accept-encoding": "gzip, deflate, br",86            "connection": "keep-alive",87            "host": "example.org",88            "user-agent": f"python-httpx/{httpx.__version__}",89            "x-auth-token": "BazToken",90        }91    }929394def test_header_update():95    url = "http://example.org/echo_headers"96    client = httpx.Client(transport=MockTransport())97    first_response = client.get(url)98    client.headers.update(99        {"User-Agent": "python-myclient/0.2.1", "Another-Header": "AThing"}100    )101    second_response = client.get(url)102103    assert first_response.status_code == 200104    assert first_response.json() == {105        "headers": {106            "accept": "*/*",107            "accept-encoding": "gzip, deflate, br",108            "connection": "keep-alive",109            "host": "example.org",110            "user-agent": f"python-httpx/{httpx.__version__}",111        }112    }113114    assert second_response.status_code == 200115    assert second_response.json() == {116        "headers": {117            "accept": "*/*",118            "accept-encoding": "gzip, deflate, br",119            "another-header": "AThing",120            "connection": "keep-alive",121            "host": "example.org",122            "user-agent": "python-myclient/0.2.1",123        }124    }125126127def test_header_does_not_exist():128    headers = httpx.Headers({"foo": "bar"})129    with pytest.raises(KeyError):130        del headers["baz"]131132133def 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 = httpx.Client(transport=MockTransport())142    response = 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/{httpx.__version__}",152            "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",153        }154    }155156157def test_host_with_non_default_port_in_url():158    """159    If the URL includes a non-default port, then it should be included in160    the Host header.161    """162    url = "http://username:password@example.org:123/echo_headers"163164    client = httpx.Client(transport=MockTransport())165    response = client.get(url)166167    assert response.status_code == 200168    assert response.json() == {169        "headers": {170            "accept": "*/*",171            "accept-encoding": "gzip, deflate, br",172            "connection": "keep-alive",173            "host": "example.org:123",174            "user-agent": f"python-httpx/{httpx.__version__}",175            "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",176        }177    }178179180def test_request_auto_headers():181    request = httpx.Request("GET", "https://www.example.org/")182    assert "host" in request.headers