Add four-hour JMeter energy workloads with Gaussian user pacing
This commit is contained in:
1 parent
23a824dd81
commit
45a040f3a2
14 files changed
+3562
No files matched your search
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise every generated plan against a local HTTPS contract stub, not testserver."""
|
||||
import datetime, json, os, ssl, subprocess, tempfile, threading, uuid
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
HERE=Path(__file__).resolve().parent
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version='HTTP/1.1'
|
||||
observations={}; tokens={}; logins=0; break_insights=False
|
||||
def log_message(self,*args): pass
|
||||
def handle_request(self):
|
||||
path=urlsplit(self.path).path
|
||||
body=json.loads(self.rfile.read(int(self.headers.get('Content-Length',0))) or '{}')
|
||||
code=200; data={}
|
||||
if path=='/api/measurement-guidance': data={'available':True}
|
||||
elif path=='/api/authentication/login':
|
||||
if body.get('password')!='test': code=401
|
||||
else:
|
||||
token=str(uuid.uuid4());self.tokens[token]=body['accountId'];type(self).logins+=1
|
||||
data={'accessToken':token,'expiresIn':65,'role':'Patient','tokenType':'Bearer'}
|
||||
elif self.headers.get('Authorization','').removeprefix('Bearer ') not in self.tokens: code=401
|
||||
elif path=='/api/professionals/me/patients': data=[{'patientId':'patient-0'},{'patientId':'patient-1'}]
|
||||
elif path=='/api/patients/me':
|
||||
account=self.tokens[self.headers['Authorization'].removeprefix('Bearer ')]
|
||||
data={'patientId':'patient-'+account.split('-')[-1]}
|
||||
elif path.startswith('/api/observations/'):
|
||||
oid=path.split('/')[-1]
|
||||
if oid not in self.observations: code=404
|
||||
elif self.command=='DELETE': del self.observations[oid];code=204
|
||||
else:
|
||||
if self.command=='PATCH':self.observations[oid].update(body)
|
||||
data=self.observations[oid]
|
||||
elif path.startswith('/api/patients/'):
|
||||
pid=path.split('/')[3];profile={'patientId':pid}
|
||||
baseline={'patientId':pid,'observationId':'baseline','systolic':128,'diastolic':82,'pulse':68,'measuredAt':'2026-09-01T08:00:00'}
|
||||
if path.endswith('/observations'):
|
||||
if self.command=='POST':
|
||||
if not body.get('measuredAt') or body.get('measurementContext',{}).get('setting') not in ['Home','Clinic','Other','Unknown']:code=400
|
||||
else:
|
||||
oid=str(uuid.uuid4());data=dict(body,patientId=pid,observationId=oid);self.observations[oid]=data;code=201
|
||||
else:data=[baseline]
|
||||
elif path.endswith('/latest'):data=baseline
|
||||
elif path.endswith('/overview'):data={'patient':profile,'latestObservation':baseline,'insight':{'contributingCount':60}}
|
||||
elif path.endswith('/insights'):
|
||||
data={'contributingCount':60}
|
||||
if self.break_insights: code=503
|
||||
elif path.endswith('/trends'):data={'patientId':pid}
|
||||
else:data=profile
|
||||
else:code=404
|
||||
payload=b'' if code==204 else json.dumps(data).encode()
|
||||
self.send_response(code);self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(payload)));self.end_headers();self.wfile.write(payload)
|
||||
do_GET=do_POST=do_PATCH=do_DELETE=handle_request
|
||||
with tempfile.TemporaryDirectory(prefix='healthapp-jmeter-verify-') as temp:
|
||||
root=Path(temp);cert=root/'cert.pem';key=root/'key.pem'
|
||||
subprocess.run(['openssl','req','-x509','-newkey','rsa:2048','-nodes','-days','1','-keyout',str(key),'-out',str(cert),'-subj','/CN=127.0.0.1','-addext','subjectAltName=IP:127.0.0.1'],check=True,capture_output=True)
|
||||
server=ThreadingHTTPServer(('127.0.0.1',0),Handler);context=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);context.load_cert_chain(cert,key);server.socket=context.wrap_socket(server.socket,server_side=True)
|
||||
threading.Thread(target=server.serve_forever,daemon=True).start()
|
||||
users=root/'users.csv';users.write_text('account_id,password,patient_id\naccount-0,test,patient-0\naccount-1,test,patient-1\n')
|
||||
accounts=root/'accounts.json'
|
||||
accounts.write_text(json.dumps([{'AccountId':f'account-{i}','Password':'test','Role':'Patient'} for i in range(2)]))
|
||||
prepared=subprocess.run(['python3',str(HERE/'prepare.py'),'--base-url',f'https://127.0.0.1:{server.server_port}','--ca',str(cert),'--accounts',str(accounts),'--output',str(root/'dataset'),'--days','4'],capture_output=True,text=True)
|
||||
assert prepared.returncode==0, prepared.stderr
|
||||
assert len(Handler.observations)==16
|
||||
assert set(o['measurementContext']['setting'] for o in Handler.observations.values())=={'Home','Clinic','Unknown'}
|
||||
assert (root/'dataset/users.csv').stat().st_mode & 0o777 == 0o600
|
||||
print('Synthetic dataset preparation passed')
|
||||
# Professional runner preflight is intentionally separate: fixture credentials are patient roles.
|
||||
for scenario in ['recording','review','correction','mixed']:
|
||||
initial_logins=Handler.logins
|
||||
result=subprocess.run(['python3',str(HERE/'run.py'),scenario,'--host','127.0.0.1','--port',str(server.server_port),'--ca',str(cert),'--users-file',str(users),'--users','2','--warmup','1','--duration','6','--ramp','0','--think-mean-ms','10','--think-stddev-ms','5','--session-pause-ms','100','--session-stddev-ms','25','--output',str(root/scenario)],capture_output=True,text=True)
|
||||
if result.returncode:
|
||||
print(result.stdout,result.stderr)
|
||||
print((root/scenario/'jmeter.log').read_text()[-6000:])
|
||||
raise SystemExit('Plan verification failed: '+scenario)
|
||||
assert Handler.logins - initial_logins >= 6, 'Initial login and token renewal were not exercised'
|
||||
data=json.loads((root/scenario/'run.json').read_text());assert data['measurement_end_ms']-data['measurement_start_ms']==6000; assert data['measured_http_samples']>0; print(scenario, 'passed;',data['http_samples'],'HTTP samples;', data['failed_http_samples'],'failures')
|
||||
# Run the professional plan directly so its assigned-patient semantic assertion is exercised.
|
||||
result=subprocess.run([str(Path.home()/'.local/bin/jmeter'),'-n','-t',str(HERE/'plans/professional.jmx'),'-l',str(root/'professional.csv'),'-j',str(root/'professional.log'),'-Jhost=127.0.0.1','-Jport='+str(server.server_port),'-Jusers_file='+str(users),'-Jusers=2','-Jtotal_duration_seconds=8','-Jramp_seconds=0','-Jthink_mean_ms=0','-Jthink_stddev_ms=0','-Jsession_pause_ms=100','-Jsession_stddev_ms=25','-Jperiod_from=2026-01-01T00:00:00Z','-Jperiod_to=2027-01-01T00:00:00Z'],capture_output=True,text=True)
|
||||
import csv
|
||||
with (root/'professional.csv').open() as f: samples=list(csv.DictReader(f))
|
||||
assert result.returncode==0 and samples and all(r['success']=='true' for r in samples), result.stdout+result.stderr
|
||||
print('professional passed;',len(samples),'samples; token renewal exercised across all plans')
|
||||
Handler.break_insights=True
|
||||
failed=subprocess.run(['python3',str(HERE/'run.py'),'review','--host','127.0.0.1','--port',str(server.server_port),'--ca',str(cert),'--users-file',str(users),'--users','2','--warmup','0','--duration','5','--ramp','0','--think-mean-ms','0','--think-stddev-ms','0','--session-pause-ms','0','--session-stddev-ms','0','--output',str(root/'expected-failure')],capture_output=True,text=True)
|
||||
assert failed.returncode!=0
|
||||
assert json.loads((root/'expected-failure/run.json').read_text())['failed_http_samples']>0
|
||||
print('Unexpected upstream failure correctly invalidates the run')
|
||||
# Constant 100 W for 4 measured hours is exactly 1,440,000 J / 0.4 kWh.
|
||||
energy_run=root/'energy-run.json';energy_run.write_text(json.dumps({'measurement_start_ms':1000000,'measurement_end_ms':15400000,'measured_http_samples':100}))
|
||||
power=root/'power.csv';power.write_text('timestamp,power_watts\n1970-01-01T00:00:00Z,100\n1970-01-01T05:00:00Z,100\n')
|
||||
energy=subprocess.run(['python3',str(HERE/'energy.py'),str(energy_run),str(power)],capture_output=True,text=True,check=True)
|
||||
energy_result=json.loads(energy.stdout); assert energy_result['joules']==1440000 and energy_result['kWh']==0.4
|
||||
print('Four-hour power integration passed')
|
||||
server.shutdown()
|
||||
Reference in new issue
Block a user