Skip to content
Myr

test_concurrency.py

This file

Path

tests/test_concurrency.py

161 lines · 5.0 KiB · Python

Last changed by

Backend operations like .read(), .write() now have a manadatory timeout argument. (#611)Tom Christiebefore adoptionbc54dd0

History of this file

Take it

1import pytest2import trio34from httpx import Timeout5from httpx.concurrency.asyncio import AsyncioBackend6from httpx.concurrency.trio import TrioBackend7from httpx.config import SSLConfig8from tests.concurrency import run_concurrently, sleep91011def get_asyncio_cipher(stream):12    return stream.stream_writer.get_extra_info("cipher", default=None)131415def get_trio_cipher(stream):16    return stream.stream.cipher() if isinstance(stream.stream, trio.SSLStream) else None171819async def read_response(stream, timeout: Timeout, should_contain: bytes) -> bytes:20    # stream.read() only gives us *up to* as much data as we ask for. In order to21    # cleanly close the stream, we must read until the end of the HTTP response.22    response = b""23    ended = False2425    for _ in range(5):  # Try read some (not too large) number of times...26        response += await stream.read(8192, timeout)27        # We know we're at the end of the response when we've received the body plus28        # the terminating CRLFs.29        if should_contain in response and response.endswith(b"\r\n\r\n"):30            ended = True31            break3233    assert ended34    return response353637@pytest.mark.parametrize(38    "backend, get_cipher",39    [40        pytest.param(AsyncioBackend(), get_asyncio_cipher, marks=pytest.mark.asyncio),41        pytest.param(TrioBackend(), get_trio_cipher, marks=pytest.mark.trio),42    ],43)44async def test_start_tls_on_tcp_socket_stream(https_server, backend, get_cipher):45    ctx = SSLConfig().load_ssl_context_no_verify()46    timeout = Timeout(5)4748    stream = await backend.open_tcp_stream(49        https_server.url.host, https_server.url.port, None, timeout50    )5152    try:53        assert stream.is_connection_dropped() is False54        assert get_cipher(stream) is None5556        stream = await stream.start_tls(https_server.url.host, ctx, timeout)57        assert stream.is_connection_dropped() is False58        assert get_cipher(stream) is not None5960        await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)6162        response = await read_response(stream, timeout, should_contain=b"Hello, world")63        assert response.startswith(b"HTTP/1.1 200 OK\r\n")6465    finally:66        await stream.close()676869@pytest.mark.parametrize(70    "backend, get_cipher",71    [72        pytest.param(AsyncioBackend(), get_asyncio_cipher, marks=pytest.mark.asyncio),73        pytest.param(TrioBackend(), get_trio_cipher, marks=pytest.mark.trio),74    ],75)76async def test_start_tls_on_uds_socket_stream(https_uds_server, backend, get_cipher):77    ctx = SSLConfig().load_ssl_context_no_verify()78    timeout = Timeout(5)7980    stream = await backend.open_uds_stream(81        https_uds_server.config.uds, https_uds_server.url.host, None, timeout82    )8384    try:85        assert stream.is_connection_dropped() is False86        assert get_cipher(stream) is None8788        stream = await stream.start_tls(https_uds_server.url.host, ctx, timeout)89        assert stream.is_connection_dropped() is False90        assert get_cipher(stream) is not None9192        await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)9394        response = await read_response(stream, timeout, should_contain=b"Hello, world")95        assert response.startswith(b"HTTP/1.1 200 OK\r\n")9697    finally:98        await stream.close()99100101async def test_concurrent_read(server, backend):102    """103    Regression test for: https://github.com/encode/httpx/issues/527104    """105    stream = await backend.open_tcp_stream(106        server.url.host, server.url.port, ssl_context=None, timeout=Timeout(5)107    )108    timeout = Timeout(5)109    try:110        await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)111        await run_concurrently(112            backend, lambda: stream.read(10, timeout), lambda: stream.read(10, timeout)113        )114    finally:115        await stream.close()116117118async def test_fork(backend):119    ok_counter = 0120121    async def ok(delay: int) -> None:122        nonlocal ok_counter123        await sleep(backend, delay)124        ok_counter += 1125126    async def fail(message: str, delay: int) -> None:127        await sleep(backend, delay)128        raise RuntimeError(message)129130    await backend.fork(ok, [0], ok, [0])131    assert ok_counter == 2132133    with pytest.raises(RuntimeError, match="Oops"):134        await backend.fork(ok, [0], fail, ["Oops", 0.01])135136    assert ok_counter == 3137138    with pytest.raises(RuntimeError, match="Oops"):139        await backend.fork(ok, [0.01], fail, ["Oops", 0])140141    assert ok_counter == 3142143    with pytest.raises(RuntimeError, match="Oops"):144        await backend.fork(fail, ["Oops", 0.01], ok, [0])145146    assert ok_counter == 4147148    with pytest.raises(RuntimeError, match="Oops"):149        await backend.fork(fail, ["Oops", 0], ok, [0.01])150151    assert ok_counter == 4152153    with pytest.raises(RuntimeError, match="My bad"):154        await backend.fork(fail, ["My bad", 0], fail, ["Oops", 0.01])155156    with pytest.raises(RuntimeError, match="Oops"):157        await backend.fork(fail, ["My bad", 0.01], fail, ["Oops", 0])158159    # No 'match', since we can't know which will be raised first.160    with pytest.raises(RuntimeError):161        await backend.fork(fail, ["My bad", 0], fail, ["Oops", 0])