Skip to content

Instantly share code, notes, and snippets.

@pgjones
Created February 2, 2019 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pgjones/6ef0ea3b8433145a70a246bb18655eed to your computer and use it in GitHub Desktop.
Save pgjones/6ef0ea3b8433145a70a246bb18655eed to your computer and use it in GitHub Desktop.
import asyncio
import inspect
from functools import partial
import pytest
scope = object()
receive = object()
send = object()
class App:
def __init__(self, scope):
self.scope = scope
async def __call__(self, receive, send):
return self.scope, receive, send
class ClassOldDouble:
def __init__(self):
pass
async def asgi(self, receive, send):
return self.scope, receive, send
def __call__(self, scope):
self.scope = scope
return self.asgi
def old_double(scope):
async def _inner(scope, receive, send):
return scope, receive, send
return partial(_inner, scope)
class NewClass:
async def __call__(self, scope, receive, send):
return scope, receive, send
async def new_def(scope, receive, send):
return scope, receive, send
@pytest.mark.parametrize("app", [App, ClassOldDouble(), old_double, NewClass(), new_def])
def test_asgi_interface(app):
double_call = None
is_class = inspect.isclass(app)
is_class_instance = inspect.isclass(type(app)) and not inspect.isfunction(app)
instance_with_async_call = is_class_instance and inspect.iscoroutinefunction(app.__call__)
instance_with_sync_call = is_class_instance and not inspect.iscoroutinefunction(app.__call__)
is_async_function = inspect.iscoroutinefunction(app)
is_sync_function = inspect.isfunction(app) and not inspect.iscoroutinefunction(app)
if is_class:
double_call = True
elif instance_with_async_call:
double_call = False
elif instance_with_sync_call:
double_call = True
elif is_async_function:
double_call = False
elif is_sync_function:
double_call = True
assert double_call is not None
if double_call:
asgi_instance = app(scope)
result = asyncio.run(asgi_instance(receive, send))
else:
result = asyncio.run(app(scope, receive, send))
assert result[0] is scope
assert result[1] is receive
assert result[2] is send
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment