Skip to content

Health Software Common Practices

HSCP-T-005 · open test

Dated accessibility survey whose fingerprints match its description

Serves HSCP-G-057, HSCP-G-263, HSCP-G-264, HSCP-G-265, HSCP-G-266, HSCP-G-267, HSCP-G-268, HSCP-G-269, HSCP-G-270, HSCP-G-271, HSCP-G-272 · Recipes: HSCP-R-014, HSCP-R-015

Code under the licence Apache 2.0 · Python 3.10 or later, standard library only, no network access

What the test checks

The evidence item is a folder in the releve-accessibilite/1 format, produced by the product's accessibility checking chain, for a website or a native application (the format is the same; for an application, a “page” is a screen):

File Content
produit.json format (releve-accessibilite/1), produit, date (YYYY-MM-DD), outils (names and versions), pieces (relative path → SHA-256 fingerprint), and freely surfaces, pages, echantillon (what is checked and what is not)
controles.jsonl one line per page, check and context: jour, surface, page, controle, contexte, outil, statut (ok, ecart or erreur), bloquant (true or false), and if needed noeuds, wcag_verifies, wcag_ecarts, wcag_sans_objet (form 1.4.3), rgaa_verifies, rgaa_ecarts (form 8.2), detail
tracabilite.csv one line per criterion, separator ;, columns referentiel, exigence, resultat at least

The test accepts it if the folder is dated (neither in the future nor older than --age-max), if every declared item exists and has the announced fingerprint, if no file in the folder escapes the declaration, and if every check and traceability line has its fields, a known status and well-formed criteria. A single item modified afterwards gets the survey refused.

Running the test

python3 verifier.py releve/ --date 2026-11-22 --age-max 31

--json gives the answer in JSON. Exit code: 0 evidence accepted, 1 evidence refused, 2 incorrect call. Python 3.10 or later, no dependency, no network access.

Producing the evidence

The checking itself belongs to free tools: for the web, axe-core (for example through @axe-core/cli or Playwright), Pa11y; for a native application, the platforms' engines plugged into the UI tests (Accessibility Test Framework for Android, the XCUITest accessibility audit). An adapter writes their results in the survey format, then computes the fingerprints (sha256sum) into produit.json. The test checks only that folder.

Examples

  • exemples/valide/releve/: two pages on mobile and desktop, one deviation, one erreur line, three traceability lines. Accepted.
  • exemples/refuse/releve/: the same survey, with the traceability edited after the fingerprints were computed and an unknown status. Refused.
  • exemples/valide-natif/releve/: a native application, two screens on the android and ios surfaces, in the police-200, sombre and paysage contexts, two deviations, one erreur line (screen not reached), three traceability lines. Accepted.

What the test does not say

  • It does not say whether the product is accessible, nor what conformance rate it reaches: automated checking covers only part of the criteria, and a rate requires an audit of all criteria on a representative sample.
  • An erreur line (the tool did not conclude) proves nothing: the test counts it, it does not take it as evidence.
  • The fingerprints prove that the items have not changed since they were declared, not who produced them: that requires signing produit.json.

Code

Download the test (zip archive: program, examples, README, licence) (17 KB) · verifier.py

The code and its messages are not translated (French).

#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 les contributeurs des Gestes communs du logiciel de santé
"""HSCP-T-005 : relevé d'accessibilité daté, dont les empreintes concordent avec la description du produit.

    python3 verifier.py <dossier du relevé> [--date AAAA-MM-JJ] [--age-max JOURS] [--json]

Le dossier suit le format `releve-accessibilite/1` (décrit dans le LISEZ-MOI) :
  produit.json      format, produit, date, outils, pieces (chemin relatif → empreinte SHA-256), et d'autres champs libres
  controles.jsonl   une ligne par page, contrôle et contexte
  tracabilite.csv   une ligne par critère, séparateur « ; »

Refus : produit.json illisible ou d'un autre format ; produit, date, outils ou pieces absents ; date illisible, future,
ou plus ancienne que --age-max ; pièce déclarée absente ou d'empreinte discordante ; fichier du dossier non déclaré ;
controles.jsonl ou tracabilite.csv absents ou non déclarés ; ligne de contrôle sans un champ obligatoire, de statut
hors vocabulaire, datée après le relevé, ou citant un critère mal formé ; colonnes de tracabilite.csv manquantes.
Il ne dit pas si le produit est accessible ni quel taux de conformité il atteint : un contrôle automatique ne couvre
qu'une partie des critères, et une ligne `erreur` (l'outil n'a pas conclu) ne prouve rien.

Codes de retour : 0 pièce acceptée, 1 pièce refusée, 2 appel incorrect.
Bibliothèque standard seulement, aucun accès réseau.
"""
import argparse
import csv
import datetime as dt
import hashlib
import json
import os
import re
import sys

