feat(treblo): validation durcie, usage unique, 5 outils, code 6 chiffres et tests (ticket nyora-2026-10-216-c)
This commit is contained in:
1 parent
1d6c3a157d
commit
a4cbda385c
4 files changed
+490
-31
No files matched your search
@@ -18,7 +18,7 @@ AUTH_HEADERS_NYORA = {
|
||||
"Accept": "application/json, text/event-stream"
|
||||
}
|
||||
|
||||
EXPECTED_TOOLS = {"generer", "statut", "recuperer", "solde"}
|
||||
EXPECTED_TOOLS = {"generer", "recuperer", "solde", "statut", "valider"}
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client():
|
||||
@@ -31,7 +31,7 @@ def test_health(client):
|
||||
data = r.json()
|
||||
assert data.get("status") == "ok"
|
||||
assert data.get("service") == "treblo-mcp"
|
||||
assert data.get("tools") == 4
|
||||
assert data.get("tools") == 5
|
||||
|
||||
def test_auth_rejection(client):
|
||||
# Sans auth
|
||||
|
||||
Executable
+316
@@ -0,0 +1,316 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os
|
||||
import json
|
||||
import pytest
|
||||
import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from cap_check import TUNIS_TZ, get_tunis_date, count_today
|
||||
from main import (
|
||||
compute_empreinte,
|
||||
valider,
|
||||
generer,
|
||||
check_daily_cap,
|
||||
update_journal_task,
|
||||
get_journal_path,
|
||||
get_validations_path,
|
||||
current_sphere_var
|
||||
)
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_env(monkeypatch, tmp_path):
|
||||
# Fichiers temporaires pour isoler chaque test
|
||||
j_file = str(tmp_path / "journal.jsonl")
|
||||
v_file = str(tmp_path / "validations.json")
|
||||
e_file = str(tmp_path / "envois.jsonl")
|
||||
|
||||
monkeypatch.setattr("main.get_journal_path", lambda: j_file)
|
||||
monkeypatch.setattr("main.get_validations_path", lambda: v_file)
|
||||
monkeypatch.setattr("main.get_envois_path", lambda: e_file)
|
||||
|
||||
# Variables d'environnement factices
|
||||
monkeypatch.setenv("TREBLO_MCP_TOKEN_NYORA", "test_nyora_token_123456789012345678901234567890123456")
|
||||
monkeypatch.setenv("TREBLO_MCP_TOKEN_PERSO", "test_perso_token_123456789012345678901234567890123456")
|
||||
monkeypatch.setenv("TREBLO_KEY_NYORA", "test_nyora_key")
|
||||
monkeypatch.setenv("TREBLO_KEY_PERSO", "test_perso_key")
|
||||
monkeypatch.setenv("TELEGRAM_BOT_TOKEN_NYORA", "fake_bot_token")
|
||||
monkeypatch.setenv("TELEGRAM_CHAT_ID", "2084513684")
|
||||
|
||||
# Neutraliser l'envoi réel de requêtes Telegram
|
||||
monkeypatch.setattr("main.send_telegram_validation_request", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr("main.send_telegram_preview_mp3", lambda *args, **kwargs: None)
|
||||
|
||||
def test_approbation_usage_unique(monkeypatch, tmp_path):
|
||||
"""(a) Une approbation est à usage unique, consommée par la génération qu'elle autorise (statut USED), jamais réutilisable."""
|
||||
v_file = str(tmp_path / "validations.json")
|
||||
now_tunis = datetime.datetime.now(TUNIS_TZ)
|
||||
exp = (now_tunis + datetime.timedelta(minutes=15)).isoformat()
|
||||
emp = compute_empreinte("nyora", ["ambient"], "", "")
|
||||
|
||||
# Demande initiale approuvée
|
||||
init_data = {
|
||||
"validations": [
|
||||
{
|
||||
"id": "val_unique",
|
||||
"sphere": "nyora",
|
||||
"empreinte": emp,
|
||||
"code": "123456",
|
||||
"status": "APPROVED",
|
||||
"attempts": 0,
|
||||
"created_at": now_tunis.isoformat(),
|
||||
"expires_at": exp,
|
||||
"details": {"tags": ["ambient"], "prompt": "", "paroles": ""}
|
||||
}
|
||||
]
|
||||
}
|
||||
with open(v_file, "w", encoding="utf-8") as f:
|
||||
json.dump(init_data, f)
|
||||
|
||||
token_cv = current_sphere_var.set("nyora")
|
||||
try:
|
||||
# Mock solde Treblo et appel API Treblo génération
|
||||
monkeypatch.setattr("main.treblo_balance", lambda sp: {"sphere": sp, "total": 9200, "num_credits": 0, "num_credits_payg": 9200})
|
||||
|
||||
mock_resp = MagicMock()
|
||||
mock_resp.read.return_value = json.dumps({"task_id": "task_unique_1", "status": "PENDING"}).encode("utf-8")
|
||||
mock_resp.__enter__.return_value = mock_resp
|
||||
monkeypatch.setattr("urllib.request.urlopen", lambda *args, **kwargs: mock_resp)
|
||||
|
||||
# 1er appel à generer : doit réussir et consommer l'approbation
|
||||
res = generer(sphere="nyora", tags=["ambient"])
|
||||
assert res.get("task_id") == "task_unique_1"
|
||||
|
||||
# Vérifier que le statut est passé à USED
|
||||
with open(v_file, "r", encoding="utf-8") as f:
|
||||
v_check = json.load(f)
|
||||
assert v_check["validations"][0]["status"] == "USED"
|
||||
|
||||
# 2ème appel avec les mêmes paramètres : doit refuser car l'approbation est déjà consommée
|
||||
with pytest.raises(ValueError) as exc:
|
||||
generer(sphere="nyora", tags=["ambient"])
|
||||
assert "validation humaine requise" in str(exc.value)
|
||||
|
||||
finally:
|
||||
current_sphere_var.reset(token_cv)
|
||||
|
||||
def test_empreinte_inclut_tags():
|
||||
"""(b) Empreinte = SHA-256 de (sphère, tags triés, prompt, paroles)."""
|
||||
# Deux ensembles de tags différents donnent deux empreintes distinctes (même sans prompt ni paroles)
|
||||
e1 = compute_empreinte("nyora", ["ambient"], "", "")
|
||||
e2 = compute_empreinte("nyora", ["piano"], "", "")
|
||||
assert e1 != e2
|
||||
|
||||
# L'ordre des tags ne change pas l'empreinte (tri canonique)
|
||||
e_order1 = compute_empreinte("nyora", ["piano", "ambient"], "", "")
|
||||
e_order2 = compute_empreinte("nyora", ["ambient", "piano"], "", "")
|
||||
assert e_order1 == e_order2
|
||||
|
||||
# La sphère influence l'empreinte
|
||||
e_perso = compute_empreinte("perso", ["ambient"], "", "")
|
||||
assert e_perso != e1
|
||||
|
||||
# Prompt ou paroles modifient l'empreinte
|
||||
e_prompt = compute_empreinte("nyora", ["ambient"], "un prompt jazz", "")
|
||||
assert e_prompt != e1
|
||||
|
||||
def test_valider_code_incorrect_refuse(tmp_path):
|
||||
"""(c) valider refuse si le code à 6 chiffres est incorrect."""
|
||||
v_file = str(tmp_path / "validations.json")
|
||||
now_tunis = datetime.datetime.now(TUNIS_TZ)
|
||||
exp = (now_tunis + datetime.timedelta(minutes=15)).isoformat()
|
||||
|
||||
init_data = {
|
||||
"validations": [
|
||||
{
|
||||
"id": "val_bad_code",
|
||||
"sphere": "nyora",
|
||||
"empreinte": "dummy_emp",
|
||||
"code": "555666",
|
||||
"status": "PENDING",
|
||||
"attempts": 0,
|
||||
"created_at": now_tunis.isoformat(),
|
||||
"expires_at": exp,
|
||||
"details": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
with open(v_file, "w", encoding="utf-8") as f:
|
||||
json.dump(init_data, f)
|
||||
|
||||
# Tentative avec un mauvais code
|
||||
with pytest.raises(ValueError) as exc:
|
||||
valider("val_bad_code", "000000")
|
||||
assert "Code incorrect" in str(exc.value)
|
||||
|
||||
# Statut toujours PENDING, 1 essai comptabilisé
|
||||
with open(v_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
v = data["validations"][0]
|
||||
assert v["status"] == "PENDING"
|
||||
assert v["attempts"] == 1
|
||||
|
||||
def test_valider_code_limite_essais(tmp_path):
|
||||
"""(d) Trois essais au plus par demande, puis la demande est annulée."""
|
||||
v_file = str(tmp_path / "validations.json")
|
||||
now_tunis = datetime.datetime.now(TUNIS_TZ)
|
||||
exp = (now_tunis + datetime.timedelta(minutes=15)).isoformat()
|
||||
|
||||
init_data = {
|
||||
"validations": [
|
||||
{
|
||||
"id": "val_3attempts",
|
||||
"sphere": "nyora",
|
||||
"empreinte": "dummy_emp",
|
||||
"code": "789123",
|
||||
"status": "PENDING",
|
||||
"attempts": 0,
|
||||
"created_at": now_tunis.isoformat(),
|
||||
"expires_at": exp,
|
||||
"details": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
with open(v_file, "w", encoding="utf-8") as f:
|
||||
json.dump(init_data, f)
|
||||
|
||||
# 1er échec
|
||||
with pytest.raises(ValueError):
|
||||
valider("val_3attempts", "111111")
|
||||
# 2ème échec
|
||||
with pytest.raises(ValueError):
|
||||
valider("val_3attempts", "222222")
|
||||
# 3ème échec -> déclenche l'annulation
|
||||
with pytest.raises(ValueError) as exc3:
|
||||
valider("val_3attempts", "333333")
|
||||
assert "annulée" in str(exc3.value).lower()
|
||||
|
||||
# Vérification que le statut est CANCELLED
|
||||
with open(v_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
assert data["validations"][0]["status"] == "CANCELLED"
|
||||
|
||||
# Même avec le code exact, la demande annulée est refusée
|
||||
with pytest.raises(ValueError) as exc_after:
|
||||
valider("val_3attempts", "789123")
|
||||
assert "annulée" in str(exc_after.value).lower()
|
||||
|
||||
def test_valider_expiration(tmp_path):
|
||||
"""(e) Une demande de validation expirée (15 minutes) ne peut pas être validée."""
|
||||
v_file = str(tmp_path / "validations.json")
|
||||
now_tunis = datetime.datetime.now(TUNIS_TZ)
|
||||
# Expirée il y a 5 minutes
|
||||
exp = (now_tunis - datetime.timedelta(minutes=5)).isoformat()
|
||||
|
||||
init_data = {
|
||||
"validations": [
|
||||
{
|
||||
"id": "val_expired",
|
||||
"sphere": "nyora",
|
||||
"empreinte": "dummy_emp",
|
||||
"code": "123456",
|
||||
"status": "PENDING",
|
||||
"attempts": 0,
|
||||
"created_at": (now_tunis - datetime.timedelta(minutes=20)).isoformat(),
|
||||
"expires_at": exp,
|
||||
"details": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
with open(v_file, "w", encoding="utf-8") as f:
|
||||
json.dump(init_data, f)
|
||||
|
||||
with pytest.raises(ValueError) as exc:
|
||||
valider("val_expired", "123456")
|
||||
assert "expirée" in str(exc.value).lower()
|
||||
|
||||
with open(v_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
assert data["validations"][0]["status"] == "EXPIRED"
|
||||
|
||||
def test_generer_sans_validation_sans_debit(monkeypatch, tmp_path):
|
||||
"""(f) Un appel generer sans validation préalable refuse la génération sans aucun débit."""
|
||||
token_cv = current_sphere_var.set("nyora")
|
||||
try:
|
||||
# Mock solde Treblo
|
||||
balance_called = {"val": False}
|
||||
def fake_balance(sp):
|
||||
balance_called["val"] = True
|
||||
return {"sphere": sp, "total": 9200, "num_credits": 0, "num_credits_payg": 9200}
|
||||
monkeypatch.setattr("main.treblo_balance", fake_balance)
|
||||
|
||||
# Aucune validation dans validations.json
|
||||
with pytest.raises(ValueError) as exc:
|
||||
generer(sphere="nyora", tags=["ambient", "chill"])
|
||||
|
||||
err_msg = str(exc.value)
|
||||
assert "validation humaine requise" in err_msg.lower()
|
||||
|
||||
# Le message de refus envoyé à l'agent ne doit JAMAIS contenir le code à 6 chiffres
|
||||
with open(str(tmp_path / "validations.json"), "r", encoding="utf-8") as f:
|
||||
v_data = json.load(f)
|
||||
assert len(v_data["validations"]) == 1
|
||||
created_val = v_data["validations"][0]
|
||||
code = created_val["code"]
|
||||
assert len(code) == 6
|
||||
assert code not in err_msg
|
||||
|
||||
# Aucun journal écrit
|
||||
j_path = str(tmp_path / "journal.jsonl")
|
||||
assert not os.path.exists(j_path) or os.path.getsize(j_path) == 0
|
||||
|
||||
finally:
|
||||
current_sphere_var.reset(token_cv)
|
||||
|
||||
def test_plafond_jour_tunis(monkeypatch, tmp_path):
|
||||
"""(g) Plafond journalier calculé en jour civil de Tunis."""
|
||||
j_file = str(tmp_path / "journal.jsonl")
|
||||
now_tunis = datetime.datetime.now(TUNIS_TZ)
|
||||
today_tunis = now_tunis.strftime("%Y-%m-%d")
|
||||
|
||||
# Écrire 5 entrées horodatées aujourd'hui en heure de Tunis
|
||||
entries = [
|
||||
{"date": f"{today_tunis}T08:00:00+01:00", "sphere": "nyora", "statut": "SUCCESS"},
|
||||
{"date": f"{today_tunis}T09:00:00+01:00", "sphere": "nyora", "statut": "SUCCESS"},
|
||||
{"date": f"{today_tunis}T10:00:00+01:00", "sphere": "nyora", "statut": "SUCCESS"},
|
||||
{"date": f"{today_tunis}T11:00:00+01:00", "sphere": "nyora", "statut": "SUCCESS"},
|
||||
{"date": f"{today_tunis}T12:00:00+01:00", "sphere": "nyora", "statut": "SUCCESS"},
|
||||
# Une entrée d'hier à Tunis (ne doit pas être comptée)
|
||||
{"date": "2026-10-30T10:00:00+01:00", "sphere": "nyora", "statut": "SUCCESS"},
|
||||
]
|
||||
with open(j_file, "w", encoding="utf-8") as f:
|
||||
for e in entries:
|
||||
f.write(json.dumps(e) + "\n")
|
||||
|
||||
monkeypatch.setenv("TREBLO_DAILY_CAP", "5")
|
||||
# Pour nyora : 5 aujourd'hui -> CAP_REFUSED
|
||||
with pytest.raises(ValueError) as exc:
|
||||
check_daily_cap("nyora")
|
||||
assert "CAP_REFUSED" in str(exc.value)
|
||||
|
||||
# Pour perso : 0 aujourd'hui -> OK
|
||||
check_daily_cap("perso")
|
||||
|
||||
def test_credits_apres_reel(tmp_path):
|
||||
"""(h) Le journal consigne credits_apres avec le solde réel de l'API Treblo après exécution."""
|
||||
j_file = str(tmp_path / "journal.jsonl")
|
||||
task_id = "test_task_solde"
|
||||
init_entry = {
|
||||
"date": "2026-11-02T10:00:00Z",
|
||||
"sphere": "nyora",
|
||||
"task_id": task_id,
|
||||
"statut": "PENDING",
|
||||
"credits_avant": 9300,
|
||||
"credits_apres": 9300
|
||||
}
|
||||
with open(j_file, "w", encoding="utf-8") as f:
|
||||
f.write(json.dumps(init_entry) + "\n")
|
||||
|
||||
# Mise à jour avec le solde réel constaté après génération (débit de 100 crédits -> 9200)
|
||||
update_journal_task(task_id, "SUCCESS", credits_apres=9200)
|
||||
|
||||
with open(j_file, "r", encoding="utf-8") as f:
|
||||
line = f.readline().strip()
|
||||
data = json.loads(line)
|
||||
assert data["statut"] == "SUCCESS"
|
||||
assert data["credits_apres"] == 9200
|
||||
Reference in new issue
Block a user