Example #1
0
    def __init__(
        self,
        status_code: Optional[int] = None,
        *,
        content: Optional[ContentDataTypes] = None,
        text: Optional[str] = None,
        html: Optional[str] = None,
        json: Optional[JSONTypes] = None,
        headers: Optional[HeaderTypes] = None,
        content_type: Optional[str] = None,
        http_version: Optional[str] = None,
        context: Optional[Kwargs] = None,
    ) -> None:
        self.http_version = http_version
        self.status_code = status_code or 200
        self.context = context if context is not None else {}

        self.headers = httpx.Headers(headers) if headers else httpx.Headers()
        if content_type:
            self.headers["Content-Type"] = content_type

        # Set body variants in reverse priority order
        self.json = json
        self.html = html
        self.text = text
        self.content = content
Example #2
0
def test_headers():
    h = httpx.Headers([("a", "123"), ("a", "456"), ("b", "789")])
    assert "a" in h
    assert "A" in h
    assert "b" in h
    assert "B" in h
    assert "c" not in h
    assert h["a"] == "123, 456"
    assert h.get("a") == "123, 456"
    assert h.get("nope", default=None) is None
    assert h.getlist("a") == ["123", "456"]
    assert h.keys() == ["a", "a", "b"]
    assert h.values() == ["123", "456", "789"]
    assert h.items() == [("a", "123"), ("a", "456"), ("b", "789")]
    assert list(h) == ["a", "a", "b"]
    assert dict(h) == {"a": "123, 456", "b": "789"}
    assert repr(h) == "Headers([('a', '123'), ('a', '456'), ('b', '789')])"
    assert h == httpx.Headers([("a", "123"), ("b", "789"), ("a", "456")])
    assert h != [("a", "123"), ("A", "456"), ("b", "789")]

    h = httpx.Headers({"a": "123", "b": "789"})
    assert h["A"] == "123"
    assert h["B"] == "789"
    assert h.raw == [(b"a", b"123"), (b"b", b"789")]
    assert repr(h) == "Headers({'a': '123', 'b': '789'})"
Example #3
0
def test_multiple_headers():
    """
    `Headers.get_list` should support both split_commas=False and split_commas=True.
    """
    h = httpx.Headers([("set-cookie", "a, b"), ("set-cookie", "c")])
    assert h.get_list("Set-Cookie") == ["a, b", "c"]

    h = httpx.Headers([("vary", "a, b"), ("vary", "c")])
    assert h.get_list("Vary", split_commas=True) == ["a", "b", "c"]
Example #4
0
def test_multiple_headers():
    """
    Most headers should split by commas for `getlist`, except 'Set-Cookie'.
    """
    h = httpx.Headers([("set-cookie", "a, b"), ("set-cookie", "c")])
    h.getlist("Set-Cookie") == ["a, b", "b"]

    h = httpx.Headers([("vary", "a, b"), ("vary", "c")])
    h.getlist("Vary") == ["a", "b", "c"]
Example #5
0
async def test_json_content(client, content, headers, expected_headers):
    async with MockRouter() as respx_mock:
        url = "https://foo.bar/"
        request = respx_mock.get(url) % dict(json=content, headers=headers)

        async_response = await client.get(url)
        assert request.called is True
        assert async_response.headers == httpx.Headers(expected_headers)
        assert async_response.json() == content

        respx_mock.reset()
        sync_response = httpx.get(url)
        assert request.called is True
        assert sync_response.headers == httpx.Headers(expected_headers)
        assert sync_response.json() == content
Example #6
0
async def test_json_content(client, content, headers, expected_headers):
    async with respx.HTTPXMock() as httpx_mock:
        url = "https://foo.bar/"
        request = httpx_mock.get(url, content=content, headers=headers)

        async_response = await client.get(url)
        assert request.called is True
        assert async_response.headers == httpx.Headers(expected_headers or headers)
        assert async_response.json() == content

        httpx_mock.reset()
        sync_response = httpx.get(url)
        assert request.called is True
        assert sync_response.headers == httpx.Headers(expected_headers or headers)
        assert sync_response.json() == content
Example #7
0
async def test_headers(client, headers, content_type, expected):
    async with respx.HTTPXMock() as httpx_mock:
        url = "https://foo.bar/"
        request = httpx_mock.get(url, content_type=content_type, headers=headers)
        response = await client.get(url)
        assert request.called is True
        assert response.headers == httpx.Headers(expected)
Example #8
0
def test_generator_with_content_length_header():
    def content():
        yield b"test 123"  # pragma: nocover

    headers = {"Content-Length": "8"}
    response = httpx.Response(200, content=content(), headers=headers)
    assert response.headers == httpx.Headers({"Content-Length": "8"})
