# -*- coding: utf-8 -*-
"""测试 fullpage_archiver.py — 纯函数部分(不依赖浏览器)。"""
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
sys.dont_write_bytecode = True
from fullpage_archiver import (
FullPageArchiver, ArchiveResult, _IMG_SRC_RE, _TABLE_RE,
)
class TestArchiveResult(unittest.TestCase):
"""ArchiveResult 数据类测试。"""
def test_to_dict(self):
r = ArchiveResult(
url="https://example.com",
title="Test Article",
page_count=3,
image_count=10,
canvas_count=2,
table_count=5,
)
d = r.to_dict()
self.assertEqual(d["url"], "https://example.com")
self.assertEqual(d["title"], "Test Article")
self.assertEqual(d["page_count"], 3)
def test_summary_contains_key_info(self):
r = ArchiveResult(
url="https://example.com",
title="测试文章",
page_count=2,
image_count=5,
canvas_count=1,
table_count=3,
inline_html_path="/tmp/test_inline.html",
)
s = r.summary
self.assertIn("测试文章", s)
self.assertIn("2", s) # page count
self.assertIn("5", s) # image count
self.assertIn("test_inline.html", s)
def test_summary_handles_errors(self):
r = ArchiveResult(
url="https://example.com",
errors=["连接超时", "图片下载失败"],
)
self.assertIn("2 个错误", r.summary)
class TestImageExtraction(unittest.TestCase):
"""图片 URL 提取正则测试。"""
def test_img_src_simple(self):
html = '
'
matches = _IMG_SRC_RE.findall(html)
self.assertEqual(len(matches), 1)
self.assertEqual(matches[0], "https://example.com/img.jpg")
def test_img_src_single_quotes(self):
html = "
"
matches = _IMG_SRC_RE.findall(html)
self.assertEqual(len(matches), 1)
def test_img_src_multiple(self):
html = """
"""
matches = _IMG_SRC_RE.findall(html)
self.assertEqual(len(matches), 3)
def test_img_data_uri_ignored(self):
"""data: URI 不应该被提取(由 _download_single_image 处理)。"""
html = ''
matches = _IMG_SRC_RE.findall(html)
self.assertEqual(len(matches), 1) # 提取出来,但在下载时跳过
self.assertIn("data:image/png", matches[0])
class TestTableExtraction(unittest.TestCase):
"""表格提取测试。"""
def test_simple_table(self):
html = """
| Name | Value |
|---|---|
| 营收 | 1500亿 |
| 净利润 | 300亿 |
| Header |
|---|
| Value 1 |
| A |
| B |
No images here
" result = self.archiver._inline_images_in_html(html, {}, "https://example.com") self.assertIn("No images here", result) def test_relink_with_no_images(self): html = "No images here
" result = self.archiver._relink_images_in_html(html, {}) self.assertIn("No images here", result) def test_extract_body_content(self): html = "Hello
" content = self.archiver._extract_body_content(html) self.assertIn("Hello", content) def test_extract_body_no_body_tag(self): html = "No body tag
" content = self.archiver._extract_body_content(html) self.assertIn("No body tag", content) if __name__ == "__main__": unittest.main()