# -*- coding: utf-8 -*-
"""test_check_modules.py — 套件与配置渲染测试"""

from service_monitor.utils import check_modules as cm


def test_suites():
    quick = [m.id for m in cm.get_suite("quick")]
    full = [m.id for m in cm.get_suite("full")]
    assert "01_system_basic" in quick
    assert "22_mysql_basic" not in quick   # MySQL 仅全量
    assert "22_mysql_basic" in full
    assert set(quick).issubset(set(full))


def test_get_module():
    m = cm.get_module("20_docker_basic")
    assert m is not None
    assert m.category == "service"
    assert m.relpath == "service/20_docker_basic.sh"
    assert cm.get_module("nonexistent") is None


def test_render_config_credentials():
    target = {"credential_overrides": {"mysql_password": "p@ss'w\"x", "redis_password": "r1"}}
    out = cm.render_config(target)
    # 密码被 shell 安全引用
    assert "MYSQL_PASSWORD=" in out
    assert "p@ss" in out  # 值存在（引用形式）
    # 不应残留占位符
    assert "__MYSQL_PASSWORD__" not in out
    assert "__REDIS_PASSWORD__" not in out


def test_render_config_container_override():
    target = {"container_overrides": {"mysql": "umysql-prod"}}
    out = cm.render_config(target)
    assert 'CONTAINERS[mysql]="umysql-prod"' in out


def test_render_config_threshold_override():
    target = {"thresholds": {"cpu_warning": 90, "evil_key": "x"}}
    out = cm.render_config(target)
    assert "export CPU_WARNING=90" in out
    assert "evil_key" not in out.lower() or "EVIL_KEY" not in out


def test_render_config_injection_safe():
    # 注入尝试：值含分号和命令
    target = {"credential_overrides": {"mysql_password": "x'; rm -rf /; echo '"}}
    out = cm.render_config(target)
    # shlex.quote 应把整个值包在单引号里，分号不逃逸
    line = [l for l in out.splitlines() if l.startswith("MYSQL_PASSWORD=")][0]
    # 危险内容被引用，不作为独立命令
    assert "rm -rf" in line   # 内容还在，但被引用
    assert line.startswith("MYSQL_PASSWORD='")  # 以单引号开始包裹


def test_list_asset_files():
    files = cm.list_asset_files()
    names = [f.name for f in files]
    assert "common.sh" in names
    assert "config.sh.template" in names
    assert "01_system_basic.sh" in names
