"""Tests del CLI del generador (la interfaz que consumirá el panel, Etapa 3). Cubre códigos de salida, salida --json y el flujo whatsapp con Evolution mockeado. El estampado escribe en tmp_path vía monkeypatch de DIR_REPLICAS. """ import json from pathlib import Path import pytest import yaml import generador.__main__ as cli from generador import nucleo from generador.nucleo import RAIZ_MOLDE FICHA_DEMO = RAIZ_MOLDE / "fichas" / "ejemplo-demo.yml" @pytest.fixture() def entorno(tmp_path, monkeypatch): """Redirige replicas/ y el registro a tmp_path para no tocar el repo.""" salida = tmp_path / "replicas" monkeypatch.setattr(cli, "DIR_REPLICAS", salida) monkeypatch.setattr(nucleo, "DIR_REPLICAS", salida) # estampar() usa permitir_sucio vía flag; los tests corren con árbol # de desarrollo → parchea el default del CLI inyectando el flag. return salida def _ficha(tmp_path, slug="cli-uno") -> Path: datos = yaml.safe_load(FICHA_DEMO.read_text(encoding="utf-8")) datos["cliente"]["slug"] = slug ruta = tmp_path / f"{slug}.yml" ruta.write_text(yaml.safe_dump(datos, allow_unicode=True), encoding="utf-8") return ruta def test_estampar_json_para_el_panel(entorno, tmp_path, capsys): rc = cli.main(["estampar", str(_ficha(tmp_path)), "--json", "--permitir-sucio"]) salida = json.loads(capsys.readouterr().out) assert rc == 0 assert salida["ok"] is True assert salida["slug"] == "cli-uno" assert salida["estado"] == "estampada" assert all(c["ok"] for c in salida["checks"]) def test_estampar_ficha_invalida_json_error(entorno, tmp_path, capsys): datos = yaml.safe_load(FICHA_DEMO.read_text(encoding="utf-8")) datos["cliente"]["slug"] = "Slug Malo" ruta = tmp_path / "mala.yml" ruta.write_text(yaml.safe_dump(datos, allow_unicode=True), encoding="utf-8") rc = cli.main(["estampar", str(ruta), "--json"]) salida = json.loads(capsys.readouterr().out) assert rc == 1 assert salida["ok"] is False and "slug inválido" in salida["error"] def test_listar_y_eliminar(entorno, tmp_path, capsys): cli.main(["estampar", str(_ficha(tmp_path, "cli-uno")), "--permitir-sucio"]) cli.main(["estampar", str(_ficha(tmp_path, "cli-dos")), "--permitir-sucio"]) capsys.readouterr() rc = cli.main(["listar", "--json"]) replicas = json.loads(capsys.readouterr().out) assert rc == 0 and set(replicas) == {"cli-uno", "cli-dos"} assert replicas["cli-uno"]["puerto"] != replicas["cli-dos"]["puerto"] rc = cli.main(["eliminar", "cli-uno", "--borrar-carpeta"]) assert rc == 0 assert not (entorno / "cli-uno").exists() capsys.readouterr() # descarta la salida de eliminar rc = cli.main(["listar", "--json"]) assert set(json.loads(capsys.readouterr().out)) == {"cli-dos"} # eliminar algo inexistente → error claro, exit 1 rc = cli.main(["eliminar", "no-existe"]) assert rc == 1 def test_validar_paquete_existente_y_roto(entorno, tmp_path, capsys): cli.main(["estampar", str(_ficha(tmp_path, "cli-uno")), "--permitir-sucio"]) capsys.readouterr() assert cli.main(["validar", "cli-uno"]) == 0 # romper el paquete → validar falla (entorno / "cli-uno" / "Plantilla_WK2.docm").write_bytes(b"fake") assert cli.main(["validar", "cli-uno"]) == 1 # paquete inexistente → exit 1 assert cli.main(["validar", "nope"]) == 1 def test_whatsapp_flujo_completo_mockeado(entorno, tmp_path, capsys, monkeypatch): """El comando whatsapp aprovisiona, guarda el QR y termina al ver 'open'.""" cli.main(["estampar", str(_ficha(tmp_path, "cli-uno")), "--permitir-sucio"]) capsys.readouterr() import httpx from tests.test_generador_evolution import EvolutionFalso from generador import evolution as evo_mod falso = EvolutionFalso() # estado inicial: connecting class ClienteMockeado(evo_mod.ClienteEvolution): def __init__(self, api_url, api_key, transport=None): super().__init__( "http://evolution.fake", "clave-buena", transport=httpx.MockTransport(falso.handler), ) monkeypatch.setattr(evo_mod, "ClienteEvolution", ClienteMockeado) # sin esperas reales: el primer sleep marca la instancia como conectada def sleep_falso(_s): falso.estado = "open" monkeypatch.setattr(cli.time, "sleep", sleep_falso) rc = cli.main(["whatsapp", "cli-uno"]) out = capsys.readouterr().out assert rc == 0 assert "WhatsApp vinculado" in out # el QR quedó en el paquete assert (entorno / "cli-uno" / "qr-whatsapp.png").exists() # y el webhook configurado apunta al adaptador nativo de ESTA réplica webhook = next(c for m, r, c in falso.requests if r.startswith("/webhook/set/")) assert webhook["webhook"]["url"] == "https://demo-bot.ejemplo.mx/webhook/evolution" def test_whatsapp_ya_vinculado_no_pide_qr(entorno, tmp_path, capsys, monkeypatch): cli.main(["estampar", str(_ficha(tmp_path, "cli-uno")), "--permitir-sucio"]) capsys.readouterr() import httpx from tests.test_generador_evolution import EvolutionFalso from generador import evolution as evo_mod falso = EvolutionFalso(instancias={"cli-uno"}, estado="open") class ClienteMockeado(evo_mod.ClienteEvolution): def __init__(self, api_url, api_key, transport=None): super().__init__( "http://evolution.fake", "clave-buena", transport=httpx.MockTransport(falso.handler), ) monkeypatch.setattr(evo_mod, "ClienteEvolution", ClienteMockeado) rc = cli.main(["whatsapp", "cli-uno"]) assert rc == 0 assert "ya vinculado" in capsys.readouterr().out assert not (entorno / "cli-uno" / "qr-whatsapp.png").exists()