Skip to content

Instantly share code, notes, and snippets.

@heyman
Last active May 4, 2020 21:38
Show Gist options
  • Save heyman/fdfe763be317191962e202481ba9f4cd to your computer and use it in GitHub Desktop.
Save heyman/fdfe763be317191962e202481ba9f4cd to your computer and use it in GitHub Desktop.
Context manager / Decorator for adding manual Locust stats entries
"""
Usage examples:
# As context manager:
with manual_report("stats_entry_name"):
# do stuff
# As a decorator for tasks:
@task
@manual_report
def my_task(self):
time.sleep(random.random())
"""
from contextlib import contextmanager
from time import time
from locust import events
@contextmanager
def _manual_report(name):
start_time = time()
try:
yield
except Exception as e:
events.request_failure.fire(
request_type="manual",
name=name,
response_time=(time()-start_time) * 1000,
response_length=0,
exception=e,
)
raise
else:
events.request_success.fire(
request_type="manual",
name=name,
response_time=(time()-start_time) * 1000,
response_length=0,
)
def manual_report(name_or_func):
if callable(name_or_func):
# used as decorator without name argument specified
return _manual_report(name_or_func.__name__)(name_or_func)
else:
return _manual_report(name_or_func)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment