import pytest,pytest_html
from asterisksecurity.encryption import AsteriskEncrypt
from asterisksecurity.error import InvalidEncriptionKey
import sys
from asterisksecurity.console import encrypt, decrypt


@pytest.mark.console
class TestConsoleEncrypt:
    def test_encrypt_missing_key(self, monkeypatch, capsys):
        monkeypatch.setattr(sys, 'argv', ['console.py', '-txt', 'test'])
        encrypt()
        assert "加密密钥不能为空。" in capsys.readouterr().out

    def test_encrypt_missing_text(self, monkeypatch, capsys):
        monkeypatch.setattr(sys, 'argv', ['console.py', '-key', 'testkey'])
        encrypt()
        assert "需要加密的字符串不能为空。" in capsys.readouterr().out

    def test_encrypt_valid(self, monkeypatch, capsys):
        monkeypatch.setattr(sys, 'argv', ['console.py', '-key', 'validkey123', '-txt', 'testtext'])
        encrypt()
        assert "加密结果：" in capsys.readouterr().out

    def test_encrypt_invalid_key(self, monkeypatch):
        monkeypatch.setattr(sys, 'argv', ['console.py', '-key', 'invalid key!', '-txt', 'test'])
        with pytest.raises(InvalidEncriptionKey):
            encrypt()

@pytest.mark.console
class TestConsoleDecrypt:
    def test_decrypt_missing_key(self, monkeypatch, capsys):
        monkeypatch.setattr(sys, 'argv', ['console.py', '-txt', 'encrypted'])
        decrypt()
        assert "解密密钥不能为空。" in capsys.readouterr().out

    def test_decrypt_missing_text(self, monkeypatch, capsys):
        monkeypatch.setattr(sys, 'argv', ['console.py', '-key', 'testkey'])
        decrypt()
        assert "需要解密的字符串不能为空。" in capsys.readouterr().out

    def test_decrypt_valid(self, monkeypatch, capsys):
        encryptor = AsteriskEncrypt("testkey123")
        encrypted = encryptor.encrypt("testdecrypt")
        monkeypatch.setattr(sys, 'argv', ['console.py', '-key', 'testkey123', '-txt', encrypted])
        decrypt()
        assert "解密结果：testdecrypt" in capsys.readouterr().out

    def test_decrypt_invalid_text(self, monkeypatch, capsys):
        monkeypatch.setattr(sys, 'argv', ['console.py', '-key', 'validkey123', '-txt', 'invalidtext'])
        decrypt()
        assert "解密失败：" in capsys.readouterr().out

    def test_decrypt_invalid_key(self, monkeypatch):
        monkeypatch.setattr(sys, 'argv', ['console.py', '-key', 'invalid!key', '-txt', 'encrypted'])
        with pytest.raises(InvalidEncriptionKey):
            decrypt()


def pytest_html_report_title(report):
    report.title = "AsteriskSecurity 测试报告"