fix:lasttest
CI / audit (push) Skipped
CI / checks (push) Successful in 3m22s
CI / image (push) Failing after 1m2s

This commit is contained in:
marco.morath committed 2026-11-26 07:11:39 +01:00
1 parent c7d622f4e3
commit 4cb6cd8cf9
3 files changed
+67 -22

No files matched your search

+59 -21
View File
@@ -20,26 +20,56 @@ Bitte nur gegen eigene Testinstanzen laufen lassen.
from __future__ import annotations
import argparse
import http.client
import ssl
import statistics
import sys
import threading
import time
import urllib.error
import urllib.request
import urllib.parse
from concurrent.futures import ThreadPoolExecutor
_local = threading.local()
def fetch(url: str, cookie: str | None) -> tuple[float, int]:
request = urllib.request.Request(url, headers={ # noqa: S310 (Adresse vom Aufrufer)
"User-Agent": "surveybox-loadtest", "Accept-Language": "de",
**({"Cookie": cookie} if cookie else {})})
start = time.perf_counter()
try:
with urllib.request.urlopen(request, timeout=30) as resp: # noqa: S310
def _connection(base: urllib.parse.SplitResult) -> http.client.HTTPConnection:
"""Eine Verbindung je Thread, wie ein Browser sie offen hält (Keep-Alive)."""
conn: http.client.HTTPConnection | None = getattr(_local, "conn", None)
if conn is None:
if base.scheme == "https":
conn = http.client.HTTPSConnection(base.hostname or "", base.port,
context=ssl.create_default_context(),
timeout=30)
else:
conn = http.client.HTTPConnection(base.hostname or "", base.port, timeout=30)
_local.conn = conn
return conn
def fetch(base: urllib.parse.SplitResult, path: str, cookie: str | None) -> tuple[float, int]:
"""Eine Anfrage; Weiterleitungen werden nicht verfolgt (zählen als Antwort)."""
headers = {"User-Agent": "surveybox-loadtest", "Accept-Language": "de",
**({"Cookie": cookie} if cookie else {})}
for attempt in (1, 2):
conn = _connection(base)
start = time.perf_counter()
try:
conn.request("GET", path, headers=headers)
resp = conn.getresponse()
resp.read()
status = resp.status
except urllib.error.HTTPError as exc:
status = exc.code
return (time.perf_counter() - start) * 1000, status
return (time.perf_counter() - start) * 1000, resp.status
except (http.client.HTTPException, OSError):
conn.close()
_local.conn = None
if attempt == 2:
return (time.perf_counter() - start) * 1000, 599
return 0.0, 599 # nicht erreichbar
def warm_up(base: urllib.parse.SplitResult, path: str, cookie: str | None, users: int) -> None:
"""Verbindungen aufbauen (TLS-Handschlag), bevor gemessen wird."""
with ThreadPoolExecutor(max_workers=users) as pool:
list(pool.map(lambda _: fetch(base, path, cookie), range(users * 2)))
def main() -> int:
@@ -55,23 +85,31 @@ def main() -> int:
parser.add_argument("--cookie", default=None, help="Cookie-Kopf für angemeldete Seiten")
args = parser.parse_args()
paths = args.path or ["/", "/login"]
base = args.base.rstrip("/")
base = urllib.parse.urlsplit(args.base.rstrip("/"))
failed = False
print(f"{'Seite':40} {'Median':>8} {'95 %':>8} {'Max':>8} Fehler")
print(f"{'Seite':34} {'einzeln':>8} {'Median':>8} {'95 %':>8} {'Max':>8} {'Abr./s':>7}"
" Fehler")
for path in paths:
url = base + path
fetch(url, args.cookie) # aufwärmen
# einzeln: eine Anfrage nach der anderen = reine Antwortzeit ohne Warteschlange
warm_up(base, path, args.cookie, 1)
single = statistics.median(fetch(base, path, args.cookie)[0] for _ in range(10))
warm_up(base, path, args.cookie, args.users)
began = time.perf_counter()
with ThreadPoolExecutor(max_workers=args.users) as pool:
results = list(pool.map(fetch, [url] * args.requests, [args.cookie] * args.requests))
n = args.requests
results = list(pool.map(fetch, [base] * n, [path] * n, [args.cookie] * n))
rate = len(results) / (time.perf_counter() - began)
times = sorted(t for t, _ in results)
errors = sum(1 for _, status in results if status >= 400)
p95 = times[max(int(len(times) * 0.95) - 1, 0)]
too_slow = p95 > args.limit_ms
failed = failed or too_slow or errors > 0
mark = " ZU LANGSAM" if too_slow else ""
print(f"{path[:40]:40} {statistics.median(times):7.0f} {p95:7.0f} {times[-1]:7.0f}"
f" {errors}{mark}")
print(f"\nGrenze 95. Perzentil: {args.limit_ms:.0f} ms bei {args.users} gleichzeitigen Abrufen")
print(f"{path[:34]:34} {single:7.0f} {statistics.median(times):7.0f} {p95:7.0f}"
f" {times[-1]:7.0f} {rate:6.0f} {errors}{mark}")
print(f"\nZeiten in ms. einzeln = Median ohne gleichzeitige Last; danach {args.users}"
f" gleichzeitige Abrufe.\nGrenze 95. Perzentil: {args.limit_ms:.0f} ms."
" Verbindungen bleiben offen (Keep-Alive), Weiterleitungen werden nicht verfolgt.")
return 1 if failed else 0