Skip to content

Commit 4b45c20

Browse files
committed
@mocketize as TestCase class decorator
1 parent 713ccd6 commit 4b45c20

File tree

1 file changed

+58
-3
lines changed

1 file changed

+58
-3
lines changed

mocket/decorators/mocketizer.py

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
from __future__ import annotations
2+
3+
import functools
4+
import inspect
5+
16
from mocket.mocket import Mocket
27
from mocket.mode import MocketMode
38
from mocket.utils import get_mocketize
@@ -60,7 +65,7 @@ def check_and_call(self, method_name):
6065
def factory(test, truesocket_recording_dir, strict_mode, strict_mode_allowed, args):
6166
instance = args[0] if args else None
6267
namespace = None
63-
if truesocket_recording_dir:
68+
if truesocket_recording_dir and instance:
6469
namespace = ".".join(
6570
(
6671
instance.__class__.__module__,
@@ -78,7 +83,7 @@ def factory(test, truesocket_recording_dir, strict_mode, strict_mode_allowed, ar
7883
)
7984

8085

81-
def wrapper(
86+
def _function_wrapper(
8287
test,
8388
truesocket_recording_dir=None,
8489
strict_mode=False,
@@ -92,4 +97,54 @@ def wrapper(
9297
return test(*args, **kwargs)
9398

9499

95-
mocketize = get_mocketize(wrapper)
100+
_function_mocketize = get_mocketize(_function_wrapper)
101+
102+
103+
def _class_decorator_factory(**options):
104+
def decorator(cls):
105+
orig_setup = getattr(cls, "setUp", lambda self, *a, **kw: None)
106+
orig_td = getattr(cls, "tearDown", lambda self, *a, **kw: None)
107+
use_add_cleanup = hasattr(cls, "addCleanup")
108+
109+
def setUp(self, *a, **kw):
110+
ctx = Mocketizer(instance=self, **options)
111+
ctx.enter()
112+
if use_add_cleanup:
113+
self.addCleanup(ctx.exit)
114+
else:
115+
self.__mocket_ctx = ctx
116+
orig_setup(self, *a, **kw)
117+
118+
cls.setUp = functools.wraps(orig_setup)(setUp)
119+
120+
if not use_add_cleanup:
121+
122+
def tearDown(self, *a, **kw):
123+
try:
124+
orig_td(self, *a, **kw)
125+
finally:
126+
if hasattr(self, "__mocket_ctx"):
127+
self.__mocket_ctx.exit()
128+
129+
cls.tearDown = functools.wraps(orig_td)(tearDown)
130+
131+
return cls
132+
133+
return decorator
134+
135+
136+
def mocketize(*dargs, **dkwargs):
137+
# bare @mocketize
138+
if dargs and len(dargs) == 1 and callable(dargs[0]) and not dkwargs:
139+
target = dargs[0]
140+
if inspect.isclass(target):
141+
return _class_decorator_factory()(target)
142+
return _function_mocketize(target)
143+
144+
# @mocketize(...)
145+
def real_decorator(target):
146+
if inspect.isclass(target):
147+
return _class_decorator_factory(**dkwargs)(target)
148+
return _function_mocketize(**dkwargs)(target)
149+
150+
return real_decorator

0 commit comments

Comments
 (0)