_link_panel_cobranza referenciaba cobranza_acumulada sin importarlo (solo se importa dentro de otras funciones, no a nivel de módulo) → NameError en cada llamada → el except 'resiliente' lo tragaba → devolvía None → reporte SIN link. Afectaba a AMBOS emisores (automático y on-demand), no solo al del scheduler. No era timing ni cableado: era un import faltante. Fix: importar cobranza_acumulada dentro del helper (mismo patrón que las otras funciones). Además: warning explícito en el scheduler cuando el reporte sale sin link, y el helper loguea con el número. NO toca calculator.py. 105 tests (+2: regresión URL ok y resiliencia None). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
97 lines
3.8 KiB
Python
97 lines
3.8 KiB
Python
"""
|
|
Token admin: sesión única por número (un token activo, indefinido, el anterior
|
|
se cancela al generar otro). Usa fakeredis. También cubre el link en el reporte
|
|
diario.
|
|
"""
|
|
import os
|
|
|
|
import fakeredis.aioredis
|
|
import pytest
|
|
|
|
os.environ.setdefault("OPENAI_API_KEY", "test-key-no-usada")
|
|
|
|
from src.services import recordatorios
|
|
from src.api import webhook as wh
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _patch_redis(monkeypatch):
|
|
fake = fakeredis.aioredis.FakeRedis(decode_responses=True)
|
|
# recordatorios importó get_client por nombre → hay que parchear ahí.
|
|
monkeypatch.setattr(recordatorios, "get_client", lambda: fake)
|
|
yield fake
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_token_valida_y_es_indefinido(_patch_redis):
|
|
tok = await recordatorios.crear_token_admin("2223334444")
|
|
assert await recordatorios.validar_token_admin(tok) == "2223334444"
|
|
# Indefinido: la key NO tiene TTL (-1 = sin expiración en Redis).
|
|
assert await _patch_redis.ttl(f"admin_token:{tok}") == -1
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_token_nuevo_cancela_anterior(_patch_redis):
|
|
viejo = await recordatorios.crear_token_admin("2223334444")
|
|
nuevo = await recordatorios.crear_token_admin("2223334444")
|
|
assert viejo != nuevo
|
|
# El anterior deja de validar; solo el nuevo funciona.
|
|
assert await recordatorios.validar_token_admin(viejo) is None
|
|
assert await recordatorios.validar_token_admin(nuevo) == "2223334444"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_sesion_unica_es_por_numero(_patch_redis):
|
|
tok_a = await recordatorios.crear_token_admin("1111111111")
|
|
tok_b = await recordatorios.crear_token_admin("2222222222")
|
|
# Regenerar A no afecta a B (cada número su propia sesión).
|
|
tok_a2 = await recordatorios.crear_token_admin("1111111111")
|
|
assert await recordatorios.validar_token_admin(tok_a) is None
|
|
assert await recordatorios.validar_token_admin(tok_a2) == "1111111111"
|
|
assert await recordatorios.validar_token_admin(tok_b) == "2222222222"
|
|
|
|
|
|
# ── Link en el reporte diario ────────────────────────────────────
|
|
|
|
def _reporte():
|
|
from datetime import date
|
|
return {"fecha": date(2026, 7, 10), "es_lunes": False,
|
|
"rentas": [], "vr": [], "extras": []}
|
|
|
|
|
|
def test_reporte_diario_incluye_link():
|
|
link = "http://x/admin/cobranza/ui?token=abc"
|
|
texto = wh._formatear_reporte(_reporte(), link=link)
|
|
assert "Panel Mi Cobranza" in texto
|
|
assert link in texto
|
|
# El link va en las primeras filas (antes de "Rentas del día").
|
|
assert texto.index(link) < texto.index("Rentas del día")
|
|
|
|
|
|
def test_reporte_diario_sin_link_no_rompe():
|
|
texto = wh._formatear_reporte(_reporte(), link=None)
|
|
assert "Panel Mi Cobranza" not in texto
|
|
assert "Rentas del día" in texto # el reporte se arma igual
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_link_panel_resiliente_devuelve_none_si_token_falla(monkeypatch):
|
|
# Si crear_token_cobranza lanza, el helper NO propaga: devuelve None (y loguea).
|
|
from src.services import cobranza_acumulada as ca
|
|
async def _boom(_n):
|
|
raise RuntimeError("redis caído")
|
|
monkeypatch.setattr(ca, "crear_token_cobranza", _boom)
|
|
assert await wh._link_panel_cobranza("5212731562186@s.whatsapp.net") is None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_link_panel_ok_devuelve_url(monkeypatch):
|
|
# Regresión del bug: el helper importa cobranza_acumulada y arma la URL bien
|
|
# (antes fallaba con NameError y el reporte salía siempre sin link).
|
|
from src.services import cobranza_acumulada as ca
|
|
async def _tok(_n):
|
|
return "tok-xyz"
|
|
monkeypatch.setattr(ca, "crear_token_cobranza", _tok)
|
|
url = await wh._link_panel_cobranza("5212731562186@s.whatsapp.net")
|
|
assert url is not None and url.endswith("/admin/cobranza/ui?token=tok-xyz")
|