├── async_timeout ├── py.typed └── __init__.py ├── pyproject.toml ├── MANIFEST.in ├── requirements.txt ├── Makefile ├── setup.cfg ├── .travis.yml ├── .gitignore ├── setup.py ├── CHANGES.rst ├── README.rst ├── tests └── test_timeout.py └── LICENSE /async_timeout/py.typed: -------------------------------------------------------------------------------- 1 | Placeholder -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.black] 2 | target-version = ["py35"] 3 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include CHANGES.rst 3 | include README.rst 4 | graft async_timeout 5 | graft tests 6 | global-exclude *.pyc 7 | global-exclude *.cache 8 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | isort==4.3.21 2 | black==20.8b1; python_version>="3.6" 3 | pytest==6.0.2 4 | pytest-asyncio==0.14.0 5 | pytest-cov==2.10.1 6 | docutils==0.16 7 | mypy==0.770 8 | flake8==3.8.3 9 | -e . 10 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SOURCES = setup.py async_timeout tests 2 | 3 | test: lint 4 | pytest tests 5 | 6 | 7 | lint: mypy check black flake8 8 | 9 | 10 | mypy: 11 | mypy --config-file setup.cfg async_timeout tests 12 | 13 | 14 | black: 15 | isort -c -rc $(SOURCES) 16 | if python -c "import sys; sys.exit(sys.version_info < (3, 6))"; then \ 17 | black --check $(SOURCES); \ 18 | fi 19 | 20 | flake8: 21 | flake8 $(SOURCES) 22 | 23 | 24 | fmt: 25 | isort -rc $(SOURCES) 26 | black $(SOURCES) 27 | 28 | 29 | check: 30 | python setup.py check -rms 31 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | exclude = .git,.env,__pycache__,.eggs 3 | max-line-length = 88 4 | ignore = N801,N802,N803,E252,W503,E133,E203 5 | 6 | [isort] 7 | line_length=88 8 | include_trailing_comma=True 9 | multi_line_output=3 10 | force_grid_wrap=0 11 | combine_as_imports=True 12 | lines_after_imports=2 13 | 14 | [tool:pytest] 15 | addopts= --cov=async_timeout --cov-report=term --cov-report=html --cov-branch 16 | 17 | [metadata] 18 | license_file = LICENSE 19 | 20 | [mypy-pytest] 21 | ignore_missing_imports = true 22 | 23 | [mypy] 24 | python_version = 3.6 25 | warn_unused_ignores = True 26 | warn_redundant_casts = True 27 | warn_no_return = True 28 | strict_optional = True 29 | show_traceback = True 30 | show_column_numbers = True 31 | no_implicit_optional = True 32 | disallow_incomplete_defs = True 33 | disallow_any_generics = True 34 | ignore_missing_imports = True 35 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | version: ~> 1.0 2 | dist: xenial 3 | sudo: required 4 | language: python 5 | 6 | python: 7 | - 3.5.3 8 | - 3.6 9 | - 3.7 10 | - 3.8 11 | 12 | install: 13 | - pip install -e . 14 | - pip install -r requirements.txt 15 | - pip install codecov 16 | 17 | script: 18 | - make test 19 | 20 | 21 | after_success: 22 | - codecov 23 | 24 | 25 | deploy: 26 | provider: pypi 27 | user: aio-libs-bot 28 | password: 29 | secure: "qbjrClh1mBqd6fSRdo4bL6ORjepBah5BDCsvS5XN760CyQsHMn2h4UkYHih2f1VVOz+tBVNHBMowmf+ESYYLdPTPHGI9CZM5fhBLOUeh2Unr/Z+IP/DH57I4DOlEgsfN4ad/Ytm72Jfpumod5izfW+hUOFHrTyXHFqg7YBxCFId7tk6mbTm1+R5Am1R9nRI1+/cg8zC+xTO+oB4DTGYTneztzCovFymhw77ySMP7Y9qR4nvLRTeTVdfjgFn2w7pJCz6k5MXtloGt+KlGvpQaELAskeuV53wK4MKIMyqrx3Aq2pckGESNGhmvd2ZX9/xAgtfwykd6ytP7GJkiHJ6vQj/V3kY2p9EqACHgzseHA9RGaA7E6hsqj8uithY3YZbTuUPTbseV8bugCepNC/P0nN651IySqokzipplhxORnIuWvFamC5aBLHYt/4N/c0jMlwLB/lN7COrVhrEm/XSUNo2WPrrdkPSKOp2PcRokJfV6dNze8zpIjawh5M0WgZH0c8yBpa1fmY6g3qrwZEh2wnv/JZt7VcLub2AWU4/R6E4hlotW+hi6fHoPAjX1VMrQ+6yguiUpL2uvidsOzsU5s5RDkV74x46CiwIo8/LCMVuPCC7Ho0QQmE4v4ht1sqTPyFgGvs1CBiBIspb2Tp4p0dQFfOmuB38ludkZa1BEIDQ=" 30 | distributions: "sdist bdist_wheel" 31 | on: 32 | tags: true 33 | all_branches: true 34 | python: 3.7 35 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | .mypy_cache 92 | .pytest_cache -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | import re 3 | 4 | from setuptools import setup 5 | 6 | 7 | here = pathlib.Path(__file__).parent 8 | fname = here / "async_timeout" / "__init__.py" 9 | 10 | 11 | with fname.open() as fp: 12 | try: 13 | version = re.findall(r'^__version__ = "([^"]+)"$', fp.read(), re.M)[0] 14 | except IndexError: 15 | raise RuntimeError("Unable to determine version.") 16 | 17 | 18 | def read(name): 19 | fname = here / name 20 | with fname.open() as f: 21 | return f.read() 22 | 23 | 24 | install_requires = [ 25 | "typing_extensions>=3.6.5", 26 | ] 27 | 28 | 29 | setup( 30 | name="async-timeout", 31 | version=version, 32 | description=("Timeout context manager for asyncio programs"), 33 | long_description="\n\n".join([read("README.rst"), read("CHANGES.rst")]), 34 | classifiers=[ 35 | "License :: OSI Approved :: Apache Software License", 36 | "Intended Audience :: Developers", 37 | "Programming Language :: Python", 38 | "Programming Language :: Python :: 3", 39 | "Programming Language :: Python :: 3.5", 40 | "Programming Language :: Python :: 3.6", 41 | "Programming Language :: Python :: 3.7", 42 | "Programming Language :: Python :: 3.8", 43 | "Topic :: Internet :: WWW/HTTP", 44 | "Framework :: AsyncIO", 45 | ], 46 | author="Andrew Svetlov", 47 | author_email="andrew.svetlov@gmail.com", 48 | url="https://github.com/aio-libs/async_timeout/", 49 | license="Apache 2", 50 | packages=["async_timeout"], 51 | python_requires=">=3.5.3", 52 | install_requires=install_requires, 53 | include_package_data=True, 54 | ) 55 | -------------------------------------------------------------------------------- /CHANGES.rst: -------------------------------------------------------------------------------- 1 | CHANGES 2 | ======= 3 | 4 | 4.0.0 (2019-11-XX) 5 | ------------------ 6 | 7 | * Add the elapsed property (#24) 8 | 9 | * Implement `timeout.at(when)` (#117) 10 | 11 | * Deprecate synchronous context manager usage 12 | 13 | 3.0.1 (2018-10-09) 14 | ------------------ 15 | 16 | * More aggressive typing (#48) 17 | 18 | 3.0.0 (2018-05-05) 19 | ------------------ 20 | 21 | * Drop Python 3.4, the minimal supported version is Python 3.5.3 22 | 23 | * Provide type annotations 24 | 25 | 2.0.1 (2018-03-13) 26 | ------------------ 27 | 28 | * Fix ``PendingDeprecationWarning`` on Python 3.7 (#33) 29 | 30 | 31 | 2.0.0 (2017-10-09) 32 | ------------------ 33 | 34 | * Changed `timeout <= 0` behaviour 35 | 36 | * Backward incompatibility change, prior this version `0` was 37 | shortcut for `None` 38 | * when timeout <= 0 `TimeoutError` raised faster 39 | 40 | 1.4.0 (2017-09-09) 41 | ------------------ 42 | 43 | * Implement `remaining` property (#20) 44 | 45 | * If timeout is not started yet or started unconstrained: 46 | `remaining` is `None` 47 | * If timeout is expired: `remaining` is `0.0` 48 | * All others: roughly amount of time before `TimeoutError` is triggered 49 | 50 | 1.3.0 (2017-08-23) 51 | ------------------ 52 | 53 | * Don't suppress nested exception on timeout. Exception context points 54 | on cancelled line with suspended `await` (#13) 55 | 56 | * Introduce `.timeout` property (#16) 57 | 58 | * Add methods for using as async context manager (#9) 59 | 60 | 1.2.1 (2017-05-02) 61 | ------------------ 62 | 63 | * Support unpublished event loop's "current_task" api. 64 | 65 | 66 | 1.2.0 (2017-03-11) 67 | ------------------ 68 | 69 | * Extra check on context manager exit 70 | 71 | * 0 is no-op timeout 72 | 73 | 74 | 1.1.0 (2016-10-20) 75 | ------------------ 76 | 77 | * Rename to `async-timeout` 78 | 79 | 1.0.0 (2016-09-09) 80 | ------------------ 81 | 82 | * The first release. 83 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | async-timeout 2 | ============= 3 | .. image:: https://travis-ci.com/aio-libs/async-timeout.svg?branch=master 4 | :target: https://travis-ci.com/aio-libs/async-timeout 5 | .. image:: https://codecov.io/gh/aio-libs/async-timeout/branch/master/graph/badge.svg 6 | :target: https://codecov.io/gh/aio-libs/async-timeout 7 | .. image:: https://img.shields.io/pypi/v/async-timeout.svg 8 | :target: https://pypi.python.org/pypi/async-timeout 9 | .. image:: https://badges.gitter.im/Join%20Chat.svg 10 | :target: https://gitter.im/aio-libs/Lobby 11 | :alt: Chat on Gitter 12 | 13 | asyncio-compatible timeout context manager. 14 | 15 | 16 | Usage example 17 | ------------- 18 | 19 | 20 | The context manager is useful in cases when you want to apply timeout 21 | logic around block of code or in cases when ``asyncio.wait_for()`` is 22 | not suitable. Also it's much faster than ``asyncio.wait_for()`` 23 | because ``timeout`` doesn't create a new task. 24 | 25 | The ``timeout(delay, *, loop=None)`` call returns a context manager 26 | that cancels a block on *timeout* expiring:: 27 | 28 | async with timeout(1.5): 29 | await inner() 30 | 31 | 1. If ``inner()`` is executed faster than in ``1.5`` seconds nothing 32 | happens. 33 | 2. Otherwise ``inner()`` is cancelled internally by sending 34 | ``asyncio.CancelledError`` into but ``asyncio.TimeoutError`` is 35 | raised outside of context manager scope. 36 | 37 | *timeout* parameter could be ``None`` for skipping timeout functionality. 38 | 39 | 40 | Alternatively, ``timeout_at(when)`` can be used for scheduling 41 | at the absolute time:: 42 | 43 | loop = asyncio.get_event_loop() 44 | now = loop.time() 45 | 46 | async with timeout_at(now + 1.5): 47 | await inner() 48 | 49 | 50 | Please note: it is not POSIX time but a time with 51 | undefined starting base, e.g. the time of the system power on. 52 | 53 | 54 | Context manager has ``.expired`` property for check if timeout happens 55 | exactly in context manager:: 56 | 57 | async with timeout(1.5) as cm: 58 | await inner() 59 | print(cm.expired) 60 | 61 | The property is ``True`` if ``inner()`` execution is cancelled by 62 | timeout context manager. 63 | 64 | If ``inner()`` call explicitly raises ``TimeoutError`` ``cm.expired`` 65 | is ``False``. 66 | 67 | The scheduled deadline time is available as ``.deadline`` property:: 68 | 69 | async with timeout(1.5) as cm: 70 | cm.deadline 71 | 72 | Not finished yet timeout can be rescheduled by ``shift_by()`` 73 | or ``shift_to()`` methods:: 74 | 75 | async with timeout(1.5) as cm: 76 | cm.shift_by(1) # add another second on waiting 77 | cm.shift_to(loop.time() + 5) # reschedule to now+5 seconds 78 | 79 | Rescheduling is forbidden if the timeout is expired or after exit from ``async with`` 80 | code block. 81 | 82 | 83 | Installation 84 | ------------ 85 | 86 | :: 87 | 88 | $ pip install async-timeout 89 | 90 | The library is Python 3 only! 91 | 92 | 93 | 94 | Authors and License 95 | ------------------- 96 | 97 | The module is written by Andrew Svetlov. 98 | 99 | It's *Apache 2* licensed and freely available. 100 | -------------------------------------------------------------------------------- /async_timeout/__init__.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import enum 3 | import sys 4 | import warnings 5 | from types import TracebackType 6 | from typing import Any, Optional, Type 7 | 8 | from typing_extensions import final 9 | 10 | 11 | __version__ = "4.0.0a2" 12 | 13 | 14 | __all__ = ("timeout", "timeout_at") 15 | 16 | 17 | def timeout(delay: Optional[float]) -> "Timeout": 18 | """timeout context manager. 19 | 20 | Useful in cases when you want to apply timeout logic around block 21 | of code or in cases when asyncio.wait_for is not suitable. For example: 22 | 23 | >>> async with timeout(0.001): 24 | ... async with aiohttp.get('https://github.com') as r: 25 | ... await r.text() 26 | 27 | 28 | delay - value in seconds or None to disable timeout logic 29 | """ 30 | loop = _get_running_loop() 31 | if delay is not None: 32 | deadline = loop.time() + delay # type: Optional[float] 33 | else: 34 | deadline = None 35 | return Timeout(deadline, loop) 36 | 37 | 38 | def timeout_at(deadline: Optional[float]) -> "Timeout": 39 | """Schedule the timeout at absolute time. 40 | 41 | deadline arguments points on the time in the same clock system 42 | as loop.time(). 43 | 44 | Please note: it is not POSIX time but a time with 45 | undefined starting base, e.g. the time of the system power on. 46 | 47 | >>> async with timeout_at(loop.time() + 10): 48 | ... async with aiohttp.get('https://github.com') as r: 49 | ... await r.text() 50 | 51 | 52 | """ 53 | loop = _get_running_loop() 54 | return Timeout(deadline, loop) 55 | 56 | 57 | class _State(enum.Enum): 58 | INIT = "INIT" 59 | ENTER = "ENTER" 60 | TIMEOUT = "TIMEOUT" 61 | EXIT = "EXIT" 62 | 63 | 64 | @final 65 | class Timeout: 66 | # Internal class, please don't instantiate it directly 67 | # Use timeout() and timeout_at() public factories instead. 68 | # 69 | # Implementation note: `async with timeout()` is preferred 70 | # over `with timeout()`. 71 | # While technically the Timeout class implementation 72 | # doesn't need to be async at all, 73 | # the `async with` statement explicitly points that 74 | # the context manager should be used from async function context. 75 | # 76 | # This design allows to avoid many silly misusages. 77 | # 78 | # TimeoutError is raised immadiatelly when scheduled 79 | # if the deadline is passed. 80 | # The purpose is to time out as sson as possible 81 | # without waiting for the next await expression. 82 | 83 | __slots__ = ("_deadline", "_loop", "_state", "_task", "_timeout_handler") 84 | 85 | def __init__( 86 | self, deadline: Optional[float], loop: asyncio.AbstractEventLoop 87 | ) -> None: 88 | self._loop = loop 89 | self._state = _State.INIT 90 | 91 | task = _current_task(self._loop) 92 | self._task = task 93 | 94 | self._timeout_handler = None # type: Optional[asyncio.Handle] 95 | if deadline is None: 96 | self._deadline = None # type: Optional[float] 97 | else: 98 | self.shift_to(deadline) 99 | 100 | def __enter__(self) -> "Timeout": 101 | warnings.warn( 102 | "with timeout() is deprecated, use async with timeout() instead", 103 | DeprecationWarning, 104 | stacklevel=2, 105 | ) 106 | self._do_enter() 107 | return self 108 | 109 | def __exit__( 110 | self, 111 | exc_type: Type[BaseException], 112 | exc_val: BaseException, 113 | exc_tb: TracebackType, 114 | ) -> Optional[bool]: 115 | self._do_exit(exc_type) 116 | return None 117 | 118 | async def __aenter__(self) -> "Timeout": 119 | self._do_enter() 120 | return self 121 | 122 | async def __aexit__( 123 | self, 124 | exc_type: Type[BaseException], 125 | exc_val: BaseException, 126 | exc_tb: TracebackType, 127 | ) -> Optional[bool]: 128 | self._do_exit(exc_type) 129 | return None 130 | 131 | @property 132 | def expired(self) -> bool: 133 | """Is timeout expired during execution?""" 134 | return self._state == _State.TIMEOUT 135 | 136 | @property 137 | def deadline(self) -> Optional[float]: 138 | return self._deadline 139 | 140 | def reject(self) -> None: 141 | """Reject scheduled timeout if any.""" 142 | # cancel is maybe better name but 143 | # task.cancel() raises CancelledError in asyncio world. 144 | if self._state not in (_State.INIT, _State.ENTER): 145 | raise RuntimeError("invalid state {}".format(self._state.value)) 146 | self._reject() 147 | 148 | def _reject(self) -> None: 149 | if self._timeout_handler is not None: 150 | self._timeout_handler.cancel() 151 | self._timeout_handler = None 152 | 153 | def shift_by(self, delay: float) -> None: 154 | """Advance timeout on delay seconds. 155 | 156 | The delay can be negative. 157 | """ 158 | now = self._loop.time() 159 | self.shift_to(now + delay) 160 | 161 | def shift_to(self, deadline: float) -> None: 162 | """Advance timeout on the abdelay seconds. 163 | 164 | If new deadline is in the past 165 | the timeout is raised immediatelly. 166 | """ 167 | if self._state == _State.EXIT: 168 | raise RuntimeError("cannot reschedule after exit from context manager") 169 | if self._state == _State.TIMEOUT: 170 | raise RuntimeError("cannot reschedule expired timeout") 171 | if self._timeout_handler is not None: 172 | self._timeout_handler.cancel() 173 | self._deadline = deadline 174 | now = self._loop.time() 175 | if deadline <= now: 176 | self._timeout_handler = None 177 | if self._state == _State.INIT: 178 | raise asyncio.TimeoutError 179 | else: 180 | # state is ENTER 181 | raise asyncio.CancelledError 182 | self._timeout_handler = self._loop.call_at( 183 | deadline, self._on_timeout, self._task 184 | ) 185 | 186 | def _do_enter(self) -> None: 187 | if self._state != _State.INIT: 188 | raise RuntimeError("invalid state {}".format(self._state.value)) 189 | self._state = _State.ENTER 190 | 191 | def _do_exit(self, exc_type: Type[BaseException]) -> None: 192 | if exc_type is asyncio.CancelledError and self._state == _State.TIMEOUT: 193 | self._timeout_handler = None 194 | raise asyncio.TimeoutError 195 | # timeout is not expired 196 | self._state = _State.EXIT 197 | self._reject() 198 | return None 199 | 200 | def _on_timeout(self, task: "asyncio.Task[None]") -> None: 201 | task.cancel() 202 | self._state = _State.TIMEOUT 203 | 204 | 205 | def _current_task(loop: asyncio.AbstractEventLoop) -> "asyncio.Task[Any]": 206 | if sys.version_info >= (3, 7): 207 | return asyncio.current_task(loop=loop) 208 | else: 209 | return asyncio.Task.current_task(loop=loop) 210 | 211 | 212 | def _get_running_loop() -> asyncio.AbstractEventLoop: 213 | if sys.version_info >= (3, 7): 214 | return asyncio.get_running_loop() 215 | else: 216 | loop = asyncio.get_event_loop() 217 | if not loop.is_running(): 218 | raise RuntimeError("no running event loop") 219 | return loop 220 | -------------------------------------------------------------------------------- /tests/test_timeout.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import os 3 | import time 4 | 5 | import pytest 6 | 7 | from async_timeout import timeout, timeout_at 8 | 9 | 10 | @pytest.mark.asyncio 11 | async def test_timeout(): 12 | canceled_raised = False 13 | 14 | async def long_running_task(): 15 | try: 16 | await asyncio.sleep(10) 17 | except asyncio.CancelledError: 18 | nonlocal canceled_raised 19 | canceled_raised = True 20 | raise 21 | 22 | with pytest.raises(asyncio.TimeoutError): 23 | async with timeout(0.01) as t: 24 | await long_running_task() 25 | assert t._loop is asyncio.get_event_loop() 26 | assert canceled_raised, "CancelledError was not raised" 27 | 28 | 29 | @pytest.mark.asyncio 30 | async def test_timeout_finish_in_time(): 31 | async def long_running_task(): 32 | await asyncio.sleep(0.01) 33 | return "done" 34 | 35 | async with timeout(0.1): 36 | resp = await long_running_task() 37 | assert resp == "done" 38 | 39 | 40 | @pytest.mark.asyncio 41 | async def test_timeout_disable(): 42 | async def long_running_task(): 43 | await asyncio.sleep(0.1) 44 | return "done" 45 | 46 | loop = asyncio.get_event_loop() 47 | t0 = loop.time() 48 | async with timeout(None): 49 | resp = await long_running_task() 50 | assert resp == "done" 51 | dt = loop.time() - t0 52 | assert 0.09 < dt < 0.13, dt 53 | 54 | 55 | @pytest.mark.asyncio 56 | async def test_timeout_is_none_no_schedule(): 57 | async with timeout(None) as cm: 58 | assert cm._timeout_handler is None 59 | assert cm.deadline is None 60 | 61 | 62 | def test_timeout_no_loop(): 63 | with pytest.raises(RuntimeError, match="no running event loop"): 64 | timeout(None) 65 | 66 | 67 | @pytest.mark.asyncio 68 | async def test_timeout_zero(): 69 | with pytest.raises(asyncio.TimeoutError): 70 | timeout(0) 71 | 72 | 73 | @pytest.mark.asyncio 74 | async def test_timeout_not_relevant_exception(): 75 | await asyncio.sleep(0) 76 | with pytest.raises(KeyError): 77 | async with timeout(0.1): 78 | raise KeyError 79 | 80 | 81 | @pytest.mark.asyncio 82 | async def test_timeout_canceled_error_is_not_converted_to_timeout(): 83 | await asyncio.sleep(0) 84 | with pytest.raises(asyncio.CancelledError): 85 | async with timeout(0.001): 86 | raise asyncio.CancelledError 87 | 88 | 89 | @pytest.mark.asyncio 90 | async def test_timeout_blocking_loop(): 91 | async def long_running_task(): 92 | time.sleep(0.1) 93 | return "done" 94 | 95 | async with timeout(0.01): 96 | result = await long_running_task() 97 | assert result == "done" 98 | 99 | 100 | @pytest.mark.asyncio 101 | async def test_for_race_conditions(): 102 | loop = asyncio.get_event_loop() 103 | fut = loop.create_future() 104 | loop.call_later(0.1, fut.set_result("done")) 105 | async with timeout(0.2): 106 | resp = await fut 107 | assert resp == "done" 108 | 109 | 110 | @pytest.mark.asyncio 111 | async def test_timeout_time(): 112 | foo_running = None 113 | loop = asyncio.get_event_loop() 114 | start = loop.time() 115 | with pytest.raises(asyncio.TimeoutError): 116 | async with timeout(0.1): 117 | foo_running = True 118 | try: 119 | await asyncio.sleep(0.2) 120 | finally: 121 | foo_running = False 122 | 123 | dt = loop.time() - start 124 | if not (0.09 < dt < 0.11) and os.environ.get("APPVEYOR"): 125 | pytest.xfail("appveyor sometimes is toooo sloooow") 126 | assert 0.09 < dt < 0.11 127 | assert not foo_running 128 | 129 | 130 | @pytest.mark.asyncio 131 | async def test_outer_coro_is_not_cancelled(): 132 | 133 | has_timeout = False 134 | 135 | async def outer(): 136 | nonlocal has_timeout 137 | try: 138 | async with timeout(0.001): 139 | await asyncio.sleep(1) 140 | except asyncio.TimeoutError: 141 | has_timeout = True 142 | 143 | task = asyncio.ensure_future(outer()) 144 | await task 145 | assert has_timeout 146 | assert not task.cancelled() 147 | assert task.done() 148 | 149 | 150 | @pytest.mark.asyncio 151 | async def test_cancel_outer_coro(): 152 | loop = asyncio.get_event_loop() 153 | fut = loop.create_future() 154 | 155 | async def outer(): 156 | fut.set_result(None) 157 | await asyncio.sleep(1) 158 | 159 | task = asyncio.ensure_future(outer()) 160 | await fut 161 | task.cancel() 162 | with pytest.raises(asyncio.CancelledError): 163 | await task 164 | assert task.cancelled() 165 | assert task.done() 166 | 167 | 168 | @pytest.mark.asyncio 169 | async def test_timeout_suppress_exception_chain(): 170 | with pytest.raises(asyncio.TimeoutError) as ctx: 171 | async with timeout(0.01): 172 | await asyncio.sleep(10) 173 | assert not ctx.value.__suppress_context__ 174 | 175 | 176 | @pytest.mark.asyncio 177 | async def test_timeout_expired(): 178 | with pytest.raises(asyncio.TimeoutError): 179 | async with timeout(0.01) as cm: 180 | await asyncio.sleep(10) 181 | assert cm.expired 182 | 183 | 184 | @pytest.mark.asyncio 185 | async def test_timeout_inner_timeout_error(): 186 | with pytest.raises(asyncio.TimeoutError): 187 | async with timeout(0.01) as cm: 188 | raise asyncio.TimeoutError 189 | assert not cm.expired 190 | 191 | 192 | @pytest.mark.asyncio 193 | async def test_timeout_inner_other_error(): 194 | class MyError(RuntimeError): 195 | pass 196 | 197 | with pytest.raises(MyError): 198 | async with timeout(0.01) as cm: 199 | raise MyError 200 | assert not cm.expired 201 | 202 | 203 | @pytest.mark.asyncio 204 | async def test_timeout_at(): 205 | loop = asyncio.get_event_loop() 206 | with pytest.raises(asyncio.TimeoutError): 207 | now = loop.time() 208 | async with timeout_at(now + 0.01) as cm: 209 | await asyncio.sleep(10) 210 | assert cm.expired 211 | 212 | 213 | @pytest.mark.asyncio 214 | async def test_timeout_at_not_fired(): 215 | loop = asyncio.get_event_loop() 216 | now = loop.time() 217 | async with timeout_at(now + 1) as cm: 218 | await asyncio.sleep(0) 219 | assert not cm.expired 220 | 221 | 222 | @pytest.mark.asyncio 223 | async def test_expired_after_rejecting(): 224 | t = timeout(10) 225 | assert not t.expired 226 | t.reject() 227 | assert not t.expired 228 | 229 | 230 | @pytest.mark.asyncio 231 | async def test_reject_finished(): 232 | async with timeout(10) as t: 233 | await asyncio.sleep(0) 234 | 235 | assert not t.expired 236 | with pytest.raises(RuntimeError, match="invalid state EXIT"): 237 | t.reject() 238 | 239 | 240 | @pytest.mark.asyncio 241 | async def test_expired_after_timeout(): 242 | with pytest.raises(asyncio.TimeoutError): 243 | async with timeout(0.01) as t: 244 | assert not t.expired 245 | await asyncio.sleep(10) 246 | assert t.expired 247 | 248 | 249 | @pytest.mark.asyncio 250 | async def test_deadline(): 251 | loop = asyncio.get_event_loop() 252 | t0 = loop.time() 253 | async with timeout(1) as cm: 254 | t1 = loop.time() 255 | assert t0 + 1 <= cm.deadline <= t1 + 1 256 | 257 | 258 | @pytest.mark.asyncio 259 | async def test_async_timeout(): 260 | with pytest.raises(asyncio.TimeoutError): 261 | async with timeout(0.01) as cm: 262 | await asyncio.sleep(10) 263 | assert cm.expired 264 | 265 | 266 | @pytest.mark.asyncio 267 | async def test_async_no_timeout(): 268 | async with timeout(1) as cm: 269 | await asyncio.sleep(0) 270 | assert not cm.expired 271 | 272 | 273 | @pytest.mark.asyncio 274 | async def test_shift_to(): 275 | loop = asyncio.get_event_loop() 276 | t0 = loop.time() 277 | async with timeout(1) as cm: 278 | t1 = loop.time() 279 | assert t0 + 1 <= cm.deadline <= t1 + 1 280 | cm.shift_to(t1 + 1) 281 | assert t1 + 1 <= cm.deadline <= t1 + 1.001 282 | 283 | 284 | @pytest.mark.asyncio 285 | async def test_shift_by(): 286 | loop = asyncio.get_event_loop() 287 | t0 = loop.time() 288 | async with timeout(1) as cm: 289 | t1 = loop.time() 290 | assert t0 + 1 <= cm.deadline <= t1 + 1 291 | cm.shift_by(1) 292 | assert t1 + 0.999 <= cm.deadline <= t1 + 1.001 293 | 294 | 295 | @pytest.mark.asyncio 296 | async def test_shift_by_negative_expired(): 297 | async with timeout(1) as cm: 298 | with pytest.raises(asyncio.CancelledError): 299 | cm.shift_by(-1) 300 | 301 | 302 | @pytest.mark.asyncio 303 | async def test_shift_by_expired(): 304 | async with timeout(0.001) as cm: 305 | with pytest.raises(asyncio.CancelledError): 306 | await asyncio.sleep(10) 307 | with pytest.raises(RuntimeError, match="cannot reschedule expired timeout"): 308 | await cm.shift_by(10) 309 | 310 | 311 | @pytest.mark.asyncio 312 | async def test_shift_to_expired(): 313 | loop = asyncio.get_event_loop() 314 | t0 = loop.time() 315 | async with timeout_at(t0 + 0.001) as cm: 316 | with pytest.raises(asyncio.CancelledError): 317 | await asyncio.sleep(10) 318 | with pytest.raises(RuntimeError, match="cannot reschedule expired timeout"): 319 | await cm.shift_to(t0 + 10) 320 | 321 | 322 | @pytest.mark.asyncio 323 | async def test_shift_by_after_cm_exit(): 324 | async with timeout(1) as cm: 325 | await asyncio.sleep(0) 326 | with pytest.raises( 327 | RuntimeError, match="cannot reschedule after exit from context manager" 328 | ): 329 | cm.shift_by(1) 330 | 331 | 332 | @pytest.mark.asyncio 333 | async def test_enter_twice(): 334 | async with timeout(10) as t: 335 | await asyncio.sleep(0) 336 | 337 | with pytest.raises(RuntimeError, match="invalid state EXIT"): 338 | async with t: 339 | await asyncio.sleep(0) 340 | 341 | 342 | @pytest.mark.asyncio 343 | async def test_deprecated_with(): 344 | with pytest.warns(DeprecationWarning): 345 | with timeout(1): 346 | await asyncio.sleep(0) 347 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------