Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gracefully handle exceptions in event listeners #1462

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion locust/event.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import logging
from .log import unhandled_greenlet_exception

class EventHook(object):
"""
Simple event class used to provide hooks for different types of events in Locust.
Expand Down Expand Up @@ -30,7 +33,11 @@ def fire(self, *, reverse=False, **kwargs):
else:
handlers = self._handlers
for handler in handlers:
handler(**kwargs)
try:
handler(**kwargs)
except Exception as e:
logging.error("Uncaught exception in event handler: %s", e)
unhandled_greenlet_exception = True


class Events:
Expand Down
24 changes: 24 additions & 0 deletions locust/test/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -1241,3 +1241,27 @@ def trigger(self):
self.fail("Got Timeout exception, runner must have hung somehow.")
finally:
timeout.cancel()

def test_gracefully_handle_exceptions_in_listener(self):
class MyUser(User):
wait_time = constant(1)
@task
def my_task(self):
pass

test_stop_run = [0]
environment = Environment(user_classes=[User])
def on_test_stop_ok(*args, **kwargs):
test_stop_run[0] += 1
def on_test_stop_fail(*args, **kwargs):
assert 0

environment.events.test_stop.add_listener(on_test_stop_ok)
environment.events.test_stop.add_listener(on_test_stop_fail)
environment.events.test_stop.add_listener(on_test_stop_ok)

runner = LocalRunner(environment)
runner.start(user_count=3, hatch_rate=3, wait=False)
self.assertEqual(0, test_stop_run[0])
runner.stop()
self.assertEqual(2, test_stop_run[0])