Spaces:
Paused

File size: 3,097 Bytes
6d2d8b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""章节持久化缓存测试。"""

from __future__ import annotations

import tempfile
import time
import unittest
from pathlib import Path

from app.chapter_cache import ChapterCache, DEFAULT_TTL
from app.cache import TTLCache
from app.crawler.scraper import BiqugeScraper
from app.crawler.site import SiteConfig

from tests.test_biquge_tw import TwFakeFetcher

ROOT = Path(__file__).resolve().parent.parent


class CountingFetcher(TwFakeFetcher):
    def __init__(self) -> None:
        super().__init__()
        self.calls: dict[str, int] = {}

    def get_text(self, url: str) -> str:
        self.calls[url] = self.calls.get(url, 0) + 1
        return super().get_text(url)


class ChapterCacheTests(unittest.TestCase):
    def setUp(self) -> None:
        self.tmp_dir = Path(tempfile.mkdtemp())
        config = SiteConfig.from_json(ROOT / "sites" / "biquge_tw.json")
        self.fetcher = CountingFetcher()
        self.cache = ChapterCache(self.tmp_dir / "cache.db", ttl=DEFAULT_TTL)
        self.scraper = BiqugeScraper(
            config,
            fetcher=self.fetcher,
            cache=TTLCache(ttl=0),  # 关闭内存 HTML 缓存,单独验证章节持久化缓存
            chapter_cache=self.cache,
            chapter_cache_ttl=DEFAULT_TTL,
        )
        self.url = "https://www.biquge.tw/book/9002/1000001.html"

    def test_second_fetch_uses_cache(self) -> None:
        first = self.scraper.fetch_chapter("9002", "1000001")
        self.assertEqual(first["title"], "第一章 开始")
        second = self.scraper.fetch_chapter("9002", "1000001")
        self.assertEqual(second["content"], first["content"])
        self.assertEqual(self.fetcher.calls.get(self.url, 0), 1)

    def test_cache_expired_refetches(self) -> None:
        self.scraper.fetch_chapter("9002", "1000001")
        # 手动把过期时间改到过去,模拟 7 天到期
        with self.cache._lock:
            self.cache._conn.execute(
                "UPDATE chapter_cache SET expires_at = ? WHERE key = ?",
                (time.time() - 1, "9002/1000001"),
            )
            self.cache._conn.commit()
        self.scraper.fetch_chapter("9002", "1000001")
        self.assertEqual(self.fetcher.calls.get(self.url, 0), 2)

    def test_default_ttl_is_seven_days(self) -> None:
        cache = ChapterCache(self.tmp_dir / "cache2.db")
        self.assertEqual(cache.ttl, 7 * 24 * 3600)

    def test_json_roundtrip_with_nav(self) -> None:
        value = {
            "book_id": "9002",
            "chapter_id": "1000001",
            "title": "第一章",
            "url": "https://www.biquge.tw/book/9002/1000001.html",
            "content": "正文内容",
            "prev": None,
            "next": {"book_id": "9002", "chapter_id": "1000002", "title": "第二章", "url": "x"},
        }
        self.cache.set("9002/1000001", value)
        got = self.cache.get("9002/1000001")
        self.assertEqual(got["content"], "正文内容")
        self.assertEqual(got["next"]["chapter_id"], "1000002")


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