from pathlib import Path from tempfile import TemporaryDirectory import json import subprocess import unittest from unittest.mock import patch from zipfile import ZipFile from tools import c4hr, epub class ProxyTests(unittest.TestCase): def test_redirect_rechecks_proxy_and_none_clears_environment_routing(self): config = ( {"archives": "socks5h://127.0.0.1:1080"}, {"archive.example": "archives", "direct.archive.example": "none"}, ) calls = [] def curl(args, **_): proxy = args[args.index("--proxy") + 1] url = args[args.index("--url") + 1] self.assertIn("--noproxy", args) self.assertEqual(args[args.index("--noproxy") + 1], "") self.assertNotIn("--location", args) calls.append((url, proxy)) if len(calls) == 1: return subprocess.CompletedProcess( args, 0, stdout="302\nhttps://direct.archive.example/text" ) Path(args[args.index("--output") + 1]).write_text("archival text") return subprocess.CompletedProcess(args, 0, stdout="200\n") with TemporaryDirectory() as directory, patch.object(c4hr, "proxy_config", return_value=config): output = Path(directory) / "download" with patch.object(c4hr.subprocess, "run", side_effect=curl): c4hr.fetch("https://catalog.archive.example/start", output) self.assertEqual(output.read_text(), "archival text") self.assertEqual(calls, [ ("https://catalog.archive.example/start", "socks5h://127.0.0.1:1080"), ("https://direct.archive.example/text", ""), ]) def test_failed_proxy_keeps_existing_output(self): config = ({"archives": "socks5h://127.0.0.1:1080"}, {"archive.example": "archives"}) with TemporaryDirectory() as directory, patch.object(c4hr, "proxy_config", return_value=config): output = Path(directory) / "download" output.write_text("previously saved") with patch.object(c4hr.subprocess, "run", side_effect=subprocess.CalledProcessError(7, "curl")) as curl: with self.assertRaises(subprocess.CalledProcessError): c4hr.fetch("https://archive.example/start", output) curl.assert_called_once() self.assertEqual(output.read_text(), "previously saved") class EpubTests(unittest.TestCase): def test_spine_order_original_anchors_and_readable_text(self): container = """ """ opf = """ """ first = """先读

预算 下滑 十万。

第二段

""" with TemporaryDirectory() as directory: folder = Path(directory) book, output = folder / "test.epub", folder / "read" with ZipFile(book, "w") as package: package.writestr("META-INF/container.xml", container) package.writestr("OEBPS/book.opf", opf) package.writestr("OEBPS/a.xhtml", "附录") package.writestr("OEBPS/text/z start.xhtml", first) self.assertEqual(epub.extract(book, output), (2, 1)) index = json.loads((output / "index.json").read_text(encoding="utf-8")) chapter, appendix = index["chapters"] self.assertEqual(chapter["spine_position"], 2) self.assertFalse(appendix["linear"]) self.assertEqual((output / chapter["xhtml"]).read_bytes(), first.encode()) self.assertEqual((output / chapter["txt"]).read_text(encoding="utf-8"), "预算 下滑 十万。\n第二段\n") with self.assertRaises(FileExistsError): epub.extract(book, output)