ID = "HSCP-T-005"
FORMAT = "releve-accessibilite/1"
OBLIGATOIRES = ("jour", "surface", "page", "controle", "contexte", "outil", "statut", "bloquant")
STATUTS = ("ok", "ecart", "erreur")
COLONNES = ("referentiel", "exigence", "resultat")
CRITERES = {"wcag": re.compile(r"^\d+\.\d+\.\d+$"), "rgaa": re.compile(r"^\d+\.\d+$")}


def jour(texte):
    try:
        return dt.date.fromisoformat(str(texte or "").strip()[:10])
    except ValueError:
        return None


def sha256(chemin):
    h = hashlib.sha256()
    with open(chemin, "rb") as f:
        for bloc in iter(lambda: f.read(65536), b""):
            h.update(bloc)
    return h.hexdigest()


def verifier(dossier, aujourd_hui, age_max):
    refus, notes = [], []
    try:
        with open(os.path.join(dossier, "produit.json"), encoding="utf-8") as f:
            produit = json.load(f)
    except OSError as e:
        return {"refus": [f"produit.json illisible : {e.strerror}"], "notes": []}
    except ValueError as e:
        return {"refus": [f"produit.json : JSON illisible ({e})"], "notes": []}
    if not isinstance(produit, dict) or produit.get("format") != FORMAT:
        return {"refus": [f"produit.json : format « {produit.get('format') if isinstance(produit, dict) else '?'} », attendu {FORMAT}"], "notes": []}
    for champ in ("produit", "date", "outils", "pieces"):
        if not produit.get(champ):
            refus.append(f"produit.json : champ « {champ} » absent ou vide")
    date = jour(produit.get("date"))
    if produit.get("date") and not date:
        refus.append(f"produit.json : date illisible « {produit.get('date')} »")
    elif date and date > aujourd_hui:
        refus.append(f"produit.json : relevé daté du {date}, après le {aujourd_hui}")
    elif date and age_max is not None and (aujourd_hui - date).days > age_max:
        refus.append(f"relevé du {date}, plus ancien que {age_max} jour(s) au {aujourd_hui}")

    # Empreintes : chaque pièce déclarée est recalculée ; tout fichier du dossier est déclaré.
    declare = produit.get("pieces") if isinstance(produit.get("pieces"), dict) else {}
    presents = set()
    for base, _, fichiers in os.walk(dossier):
        for nom in fichiers:
            rel = os.path.relpath(os.path.join(base, nom), dossier).replace(os.sep, "/")
            if rel != "produit.json":
                presents.add(rel)
    concordent = 0
    for rel in sorted(presents | set(declare)):
        attendu = str(declare.get(rel) or "").lower()
        if rel not in declare:
            refus.append(f"{rel} : présent dans le dossier, absent des pièces de produit.json")
        elif rel not in presents:
            refus.append(f"{rel} : déclaré dans produit.json, absent du dossier")
        elif not re.match(r"^[0-9a-f]{64}$", attendu):
            refus.append(f"{rel} : empreinte déclarée qui n'est pas un SHA-256")
        elif sha256(os.path.join(dossier, rel)) != attendu:
            refus.append(f"{rel} : empreinte discordante (déclarée {attendu[:12]}…, calculée {sha256(os.path.join(dossier, rel))[:12]}…)")
        else:
            concordent += 1
    for requis in ("controles.jsonl", "tracabilite.csv"):
        if requis not in presents:
            refus.append(f"{requis} absent du dossier")

    # Lignes de contrôle.
    statuts = dict.fromkeys(STATUTS, 0)
    chemin = os.path.join(dossier, "controles.jsonl")
    if os.path.exists(chemin):
        for num, texte in enumerate(open(chemin, encoding="utf-8").read().splitlines(), 1):
            if not texte.strip():
                continue
            ici = f"controles.jsonl ligne {num}"
            try:
                x = json.loads(texte)
            except ValueError as e:
                refus.append(f"{ici} : JSON illisible ({e})")
                continue
            manque = [c for c in OBLIGATOIRES if x.get(c) in (None, "")]
            if manque:
                refus.append(f"{ici} : champ(s) absent(s) : {', '.join(manque)}")
            if x.get("statut") not in STATUTS:
                refus.append(f"{ici} : statut « {x.get('statut')} » hors vocabulaire ({', '.join(STATUTS)})")
            else:
                statuts[x["statut"]] += 1
            if "bloquant" in x and not isinstance(x["bloquant"], bool):
                refus.append(f"{ici} : bloquant doit valoir true ou false")
            j = jour(x.get("jour"))
            if x.get("jour") and not j:
                refus.append(f"{ici} : jour illisible « {x.get('jour')} »")
            elif j and date and j > date:
                refus.append(f"{ici} : contrôle du {j}, après la date du relevé ({date})")
            for ref, motif in CRITERES.items():
                for champ in (f"{ref}_verifies", f"{ref}_ecarts", f"{ref}_sans_objet"):
                    mauvais = [c for c in x.get(champ) or [] if not motif.match(str(c))]
                    if mauvais:
                        refus.append(f"{ici} : {champ} cite un critère mal formé « {mauvais[0]} »")
            if x.get("statut") == "ecart" and not (x.get("wcag_ecarts") or x.get("rgaa_ecarts")):
                notes.append(f"{ici} : écart sans critère nommé")
        if not sum(statuts.values()):
            refus.append("controles.jsonl sans aucune ligne")

    # Traçabilité.
    chemin = os.path.join(dossier, "tracabilite.csv")
    lignes_trace = 0
    if os.path.exists(chemin):
        with open(chemin, encoding="utf-8-sig", newline="") as f:
            lecteur = csv.DictReader(f, delimiter=";")
            manque = [c for c in COLONNES if c not in (lecteur.fieldnames or [])]
            if manque:
                refus.append(f"tracabilite.csv : colonne(s) absente(s) : {', '.join(manque)}")
            else:
                for num, r in enumerate(lecteur, 2):
                    lignes_trace += 1
                    if not (r.get("exigence") or "").strip() or not (r.get("resultat") or "").strip():
                        refus.append(f"tracabilite.csv ligne {num} : exigence ou resultat vide")

    notes.insert(0, f"relevé de « {produit.get('produit')} » du {date or '?'} : {concordent} pièce(s) d'empreinte concordante, "
                    f"contrôles ok {statuts['ok']}, ecart {statuts['ecart']}, erreur {statuts['erreur']} ; {lignes_trace} ligne(s) de traçabilité")
    if statuts["erreur"]:
        notes.append(f"{statuts['erreur']} ligne(s) « erreur » : l'outil n'a pas conclu, elles ne prouvent rien")
    return {"refus": refus, "notes": notes}