Example #9
0
def test_headers_list_repr():
    """
    Headers should display with a list repr if they include multiple identical keys.
    """
    headers = httpx.Headers([("custom", "example 1"), ("custom", "example 2")])
    assert (repr(headers) ==
            "Headers([('custom', 'example 1'), ('custom', 'example 2')])")
Example #10
0
async def test_request_callback(client):
    def callback(request, response):
        request.read()
        if request.url.host == "foo.bar" and request.content == b'{"foo": "bar"}':
            response.headers["X-Foo"] = "bar"
            response.content = lambda request, name: f"hello {name}"
            response.context["name"] = "lundberg"
            response.http_version = "HTTP/2"
            return response

    async with MockTransport(assert_all_called=False) as respx_mock:
        request = respx_mock.add(callback,
                                 status_code=202,
                                 headers={"X-Ham": "spam"})
        response = await client.post("https://foo.bar/", json={"foo": "bar"})

        assert request.called is True
        assert request.pass_through is None
        assert response.status_code == 202
        assert response.http_version == "HTTP/2"
        assert response.headers == httpx.Headers({
            "Content-Type": "text/plain; charset=utf-8",
            "Content-Length": "14",
            "X-Ham": "spam",
            "X-Foo": "bar",
        })
        assert response.text == "hello lundberg"

        with pytest.raises(ValueError):
            respx_mock.add(lambda req, res: "invalid")
            await client.get("https://ham.spam/")
Example #11
0
def test_header_as_httpx_headers(httpx_mock: HTTPXMock):
    httpx_mock.add_response(headers=httpx.Headers({"set-cookie": "key=value"}))

    with httpx.Client() as client:
        response = client.get("http://test_url")

    assert dict(response.cookies) == {"key": "value"}
Example #12
0
def test_headers_encoding_in_repr():
    """
    Headers should display an encoding in the repr if required.
    """
    headers = httpx.Headers({b"custom": "example ☃".encode("utf-8")})
    assert repr(
        headers) == "Headers({'custom': 'example ☃'}, encoding='utf-8')"
Example #13
0
async def test_asgi():  # pragma: nocover
    from respx.mocks import HTTPCoreMocker

    try:
        HTTPCoreMocker.add_targets(
            "httpx._transports.asgi.ASGITransport",
            "httpx._transports.wsgi.WSGITransport",
        )
        async with respx.mock:
            async with httpx.AsyncClient(app="fake-asgi") as client:
                url = "https://foo.bar/"
                jzon = {"status": "ok"}
                headers = {"X-Foo": "bar"}
                request = respx.get(url) % dict(
                    status_code=202, headers=headers, json=jzon)
                response = await client.get(url)
                assert request.called is True
                assert response.status_code == 202
                assert response.headers == httpx.Headers({
                    "Content-Type": "application/json",
                    "Content-Length": "16",
                    **headers,
                })
                assert response.json() == {"status": "ok"}
    finally:
        HTTPCoreMocker.remove_targets(
            "httpx._transports.asgi.ASGITransport",
            "httpx._transports.wsgi.WSGITransport",
        )
Example #14
0
def test_sensitive_headers(header):
    """
    Some headers should be obfuscated because they contain sensitive data.
    """
    value = "s3kr3t"
    h = httpx.Headers({header: value})
    assert repr(h) == "Headers({'%s': '[secure]'})" % header
Example #15
0
async def test_request_callback(client):
    def callback(request, response):
        if request.url.host == "foo.bar":
            response.headers["X-Foo"] = "bar"
            response.content = lambda request, name: f"hello {name}"
            response.context["name"] = "lundberg"
            return response

    async with respx.HTTPXMock(assert_all_called=False) as httpx_mock:
        request = httpx_mock.request(
            callback, status_code=202, headers={"X-Ham": "spam"}
        )
        response = await client.get("https://foo.bar/")

        assert request.called is True
        assert request.pass_through is None
        assert response.status_code == 202
        assert response.headers == httpx.Headers(
            {"Content-Type": "text/plain", "X-Ham": "spam", "X-Foo": "bar"}
        )
        assert response.text == "hello lundberg"

        with pytest.raises(ValueError):
            httpx_mock.request(lambda req, res: "invalid")
            await client.get("https://ham.spam/")
Example #16
0
async def test_headers(client, headers, content_type, expected):
    async with MockRouter() as respx_mock:
        url = "https://foo.bar/"
        request = respx_mock.get(url).respond(headers=headers,
                                              content_type=content_type)
        response = await client.get(url)
        assert request.called is True
        assert response.headers == httpx.Headers(expected)
Example #17
0
def test_headers_decode_iso_8859_1():
    """
    Headers containing non-UTF-8 codepoints should default to decoding as iso-8859-1.
    """
    raw_headers = [(b"Custom", "Code point: ÿ".encode("iso-8859-1"))]
    headers = httpx.Headers(raw_headers)
    assert dict(headers) == {"custom": "Code point: ÿ"}
    assert headers.encoding == "iso-8859-1"
