Files
ESBSC-CONVOC/tests/v4_http.py
T
2026-11-11 09:24:28 +01:00

78 lines
8.2 KiB
Python

"""HTTP checks for the disposable fixture created by tests/v4.php. Standard library only."""
import os,json,re,urllib.request,urllib.parse,http.cookiejar,zipfile,io
from pathlib import Path
from html.parser import HTMLParser
if os.environ.get('ESBSC_TEST_DATABASE')!='1':raise SystemExit('Disposable database required')
BASE=os.environ.get('ESBSC_TEST_URL','http://127.0.0.1:8124')
fixture=json.loads(Path('/tmp/v4-fixture.json').read_text());count=0
class Fields(HTMLParser):
def __init__(self):super().__init__();self.inputs={};self.selects={};self.current=None;self.options=[]
def handle_starttag(self,tag,attrs):
a=dict(attrs)
if tag=='input' and a.get('name'):self.inputs[a['name']]=a.get('value','')
if tag=='select':self.current=a.get('name');self.options=[]
if tag=='option' and self.current:self.options.append(a)
def handle_endtag(self,tag):
if tag=='select' and self.current:self.selects[self.current]=self.options;self.current=None
def fields(html):p=Fields();p.feed(html);return p
def client():return urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
def request(c,path,data=None,content_type=None):
if isinstance(data,dict):data=urllib.parse.urlencode(data,doseq=True).encode()
r=urllib.request.Request(BASE+path,data=data)
if content_type:r.add_header('Content-Type',content_type)
try:
with c.open(r) as p:return p.status,p.read().decode(),p.geturl()
except urllib.error.HTTPError as e:return e.code,e.read().decode(),e.geturl()
def check(ok,label):
global count;count+=1;assert ok,label;print('HTTP V4',count,label,flush=True)
def login(email):
c=client();_,html,_=request(c,'/login');s,h,url=request(c,'/login',{'csrf':fields(html).inputs['csrf'],'email':email,'password':'V4-local-test-password'});print('LOGIN FAILURE',s,url,re.sub('<[^>]+>',' ',h)[-1000:]) if not (s==200 and '/login' not in url) else None;check(s==200 and '/login' not in url,'Connexion '+email);return c
admin=login('v4-admin@example.test')
for path in ['/','/players','/staff','/matches','/spond','/settings','/seasons','/regulations','/imports','/users','/convocations?week='+fixture['date'],'/squad?match_id='+str(fixture['mid'][0])]:
code,html,_=request(admin,path);check(code==200 and 'Fatal error' not in html and 'Warning:' not in html,path+' rendu sans erreur')
code,html,_=request(admin,'/squad?match_id='+str(fixture['mid'][0]));check('DUPONT Alex' in html and 'data-profile-player="1"' in html and 'Spond :' in html,'Double profil et disponibilités dans préparation')
csrf=fields(html).inputs['csrf'];code,_,_=request(admin,'/settings/save',{'csrf':'invalide'});check(code==422,'CSRF refusé')
viewer=login('v4-viewer@example.test');_,h,_=request(viewer,'/');viewer_csrf=fields(h).inputs['csrf'];code,_,_=request(viewer,'/spond/apply',{'csrf':viewer_csrf,'batch_id':1});check(code==422,'Lecture seule ne peut importer Spond')
# Synthetic workbook: first sheet deliberately invalid for import, correct second sheet only.
b=io.BytesIO()
with zipfile.ZipFile(b,'w',zipfile.ZIP_DEFLATED) as z:
z.writestr('xl/workbook.xml','<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="À imprimer" sheetId="1" r:id="rId1"/><sheet name="À importer" sheetId="2" r:id="rId2"/></sheets></workbook>')
z.writestr('xl/_rels/workbook.xml.rels','<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Target="worksheets/sheet2.xml"/></Relationships>')
z.writestr('xl/worksheets/sheet1.xml','this sheet must never be parsed')
rows={4:['Statut','Nom','Adresse e-mail','Téléphone','Délai de réponse'],5:['Participe','Alex Dupont','test@example.test','0612345678',fixture['season'][:4]+'-09-26 14:00:00'],6:['Sans réponse','Camille Martin','','',''],7:['Ne peut pas participer','Personne inconnue','','','']}
from xml.sax.saxutils import escape
xml='<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>'
for n,values in rows.items():xml+='<row r="%s">'%n+''.join('<c r="%s%s" t="inlineStr"><is><t>%s</t></is></c>'%(chr(65+i),n,escape(v)) for i,v in enumerate(values))+'</row>'
z.writestr('xl/worksheets/sheet2.xml',xml+'</sheetData></worksheet>')
boundary='esbsc-test-boundary';parts=[]
for k,v in {'csrf':csrf,'week':fixture['date'],'match_id':'0'}.items():parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode())
parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="xlsx"; filename="spond-test.xlsx"\r\nContent-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\r\n\r\n'.encode()+b.getvalue()+b'\r\n');parts.append(f'--{boundary}--\r\n'.encode())
code,html,url=request(admin,'/spond/preview',b''.join(parts),'multipart/form-data; boundary='+boundary);check(code==200 and 'Aperçu · spond-test.xlsx' in html,'Upload lit exclusivement la deuxième feuille')
f=fields(html);check(f.selects['choices[0]'][int(fixture['ids'][0])+1].get('selected') is not None if False else 'Correspondance mémorisée' in html,'Correspondance précédente proposée')
code,html,_=request(admin,'/spond/apply',{'csrf':csrf,'batch_id':f.inputs['batch_id'],'choices[0]':fixture['ids'][0],'choices[1]':fixture['ids'][1],'choices[2]':'skip'});check(code==200 and 'Enregistrement effectué.' in html,'Import confirmé avec inconnu explicitement ignoré')
code,html,_=request(admin,'/convocations?week='+fixture['date']);check('Spond : Présent' in html and 'Spond : Sans réponse' in html and 'data-spond-filter' in html,'Disponibilités et filtres des non-convoqués')
# Profile settings variant save/read round trip.
code,html,_=request(admin,'/regulations');rev=fields(html).inputs['revision']
form={'csrf':csrf,'revision':rev,'team_id':4,'season':fixture['season'],'competition':'V4 championnat','mutation_base':4,'mutation_bonus':0,'outside_limit':2,'max_players':14,'ten_limit':3,'ten_from':fixture['season'][:4]+'-10-01','ten_rule':'on','championship':'on','special_higher_enabled':'on','confirmed':'on','reference':'Texte de test uniquement : profil confirmé sur base jetable'}
code,html,_=request(admin,'/regulations/save',form);check(code==200 and 'V4 championnat' in html,'Enregistrement profil V4')
# Archive switch is readable but rejects mutation.
next_season=str(int(fixture['season'][:4])+1)+'/'+str(int(fixture['season'][:4])+2)
code,html,_=request(admin,'/seasons/select',{'csrf':csrf,'season':next_season});check(code==200 and 'en consultation' in html,'Sélecteur affiche archive')
code,html,_=request(admin,'/settings/save',{'csrf':csrf});check(code==422 and 'archivée' in html,'Mutation refusée depuis archive')
request(admin,'/seasons/select',{'csrf':csrf,'season':fixture['season']})
code,html,_=request(admin,'/auth/callback?state=bad&code=bad');check(code==422 and 'invalide' in html,'Callback OpenID sans état valide refusé')
# Exercise the actual multipart logo uploader and GD normalization.
import zlib,struct,binascii
w,h=600,300
def chunk(k,data):return struct.pack('>I',len(data))+k+data+struct.pack('>I',binascii.crc32(k+data)&0xffffffff)
raw=b''.join(b'\x00'+(b'\x20\x4b\x38' if y<150 else b'\xee\xee\xee')*w for y in range(h))
png=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(raw))+chunk(b'IEND',b'')
parts=[]
for k,v in {'csrf':csrf,'name':'Club de test V4','short_name':'CLUB TEST','fff_number':'520480','primary':'#204b38','accent':'#296b45','default_venue':'Terrain principal','slot_minutes':'150'}.items():parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode())
parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="logo"; filename="logo.png"\r\nContent-Type: image/png\r\n\r\n'.encode()+png+b'\r\n');parts.append(f'--{boundary}--\r\n'.encode())
code,html,_=request(admin,'/settings/save',b''.join(parts),'multipart/form-data; boundary='+boundary);check(code==200 and 'Enregistrement effectué.' in html and 'data:image/png;base64,' in html,'Logo PNG uploadé, normalisé et affiché')
code,css,_=request(client(),'/brand.css');check(code==200 and '#204b38' in css,'Palette personnalisée disponible sur connexion')
print('HTTP V4 OK',count)