Last active
July 15, 2020 11:33
-
-
Save cbpygit/dec8c224d0ef9ea7690882c612c67080 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import wraps | |
def allow_simulate_exception(exception_class=Exception): | |
def _allow_simulate_exception(method): | |
"""Decorator that allows to raise an exception """ | |
@wraps(method) | |
def _raise_exception_if_method_name_fits(self, *method_args, | |
**method_kwargs): | |
if method.__qualname__.split('.')[-1] == self.raise_exception_in_method: | |
raise exception_class( | |
f'Simulated exception in method ' | |
f'{self.raise_exception_in_method}.') | |
method_output = method(self, *method_args, **method_kwargs) | |
return method_output | |
return _raise_exception_if_method_name_fits | |
return _allow_simulate_exception | |
class Foo: | |
def __init__(self, raise_exception_in_method=None): | |
self.raise_exception_in_method = raise_exception_in_method | |
@allow_simulate_exception(RuntimeError) | |
def bar(self, print_this='hello'): | |
print(print_this) | |
foo_no_exception = Foo() | |
foo_no_exception.bar() | |
foo_with_exception = Foo(raise_exception_in_method='bar') | |
foo_with_exception.bar() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment