diff --git a/tests/unit/base/test_deprecation.py b/tests/unit/base/test_deprecation.py new file mode 100644 index 0000000000..a502696ea4 --- /dev/null +++ b/tests/unit/base/test_deprecation.py @@ -0,0 +1,43 @@ +import unittest +import warnings + +from twilio.base.obsolete import deprecated_method + + +class DeprecatedMethodTest(unittest.TestCase): + + def test_deprecation_decorator(self): + + @deprecated_method() + def old_method(): + return True + + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.simplefilter("always") + # Call function that should raise a warning, but still execute + self.assertTrue(old_method()) + if len(caught_warnings): + self.assertEqual( + str(caught_warnings[0].message), + 'Function method .old_method() is being deprecated' + ) + assert issubclass(caught_warnings[0].category, DeprecationWarning) + + def test_deprecation_decorator_with_new_method(self): + + @deprecated_method('new_method') + def old_method(): + return True + + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.simplefilter("always") + + # Call function that should raise a warning, but still execute + self.assertTrue(old_method()) + + if len(caught_warnings): + self.assertEqual( + str(caught_warnings[0].message), + 'Function method .old_method() is being deprecated in favor of .new_method()' + ) + assert issubclass(caught_warnings[0].category, DeprecationWarning) diff --git a/twilio/base/obsolete.py b/twilio/base/obsolete.py index 6c89ba86dd..2c1057b69a 100644 --- a/twilio/base/obsolete.py +++ b/twilio/base/obsolete.py @@ -21,3 +21,23 @@ def new_func(*args, **kwargs): ) return new_func + + +def deprecated_method(new_func=None): + """ + This is a decorator which can be used to mark deprecated methods. + It will report in a DeprecationWarning being emitted to stderr when the deprecated method is used. + """ + + def deprecated_method_wrapper(func): + + @functools.wraps(func) + def wrapper(*args, **kwargs): + msg = 'Function method .{}() is being deprecated'.format(func.__name__) + msg += ' in favor of .{}()'.format(new_func) if new_func else '' + warnings.warn(msg, DeprecationWarning) + return func(*args, **kwargs) + + return wrapper + + return deprecated_method_wrapper