Example #18
0
def test_headers_decode_utf_8():
    """
    Headers containing non-ascii codepoints should default to decoding as utf-8.
    """
    raw_headers = [(b"Custom", "Code point: ☃".encode("utf-8"))]
    headers = httpx.Headers(raw_headers)
    assert dict(headers) == {"custom": "Code point: ☃"}
    assert headers.encoding == "utf-8"
Example #19
0
def test_headers_decode_ascii():
    """
    Headers should decode as ascii by default.
    """
    raw_headers = [(b"Custom", b"Example")]
    headers = httpx.Headers(raw_headers)
    assert dict(headers) == {"custom": "Example"}
    assert headers.encoding == "ascii"
Example #20
0
    def parse(self, request: RequestTypes) -> httpx.Headers:
        if isinstance(request, httpx.Request):
            headers = request.headers
        else:
            _, _, _headers, *_ = request
            headers = httpx.Headers(_headers)

        return headers
Example #21
0
def test_headers():
    request = httpx.Request("POST", "http://example.org", json={"test": 123})

    assert request.headers == httpx.Headers({
        "Host": "example.org",
        "Content-Type": "application/json",
        "Content-Length": "13",
    })
Example #22
0
def get_client(token):
    return httpx.Client(
        headers=httpx.Headers(
            {
                "User-Agent": "GitHubClassroomUtils/1.0",
                "Authorization": f"token {token}",
            }
        )
    )
def test_with_headers(httpx_mock: HTTPXMock):
    httpx_mock.add_response(url="http://test_url",
                            data=b"test content 1",
                            headers={"X-Test": "Test value"})

    with httpx.Client() as client:
        response = client.get("http://test_url")
        assert response.content == b"test content 1"
        assert response.headers == httpx.Headers({"x-test": "Test value"})
def test_default_response(httpx_mock: HTTPXMock):
    httpx_mock.add_response()

    with httpx.Client() as client:
        response = client.get("http://test_url")
    assert response.content == b""
    assert response.status_code == 200
    assert response.headers == httpx.Headers({})
    assert response.http_version == "HTTP/1.1"
Example #25
0
def test_generator_with_transfer_encoding_header():
    def content():
        yield b"test 123"  # pragma: nocover

    request = httpx.Request("POST", "http://example.org", content=content())
    assert request.headers == httpx.Headers({
        "Host": "example.org",
        "Transfer-Encoding": "chunked"
    })
 def auth_flow(self, request):
     body_sha512 = b64encode(
         hashlib.sha512(request.content).digest()).decode('ascii')
     headers_to_sign = tuple(request.headers.items()) + (
         ('digest', f'SHA512={body_sha512}'), )
     request.headers = httpx.Headers(
         sign_headers(self.key_id, self.private_key.sign,
                      request.method, request.url.full_path,
                      headers_to_sign))
     yield request
Example #27
0
def test_iterable_content():
    class Content:
        def __iter__(self):
            yield b"test 123"  # pragma: nocover

    request = httpx.Request("POST", "http://example.org", content=Content())
    assert request.headers == httpx.Headers({
        "Host": "example.org",
        "Transfer-Encoding": "chunked"
    })
Example #28
0
def test_headers_decode_explicit_encoding():
    """
    An explicit encoding may be set on headers in order to force a
    particular decoding.
    """
    raw_headers = [(b"Custom", "Code point: ☃".encode("utf-8"))]
    headers = httpx.Headers(raw_headers)
    headers.encoding = "iso-8859-1"
    assert dict(headers) == {"custom": "Code point: â\x98\x83"}
    assert headers.encoding == "iso-8859-1"
Example #29
0
def test_get_file_status(event_loop):
    headers = httpx.Headers({'Authorization': auth})
    with httpx.Client() as s:
        token = s.get(endpoint, headers=headers).json()['delegationToken']
        client = WebHdfsAsyncClient(host='namenode.local',
                                    port=8443,
                                    user='******',
                                    kerberos_token=token)
        response = event_loop.run_until_complete(
            client.get_file_status("/tmp/dos.txt"))
        assert response['FileStatus']['type'] == 'FILE'
Example #30
0
def ensure_gh_token(token: str):
    """
    Raise token error if token is valid by requesting github
    """
    httpx_headers = httpx.Headers({
        "User-Agent": "GitHubClassroomUtils/1.0",
        "Authorization": f"token {token}",
    })
    res = httpx.get("https://api.github.com/user", headers=httpx_headers)
    if res.status_code != 200:
        raise ERR_INVALID_GITHUB_TOKEN(token=token)