Skip to content

Commit

Permalink
Add activate_async decorator (#48)
Browse files Browse the repository at this point in the history
* Add activate_async decorator
* make activate_async python 3.4 compatible
* unify the import statement
  • Loading branch information
sky-code authored and h2non committed Oct 19, 2017
1 parent 1a89fff commit 25dd10c
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 5 deletions.
30 changes: 30 additions & 0 deletions pook/activate_async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import functools
from asyncio import iscoroutinefunction, coroutine


def activate_async(fn, _engine):
"""
Async version of activate decorator
Arguments:
fn (function): function that be wrapped by decorator.
_engine (Engine): pook engine instance
Returns:
function: decorator wrapper function.
"""
@functools.wraps(fn)
@coroutine
def wrapper(*args, **kw):
_engine.activate()
try:
if iscoroutinefunction(fn):
yield from fn(*args, **kw) # noqa
else:
fn(*args, **kw)
except Exception as err:
raise err
finally:
_engine.disable()

return wrapper
22 changes: 17 additions & 5 deletions pook/api.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
import re
import functools
from inspect import isfunction
import re
from contextlib import contextmanager
from .engine import Engine
from inspect import isfunction

from .engine import Engine
from .matcher import MatcherEngine
from .mock import Mock
from .mock_engine import MockEngine
from .request import Request
from .response import Response
from .matcher import MatcherEngine
from .mock_engine import MockEngine

try:
from asyncio import iscoroutinefunction
except ImportError:
iscoroutinefunction = None
if iscoroutinefunction is not None:
from .activate_async import activate_async
else:
activate_async = None

# Public API symbols to export
__all__ = (
Expand Down Expand Up @@ -96,6 +105,9 @@ def test_request():
_engine.activate()
return None

if iscoroutinefunction is not None and iscoroutinefunction(fn):
return activate_async(fn, _engine)

@functools.wraps(fn)
def wrapper(*args, **kw):
_engine.activate()
Expand Down

0 comments on commit 25dd10c

Please sign in to comment.