示例工程 40-type-checker-in-python
40-type-checker-in-python/05-cli/test_cli.py
"""test_cli.py"""
from __future__ import annotations
import subprocess
import sys
from pathlib import Path
import pytest
from cli import check_source, main, run
def test_check_source_codes() -> None:
errors = check_source('x = 1\ny = x + "a"\nz = missing\n')
assert [(error.line, error.code) for error in errors] == [(2, "E001"), (3, "E002")]
def test_run_clean_and_bad(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
good = tmp_path / "good.py"
good.write_text("x = 1\ny = x + 2\n", encoding="utf-8")
assert run([good]) == 0
assert "OK: 1 file(s)" in capsys.readouterr().out
bad = tmp_path / "bad.py"
bad.write_text('x = 1\ny = x + "a"\n', encoding="utf-8")
assert run([bad]) == 1
assert "Found 1 error" in capsys.readouterr().out
def test_missing_file_returns_2(tmp_path: Path) -> None:
assert run([tmp_path / "nope.py"]) == 2
def test_main_uses_argv(tmp_path: Path) -> None:
good = tmp_path / "ok.py"
good.write_text("x = 1\n", encoding="utf-8")
assert main([str(good)]) == 0
def test_subprocess_exit_code(tmp_path: Path) -> None:
bad = tmp_path / "bad.py"
bad.write_text('x = 1\ny = x + "a"\n', encoding="utf-8")
completed = subprocess.run(
[sys.executable, str(Path(__file__).with_name("cli.py")), str(bad)],
capture_output=True,
text=True,
check=False,
)
assert completed.returncode == 1
assert "[E001]" in completed.stdout