Files
mentor-export/tests/test_cli.py
T

152 lines
7.7 KiB
Python

from pathlib import Path
from threading import Event
import json
def test_batch_does_not_stop_after_one_project_failure(tmp_path):
from mentorexport.cli import run_batch
def exporter(project, installation, folder, shared, **options):
if project["name"] == "坏工程":
raise ValueError("无法读取数据库")
return {"status": "success", "items": [{"key": "ascii", "status": "success", "outputs": []}]}
projects = [{"name": name, "path": str(tmp_path / (name + ".prj"))} for name in ("坏工程", "好工程")]
batch, code = run_batch(projects, [], {}, tmp_path / "out", tmp_path, exporter=exporter)
state = json.loads((batch / "batch.json").read_text(encoding="utf-8"))
assert code == 0 and state["state"] == "complete"
assert [p["status"] for p in state["projects"]] == ["skipped", "success"]
assert (batch / "导出汇总.html").is_file()
def test_pre_cancelled_batch_does_not_start_exporter(tmp_path):
from mentorexport.cli import run_batch
stop = Event()
stop.set()
def exporter(*args, **kwargs):
raise AssertionError("cancelled batch started native work")
batch, code = run_batch([{"name": "工程", "path": str(tmp_path / "a.prj")}], [], {},
tmp_path / "out", tmp_path, stop_event=stop, exporter=exporter)
state = json.loads((batch / "batch.json").read_text(encoding="utf-8"))
assert code == 130 and state["projects"][0]["status"] == "cancelled"
assert (Path(state["projects"][0]["folder"]) / "export.json").is_file()
def test_report_escapes_project_names_and_failure_details(tmp_path):
from mentorexport.report import write_report
record = {"state": "complete", "projects": [
{"project": {"name": "<script>alert(1)</script>", "path": "a.prj"},
"folder": str(tmp_path / "a"), "status": "failed",
"result": {"status": "failed", "reason": "<img src=x>", "items": []}}], "problems": []}
write_report(tmp_path, record)
html = (tmp_path / "导出汇总.html").read_text(encoding="utf-8")
assert "<script>" not in html and "<img src=x>" not in html
assert "&lt;script&gt;" in html and "&lt;img src=x&gt;" in html
def test_retry_loads_export_receipt_written_before_batch_crash(tmp_path):
from mentorexport.cli import previous_results
attempt = tmp_path / "工程"
attempt.mkdir()
(attempt / "export.json").write_text(json.dumps({"status": "partial", "items": [{"key": "csv", "status": "success"}]}))
record = {"projects": [{"project": {"path": "a.prj"}, "folder": str(attempt), "status": "running"}]}
values = previous_results(record)
assert values["a.prj"]["items"][0]["key"] == "csv"
def test_output_cannot_write_inside_source_database_or_library(tmp_path):
from mentorexport.cli import validate_output
import pytest
project = {"path": str(tmp_path / "source/a.prj"), "database": str(tmp_path / "source/database"),
"library": str(tmp_path / "library/mentor.lmc")}
for output in (tmp_path / "source/database/results", tmp_path / "library/results"):
with pytest.raises(ValueError):
validate_output(output, tmp_path / "source", [project])
validate_output(tmp_path / "results", tmp_path / "source", [project])
def test_retry_cannot_claim_running_owner_has_exited():
from mentorexport.cli import assert_retry_safe, process_identity
import os
import pytest
with pytest.raises(ValueError, match="运行"):
assert_retry_safe({"state": "running", "owner": process_identity(os.getpid())})
def test_uncertain_cleanup_does_not_cancel_following_project(tmp_path):
from mentorexport.cli import run_batch
visited = []
def exporter(project, installation, folder, shared, **options):
visited.append(project["name"])
return {"status": "skipped", "cleanup_uncertain": True, "items": []}
projects = [{"name": name, "path": str(tmp_path / (name + ".prj"))} for name in ("工程A", "工程B")]
stop = Event()
batch, code = run_batch(projects, [], {}, tmp_path / "out", tmp_path, exporter=exporter, stop_event=stop)
state = json.loads((batch / "batch.json").read_text(encoding="utf-8"))
assert visited == ["工程A", "工程B"]
assert code == 0 and state["state"] == "complete" and not stop.is_set()
assert state["warnings"]
def test_report_error_does_not_block_batch(tmp_path, monkeypatch):
from mentorexport import cli
visited = []
def broken_report(*args):
raise OSError("HTML file is locked")
def exporter(project, installation, folder, shared, **options):
visited.append(project["name"])
return {"status": "success", "items": []}
monkeypatch.setattr(cli, "write_report", broken_report)
projects = [{"name": name, "path": str(tmp_path / (name + ".prj"))} for name in ("工程A", "工程B")]
batch, code = cli.run_batch(projects, [], {}, tmp_path / "out", tmp_path, exporter=exporter)
record = json.loads((batch / "batch.json").read_text(encoding="utf-8"))
assert visited == ["工程A", "工程B"] and code == 0
assert any("HTML file is locked" in message for message in record["warnings"])
def test_scan_problems_and_no_projects_do_not_return_failed_batch(tmp_path):
from mentorexport.cli import run_batch
batch, code = run_batch([], [{"path": "missing.prj", "reason": "missing database"}], {}, tmp_path / "out", tmp_path)
state = json.loads((batch / "batch.json").read_text(encoding="utf-8"))
assert code == 0 and state["state"] == "complete" and state["problems"]
def test_export_continues_despite_help_preflight_failure(tmp_path, monkeypatch):
from mentorexport import cli
monkeypatch.setattr(cli, "runtime_check", lambda: [])
monkeypatch.setattr(cli, "_choose_installation", lambda *args: {"root": str(tmp_path), "version": "test"})
monkeypatch.setattr(cli, "preflight_installation", lambda *args: {"status": "failed", "reason": "help did not match"})
monkeypatch.setattr(cli, "_settings_paths", lambda: [])
monkeypatch.setattr(cli, "_save_settings", lambda value: None)
result = cli.main(["--input", str(tmp_path), "--output", str(tmp_path / "out"), "--yes"])
assert result == 0
assert list((tmp_path / "out").glob("批次_*/batch.json"))
def test_preflight_exception_is_a_warning_not_a_batch_blocker(tmp_path, monkeypatch):
from mentorexport import cli
monkeypatch.setattr(cli, "runtime_check", lambda: [])
monkeypatch.setattr(cli, "_choose_installation", lambda *args: {"root": str(tmp_path), "version": "test"})
def locked(*args): raise PermissionError("diagnostic directory locked")
monkeypatch.setattr(cli, "preflight_installation", locked)
monkeypatch.setattr(cli, "_settings_paths", lambda: [])
monkeypatch.setattr(cli, "_save_settings", lambda value: None)
assert cli.main(["--input", str(tmp_path), "--output", str(tmp_path / "out"), "--yes"]) == 0
assert list((tmp_path / "out").glob("批次_*/batch.json"))
def test_batch_passes_worker_limit_and_records_execution_mode(tmp_path):
from mentorexport.cli import run_batch
limits = []
def exporter(project, installation, folder, shared, **options):
limits.append(options["jobs"])
return {"status": "success", "items": []}
batch, code = run_batch([{"name": "工程", "path": str(tmp_path / "a.prj")}], [], {},
tmp_path / "out", tmp_path, exporter=exporter, jobs=2)
record = json.loads((batch / "batch.json").read_text(encoding="utf-8"))
assert code == 0 and limits == [2] and record["execution"]["jobs"] == 2
def test_invalid_worker_limit_does_not_start_export(tmp_path):
from mentorexport.cli import main
for jobs in ("0", "9"):
assert main(["--input", str(tmp_path), "--jobs", jobs, "--yes"]) == 2