Skip to content

Instantly share code, notes, and snippets.

@agronholm
Created August 9, 2018 19:36
Show Gist options
  • Save agronholm/6eb11f9c27c01e1a9d1915a37315ca23 to your computer and use it in GitHub Desktop.
Save agronholm/6eb11f9c27c01e1a9d1915a37315ca23 to your computer and use it in GitHub Desktop.
SQLAlchemy asyncio threading fixture
@pytest.fixture(scope='session', autouse=True)
def sqlalchemy_thread_check(connection):
"""Raise an exception is SQL is executed in the event loop thread in the application code."""
def check_thread(*args):
if asyncio._get_running_loop():
frames = [f for f in extract_stack()[:-1] if 'ebserver' in f.filename]
if frames:
raise RuntimeError(f'SQL executed in the event loop thread '
f'(from {frames[-1].filename}:{frames[-1].lineno})')
for event in 'before_execute', 'before_cursor_execute':
listen(connection, event, check_thread)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment