Skip to content

Commit a8bce72

Browse files
committed
Update retry decorator to allow decorating functions and staticmethods
Update `retry` to raise unhandled exceptions with unit test coverage
1 parent 92d31bc commit a8bce72

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

neon_mq_connector/utils/connection_utils.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
2626
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
2727
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28+
import inspect
2829
import logging
2930
import time
3031

@@ -86,7 +87,11 @@ def retry(callback_on_exceeded: Union[str, Callable] = None,
8687
callback_on_exceeded_args = []
8788

8889
def decorator(function):
89-
def wrapper(self, *args, **kwargs):
90+
def wrapper(*args, **kwargs):
91+
signature = inspect.signature(function).parameters
92+
self = args[0] if 'self' in signature else None
93+
if self:
94+
args = args[1:]
9095
with_self = use_self and self
9196
num_attempts = 1
9297
error_body = f"{function.__name__}(args={args}, kwargs={kwargs})"
@@ -137,6 +142,9 @@ def wrapper(self, *args, **kwargs):
137142
*callback_on_exceeded_args)
138143
elif isinstance(callback_on_exceeded, Callable):
139144
return callback_on_exceeded(*callback_on_exceeded_args)
145+
else:
146+
raise RuntimeError(f"Ran out of retries for {function}")
147+
140148
return wrapper
141149
return decorator
142150

tests/test_utils.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,16 @@ def test_retry(self):
304304
self.assertFalse(outcome)
305305
self.assertEqual(3, self.counter)
306306

307+
# Retry raises exception
308+
@retry(num_retries=1)
309+
def _retry_fails():
310+
raise Exception("This method is supposed to fail")
311+
312+
with self.assertRaises(Exception) as e:
313+
_retry_fails()
314+
self.assertIsInstance(e.exception, RuntimeError)
315+
self.assertIn("_retry_fails", repr(e.exception))
316+
307317
def test_wait_for_mq_startup(self):
308318
self.assertTrue(wait_for_mq_startup("mq.neonaiservices.com", 5672))
309319
self.assertFalse(wait_for_mq_startup("www.neon.ai", 5672, 1))

0 commit comments

Comments
 (0)