Skip to content

Commit

Permalink
Moved test decorator to separate file
Browse files Browse the repository at this point in the history
  • Loading branch information
sacOO7 committed Oct 4, 2023
1 parent 031d11f commit a385840
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 34 deletions.
33 changes: 0 additions & 33 deletions ably/executer/decorator.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,6 @@
import functools
from asyncio import events

from ably.executer.eventloop import AppEventLoop


def force_sync(fn):
'''
Forces async function to be used as sync function.
Blocks execution of caller till result is returned.
This decorator should only be used on async methods/coroutines.
'''
import asyncio

@functools.wraps(fn)
def wrapper(*args, **kwargs):
caller_eventloop = None
try:
caller_eventloop: events = asyncio.get_running_loop()
except Exception:
pass
app_loop: events = AppEventLoop.get_global().loop

res = fn(*args, **kwargs)
if asyncio.iscoroutine(res):
# Handle calls from app eventloop on the same loop, return awaitable
if caller_eventloop is not None and caller_eventloop == app_loop:
return res

# Block the caller till result is returned
future = asyncio.run_coroutine_threadsafe(res, app_loop)
return future.result()
return res

return wrapper


def optional_sync(fn):
'''
Expand Down
35 changes: 35 additions & 0 deletions test/ably/decorator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import functools
from asyncio import events

from ably.executer.eventloop import AppEventLoop


def force_sync(fn):
'''
Forces async function to be used as sync function.
Blocks execution of caller till result is returned.
This decorator should only be used on async methods/coroutines.
'''
import asyncio

@functools.wraps(fn)
def wrapper(*args, **kwargs):
caller_eventloop = None
try:
caller_eventloop: events = asyncio.get_running_loop()
except Exception:
pass
app_loop: events = AppEventLoop.get_global().loop

res = fn(*args, **kwargs)
if asyncio.iscoroutine(res):
# Handle calls from app eventloop on the same loop, return awaitable
if caller_eventloop is not None and caller_eventloop == app_loop:
return res

# Block the caller till result is returned
future = asyncio.run_coroutine_threadsafe(res, app_loop)
return future.result()
return res

return wrapper
2 changes: 1 addition & 1 deletion test/ably/testapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
import os
import logging

from ably.executer.decorator import force_sync
from ably.rest.rest import AblyRest
from ably.types.capability import Capability
from ably.types.options import Options
from ably.util.exceptions import AblyException
from ably.realtime.realtime import AblyRealtime
from test.ably.decorator import force_sync

log = logging.getLogger(__name__)

Expand Down

0 comments on commit a385840

Please sign in to comment.