vercors.me : statistiques de fréquentation sans cookie (journal Caddy anonymisé, agrégation, page /statistiques)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cette révision appartient à :
Théo GastineletClaude Opus 5.5 a révisé 2026-11-05 11:16:30 +01:00
1 Parent 518abc0708
révision a5278c3b32
6 fichiers modifiés
+608

Aucun fichier ne correspond à votre recherche

+101
Voir le fichier
@@ -0,0 +1,101 @@
"""Tests des statistiques de fréquentation, avec un faux journal Caddy : python -I tests/test_statistiques_vercors.py"""
import datetime as dt
import gzip
import json
import os
import sys
import tempfile
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "collecte"))
import statistiques_vercors as st # noqa: E402
MAINT = dt.datetime(2026, 11, 5, 10, 0, tzinfo=dt.timezone.utc)
IP_SECRETE = "203.0.113.77"
def ts(jour, h=12):
return dt.datetime.fromisoformat(jour + "T%02d:00:00+00:00" % h).timestamp()
def ligne(jour, uri="/", classe="bureau", ref="", langue="fr", status=200, methode="GET", hote="vercors.me", h=12, brut=False):
r = {"level": "info", "ts": ts(jour, h), "status": status, "ua_classe": classe, "referent": ref, "langue": langue,
"request": {"method": methode, "host": hote, "uri": uri}}
if brut: # journal mal filtré : l'IP et les cookies ne doivent de toute façon jamais ressortir
r["request"].update(remote_ip=IP_SECRETE, headers={"Cookie": ["secret=1"], "User-Agent": ["Mozilla/5.0 (iPhone)"]})
del r["ua_classe"]
return json.dumps(r)
def faux_journal():
L = []
for _ in range(12):
L.append(ligne("2026-11-04", "/", "bureau", ref="duckduckgo.com"))
for _ in range(7):
L.append(ligne("2026-11-04", "/a-propos.html", "mobile", ref="https://www.google.com/search?q=secret", langue="en"))
L.append(ligne("2026-11-04", "/cgu", "mobile", ref="petit-site.fr")) # 1 occurrence : jamais publié
for _ in range(3):
L.append(ligne("2026-11-03", "/", "bureau")) # jour < 5 : null
for _ in range(30):
L.append(ligne("2026-11-04", "/", "robot")) # robots : hors vues
L += [ligne("2026-11-04", "/data/meteo.json"), ligne("2026-11-04", "/polices/x.woff2"),
ligne("2026-11-04", "/app.js"), ligne("2026-11-04", "/inexistant", status=404),
ligne("2026-11-04", "/", methode="POST"), ligne("2026-11-04", "/", hote="autre.org"),
ligne("2026-11-04", "/", ref="https://vercors.me/a-propos"), "pas du json", "[1,2]", ""]
L.append(ligne("2026-11-04", "/?utm=jeton123", brut=True)) # requête avec IP brute
return "\n".join(L) + "\n"
def lancer(dossier, sortie="s.json"):
args = ["--journaux", os.path.join(dossier, "vercors.me*.log*"), "--etat", os.path.join(dossier, "etat.json"),
"--sortie", os.path.join(dossier, sortie), "--maintenant", "2026-11-05T10:00:00Z"]
assert st.main(args) == 0
with open(os.path.join(dossier, sortie), encoding="utf-8") as f:
return f.read()
def main():
with tempfile.TemporaryDirectory() as d:
with open(os.path.join(d, "vercors.me.log"), "w", encoding="utf-8") as f:
f.write(faux_journal())
with gzip.open(os.path.join(d, "vercors.me-2026.log.gz"), "wt", encoding="utf-8") as f:
f.write(ligne("2026-11-02", "/", "bureau") + "\n")
brut = lancer(d)
s = json.loads(brut)
# rien d'individuel
for interdit in (IP_SECRETE, "secret", "jeton123", "remote_ip", "Cookie", "petit-site.fr", "q="):
assert interdit not in brut, interdit
assert "secret" not in open(os.path.join(d, "etat.json"), encoding="utf-8").read()
assert IP_SECRETE not in open(os.path.join(d, "etat.json"), encoding="utf-8").read()
jours = {j["jour"]: j["pages_vues"] for j in s["par_jour"]}
assert jours["2026-11-04"] == 12 + 7 + 1 + 1 + 1 + 0, jours["2026-11-04"] # /, a-propos, cgu, ref interne, brut
assert jours["2026-11-03"] is None and jours["2026-11-02"] is None and jours["2026-11-05"] is None
pages = {p["page"]: p["vues"] for p in s["pages_les_plus_vues"]}
assert pages == {"/": 12 + 1 + 1 + 3 + 1, "/a-propos": 7}, pages
assert "/cgu" not in pages and "/data/meteo.json" not in pages and "/app.js" not in pages
assert all(v >= st.SEUIL for v in pages.values())
assert s["appareils_pct"]["telephone"] is not None and s["appareils_pct"]["ordinateur"] is not None
assert 0 <= s["appareils_pct"]["telephone"] <= 100
sites = {r["site"] for r in s["referents"]}
assert sites == {"duckduckgo.com", "google.com"}, sites
assert [l["langue"] for l in s["langues"]] == ["fr", "en"] or {l["langue"] for l in s["langues"]} == {"fr", "en"}
assert s["seuil"] == 5 and s["periode"]["fin"] == "2026-11-05" and len(s["par_jour"]) == 90
# idempotence : relancer ne double rien
assert json.loads(lancer(d, "s2.json")) == s
# journaux purgés : l'historique de l'état est conservé
os.remove(os.path.join(d, "vercors.me.log"))
s3 = json.loads(lancer(d, "s3.json"))
assert {j["jour"]: j["pages_vues"] for j in s3["par_jour"]}["2026-11-04"] == 22
# heure d'été : 31 octobre 2026 22:30 UTC = 23:30 à Paris, 1er novembre 00:30 en heure d'hiver
assert st.jour_paris(dt.datetime(2026, 10, 31, 22, 30, tzinfo=dt.timezone.utc).timestamp()) == "2026-10-31"
assert st.jour_paris(dt.datetime(2026, 11, 1, 23, 30, tzinfo=dt.timezone.utc).timestamp()) == "2026-11-02"
assert st.page_normalisee("/index.html") == "/" and st.page_normalisee("/a-propos/") == "/a-propos"
assert st.page_normalisee("/x.php") is None and st.page_normalisee("/a b") is None
print("OK")
if __name__ == "__main__":
main()