Created
May 28, 2019 00:33
-
-
Save takwas/a0623623554f04434c46f05ea64df950 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 log(utf8_string, tags): | |
# do some logging | |
pass | |
def log_on_exception(*tags): | |
"""Decorate a function to log any exception it raises. | |
This decorator provides functionality to log a message | |
when an exception is raised from within the decorated | |
function. | |
:param tags: a sequence of tags | |
:return: the result of the function it wraps | |
""" | |
def func_decor(func): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
try: | |
func_result = func(*args, **kwargs) | |
except Exception as e: | |
error_msg = getattr(e, 'message', repr(e)) | |
log(error_msg, tags) | |
# re-raise exception | |
raise | |
return func_result | |
return wrapper | |
return func_decor |
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
import unittest | |
from hotjar import log_on_exception | |
@log_on_exception('tag1', 'tag2') | |
def raising_func(): | |
raise NotImplementedError | |
def normal_func(): | |
return 'random value' | |
class HotjarTestCase(unittest.TestCase): | |
def test_log_on_exception_raise(self): | |
with self.assertRaises(NotImplementedError): | |
raising_func() | |
def test_log_on_exception_return_value(self): | |
"""Ensure that the decorator's return value is | |
that of the function assuming no error is raised.""" | |
undecorated_func_result = normal_func() | |
decorated_func_result = log_on_exception('tag1', 'tag2')(normal_func)() | |
self.assertEqual(undecorated_func_result, decorated_func_result) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment