diff --git a/tools/example_runner.py b/tools/example_runner.py index 65100476..7e574edb 100644 --- a/tools/example_runner.py +++ b/tools/example_runner.py @@ -3,7 +3,7 @@ 用法: python tools/example_runner.py [path] -不写 path 默认扫描 Article/。 +path 可以是 Markdown 文件或目录;不写 path 默认扫描 Article/。 代码块前若有 注释行则跳过。 """ @@ -59,7 +59,7 @@ def run_block(code: str, timeout: int = 30, cwd: str | None = None) -> tuple[boo def main() -> int: parser = argparse.ArgumentParser() - parser.add_argument("paths", nargs="*", default=["Article"]) + parser.add_argument("paths", nargs="*", default=["Article"], help="Markdown 文件或目录") parser.add_argument("--timeout", type=int, default=30) args = parser.parse_args() @@ -72,10 +72,13 @@ def main() -> int: with tempfile.TemporaryDirectory() as workdir: for top in args.paths: root = Path(top) - if not root.exists(): - print(f"路径不存在:{root}", file=sys.stderr) - continue - for md in sorted(root.rglob("*.md")): + if root.is_dir(): + articles = sorted(root.rglob("*.md")) + elif root.is_file() and root.suffix.lower() == ".md": + articles = [root] + else: + parser.error(f"请指定存在的 Markdown 文件或目录:{root}") + for md in articles: for line_no, code, skip in extract_blocks(md): total += 1 if skip: diff --git a/tools/test_example_runner.py b/tools/test_example_runner.py index 063b1cc7..f0705398 100644 --- a/tools/test_example_runner.py +++ b/tools/test_example_runner.py @@ -1,9 +1,10 @@ -"""示例运行器的回归检查:示例写出的文件不能落进调用者的当前目录。""" +"""示例运行器的命令行和工作目录回归检查。""" import contextlib import io import os from pathlib import Path +import subprocess import sys import tempfile import unittest @@ -11,8 +12,33 @@ from example_runner import main +RUNNER = Path(__file__).with_name("example_runner.py") + class ExampleRunnerTests(unittest.TestCase): + def test_single_markdown_file_runs_its_examples(self): + with tempfile.TemporaryDirectory() as folder: + article = Path(folder) / "lesson.md" + article.write_text("```python\nassert False\n```\n", encoding="utf-8") + result = subprocess.run( + [sys.executable, RUNNER, article], capture_output=True, text=True + ) + self.assertEqual(result.returncode, 1) + self.assertIn(f"FAIL {article}:1", result.stdout) + self.assertIn("总计 1 块", result.stdout) + + def test_invalid_input_paths_report_an_error(self): + with tempfile.TemporaryDirectory() as folder: + other_file = Path(folder) / "lesson.txt" + other_file.touch() + for path in (other_file, Path(folder) / "missing.md"): + with self.subTest(path=path): + result = subprocess.run( + [sys.executable, RUNNER, path], capture_output=True, text=True + ) + self.assertEqual(result.returncode, 2) + self.assertIn(str(path), result.stderr) + def test_examples_do_not_write_into_caller_cwd(self): with tempfile.TemporaryDirectory() as caller: article = Path(caller) / "docs" / "a.md"