-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.py
More file actions
327 lines (280 loc) · 10.3 KB
/
Copy pathscript.py
File metadata and controls
327 lines (280 loc) · 10.3 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import asyncio
import aiohttp
import csv
import time
import json
import random
import string
from tqdm import tqdm
import argparse
from collections import defaultdict
from typing import List, Dict, Any, DefaultDict, Optional, Union
from jsonpath_ng import parse
from termgraph import termgraph as tg
def generate_random_string(length: int = 10) -> str:
return "".join(random.choices(string.ascii_letters + string.digits, k=length))
def generate_random_value(template: str) -> str:
if template == "{{random_string}}":
return generate_random_string()
elif template == "{{random_int}}":
return str(random.randint(1, 1000000))
elif template == "{{random_float}}":
return f"{random.uniform(0, 1000):.2f}"
else:
return template
def generate_json_body(template: Dict[str, Any]) -> Dict[str, Any]:
return {
k: generate_random_value(v) if isinstance(v, str) else v
for k, v in template.items()
}
def extract_json_values(
json_data: Dict[str, Any], json_paths: List[str]
) -> Dict[str, Any]:
extracted_values = {}
for path in json_paths:
jsonpath_expr = parse(path)
matches = [match.value for match in jsonpath_expr.find(json_data)]
extracted_values[path] = matches[0] if matches else None
return extracted_values
async def make_request(
session: aiohttp.ClientSession,
url: str,
method: str,
json_template: Optional[Dict[str, Any]],
json_paths: List[str],
semaphore: Optional[asyncio.Semaphore] = None,
) -> Dict[str, Any]:
start_time = time.time()
try:
json_body = generate_json_body(json_template) if json_template else None
if semaphore:
async with semaphore:
if method == "GET":
async with session.get(url) as response:
elapsed = time.time() - start_time
content = await response.text()
elif method == "POST":
async with session.post(url, json=json_body) as response:
elapsed = time.time() - start_time
content = await response.text()
else:
raise ValueError(f"Unsupported HTTP method: {method}")
else:
if method == "GET":
async with session.get(url) as response:
elapsed = time.time() - start_time
content = await response.text()
elif method == "POST":
async with session.post(url, json=json_body) as response:
elapsed = time.time() - start_time
content = await response.text()
else:
raise ValueError(f"Unsupported HTTP method: {method}")
try:
json_response = json.loads(content)
extracted_values = extract_json_values(json_response, json_paths)
except json.JSONDecodeError:
extracted_values = {path: None for path in json_paths}
return {
"url": url,
"method": method,
"status": response.status,
"latency": elapsed,
"request": str(response.request_info),
"request_body": json.dumps(json_body) if json_body else "",
"response": content,
**extracted_values,
}
except Exception as e:
return {
"url": url,
"method": method,
"status": "Error",
"latency": time.time() - start_time,
"request": url,
"request_body": json.dumps(json_body) if json_body else "",
"response": str(e),
**{path: None for path in json_paths},
}
async def pre_check(
url: str,
method: str,
json_template: Optional[Dict[str, Any]],
json_paths: List[str],
) -> Dict[str, Any]:
async with aiohttp.ClientSession() as session:
result = await make_request(session, url, method, json_template, json_paths)
return result
async def load_test(
urls: List[str],
method: str,
json_template: Optional[Dict[str, Any]],
json_paths: List[str],
rate_limit: int,
total_requests: int,
) -> List[Dict[str, Any]]:
results: List[Dict[str, Any]] = []
semaphore = asyncio.Semaphore(rate_limit)
async with aiohttp.ClientSession() as session:
tasks: List[asyncio.Task] = []
with tqdm(total=total_requests, desc="Requests", unit="req") as pbar:
for i in range(total_requests):
url = urls[i % len(urls)]
task = asyncio.create_task(
make_request(
session, url, method, json_template, json_paths, semaphore
)
)
task.add_done_callback(lambda t: results.append(t.result()))
task.add_done_callback(lambda _: pbar.update(1))
tasks.append(task)
if i < total_requests - 1:
await asyncio.sleep(1 / rate_limit) # Rate limiting
await asyncio.gather(*tasks)
return results
def write_report(
results: List[Dict[str, Any]], output_file: str, json_paths: List[str]
) -> None:
fieldnames = [
"url",
"method",
"status",
"latency",
"request",
"request_body",
"response",
] + json_paths
with open(output_file, "w", newline="") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for result in results:
writer.writerow(result)
def create_latency_chart(results: List[Dict[str, Any]]) -> None:
latencies = [result["latency"] for result in results]
# Create latency ranges
ranges = [
(0, 0.1),
(0.1, 0.25),
(0.25, 0.5),
(0.5, 0.75),
(0.75, 1),
(1, 1.5),
(1.5, 2),
(2, 3),
(3, 5),
(5, float("inf")),
]
# Count latencies in each range
counts = [sum(1 for l in latencies if r[0] <= l < r[1]) for r in ranges]
# Prepare data for termgraph
data = [
[f"{r[0]}-{r[1] if r[1] != float('inf') else '5+'}s", count]
for r, count in zip(ranges, counts)
if count > 0
]
# Chart labels
labels = [item[0] for item in data]
data = [item[1:] for item in data]
# Additional args for termgraph
args = {
"stacked": False,
"vertical": False,
"width": 50,
"format": "{:<5.0f}",
"suffix": "",
"no_labels": False,
"no_values": False,
"histogram": "",
}
print("\nLatency Distribution:")
tg.chart(colors=["blue"], data=data, args=args, labels=labels)
def print_summary(results: List[Dict[str, Any]]) -> None:
status_counts: DefaultDict[Any, int] = defaultdict(int)
method_counts: DefaultDict[str, int] = defaultdict(int)
total_latency = 0.0
max_latency = 0.0
min_latency = float("inf")
for result in results:
status_counts[result["status"]] += 1
method_counts[result["method"]] += 1
latency = result["latency"]
total_latency += latency
max_latency = max(max_latency, latency)
min_latency = min(min_latency, latency)
print("\nSummary:")
print(f"Total requests: {len(results)}")
print(f"Average latency: {total_latency / len(results):.2f} seconds")
print(f"Min latency: {min_latency:.2f} seconds")
print(f"Max latency: {max_latency:.2f} seconds")
print("\nMethod distribution:")
for method, count in method_counts.items():
print(f" {method}: {count}")
print("\nStatus code distribution:")
for status, count in status_counts.items():
print(f" {status}: {count}")
# Add latency chart
create_latency_chart(results)
async def main() -> None:
parser = argparse.ArgumentParser(
description="Rate-limited HTTP load testing script"
)
parser.add_argument("urls", nargs="+", help="URLs to test (can provide multiple)")
parser.add_argument(
"--method", choices=["GET", "POST"], default="GET", help="HTTP method to use"
)
parser.add_argument(
"--json-template", type=str, help="JSON template for request body"
)
parser.add_argument(
"--json-paths", nargs="+", help="JSON paths to extract from response"
)
parser.add_argument(
"--rate", type=int, default=10, help="Rate limit (requests per second)"
)
parser.add_argument(
"--requests", type=int, default=100, help="Total number of requests to make"
)
parser.add_argument(
"--output", default="load_test_results.csv", help="Output CSV file name"
)
args = parser.parse_args()
json_template = json.loads(args.json_template) if args.json_template else None
json_paths = args.json_paths if args.json_paths else []
if args.method == "POST" and not json_template:
parser.error("POST method requires a JSON template (use --json-template)")
# Pre-check step
print("Performing pre-check...")
pre_check_result = await pre_check(
args.urls[0], args.method, json_template, json_paths
)
if pre_check_result["status"] == "Error" or pre_check_result["status"] >= 400:
print(f"Pre-check failed. Error: {pre_check_result['response']}")
user_input = input(
"Do you want to continue with the load test? (y/n): "
).lower()
if user_input != "y":
print("Exiting the script.")
return
print(
f"Starting load test with {args.requests} {args.method} requests at {args.rate} requests per second"
)
results = await load_test(
args.urls, args.method, json_template, json_paths, args.rate, args.requests
)
write_report(results, args.output, json_paths)
print(f"\nDetailed results written to {args.output}")
print_summary(results)
## ART
design = r"""
c=====e
H
____________ _,,_H__
(__((__((___() //| |
(__((__((___()()_____________________________________// |ACME |
(__((__((___()()()------------------------------------' |_____|
"""
if __name__ == "__main__":
print(design)
print("Load Testing: Try to blow up your service.")
print("=" * 40)
asyncio.run(main())