Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
7 changes: 6 additions & 1 deletion asgiref/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,10 +426,15 @@ def __init__(
executor: Optional["ThreadPoolExecutor"] = None,
context: Optional[contextvars.Context] = None,
) -> None:
func_call = getattr(func, "__call__", func)
if (
not callable(func)
or iscoroutinefunction(func)
or iscoroutinefunction(getattr(func, "__call__", func))
or iscoroutinefunction(func_call)
or inspect.isgeneratorfunction(func)
or inspect.isgeneratorfunction(func_call)
or inspect.isasyncgenfunction(func)
or inspect.isasyncgenfunction(func_call)
):
raise TypeError("sync_to_async can only be applied to sync functions.")

Expand Down
27 changes: 27 additions & 0 deletions tests/test_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,22 @@ def test_sync_to_async_fail_non_function():
)


def test_sync_to_async_fail_generator_function():
"""
sync_to_async raises a TypeError when applied to a generator function.
"""

def test_function():
yield 1

with pytest.raises(TypeError) as excinfo:
sync_to_async(test_function)

assert excinfo.value.args == (
"sync_to_async can only be applied to sync functions.",
)


@pytest.mark.asyncio
async def test_sync_to_async_fail_async():
"""
Expand Down Expand Up @@ -120,6 +136,17 @@ async def __call__(self):
sync_to_async(CallableClass())


def test_sync_to_async_raises_typeerror_for_generator_callable_instance():
class CallableClass:
def __call__(self):
yield 1

with pytest.raises(
TypeError, match="sync_to_async can only be applied to sync functions."
):
sync_to_async(CallableClass())


@pytest.mark.asyncio
async def test_sync_to_async_decorator():
"""
Expand Down