diff --git a/newsfragments/10.feature.rst b/newsfragments/10.feature.rst new file mode 100644 index 0000000..1749fa0 --- /dev/null +++ b/newsfragments/10.feature.rst @@ -0,0 +1,3 @@ +Sniffio can now detect Twisted_. + +.. _Twisted: https://twistedmatrix.com/trac/ diff --git a/sniffio/_impl.py b/sniffio/_impl.py index c1a7bbf..828debe 100644 --- a/sniffio/_impl.py +++ b/sniffio/_impl.py @@ -89,6 +89,13 @@ async def generic_sleep(seconds): from curio.meta import curio_running if curio_running(): return 'curio' + + # Sniff for Twisted + if 'twisted' in sys.modules: + from twisted.internet import reactor + from twisted.python.threadable import isInIOThread + if reactor.running and isInIOThread(): + return "twisted" raise AsyncLibraryNotFoundError( "unknown async library, or not in async context" diff --git a/sniffio/_tests/test_sniffio.py b/sniffio/_tests/test_sniffio.py index 984c8c0..59159e6 100644 --- a/sniffio/_tests/test_sniffio.py +++ b/sniffio/_tests/test_sniffio.py @@ -1,5 +1,6 @@ import os import sys +import warnings import pytest @@ -82,3 +83,46 @@ async def this_is_curio(): with pytest.raises(AsyncLibraryNotFoundError): current_async_library() + + +@pytest.fixture(params=['select', 'asyncio']) +def reactor(request): + with warnings.catch_warnings(): + warnings.simplefilter('ignore', DeprecationWarning) + from twisted.internet import asyncioreactor, selectreactor + + if request.param == 'asyncio': + import asyncio + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + asyncioreactor.install(loop) + yield + loop.close() + else: + selectreactor.install() + yield + + del sys.modules['twisted.internet.reactor'] + + +def test_twisted(reactor): + from twisted.internet import reactor + + with pytest.raises(AsyncLibraryNotFoundError): + current_async_library() + + ran = [] + + def this_is_twisted(): + try: + assert current_async_library() == "twisted" + ran.append(True) + finally: + reactor.stop() + + reactor.callWhenRunning(this_is_twisted) + reactor.run() + assert ran == [True] + + with pytest.raises(AsyncLibraryNotFoundError): + current_async_library() diff --git a/test-requirements.txt b/test-requirements.txt index 6742196..29af8d8 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -1,3 +1,4 @@ pytest pytest-cov curio +twisted