forked from locustio/locust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanual_stats_reporting.py
78 lines (63 loc) · 2.09 KB
/
manual_stats_reporting.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""
Example of a manual_report() function that can be used either as a context manager
(with statement), or a decorator, to manually add entries to Locust's statistics.
Usage as a context manager:
with manual_report("stats entry name"):
# Run time of this block will be reported under a stats entry called "stats entry name"
# do stuff here, if an Exception is raised, it'll be reported as a failure
Usage as a decorator:
@task
@manual_report
def my_task(self):
# The run time of this task will be reported under a stats entry called "my task" (type "manual").
# If an Exception is raised, it'll be reported as a failure
"""
from locust import User, constant, events, task
import random
from contextlib import ContextDecorator, contextmanager
from time import sleep, time
@contextmanager
def _manual_report(name):
start_time = time()
try:
yield
except Exception as e:
events.request.fire(
request_type="manual",
name=name,
response_time=(time() - start_time) * 1000,
response_length=0,
exception=e,
)
raise
else:
events.request.fire(
request_type="manual",
name=name,
response_time=(time() - start_time) * 1000,
response_length=0,
exception=None,
)
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)
class MyUser(User):
wait_time = constant(1)
@task
def successful_task(self):
with manual_report("successful_task"):
sleep(random.random())
@task
@manual_report
def decorator_test(self):
if random.random() > 0.5:
raise Exception("decorator_task failed")
sleep(random.random())
@task
def failing_task(self):
with manual_report("failing_task"):
sleep(random.random())
raise Exception("Oh nooes!")