-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocustfile.py
89 lines (72 loc) · 2.61 KB
/
locustfile.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
79
80
81
82
83
84
85
86
87
88
89
import time
import random
import string
import websocket
from locust import HttpUser, TaskSet, task, between, User
class WebSocketClient:
def __init__(self, host):
self.host = host
self.ws = None
def connect(self):
self.ws = websocket.create_connection(self.host)
def send(self, message):
self.ws.send(message)
def receive(self):
return self.ws.recv()
def close(self):
if self.ws:
self.ws.close()
class WebSocketTaskSet(TaskSet):
def __init__(self, parent):
super().__init__(parent)
self.ws_client = None
def on_start(self):
# Generate random session_id
length = 12
session_id = ''.join(random.choices(string.ascii_letters + string.digits, k=length))
# Connect
self.ws_client = WebSocketClient(f"ws://127.0.0.1:1865/ws/{session_id}")
self.ws_client.connect()
def on_stop(self):
self.ws_client.close()
@task
def send_message(self):
start_time = time.time()
try:
self.ws_client.send('{"text": "Hello"}')
# Read until we get a response without "chat_token"
while True:
response = self.ws_client.receive()
if "chat_token" not in response:
break
# Decide success or failure
if "chat" in response:
# Mark as success: pass `exception=None`
self.user.environment.events.request.fire(
request_type="websocket",
name="send_message",
response_time=(time.time() - start_time) * 1000, # ms
response_length=len(response),
exception=None
)
else:
# Mark as failure: pass an Exception
self.user.environment.events.request.fire(
request_type="websocket",
name="send_message",
response_time=(time.time() - start_time) * 1000,
response_length=len(response),
exception=Exception("No 'chat' in response")
)
except Exception as e:
# If anything goes wrong, also mark as failure
self.user.environment.events.request.fire(
request_type="websocket",
name="send_message",
response_time=(time.time() - start_time) * 1000,
response_length=0,
exception=e
)
class MyWebSocketUser(HttpUser):
tasks = [WebSocketTaskSet]
wait_time = between(5, 10)