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

83 lines
6.7 KiB
Python

"""HTTP integration tests. Disposable fixture from tests/integration.php only.
Requirements: requests, beautifulsoup4. Start PHP server with SESSION_SECURE=0.
"""
import os, re
from pathlib import Path
import requests
from bs4 import BeautifulSoup
BASE=os.environ.get('ESBSC_TEST_URL','http://127.0.0.1:8097')
if os.environ.get('ESBSC_TEST_DATABASE')!='1':raise SystemExit('Disposable test database only: ESBSC_TEST_DATABASE=1')
count=0
def check(value,label):
global count
count+=1
assert value,label
print(f'OK HTTP {count} - {label}',flush=True)
def client():
s=requests.Session();s.trust_env=False;return s
def form(s,path,action,extra):
page=s.get(BASE+path); soup=BeautifulSoup(page.text,'html.parser'); f=soup.find('form',action=action)
assert f is not None,(path,action,page.status_code,page.text[:100])
data={i.get('name'):i.get('value','') for i in f.find_all('input',type='hidden')}
data.update(extra);return s.post(BASE+action,data=data)
def login(email,pwd):
s=client();r=form(s,'/login','/login',dict(email=email,password=pwd));return s,r
s=client();r=s.get(BASE+'/players',allow_redirects=False);check(r.status_code==303 and r.headers['Location']=='/login','Accès anonyme redirigé')
s,r=login('admin@example.test','Testing-only-123!');check(r.status_code==200 and 'Disponibilités du club' in r.text,'Connexion administrateur')
for path in ['/','/players','/matches','/sanctions','/events','/imports','/users','/reports','/audit','/check?id=1&team_id=3&date=2026-06-07']:
r=s.get(BASE+path);check(r.status_code==200 and 'Warning:' not in r.text and 'Fatal error' not in r.text,'Page '+path)
r=s.post(BASE+'/players/save',data={'last_name':'Intrus'});check(r.status_code==422 and 'formulaire invalide' in r.text,'Protection CSRF')
r=s.get(BASE+'/check?team_id=3&date=2026-06-07&licences=INCONNUE');check('Licence inconnue' in r.text and 'Contrôle nécessaire' in r.text,'Licence inconnue signalée dans le contrôle')
# Two new accounts; their initial passwords must change.
for email,role in [('coach@example.test','coach'),('viewer@example.test','viewer')]:
r=form(s,'/users','/users/save',dict(email=email,name='Responsable test',role=role,password='Temporary-test-123!',active='1'))
check(r.status_code==200,'Création du compte '+role)
c,r=login(email,'Temporary-test-123!');check('/password' in r.url,'Changement de mot de passe imposé '+role)
r=form(c,'/password','/password',dict(current_password='Temporary-test-123!',new_password='Permanent-test-123!',confirm_password='Permanent-test-123!'))
check('/login' in r.url,'Changement invalide la session '+role)
c,r=login(email,'Permanent-test-123!');check(r.status_code==200 and 'Vue du week-end' in r.text,'Connexion après changement '+role)
token=BeautifulSoup(r.text,'html.parser').find('input',{'name':'csrf'})['value']
r=c.post(BASE+'/players/save',data={'csrf':token,'licence_number':'UNAUTH'});check(r.status_code==422,'Écriture sportive interdite '+role)
r=c.get(BASE+'/users');check(r.status_code==422,'Gestion des comptes interdite '+role)
if role=='coach':coach=c
else:viewer=c
# Existing match #1 created in integration test.
r=form(coach,'/squad?match_id=1','/squad',{'players[]':['1','2']});check(r.status_code==200 and '2 convoqués' in r.text,'Dirigeant enregistre son groupe')
r=form(viewer,'/squad?match_id=1','/squad',{'players[]':['1']});check(r.status_code==422,'Lecture seule ne modifie pas le groupe')
r=form(coach,'/squad?match_id=1','/reports/create',{});check(r.status_code==200 and 'Convocation enregistrée' in r.text,'Rapport basé sur les convoqués')
report_url=r.url;rid=re.search(r'id=(\d+)',report_url).group(1)
r=coach.get(BASE+'/reports/pdf?id='+rid);check(r.status_code==200 and r.content.startswith(b'%PDF-1.4') and r.headers['Content-Type'].startswith('application/pdf'),'Téléchargement PDF authentifié')
r=s.get(BASE+'/reports');check('À refaire' in r.text,'Ancien rapport périmé signalé')
# Create a player containing HTML to verify output escaping.
r=form(s,'/players','/players/save',dict(licence_number='QA-XSS',last_name='<script>alert(1)</script>',first_name='Éric',category='Senior',usual_team_id='1',active='1'))
check(r.status_code==200 and '<script>alert(1)</script>' not in r.text and '&lt;SCRIPT&gt;' in r.text,'Noms échappés contre injection HTML')
r=coach.get(report_url);check('Les données ont changé' in r.text,'Rapport de groupe invalidé après modification')
# Stale edit form cannot overwrite a newer change.
page=s.get(BASE+'/players?id=1');soup=BeautifulSoup(page.text,'html.parser');f=soup.find('form',action='/players/save');data={i['name']:i.get('value','') for i in f.find_all('input',type='hidden')}
r=form(s,'/imports','/freshness',dict(scope='players',note='Contrôle de test'))
data.update(licence_number='00123',last_name='AMIL',first_name='Riyad',active='1',reason='Test ancien formulaire')
r=s.post(BASE+'/players/save',data=data);check(r.status_code==422 and 'Les données ont changé' in r.text,'Édition périmée refusée')
# Real upload flow.
page=s.get(BASE+'/imports');token=BeautifulSoup(page.text,'html.parser').find('input',{'name':'csrf'})['value']
csv='licence;nom;prenom;categorie;equipe;actif\nHTTP-123;ESSAI;Jules;Senior;E1;oui\n'
r=s.post(BASE+'/imports/preview',data=dict(csrf=token,kind='players'),files={'csv':('joueurs.csv',csv.encode(),'text/csv')});check(r.status_code==200 and 'Valider les 1 lignes' in r.text,'Aperçu upload CSV')
url=r.url.replace(BASE,'');r=form(s,url,'/imports/apply',{});check(r.status_code==200 and 'joueurs.csv' in r.text,'Validation upload CSV')
r=s.get(BASE+'/players');check('HTTP-123' in r.text,'Joueur importé présent')
# Account deactivation invalidates the already logged-in coach immediately.
page=s.get(BASE+'/users');soup=BeautifulSoup(page.text,'html.parser');tr=next(tr for tr in soup.select('tbody tr') if 'coach@example.test' in tr.text);editurl=tr.find('a')['href']
r=form(s,editurl,'/users/save',dict(email='coach@example.test',name='Responsable test',role='coach',password=''))
r=coach.get(BASE+'/',allow_redirects=False);check(r.status_code==303 and r.headers['Location']=='/login','Désactivation révoque la session ouverte')
r=s.get(BASE+'/config/database.php');check(r.status_code==404 and 'test-only' not in r.text,'Configuration non exposée')
for path,name in [('/?from=2026-05-31','dashboard'),('/squad?match_id=1','squad'),('/users','users'),('/imports','imports')]:
r=s.get(BASE+path)
out=Path(os.environ.get('ESBSC_QA_DIR','/tmp/esbsc-qa'));out.mkdir(exist_ok=True,parents=True)
# Static render fixture for visual QA; no saved session or credentials.
html=r.text.replace('<link rel="stylesheet" href="/assets/app.css">','<style>'+Path('public/assets/app.css').read_text()+'</style>').replace('<script defer src="/assets/app.js"></script>','')
(out/(name+'.html')).write_text(html)
print(f'{count} tests HTTP réussis.')