concurrency.py
This file
Path
tests/concurrency.py
77 lines · 2.1 KiB · Python
Last changed by
Refactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d
History of this fileTake it
1"""2This module contains concurrency utilities that are only used in tests, thus not3required as part of the ConcurrencyBackend API.4"""56import asyncio7import functools8import typing910import trio1112from httpx.concurrency.asyncio import AsyncioBackend13from httpx.concurrency.auto import AutoBackend14from httpx.concurrency.trio import TrioBackend151617@functools.singledispatch18async def sleep(backend, seconds: int):19 raise NotImplementedError # pragma: no cover202122@sleep.register(AutoBackend)23async def _sleep_auto(backend, seconds: int):24 return await sleep(backend.backend, seconds=seconds)252627@sleep.register(AsyncioBackend)28async def _sleep_asyncio(backend, seconds: int):29 await asyncio.sleep(seconds)303132@sleep.register(TrioBackend)33async def _sleep_trio(backend, seconds: int):34 await trio.sleep(seconds)353637@functools.singledispatch38async def run_concurrently(backend, *coroutines: typing.Callable[[], typing.Awaitable]):39 raise NotImplementedError # pragma: no cover404142@run_concurrently.register(AutoBackend)43async def _run_concurrently_auto(backend, *coroutines):44 await run_concurrently(backend.backend, *coroutines)454647@run_concurrently.register(AsyncioBackend)48async def _run_concurrently_asyncio(backend, *coroutines):49 coros = (coroutine() for coroutine in coroutines)50 await asyncio.gather(*coros)515253@run_concurrently.register(TrioBackend)54async def _run_concurrently_trio(backend, *coroutines):55 async with trio.open_nursery() as nursery:56 for coroutine in coroutines:57 nursery.start_soon(coroutine)585960@functools.singledispatch61def get_cipher(backend, stream):62 raise NotImplementedError # pragma: no cover636465@get_cipher.register(AutoBackend)66def _get_cipher_auto(backend, stream):67 return get_cipher(backend.backend, stream)686970@get_cipher.register(AsyncioBackend)71def _get_cipher_asyncio(backend, stream):72 return stream.stream_writer.get_extra_info("cipher", default=None)737475@get_cipher.register(TrioBackend)76def get_trio_cipher(backend, stream):77 return stream.stream.cipher() if isinstance(stream.stream, trio.SSLStream) else None