def main(argv=None):
    analyseur = argparse.ArgumentParser(description=__doc__.split("\n")[0], formatter_class=argparse.RawDescriptionHelpFormatter)
    analyseur.add_argument("dossier", help="dossier du relevé (produit.json, controles.jsonl, tracabilite.csv)")
    analyseur.add_argument("--date", help="date de la vérification (défaut : aujourd'hui), AAAA-MM-JJ")
    analyseur.add_argument("--age-max", type=int, help="âge maximal du relevé, en jours (défaut : pas de limite)")
    analyseur.add_argument("--json", action="store_true", help="sortie JSON")
    a = analyseur.parse_args(argv)
    aujourd_hui = jour(a.date) if a.date else dt.date.today()
    if not aujourd_hui:
        analyseur.error(f"--date illisible : {a.date}")
    if not os.path.isdir(a.dossier):
        analyseur.error(f"{a.dossier} n'est pas un dossier")
    r = verifier(a.dossier, aujourd_hui, a.age_max)
    r.update(test=ID, piece=a.dossier, date=str(aujourd_hui), accepte=not r["refus"])
    if a.json:
        print(json.dumps(r, ensure_ascii=False, indent=1))
    else:
        print(f"{ID} relevé d'accessibilité : {a.dossier} (au {aujourd_hui})")
        for x in r["refus"]:
            print(f"  REFUS  {x}")
        for x in r["notes"]:
            print(f"  NOTE   {x}")
        print("Résultat : " + ("pièce acceptée" if r["accepte"] else f"pièce refusée ({len(r['refus'])} refus)"))
    return 0 if r["accepte"] else 1


if __name__ == "__main__":
    sys.exit(main())

Files of the test