Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added detection for Twisted #10

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Used isInIOThread to detect Twisted
agronholm committed Dec 28, 2019

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
commit 4c01e9b370d11f657627af9f34b69e1dcf33fce1
19 changes: 7 additions & 12 deletions sniffio/_impl.py
Original file line number Diff line number Diff line change
@@ -55,6 +55,13 @@ async def generic_sleep(seconds):
if value is not None:
return value

# 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"

# Sniff for curio (for now)
if 'curio' in sys.modules:
from curio.meta import curio_running
@@ -78,18 +85,6 @@ async def generic_sleep(seconds):
except RuntimeError:
pass

if "twisted.internet" in sys.modules:
from traceback import walk_stack
from twisted.internet import reactor

# Check if the reactor is running in this thread
if reactor.running:
for frame, lineno in walk_stack(sys._getframe(2)):
if frame.f_code.co_name == 'run':
if frame.f_code.co_filename.endswith(
'twisted/internet/base.py'):
return "twisted"

raise AsyncLibraryNotFoundError(
"unknown async library, or not in async context"
)
23 changes: 21 additions & 2 deletions sniffio/_tests/test_sniffio.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sys
import warnings

import pytest
@@ -66,10 +67,28 @@ async def this_is_curio():
current_async_library()


def test_twisted():
@pytest.fixture(params=['select', 'asyncio'])
def reactor(request):
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
from twisted.internet import reactor
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()