Skip to content
Myr

test_headers.py

This file

Path

tests/client/test_headers.py

237 lines · 7.2 KiB · Python

Last changed by

Clarified error when header value is None (#3312)Polina Beskorovainaiabefore adoption49d74a2

History of this file

Take it

1#!/usr/bin/env python323import pytest45import httpx678def echo_headers(request: httpx.Request) -> httpx.Response:9    data = {"headers": dict(request.headers)}10    return httpx.Response(200, json=data)111213def echo_repeated_headers_multi_items(request: httpx.Request) -> httpx.Response:14    data = {"headers": list(request.headers.multi_items())}15    return httpx.Response(200, json=data)161718def echo_repeated_headers_items(request: httpx.Request) -> httpx.Response:19    data = {"headers": list(request.headers.items())}20    return httpx.Response(200, json=data)212223def test_client_header():24    """25    Set a header in the Client.26    """27    url = "http://example.org/echo_headers"28    headers = {"Example-Header": "example-value"}2930    client = httpx.Client(transport=httpx.MockTransport(echo_headers), headers=headers)31    response = client.get(url)3233    assert response.status_code == 20034    assert response.json() == {35        "headers": {36            "accept": "*/*",37            "accept-encoding": "gzip, deflate, br, zstd",38            "connection": "keep-alive",39            "example-header": "example-value",40            "host": "example.org",41            "user-agent": f"python-httpx/{httpx.__version__}",42        }43    }444546def test_header_merge():47    url = "http://example.org/echo_headers"48    client_headers = {"User-Agent": "python-myclient/0.2.1"}49    request_headers = {"X-Auth-Token": "FooBarBazToken"}50    client = httpx.Client(51        transport=httpx.MockTransport(echo_headers), headers=client_headers52    )53    response = client.get(url, headers=request_headers)5455    assert response.status_code == 20056    assert response.json() == {57        "headers": {58            "accept": "*/*",59            "accept-encoding": "gzip, deflate, br, zstd",60            "connection": "keep-alive",61            "host": "example.org",62            "user-agent": "python-myclient/0.2.1",63            "x-auth-token": "FooBarBazToken",64        }65    }666768def test_header_merge_conflicting_headers():69    url = "http://example.org/echo_headers"70    client_headers = {"X-Auth-Token": "FooBar"}71    request_headers = {"X-Auth-Token": "BazToken"}72    client = httpx.Client(73        transport=httpx.MockTransport(echo_headers), headers=client_headers74    )75    response = client.get(url, headers=request_headers)7677    assert response.status_code == 20078    assert response.json() == {79        "headers": {80            "accept": "*/*",81            "accept-encoding": "gzip, deflate, br, zstd",82            "connection": "keep-alive",83            "host": "example.org",84            "user-agent": f"python-httpx/{httpx.__version__}",85            "x-auth-token": "BazToken",86        }87    }888990def test_header_update():91    url = "http://example.org/echo_headers"92    client = httpx.Client(transport=httpx.MockTransport(echo_headers))93    first_response = client.get(url)94    client.headers.update(95        {"User-Agent": "python-myclient/0.2.1", "Another-Header": "AThing"}96    )97    second_response = client.get(url)9899    assert first_response.status_code == 200100    assert first_response.json() == {101        "headers": {102            "accept": "*/*",103            "accept-encoding": "gzip, deflate, br, zstd",104            "connection": "keep-alive",105            "host": "example.org",106            "user-agent": f"python-httpx/{httpx.__version__}",107        }108    }109110    assert second_response.status_code == 200111    assert second_response.json() == {112        "headers": {113            "accept": "*/*",114            "accept-encoding": "gzip, deflate, br, zstd",115            "another-header": "AThing",116            "connection": "keep-alive",117            "host": "example.org",118            "user-agent": "python-myclient/0.2.1",119        }120    }121122123def test_header_repeated_items():124    url = "http://example.org/echo_headers"125    client = httpx.Client(transport=httpx.MockTransport(echo_repeated_headers_items))126    response = client.get(url, headers=[("x-header", "1"), ("x-header", "2,3")])127128    assert response.status_code == 200129130    echoed_headers = response.json()["headers"]131    # as per RFC 7230, the whitespace after a comma is insignificant132    # so we split and strip here so that we can do a safe comparison133    assert ["x-header", ["1", "2", "3"]] in [134        [k, [subv.lstrip() for subv in v.split(",")]] for k, v in echoed_headers135    ]136137138def test_header_repeated_multi_items():139    url = "http://example.org/echo_headers"140    client = httpx.Client(141        transport=httpx.MockTransport(echo_repeated_headers_multi_items)142    )143    response = client.get(url, headers=[("x-header", "1"), ("x-header", "2,3")])144145    assert response.status_code == 200146147    echoed_headers = response.json()["headers"]148    assert ["x-header", "1"] in echoed_headers149    assert ["x-header", "2,3"] in echoed_headers150151152def test_remove_default_header():153    """154    Remove a default header from the Client.155    """156    url = "http://example.org/echo_headers"157158    client = httpx.Client(transport=httpx.MockTransport(echo_headers))159    del client.headers["User-Agent"]160161    response = client.get(url)162163    assert response.status_code == 200164    assert response.json() == {165        "headers": {166            "accept": "*/*",167            "accept-encoding": "gzip, deflate, br, zstd",168            "connection": "keep-alive",169            "host": "example.org",170        }171    }172173174def test_header_does_not_exist():175    headers = httpx.Headers({"foo": "bar"})176    with pytest.raises(KeyError):177        del headers["baz"]178179180def test_header_with_incorrect_value():181    with pytest.raises(182        TypeError,183        match=f"Header value must be str or bytes, not {type(None)}",184    ):185        httpx.Headers({"foo": None})  # type: ignore186187188def test_host_with_auth_and_port_in_url():189    """190    The Host header should only include the hostname, or hostname:port191    (for non-default ports only). Any userinfo or default port should not192    be present.193    """194    url = "http://username:password@example.org:80/echo_headers"195196    client = httpx.Client(transport=httpx.MockTransport(echo_headers))197    response = client.get(url)198199    assert response.status_code == 200200    assert response.json() == {201        "headers": {202            "accept": "*/*",203            "accept-encoding": "gzip, deflate, br, zstd",204            "connection": "keep-alive",205            "host": "example.org",206            "user-agent": f"python-httpx/{httpx.__version__}",207            "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",208        }209    }210211212def test_host_with_non_default_port_in_url():213    """214    If the URL includes a non-default port, then it should be included in215    the Host header.216    """217    url = "http://username:password@example.org:123/echo_headers"218219    client = httpx.Client(transport=httpx.MockTransport(echo_headers))220    response = client.get(url)221222    assert response.status_code == 200223    assert response.json() == {224        "headers": {225            "accept": "*/*",226            "accept-encoding": "gzip, deflate, br, zstd",227            "connection": "keep-alive",228            "host": "example.org:123",229            "user-agent": f"python-httpx/{httpx.__version__}",230            "authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ=",231        }232    }233234235def test_request_auto_headers():236    request = httpx.Request("GET", "https://www.example.org/")237    assert "host" in request.headers