知らない分野を、原文にたどりつくまで芋づる式に掘る Claude Code のスキル
Python
scripts: Windows(cp932)と Python 3.10 で止まらないようにする (#3)
MaryCached6af29886f9c
diff --git a/README.md b/README.mdindex 9f81ac0..4eb40ee 100644--- a/README.md+++ b/README.md@@ -47,8 +47,8 @@ npx skills add MaryCache/imozuru| コマンド | 使うところ | 無いとき ||---|---|---|-| `pdftotext`(poppler) | PDF を文字にする | PDF の本文が取れず `FAIL` になる |-| `tesseract` | 文字の層が無い古い PDF の OCR | その PDF は `FAIL` になる |+| `pdftotext`(poppler か Xpdf) | PDF を文字にする | PDF の本文が取れず `FAIL` になる |+| `pdftoppm`(poppler か Xpdf)と `tesseract` | 文字の層が無い古い PDF の OCR | その PDF は `FAIL` になる || `yt-dlp` | YouTube の字幕を落とす | 動画は `FAIL` になる || [ax](https://github.com/yusukebe/ax) | HTML を markdown にする | 標準ライブラリで文字にする(見出しや表の形は ax のほうが残る) |diff --git a/skills/imozuru/SKILL.md b/skills/imozuru/SKILL.mdindex 1b752fc..18fb422 100644--- a/skills/imozuru/SKILL.md+++ b/skills/imozuru/SKILL.md@@ -223,7 +223,7 @@ map.md を下の書式で作り、**問い**と、答えるのに要る**主張*スクリプトは Python 3.10 以上の標準ライブラリだけで動く。外部コマンドは、あれば使う(無いときの動きは各行に書いた)。-- `scripts/fetch.py <sources_dir> <name> <url>` — 落として本物か確かめる。PDF は .pdf と .txt(`pdftotext -layout`・poppler)、HTML は .md、YouTube は字幕を `[分:秒] 文` の .md(`yt-dlp`・動画は落とさない)。文字の層が無い PDF は `tesseract` で OCR する。HTML は [ax](https://github.com/yusukebe/ax) があれば ax で、無ければ標準ライブラリで本文を文字にする(見出しや表の形は ax のほうが残る)。取ってきたものは作業用のフォルダで検査し、通ったものだけを sources_dir へ移す。404・壁・短すぎる本文は `FAIL`(同じ名前の原文がすでにあれば、そのまま残る)。X は本文が取れないので取りに行かず `FAIL`=URL と、検索役が拾った抜粋を(未確認)で map.md に残す+- `scripts/fetch.py <sources_dir> <name> <url>` — 落として本物か確かめる。PDF は .pdf と .txt(`pdftotext -layout`・poppler か Xpdf)、HTML は .md、YouTube は字幕を `[分:秒] 文` の .md(`yt-dlp`・動画は落とさない)。文字の層が無い PDF は `pdftoppm` と `tesseract` で OCR する。要るコマンドが無いときは、無いコマンドの名前を書いて `FAIL` する。HTML は [ax](https://github.com/yusukebe/ax) があれば ax で、無ければ標準ライブラリで本文を文字にする(見出しや表の形は ax のほうが残る)。取ってきたものは作業用のフォルダで検査し、通ったものだけを sources_dir へ移す。404・壁・短すぎる本文は `FAIL`(同じ名前の原文がすでにあれば、そのまま残る)。X は本文が取れないので取りに行かず `FAIL`=URL と、検索役が拾った抜粋を(未確認)で map.md に残す- 動画の場所は行番号の代わりに時刻で指す(`sources/x.md [12:34]`)- `scripts/report.py <topic_dir> [--check]` — extracts.json の抜き書きを原文と照合し、合えば report.html にする。`--check` は照合だけ- `scripts/watch.py add|list|check` — 見張り。RSS / Atom を引いて前回からの新着を出す。検索を使わないので費用はかからず結果も揺れない。DOCTYPE・ENTITY を含むフィードは安全のため読まないdiff --git a/skills/imozuru/scripts/fetch.py b/skills/imozuru/scripts/fetch.pyindex 7cec206..2af4577 100755--- a/skills/imozuru/scripts/fetch.py+++ b/skills/imozuru/scripts/fetch.py@@ -46,19 +46,47 @@ WALL_PATTERNS = ()+class _Redirect308(urllib.request.HTTPRedirectHandler):+ """Python 3.10 でも 308 の転送をたどる。++ 3.10 の HTTPRedirectHandler は http_error_308 を持たず、redirect_request も 308 をはねる+ (どちらも 3.11 で足された)。308 は 307 と同じく「同じメソッドのまま別の URL へ」なので、+ 307 として扱わせる。3.11 以降では動きは変わらない(openhands.dev などが 308 を返す・#3)。+ """++ http_error_308 = urllib.request.HTTPRedirectHandler.http_error_302++ def redirect_request(self, req, fp, code, msg, headers, newurl):+ return super().redirect_request(req, fp, 307 if code == 308 else code, msg, headers, newurl)+++_OPENER = urllib.request.build_opener(_Redirect308)++def download(url: str) -> tuple[bytes, str]:"""URL を取りに行き、本体と Content-Type を返す。"""req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 imozuru"})- with urllib.request.urlopen(req, timeout=90) as res:+ with _OPENER.open(req, timeout=90) as res:return res.read(MAX_BYTES), res.headers.get("Content-Type", "")+def missing(*commands: str) -> list[str]:+ """手元に無い外部コマンドの名前を返す。無いまま呼ぶと FileNotFoundError で止まるため。"""+ return [c for c in commands if shutil.which(c) is None]++def pdf_to_text(pdf: Path) -> str:- """pdftotext で段組みを保ったまま文字にする。行番号で原文を指せるように -layout を使う。"""+ """pdftotext で段組みを保ったまま文字にする。行番号で原文を指せるように -layout を使う。++ Xpdf の pdftotext(Git for Windows に入っている)は既定で Latin-1 を出すので、+ -enc UTF-8 で出力の文字コードを決める。poppler の pdftotext も同じ引数を受け付ける(#3)。+ """+ if missing("pdftotext"):+ return ""out = pdf.with_suffix(".txt")- subprocess.run(["pdftotext", "-layout", str(pdf), str(out)], check=False,+ subprocess.run(["pdftotext", "-layout", "-enc", "UTF-8", str(pdf), str(out)], check=False,stderr=subprocess.DEVNULL)- return out.read_text(errors="replace") if out.exists() else ""+ return out.read_text(encoding="utf-8", errors="replace") if out.exists() else ""def ocr_pdf(pdf: Path) -> str:@@ -67,7 +95,10 @@ def ocr_pdf(pdf: Path) -> str:Spencer ら 1995 の PDF は取れたのに pdftotext が1文字しか返さなかった(2026-10-10)。英語だけ(入っている言語データが eng のみ)。1ページずつ 200dpi の画像にして読む。OCR の誤りは残るので、.txt の先頭に OCR だと書いて、読む人が原本と照らせるようにする。+ pdftoppm か tesseract が無ければ何もせず空を返す(呼び手が FAIL に無いコマンドを書く)。"""+ if missing("pdftoppm", "tesseract"):+ return ""tmp = pdf.parent / f".{pdf.stem}-ocr"tmp.mkdir(exist_ok=True)subprocess.run(["pdftoppm", "-r", "200", "-png", str(pdf), str(tmp / "p")],@@ -75,13 +106,14 @@ def ocr_pdf(pdf: Path) -> str:pages = []for img in sorted(tmp.glob("p-*.png")):res = subprocess.run(["tesseract", str(img), "-", "-l", "eng"],- capture_output=True, text=True)+ capture_output=True, encoding="utf-8", errors="replace")pages.append(f"=== page {img.stem.split('-')[-1]} ===\n{res.stdout}")img.unlink()tmp.rmdir()text = "\n".join(pages)out = pdf.with_suffix(".txt")- out.write_text("(OCR で起こした本文。誤りが残るので、引用は原本の PDF で確かめる)\n\n" + text)+ out.write_text("(OCR で起こした本文。誤りが残るので、引用は原本の PDF で確かめる)\n\n" + text,+ encoding="utf-8")return text@@ -173,7 +205,8 @@ def html_to_md(url: str, out: Path, body: bytes | None = None) -> str:body を渡されたら取り直さずにそれを使う(ax が無いときの二重の取得を避ける)。"""if HAS_AX:- res = subprocess.run(["ax", url, "--md", "--all"], capture_output=True, text=True)+ res = subprocess.run(["ax", url, "--md", "--all"], capture_output=True,+ encoding="utf-8", errors="replace")text = res.stdoutelse:if body is None:@@ -185,7 +218,7 @@ def html_to_md(url: str, out: Path, body: bytes | None = None) -> str:parser = _TextExtractor(url)parser.feed(body.decode("utf-8", errors="replace"))text = parser.text()- out.write_text(text)+ out.write_text(text, encoding="utf-8")return text@@ -197,7 +230,7 @@ def ax_save(url: str, out: Path) -> bool:ax が無いときは urllib で取り直す。"""if HAS_AX:- subprocess.run(["ax", url, "-o", str(out)], capture_output=True, text=True)+ subprocess.run(["ax", url, "-o", str(out)], capture_output=True)else:try:out.write_bytes(download(url)[0])@@ -221,17 +254,18 @@ def youtube_to_md(url: str, out: Path) -> str:自動字幕は誤変換が多い(大陸塗りの試しで「線画」が「洗画」)。どちらを使ったかを見出しに残し、読み手が引用を動画で確かめるべきか分かるようにする。手動と自動は同じファイル名で出てくるので、まず手動だけで取り、無いときだけ自動で取り直す。+ 題名の出力は --encoding で UTF-8 に決める。Windows でパイプに出すと、決めない限り cp932 になる。"""tmp = out.parent / f".{out.stem}-subs"tmp.mkdir(exist_ok=True)kind = "手動"for flag in ("--write-subs", "--write-auto-subs"):meta = subprocess.run(- ["yt-dlp", "--no-update", "--skip-download", flag,+ ["yt-dlp", "--no-update", "--skip-download", flag, "--encoding", "utf-8","--sub-langs", "ja,en", "--sub-format", "vtt", "--no-simulate","--print", "%(title)s\t%(uploader)s\t%(upload_date)s","-o", str(tmp / "v.%(ext)s"), url],- capture_output=True, text=True)+ capture_output=True, encoding="utf-8", errors="replace")if any(tmp.glob("*.vtt")):breakkind = "自動(誤変換あり・引用は動画で確かめる)"@@ -239,7 +273,7 @@ def youtube_to_md(url: str, out: Path) -> str:lines, last = [], ""if vtts:stamp = "00:00"- for raw in vtts[0].read_text(errors="replace").splitlines():+ for raw in vtts[0].read_text(encoding="utf-8", errors="replace").splitlines():m = re.match(r"(\d\d):(\d\d):(\d\d)\.\d+ -->", raw)if m:h, mi, s = (int(x) for x in m.groups())@@ -258,7 +292,8 @@ def youtube_to_md(url: str, out: Path) -> str:title = head[0] if head and head[0] else urlinfo = " / ".join(head[1:]) if len(head) > 1 else ""body = "\n".join(lines)- out.write_text(f"# {title}\n\n{url}\n{info}\n字幕: {kind + ' ' + vtts[0].name if vtts else 'なし'}\n\n{body}\n")+ out.write_text(f"# {title}\n\n{url}\n{info}\n字幕: {kind + ' ' + vtts[0].name if vtts else 'なし'}\n\n{body}\n",+ encoding="utf-8")return body@@ -286,6 +321,9 @@ def fetch_source(sources: Path, name: str, url: str, destination: Path) -> int:print(f"FAIL\t{name}\tX はログインの壁で本文が取れない(URL を map.md に残す)")return 1if YOUTUBE.search(url):+ if missing("yt-dlp"):+ print(f"FAIL\t{name}\tyt-dlp が無いので字幕を落とせない")+ return 1kept = sources / f"{name}.md"body = youtube_to_md(url, kept)if len(body) < MIN_TRANSCRIPT_CHARS:@@ -322,7 +360,7 @@ def fetch_source(sources: Path, name: str, url: str, destination: Path) -> int:ext = ".json" if "json" in ctype else ".csv" if "csv" in ctype else ".md"kept = saved = sources / f"{name}{ext}"text = body.decode("utf-8", errors="replace")- kept.write_text(text)+ kept.write_text(text, encoding="utf-8")elif "html" in ctype or body.lstrip()[:1] == b"<":kept = sources / f"{name}.md"text = html_to_md(url, kept, body)@@ -360,6 +398,10 @@ def fetch_source(sources: Path, name: str, url: str, destination: Path) -> int:for p in (saved, kept):p.unlink(missing_ok=True)reason = f"壁に当たった({wall})" if wall else f"本文が短すぎる({len(text)}文字)"+ # PDF の文字起こしに要るコマンドが欠けていたなら、短い理由はたいていそれ+ lacking = missing("pdftotext", "pdftoppm", "tesseract") if saved.suffix == ".pdf" else []+ if lacking:+ reason += f"。{'・'.join(lacking)} が無い"print(f"FAIL\t{name}\t{reason}")return 1@@ -381,4 +423,6 @@ def main() -> int:if __name__ == "__main__":+ # 本文の先頭の一行を出すので、端末の文字コードに無い字(cp932 の à など)で落ちないようにする+ sys.stdout.reconfigure(errors="replace")sys.exit(main())diff --git a/skills/imozuru/scripts/report.py b/skills/imozuru/scripts/report.pyindex 6ff9a33..4eaffae 100644--- a/skills/imozuru/scripts/report.py+++ b/skills/imozuru/scripts/report.py@@ -43,7 +43,7 @@ def verify(src_dir: Path, q: dict) -> tuple[bool, list[str], int, int]:if not path.exists():return False, [], 0, 0# splitlines() はページ区切り(\f)も改行に数え、grep・sed と行番号がずれる。改行だけで数える- lines = path.read_text(errors="replace").split("\n")+ lines = path.read_text(encoding="utf-8", errors="replace").split("\n")start = max(1, q["line"] - 2)end = min(len(lines), q.get("end", q["line"]) + 2)region = norm(" ".join(lines[start - 1:end]))@@ -128,7 +128,7 @@ def main() -> int:return 2topic = Path(sys.argv[1]).expanduser()check_only = "--check" in sys.argv- data = json.loads((topic / "extracts.json").read_text())+ data = json.loads((topic / "extracts.json").read_text(encoding="utf-8"))src = topic / "sources"bad, rendered = [], {}@@ -179,10 +179,12 @@ def main() -> int:</main></body></html>"""out = topic / "report.html"- out.write_text(page)+ out.write_text(page, encoding="utf-8")print(f"→ {out}")return 0if __name__ == "__main__":+ # 抜き書きの頭を出すので、端末の文字コードに無い字(cp932 の à など)で落ちないようにする+ sys.stdout.reconfigure(errors="replace")sys.exit(main())diff --git a/skills/imozuru/scripts/watch.py b/skills/imozuru/scripts/watch.pyindex 847a694..098e470 100644--- a/skills/imozuru/scripts/watch.py+++ b/skills/imozuru/scripts/watch.py@@ -43,9 +43,24 @@ HEAD_CHARS = 120SEEN_LIMIT = 500+class _Redirect308(urllib.request.HTTPRedirectHandler):+ """Python 3.10 でも 308 の転送をたどる(3.10 は 308 を扱わない)。++ fetch.py と同じもの。-I で動かすとスクリプトの置き場が import の道に入らないので、写して持つ。+ """++ http_error_308 = urllib.request.HTTPRedirectHandler.http_error_302++ def redirect_request(self, req, fp, code, msg, headers, newurl):+ return super().redirect_request(req, fp, 307 if code == 308 else code, msg, headers, newurl)+++_OPENER = urllib.request.build_opener(_Redirect308)++def fetch(url: str) -> tuple[bytes, str]:req = urllib.request.Request(url, headers=UA)- with urllib.request.urlopen(req, timeout=60) as res:+ with _OPENER.open(req, timeout=60) as res:return res.read(5_000_000), res.headers.get("Content-Type", "")@@ -158,7 +173,8 @@ def load_watch(topic: Path) -> list[list[str]]:p = topic / "watch.tsv"if not p.exists():return []- return [ln.split("\t") for ln in p.read_text().splitlines() if ln and not ln.startswith("#")]+ return [ln.split("\t") for ln in p.read_text(encoding="utf-8").splitlines()+ if ln and not ln.startswith("#")]def cmd_add(topic: Path, url: str, name: str | None) -> int:@@ -190,8 +206,8 @@ def cmd_add(topic: Path, url: str, name: str | None) -> int:topic.mkdir(parents=True, exist_ok=True)p = topic / "watch.tsv"if not p.exists():- p.write_text("# 種類\t名前\tフィード\t元の URL\n")- with p.open("a") as f:+ p.write_text("# 種類\t名前\tフィード\t元の URL\n", encoding="utf-8")+ with p.open("a", encoding="utf-8") as f:f.write(f"{kind}\t{label}\t{feed}\t{url}\n")print(f"足した: {kind}\t{label}\t{feed}(いま {len(found)} 件)")return 0@@ -207,7 +223,7 @@ def cmd_check(topic: Path, days: int, fresh: bool) -> None:if not rows:raise SystemExit(f"見張る先が無い: {topic}/watch.tsv(watch.py add で足す)")state_p = topic / "watch-state.json"- state = json.loads(state_p.read_text()) if state_p.exists() else {}+ state = json.loads(state_p.read_text(encoding="utf-8")) if state_p.exists() else {}now = dt.datetime.now(dt.timezone.utc)cutoff = now - dt.timedelta(days=days)lines = [f"# 新着 {now.astimezone():%Y-%m-%d %H:%M}", ""]@@ -247,7 +263,7 @@ def cmd_check(topic: Path, days: int, fresh: bool) -> None:lines += ["新着なし", ""]if quiet:lines += ["## 新着の無かった場所(窓に関係なく最新の1件)", *quiet, ""]- state_p.write_text(json.dumps(state, ensure_ascii=False, indent=1))+ state_p.write_text(json.dumps(state, ensure_ascii=False, indent=1), encoding="utf-8")# 秒まで入れる。日付だけだと同じ日の2回目が1回目を上書きして消した(2026-10-10 の試し)。out = topic / "watch" / f"{now.astimezone():%Y-%m-%d-%H%M%S}.md"n = 2@@ -255,7 +271,7 @@ def cmd_check(topic: Path, days: int, fresh: bool) -> None:out = out.with_name(f"{now.astimezone():%Y-%m-%d-%H%M%S}-{n}.md")n += 1out.parent.mkdir(exist_ok=True)- out.write_text("\n".join(lines) + "\n")+ out.write_text("\n".join(lines) + "\n", encoding="utf-8")print("\n".join(lines))print(f"\n→ {out}(新着 {total} 件・見張る先 {len(rows)})")@@ -288,4 +304,6 @@ def main() -> int:if __name__ == "__main__":+ # 記事の題と冒頭を出すので、端末の文字コードに無い字(cp932 の à など)で落ちないようにする+ sys.stdout.reconfigure(errors="replace")sys.exit(main())diff --git a/tests/test_fetch.py b/tests/test_fetch.pyindex 59e05d4..a98a6a0 100644--- a/tests/test_fetch.py+++ b/tests/test_fetch.py@@ -27,6 +27,8 @@ class FetchPreservationTests(unittest.TestCase):self.addCleanup(self.stack.close)self.stack.enter_context(contextlib.redirect_stdout(self.stdout))self.stack.enter_context(patch.object(fetch, "HAS_AX", False))+ # 外部コマンドの有無で結果が変わらないように、既定では全部あることにする+ self.stack.enter_context(patch.object(fetch, "missing", return_value=[]))def seed(self, *suffixes):for suffix in suffixes:diff --git a/tests/test_portability.py b/tests/test_portability.pynew file mode 100644index 0000000..9293e1f--- /dev/null+++ b/tests/test_portability.py@@ -0,0 +1,169 @@+"""Windows(cp932)・Python 3.10・外部コマンドの欠けで止まらないことを検査する(#3)。"""++import ast+import contextlib+import http.server+import importlib.util+import io+import subprocess+import sys+import tempfile+import threading+import unittest+import urllib.error+import urllib.request+from pathlib import Path+from unittest.mock import patch+++ROOT = Path(__file__).resolve().parents[1]+SCRIPTS = ROOT / "skills/imozuru/scripts"+++def load(name):+ spec = importlib.util.spec_from_file_location(f"imozuru_{name}", SCRIPTS / f"{name}.py")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++fetch = load("fetch")+watch = load("watch")+++class EncodingTests(unittest.TestCase):+ def test_text_io_names_its_encoding(self):+ """encoding を省くと Windows では cp932 で読み書きして落ちる。省いた呼び出しを1つも残さない。"""+ omitted = []+ for script in sorted(SCRIPTS.glob("*.py")):+ for node in ast.walk(ast.parse(script.read_text(encoding="utf-8"))):+ if not isinstance(node, ast.Call):+ continue+ func = node.func+ name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "")+ keywords = {k.arg: k.value for k in node.keywords}+ # open は組み込みか Path.open(モードを文字列で渡す)だけ。URL の opener.open(req) は除く+ file_open = name == "open" and (+ isinstance(func, ast.Name) or not node.args+ or isinstance(node.args[0], ast.Constant) and isinstance(node.args[0].value, str))+ text_io = name in ("read_text", "write_text") or file_open+ text_run = name == "run" and isinstance(keywords.get("text"), ast.Constant) \+ and keywords["text"].value is True+ if (text_io or text_run) and "encoding" not in keywords:+ omitted.append(f"{script.name}:{node.lineno} {name}")+ self.assertEqual(omitted, [])++ def test_report_check_runs_without_default_encoding(self):+ """既定の文字コードに頼る箇所があれば、EncodingWarning をエラーにして落とす。"""+ res = subprocess.run(+ [sys.executable, "-I", "-X", "warn_default_encoding", "-W", "error::EncodingWarning",+ str(SCRIPTS / "report.py"), str(ROOT / "examples/demo"), "--check"],+ capture_output=True, encoding="utf-8")+ self.assertEqual(res.returncode, 0, res.stderr)+ self.assertIn("照合 OK", res.stdout)+++class PdfToTextTests(unittest.TestCase):+ def test_pdftotext_writes_utf8(self):+ """Xpdf の pdftotext は既定で Latin-1 を出すので、-enc UTF-8 を渡す。"""+ with tempfile.TemporaryDirectory() as tmp:+ pdf = Path(tmp) / "paper.pdf"+ pdf.write_bytes(b"%PDF-1.4")++ def fake_run(args, **kwargs):+ pdf.with_suffix(".txt").write_bytes("Schizophrénie\n".encode("utf-8"))++ with patch.object(fetch, "missing", return_value=[]), \+ patch.object(fetch.subprocess, "run", side_effect=fake_run) as run:+ text = fetch.pdf_to_text(pdf)+ args = run.call_args.args[0]+ self.assertEqual(args[args.index("-enc") + 1], "UTF-8")+ self.assertEqual(text, "Schizophrénie\n")+++class _Redirects(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ if self.path == "/old":+ self.send_response(308)+ self.send_header("Location", "/new")+ self.end_headers()+ else:+ body = b"moved here"+ self.send_response(200)+ self.send_header("Content-Type", "text/plain")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *args):+ pass+++def _redirect_request_310(original):+ """Python 3.10 の redirect_request と同じく、308 をはねる版を作る(3.11 で 308 が足された)。"""+ def redirect_request(self, req, fp, code, msg, headers, newurl):+ if code == 308:+ raise urllib.error.HTTPError(req.full_url, code, msg, headers, fp)+ return original(self, req, fp, code, msg, headers, newurl)+ return redirect_request+++class Redirect308Tests(unittest.TestCase):+ def setUp(self):+ self.server = http.server.HTTPServer(("127.0.0.1", 0), _Redirects)+ threading.Thread(target=self.server.serve_forever, daemon=True).start()+ self.addCleanup(self.server.server_close)+ self.addCleanup(self.server.shutdown)+ self.url = f"http://127.0.0.1:{self.server.server_port}/old"+ handler = urllib.request.HTTPRedirectHandler+ # 3.10 の動きを再現する。3.10 では http_error_308 も無いが、こちらは自前の handler が持つ+ self.stack = contextlib.ExitStack()+ self.addCleanup(self.stack.close)+ self.stack.enter_context(patch.object(+ handler, "redirect_request", _redirect_request_310(handler.redirect_request)))++ def test_stock_opener_rejects_308_under_310_behaviour(self):+ """再現が効いていることの確かめ。素の urlopen は 3.10 と同じく 308 で止まる。"""+ with self.assertRaises(urllib.error.HTTPError) as caught:+ urllib.request.urlopen(self.url, timeout=10)+ self.assertEqual(caught.exception.code, 308)++ def test_fetch_download_follows_308(self):+ body, ctype = fetch.download(self.url)+ self.assertEqual(body, b"moved here")+ self.assertEqual(ctype, "text/plain")++ def test_watch_fetch_follows_308(self):+ body, _ = watch.fetch(self.url)+ self.assertEqual(body, b"moved here")+++class MissingCommandTests(unittest.TestCase):+ def setUp(self):+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ self.sources = Path(tmp.name)+ self.stdout = io.StringIO()+ self.stack = contextlib.ExitStack()+ self.addCleanup(self.stack.close)+ self.stack.enter_context(contextlib.redirect_stdout(self.stdout))+ # どのコマンドも無い環境+ self.stack.enter_context(patch.object(fetch, "missing", side_effect=lambda *c: list(c)))++ def run_fetch(self, url):+ with patch.object(sys, "argv", ["fetch.py", str(self.sources), "paper", url]):+ return fetch.main()++ def test_pdf_without_tools_fails_with_reason(self):+ with patch.object(fetch, "download", return_value=(b"%PDF-1.4\nscan", "application/pdf")):+ self.assertEqual(self.run_fetch("https://example.test/scan.pdf"), 1)+ self.assertIn("pdftotext・pdftoppm・tesseract が無い", self.stdout.getvalue())+ self.assertEqual(list(self.sources.iterdir()), [])++ def test_youtube_without_ytdlp_fails_with_reason(self):+ self.assertEqual(self.run_fetch("https://www.youtube.com/watch?v=example"), 1)+ self.assertIn("yt-dlp が無い", self.stdout.getvalue())+++if __name__ == "__main__":+ unittest.main()