import os
import tempfile
import unittest
from unittest.mock import patch, MagicMock
from pdf2img2pdf import convert, check_poppler_installed

class TestPdf2Img2Pdf(unittest.TestCase):

    def setUp(self):
        """在每个测试前运行，准备临时文件"""
        self.input_pdf = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
        self.output_pdf = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
        self.input_pdf.close()
        self.output_pdf.close()

    def tearDown(self):
        """在每个测试后运行，清理临时文件"""
        if os.path.exists(self.input_pdf.name):
            os.unlink(self.input_pdf.name)
        if os.path.exists(self.output_pdf.name):
            os.unlink(self.output_pdf.name)

    @patch("pdf2img2pdf.pdf2image.convert_from_path")
    @patch("pdf2img2pdf.img2pdf.convert")
    def test_convert_success(self, mock_img2pdf, mock_pdf2image):
        """测试 convert 函数是否能成功执行"""
        # 模拟 pdf2image 返回图像列表
        mock_images = [MagicMock()]
        mock_pdf2image.return_value = mock_images

        # 模拟 img2pdf 返回二进制数据
        mock_img2pdf.return_value = b"fake_pdf_data"

        # 调用函数
        convert(self.input_pdf.name, self.output_pdf.name)

        # 断言 pdf2image 被正确调用
        mock_pdf2image.assert_called_once_with(self.input_pdf.name)

        # 断言 img2pdf 被正确调用
        mock_img2pdf.assert_called_once_with([img.filename for img in mock_images])

        # 断言输出文件被创建
        self.assertTrue(os.path.exists(self.output_pdf.name))

    @patch("shutil.which")
    def test_check_poppler_installed_success(self, mock_which):
        """测试 check_poppler_installed 在 Poppler 已安装时不会抛出异常"""
        mock_which.return_value = "/usr/bin/pdftoppm"  # 模拟找到了 pdftoppm
        try:
            check_poppler_installed()
        except RuntimeError:
            self.fail("check_poppler_installed() raised RuntimeError unexpectedly!")

    @patch("shutil.which")
    def test_check_poppler_installed_failure(self, mock_which):
        """测试 check_poppler_installed 在 Poppler 未安装时抛出异常"""
        mock_which.return_value = None  # 模拟未找到 pdftoppm 或 pdfinfo
        with self.assertRaises(RuntimeError) as context:
            check_poppler_installed()
        self.assertIn("Poppler is not installed", str(context.exception))

if __name__ == "__main__":
    unittest.main()