feat(treblo): titre obligatoire, nom fichier nettoye, paroles html, script envoi (ticket nyora-2026-10-216-d)
This commit is contained in:
1 parent
a4cbda385c
commit
a325cf221d
5 files changed
+689
-44
No files matched your search
Executable
+288
@@ -0,0 +1,288 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import pytest
|
||||
import datetime
|
||||
import subprocess
|
||||
from zoneinfo import ZoneInfo
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from cap_check import TUNIS_TZ
|
||||
from main import (
|
||||
compute_empreinte,
|
||||
validate_titre,
|
||||
nettoyer_titre_fichier,
|
||||
titre_vers_nom_fichier,
|
||||
echapper_html,
|
||||
preparer_messages_paroles,
|
||||
generer,
|
||||
valider,
|
||||
send_telegram_preview_mp3,
|
||||
get_journal_path,
|
||||
get_validations_path,
|
||||
get_envois_path,
|
||||
get_titres_path,
|
||||
current_sphere_var
|
||||
)
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_test_env(monkeypatch, tmp_path):
|
||||
j_file = str(tmp_path / "journal.jsonl")
|
||||
v_file = str(tmp_path / "validations.json")
|
||||
e_file = str(tmp_path / "envois.jsonl")
|
||||
t_file = str(tmp_path / "titres.json")
|
||||
|
||||
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)
|
||||
monkeypatch.setattr("main.get_titres_path", lambda: t_file)
|
||||
|
||||
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")
|
||||
|
||||
# Mocks de sécurité : interdire tout envoi réel
|
||||
monkeypatch.setattr("main.send_telegram_validation_request", lambda *args, **kwargs: None)
|
||||
|
||||
|
||||
def test_validation_id_autre_contenu_refuse(monkeypatch, tmp_path):
|
||||
"""T0. Quand un validation_id est fourni mais ne correspond pas au contenu (tags/prompt/paroles),
|
||||
refus clair sans débit, et l'approbation reste intacte (statut APPROVED)."""
|
||||
v_file = str(tmp_path / "validations.json")
|
||||
now_tunis = datetime.datetime.now(TUNIS_TZ)
|
||||
exp = (now_tunis + datetime.timedelta(minutes=15)).isoformat()
|
||||
|
||||
# Approbation pour des tags 'blues'
|
||||
emp_blues = compute_empreinte("nyora", ["blues"], "", "")
|
||||
|
||||
init_data = {
|
||||
"validations": [
|
||||
{
|
||||
"id": "val_blues_ok",
|
||||
"sphere": "nyora",
|
||||
"empreinte": emp_blues,
|
||||
"code": "654321",
|
||||
"status": "APPROVED",
|
||||
"attempts": 0,
|
||||
"created_at": now_tunis.isoformat(),
|
||||
"expires_at": exp,
|
||||
"details": {"tags": ["blues"], "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:
|
||||
balance_called = {"count": 0}
|
||||
def fake_balance(sp):
|
||||
balance_called["count"] += 1
|
||||
return {"sphere": sp, "total": 9200, "num_credits": 0, "num_credits_payg": 9200}
|
||||
monkeypatch.setattr("main.treblo_balance", fake_balance)
|
||||
|
||||
# Appel avec d'autres tags ("ambient") et le validation_id "val_blues_ok"
|
||||
with pytest.raises(ValueError) as exc:
|
||||
generer(sphere="nyora", titre="Test Ambient", tags=["ambient"], validation_id="val_blues_ok")
|
||||
|
||||
err = str(exc.value).lower()
|
||||
assert "refus" in err or "approbation" in err or "empreinte" in err
|
||||
|
||||
# L'approbation doit rester intacte (APPROVED)
|
||||
with open(v_file, "r", encoding="utf-8") as f:
|
||||
v_check = json.load(f)
|
||||
assert v_check["validations"][0]["status"] == "APPROVED"
|
||||
assert "used_at" not in v_check["validations"][0]
|
||||
|
||||
# Aucun appel Treblo balance pour générer
|
||||
assert balance_called["count"] == 0
|
||||
|
||||
# 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_nom_fichier_depuis_titre():
|
||||
"""T2. Nettoyage du nom de fichier : accents conservés, espaces multiples réduits, extension .mp3."""
|
||||
assert titre_vers_nom_fichier("Brume de Nuit") == "Brume de Nuit.mp3"
|
||||
assert titre_vers_nom_fichier("Blues sous la Pluie") == "Blues sous la Pluie.mp3"
|
||||
assert titre_vers_nom_fichier("Éphémère été à Paris") == "Éphémère été à Paris.mp3"
|
||||
assert titre_vers_nom_fichier(" Chanson avec espaces ") == "Chanson avec espaces.mp3"
|
||||
|
||||
|
||||
def test_nom_fichier_caracteres_interdits():
|
||||
"""T2. Remplacement des caractères interdits / \\ : * ? \" < > | et caractères de contrôle par un tiret, limite 80 car."""
|
||||
raw = 'Rock / Pop : Live * 2026 ? "Great" <Old> | New \\ Best\x07'
|
||||
res = titre_vers_nom_fichier(raw)
|
||||
assert res == 'Rock - Pop - Live - 2026 - -Great- -Old- - New - Best-.mp3'
|
||||
for c in '/\\:*?"<>|\x07':
|
||||
assert c not in res
|
||||
|
||||
# Troncation à 80 caractères au plus (hors extension)
|
||||
long_titre = "Z" * 120
|
||||
res_long = titre_vers_nom_fichier(long_titre)
|
||||
assert res_long == ("Z" * 80) + ".mp3"
|
||||
|
||||
|
||||
def test_titre_obligatoire(monkeypatch, tmp_path):
|
||||
"""T1. Le paramètre titre est obligatoire, 1-60 caractères, sans nom d'artiste ni formule 'comme X'."""
|
||||
token_cv = current_sphere_var.set("nyora")
|
||||
try:
|
||||
# Titre vide
|
||||
with pytest.raises(ValueError) as exc1:
|
||||
generer(sphere="nyora", titre="")
|
||||
assert "titre" in str(exc1.value).lower()
|
||||
|
||||
# Titre avec espaces seuls
|
||||
with pytest.raises(ValueError) as exc1b:
|
||||
generer(sphere="nyora", titre=" ")
|
||||
assert "titre" in str(exc1b.value).lower()
|
||||
|
||||
# Titre > 60 caractères
|
||||
with pytest.raises(ValueError) as exc2:
|
||||
generer(sphere="nyora", titre="A" * 61, tags=["ambient"])
|
||||
assert "60" in str(exc2.value)
|
||||
|
||||
# Formule 'comme X' interdite
|
||||
with pytest.raises(ValueError) as exc3:
|
||||
generer(sphere="nyora", titre="Blues comme BB King", tags=["blues"])
|
||||
assert "comme" in str(exc3.value).lower()
|
||||
|
||||
# Formule 'like X'
|
||||
with pytest.raises(ValueError) as exc3b:
|
||||
generer(sphere="nyora", titre="Track like Miles Davis", tags=["jazz"])
|
||||
assert "titre" in str(exc3b.value).lower() or "comme" in str(exc3b.value).lower()
|
||||
|
||||
# Titre valide accepté par la validation
|
||||
assert validate_titre("Brume de Nuit") == "Brume de Nuit"
|
||||
finally:
|
||||
current_sphere_var.reset(token_cv)
|
||||
|
||||
|
||||
def test_paroles_mise_en_forme():
|
||||
"""T3. Paroles : titre en gras avec 🎵, étiquettes en italique, séparateur, paroles en blockquote avec strophes."""
|
||||
paroles = "Late at night when the city is still\nI hear the blues rolling down the hill\n\nOld acoustic guitar crying in the rain\nWhispering secrets of sorrow and pain"
|
||||
msgs = preparer_messages_paroles(
|
||||
titre="Blues sous la Pluie",
|
||||
tags=["southern soul", "blues", "soulful"],
|
||||
paroles=paroles
|
||||
)
|
||||
assert len(msgs) == 1
|
||||
m = msgs[0]
|
||||
assert "<b>🎵 Blues sous la Pluie</b>" in m
|
||||
assert "<i>southern soul, blues, soulful</i>" in m
|
||||
assert "---" in m
|
||||
assert "<blockquote>" in m and "</blockquote>" in m
|
||||
# Vérification que le saut de ligne entre strophes (\n\n) est bien conservé
|
||||
assert "Late at night when the city is still\nI hear the blues rolling down the hill\n\nOld acoustic guitar crying in the rain\nWhispering secrets of sorrow and pain" in m
|
||||
|
||||
|
||||
def test_paroles_echappement_html():
|
||||
"""T3. Tout le texte est échappé (&, <, >) avant mise en forme."""
|
||||
msgs = preparer_messages_paroles(
|
||||
titre="Rock & Roll <Live>",
|
||||
tags=["r&b", "<metal>"],
|
||||
paroles="Strophe 1 & 2 <test>\nFin > début"
|
||||
)
|
||||
assert len(msgs) == 1
|
||||
m = msgs[0]
|
||||
assert "Rock & Roll <Live>" in m
|
||||
assert "r&b, <metal>" in m
|
||||
assert "Strophe 1 & 2 <test>\nFin > début" in m
|
||||
assert "<Live>" not in m
|
||||
assert "<metal>" not in m
|
||||
assert "<test>" not in m
|
||||
|
||||
|
||||
def test_paroles_decoupage_4096():
|
||||
"""T3. Au-delà de 4096 caractères, découpage aux frontières de strophe en plusieurs messages <= 4096 car."""
|
||||
strophe_txt = "Ligne de chanson répétée pour tester la longueur du message.\n" * 8
|
||||
# 12 strophes pour dépasser largement 4096 caractères
|
||||
strophes = [f"Strophe {i+1} :\n" + strophe_txt for i in range(12)]
|
||||
paroles = "\n\n".join(strophes)
|
||||
assert len(paroles) > 5000
|
||||
|
||||
msgs = preparer_messages_paroles(
|
||||
titre="Épopée Longue",
|
||||
tags=["epic", "ambient"],
|
||||
paroles=paroles
|
||||
)
|
||||
assert len(msgs) >= 2
|
||||
for idx, m in enumerate(msgs):
|
||||
assert len(m) <= 4096
|
||||
assert m.endswith("</blockquote>")
|
||||
if idx == 0:
|
||||
assert "<b>🎵 Épopée Longue</b>" in m
|
||||
assert "<i>epic, ambient</i>" in m
|
||||
assert "---" in m
|
||||
assert "<blockquote>" in m
|
||||
else:
|
||||
assert "<blockquote>" in m
|
||||
|
||||
# Vérifier que toutes les strophes sont présentes dans l'ensemble des messages
|
||||
corpus = "".join(msgs)
|
||||
for i in range(12):
|
||||
assert f"Strophe {i+1} :" in corpus
|
||||
|
||||
|
||||
def test_instrumental_message_dedie():
|
||||
"""T3. Chanson instrumentale sans paroles : court message Instrumental avec titre et étiquettes."""
|
||||
msgs = preparer_messages_paroles(
|
||||
titre="Brume de Nuit",
|
||||
tags=["ambient", "piano", "chill"],
|
||||
paroles=""
|
||||
)
|
||||
assert len(msgs) == 1
|
||||
m = msgs[0]
|
||||
assert "<b>🎵 Brume de Nuit</b>" in m
|
||||
assert "<i>ambient, piano, chill</i>" in m
|
||||
assert "Instrumental" in m
|
||||
assert "<blockquote>" not in m
|
||||
|
||||
|
||||
def test_envoi_cli_claude(monkeypatch, tmp_path):
|
||||
"""T4. Script /app/envoyer_apercu.py avec --aide mentionnant task_id et --titre, et exécution conforme."""
|
||||
# Test aide
|
||||
script_path = "/app/envoyer_apercu.py"
|
||||
if not os.path.exists(script_path):
|
||||
script_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "envoyer_apercu.py")
|
||||
|
||||
proc = subprocess.run([sys.executable, script_path, "--aide"], capture_output=True, text=True)
|
||||
assert proc.returncode == 0
|
||||
assert "task_id" in proc.stdout
|
||||
assert "--titre" in proc.stdout
|
||||
|
||||
# Test fonctionnel CLI avec simulateur Telegram
|
||||
musique_dir = tmp_path / "musique" / "perso"
|
||||
musique_dir.mkdir(parents=True, exist_ok=True)
|
||||
mp3_file = musique_dir / "task_cli_test_123.mp3"
|
||||
mp3_file.write_bytes(b"FAKE_AUDIO_DATA")
|
||||
|
||||
json_file = musique_dir / "task_cli_test_123.json"
|
||||
json_file.write_text(json.dumps({"tags": ["blues"], "paroles": "Lyrics"}), encoding="utf-8")
|
||||
|
||||
calls = []
|
||||
def fake_send(sphere, mp3_path, task_id, titre=None, tags=None, paroles=None):
|
||||
calls.append({"sphere": sphere, "task_id": task_id, "titre": titre, "tags": tags, "paroles": paroles})
|
||||
return {"message_id": 1234, "texte_message_id": 5678}
|
||||
|
||||
import envoyer_apercu
|
||||
monkeypatch.setattr(envoyer_apercu, "send_telegram_preview_mp3", fake_send)
|
||||
monkeypatch.setattr(envoyer_apercu, "get_titre_for_task", lambda tid: "Blues sous la Pluie")
|
||||
monkeypatch.setattr(envoyer_apercu, "get_musique_dir", lambda sp: str(tmp_path / "musique" / sp))
|
||||
|
||||
test_argv = ["envoyer_apercu.py", "task_cli_test_123", "--sphere", "perso", "--titre", "Blues sous la Pluie"]
|
||||
monkeypatch.setattr(sys, "argv", test_argv)
|
||||
|
||||
envoyer_apercu.main()
|
||||
assert len(calls) == 1
|
||||
assert calls[0]["task_id"] == "task_cli_test_123"
|
||||
assert calls[0]["sphere"] == "perso"
|
||||
assert calls[0]["titre"] == "Blues sous la Pluie"
|
||||
Reference in new issue
Block a user