Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions tools/example_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
用法:
python tools/example_runner.py [path]

不写 path 默认扫描 Article/。
path 可以是 Markdown 文件或目录;不写 path 默认扫描 Article/。
代码块前若有 <!-- skip-ci --> 注释行则跳过。
"""

Expand Down Expand Up @@ -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()

Expand All @@ -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:
Expand Down
28 changes: 27 additions & 1 deletion tools/test_example_runner.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,44 @@
"""示例运行器的回归检查:示例写出的文件不能落进调用者的当前目录。"""
"""示例运行器的命令行和工作目录回归检查。"""

import contextlib
import io
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest import mock

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"
Expand Down