140 lines
6.9 KiB
Python
140 lines
6.9 KiB
Python
from pathlib import Path
|
|
from tempfile import TemporaryDirectory
|
|
import io
|
|
import json
|
|
import subprocess
|
|
import sys
|
|
import unittest
|
|
from unittest.mock import patch
|
|
from zipfile import ZipFile
|
|
|
|
from tools import c4hr, epub
|
|
|
|
|
|
class DatabaseBrowserTests(unittest.TestCase):
|
|
def open_database(self, config, run_bsk):
|
|
args = ["c4hr.py", "open-db", "archives"]
|
|
entry = {"name": "Archives", "purpose": "Find records",
|
|
"url": "https://archive.example/", "enabled": True, **config}
|
|
with patch.object(sys, "argv", args), patch.object(c4hr, "run_bsk", run_bsk):
|
|
with patch.object(c4hr, "read_config", return_value={"databases": {"archives": entry}}):
|
|
return c4hr.main()
|
|
|
|
def test_enabled_database_without_browser_uses_unique_connected_instance(self):
|
|
calls = []
|
|
|
|
def run_bsk(args, *, capture_stdout=False):
|
|
calls.append(args)
|
|
if args[0] == "browsers":
|
|
self.assertTrue(capture_stdout)
|
|
return subprocess.CompletedProcess(args, 0, stdout='[{"instance_id":"chrome-profile"}]')
|
|
return subprocess.CompletedProcess(args, 0)
|
|
|
|
self.assertEqual(self.open_database({}, run_bsk), 0)
|
|
self.assertEqual(calls[0], ["browsers", "--json"])
|
|
self.assertEqual(calls[1][-4:], ["--browser", "chrome-profile", "--json", "https://archive.example/"])
|
|
|
|
def test_explicit_browser_does_not_probe_other_instances(self):
|
|
calls = []
|
|
|
|
def run_bsk(args, *, capture_stdout=False):
|
|
calls.append(args)
|
|
self.assertFalse(capture_stdout)
|
|
return subprocess.CompletedProcess(args, 0)
|
|
|
|
self.assertEqual(self.open_database({"browser": "My research profile"}, run_bsk), 0)
|
|
self.assertEqual(len(calls), 1)
|
|
self.assertEqual(calls[0][-4:], ["--browser", "My research profile", "--json", "https://archive.example/"])
|
|
|
|
def test_no_or_multiple_connected_browsers_never_open_database(self):
|
|
for browsers, message in [
|
|
([], "尚未连接浏览器"),
|
|
([{"instance_id": "chrome"}, {"instance_id": "edge"}], "已连接多个浏览器"),
|
|
]:
|
|
with self.subTest(browsers=browsers), patch("sys.stderr", new_callable=io.StringIO) as error:
|
|
def run_bsk(args, *, capture_stdout=False):
|
|
self.assertEqual(args, ["browsers", "--json"])
|
|
return subprocess.CompletedProcess(args, 0, stdout=json.dumps(browsers))
|
|
|
|
with self.assertRaises(SystemExit) as exit_state:
|
|
self.open_database({}, run_bsk)
|
|
self.assertEqual(exit_state.exception.code, 1)
|
|
self.assertIn(message, error.getvalue())
|
|
|
|
|
|
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 = """<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
|
|
<rootfiles><rootfile full-path="OEBPS/book.opf"
|
|
media-type="application/oebps-package+xml"/></rootfiles></container>"""
|
|
opf = """<package xmlns="http://www.idpf.org/2007/opf">
|
|
<manifest><item id="a" href="a.xhtml" media-type="application/xhtml+xml"/>
|
|
<item id="z" href="text/z%20start.xhtml" media-type="application/xhtml+xml"/>
|
|
<item id="cover" href="cover.png" media-type="image/png"/></manifest>
|
|
<spine><itemref idref="cover"/><itemref idref="z"/><itemref idref="a" linear="no"/></spine>
|
|
</package>"""
|
|
first = """<html xmlns="http://www.w3.org/1999/xhtml"><head><title>先读</title></head>
|
|
<body><p id="quote">预算 下滑 <em>十万</em>。</p><p>第二段</p></body></html>"""
|
|
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", "<html><body>附录</body></html>")
|
|
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)
|